File: replace.c

package info (click to toggle)
garlic 1.6-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 4,516 kB
  • sloc: ansic: 52,465; makefile: 2,254
file content (969 lines) | stat: -rw-r--r-- 32,762 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
/* Copyright (C) 2001-2003 Damir Zucic */

/*=============================================================================

				replace.c

Purpose:
	Execute replace command: replace selected residues with template
	residues,  using  the sequence  from the  sequence buffer.  This
	function works only for protein structures.

Input:
	(1) Pointer to MolComplexS structure.
	(2) The number of macromolecular complexes.
	(3) The first free macromolecular complex identifier.
	(4) Pointer to RuntimeS structure.
	(5) Pointer to ConfigS structure.
	(6) Pointer to GUIS structure.
	(7) Pointer to NearestAtomS structure.
	(8) The number of pixels in the main window free area.
	(9) Pointer to refreshI.

Output:
	(1) Selected residues replaced. 
	(2) Return value.

Return value:
	(1) Positive (command) code on success.
	(2) Negative (error) code on failure.

Notes:
	(1) If exiting from this function before it ends,  do not forget
	    to free the storage used for the temporary structure.  It is
	    also important  to reset pointers and counts.  Note that the
	    same  MolComplexS  structure  may be used more than once for
	    the temporary molecular structure.

	(2) Residue indices used in  this function should be of the type
	    int, not size_t.  The type  size_t  may be unsigned so it is
	    not safe for subtraction.

	(3) This function resets the edit mode index.

========includes:============================================================*/

#include <stdio.h>

#include <string.h>
#include <stdlib.h>
#include <math.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>

#include "defines.h"
#include "commands.h"
#include "typedefs.h"

/*======function prototypes:=================================================*/

int		CountRequiredAtoms_ (RuntimeS *, int);
int		CopyTemplateAtoms_ (MolComplexS *, RuntimeS *,
				    ResidueS *, int);
int		ExtractSequence_ (MolComplexS *);
int		ResetPhi_ (MolComplexS *);
int		ResetPsi_ (MolComplexS *);
int		ExtractNCA_ (VectorS *, VectorS *, AtomS *, size_t, size_t);
int		RotateAtom_ (AtomS *, VectorS *, VectorS *, double);
int		ExtractC_ (VectorS *, AtomS *, size_t, size_t);
int		ExtractNCAC_ (VectorS *, VectorS *, VectorS *,
			      AtomS *, size_t, size_t);
int		ExtractN_ (VectorS *, AtomS *, size_t, size_t);
void		TranslateRange_ (AtomS *, size_t, size_t,
				 double, double, double);
void		VectorProduct_ (VectorS *, VectorS *, VectorS *);
double		AbsoluteValue_ (VectorS *);
double		ScalarProduct_ (VectorS *, VectorS *);
void		RotateRange_ (AtomS *, size_t, size_t,
			      VectorS *, VectorS *, double);
int		ParallelPart_ (VectorS *, VectorS *, VectorS *);
int		PrepareStereoData_ (MolComplexS *, ConfigS *);
size_t		StrongBonds_ (MolComplexS *, int, ConfigS *);
size_t		PseudoBonds_ (MolComplexS *, int, ConfigS *);
size_t		DisulfideBonds_ (MolComplexS *, int, ConfigS *);
int		RefreshBackbone_ (MolComplexS *, ConfigS *);
int		AssignRadii_ (MolComplexS *, ConfigS *);
int		AssignHydrophobicity_ (MolComplexS *, int);
int		DihedralAngles_ (MolComplexS *, ConfigS *);
size_t		MainRefresh_ (MolComplexS *, int,
			      RuntimeS *, ConfigS *, GUIS *,
			      NearestAtomS *, size_t, unsigned int);
int		ControlRefresh_ (MolComplexS *, ConfigS *, GUIS *);

/*======execute replace command:=============================================*/

int Replace_ (MolComplexS *mol_complexSP,
	      int mol_complexesN, int next_mol_complexID,
	      RuntimeS *runtimeSP, ConfigS *configSP, GUIS *guiSP,
	      NearestAtomS *nearest_atomSP, size_t pixelsN,
	      unsigned int *refreshIP)
{
int			max_length;
size_t			char_size, atom_struct_size;
MolComplexS		*curr_mol_complexSP;
int			old_atomsN, new_atomsN;
int			total_residuesN, residueI;
int			selected_residuesN = 0, selected_residueI = 0;
ResidueS		*old_residueSP;
AtomS			*old_first_atomSP;
int			residue_recognizedF;
int			template_residuesN, template_residueI;
ResidueS		*template_residueSP;
AtomS			*template_first_atomSP;
char			*curr_template_nameP;
char			bad_residue_nameA[10];
char			*old_residue_nameP, *new_residue_nameP;
double			phi, psi, delta_phi, delta_psi;
int			deleted_atomsN = 0, inserted_atomsN = 0;
size_t			new_memory_size;
static AtomS		*reallocated_atomSP;
int			temporary_mol_complexI;
static MolComplexS	*temporary_mol_complexSP;
int			required_atomsN;
size_t			elementsN;
int			n;
ResidueS		*new_residueSP;
size_t			old_atom_startI, old_atom_endI;
size_t			template_atom_startI, template_atom_endI;
size_t			new_atom_startI, new_atom_endI;
VectorS			old_N_vectorS, old_CA_vectorS, old_C_vectorS;
VectorS			new_N_vectorS, new_CA_vectorS, new_C_vectorS;
int			residue_sequenceI;
int			atomI;
AtomS			*atomSP;
char			*residue_nameP;
char			*atom_nameP;
double			delta_x, delta_y, delta_z;
VectorS			vector1S, vector2S, vector3S;
VectorS			axis_vectorS;
double			denominator, ratio, angle;
VectorS			old_parallel_vectorS, old_perpendicular_vectorS;
VectorS			new_parallel_vectorS, new_perpendicular_vectorS;
AtomS			*new_first_atomSP;
int			current_atomsN;
int			delta_atomsN;
AtomS			*source_atomSP, *dest_atomSP;
int			trailing_atomsN;
size_t			bytesN;
int			atoms_in_new_residue;

/* The maximal residue name length: */
max_length = RESNAMESIZE - 1;

/* Size of some data types: */
char_size = sizeof (char);
atom_struct_size = sizeof (AtomS);

/* Prepare the pointer to default complex: */
curr_mol_complexSP = mol_complexSP + runtimeSP->default_complexI;

/** Number of atoms in a macromolecular complex: **/
old_atomsN = curr_mol_complexSP->atomsN;
if (old_atomsN == 0)
	{
	strcpy (runtimeSP->messageA, "Default structure is empty!");
	runtimeSP->message_length = strlen (runtimeSP->messageA);
	return ERROR_REPLACE;
	}

/* Prepare the total number of residues: */
total_residuesN = curr_mol_complexSP->residuesN;

/* Prepare the number of template residues: */
template_residuesN = runtimeSP->template_residuesN;

/* Check how many residues are selected in default structure. */
/* A residue is treated as selected if the first atom of this */
/* residue is selected.  For proteins, this is usualy N atom. */
for (residueI = 0; residueI < total_residuesN; residueI++)
	{
	/* Pointer to the old residue: */
	old_residueSP = curr_mol_complexSP->residueSP + residueI;

	/* Pointer to the first atom: */
	old_first_atomSP = curr_mol_complexSP->atomSP +
			   old_residueSP->residue_startI;

	/* If the first atom is not selected, do */
	/* not count  this residue  as selected: */
	if (old_first_atomSP->selectedF == 0) continue;

	/* Update the number of selected residues: */
	selected_residuesN++;
	}

/* Compare the number of selected residues with the number of */
/* residues in  the main sequence buffer;  this function will */
/* refuse to replace residues if these numbers are not equal: */
if (selected_residuesN != (int) runtimeSP->residuesN)
	{
	sprintf (runtimeSP->messageA,
		"%d resid. selected but sequence buffer contains %d!",
		selected_residuesN, runtimeSP->residuesN);
	runtimeSP->message_length = strlen (runtimeSP->messageA);
	return ERROR_REPLACE;
	}

/* Check the residues which should be replaced. Garlic will */
/* refuse to replace  nucleic bases and/or hetero residues. */
for (residueI = 0; residueI < total_residuesN; residueI++)
	{
	/* Pointer to the old residue: */
	old_residueSP = curr_mol_complexSP->residueSP + residueI;

	/* Pointer to the first atom: */
	old_first_atomSP = curr_mol_complexSP->atomSP +
			   old_residueSP->residue_startI;

	/* If the first atom is not selected, skip this residue: */
	if (old_first_atomSP->selectedF == 0) continue;

	/* Name of old residue: */
	old_residue_nameP = old_first_atomSP->raw_atomS.pure_residue_nameA;

	/* If the current residue is recognized, this flag will be set to */
	/* one;  if recognition failes,  the value will remain unchanged: */
	residue_recognizedF = 0;

	/* Scan the list of template residues: */
	for (template_residueI = 0;
	     template_residueI < template_residuesN;
	     template_residueI++)
		{
		/* Pointer to the current template residue: */
		template_residueSP = runtimeSP->template_residueSP +
				     template_residueI;

		/* Pointer to  the first atom of */
		/* the current template residue: */
		old_first_atomSP = runtimeSP->template_atomSP +
				   template_residueSP->residue_startI;

		/* Pointer to the current template residue name: */
		curr_template_nameP =
				old_first_atomSP->raw_atomS.pure_residue_nameA;

		/* Compare the current residue name */
		/* with  the template residue name: */
		if (strncmp (old_residue_nameP,
			     curr_template_nameP, max_length) == 0)
			{
			residue_recognizedF = 1;
			break;
			}
		}

	/* If residue recognition failed, the replacement will not work: */
	if (!residue_recognizedF)
		{
		strncpy (bad_residue_nameA, old_residue_nameP, max_length);
		bad_residue_nameA[max_length] = '\0';
		sprintf (runtimeSP->messageA,
			 "Don't know how to replace the residue %s",
			 bad_residue_nameA);
		runtimeSP->message_length = strlen (runtimeSP->messageA);
		return ERROR_REPLACE;
		}
	}

/* Check the sequence in the main sequence buffer: */
for (residueI = 0; residueI < (int) runtimeSP->residuesN; residueI++)
	{
	/* Prepare the pointer to the current residue name: */
	new_residue_nameP = runtimeSP->sequenceP + residueI * max_length;

	/* If the current residue is recognized, this flag will be set to */
	/* one;  if recognition failes,  the value will remain unchanged: */
	residue_recognizedF = 0;

	/* Scan the list of template residues: */
	for (template_residueI = 0;
	     template_residueI < template_residuesN;
	     template_residueI++)
		{
		/* Pointer to the current template residue: */
		template_residueSP = runtimeSP->template_residueSP +
				     template_residueI;

		/* Pointer to  the first atom of */
		/* the current template residue: */
		template_first_atomSP = runtimeSP->template_atomSP +
					template_residueSP->residue_startI;

		/* Pointer to the current template residue name: */
		curr_template_nameP =
			template_first_atomSP->raw_atomS.pure_residue_nameA;

		/* Compare the current residue name */
		/* with  the template residue name: */
		if (strncmp (new_residue_nameP,
			     curr_template_nameP, max_length) == 0)
			{
			residue_recognizedF = 1;
			break;
			}
		}

	/* If residue recognition failed,  the */
	/* atomic structure cannot be created: */
	if (!residue_recognizedF)
		{
		strncpy (bad_residue_nameA, new_residue_nameP, max_length);
		bad_residue_nameA[max_length] = '\0';
		sprintf (runtimeSP->messageA, "Residue not recognized: %s",
			 bad_residue_nameA);
		runtimeSP->message_length = strlen (runtimeSP->messageA);
		return ERROR_REPLACE;
		}
	}

/* Some residues might be replaced by prolines.  Check the */
/* phi angle, because it has a limited range for prolines: */
for (residueI = 0; residueI < total_residuesN; residueI++)
	{
	/* Pointer to the old residue: */
	old_residueSP = curr_mol_complexSP->residueSP + residueI;

	/* Pointer to the first atom: */
	old_first_atomSP = curr_mol_complexSP->atomSP +
			   old_residueSP->residue_startI;

	/* If the first atom is not selected, skip this residue: */
	if (old_first_atomSP->selectedF == 0) continue;

	/* Name of the old residue: */
	old_residue_nameP = old_first_atomSP->raw_atomS.pure_residue_nameA;

	/* Name of the new residue: */
	new_residue_nameP = runtimeSP->sequenceP +
			    selected_residueI * max_length;

	/* If new residue is proline, check what was the old one: */
	do
		{
		/* Is new residue proline? */
		if (strncmp (new_residue_nameP, "PRO", max_length) != 0)
			{
			break;
			}

		/* Is old residue proline? */
		if (strcmp (old_residue_nameP, "PRO") == 0) break;

		/* If this point is reached the new residue is */
		/* proline and  the old one is something else. */

		/* Check the old phi angle: it should be in the */
		/* range between -90 degrees and -40 degrees if */
		/* replacing  non-proline  residue by  proline: */
		phi = old_residueSP->phi;
		if ((phi >= -1.5707963) && (phi <= -0.6981317)) break;

		/* If this point is reached, garlic will not be */
		/* able to replace  the old residue by proline: */
		sprintf (runtimeSP->messageA,
			"Unable to replace %s %d by proline!",
			old_residue_nameP,
			old_first_atomSP->raw_atomS.residue_sequenceI);
		runtimeSP->message_length = strlen (runtimeSP->messageA);
		return ERROR_REPLACE;

		/* End of single-pass loop: */
		} while (0);

	/* Update index: */
	selected_residueI++;
        }

/* Count the number of atoms which should be deleted: */
for (residueI = 0; residueI < total_residuesN; residueI++)
	{
	/* Pointer to the old residue: */
	old_residueSP = curr_mol_complexSP->residueSP + residueI;

	/* The start index and the end index of the old residue: */
	old_atom_startI = old_residueSP->residue_startI;
	old_atom_endI   = old_residueSP->residue_endI;

	/* Pointer to the first atom: */
	old_first_atomSP = curr_mol_complexSP->atomSP + old_atom_startI;

	/* If the first atom is not selected, skip this residue: */
	if (old_first_atomSP->selectedF == 0) continue;

	/* Update the number of atoms which should be deleted: */
	deleted_atomsN += (int) old_atom_endI - (int) old_atom_startI + 1;
	}

/* Count the number of atoms which should be inserted: */
for (residueI = 0; residueI < (int) runtimeSP->residuesN; residueI++)
	{
	/* Prepare the pointer to the current residue name: */
	new_residue_nameP = runtimeSP->sequenceP + residueI * max_length;

	/* Scan the list of template residues: */
	for (template_residueI = 0;
	     template_residueI < template_residuesN;
	     template_residueI++)
		{
		/* Pointer to the current template residue: */
		template_residueSP = runtimeSP->template_residueSP +
				     template_residueI;

		/* The start index and the end index of the new residue: */
		template_atom_startI = template_residueSP->residue_startI;
		template_atom_endI   = template_residueSP->residue_endI;

		/* Pointer to  the first atom of */
		/* the current template residue: */
		template_first_atomSP = runtimeSP->template_atomSP +
					template_atom_startI;

		/* Pointer to the current template residue name: */
		curr_template_nameP =
			template_first_atomSP->raw_atomS.pure_residue_nameA;

		/* Compare the current residue name */
		/* with  the template residue name: */
		if (strncmp (new_residue_nameP,
			     curr_template_nameP, max_length) == 0)
			{
			inserted_atomsN += (int) template_atom_endI -
					   (int) template_atom_startI + 1;
			break;
			}
		}
	}

/* Calculate the number of atoms after the insertion: */
new_atomsN = old_atomsN + inserted_atomsN - deleted_atomsN;

/* Check the available storage and reallocate memory if necessary: */
if (new_atomsN > (int) curr_mol_complexSP->max_atomsN + 100)
	{
	/* Prepare the number of bytes: */
	new_memory_size = new_atomsN * atom_struct_size;

	/* Try to reallocate storage: */
	reallocated_atomSP = realloc (curr_mol_complexSP->atomSP,
				      new_memory_size);

	/* If reallocation fails return the error code. */
	/* The original data  should not  be corrupted. */
	if (!reallocated_atomSP)
		{
		strcpy (runtimeSP->messageA, "Memory reallocation failed!");
                runtimeSP->message_length = strlen (runtimeSP->messageA);
		return ERROR_REPLACE;
		}

	/* If this point is reached,  reallocation was successfull. */
	/* Copy the pointer and update the maximal number of atoms. */
	curr_mol_complexSP->atomSP = reallocated_atomSP;
	curr_mol_complexSP->max_atomsN = new_atomsN;
	}

/* Create  the temporary structure,  to copy the residues */
/* which will replace the selected part of the structure. */
/* Do not allocate storage  for header and backbone data. */

/* Prepare the index of the new structure: */
temporary_mol_complexI = mol_complexesN;

/* Prepare the pointer to the new macromolecular complex: */
temporary_mol_complexSP = mol_complexSP + temporary_mol_complexI;

/* Prepare the identifier for the new macromolecular complex: */
temporary_mol_complexSP->mol_complexID = next_mol_complexID;

/* Count the number of atoms: */
required_atomsN = CountRequiredAtoms_ (runtimeSP, runtimeSP->residuesN);

/* Prepare the maximal number of atoms in the new structure: */
elementsN = required_atomsN + 125;
temporary_mol_complexSP->max_atomsN = elementsN;

/* Allocate the memory for atomic coordinates (add some extra space): */
temporary_mol_complexSP->atomSP =
			(AtomS *) calloc (elementsN, atom_struct_size);
if (temporary_mol_complexSP->atomSP == NULL)
	{
	strcpy (runtimeSP->messageA,
		"Failed to allocate storage for the temporary structure!");
	runtimeSP->message_length = strlen (runtimeSP->messageA);
	return ERROR_REPLACE;
	}

/* Copy the required template residues: */
for (residueI = 0; residueI < (int) runtimeSP->residuesN; residueI++)
	{
	/* The name of the residue which will be inserted: */
	new_residue_nameP = runtimeSP->sequenceP + residueI * max_length;

	/* Scan the list of template residues: */
	for (template_residueI = 0;
	     template_residueI < template_residuesN;
	     template_residueI++)
		{
		/* Pointer to the current template residue: */
		template_residueSP = runtimeSP->template_residueSP +
				     template_residueI;

		/* Pointer to  the first atom of */
		/* the current template residue: */
		template_first_atomSP = runtimeSP->template_atomSP +
					template_residueSP->residue_startI;

		/* Pointer to the current template residue name: */
		curr_template_nameP =
			template_first_atomSP->raw_atomS.pure_residue_nameA;

		/* Compare  the current residue name */
		/* with  the template  residue name; */
		/* if they match, prepare the number */
		/* of atoms and add it to the total. */
		if (strncmp (new_residue_nameP,
			     curr_template_nameP, max_length) == 0)
			{
			/* Copy template atoms: */
			CopyTemplateAtoms_ (temporary_mol_complexSP, runtimeSP,
					    template_residueSP, residueI);
			break;
			}
		}
	}

/* Prepare the sequence (residue) information for the temporary */
/* structure.  Do not forget  to free the storage and  to reset */
/* the pointer  allocated  in the  function  ExtractSequence_ ! */
n = ExtractSequence_ (temporary_mol_complexSP);
if (n < 0)
	{
	strcpy (runtimeSP->messageA,
		"Unable to extract sequence from the temporary structure!");
	runtimeSP->message_length = strlen (runtimeSP->messageA);
	free (temporary_mol_complexSP->atomSP);
	temporary_mol_complexSP->atomSP = NULL;
	temporary_mol_complexSP->atomsN = 0;
	temporary_mol_complexSP->max_atomsN = 0;
	temporary_mol_complexSP->mol_complexID = 0;
	return ERROR_REPLACE;
	}

/* Reset dihedral angles: */
ResetPhi_ (temporary_mol_complexSP);
ResetPsi_ (temporary_mol_complexSP);

/* Set the initial value for selected_residueI: */
selected_residueI = 0;

/* Copy dihedral angles, copy the residue sequence */
/* numbers and  translate and rotate new residues: */
for (residueI = 0; residueI < total_residuesN; residueI++)
	{
	/* Pointer to the old residue: */
	old_residueSP = curr_mol_complexSP->residueSP + residueI;

	/* Pointer to the first atom of the old residue: */
	old_first_atomSP = curr_mol_complexSP->atomSP +
			   old_residueSP->residue_startI;

	/* If the first atom is not selected, skip this residue: */
	if (old_first_atomSP->selectedF == 0) continue;

	/* The start and the end atomic index of the old residue: */
	old_atom_startI = old_residueSP->residue_startI;
	old_atom_endI   = old_residueSP->residue_endI;

	/* Prepare pointer to the new residue: */
	new_residueSP = temporary_mol_complexSP->residueSP + selected_residueI;

	/* Update and check the index used to distinguish selected residues: */
	selected_residueI++;
	if (selected_residueI > selected_residuesN) break;

	/* The start index and the end index of the new residue: */
	new_atom_startI = new_residueSP->residue_startI;
	new_atom_endI   = new_residueSP->residue_endI;

	/*------copy the residue sequence number:----------------------------*/

	residue_sequenceI = old_first_atomSP->raw_atomS.residue_sequenceI;
	for (atomI = (int) new_atom_startI;
	     atomI <= (int) new_atom_endI; atomI++)
		{
		/* Pointer to the current new atom: */
		dest_atomSP = temporary_mol_complexSP->atomSP + atomI;

		/* Copy the residue sequence number: */
		dest_atomSP->raw_atomS.residue_sequenceI = residue_sequenceI;
		}

	/*------copy the phi angle:------------------------------------------*/

	/* The phi angle for the old residue: */
	phi = old_residueSP->phi;

	/* The rotation angle: */
	delta_phi = phi + 3.1415927;

	/* Coordinates of the new N and CA: */
	n = ExtractNCA_ (&new_N_vectorS, &new_CA_vectorS,
			 temporary_mol_complexSP->atomSP,
			 new_atom_startI, new_atom_endI);
	if (n < 2) continue;

	/* Scan the new residue: */
	for (atomI = (int) new_atom_startI;
	     atomI <= (int) new_atom_endI; atomI++)
		{
		/* Pointer to the current atom: */
		atomSP = temporary_mol_complexSP->atomSP + atomI;

		/* Skip proline: */
		residue_nameP = atomSP->raw_atomS.pure_residue_nameA;
		if (strcmp (residue_nameP, "PRO") == 0) continue;

		/* Do not rotate H, N and CA: */
		atom_nameP = atomSP->raw_atomS.pure_atom_nameA;
		if ((strcmp (atom_nameP, "H")  == 0) ||
		    (strcmp (atom_nameP, "N")  == 0) ||
		    (strcmp (atom_nameP, "CA") == 0))
			{
			continue;
			}

		/* Rotate the current atom about N-CA bond: */
		RotateAtom_ (atomSP,
			     &new_N_vectorS, &new_CA_vectorS, delta_phi);
		}

	/*------copy the psi angle:------------------------------------------*/

	/* The psi angle for the old residue: */
	psi = old_residueSP->psi;

	/* The rotation angle: */
	delta_psi = psi - 3.1415927;

	/* Coordinates of the new C: */
	n = ExtractC_ (&new_C_vectorS,
		       temporary_mol_complexSP->atomSP,
		       new_atom_startI, new_atom_endI);
	if (n < 1) continue;

	/* Scan the new residue: */
	for (atomI = (int) new_atom_startI;
	     atomI <= (int) new_atom_endI; atomI++)
		{
		/* Pointer to the current atom: */
		atomSP = temporary_mol_complexSP->atomSP + atomI;

		/* Rotate only the O atom: */
		if (strcmp (atomSP->raw_atomS.pure_atom_nameA, "O") != 0)
			{
			continue;
			}

		/* Rotate O atom about CA-C bond: */
		RotateAtom_ (atomSP,
			     &new_CA_vectorS, &new_C_vectorS, delta_psi);
		}

	/*------translate new residue:---------------------------------------*/

	/* Coordinates of the old N, CA and C: */
	n = ExtractNCAC_ (&old_N_vectorS, &old_CA_vectorS, &old_C_vectorS,
			  curr_mol_complexSP->atomSP,
			  old_atom_startI, old_atom_endI);
	if (n < 3) continue;

	/* Initial coordinates of the new N atom: */
	n = ExtractN_ (&new_N_vectorS,
		       temporary_mol_complexSP->atomSP,
		       new_atom_startI, new_atom_endI);
	if (n < 1) continue;

	/* The translation shift for the new residue: */
	delta_x = old_N_vectorS.x - new_N_vectorS.x;
	delta_y = old_N_vectorS.y - new_N_vectorS.y;
	delta_z = old_N_vectorS.z - new_N_vectorS.z;

	/* Translate the new residue: */
	TranslateRange_ (temporary_mol_complexSP->atomSP,
			 new_atom_startI, new_atom_endI,
			 delta_x, delta_y, delta_z);

	/*------the first rotation:------------------------------------------*/

	/* Extract the updated N and CA coordinates of the new residue: */
	n = ExtractNCA_ (&new_N_vectorS, &new_CA_vectorS,
			temporary_mol_complexSP->atomSP,
			new_atom_startI, new_atom_endI);
	if (n < 2) continue;

	/* The vector parallel to N-CA bond of the new residue: */
	vector1S.x = new_CA_vectorS.x - new_N_vectorS.x;
	vector1S.y = new_CA_vectorS.y - new_N_vectorS.y;
	vector1S.z = new_CA_vectorS.z - new_N_vectorS.z;

	/* The vector parallel to the N-CA bond of the old residue: */
	vector2S.x = old_CA_vectorS.x - old_N_vectorS.x;
	vector2S.y = old_CA_vectorS.y - old_N_vectorS.y;
	vector2S.z = old_CA_vectorS.z - old_N_vectorS.z;

	/* The rotation axis vector is perpendicular to both N-CA bonds: */
	VectorProduct_ (&axis_vectorS, &vector1S, &vector2S);

	/* Calculate the rotation angle, but remember that arc */
	/* cosine is very sensitive  to floating point errors: */
	denominator = AbsoluteValue_ (&vector1S) * AbsoluteValue_ (&vector2S);
	if (denominator == 0.0) continue;
	ratio = ScalarProduct_ (&vector1S, &vector2S) / denominator;
	if (ratio <= -1.0) angle = 3.1415927;
	else if (ratio >= 1.0) angle = 0.0;
	else angle = acos (ratio);

	/* Rotate the new residue: */
	RotateRange_ (temporary_mol_complexSP->atomSP,
		      new_atom_startI, new_atom_endI,
		      &new_N_vectorS, &axis_vectorS, angle);

	/*------the second rotation:-----------------------------------------*/

	/* Extract the updated N, CA and C coordinates of the new residue: */
	n = ExtractNCAC_ (&new_N_vectorS, &new_CA_vectorS, &new_C_vectorS,
			  temporary_mol_complexSP->atomSP,
			  new_atom_startI, new_atom_endI);
	if (n < 3) continue;

	/* The rotation axis vector is parallel */
	/* to the N-CA bond of the new residue: */
	axis_vectorS.x = new_CA_vectorS.x - new_N_vectorS.x;
	axis_vectorS.y = new_CA_vectorS.y - new_N_vectorS.y;
	axis_vectorS.z = new_CA_vectorS.z - new_N_vectorS.z;

	/* CA-C vector (old residue): */
	vector1S.x = old_C_vectorS.x - old_CA_vectorS.x;
	vector1S.y = old_C_vectorS.y - old_CA_vectorS.y;
	vector1S.z = old_C_vectorS.z - old_CA_vectorS.z;

	/* The parallel part of CA-C vector (old residue): */
	n = ParallelPart_ (&old_parallel_vectorS, &axis_vectorS, &vector1S);
	if (n < 0) continue;

	/* The perpendicular part of CA-C vector (old residue): */
	old_perpendicular_vectorS.x = vector1S.x - old_parallel_vectorS.x;
	old_perpendicular_vectorS.y = vector1S.y - old_parallel_vectorS.y;
	old_perpendicular_vectorS.z = vector1S.z - old_parallel_vectorS.z;

	/* CA-C vector (new residue): */
	vector2S.x = new_C_vectorS.x - new_CA_vectorS.x;
	vector2S.y = new_C_vectorS.y - new_CA_vectorS.y;
	vector2S.z = new_C_vectorS.z - new_CA_vectorS.z;

	/* The parallel part of CA-C vector (new residue): */
	n = ParallelPart_ (&new_parallel_vectorS, &axis_vectorS, &vector2S);
	if (n < 0) continue;

	/* The perpendicular part of CA-C vector (new residue): */
	new_perpendicular_vectorS.x = vector2S.x - new_parallel_vectorS.x;
	new_perpendicular_vectorS.y = vector2S.y - new_parallel_vectorS.y;
	new_perpendicular_vectorS.z = vector2S.z - new_parallel_vectorS.z;

	/* Calculate the rotation angle, but remember that arc */
	/* cosine is very sensitive  to floating point errors: */
	denominator = AbsoluteValue_ (&old_perpendicular_vectorS) *
		      AbsoluteValue_ (&new_perpendicular_vectorS);
	if (denominator == 0.0) continue;
	ratio = ScalarProduct_ (&old_perpendicular_vectorS,
				&new_perpendicular_vectorS) / denominator;
	if (ratio < -1.0) angle = 3.1415927;
	else if (ratio > 1.0) angle = 0.0;
	else angle = acos (ratio);

	/* The sign of the angle is still unknown. Prepare */
	/* the vector which is  perpendicular to  both the */ 
	/* rotation axis and to CA-C bond for old residue: */
	VectorProduct_ (&vector3S, &axis_vectorS, &old_perpendicular_vectorS);
	if (ScalarProduct_ (&new_perpendicular_vectorS, &vector3S) > 0.0)
		{
		angle *= -1;
		}

	/* Rotate the new residue: */
	RotateRange_ (temporary_mol_complexSP->atomSP,
		      new_atom_startI, new_atom_endI,
		      &new_N_vectorS, &axis_vectorS, angle);
	}

/* Now it is time to replace the residues. Scan the structure backwards. */

/* Set the initial value for the current number of atoms: */
current_atomsN = old_atomsN;

/* Set the initial value for selected_residueI: */
selected_residueI = selected_residuesN;

/* Scan the old complex backwards. Note that the index must be signed. */
/* Unsigned index  will cause  the following loop to  execute forever! */
for (residueI = total_residuesN - 1; residueI >= 0; residueI--)
	{
	/* Pointer to the old residue: */
	old_residueSP = curr_mol_complexSP->residueSP + residueI;

	/* The start index and the end index of the old residue: */
	old_atom_startI = old_residueSP->residue_startI;
	old_atom_endI   = old_residueSP->residue_endI;

	/* Pointer to the first atom of the old residue: */
	old_first_atomSP = curr_mol_complexSP->atomSP + old_atom_startI;

	/* If the first atom is not selected, skip this residue: */
	if (old_first_atomSP->selectedF == 0) continue;

	/* Update and check the index used to distinguish selected residues: */
	selected_residueI--;
	if (selected_residueI < 0) break;

	/* Prepare the pointer to the new residue: */
	new_residueSP = temporary_mol_complexSP->residueSP + selected_residueI; 

	/* The start index and the end index of the new residue: */
	new_atom_startI = new_residueSP->residue_startI;
	new_atom_endI   = new_residueSP->residue_endI;

	/* Pointer to the first atom of the new residue: */
	new_first_atomSP = temporary_mol_complexSP->atomSP + new_atom_startI;

	/* The new residue may be different in size from the old residue: */
	delta_atomsN = ((int) new_atom_endI - (int) new_atom_startI) -
		       ((int) old_atom_endI - (int) old_atom_startI);

	/* If delta_atomsN is not zero and if not dealing with the */
	/* last residue,  the storage  for atomic data  has  to be */
	/* rearranged.  Prepare the source and destination pointer */
	/* and the number of bytes which have to be shifted. After */
	/* that,  shift all atoms  after the current  old residue. */
	/* Do  not  forget  to update  the total number  of atoms! */
	if ((delta_atomsN != 0) && (residueI != total_residuesN - 1))
		{
		/* Source and destination pointer: */
		source_atomSP = curr_mol_complexSP->atomSP + old_atom_endI + 1;
		dest_atomSP = source_atomSP + delta_atomsN;

		/* The number of atoms after the */
		/* last atom of the old residue: */
		if (current_atomsN > (int) old_atom_endI)  /* Paranoid check */
			{
			trailing_atomsN = current_atomsN - old_atom_endI - 1;
			}
		else trailing_atomsN = 0;

		/* The number of bytes to be moved in memory: */
		bytesN = trailing_atomsN * atom_struct_size;

		/* Rearrange atomic data (move part of the atomic array): */
		memmove (dest_atomSP, source_atomSP, bytesN);

		/* Update the number of atoms in the structure: */
		current_atomsN += delta_atomsN;
		}

	/* Now, finally, insert the new residue: */
	if (new_atom_endI >= new_atom_startI)    /* Paranoid check, again */
		{
		atoms_in_new_residue = new_atom_endI - new_atom_startI + 1;
		}
	else atoms_in_new_residue = 0;
	bytesN = atoms_in_new_residue * atom_struct_size;
	memcpy (old_first_atomSP, new_first_atomSP, bytesN);
	}

/* Update the position_changedF flag: */
curr_mol_complexSP->position_changedF = 1;

/* Delete the temporary structure and reset pointers and counts: */
free (temporary_mol_complexSP->atomSP);
temporary_mol_complexSP->atomSP = NULL;
temporary_mol_complexSP->atomsN = 0;
temporary_mol_complexSP->max_atomsN = 0;
temporary_mol_complexSP->mol_complexID = 0;
free (temporary_mol_complexSP->residueSP);
temporary_mol_complexSP->residueSP = NULL;
temporary_mol_complexSP->residuesN = 0;

/* Update the number of atoms (after the replacement): */
curr_mol_complexSP->atomsN = new_atomsN;

/* Update atomic serial numbers: */
for (atomI = 0; atomI < new_atomsN; atomI++)
	{
	atomSP = curr_mol_complexSP->atomSP + atomI;
	atomSP->raw_atomS.serialI = atomI + 1;
	}

/* Prepare the stereo data (coordinates for the right image): */
if (configSP->stereoF) PrepareStereoData_ (curr_mol_complexSP, configSP);

/* Update strong bonds: */
StrongBonds_ (curr_mol_complexSP, runtimeSP->default_complexI, configSP);

/* Update pseudo-bonds: */
PseudoBonds_ (curr_mol_complexSP, runtimeSP->default_complexI, configSP);

/* Prepare disulfide bonds: */
DisulfideBonds_ (curr_mol_complexSP, runtimeSP->default_complexI, configSP);

/* Refresh backbone data: */
RefreshBackbone_ (curr_mol_complexSP, configSP);

/* Assign radius to each atom: */
AssignRadii_ (curr_mol_complexSP, configSP);

/* Assign default hydrophobicity to each atom: */
AssignHydrophobicity_ (curr_mol_complexSP,
		       curr_mol_complexSP->hydrophobicity_scaleI);

/* Refresh the sequence information: */
if (curr_mol_complexSP->residueSP)
	{
	free (curr_mol_complexSP->residueSP);
	curr_mol_complexSP->residueSP = NULL;
	curr_mol_complexSP->residuesN = 0;
	}
ExtractSequence_ (curr_mol_complexSP);

/* Calculate dihedral angles and cis-trans flags: */
DihedralAngles_ (curr_mol_complexSP, configSP);

/*@@*/ /* Update the secondary structure information: */

/* Reset the editing mode index: */
runtimeSP->edit_modeI = 0;

/* Reset the edit_single_bondF flag: */
runtimeSP->edit_single_bondF = 0;

/* Reset the main window mode index: */
guiSP->main_window_modeI = 0;

/* Refresh the main window: */
(*refreshIP)++;
MainRefresh_ (mol_complexSP, mol_complexesN,
	      runtimeSP, configSP, guiSP,
	      nearest_atomSP, pixelsN, *refreshIP);

/* Refresh the control window: */
ControlRefresh_ (mol_complexSP + runtimeSP->default_complexI, configSP, guiSP);

/* Return the command code: */
return COMMAND_REPLACE;
}

/*===========================================================================*/