/* 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;
}

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


