/* Copyright (C) 2001-2003 Damir Zucic */

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

				create_structure.c

Purpose:
	Create  the new structure.  Use the sequence  from the main sequence
	buffer and the secondary structure from the main secondary structure
	buffer.  Atomic data should be copied  from the template data.  This
	function works only with protein sequences. This functions should be
	compared with  load_complex.c,  to check  what should be prepared in
	addition to complete the structure.

Input:
	(1) Pointer to MolComplexS structure.
	(2) Pointer to the number of macromolecular complexes.
	(3) Pointer to the next macromolecular complex identifier.
	(4) Pointer to RuntimeS structure.
	(5) The number of residues.
	(6) Pointer to ConfigS structure.
	(7) Pointer to GUIS structure.

Output:
	(1) Allocate memory and create structure.
	(2) Return value.

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

Notes:
	(1) The number of atoms in the structure  is updated in the function
	    CopyTemplateAtoms_ ().

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

#include <stdio.h>

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

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

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

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

void		ErrorMessage_ (char *, char *, char *,
			       char *, char *, char *, char *);
void		InitializeHeader_ (HeaderS *);
int		CountRequiredAtoms_ (RuntimeS *, int);
int		CopyTemplateAtoms_ (MolComplexS *, RuntimeS *,
				    ResidueS *, int);
int		ExtractSequence_ (MolComplexS *);
int		FixChain_ (MolComplexS *, RuntimeS *);
int		GeometricCenter_ (MolComplexS *);
void		FlipVector_ (VectorS *, VectorS *);
void		TranslateComplex_ (MolComplexS *, VectorS *, ConfigS *, int);
int		ComplexExtent_ (MolComplexS *);
void		InitSlab_ (MolComplexS *);
void		InitFading_ (MolComplexS *);
int		PrepareStereoData_ (MolComplexS *, ConfigS *);
size_t		StrongBonds_ (MolComplexS *, int, ConfigS *);
size_t		PseudoBonds_ (MolComplexS *, int, ConfigS *);
size_t		DisulfideBonds_ (MolComplexS *, int, ConfigS *);
int		PrepareBackbone_ (MolComplexS *, ConfigS *);
int		AssignRadii_ (MolComplexS *, ConfigS *);
int		AssignHydrophobicity_ (MolComplexS *, int);
int		DihedralAngles_ (MolComplexS *, ConfigS *);
int		AllocSecondaryStructure_ (MolComplexS *);
/*@@*/ /* Generate secondary structure */
int		GeneratePlane_ (MolComplexS *, ConfigS *, GUIS *);
int		InitializeMembrane_ (MolComplexS *, ConfigS *, GUIS *);

/*======create new structure:================================================*/

int CreateStructure_ (MolComplexS *mol_complexSP,
		      int *mol_complexesNP, int *next_mol_complexIDP,
		      RuntimeS *runtimeSP, int residuesN,
		      ConfigS *configSP, GUIS *guiSP)
{
int			max_length;
size_t	 		char_size, atom_struct_size;
int			new_mol_complexI;
static MolComplexS	*new_mol_complexSP;
int			new_mol_complexID;
int			required_atomsN;
size_t			elementsN;
int			residueI;
char			*curr_residue_nameP;
int			template_residuesN, template_residueI;
ResidueS		*template_residueSP;
AtomS			*first_atomSP;
char			*curr_template_nameP;
int			n;
VectorS			shift_vectorS;		/* Shift to geometric center */
int			default_hyphob_scaleI = 2;
int			mol_complexI;
MolComplexS		*curr_mol_complexSP;

/* 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 index of the new structure: */
new_mol_complexI = *mol_complexesNP;

/* Prepare the pointer to the new macromolecular complex: */
new_mol_complexSP = mol_complexSP + new_mol_complexI;

/* Initialize the file name: */
new_mol_complexSP->file_nameA[0] = '\0';

/* Prepare the identifier for the new macromolecular complex: */
new_mol_complexID = *next_mol_complexIDP;
new_mol_complexSP->mol_complexID = new_mol_complexID;

/* Update the next macromolecular complex identifier: */
(*next_mol_complexIDP)++;

/* Update the number of macromolecular complexes: */
(*mol_complexesNP)++;

/* Allocate memory for header strings: */
new_mol_complexSP->headerS.total_linesN = MAXHEADERLINES + MAXTITLELINES +
					  MAXCOMPNDLINES + MAXSOURCELINES +
					  MAXEXPDTALINES + MAXAUTHORLINES;
elementsN = new_mol_complexSP->headerS.total_linesN * HEADERLINESIZE + 100;
new_mol_complexSP->headerS.dataP = (char *) calloc (elementsN, char_size);
if (new_mol_complexSP->headerS.dataP == NULL)
	{
	ErrorMessage_ ("garlic", "CreateStructure_", "",
		       "Failed to allocate memory for header data!\n",	
		       "", "", "");
	return -1;
	}

/* Initialize the unique PDB identifier: */
strcpy (new_mol_complexSP->unique_PDB_codeA, "XXXX");

/* Initialize the memory reserved for text and initialize offsets: */
InitializeHeader_ (&new_mol_complexSP->headerS);

/* Set the initial number of atoms (it will grow up later): */
new_mol_complexSP->atomsN = 0;

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

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

/* Allocate the memory for atomic coordinates (add some extra space): */
new_mol_complexSP->atomSP = (AtomS *) calloc (elementsN, atom_struct_size);
if (new_mol_complexSP->atomSP == NULL)
	{
	ErrorMessage_ ("garlic", "CreateStructure_", "",
		       "Failed to allocate memory for atomic data!\n",
		       "", "", "");
	free (new_mol_complexSP->headerS.dataP);
	new_mol_complexSP->headerS.dataP = NULL;
	return -2;
	}

/* Copy the required template residues. */

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

/* Scan the sequence: */
for (residueI = 0; residueI < residuesN; residueI++)
	{
	/* Prepare the pointer to the current residue name: */
	curr_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: */
		first_atomSP = runtimeSP->template_atomSP +
			       template_residueSP->residue_startI;

		/* Pointer to the current template residue name: */
		curr_template_nameP =
				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 (curr_residue_nameP,
			     curr_template_nameP, max_length) == 0)
			{
			/* Copy template atoms: */
			CopyTemplateAtoms_ (new_mol_complexSP, runtimeSP,
					    template_residueSP, residueI);
			break;
			}
		}
	}

/* Extract sequence information: */
ExtractSequence_ (new_mol_complexSP);

/* Fix the macromolecular chain: */
n = FixChain_ (new_mol_complexSP, runtimeSP);
if (n < 0)
	{
	ErrorMessage_ ("garlic", "CreateStructure_", "",
		       "Unable to fix the polypeptide chain!\n",
		       "", "", "");
	free (new_mol_complexSP->headerS.dataP);
	new_mol_complexSP->headerS.dataP = NULL;
	free (new_mol_complexSP->atomSP);
	new_mol_complexSP->atomSP = NULL;
	return n;
	}

/* Initialize the move bits: */
new_mol_complexSP->move_bits =  STRUCTURE_MASK |
				PLANE_MASK |
				MEMBRANE_MASK |
				ENVELOPE_MASK;

/* Find geometric center: */
GeometricCenter_ (new_mol_complexSP);

/* Flip vector (multiply by -1): */
FlipVector_ (&shift_vectorS, &new_mol_complexSP->geometric_center_vectorS);

/* Translate geometric  center of the complex to */
/* the origin of the absolute coordinate system: */
TranslateComplex_ (new_mol_complexSP, &shift_vectorS, configSP, 0);

/* Initial rotation center position: */
new_mol_complexSP->rotation_center_vectorS.x = 0.0;
new_mol_complexSP->rotation_center_vectorS.y = 0.0;
new_mol_complexSP->rotation_center_vectorS.z = 0.0;

/* Spatial extend of the whole macromolecular complex: */
ComplexExtent_ (new_mol_complexSP);

/* Initialize the slab mode (use the current default slab mode): */
new_mol_complexSP->slab_modeI = configSP->default_slab_modeI;

/* Initialize slab: */
InitSlab_ (new_mol_complexSP);

/* Initialize the color fading mode (use the current default fading mode): */
new_mol_complexSP->fading_modeI = configSP->default_fading_modeI;

/* Initialize color fading parameters: */
InitFading_ (new_mol_complexSP);

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

/* Prepare bonds; use inter-atomic */
/* distances  for  identification: */
StrongBonds_ (new_mol_complexSP, new_mol_complexI, configSP);

/* Prepare pseudo-bonds: */
PseudoBonds_ (new_mol_complexSP, new_mol_complexI, configSP);

/* Prepare disulfide bonds: */
DisulfideBonds_ (new_mol_complexSP, new_mol_complexI, configSP);

/* Prepare  backbone  data - allocate  and */
/* fill the array of BackboneS structures: */
PrepareBackbone_ (new_mol_complexSP, configSP);

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

/* Assign default hydrophobicity to each atom: */
AssignHydrophobicity_ (new_mol_complexSP, default_hyphob_scaleI);

/* The sequence information was extracted before, no need to do this again. */

/* Calculate dihedral angles and cis_trans flags: */
DihedralAngles_ (new_mol_complexSP, configSP);

/* Allocate and initialize the storage for the secondary structure: */
if (AllocSecondaryStructure_ (new_mol_complexSP) < 0)
	{
	ErrorMessage_ ("garlic", "CreateStructure_", "",
		       "Failed to allocate memory for secondary structure!\n",
		       "", "", "");
	free (new_mol_complexSP->headerS.dataP);
	new_mol_complexSP->headerS.dataP = NULL;
	free (new_mol_complexSP->atomSP);
	new_mol_complexSP->atomSP = NULL;
	return -4;
	}

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

/* Generate the plane (represented by an ellipse): */
GeneratePlane_ (new_mol_complexSP, configSP, guiSP);

/* Initialize data required to draw the membrane: */
InitializeMembrane_ (new_mol_complexSP, configSP, guiSP); 

/* Initialize the flag reserved for hydrogen bonds: if value */
/* is equal to zero, hydrogen bonds are missing or obsolete. */
new_mol_complexSP->hydrogen_bondsF = 0;

/* The hydrogen bonds are initially invisible: */
new_mol_complexSP->hydrogen_bonds_hiddenF = 1;

/* The membrane is initially undefined: */
new_mol_complexSP->membraneS.definedF = 0;

/* Set the probe radius (copy default value): */
new_mol_complexSP->bond_probe_radius = configSP->default_bond_probe_radius;

/* Set the stick radius (used to draw bonds as sticks; copy default value): */
new_mol_complexSP->stick_radius = configSP->default_stick_radius;

/* Set the group_memberF to zero: */ 
new_mol_complexSP->group_memberF = 0;

/* If some structures were grouped, break */
/* the group,  i.e. reset the group flag: */
runtimeSP->groupF = 0;

/* If some structures were involved in a formation of a */
/* group, restore the original rotation center vectors: */
for (mol_complexI = 0; mol_complexI < *mol_complexesNP; mol_complexI++)
	{
	/* Prepare the pointer to the current macromolecular complex: */
	curr_mol_complexSP = mol_complexSP + mol_complexI;

	/* Check was this complex a group member: */
	if (curr_mol_complexSP->group_memberF == 0) continue;

	/* If this point is reached, the current complex was a group member. */

	/* Restore the original rotation center vector: */
	curr_mol_complexSP->rotation_center_vectorS.x =
				curr_mol_complexSP->backup_vectorS.x;
	curr_mol_complexSP->rotation_center_vectorS.y =
				curr_mol_complexSP->backup_vectorS.y;
	curr_mol_complexSP->rotation_center_vectorS.z =
				curr_mol_complexSP->backup_vectorS.z;

	/* Reset the group_memberF: */
	curr_mol_complexSP->group_memberF = 0;
	}

/* Set  the catch flag  to indicate  that  the new */
/* complex is the only one  which is caught,  i.e. */
/* affected by movement, slab and fading controls: */
for (mol_complexI = 0; mol_complexI < *mol_complexesNP; mol_complexI++)
	{
	/** Pointer to the current macromolecular complex: **/
	curr_mol_complexSP = mol_complexSP + mol_complexI;

	/** The catch flag for the new complex should be set to one: **/
	if (curr_mol_complexSP->mol_complexID == new_mol_complexID)
		{
		curr_mol_complexSP->catchF = 1;
		}
	/** All other catch flags should be set to zero: **/
	else curr_mol_complexSP->catchF = 0;
	}

/* Return positive value on success: */
return 1;
}

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


