/*
FILE:     xtal.C
*/
/*
VERSION:  1.600
*/
/*
DATE:     2/3/2005
*/
/*
  Comments and Questions to: sw-help@rcsb.rutgers.edu
*/
/*
COPYRIGHT 1999-2005 Rutgers - The State University of New Jersey

This software is provided WITHOUT WARRANTY OF MERCHANTABILITY OR
FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR
IMPLIED.  RUTGERS MAKE NO REPRESENTATION OR WARRANTY THAT THE
SOFTWARE WILL NOT INFRINGE ANY PATENT, COPYRIGHT OR OTHER
PROPRIETARY RIGHT.

The user of this software shall indemnify, hold harmless and defend
Rutgers, its governors, trustees, officers, employees, students,
agents and the authors against any and all claims, suits,
losses, liabilities, damages, costs, fees, and expenses including
reasonable attorneys' fees resulting from or arising out of the
use of this software.  This indemnification shall include, but is
not limited to, any and all claims alleging products liability.
*/
/*
               PDB SOFTWARE LICENSE AGREEMENT

BY CLICKING THE ACCEPTANCE BUTTON OR INSTALLING OR USING 
THIS "SOFTWARE, THE INDIVIDUAL OR ENTITY LICENSING THE  
SOFTWARE ("LICENSEE") IS CONSENTING TO BE BOUND BY AND IS 
BECOMING A PARTY TO THIS AGREEMENT.  IF LICENSEE DOES NOT 
AGREE TO ALL OF THE TERMS OF THIS AGREEMENT
THE LICENSEE MUST NOT INSTALL OR USE THE SOFTWARE.

1. LICENSE AGREEMENT

This is a license between you ("Licensee") and the Protein Data Bank (PDB) 
at Rutgers, The State University of New Jersey (hereafter referred to 
as "RUTGERS").   The software is owned by RUTGERS and protected by 
copyright laws, and some elements are protected by laws governing 
trademarks, trade dress and trade secrets, and may be protected by 
patent laws. 

2. LICENSE GRANT

RUTGERS grants you, and you hereby accept, non-exclusive, royalty-free 
perpetual license to install, use, modify, prepare derivative works, 
incorporate into other computer software, and distribute in binary 
and source code format, or any derivative work thereof, together with 
any associated media, printed materials, and on-line or electronic 
documentation (if any) provided by RUTGERS (collectively, the "SOFTWARE"), 
subject to the following terms and conditions: (i) any distribution 
of the SOFTWARE shall bind the receiver to the terms and conditions 
of this Agreement; (ii) any distribution of the SOFTWARE in modified 
form shall clearly state that the SOFTWARE has been modified from 
the version originally obtained from RUTGERS.  

2. COPYRIGHT; RETENTION OF RIGHTS.  

The above license grant is conditioned on the following: (i) you must 
reproduce all copyright notices and other proprietary notices on any 
copies of the SOFTWARE and you must not remove such notices; (ii) in 
the event you compile the SOFTWARE, you will include the copyright 
notice with the binary in such a manner as to allow it to be easily 
viewable; (iii) if you incorporate the SOFTWARE into other code, you 
must provide notice that the code contains the SOFTWARE and include 
a copy of the copyright notices and other proprietary notices.  All 
copies of the SOFTWARE shall be subject to the terms of this Agreement.  

3. NO MAINTENANCE OR SUPPORT; TREATMENT OF ENHANCEMENTS 

RUTGERS is under no obligation whatsoever to: (i) provide maintenance 
or support for the SOFTWARE; or (ii) to notify you of bug fixes, patches, 
or upgrades to the features, functionality or performance of the 
SOFTWARE ("Enhancements") (if any), whether developed by RUTGERS 
or third parties.  If, in its sole discretion, RUTGERS makes an 
Enhancement available to you and RUTGERS does not separately enter 
into a written license agreement with you relating to such bug fix, 
patch or upgrade, then it shall be deemed incorporated into the SOFTWARE 
and subject to this Agreement. You are under no obligation whatsoever 
to provide any Enhancements to RUTGERS or the public that you may 
develop over time; however, if you choose to provide your Enhancements 
to RUTGERS, or if you choose to otherwise publish or distribute your 
Enhancements, in source code form without contemporaneously requiring 
end users or RUTGERS to enter into a separate written license agreement 
for such Enhancements, then you hereby grant RUTGERS a non-exclusive,
royalty-free perpetual license to install, use, modify, prepare
derivative works, incorporate into the SOFTWARE or other computer
software, distribute, and sublicense your Enhancements or derivative
works thereof, in binary and source code form.

4. FEES.  There is no license fee for the SOFTWARE.  If Licensee
wishes to receive the SOFTWARE on media, there may be a small charge
for the media and for shipping and handling.  Licensee is
responsible for any and all taxes.

5. TERMINATION.  Without prejudice to any other rights, Licensor
may terminate this Agreement if Licensee breaches any of its terms
and conditions.  Upon termination, Licensee shall destroy all
copies of the SOFTWARE.

6. PROPRIETARY RIGHTS.  Title, ownership rights, and intellectual
property rights in the Product shall remain with RUTGERS.  Licensee 
acknowledges such ownership and intellectual property rights and will 
not take any action to jeopardize, limit or interfere in any manner 
with RUTGERS' ownership of or rights with respect to the SOFTWARE.  
The SOFTWARE is protected by copyright and other intellectual 
property laws and by international treaties.  Title and related 
rights in the content accessed through the SOFTWARE is the property 
of the applicable content owner and is protected by applicable law.  
The license granted under this Agreement gives Licensee no rights to such
content.

7. DISCLAIMER OF WARRANTY.  THE SOFTWARE IS PROVIDED FREE OF 
CHARGE, AND, THEREFORE, ON AN "AS IS" BASIS, WITHOUT WARRANTY OF 
ANY KIND, INCLUDING WITHOUT LIMITATION THE WARRANTIES THAT IT 
IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE 
OR NON-INFRINGING.  THE ENTIRE RISK AS TO THE QUALITY AND 
PERFORMANCE OF THE SOFTWARE IS BORNE BY LICENSEE.  SHOULD THE 
SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, THE LICENSEE AND NOT 
LICENSOR ASSUMES THE ENTIRE COST OF ANY SERVICE AND REPAIR.  
THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF 
THIS AGREEMENT.  NO USE OF THE PRODUCT IS AUTHORIZED HEREUNDER 
EXCEPT UNDER THIS DISCLAIMER.

8. LIMITATION OF LIABILITY.  TO THE MAXIMUM EXTENT PERMITTED BY
APPLICABLE LAW,  IN NO EVENT WILL LICENSOR BE LIABLE FOR ANY 
INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 
OUT OF THE USE OF OR INABILITY TO USE THE SOFTWARE, INCLUDING, 
WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK 
STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL 
OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF ADVISED OF THE
POSSIBILITY THEREOF. 
*/
#include <stdio.h>
#include <string.h>
#include "class.h"
#include "xtal.h"
#include "atom.h"
#include "symop.h"
#include "gridcell.h"
#include "list.h"

static char lowerchar (const char c)
{
       if ((c >= 'A') && (c <= 'Z')) return char(c+('z'-'Z'));
       else return c;
}

static void lower(const char* s1, char* s2)
{
       int i = 0, len;
       len = strlen(s1);
       while ((i <= len)) {
            s2[i] = lowerchar(s1[i]);
            i++;
       }
       s2[i] = '\0';
}

xtal::xtal()
{
       a = b = c = 0.0;
       alpha = beta = gamma = 90.0;
       cosalpha = cosbeta = cosgamma = 1.0; 
       atlist = 0;
       xtalgrid = 0;
}

xtal::~xtal()
{
       Clear();
}

void xtal::Clear()
{
       if (atlist) delete [] atlist;
       atlist = 0;
       if (xtalgrid) delete xtalgrid;
       xtalgrid = 0;
       atl.DeleteList();
       oplist.DeleteList();
}

int xtal::init(const NDBCELLCONST *cell, _MOLECULE *mol, const int remove_hydrogen)
{
       int i, j, k;
       symop newsym;
       float oper[3][4];
       atom newat;
       _ATOM *_atom = NULL;
       _RESIDUE *residue = NULL;
       _CHAIN *chain = NULL;

       a = cell->a; b = cell->b; c = cell->c;
       alpha = cell->alpha;
       beta = cell->beta;
       gamma = cell->gamma;
       strcpy(sg, cell->space_group);

       cosalpha = float(cos(double(degtorad * alpha)));
       cosbeta = float(cos(double(degtorad * beta)));
       cosgamma = float(cos(double(degtorad * gamma)));

       for (i = 0; i < 3; i++) {
            for (j = 0; j < 3; j++)
                 xform[i][j] = cell->o_to_f[i][j];
            xform[i][3] = cell->o_to_f_v[i];
       }

       numsym = cell->nop;
       for (i = 0; i < numsym; i++) {
            newsym.setopid(i);
            for (j = 0; j < 3; j++) {
                 for (k = 0; k < 3; k++) {
                      oper[j][k] = cell->symops[i].rot[j][k];
                 }
                 oper[j][3] = cell->symops[i].trans[j];
            }
            newsym.setop(oper);
            oplist.append(newsym);
       }

       numatoms = 0;
       chain = mol->GetFirstChain();
       while (chain) {
            if (chain->op() == 1) {
                 residue = chain->GetFirstResidue();
                 while (residue) {
                      _atom = residue->GetFirstAtom();
                      while (_atom) {
                           if (remove_hydrogen && _atom->is_hydrogen()) {
                                _atom = residue->GetNextAtom();
                                continue;
                           }
                           numatoms++;
                           if (chain->chain_type() > 0)
                                newat.settp(NdbToken[chain->chain_type()-1].TokenName);
                           else newat.settp(_atom->type());
                           newat.setnum(_atom->atnum());
                           // newat.setattp(_atom->atmtype());
                           newat.setattp(_atom->pdb_atmnam());
                           newat.setatomtype(_atom->atom_type());
                           newat.setrestp(_atom->restype());
                           newat.setchntp(_atom->chnid());
                           newat.setalt_loc(_atom->alt_loc()[0]);
                           newat.setresnum(_atom->resnum());
                           newat.setx(_atom->orig().x);
                           newat.sety(_atom->orig().y);
                           newat.setz(_atom->orig().z);
                           newat.setocc(_atom->occ());
                           newat.settemp(_atom->t_fct());
                           newat.setcrys(this);
                           atl.append(newat);
                           _atom = residue->GetNextAtom();
                      }
                      residue = chain->GetNextResidue();
                 }
            }
            chain = mol->GetNextChain();
       }
       numatomsAsym = numatoms;
       return (numatoms);
}

void xtal::init(const int num_a, COORD **coord_a, const int num_b, COORD **coord_b)
{
       int i;
       symop newsym;
       float oper[3][4];
       atom newat;

       a = b = c = 1000.0;
       alpha = beta = gamma = 90.0;
       strcpy(sg, "P 1");

       cosalpha = float(cos(double(degtorad * alpha)));
       cosbeta = float(cos(double(degtorad * beta)));
       cosgamma = float(cos(double(degtorad * gamma)));

       xform[0][0] = xform[1][1] = xform[2][2] = 1.0 / a;
       xform[0][1] = xform[0][2] = xform[0][3] =
       xform[1][0] = xform[1][2] = xform[1][3] =
       xform[2][0] = xform[2][1] = xform[2][3] = 0.0;

       numsym = 1;
       oper[0][0] = oper[1][1] = oper[2][2] = 1;
       oper[0][1] = oper[0][2] = oper[0][3] =
       oper[1][0] = oper[1][2] = oper[1][3] =
       oper[2][0] = oper[2][1] = oper[2][3] = 0;
       newsym.setopid(0);
       newsym.setop(oper);
       oplist.append(newsym);

       numatoms = 0;
       for (i = 0; i < num_a; i++) {
            numatoms++;
            newat.setnum(numatoms);
            newat.setchntp("a");
            newat.setx(coord_a[i]->x);
            newat.sety(coord_a[i]->y);
            newat.setz(coord_a[i]->z);
            newat.setcrys(this);
            atl.append(newat);
       }
       for (i = 0; i < num_b; i++) {
            numatoms++;
            newat.setnum(numatoms);
            newat.setchntp("b");
            newat.setx(coord_b[i]->x);
            newat.sety(coord_b[i]->y);
            newat.setz(coord_b[i]->z);
            newat.setcrys(this);
            atl.append(newat);
       }
       numatomsAsym = numatoms;
}

void xtal::setSymms(List<symop> s)
{
  oplist = s;
  numsym = s.length();
}

// Use the list of symmetry operations on the list of atoms in the asymmetric
// unit to generate the array of atoms in the entire unit cell.  If the
// atoms are known to be in cartesian, then first convert all of them to
// fractional.  Delete the initial list data structure, to save space.  
// Each copy of the asymmetric unit is contiguous.
void xtal::getSymmAtoms()
{
  int ats = 0; 
  int initnumatoms = numatoms; 
  ListObj<symop> *ptr = oplist.front()->rest(); 
  ListObj<atom> *atpt; 

  numatoms *= numsym;
  numatomsAsym *= numsym; 
  atlist = new atom[numatoms+1];
  atpt = atl.front();
  // Copy all of the asymmetric unit atoms into the array.  Assumes the
  // first symmetry operation is identity.
  for (int i=0; i < initnumatoms; i++) 
    {
      atlist[i]=atpt->firstval();
      if (orth=='c') atlist[i].fractionalize();
      atpt=atpt->rest();
    }
  ats=initnumatoms;  
  for (int j = 1; j < numsym; j++) //assumes first symmetry is identity
    { 
      for (int k=0; k<initnumatoms; k++)
          atlist[ats++] = atlist[k].symrel(ptr->firstval());
      ptr = ptr->rest();
    }
  atl.DeleteList();
}

//////////////////////////////////////////////////////////////////////
//		     Data Member Access Methods
//////////////////////////////////////////////////////////////////////

// Return the list of symmetry operations
List<symop> xtal::syms()
{
  return oplist;
}

char* xtal::Space()
{
  return sg;
}

char* xtal::xtalName()
{
  return crysnm;
}

// Return the list of atoms.  This is *only* the atoms in the asymmetric
// unit.  The entire cell is stored in an array, for fast random access.
List<atom> xtal::ats()
{
  return atl;
}

// Return a pointer to the beginning of the array of atoms
atom* xtal::crysAtoms()
{
  return atlist;
}

// Return a pointer to the grid partitioning the crystal
grid* xtal::crysGrid()
{
  return xtalgrid;
}

// Return the cell dimensions of the crystal
cellDim xtal::aval()
{
  return a;
}

cellDim xtal::bval()
{
  return b;
}

cellDim xtal::cval()
{
  return c;
}

cellDim xtal::alphaval()
{
  return alpha;
}

cellDim xtal::betaval()
{
  return beta;
}

cellDim xtal::gammaval()
{
  return gamma;
}

// Return the number of atoms in the crystal...beware...this changes
// between when the crystal is read in and when the symmetry related
// atoms are calculated
int xtal::numberAtoms()
{
  return numatoms;
}

int xtal::numSource()
{
  return numsrc;
}

int xtal::numTarget()
{
  return numtar;
}

//////////////////////////////////////////////////////////////////////
//		   Data member manipulation methods
//////////////////////////////////////////////////////////////////////

// Record whether coordinates are in fractional or cartesian
void xtal::setorth(const char ort)
{
  orth=ort;
}

void xtal::setnumAts(const int num)
{
  numatoms = num;
}

void xtal::setnumAtsAsym(const int num)
{
  numatomsAsym = num;
}

void xtal::setAtl (List<atom> l)
{
  atl = l;
}

// Set up grid data structure for crystal...call grid constructor.
void xtal::makeGrid()
{ int elts;
  elts = int(floor (1+exp((log(double(numatomsAsym)))/3)));
  xtalgrid = new grid(elts,this);
}

// Translate all atoms in the crystal into the center unit cell.  Note
// this should only be called after all of the symmetry related atoms
// have been generated.  Otherwise the program will crash (atom array
// not generated yet) and even if it didn't, would not work correctly,
// since after generating the symmetry related atoms, some of them might
// not be in the center unit cell.
void xtal::moveAllAtomsToCenter()
{
  for (int i = 0; i < numatoms; i++)
    atlist[i].moveToCenterCell();
}

// Hash each atom into the appropriate grid element.  Again, make sure
// this is done *after* the symmetry related atoms are generated.
void xtal::placeAtomsInGrid()
{
//  delete xtalgrid;

  this->makeGrid(); 
  for (int i=0; i < numatoms; i++) 
      atlist[i].placeAtomInGrid(xtalgrid); 
}

// Delete all the atoms in the crystal's atom array
void xtal::deleteAtoms()
{
  delete [] atlist;
}

// Delete a crystal's grid...call grid destructor  
void xtal::deleteGrid()
{
  delete xtalgrid;
}

void xtal::setsg(xtal* crys)
{
  strcpy(sg,crys->sg);
}

void xtal::setxform(xtal* crys)
{
  xform[0][0] = crys->xform[0][0];
  xform[0][1] = crys->xform[0][1];
  xform[0][2] = crys->xform[0][2];
  xform[0][3] = crys->xform[0][3];
  xform[1][0] = crys->xform[1][0];
  xform[1][1] = crys->xform[1][1];
  xform[1][2] = crys->xform[1][2];
  xform[1][3] = crys->xform[1][3];
  xform[2][0] = crys->xform[2][0];
  xform[2][1] = crys->xform[2][1];
  xform[2][2] = crys->xform[2][2];
  xform[2][3] = crys->xform[2][3];
}

///////////////////////////////////////////////////////////////////////
// Methods for selecting atoms with particular feature from entire list
///////////////////////////////////////////////////////////////////////

List<atom*>* xtal::selectAtoms(const char *selectType)
{
       char inpt[100];
       List<atom*>* fromatoms = NULL;
       int lastpos;

       while (!fromatoms || (fromatoms->length()==0)) {
            lower(selectType, inpt);
            fromatoms = parseall(inpt, 0, lastpos, this);
       }
       return fromatoms;
}

// Select atoms of some range number (a la BANG), but also their symmetry
// related versions.
List<atom*> xtal::selectSymAtoms(const int lo, int hi)
{
  List<atom*> al;
  int nsym= oplist.length();
  int losym=0;
  int offset = numatoms/nsym;

  if (hi>=offset) hi=offset;
  for (int i=lo-1; i<hi; i++)
    for (int j=losym; j < nsym; j++)
       al.append(atlist[i+offset*j].atptr());
  return al;
}

// Select all atoms (including symmetry related) with particular residue number
List<atom*> xtal::selectResAtoms(const int resid)
{
  List<atom*> al;
  int lowat=0;
  int numat=numatoms;

  for (int i=lowat; i<numat; i++)
     if(atlist[i].res()==resid) al.append(atlist[i].atptr());
  return al;
}  

// Select all atoms (including symmetry related) with particular chain id
List<atom*> xtal::selectChainAtoms(const char *chn)
{
  List<atom*> al;
  int lowat=0;
  int numat=numatoms;

  for (int i=lowat; i<numat; i++)
     if (!strcmp(atlist[i].chain(), chn)) al.append(atlist[i].atptr());
  return al;
}  

// Select all atoms (including symmetry related) with particular type
List<atom*> xtal::selectTypeAtoms(const char* ty)
{
  List<atom*> al;
  char at[7];
  int lowat = 0;
  int numat = numatoms;

  for (int i=lowat; i<numat; i++)
    {
     lower(atlist[i].typ(), at);	 
     if(strstr(at,ty)) al.append(atlist[i].atptr());
    }
  return al;
}  

// Select all atoms (including symmetry related) with particular atom type
// and base type
List<atom*> xtal::selectAtomTypeAtoms(const char* bty, const char* ty)
{
  List<atom*> al;
  char at[4];
  char bt[4];
  int lowat=0;
  int numat=numatoms;

  for (int i=lowat; i<numat; i++)
    {
     lower(atlist[i].resType(), bt);	 
     lower(atlist[i].attyp(), at);	 
     if((strcmp(at,ty)==0) && (strcmp(bt,bty)==0))
          al.append(atlist[i].atptr());
    }
  return al;
}  

// Select all atoms (including symmetry related) with particular type
List<atom*> xtal::selectAtomTypeAtoms(const char* ty)
{
  List<atom*> al;
  char at[4];
  int lowat=0;
  int numat=numatoms;

  for (int i=lowat; i<numat; i++)
    {
     lower(atlist[i].attyp(), at);	 
     if((strcmp(at,ty)==0))
          al.append(atlist[i].atptr());
    }
  return al;
}  

// Select all atoms (including symmetry related) that match particular type
List<atom*> xtal::selectAtomLikeAtoms(const char* ty)
{
  List<atom*> al;
  char at[4];
  int lowat=0;
  int numat=numatoms;

  for (int i=lowat; i<numat; i++)
    {
     lower(atlist[i].attyp(), at);	 
     if((strstr(at,ty)))
          al.append(atlist[i].atptr());
    }
  return al;
}  

// Select all atoms (including symmetry related) with particular residue type
List<atom*> xtal::selectResTypeAtoms(const char* ty)
{
  List<atom*> al;
  char at[4];
  int lowat=0;
  int numat=numatoms;

  for (int i=lowat; i<numat; i++)
    {
     lower(atlist[i].resType(), at);	 
     if(strcmp(at,ty)==0) al.append(atlist[i].atptr());
    }
  return al;
}  
