NCBI C Toolkit Cross Reference

C/biostruc/mmdbapi4.c


  1 /*   mmdbapi4.c
  2 * ===========================================================================
  3 *
  4 *                            PUBLIC DOMAIN NOTICE
  5 *            National Center for Biotechnology Information (NCBI)
  6 *
  7 *  This software/database is a "United States Government Work" under the
  8 *  terms of the United States Copyright Act.  It was written as part of
  9 *  the author's official duties as a United States Government employee and
 10 *  thus cannot be copyrighted.  This software/database is freely available
 11 *  to the public for use. The National Library of Medicine and the U.S.
 12 *  Government do not place any restriction on its use or reproduction.
 13 *  We would, however, appreciate having the NCBI and the author cited in
 14 *  any work or product based on this material
 15 *
 16 *  Although all reasonable efforts have been taken to ensure the accuracy
 17 *  and reliability of the software and data, the NLM and the U.S.
 18 *  Government do not and cannot warrant the performance or results that
 19 *  may be obtained by using this software or data. The NLM and the U.S.
 20 *  Government disclaim all warranties, express or implied, including
 21 *  warranties of performance, merchantability or fitness for any particular
 22 *  purpose.
 23 *
 24 * ===========================================================================
 25 *
 26 * File Name:  mmdbapi4.c
 27 *
 28 * Author:  Christopher Hogue
 29 *
 30 * Version Creation Date:   10/18/95
 31 *
 32 * $Revision: 6.8 $
 33 *
 34 * File Description: Code for Modelstruc -> Biostruc conversion
 35 *                   And User-feature handling.
 36 *
 37 * Modifications:  
 38 * --------------------------------------------------------------------------
 39 * Date     Name        Description of modification
 40 * -------  ----------  -----------------------------------------------------
 41 * $Log: mmdbapi4.c,v $
 42 * Revision 6.8  2003/05/13 13:48:20  bauer
 43 * changed iCountAtoms in RefreshModelAsnMem from Int2 to Int4
 44 *
 45 * Revision 6.7  2000/12/05 22:13:07  ywang
 46 * fix bugs for MakePDBSeqId2
 47 *
 48 * Revision 6.6  1999/03/12 18:37:08  kans
 49 * fixed ErrPostEx problem
 50 *
 51 * Revision 6.5  1999/02/25 23:11:53  ywang
 52 * synchronize with cn3d to save out mime data
 53 *
 54 * Revision 6.4  1998/09/02 16:25:27  kans
 55 * removed comments around debug ifdef to suppress printf statement
 56 *
 57 * Revision 6.3  1998/08/26 18:02:43  kans
 58 * fixed -v -fd warnings
 59 *
 60 * Revision 6.2  1998/03/10 04:31:08  lewisg
 61 * change name of MakePDBSeqId to MakePDBSeqId2 to avoid name conflict
 62 *
 63 * Revision 6.1  1998/03/06 23:17:29  lewisg
 64 * codewarrior fixes
 65 *
 66 * Revision 6.0  1997/08/25 18:11:16  madden
 67 * Revision changed to 6.0
 68 *
 69 * Revision 5.3  1996/11/26 19:15:44  epstein
 70 * represent gaps correctly in sequence alignments
 71 *
 72  * Revision 5.2  1996/11/25  16:14:41  epstein
 73  * fix off-by-one error since VAST alignments are indexed beginning at position 1 rather than 0
 74  *
 75  * Revision 5.1  1996/11/22  21:16:59  epstein
 76  * add BiostrucAnnotSetToSeqAnnot()
 77  *
 78  * Revision 5.0  1996/05/28  14:02:09  ostell
 79  * Set to revision 5.0
 80  *
 81  * Revision 1.4  1996/02/07  23:05:56  hogue
 82  * fixed a type cast in FreeSingleModel
 83  *
 84  * Revision 1.3  1996/02/02  21:26:26  hogue
 85  * changed to include only mmdbapi.h (brings in all 1-4)
 86  *
 87  * Revision 1.2  1996/02/02  19:45:01  hogue
 88  * Initial Revision
 89  *
 90 *
 91 * ==========================================================================
 92 */
 93 
 94 /*****************************************************************************
 95 *
 96 *  mmdbapi4.c
 97 *   
 98 *   UNDER CONSTRUCTION NOTICE. 
 99 *       EVERYTHING SUBJECT TO RADICAL CHANGES!
100 *   
101 *  programmer C.W.V. Hogue
102 *  created: 18 Oct 95
103 *  last mod: 
104 *****************************************************************************/
105 
106 #include <mmdbapi.h>
107 #include <sequtil.h>
108 
109 
110 
111 
112 
113 
114 static Int4 ScaleToInt(FloatLo f)  
115 {
116 
117   Int4 iI;
118   FloatHi fh;
119   fh = f * SAVE_XYZ_SCALE_FACTOR;  /* scale floating point portion */
120   if (fh > 0)  
121     fh += 0.5;   /* this will push a 2.99999 to 3.099999 */
122   else  fh -= 0.5;  /* or a -2172.9999 to a -2173.0999  */
123   iI = (Int4) fh;  /* which is truncated here */
124   return iI;
125 }               
126 
127 
128 Boolean LIBCALL  RefreshSurface(SurfaceCoordinatesPtr  pscThis, PMOD pmodThis)
129 {
130 
131     CylinderPtr pcylThis = NULL;
132     BrickPtr pbrkThis = NULL;
133     ConePtr pconThis = NULL;
134     TMeshPtr ptmshThis = NULL;
135     TrianglesPtr ptriThis = NULL;
136     SpherePtr psphThis = NULL;
137     ModelSpacePointPtr pmspTop = NULL;
138     ModelSpacePointPtr pmspBottom = NULL;
139     ModelSpacePointPtr pmspTemp = NULL;
140     RealValuePtr prvRadius = NULL;
141     ValNodePtr pvnSwap = NULL;
142     ValNodePtr pvnX = NULL;
143     ValNodePtr pvnY = NULL;
144     ValNodePtr pvnZ = NULL;
145     Int4 iCount = 0;
146     Int4 iCoords = 0;
147     Int4 iVal = 0;
148     Boolean rsult = FALSE;
149 
150     switch (pscThis->Surface_surface->choice)
151       {
152            case Surface_surface_cylinder:
153              if (!(pmodThis->bWhat & (Byte) OBJ_CYLINDER)) return FALSE;
154              pcylThis = (CylinderPtr) pscThis->Surface_surface->data.ptrvalue;
155              if (!pmodThis->ppflObject) return FALSE;
156              pmspTop = pcylThis->axis_top;
157              pmspBottom = pcylThis->axis_bottom;
158              prvRadius = pcylThis->radius;
159              pmspTop->x = ScaleToInt(pmodThis->ppflObject[0][0]); 
160              pmspTop->y = ScaleToInt(pmodThis->ppflObject[0][1]);
161              pmspTop->z = ScaleToInt(pmodThis->ppflObject[0][2]); 
162              pmspTop->scale_factor = SAVE_XYZ_SCALE_FACTOR;
163              pmspBottom->x = ScaleToInt(pmodThis->ppflObject[1][0]);  
164              pmspBottom->y = ScaleToInt(pmodThis->ppflObject[1][1]);
165              pmspBottom->z = ScaleToInt(pmodThis->ppflObject[1][2]); 
166              pmspBottom->scale_factor = SAVE_XYZ_SCALE_FACTOR;
167              prvRadius->scaled_integer_value = ScaleToInt(pmodThis->flRadius);
168              prvRadius->scale_factor = SAVE_XYZ_SCALE_FACTOR;
169              return TRUE;
170            case Surface_surface_sphere:
171              if (!(pmodThis->bWhat & (Byte) OBJ_SPHERE)) return FALSE;
172              psphThis = (SpherePtr) pscThis->Surface_surface->data.ptrvalue;
173              if (!pmodThis->ppflObject) return FALSE;
174              pmspTop = psphThis->center;
175              prvRadius = psphThis->radius;
176              pmspTop->x = ScaleToInt(pmodThis->ppflObject[0][0]);
177              pmspTop->y = ScaleToInt(pmodThis->ppflObject[0][1]);
178              pmspTop->z = ScaleToInt(pmodThis->ppflObject[0][2]);
179              pmspTop->scale_factor = SAVE_XYZ_SCALE_FACTOR;
180              prvRadius->scaled_integer_value = ScaleToInt(pmodThis->flRadius);
181              prvRadius->scale_factor = SAVE_XYZ_SCALE_FACTOR;
182              return TRUE;
183            case Surface_surface_brick:
184              if (!(pmodThis->bWhat &(Byte) OBJ_BRICK)) return FALSE;
185              pbrkThis = (BrickPtr) pscThis->Surface_surface->data.ptrvalue;
186              if (!pmodThis->ppflObject) return FALSE;
187              pmspTemp = pbrkThis->corner_000;
188              pmspTemp->x = ScaleToInt(pmodThis->ppflObject[0][0]);  
189              pmspTemp->y = ScaleToInt(pmodThis->ppflObject[0][1]); 
190              pmspTemp->z = ScaleToInt(pmodThis->ppflObject[0][2]);  
191              pmspTemp->scale_factor = SAVE_XYZ_SCALE_FACTOR;
192              pmspTemp = pbrkThis->corner_001;
193              pmspTemp->x = ScaleToInt(pmodThis->ppflObject[1][0]);  
194              pmspTemp->y = ScaleToInt(pmodThis->ppflObject[1][1]); 
195              pmspTemp->z = ScaleToInt(pmodThis->ppflObject[1][2]); 
196              pmspTemp->scale_factor = SAVE_XYZ_SCALE_FACTOR;
197              pmspTemp = pbrkThis->corner_010;
198              pmspTemp->x =  ScaleToInt(pmodThis->ppflObject[2][0]); 
199              pmspTemp->y =  ScaleToInt(pmodThis->ppflObject[2][1]); 
200              pmspTemp->z =  ScaleToInt(pmodThis->ppflObject[2][2]); 
201              pmspTemp->scale_factor = SAVE_XYZ_SCALE_FACTOR;
202              pmspTemp = pbrkThis->corner_011;
203              pmspTemp->x =  ScaleToInt(pmodThis->ppflObject[3][0]); 
204              pmspTemp->y =  ScaleToInt(pmodThis->ppflObject[3][1]);  
205              pmspTemp->z =  ScaleToInt(pmodThis->ppflObject[3][2]);  
206              pmspTemp->scale_factor = SAVE_XYZ_SCALE_FACTOR;
207              pmspTemp = pbrkThis->corner_100;
208              pmspTemp->x =  ScaleToInt(pmodThis->ppflObject[4][0]); 
209              pmspTemp->y =  ScaleToInt(pmodThis->ppflObject[4][1]); 
210              pmspTemp->z =  ScaleToInt(pmodThis->ppflObject[4][2]); 
211              pmspTemp->scale_factor = SAVE_XYZ_SCALE_FACTOR;
212              pmspTemp = pbrkThis->corner_101;
213              pmspTemp->x =  ScaleToInt(pmodThis->ppflObject[5][0]); 
214              pmspTemp->y =  ScaleToInt(pmodThis->ppflObject[5][1]); 
215              pmspTemp->z =  ScaleToInt(pmodThis->ppflObject[5][2]); 
216              pmspTemp->scale_factor = SAVE_XYZ_SCALE_FACTOR;
217              pmspTemp = pbrkThis->corner_110;
218              pmspTemp->x =  ScaleToInt(pmodThis->ppflObject[6][0]); 
219              pmspTemp->y =  ScaleToInt(pmodThis->ppflObject[6][1]); 
220              pmspTemp->z =  ScaleToInt(pmodThis->ppflObject[6][2]); 
221              pmspTemp->scale_factor = SAVE_XYZ_SCALE_FACTOR;
222              pmspTemp = pbrkThis->corner_111;
223              pmspTemp->x =  ScaleToInt(pmodThis->ppflObject[7][0]);
224              pmspTemp->y =  ScaleToInt(pmodThis->ppflObject[7][1]);
225              pmspTemp->z =  ScaleToInt(pmodThis->ppflObject[7][2]);
226              pmspTemp->scale_factor = SAVE_XYZ_SCALE_FACTOR;
227              return TRUE;          
228            case Surface_surface_cone:
229              if (!(pmodThis->bWhat & (Byte) OBJ_CONE)) return FALSE;
230              pconThis = (ConePtr) pscThis->Surface_surface->data.ptrvalue;
231              if (!pmodThis->ppflObject) return FALSE;
232              pmspTop = pconThis->axis_top;
233              pmspBottom = pconThis->axis_bottom;
234              prvRadius = pconThis->radius_bottom;
235              pmspTop->x = ScaleToInt(pmodThis->ppflObject[0][0]);
236              pmspTop->y = ScaleToInt(pmodThis->ppflObject[0][1]);
237              pmspTop->z = ScaleToInt(pmodThis->ppflObject[0][2]);
238              pmspTop->scale_factor = SAVE_XYZ_SCALE_FACTOR;
239              pmspBottom->x = ScaleToInt(pmodThis->ppflObject[1][0]);
240              pmspBottom->y = ScaleToInt(pmodThis->ppflObject[1][1]);
241              pmspBottom->z=  ScaleToInt(pmodThis->ppflObject[1][2]);
242              pmspBottom->scale_factor = SAVE_XYZ_SCALE_FACTOR;
243              prvRadius->scaled_integer_value = ScaleToInt(pmodThis->flRadius);
244              prvRadius->scale_factor = SAVE_XYZ_SCALE_FACTOR;;
245              return TRUE;
246            case Surface_surface_tmesh:
247              if (!(pmodThis->bWhat & (Byte) OBJ_TMESH)) return FALSE;
248              ptmshThis = (TMeshPtr) pscThis->Surface_surface->data.ptrvalue;
249              if (!pmodThis->ppflObject) return FALSE;
250              if (!pmodThis->pucSwap) return FALSE; 
251              ptmshThis->scale_factor = SAVE_XYZ_SCALE_FACTOR;
252              iCoords = pmodThis->iCoordNo;
253              for (iCount = 0; iCount < iCoords; iCount++) 
254                 {
255                     pvnX = ValNodeAddInt(&pvnX, 0, ScaleToInt(pmodThis->ppflObject[iCount][0]));
256                     pvnY = ValNodeAddInt(&pvnY, 0, ScaleToInt(pmodThis->ppflObject[iCount][1]));
257                     pvnZ = ValNodeAddInt(&pvnZ, 0, ScaleToInt(pmodThis->ppflObject[iCount][2]));
258                     pvnSwap = ValNodeAddBoolean(&pvnSwap, 0, (Boolean)(pmodThis->pucSwap[iCount] == 
259                                             (Uchar) 1)); 
260                     if (ptmshThis->x == NULL)
261                        {
262                          ptmshThis->x = pvnX;  /* these have been set to null */
263                          ptmshThis->y = pvnY;
264                          ptmshThis->z = pvnZ;
265                          ptmshThis->swap = pvnSwap;
266                        } 
267                     if ((pvnX == NULL) || (pvnY == NULL) || (pvnZ == NULL) || (pvnSwap == NULL))
268                         goto objallocerr;
269                 } 
270              ptmshThis->number_of_points = iCoords;
271              return TRUE;
272            case Surface_surface_triangles:
273              if (!(pmodThis->bWhat & (Byte) OBJ_TRIANGLES)) return FALSE;
274              ptriThis = (TrianglesPtr) pscThis->Surface_surface->data.ptrvalue;
275              if (!pmodThis->ppflObject) return FALSE;
276              if (!pmodThis->ppi4Triangles) return FALSE;
277              ptriThis->scale_factor = SAVE_XYZ_SCALE_FACTOR;
278              iCoords = pmodThis->iCoordNo;
279              for (iCount = 0; iCount < iCoords; iCount++) 
280                 {
281                     pvnX = ValNodeAddInt(&pvnX, 0, ScaleToInt(pmodThis->ppflObject[iCount][0]));
282                     pvnY = ValNodeAddInt(&pvnY, 0, ScaleToInt(pmodThis->ppflObject[iCount][1]));
283                     pvnZ = ValNodeAddInt(&pvnZ, 0, ScaleToInt(pmodThis->ppflObject[iCount][2]));
284                     if (ptmshThis->x == NULL)
285                        {
286                          ptriThis->x = pvnX;  /* these have been set to null */
287                          ptriThis->y = pvnY;
288                          ptriThis->z = pvnZ;
289                        } 
290                     if ((pvnX == NULL) || (pvnY == NULL) || (pvnZ == NULL))
291                         goto objallocerr;
292                 } 
293              ptriThis->number_of_points = iCoords;  
294              iCoords = pmodThis->iTriNo;
295              pvnX = NULL; 
296              pvnY = NULL;
297              pvnZ = NULL;
298              for (iCount = 0; iCount < iCoords; iCount++) 
299                 {
300                     pvnX = ValNodeAddInt(&pvnX, 0, pmodThis->ppi4Triangles[iCount][0]);
301                     pvnY = ValNodeAddInt(&pvnY, 0, pmodThis->ppi4Triangles[iCount][1] );
302                     pvnZ = ValNodeAddInt(&pvnZ, 0, pmodThis->ppi4Triangles[iCount][2] );
303                     if (ptmshThis->x == NULL)
304                        {
305                          ptriThis->v1 = pvnX;  /* these have been set to null */
306                          ptriThis->v2 = pvnY;
307                          ptriThis->v3 = pvnZ;
308                        } 
309                     if ((pvnX == NULL) || (pvnY == NULL) || (pvnZ == NULL))
310                         goto objallocerr;
311                  
312                 }  
313              ptriThis->number_of_triangles = iCoords;
314              return TRUE;
315            default:
316              rsult = FALSE;
317        }
318     return rsult;   
319     
320     objallocerr:
321    
322       FreeSurfaceModelAsnList(pscThis);
323       return FALSE;
324 }
325 
326 
327 
328                 
329                         
330 
331 static void FreeCoordinatesAsnLists(CoordinatesPtr pcoThis)
332 {
333     AtomicCoordinatesPtr                pacThis = NULL;
334     SurfaceCoordinatesPtr               pscThis = NULL;
335     DensityCoordinatesPtr               pdcThis = NULL; 
336     
337   
338     switch (pcoThis->choice)
339      {
340       case Coordinates_surface:
341         pscThis = (SurfaceCoordinatesPtr) pcoThis->data.ptrvalue;
342         FreeSurfaceModelAsnList(pscThis);
343         return;
344       case Coordinates_density:
345         pdcThis = (DensityCoordinatesPtr) pcoThis->data.ptrvalue;
346 /*      FreeDensityModelAsnList(pdcThis); */
347         return;
348       case Coordinates_atomic:
349         pacThis = (AtomicCoordinatesPtr) pcoThis->data.ptrvalue;
350         FreeAtomicModelAsnLists(pacThis);
351         return;
352       default:
353         return;
354      }
355 }       
356         
357         
358 void LIBCALL   FreeRedundantAsn(PDNMS pdnmsThis)
359 {
360    /* does un-hooking of dict from chemical graph; frees chem-graph */
361    /* Recoverable - out of memory errors are handled with this */
362    /* frees model data ASN.1 & parts of chemical graph  */
363 
364     PMLD pmldThis = NULL;
365     PMSD pmsdThis = NULL;
366     PDNML pdnmlThis = NULL;
367     BiostrucModelPtr pbsmThis = NULL;
368     ModelCoordinateSetPtr pmcsThis = NULL;
369     CoordinatesPtr pcoThis = NULL;
370     PDNMM pdnmmThis = NULL;
371     PMMD pmmdThis = NULL;
372     MoleculeGraphPtr pmgThis = NULL;
373 
374     /* get rid of model redundant stuff */
375     if (!pdnmsThis) return;
376     pmsdThis = (PMSD) pdnmsThis->data.ptrvalue;
377     if (!pmsdThis) return;
378     
379     /* remove redundant parts of Chemical Graph */
380     /* keep, dictionary, descrs and seq_id's */
381     
382     if (pmsdThis->pbsBS->chemical_graph)
383       {
384         /* unhook dict from chem graph */
385         if (pmsdThis->pbsBS->chemical_graph->residue_graphs)
386         pmsdThis->pbsBS->chemical_graph->residue_graphs = NULL;
387         /* these are pointed to also by pmsdThis->pDictLocal */
388 
389         /* unhook the Descr's from chem graph */
390         if (pmsdThis->pbsBS->chemical_graph->descr)
391           pmsdThis->pbsBS->chemical_graph->descr = NULL;
392         /* pointed to by pmsdThis->pGraphDescr */
393     
394         /* walk the molecules in the chem graph, unhook the pMolDescr, pSeqId */
395         pmgThis = pmsdThis->pbsBS->chemical_graph->molecule_graphs;
396         while (pmgThis) /* walk up the molecule_graphs */
397         {
398             pmgThis->descr = NULL;
399             pmgThis->seq_id = NULL;
400             pmgThis = pmgThis->next;
401         }
402       
403         /* free chem-graph */
404         BiostrucGraphFree(pmsdThis->pbsBS->chemical_graph);
405         pmsdThis->pbsBS->chemical_graph = NULL;
406       }
407   
408     /* remove redundant parts of models */ 
409     
410     pdnmlThis = pmsdThis->pdnmlModels;
411     while (pdnmlThis)
412       {
413         pmldThis = (PMLD) pdnmlThis->data.ptrvalue;
414         if (!pmldThis) return;  
415         while (pmldThis) 
416         {  
417             pmcsThis = pmldThis->pbsmModel->model_coordinates;
418             while (pmcsThis)
419                 {  /* match the two together */  
420                     if (pmcsThis->id == pmldThis->iNoCoordSet) break;
421                     pmcsThis = pmcsThis->next;
422                 }  /* find the Asn.1 stub */
423             pcoThis = (CoordinatesPtr) pmcsThis->Coordinates_coordinates->data.ptrvalue;
424             if (pcoThis) FreeCoordinatesAsnLists(pcoThis);  /* pare down to stubs */
425             pmldThis = pmldThis->next;
426         }
427        pdnmlThis = pdnmlThis->next;
428      }
429   return;  
430 }       
431 
432 
433  
434 Boolean LIBCALL RefreshModelAsnMem(PDNMS pdnmsThis,  Int2 iModel)
435 {
436 
437 /* Does a direct copy of all Modelstruc coordinates into Biostruc Model      */
438 /* data structures. Used to populate coordinates before saving               */
439 /* The ASN.1 stub is validated - and it must be present and complete, or     */ 
440 /* the routine will fail */
441 /* The stub would be absent under conditions where a model was               */
442 /* constructed by hand without using the NewModel() function                 */
443 
444 
445     PMAD        pmadThis = NULL;
446     PALD        paldThis = NULL;
447     PMOD        pmodThis = NULL;
448     PMDD        pmddThis = NULL;
449     PMLD        pmldThis = NULL;
450     PDNML       pdnmlThis = NULL;
451     PMSD        pmsdThis = NULL;
452     PDNMM       pdnmmThis = NULL; 
453     PMMD        pmmdThis = NULL; 
454     PDNMG       pdnmgThis = NULL;
455     PMGD        pmgdThis = NULL;  
456     PVNMA       pvnmaThis = NULL;
457     
458     AlternateConformationIdsPtr         paciThis = NULL;
459     BiostrucModelPtr                    pbsmThis = NULL;
460     AtomicCoordinatesPtr                pacThis = NULL;
461     IsotropicTemperatureFactorsPtr      pitfThis = NULL;
462     AnisotropicTemperatureFactorsPtr    patfThis = NULL;
463     AtomicOccupanciesPtr                pocThis = NULL;
464     ModelSpacePointsPtr                 pmspThis = NULL;
465     AtomPntrsPtr                        pappThis = NULL;
466     CoordinatesPtr                      pcoThis = NULL;
467     ModelCoordinateSetPtr               pmcsThis = NULL;
468     SurfaceCoordinatesPtr               pscThis = NULL;
469   /*  DensityCoordinatesPtr             pdcThis = NULL; 
470   */   
471     CharPtr                             pcTemp = NULL;
472     Int4                                iCountAtoms = 0;
473     Int4                                iX,  iY,  iZ;
474     Int4                                iCoordSets = 0;
475     Boolean                             bFirst = TRUE;
476     Boolean                             bGotoCalled = FALSE;
477     ValNodePtr  pvnX = NULL;
478     ValNodePtr  pvnY = NULL;
479     ValNodePtr  pvnZ = NULL;
480     ValNodePtr  pvnB11 = NULL;
481     ValNodePtr  pvnB12 = NULL;
482     ValNodePtr  pvnB13 = NULL;
483     ValNodePtr  pvnB22 = NULL;
484     ValNodePtr  pvnB23 = NULL;
485     ValNodePtr  pvnB33 = NULL;
486     ValNodePtr  pvnOcc = NULL;
487     ValNodePtr  pvnAlt = NULL;
488     ValNodePtr  pvnMid = NULL;
489     ValNodePtr  pvnRid = NULL;
490     ValNodePtr  pvnAid = NULL;
491     ValNodePtr  pmdrThis = NULL;       
492     int         iBailno = 0;
493    
494  
495     pmsdThis = (PMSD) pdnmsThis->data.ptrvalue;
496  /* find the right model in the doubly-linked list */
497     if (!pmsdThis->pdnmlModels) 
498       {
499 
500 #ifdef _DEBUG_5 
501 printf("No models in structure...\n");
502 #endif    
503    
504          return FALSE;
505       }
506     pdnmlThis = DValNodeFindNext(pmsdThis->pdnmlModels, NULL, iModel); 
507     if (!pdnmlThis)
508       {
509 #ifdef _DEBUG_5 
510 printf("No such model in RefreshModelAsn \n");
511    
512          pdnmlThis = pmsdThis->pdnmlModels;
513          while (pdnmlThis)
514           {
515             printf("but found model %d\n", (int) pdnmlThis->choice);
516             pdnmlThis = pdnmlThis->next;
517           }
518          return FALSE;  /* no such model */
519 #endif 
520       }
521  /* cast to the model node */
522     pmldThis = (PMLD) pdnmlThis->data.ptrvalue;  
523     if (!pmldThis->pbsmModel) { iBailno = 1; goto errorbail; }
524  /* there must be a pbsmModel at this point */
525     pbsmThis = pmldThis->pbsmModel;
526     pbsmThis->id =  pmldThis->iId;   /* refresh the id, type */
527     pbsmThis->type = pmldThis->iType;
528     
529     /* refresh  name string   */  
530     /* find the old string */
531     pmdrThis = ValNodeFindNext(pbsmThis->descr, NULL, ModelDescr_name);
532     if (pmdrThis)
533       {
534          /* free it */
535          if (pmdrThis->data.ptrvalue) 
536            MemFree((CharPtr) pmdrThis->data.ptrvalue);
537          /* replace it */
538          if (pmldThis->pcModelName) 
539             pmdrThis->data.ptrvalue = StringSave(pmldThis->pcModelName);
540          else 
541             pmdrThis->data.ptrvalue = NULL;
542       }  
543     else
544       {
545           ValNodeCopyStr(&pmldThis->pbsmModel->descr, ModelDescr_name, pmldThis->pcModelName);
546           /* if no string, this does nothing */
547       }
548       /* conditionally rebuild the ASN.1 stub */
549     if (!pbsmThis->model_coordinates)
550       {
551         iBailno = 1;
552         goto errorbail;
553       }
554       
555     /* model_space is optional - if it wasn't already there we don't fill it in here... */
556       
557     if (!pbsmThis->model_coordinates) { iBailno = 2; goto errorbail; }
558        /* there must be a model_coordinates node */
559       
560     /* Do each coord set for this one model */
561     while (pmldThis) 
562      {  
563      
564       /*
565        * each pmldThis contains either one chemical graph's worth of ald's or
566        * one object or one density  pointer 
567        * There must be one pmcsThis for each pmldThis. 
568        */   
569         
570         /* find the matching id in the ASN.1 stub model_coordinates list */
571         pmcsThis = pbsmThis->model_coordinates;
572         while (pmcsThis)
573           {
574             if (pmcsThis->id == pmldThis->iNoCoordSet) break;
575             pmcsThis = pmcsThis->next;
576           }  
577         if (!pmcsThis){ iBailno = 3; goto errorbail; } /* not found - ASN.1 stub error condition */
578         
579         
580         
581         /* find all the heads of pointers we'll need to be updating */
582         /* from within the ASN.1 stub */
583     
584           
585         if (!pmcsThis->Coordinates_coordinates) { iBailno = 4; goto errorbail; }  
586           /* this part of the ASN.1 stub must be present */
587         if (pmcsThis->Coordinates_coordinates->choice == Coordinates_coordinates_reference) goto skipnext;
588             /* cannot handle coordinates by reference yet */
589                 
590         pcoThis = (CoordinatesPtr) pmcsThis->Coordinates_coordinates->data.ptrvalue;
591         if (!pcoThis) { iBailno = 5; goto errorbail; } /* this part of the ASN.1 stub must be present */
592    
593           /* see what kind of data pmldThis contains, surface, density or atoms */
594           
595         pmodThis = pmldThis->pmodObject;
596         if (pmodThis) /* is it a surface object ? */
597           {
598             if (pcoThis->choice != Coordinates_surface){ iBailno = 6; goto errorbail; } /* ASN.1 stub mismatch */
599               /* rebuild or refresh ASN.1 object */
600               pscThis = (SurfaceCoordinatesPtr) pcoThis->data.ptrvalue;
601               FreeSurfaceModelAsnList(pscThis); 
602               if (!RefreshSurface(pscThis, pmodThis)) { iBailno = 6; goto memnewbail; } /* memory error */;
603               goto skipnext;
604           }
605  
606         pmddThis = pmldThis->pmddDensity;
607         if (pmddThis)  /* is it a density object ?  */
608           {
609             if (pcoThis->choice != Coordinates_density) { iBailno = 7; goto errorbail; }  /* ASN.1 stub mismatch */
610               /* rebuild or refresh ASN.1 density */
611               
612         /*      FreeDensityAsnList();
613                 RefreshDensity();
614         */
615               goto skipnext;
616           }
617           
618         /* still here - MUST be atoms */
619         if (pcoThis->choice != Coordinates_atomic) { iBailno = 8; goto errorbail; }  /* ASN.1 stub mismatch */
620         
621         pacThis = NULL;
622         pacThis = (AtomicCoordinatesPtr) pcoThis->data.ptrvalue;
623         if (!pacThis) { iBailno = 9; goto errorbail; }  /* ASN.1 stub not complete */
624         
625         /* Free all remaining data off AtomicCoordinatesPtr pacThis */
626         
627         FreeAtomicModelAsnLists(pacThis);
628         
629         /* at this point pacThis is clean excepting any !!!CONF-ENSEMBLES!! that may be present */
630         
631         /* go ahead and rebuild the pacThis model linked-lists from the ALD node data */
632 
633         iCountAtoms = 0;
634         bFirst = TRUE;
635         bGotoCalled = FALSE;
636         pdnmmThis = pmsdThis->pdnmmHead;
637         if (pmldThis->ppAsnOrder)
638           {   /* if the order matrix is present, then     */
639               /* traverse nodes in order they were loaded */
640               /* This matrix begins with element #1 for ASN.1 indexing purposes */
641               /* and ends with a null pointer */
642             for (iCountAtoms = 1; pmldThis->ppAsnOrder[iCountAtoms] != NULL; iCountAtoms++)
643               {
644                   paldThis = pmldThis->ppAsnOrder[iCountAtoms];
645                   bGotoCalled = TRUE;
646                   pmadThis = (PMAD) paldThis->pfbParent;
647                   goto aldsaveblockstart;
648                    /* goto used to avoid  code duplication                         */
649                    /* making a separate function is impractical in this case owing */
650                    /* to the large number of linked-lists kept as overhead         */
651                    /* This way, everything stays in scope.                         */
652                   aldsaveblockreturn: ;
653                                  
654               }  /* for */
655             iCountAtoms--;  /* back it up one to the correct count */
656           }  /* if ppAsnOrder */
657         else  
658           /* traverse the hierachical structure to find paldThis */
659         while(pdnmmThis)
660             {   /*molecule*/
661                 pmmdThis = (PMMD) pdnmmThis->data.ptrvalue;
662                 pdnmgThis =  pmmdThis->pdnmgHead;
663                 while(pdnmgThis)
664                 {   /*graph*/
665                     pmgdThis = (PMGD) pdnmgThis->data.ptrvalue;
666                     pvnmaThis = pmgdThis->pvnmaAHead;
667                     while (pvnmaThis)
668                         {   /*atom*/
669                             pmadThis = (PMAD) pvnmaThis->data.ptrvalue;
670                             paldThis = GetAtomLocs(pmadThis,  iModel);
671                             while (paldThis)
672                               {
673                                 iCountAtoms++;
674         aldsaveblockstart:   /* goto used in the for loop to avoid code duplication */
675                                 if ((!paldThis->pflvData)  || (paldThis->iFloatNo <  2)) goto errorbail; /* coords missing */
676                                 iX =  ScaleToInt(paldThis->pflvData[0]);
677                                 iY =  ScaleToInt(paldThis->pflvData[1]);
678                                 iZ =  ScaleToInt(paldThis->pflvData[2]);
679                                    
680                                 if (bFirst)
681                                   {
682                                      /* initialize lists off of pacThis */
683                                      /* note that each ALD must have same amt of data as first */
684                                     pacThis->atoms = AtomPntrsNew();
685                                     if (!pacThis->atoms) { iBailno = 10; goto memnewbail; } 
686                                        /* number_of_ptrs, molecule_ids, resiude_ids, atom_ids */
687                                     pacThis->atoms->molecule_ids = 
688                                         ValNodeAddInt(  NULL, 
689                                                         0, 
690                                                         IndexFromNode((PFB)GetParentMol((PFB)pmadThis)));
691                                     if (!pacThis->atoms->molecule_ids) { iBailno = 11; goto memnewbail; } 
692                                     pvnMid = pacThis->atoms->molecule_ids;
693                                     pacThis->atoms->residue_ids = 
694                                         ValNodeAddInt(  NULL, 
695                                                         0, 
696                                                         IndexFromNode((PFB)GetParentGraph((PFB)pmadThis)));
697                                     if (!pacThis->atoms->residue_ids){ iBailno = 12; goto memnewbail; }         
698                                     pvnRid = pacThis->atoms->residue_ids;                                       
699                                     pacThis->atoms->atom_ids =
700                                         ValNodeAddInt(  NULL, 
701                                                         0, 
702                                                         IndexFromNode((PFB)pmadThis));
703                                     if (!pacThis->atoms->atom_ids) { iBailno = 13; goto memnewbail; }     
704                                     pvnAid = pacThis->atoms->atom_ids; 
705                                     pacThis->sites = ModelSpacePointsNew();
706                                     if (!pacThis->sites){ iBailno = 14; goto memnewbail; } 
707                                       /* scale_factor, x, y, z */
708                                     pacThis->sites->x = ValNodeAddInt(NULL, 0, iX);
709                                     if (!pacThis->sites->x) { iBailno = 15; goto memnewbail; } 
710                                     pvnX = pacThis->sites->x;
711                                     pacThis->sites->y = ValNodeAddInt(NULL, 0, iY);
712                                     if (!pacThis->sites->y) { iBailno = 16; goto memnewbail; } 
713                                     pvnY = pacThis->sites->y;
714                                     pacThis->sites->z = ValNodeAddInt(NULL, 0, iZ); 
715                                     if (!pacThis->sites->z) { iBailno = 17; goto memnewbail; } 
716                                     pvnZ = pacThis->sites->z;
717                                     pacThis->sites->scale_factor = SAVE_XYZ_SCALE_FACTOR;
718                                     if (paldThis->iFloatNo >= 3)
719                                       {
720                                           pacThis->occupancies = AtomicOccupanciesNew();
721                                           if (!pacThis->occupancies) { iBailno = 18; goto memnewbail; } 
722                                              /* scale_factor, o */
723                                           iZ =  ScaleToInt(paldThis->pflvData[3]);
724                                           pacThis->occupancies->o = ValNodeAddInt(NULL, 0, iZ);
725                                           if (!pacThis->occupancies->o) { iBailno = 19; goto memnewbail; } 
726                                           pvnOcc = pacThis->occupancies->o;
727                                           pacThis->occupancies->scale_factor = SAVE_XYZ_SCALE_FACTOR;
728                                       }
729                                     if (paldThis->iFloatNo == 4) /* Isotropic Temp Factors */
730                                       {
731                                           pitfThis = IsotropicTemperatureFactorsNew();
732                                           if (!pitfThis) { iBailno = 20; goto memnewbail; } 
733                                           pacThis->temperature_factors = ValNodeAddPointer(NULL, 
734                                                                                     AtomicTemperatureFactors_isotropic, 
735                                                                                     pitfThis);
736                                           if (!pacThis->temperature_factors) { iBailno = 21; goto memnewbail; } 
737                                           iZ =  ScaleToInt(paldThis->pflvData[4]);
738                                           pitfThis->b = ValNodeAddInt(NULL, 0,  iZ);
739                                           if (!pitfThis->b){ iBailno = 22; goto memnewbail; } 
740                                           pvnB11 = pitfThis->b;
741                                           pitfThis->scale_factor = SAVE_XYZ_SCALE_FACTOR;
742                                       }
743                                     if (paldThis->iFloatNo == 9) /* Anisotropic Temp Factors */
744                                       {
745                                         patfThis = AnisotropicTemperatureFactorsNew();
746                                         if (!patfThis) { iBailno = 23; goto memnewbail; } 
747                                         pacThis->temperature_factors = ValNodeAddPointer(NULL, 
748                                                                                     AtomicTemperatureFactors_anisotropic, 
749                                                                                     patfThis);
750                                         if (!pacThis->temperature_factors) { iBailno = 24; goto memnewbail; } 
751                                         patfThis->scale_factor = SAVE_XYZ_SCALE_FACTOR;
752                                         iZ = ScaleToInt(paldThis->pflvData[4]);
753                                         patfThis->b_11 = ValNodeAddInt(NULL, 0,  iZ);
754                                         if (!patfThis->b_11) { iBailno = 25; goto memnewbail; } 
755                                         pvnB11 = patfThis->b_11;
756                                         iZ =  ScaleToInt(paldThis->pflvData[5]);
757                                         patfThis->b_12 = ValNodeAddInt(NULL, 0,  iZ);
758                                         if (!patfThis->b_12) { iBailno = 26; goto memnewbail; } 
759                                         pvnB12 = patfThis->b_12;
760                                         iZ =  ScaleToInt(paldThis->pflvData[6]);
761                                         patfThis->b_13 = ValNodeAddInt(NULL, 0,  iZ);
762                                         if (!patfThis->b_13) { iBailno = 27; goto memnewbail; } 
763                                         pvnB13 = patfThis->b_13;
764                                         iZ =  ScaleToInt(paldThis->pflvData[7]);
765                                         patfThis->b_22 = ValNodeAddInt(NULL, 0,  iZ);
766                                         if (!patfThis->b_22) { iBailno = 28; goto memnewbail; } 
767                                         pvnB22 = patfThis->b_22;
768                                         iZ =  ScaleToInt(paldThis->pflvData[8]);
769                                         patfThis->b_23 = ValNodeAddInt(NULL, 0,  iZ);
770                                         if (!patfThis->b_23) { iBailno = 29; goto memnewbail; } 
771                                         pvnB23 = patfThis->b_23;
772                                         iZ =  ScaleToInt(paldThis->pflvData[9]);
773                                         patfThis->b_33 = ValNodeAddInt(NULL, 0,  iZ);
774                                         if (!patfThis->b_33) { iBailno = 30; goto memnewbail; } 
775                                         pvnB33 = patfThis->b_33;
776                                       }   
777                                     if (pmldThis->pcAltConf) /* is there an alt-conf string for this model ? */
778                                       {
779                                         pacThis->alternate_conf_ids = ValNodeCopyStr(NULL, 0, STRING_UNK_MOL);
780                                         if (!pacThis->alternate_conf_ids) { iBailno = 31; goto memnewbail; } 
781                                         pcTemp = (CharPtr) pacThis->alternate_conf_ids->data.ptrvalue;
782                                         pcTemp[0] = paldThis->cAltConf;
783                                         pvnAlt = pacThis->alternate_conf_ids;
784                                       }
785                                   }  /* first-case */
786                                 else
787                                   {
788                                     /* otherwise the parent pointers are already initialized */
789                                     /* Allocate new nodes; x,y,z,o,m_ids,r_ids,a_ids,temp(s) */
790                                     
791                                     pvnMid->next = ValNodeAddInt(   NULL, 
792                                                                     0, 
793                                                                     IndexFromNode((PFB)GetParentMol((PFB)pmadThis)));
794                                     if (!pvnMid->next) { iBailno = 32; goto memnewbail; } 
795                                     pvnMid = pvnMid->next;
796                                     pvnRid->next = ValNodeAddInt(   NULL, 
797                                                                     0, 
798                                                                     IndexFromNode((PFB)GetParentGraph((PFB)pmadThis)));
799                                     if (!pvnRid->next) { iBailno = 33; goto memnewbail; } 
800                                     pvnRid = pvnRid->next;
801                                     pvnAid->next = ValNodeAddInt(   NULL, 
802                                                                     0, 
803                                                                     IndexFromNode((PFB)pmadThis));
804                                     if (!pvnAid->next) { iBailno = 34; goto memnewbail; } 
805                                     pvnAid = pvnAid->next;
806                                     pvnX->next = ValNodeAddInt(NULL, 0, iX);
807                                     if (!pvnX->next){ iBailno = 35; goto memnewbail; } 
808                                     pvnX = pvnX->next;
809                                     pvnY->next = ValNodeAddInt(NULL, 0, iY);
810                                     if (!pvnY->next) { iBailno = 36; goto memnewbail; } 
811                                     pvnY = pvnY->next;
812                                     pvnZ->next = ValNodeAddInt(NULL, 0, iZ); 
813                                     if (!pvnZ->next) { iBailno = 37; goto memnewbail; } 
814                                     pvnZ = pvnZ->next;
815                                     if (paldThis->iFloatNo == 4)
816                                       {
817                                         iZ =  ScaleToInt(paldThis->pflvData[4]);
818                                         pvnB11->next = ValNodeAddInt(NULL, 0,  iZ);
819                                         if (!pvnB11->next) { iBailno = 38; goto memnewbail; } 
820                                         pvnB11 = pvnB11->next;
821                                       } 
822                                     if (paldThis->iFloatNo == 9)
823                                       {
824                                         iZ =  ScaleToInt(paldThis->pflvData[4]);
825                                         pvnB11->next = ValNodeAddInt(NULL, 0,  iZ);
826                                         if (!pvnB11->next) { iBailno = 39; goto memnewbail; } 
827                                         pvnB11 = pvnB11->next;
828                                         iZ =  ScaleToInt(paldThis->pflvData[5]);
829                                         pvnB12->next = ValNodeAddInt(NULL, 0,  iZ);
830                                         if (!pvnB12->next) { iBailno = 40; goto memnewbail; } 
831                                         pvnB12 = pvnB12->next;
832                                         iZ =  ScaleToInt(paldThis->pflvData[6]);
833                                         pvnB13->next = ValNodeAddInt(NULL, 0,  iZ);
834                                         if (!pvnB13->next) { iBailno = 41; goto memnewbail; } 
835                                         pvnB13 = pvnB13->next;
836                                         iZ =  ScaleToInt(paldThis->pflvData[7]);
837                                         pvnB22->next = ValNodeAddInt(NULL, 0,  iZ);
838                                         if (!pvnB22->next) { iBailno = 42; goto memnewbail; } 
839                                         pvnB22 = pvnB22->next;
840                                         iZ =  ScaleToInt(paldThis->pflvData[8]);
841                                         pvnB23->next = ValNodeAddInt(NULL, 0,  iZ);
842                                         if (!pvnB23->next) { iBailno = 43; goto memnewbail; } 
843                                         pvnB23 = pvnB23->next;
844                                         iZ =  ScaleToInt(paldThis->pflvData[9]);
845                                         pvnB33->next = ValNodeAddInt(NULL, 0,  iZ);
846                                         if (!pvnB33->next) { iBailno = 44; goto memnewbail; } 
847                                         pvnB33 = pvnB33->next;
848                                       }
849                                     if (pvnOcc)
850                                       {  
851                                         iZ =  ScaleToInt(paldThis->pflvData[3]);
852                                         pvnOcc->next =   ValNodeAddInt(NULL, 0, iZ);
853                                         if (!pvnOcc->next) { iBailno = 45; goto memnewbail; } 
854                                         pvnOcc = pvnOcc->next;
855                                       }
856                                     if (pvnAlt)
857                                       {
858                                         pvnAlt->next = ValNodeCopyStr(NULL, 0, STRING_UNK_MOL);
859                                         if (!pvnAlt->next) { iBailno = 46; goto memnewbail; } 
860                                         pcTemp = (CharPtr) pvnAlt->next->data.ptrvalue;
861                                         pcTemp[0] = paldThis->cAltConf;
862                                         pvnAlt = pvnAlt->next;
863                                       }
864                                   }  /* continuation of linked-lists */
865                                   
866                                   bFirst = FALSE; 
867         if (bGotoCalled) goto aldsaveblockreturn;  /* ends the for loop block goto */
868                                   paldThis = paldThis->next;  /* traverse alt-confs */
869                               }  /* while paldThis */
870                             pvnmaThis = pvnmaThis->next;
871                         }   /*atom*/
872                     pdnmgThis = pdnmgThis->next;
873                 }/*graph*/
874                 pdnmmThis = pdnmmThis->next;
875             }   /*molecule*/
876 
877     /* copy COUNTER into appropriate places */
878             
879             
880         pacThis->number_of_points = iCountAtoms;
881         pacThis->atoms->number_of_ptrs = iCountAtoms;
882    
883     skipnext:    
884        pmldThis = pmldThis->next;  /* next coordinate set in same model */
885      
886      } /* while pmldThis */
887 
888 return TRUE;
889     
890     
891     errorbail:
892 #ifdef _DEBUG_5
893 printf("errorbail out %d - ASN.1 stub mismatch \n ",iBailno );
894 #endif    
895       /* Unrecoverable stub mismach or Modelstruc indexing errors */
896       /* fatal */
897         ErrClear(); 
898         ErrPostEx(SEV_FATAL,0,0, "Save operation found corrupt data structures\n Error at %d.",iBailno);
899         ErrShow();
900           
901       return FALSE;
902       
903     memnewbail:
904 #ifdef _DEBUG_5
905 printf("memnewbail out %d - out of memory error \n ", iBailno );
906 #endif 
907       /* Recoverable out of memory error */
908       /* clear all ASN data out - must start save process from scratch */
909   
910   
911     FreeRedundantAsn(pdnmsThis);
912     ErrClear(); 
913     ErrPostEx(SEV_ERROR,0,0, "Out of memory (at %d) while trying to save.\n Try again after closing other windows/programs.",iBailno);
914     ErrShow();
915     return FALSE;
916 
917 }
918 
919 
920         
921 
922 
923 Boolean LIBCALL RebuildChemGraphAsn(PDNMS pdnmsThis)
924 {
925    /* looks for kept chemical graps - if not ASN.1 minimum
926     * or if it was not kept,  it reconstructs the chemical graph.
927     * Upon TRUE,  pdnmsThis' Chemical Graph ASN.1 is repopulated.
928     * FASE means it cannot be repopulated.
929     */
930 
931     Boolean                     bOK = TRUE;
932     Boolean                     bFirstMol = TRUE;
933     Boolean                     bFirstRes = TRUE;
934     Boolean                     bFirstIRB = TRUE;
935     Int1                        iDictChoice;
936     PMSD                        pmsdThis = NULL;
937     PDNMM                       pdnmmThis = NULL;
938     PMMD                        pmmdThis = NULL;
939     MoleculeGraphPtr            pmgNew = NULL;
940     MoleculeGraphPtr            pmgLast = NULL;
941     ResiduePtr                  prNew = NULL;
942     ResiduePtr                  prLast = NULL;
943     PDNMG                       pdnmgThis = NULL;
944     PMGD                        pmgdThis = NULL;
945     BiostrucResidueGraphSetPntrPtr      pbrgsNew = NULL;
946     DbtagPtr                    pdbtNew = NULL;
947     PVNMB                       pvnmbThis = NULL;
948     PMBD                        pmbdThis = NULL;
949     InterResidueBondPtr         pirbNew = NULL;
950     InterResidueBondPtr         pirbLast = NULL;
951            
952     
953     pmsdThis = (PMSD) pdnmsThis->data.ptrvalue;
954     if (!(pmsdThis->bMe == (Byte) AM_MSD)) return FALSE;
955     
956     /* affix a new chemical graph node to the Biostruc */ 
957     pmsdThis->pbsBS->chemical_graph = BiostrucGraphNew();
958    
959     if (!pmsdThis->pbsBS->chemical_graph) goto allocerr;
960     /* re-attach the main descr (ASN optional) */
961     pmsdThis->pbsBS->chemical_graph->descr = pmsdThis->pGraphDescr;
962 
963     /* re-attach the local dictionary (ASN optional) */
964     pmsdThis->pbsBS->chemical_graph->residue_graphs = pmsdThis->pDictLocal;
965 
966     /* rebuild molecule_graphs */
967     /* here the seq-id's and descr's have been preserved in MMD's */
968     pdnmmThis = pmsdThis->pdnmmHead;
969     bFirstMol = TRUE;
970     while(pdnmmThis)  /* walk the molecule list */
971       {
972         pmmdThis = (PMMD) pdnmmThis->data.ptrvalue;
973         pmgNew = MoleculeGraphNew();
974         if (!pmgNew) goto allocerr;
975         if (bFirstMol) 
976           { 
977             pmsdThis->pbsBS->chemical_graph->molecule_graphs = pmgNew;
978             pmgLast = pmgNew;
979             bFirstMol = FALSE;
980           }
981         else
982           {
983             pmgLast->next = pmgNew;
984             pmgLast = pmgNew;
985           }
986            
987         /* Fill pmgNew's id, descr, seq_id */ 
988         
989         pmgNew->id = pdnmmThis->choice;
990         pmgNew->descr = pmmdThis->pMolDescr;
991         pmgNew->seq_id = pmmdThis->pSeqId;
992         
993         
994         /* residue_sequence */
995         
996         pdnmgThis = pmmdThis->pdnmgHead; /* top of sequence */
997         bFirstRes = TRUE;
998         while (pdnmgThis)  /* walk the residues */
999           {
1000             pmgdThis = (PMGD) pdnmgThis->data.ptrvalue;
1001             prNew = ResidueNew();
1002             if (!prNew) goto allocerr;
1003             if  (bFirstRes)
1004               {
1005                   pmgNew->residue_sequence = prNew;
1006                   prLast = prNew;
1007                   bFirstRes = FALSE;
1008               }
1009             else
1010               {
1011                   prLast->next = prNew;
1012                   prLast = prNew;
1013               }
1014             /* Fill in prNew's id, name, residue    */
1015                 
1016             prNew->id = pdnmgThis->choice;
1017             prNew->name = StringSave(pmgdThis->pcGraphNum);  /* this gets copied */
1018             
1019             if (pmgdThis->bWhat & (Byte) DICT_GLOBAL) 
1020               {
1021                  iDictChoice = ResidueGraphPntr_standard;
1022                  pbrgsNew = BiostrucResidueGraphSetPntrNew();
1023                  if (!pbrgsNew) goto allocerr;
1024                  pdbtNew = DbtagNew();
1025                  if (!pdbtNew) goto allocerr;
1026                  pdbtNew->db = StringSave(DICT_STANDARD_STRING);
1027                  pdbtNew->tag = ObjectIdNew();
1028                  if (!pdbtNew->tag) goto allocerr;
1029                  pdbtNew->tag->id = DICT_STANDARD_ID;
1030                  pbrgsNew->biostruc_residue_graph_set_id =  
1031                  ValNodeAddPointer(NULL, BiostrucId_other_database, pdbtNew);
1032                  pbrgsNew->residue_graph_id = pmgdThis->iIDict;
1033                  prNew->residue_graph = ValNodeAddPointer(NULL, iDictChoice, pbrgsNew);
1034               }
1035             else  
1036             if (pmgdThis->bWhat & (Byte) DICT_LOCAL) 
1037               {
1038                  iDictChoice = ResidueGraphPntr_local;
1039                  prNew->residue_graph = ValNodeAddInt(NULL, iDictChoice, pmgdThis->iIDict);
1040                  if (!prNew->residue_graph) goto allocerr;
1041               }
1042             else  
1043            /* if (pmgdThis->bWhat & (Byte) DICT_REF)  */
1044               {
1045               
1046                     ErrClear(); 
1047                     ErrPostEx(SEV_FATAL,0,0, "Cannot handle Dictionary \nCannot Reference to Another Biostruc");
1048                     ErrShow();
1049                     return FALSE;
1050               }
1051               
1052             pdnmgThis = pdnmgThis->next;
1053           }
1054                 
1055          /* inter_residue_bonds */
1056        
1057         
1058         pvnmbThis = pmmdThis->pvnmbIRBHead;
1059         bFirstIRB = TRUE;
1060         while(pvnmbThis)
1061           {
1062             pmbdThis = (PMBD) pvnmbThis->data.ptrvalue;
1063             pirbNew = InterResidueBondNew();
1064             if (!pirbNew) goto allocerr;
1065             if  (bFirstIRB)
1066               {
1067                   pmgNew->inter_residue_bonds = pirbNew;
1068                   pirbLast = pirbNew;
1069                   bFirstIRB = FALSE;
1070               }
1071             else
1072               {
1073                   pirbLast->next = pirbNew;
1074                   pirbLast = pirbNew;
1075               }
1076             /* fill in pirbNew's atom_id_1, atom_id_2, bond_order */
1077             pirbNew->atom_id_1 = AtomPntrNew();
1078             if (! pirbNew->atom_id_1) goto allocerr;
1079             pirbNew->atom_id_2 = AtomPntrNew();
1080             if (! pirbNew->atom_id_2) goto allocerr;
1081             
1082             pirbNew->atom_id_1->molecule_id = IndexFromNode((PFB)pmmdThis);
1083             pirbNew->atom_id_1->residue_id = IndexFromNode((PFB)GetParentGraph((PFB)pmbdThis->pmadFrom));
1084             pirbNew->atom_id_1->atom_id = IndexFromNode((PFB)pmbdThis->pmadFrom);
1085             
1086             pirbNew->atom_id_2->molecule_id = IndexFromNode((PFB)pmmdThis);
1087             pirbNew->atom_id_2->residue_id = IndexFromNode((PFB)GetParentGraph((PFB)pmbdThis->pmadTo));
1088             pirbNew->atom_id_2->atom_id = IndexFromNode((PFB)pmbdThis->pmadTo);
1089             
1090             pirbNew->bond_order = pvnmbThis->choice;  /* bond order held here */
1091             
1092             pvnmbThis = pvnmbThis->next;
1093           }  /* inter-residue bonds */          
1094         
1095         pdnmmThis = pdnmmThis->next;
1096       }  /* molecule */
1097          
1098    /* rebuild inter_molecule_bonds */   
1099         
1100    pvnmbThis = pmsdThis->pvnmbIMBHead;
1101    bFirstIRB = TRUE;
1102    while(pvnmbThis)
1103       {
1104         pmbdThis = (PMBD) pvnmbThis->data.ptrvalue;
1105         pirbNew = InterResidueBondNew();
1106         if (!pirbNew) goto allocerr;
1107         if  (bFirstIRB)
1108           {
1109             pmsdThis->pbsBS->chemical_graph->inter_molecule_bonds = pirbNew;
1110             pirbLast = pirbNew;
1111             bFirstIRB = FALSE;
1112           }
1113         else
1114           {
1115             pirbLast->next = pirbNew;
1116             pirbLast = pirbNew;
1117           }
1118         /* fill in pirbNew's atom_id_1, atom_id_2, bond_order */
1119         pirbNew->atom_id_1 = AtomPntrNew();
1120         if (! pirbNew->atom_id_1) goto allocerr;
1121         pirbNew->atom_id_2 = AtomPntrNew();
1122         if (! pirbNew->atom_id_2) goto allocerr;
1123         
1124         pirbNew->atom_id_1->molecule_id = IndexFromNode((PFB)GetParentMol((PFB)pmbdThis->pmadFrom));
1125         pirbNew->atom_id_1->residue_id = IndexFromNode((PFB)GetParentGraph((PFB)pmbdThis->pmadFrom));
1126         pirbNew->atom_id_1->atom_id = IndexFromNode((PFB)pmbdThis->pmadFrom);
1127         
1128         pirbNew->atom_id_2->molecule_id = IndexFromNode((PFB)GetParentMol((PFB)pmbdThis->pmadTo));
1129         pirbNew->atom_id_2->residue_id = IndexFromNode((PFB)GetParentGraph((PFB)pmbdThis->pmadTo));
1130         pirbNew->atom_id_2->atom_id = IndexFromNode((PFB)pmbdThis->pmadTo);
1131         
1132         pirbNew->bond_order = pvnmbThis->choice;  /* bond order held here */
1133         
1134         pvnmbThis = pvnmbThis->next;
1135     }  /* inter-molecule bonds */        
1136   
1137    
1138    if (pmsdThis->pbsBS->chemical_graph) return TRUE;
1139 
1140   allocerr: 
1141     /* Recoverable out of memory error */
1142       /* clear all ASN data out - must start save process from scratch */
1143     FreeRedundantAsn(pdnmsThis);
1144     ErrClear(); 
1145     ErrPostEx(SEV_ERROR,0,0, "Out of memory while trying to save.\n Try again after closing other windows/programs.");
1146     ErrShow();
1147     return FALSE;
1148   
1149 }
1150 
1151 
1152 
1153 
1154 Boolean LIBCALL WriteOutBiostruc(BiostrucPtr pbsThis, CharPtr pcSave,  Byte bSave)
1155 {   
1156 
1157     AsnIoPtr paioAIP = NULL;
1158     Boolean bWriteOK = FALSE;
1159     CharPtr pcSaveMode = NULL;
1160     BiostrucFeatureSetPtr pfsThis = NULL; 
1161 
1162     if (!pcSave) return FALSE;
1163     if (!pbsThis) return FALSE;    
1164     if (bSave & (Byte) SAVE_BINARY) pcSaveMode = SAVE_BINARY_STRING; 
1165     else pcSaveMode = SAVE_ASCII_STRING;  
1166   
1167     if (bSave & (Byte) NOT_FEATURES)
1168       {
1169         pfsThis = pbsThis->features;
1170         pbsThis->features = NULL;
1171       } /* unlink features */
1172    
1173     paioAIP = AsnIoOpen(pcSave, pcSaveMode);  
1174     bWriteOK = BiostrucAsnWrite(pbsThis, paioAIP, NULL);
1175     AsnIoClose (paioAIP); 
1176    
1177     if (bSave & (Byte) NOT_FEATURES)
1178      {
1179        pbsThis->features = pfsThis;
1180      } /* re-link features */
1181         
1182     return bWriteOK;
1183 }
1184 
1185 
1186 Boolean LIBCALL WriteASNChemGraphOnly(PDNMS pdnmsThis, CharPtr pcSave,  Byte bSave)
1187 {
1188     /* writes out chemical graph only - models are not destroyed */
1189     AsnIoPtr paioAIP = NULL;
1190     Boolean bWriteOK = FALSE;
1191     CharPtr pcSaveMode = NULL;
1192     Int4 iHash = 0;
1193     BiostrucFeatureSetPtr pfsThis = NULL; 
1194     BiostrucModelPtr pbsmThis = NULL;
1195     PMSD pmsdThis = NULL;
1196     
1197     if (!pdnmsThis) return FALSE;
1198     pmsdThis = (PMSD) pdnmsThis->data.ptrvalue;
1199       
1200    if (RebuildChemGraphAsn(pdnmsThis) == FALSE)
1201      {
1202         bWriteOK = FALSE;
1203         goto seeyalater;
1204      }
1205 #ifdef _DEBUG_5
1206 printf("Chem Graph rebuilt \n");
1207 #endif  
1208     
1209     if (bSave & (Byte) SAVE_BINARY) pcSaveMode = SAVE_BINARY_STRING; 
1210     else pcSaveMode = SAVE_ASCII_STRING;  
1211       
1212     if (bSave & (Byte) NOT_FEATURES)
1213       {
1214         pfsThis = pmsdThis->pbsBS->features;
1215         pmsdThis->pbsBS->features = NULL;
1216       } /* unlink features */
1217    
1218    
1219     pbsmThis = pmsdThis->pbsBS->model;
1220     pmsdThis->pbsBS->model = NULL;  
1221     /* unlink models */
1222    
1223     paioAIP = AsnIoOpen(pcSave, pcSaveMode);  
1224     bWriteOK = BiostrucAsnWrite(pmsdThis->pbsBS, paioAIP, NULL);
1225     AsnIoClose (paioAIP); 
1226    
1227     if (bSave & (Byte) NOT_FEATURES)
1228      {
1229        pmsdThis->pbsBS->features = pfsThis;
1230      } /* re-link features */
1231    
1232    
1233     pmsdThis->pbsBS->model = pbsmThis;
1234     /* relink models */
1235   seeyalater:    
1236     FreeRedundantAsn(pdnmsThis);
1237     /* remove the chem graph */
1238    
1239     return bWriteOK;
1240     
1241 }
1242 
1243 
1244 
1245 
1246 Boolean LIBCALL WriteAsnLocalDict(PDNMS pdnmsThis, CharPtr pcSave,  Byte bSave,   Boolean SaveId)
1247 {
1248     CharPtr pcSaveMode = NULL;
1249     BiostrucResidueGraphSetPtr pbrgsDict = NULL;
1250     PMSD pmsdThis = NULL;
1251     AsnIoPtr paioAIP = NULL;
1252     Boolean bRet;
1253     
1254     if (bSave & (Byte) SAVE_BINARY) pcSaveMode = SAVE_BINARY_STRING; 
1255     else pcSaveMode = SAVE_ASCII_STRING;  
1256             
1257     pmsdThis = (PMSD) pdnmsThis->data.ptrvalue;
1258     if (pmsdThis->bMe == (Byte) AM_MSD)
1259         if (pmsdThis->pDictLocal)
1260             {
1261               pbrgsDict =  BiostrucResidueGraphSetNew();
1262               if (!pbrgsDict) return FALSE;
1263               pbrgsDict->residue_graphs = pmsdThis->pDictLocal; /* attach dict */
1264               if (SaveId) pbrgsDict->id = pmsdThis->pbsBS->id;  /* point at id */
1265               paioAIP = AsnIoOpen(pcSave, pcSaveMode); 
1266               bRet = BiostrucResidueGraphSetAsnWrite(pbrgsDict, paioAIP, NULL);
1267               AsnIoClose(paioAIP);
1268               pbrgsDict->residue_graphs = NULL;  /* detach dict */
1269               pbrgsDict->id = NULL; /* detach id */
1270               BiostrucResidueGraphSetFree(pbrgsDict);
1271               return bRet;
1272             }
1273     return FALSE;       
1274 }
1275 
1276 
1277 static void LIBCALLBACK FreeModelChemGraphLoc(PFB pfbThis, Int4 iModel, Int4 iIndex, Pointer ptr)
1278 {   /* callback for FreeSingleModel - frees the model-specific data from a chem-graph node */
1279  
1280    PMAD pmadThis = NULL;
1281    PALD paldThis = NULL;
1282    PMGD pmgdThis = NULL;
1283    PMMD pmmdThis = NULL;
1284    PVNAL pvnalThis = NULL;
1285    ValNodePtr *ppvn  = NULL;
1286    ValNodePtr pvnKillList = NULL;
1287 
1288    
1289    if (pfbThis->bMe == (Byte) AM_MAD)
1290      {  /* iIndex & ptr not used */
1291         pmadThis = (PMAD) pfbThis;
1292         /* look up the cointainedBy list for model ocurrences */
1293         paldThis = GetAtomLocs(pmadThis, iModel); 
1294         if (paldThis) 
1295           {
1296             pvnalThis = paldThis->pvnalLink;
1297             FreeALD(paldThis);
1298             pvnalThis->data.ptrvalue = NULL;
1299             pvnalThis = ValNodeExtract(&pmadThis->pvnalLocate, iModel); 
1300             if (pvnalThis) ValNodeFree(pvnalThis);
1301           }
1302         ppvn = &pmadThis->pvnContainedBy;
1303      }  
1304      
1305    if (pfbThis->bMe == (Byte) AM_MGD)
1306         
1307      {
1308          /* kill the pvnContainedBy entries for this model in choice field */
1309          pmgdThis = (PMGD) pfbThis;
1310          ppvn = &pmgdThis->pvnContainedBy;
1311      }
1312  
1313    if (pfbThis->bMe == (Byte) AM_MMD)
1314      {
1315          /* kill the pvnContainedBy entries for this model in choice field */
1316          pmmdThis = (PMMD) pfbThis;
1317          ppvn = &pmmdThis->pvnContainedBy;
1318      }
1319    if (!ppvn) return;  
1320    pvnKillList = ValNodeExtractList(ppvn, iModel);
1321    if (pvnKillList) ValNodeFree(pvnKillList);  
1322   
1323 }
1324 
1325 Boolean LIBCALL FreeSingleModel(PDNMS pdnmsThis, Int2 iModel)
1326 {
1327     PMLD pmldThis = NULL;
1328     PMLD pmldTemp = NULL;
1329     PMSD pmsdThis = NULL;
1330     PDNML pdnmlThis = NULL;
1331     PDNML pdnmlTemp = NULL;
1332     BiostrucModelPtr pbsmTemp = NULL;
1333     BiostrucModelPtr pbsmLast = NULL;
1334     BiostrucModelPtr pbsmHead = NULL;
1335     ValNodePtr pvn = NULL;
1336     PDNML pdnml = NULL;
1337     
1338     if (!pdnmsThis) return FALSE;
1339     pmsdThis = (PMSD) pdnmsThis->data.ptrvalue;
1340     
1341   
1342    pdnmlTemp = pmsdThis->pdnmlModels;
1343    while(pdnmlTemp)
1344      {
1345         if (pdnmlTemp->choice == iModel) 
1346             break;
1347         pdnmlTemp = pdnmlTemp->next;
1348      }
1349      
1350    if (!pdnmlTemp) 
1351      {
1352 #ifdef _DEBUG_5
1353 printf("Cannot find iModel %d to delete it\n",(int) iModel);
1354 #endif  
1355        return FALSE;
1356      }
1357    
1358    pdnmlThis = pdnmlTemp;
1359    pmldThis = (PMLD) pdnmlThis->data.ptrvalue;
1360     
1361         /* call a traverser callback which removes the model's pvnal lists */
1362         /* and pvnContainedBy instances from MMD, MGD and MAD. */
1363 #ifdef _DEBUG_5
1364 printf("Calling Traverser iModel %d\n",(int) iModel);
1365 #endif  
1366 
1367     TraverseOneModel(pdnmsThis, TRAVERSE_ALL, 
1368                         iModel, 0,   NULL, (pNodeFunc)FreeModelChemGraphLoc);
1369 
1370        /* unlink all the models' ASN.1 portions */
1371 #ifdef _DEBUG_5
1372 printf("Traverser Done\n");
1373 #endif  
1374        
1375     pdnmlTemp =  pmsdThis->pdnmlModels;
1376     while (pdnmlTemp)  
1377       { 
1378          pmldTemp = (PMLD) pdnmlTemp->data.ptrvalue;
1379          if (pmldTemp->pbsmModel)
1380             pmldTemp->pbsmModel->next = NULL;  /* unlinked */      
1381          else
1382            {
1383             ErrClear(); 
1384             ErrPostEx(SEV_ERROR,0,0, "Model Lacks ASN.1 Stub\n pmldTemp->pbsmModel");
1385             ErrShow();
1386             return FALSE;
1387            }
1388          pdnmlTemp = pdnmlTemp->next;
1389       } 
1390       
1391         /* free the Biostruc model stub off first node's pdnmlThis>>pmldThis->pbsmModel */
1392         /* these are now all detached from each other and can be deleted */
1393         /*   without causing a chain reaction */
1394 #ifdef _DEBUG_5
1395 printf("Freeing Biostruc Models\n");
1396 #endif  
1397 
1398     if (pmldThis->pbsmModel) BiostrucModelFree(pmldThis->pbsmModel);
1399     pmldThis->pbsmModel = NULL;         
1400    
1401          /* extract the MOD's and MDD's from the lists off of pmsdThis and free them */
1402     pvn = ValNodeExtractList(&pmsdThis->pvnmoHead, iModel);
1403     if (pvn) FreeListVNMO((PVNMO) pvn);
1404     pmsdThis->iObjCount = 0;
1405     pvn = pmsdThis->pvnmoHead;
1406     while (pvn)
1407       {
1408           (pmsdThis->iObjCount)++;
1409           pvn = pvn->next;
1410       }
1411     
1412     pvn = NULL;
1413     pvn = ValNodeExtractList(&pmsdThis->pvnmdHead, iModel);
1414     if (pvn) FreeListVNMD((PVNMD) pvn);
1415     pmsdThis->iDensCount = 0;
1416     pvn = pmsdThis->pvnmdHead;
1417     while (pvn)
1418       {
1419           (pmsdThis->iDensCount)++;
1420           pvn = pvn->next;
1421       }
1422  
1423    /* free the chain of mld's off of pdnmlThis */
1424   
1425   
1426         /* unhook the structure model node to delete */
1427 #ifdef _DEBUG_5 
1428         pdnml  = pmsdThis->pdnmlModels;
1429          while (pdnml )
1430           {
1431             printf("Before found model %d\n", (int) pdnml->choice);
1432             pdnml = pdnml->next;
1433           }
1434 #endif      
1435 
1436     pdnmlThis = DValNodeExtract(&pmsdThis->pdnmlModels, iModel);
1437 
1438 #ifdef _DEBUG_5 
1439         pdnml  = pmsdThis->pdnmlModels;
1440          while (pdnml )
1441           {
1442             printf(" After Unlink - found model %d\n", (int) pdnml->choice);
1443             pdnml = pdnml->next;
1444           }
1445 #endif    
1446   
1447 #ifdef _DEBUG_5
1448 printf("Freeing MLD's\n");
1449 #endif  
1450 
1451    if (pdnmlThis) FreeListDNML(pdnmlThis);
1452 
1453 #ifdef _DEBUG_5
1454 printf("MLDs freed\n");
1455 #endif      
1456 
1457  
1458 #ifdef _DEBUG_5
1459 printf("Re-linking pbsmModels\n");
1460 #endif  
1461 
1462         /* re-link the remaining list of pbsmModel's... */
1463         
1464     pdnmlTemp = pmsdThis->pdnmlModels;
1465     while (pdnmlTemp)  /* link the model list ASN.1 portions */
1466       { 
1467          pmldThis = (PMLD) pdnmlTemp->data.ptrvalue;
1468          if (!pbsmHead) pbsmHead = pmldThis->pbsmModel; /* sets the first one */
1469          if (pbsmLast) pbsmLast->next = pmldThis->pbsmModel; /* point to this one */
1470          
1471          pbsmLast = pmldThis->pbsmModel;
1472          pdnmlTemp = pdnmlTemp->next;
1473       } 
1474    pmsdThis->pbsBS->model = pbsmHead;  /* reset the Biostruc main model pointer to new list */
1475    pmsdThis->iModels--;
1476    return TRUE;
1477 }
1478 
1479 
1480 
1481 Boolean LIBCALL WriteAsnModelList(PDNMS pdnmsThis,   Int2 iNumModels,  Int2Ptr i2Vec,  
1482                                     CharPtr pcSave,  Byte bSave, Boolean iCn3d)
1483 {
1484     /* The master ASN.1 writer routine */
1485     /* MODELS not specified for writing are ERASED for congruency */
1486     /* the User-interface needs to notify the user of this if some models are not saved */
1487     /* takes a vector containing model numbers as input */
1488     /* one can save any arbitrary collection of models */
1489     /* or one can save no models - just features, or dictionaries */
1490     /* use bSave Byte to  pick binary/ascii modes */
1491    
1492     Int2 iIndex = 0;
1493     Int2 iTest = 0;
1494     Boolean bFirst = TRUE;
1495     BiostrucPtr pBSThis = NULL;
1496     BiostrucModelPtr pbsmThis = NULL;
1497     PMSD pmsdThis = NULL;
1498     PDNML pdnmlThis = NULL;
1499     ValNodePtr pvnDelList = NULL;
1500     ValNodePtr pvnDelTemp = NULL;
1501     PDNML pdnmlTemp = NULL;
1502     PMLD  pmldThis = NULL;
1503     Boolean bRet;
1504     ValNodePtr pvn = NULL;  
1505     AsnIoPtr paioAIP = NULL;
1506     Int4 iHash = 0;
1507     Boolean bFound;
1508    
1509  
1510  /*FIRST-PASS VALIDATION*/
1511     
1512     pmsdThis = (PMSD) pdnmsThis->data.ptrvalue;
1513     if (!(pmsdThis->bMe == (Byte) AM_MSD)) return FALSE;
1514     /* A pbsBS must exist or be created! */
1515     if (!(pmsdThis->pbsBS))
1516       {
1517           ErrClear(); 
1518           ErrPostEx(SEV_ERROR,0,0, "Modelstruc Lacks Biostruc ASN.1 Stub\n pmsdThis->pbsBS");
1519           ErrShow();
1520           return FALSE;
1521       } 
1522    
1523   
1524     
1525  /*CHEMICAL-GRAPH*/
1526     
1527     if (RebuildChemGraphAsn(pdnmsThis) == FALSE)
1528       {
1529         bRet = FALSE;
1530 #ifdef _DEBUG_5
1531 printf("Chem Graph rebuild failed \n");
1532 #endif
1533         goto outofhere;
1534       } 
1535     
1536 #ifdef _DEBUG_5 
1537 printf("Chem Graph rebuilt \n");
1538 #endif    
1539     
1540 
1541 
1542 /*MODELS*/   
1543       
1544   
1545     /* walk through models, free the ones not on the list (ALD, MLD, and ASN stubs) */
1546     pdnmlTemp = pmsdThis->pdnmlModels;
1547  
1548     while(pdnmlTemp)
1549       {
1550           bFound = FALSE;
1551           for (iIndex = 0; iIndex < iNumModels; iIndex++)
1552              {
1553                  if ((Int2)pdnmlTemp->choice == i2Vec[iIndex])
1554                    {
1555                      bFound = TRUE;
1556                    }  
1557              }
1558           if (!bFound) pvnDelTemp = ValNodeAddPointer(&pvnDelTemp, 0, (VoidPtr) pdnmlTemp); 
1559           if (!pvnDelList) pvnDelList = pvnDelTemp;  /* set the head pointer */
1560           pdnmlTemp = pdnmlTemp->next;  
1561       }
1562     
1563     pvnDelTemp = pvnDelList;
1564     while(pvnDelTemp)
1565      {
1566         pdnmlTemp = (PDNML) pvnDelTemp->data.ptrvalue;
1567         if (FreeSingleModel(pdnmsThis, (Int2)pdnmlTemp->choice) == FALSE)
1568           {
1569              ErrClear(); 
1570              ErrPostEx(SEV_FATAL,0,0, "Model Not Correctly Freed. Possibly Corrupt Memory Data\n");
1571              ErrShow();
1572              goto outofhere;
1573           }
1574         pvnDelTemp = pvnDelTemp->next; 
1575      }
1576    
1577    if (pvnDelList) ValNodeFree(pvnDelList);
1578    
1579     /* now pmsdThis->pbsBS->model contains only the models for saving */   
1580     for (iIndex = 0; iIndex < iNumModels; iIndex++)
1581        {  
1582         /* for each model, refresh or rebuild its data */
1583 #ifdef _DEBUG_5
1584 printf("Refreshing Model %d\n ", (int) i2Vec[iIndex]);
1585 #endif
1586         
1587          if (RefreshModelAsnMem(pdnmsThis, i2Vec[iIndex]) == FALSE)
1588            {
1589              bRet = FALSE;
1590 #ifdef _DEBUG_5
1591 printf("Refreshing Model failed %d\n ", (int) i2Vec[iIndex]);
1592 #endif   
1593                      goto outofhere;
1594            } 
1595        
1596        }
1597       
1598        
1599     /* it is up to the bSave parameter to specify whether there is a new ID to  */
1600     /* be hashed automatically */
1601  
1602      
1603 
1604     if (bSave & (Byte) NEW_MMDB_ID) 
1605       {
1606         iHash = MakeHashChange(pdnmsThis);
1607         if (iHash != pmsdThis->iHashChange)
1608           { 
1609               pmsdThis->iMMDBid = iHash;
1610               pvn = pmsdThis->pbsBS->id;
1611               pmsdThis->pbsBS->id = NULL;
1612               pmsdThis->pbsBS->id = ValNodeAddInt(&pmsdThis->pbsBS->id, BiostrucId_mmdb_id, iHash);
1613               if (pvn) ValNodeFree(pvn);
1614           }
1615       }
1616      
1617      if(iCn3d){
1618         if(pmsdThis->pbsBS) bRet = TRUE;
1619         return bRet;
1620                /* leave cn3d handle FreeRedundantAsn - yanli */
1621      }
1622 
1623      bRet = WriteOutBiostruc(pmsdThis->pbsBS, pcSave, bSave);
1624 
1625 #ifdef _DEBUG_5
1626 if (!bRet) printf("WriteOutBiostruc Failed\n");
1627 #endif    
1628            
1629   outofhere:
1630      FreeRedundantAsn(pdnmsThis);
1631      
1632      return bRet;
1633    
1634 }
1635 
1636 
1637 Boolean LIBCALL WriteAsnOneModel(PDNMS pdnmsThis,  Int2 iModel,  CharPtr pcSave,  
1638                 Byte bSave)
1639 {
1640    /* call to save a single model */
1641 
1642     Boolean bRet;
1643     PMSD pmsdThis = NULL;
1644     
1645     pmsdThis = (PMSD)  PFBFromDN(pdnmsThis);
1646     if (!(pmsdThis->bMe == (Byte) AM_MSD)) return FALSE;
1647    
1648     bRet = WriteAsnModelList(pdnmsThis,  1, (Int2Ptr) &iModel, 
1649                                 pcSave, bSave, 0);
1650     return bRet;
1651 }
1652 
1653 Boolean LIBCALL WriteAsnAllModel(PDNMS pdnmsThis,  CharPtr pcSave,  Byte bSave)
1654 {
1655 
1656     Int2Ptr i2Vec = NULL;
1657     PDNML pdnmlThis = NULL;
1658     PMSD pmsdThis = NULL;
1659     PMLD pmldThis = NULL;
1660     Int2 iCount = 0;
1661     Boolean bRet = FALSE;
1662  
1663     pmsdThis = (PMSD) pdnmsThis->data.ptrvalue;
1664     if (!(pmsdThis->bMe == (Byte) AM_MSD)) return FALSE;
1665     
1666     pdnmlThis = pmsdThis->pdnmlModels; /* the linked-list of models */
1667     if (pdnmlThis)
1668       while (pdnmlThis)
1669        {
1670          pmldThis = (PMLD) pdnmlThis->data.ptrvalue;
1671          if (pmldThis)
1672            {
1673                 iCount++;
1674            } 
1675          pdnmlThis = pdnmlThis->next;
1676        }
1677     else return bRet;  /* no models */
1678     i2Vec = I2Vector(0, iCount);  /* allocate vector */
1679     if (!i2Vec) return bRet; 
1680     iCount = 0;
1681     pdnmlThis = pmsdThis->pdnmlModels;
1682     while (pdnmlThis)
1683         {  /* copy the model id's into the vector */
1684           pmldThis = (PMLD) pdnmlThis->data.ptrvalue;
1685           if (pmldThis)
1686            {
1687              i2Vec[iCount] = pdnmlThis->choice;
1688              iCount++;
1689            }
1690           pdnmlThis = pdnmlThis->next;
1691         }
1692     bRet = WriteAsnModelList(pdnmsThis, iCount, i2Vec, pcSave, bSave, 0);
1693     if (i2Vec) I2VectorFree(i2Vec, 0);  /* free vector */
1694     return bRet;          
1695 }
1696 
1697 
1698 
1699 
1700 SeqIdPtr MakePDBSeqId2 (CharPtr pcPDB, Char cChain, int iDomain, Boolean getgi)
1701 {
1702   SeqIdPtr        sip;
1703   PDBSeqIdPtr     psip;
1704   Int4 gi;
1705 
1706   psip = PDBSeqIdNew ();
1707 
1708   psip->chain = cChain;
1709   psip->rel = NULL;
1710   psip->mol = StringSave (pcPDB);
1711   sip = ValNodeNew (NULL);
1712   sip->choice = SEQID_PDB;
1713   sip->data.ptrvalue = psip;
1714 
1715   if (getgi)
1716   {
1717     if ((gi = GetGIForSeqId (sip)) > 0) {
1718       SeqIdFree (sip);
1719       sip = ValNodeNew (NULL);
1720       sip->choice = SEQID_GI;
1721       sip->data.intvalue = gi;
1722     }
1723   }
1724 
1725   return sip;
1726 }
1727 
1728 /* produce a sequence alignment from a structure-alignment */
1729 SeqAnnotPtr LIBCALL BiostrucAnnotSetToSeqAnnot (BiostrucAnnotSetPtr set, Boolean usePValue)
1730 {
1731   SeqAnnotPtr     sap = NULL;
1732   SeqAlignPtr     salp;
1733   ScorePtr        scp;
1734   Int2 count;
1735   ObjectIdPtr     oid;
1736   DenseSegPtr     dsp;
1737   SeqIdPtr        mastersip = NULL, slavesip;
1738   SeqIdPtr        pdbsip = NULL;
1739   BiostrucFeaturePtr feature;
1740   ChemGraphAlignmentPtr pcga1 = NULL;
1741   ValNodePtr      loc1 = NULL;
1742   ValNodePtr      vnp = NULL;
1743   SeqAlignPtr     tail = NULL;
1744   ChemGraphPntrsPtr cgpp;
1745   ResidueIntervalPntrPtr master;
1746   ResidueIntervalPntrPtr slave;
1747   ResidueIntervalPntrPtr masterseg;
1748   ResidueIntervalPntrPtr slaveseg;
1749   CharPtr         pcPDB;
1750   int             iDomain;
1751   ValNodePtr      pvn;
1752   Char            cChain;
1753   Char            buf[100];
1754   Char            buf2[50];
1755   Int4 nextmasterstart, nextslavestart;
1756 
1757 
1758   if (set == NULL || set->features == NULL || set->features->features == NULL)
1759     return NULL;
1760 
1761   for (feature = set->features->features; feature != NULL; feature = feature->next) {
1762 
1763     /* construct the master SeqId if it hasn't already been constructed */
1764     if (mastersip == NULL) {
1765       pcPDB = StringSave (PDBNAME_DEFAULT);
1766       iDomain = 0;
1767       cChain = '-';
1768       pcPDB[0] = feature->name[0];
1769       pcPDB[1] = feature->name[1];
1770       pcPDB[2] = feature->name[2];
1771       pcPDB[3] = feature->name[3];
1772       cChain = feature->name[4];
1773       iDomain = atoi ((char *) &feature->name[5]);
1774       mastersip = MakePDBSeqId2 (pcPDB, cChain, iDomain, TRUE);
1775       pdbsip = MakePDBSeqId2 (pcPDB, cChain, iDomain, FALSE);
1776       MemFree (pcPDB);
1777     }
1778     /* get the embedded PDB code of the hit */
1779     pcPDB = StringSave (PDBNAME_DEFAULT);
1780     iDomain = 0;
1781     cChain = '-';
1782 
1783     if (StringLen (feature->name) >= 13) {
1784       pcPDB[0] = feature->name[7];
1785       pcPDB[1] = feature->name[8];
1786       pcPDB[2] = feature->name[9];
1787       pcPDB[3] = feature->name[10];
1788       cChain = feature->name[11];
1789       iDomain = atoi ((char *) &feature->name[12]);
1790       slavesip = MakePDBSeqId2 (pcPDB, cChain, iDomain, TRUE);
1791       MemFree (pcPDB);
1792     }
1793     pvn = ValNodeFindNext (feature->Location_location, NULL, Location_location_alignment);
1794     if (pvn)
1795       pcga1 = (ChemGraphAlignmentPtr) pvn->data.ptrvalue;
1796 
1797     vnp = pcga1->alignment;
1798 
1799     if (vnp->choice != ChemGraphPntrs_residues)
1800       continue;
1801 
1802     cgpp = (ChemGraphPntrsPtr) vnp->data.ptrvalue;
1803 
1804     if (cgpp->choice != ResiduePntrs_interval)
1805       continue;
1806     master = (ResidueIntervalPntrPtr) cgpp->data.ptrvalue;
1807     cgpp = (ChemGraphPntrsPtr) vnp->next->data.ptrvalue;
1808     slave = (ResidueIntervalPntrPtr) cgpp->data.ptrvalue;
1809     
1810     for (nextmasterstart = 1, nextslavestart = 1, count = 0, masterseg = master, slaveseg = slave; masterseg != NULL && slaveseg != NULL; masterseg = masterseg->next, slaveseg = slaveseg->next) {
1811       if (count > 0 && nextmasterstart < masterseg->from)
1812           count++;
1813       if (count > 0 && nextslavestart < slaveseg->from)
1814           count++;
1815       count++;
1816       nextmasterstart = masterseg->to + 1;
1817       nextslavestart = slaveseg->to + 1;
1818     }
1819 
1820     salp = SeqAlignNew ();
1821     if (sap == NULL) {
1822       sap = SeqAnnotNew ();
1823       sap->type = 2;            /* align */
1824       sap->data = salp;
1825       sap->desc = ValNodeNew(NULL);
1826       sap->desc->choice = 2; /* title */
1827       SeqIdWrite (pdbsip, buf2, PRINTID_FASTA_LONG, sizeof(buf2));
1828       sprintf (buf, "VAST structural alignment for %s, mapped to sequence alignment", buf2);
1829       sap->desc->data.ptrvalue = StringSave(buf);
1830     } else {
1831       tail->next = salp;
1832     }
1833     tail = salp;
1834     salp->type = 3 /* partial */ ;
1835     salp->dim = 2;
1836 
1837     scp = ScoreNew ();
1838     salp->score = scp;
1839     salp->segtype = 2 /* denseg */ ;
1840     scp->choice = 2;            /* real */
1841     scp->value.realvalue = ((FloatHi) pcga1->aligndata->vast_score) / pcga1->aligndata->scale_factor;
1842     oid = ObjectIdNew ();
1843     scp->id = oid;
1844     oid->str = StringSave ("VAST score");
1845     scp->next = ScoreNew ();
1846     scp = scp->next;
1847     scp->choice = 2;            /* real */
1848     scp->value.realvalue = ((FloatHi) pcga1->aligndata->vast_mlogp) / pcga1->aligndata->scale_factor;
1849     oid = ObjectIdNew ();
1850     scp->id = oid;
1851     oid->str = StringSave ("VAST p-value");
1852     scp->next = ScoreNew ();
1853     scp = scp->next;
1854     scp->choice = 2;            /* real */
1855     scp->value.realvalue = ((FloatHi) pcga1->aligndata->rmsd) / pcga1->aligndata->scale_factor;
1856     oid = ObjectIdNew ();
1857     scp->id = oid;
1858     oid->str = StringSave ("VAST root mean square deviation, measured in angstroms");
1859     scp->next = ScoreNew ();
1860     scp = scp->next;
1861     scp->choice = 1;            /* int */
1862     scp->value.intvalue = pcga1->aligndata->align_res;
1863     oid = ObjectIdNew ();
1864     scp->id = oid;
1865     oid->str = StringSave ("VAST aligned residue count");
1866 
1867     dsp = DenseSegNew ();
1868     salp->segs = (Pointer) dsp;
1869     dsp->dim = 2;
1870     dsp->numseg = count;
1871     dsp->ids = SeqIdDup (mastersip);
1872     dsp->ids->next = slavesip;
1873     dsp->starts = (Int4Ptr) MemNew (count * sizeof (Int4) * 2);
1874     dsp->lens = (Int4Ptr) MemNew (count * sizeof (Int4));
1875 
1876     for (nextmasterstart = 1, nextslavestart = 1, count = 0, masterseg = master, slaveseg = slave; masterseg != NULL && slaveseg != NULL; masterseg = masterseg->next, slaveseg = slaveseg->next) {
1877       if (count > 0 && nextmasterstart < masterseg->from)
1878       { /* add a gap */
1879         dsp->starts[count * 2] = nextmasterstart - 1;
1880         dsp->starts[count * 2 + 1] = -1;
1881         dsp->lens[count] = masterseg->from - nextmasterstart;
1882         count++;
1883       }
1884       if (count > 0 && nextslavestart < slaveseg->from)
1885       { /* add a gap */
1886         dsp->starts[count * 2 + 1] = nextslavestart - 1;
1887         dsp->starts[count * 2] = -1;
1888         dsp->lens[count] = slaveseg->from - nextslavestart;
1889         count++;
1890       }
1891       dsp->starts[count * 2] = masterseg->from-1;
1892       dsp->starts[count * 2 + 1] = slaveseg->from-1;
1893       dsp->lens[count] = masterseg->to - masterseg->from + 1;
1894       count++;
1895       nextmasterstart = masterseg->to + 1;
1896       nextslavestart = slaveseg->to + 1;
1897     }
1898 
1899   }
1900 
1901   SeqIdFree (mastersip);
1902   SeqIdFree (pdbsip);
1903   return sap;
1904 }
1905 

source navigation ]   [ diff markup ]   [ identifier search ]   [ freetext search ]   [ file search ]  

This page was automatically generated by the LXR engine.
Visit the LXR main site for more information.