/*
FILE:     CifFile.C
*/
/*
VERSION:  4
*/
/*
DATE:     6/17/2002
*/
/*
  Comments and Questions to: sw-help@rcsb.rutgers.edu
*/
/*
COPYRIGHT 1999-2002 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. 
*/
/* **************************************************************** *
  
  PURPOSE:      This file contains the methods for class CifFile and 
                the anonymous function:
		AddADicItem(ReVarCifArray <CifDataItem> *newdata,const  
                            CifString keyword, const CifString value, 
			    const CifString relation_label) 

 * **************************************************************** */

#include "CifFile.h"

// *********************************************************************
//      CifFile
// *********************************************************************
CifString*CifFile::GetItemDataTypeCode(const int dataBlockIndex, 
					       const int categoryIndex,
					       const int itemIndex) 
{
  if (dataBlockIndex < 0 || dataBlockIndex >= _dataBlocks.Length())
    return  NULL;
  else return _dataBlocks[dataBlockIndex].GetItemDataTypeCode(categoryIndex, itemIndex);

}

CifString*CifFile::GetItemDataTypeCode(const int dataBlockIndex, 
					       const CifString category,
					       const CifString item) 
{
  if (dataBlockIndex < 0 || dataBlockIndex >= _dataBlocks.Length())
    return  NULL;
  else return _dataBlocks[dataBlockIndex].GetItemDataTypeCode(category, item);
}

 int CifFile::GetItemDataType(const int dataBlockIndex, 
				 const int categoryIndex,
				 const int itemIndex) 
{
  if (dataBlockIndex < 0 || dataBlockIndex >= _dataBlocks.Length())
    return  CIF_DATABLOCK_NOT_EXIST ;
  else return _dataBlocks[dataBlockIndex].GetItemDataType(categoryIndex, itemIndex);
}
 int CifFile::GetItemDataType(const int dataBlockIndex, 
				 const CifString categoryName,
				 const CifString itemName) 
{
  if (dataBlockIndex < 0 || dataBlockIndex >= _dataBlocks.Length())
    return  CIF_DATABLOCK_NOT_EXIST ;
  else return _dataBlocks[dataBlockIndex].GetItemDataType(categoryName, itemName);
}



int CifFile::GetIndex(const char *datablock_name)
// ----------------------------------------------------------------------
//   GetIndex() Finds the index of the datablock_namein dics array, 
//              -1 if not found
// --------------------------------------------------------------------- 
{
  int i;
  CifString Datablock_label(datablock_name);
  Datablock_label.ToLower();

  for (i=0; i< _dataBlocks.Length(); i++) 
    if (!CompareNoCase(_dataBlocks[i]._dataBlockName, Datablock_label)) 
      break;

  if (i != _dataBlocks.Length()) return i;
  else return -1;
}


void CifFile::Print() const
// ----------------------------------------------------------------------
//   Print(): Dump the structure
// --------------------------------------------------------------------- 
{
  unsigned i; 
  PrintLine("File");
  for (i=0; i<_dataBlocks.Length(); i++) 
    _dataBlocks[i].Print();
}
void CifFile::PrintDetails()  const
// ----------------------------------------------------------------------
//   Print(): Dump the structure
// --------------------------------------------------------------------- 
{
  unsigned i; 
  cout << "GLOBALS: " << endl;
  _globalInformation.Print();

  for (i=0; i<_dataBlocks.Length(); i++) {
    cout << "datablocks: " << i << ' ';
    _dataBlocks[i].PrintDetails();
  }
  PrintLine();
}


void CifFile::PrintTable()  const
// ----------------------------------------------------------------------
//   Print(): Dump the structure
// --------------------------------------------------------------------- 
{
  unsigned i;
  cout << "GLOBALS: " << endl;
  _globalInformation.Print();

  for (i=0; i<_dataBlocks.Length(); i++) {
    cout << "datablocks: " << i << ' ';
    _dataBlocks[i].PrintTable();
  }
}

void CifFile::PrintDiagnostics()
{
  int i,j;
  //
  //  Output error and warning messages .... 
  //
  for (i=0; i < _dataBlocks.Length(); i++) {

    cout << endl << "There are " <<   _dataBlocks[i].CountErrors() << " errors in block " << 
      _dataBlocks[i]._dataBlockName.Text() << " [" << i << "]" << endl << endl;

    for (j=0; j <  _dataBlocks[i].CountErrors(); j++) {
      cout <<  _dataBlocks[i].GetError(j)->Text() << endl;
    }

    cout << endl << "There are " << _dataBlocks[i].CountWarnings() << " warnings in block " << 
      _dataBlocks[i]._dataBlockName.Text() << " [" << i << "]" << endl << endl;

    for (j=0; j <  _dataBlocks[i].CountWarnings(); j++) {
      cout <<  _dataBlocks[i].GetWarning(j)->Text() << endl;
    }
  }
}

CifFile &CifFile::Copy(const CifFile &file)
{
//  file_name.Copy(file.file_name);
  _globalInformation.Copy(file._globalInformation);
  _dataBlocks.Clear();
    
  for (unsigned i=0; i < file._dataBlocks.Length(); i++) 
    _dataBlocks.Add(file._dataBlocks[i]);
  return *this;
}
CifString *CifFile::GetItemPrimitiveCode(const int dataBlockIndex, 
					       const int categoryIndex,
					       const int itemIndex) 
{
  if (dataBlockIndex < 0 || dataBlockIndex >= _dataBlocks.Length())
    return  NULL;
  else return _dataBlocks[dataBlockIndex].GetItemPrimitiveCode(categoryIndex, itemIndex);

}
CifString*CifFile::GetItemPrimitiveCode(const int dataBlockIndex, 
					       const CifString category,
					       const CifString item) 
{
  if (dataBlockIndex < 0 || dataBlockIndex >= _dataBlocks.Length())
    return  NULL;
  else return _dataBlocks[dataBlockIndex].GetItemPrimitiveCode(category, item);
}


int CifFile:: ReadFile(const char *filename, const char *dicDataBlockName, const int verify)
{
  int ret, i,type, dicDataBlockNo = -1, index;
  CifFileIo  *newCifFile;
  CifCategory newCategory;
  CifDataBlock cifDatablock, *dic;
  CifString label, message;

  if (dicDataBlockName != NULL) dicDataBlockNo = GetIndex(dicDataBlockName);

  // Look for an existing persistent object version of the this file.
  if (dicDataBlockNo != -1 && dicDataBlockName != NULL) {
    if (PermanentRead(filename, 
		      _dataBlocks[dicDataBlockNo]._fileName.Text(),
		      _dataBlocks[dicDataBlockNo]._dataBlockName.Text())) { 
      return TRUE;
    }
  } else if (PermanentRead(filename)) { 
    return TRUE;
  }
  
  // Open given CIF text filename for reading
  ret = FILE_OPERATION_SUCCEED;
  newCifFile = new CifFileIo;
  if ((ret = newCifFile->OpenFile(filename, 'r'))!= FILE_OPERATION_SUCCEED ) {
    delete newCifFile;
    cout << filename << " can not be opened" << endl;
    return ret;
  }

  if (dicDataBlockNo != -1) {
    dic = &_dataBlocks[dicDataBlockNo];
  }  else {
    dic = NULL;
  }

  // Get the first token, if data_ is the keyword, store the label 
  cifDatablock._fileName.Copy(newCifFile->GetFileName());
  cifDatablock._fileOffset = newCifFile->GetInMemoryOffset();
  type = newCifFile->GetNextCifToken(&cifDatablock, dic);

  if (type == CIF_KEYWORD_DATA) {
    if ((index = GetIndex(&newCifFile->GetTokenValue()->Text()[5])) != -1) {
      message.Clear();
      message += "Repeated datablock name at index ";
      message += index;
      message += " in file \'";
      message += _dataBlocks[index]._fileName;
      message += "\'";
      cifDatablock.ErrorMessage(CIF_ERROR, newCifFile->GetCurrLineNo(), message);
    }
      
    cifDatablock.SetDatablockName(&newCifFile->GetTokenValue()->Text()[5]);
    newCifFile->GetNextCifToken(&cifDatablock, dic);
  }

  while (type == CIF_KEYWORD_GLOBAL   || type == CIF_KEYWORD_DATA  || 
	 type == CIF_KEYWORD_INCLUDE  || type == CIF_KEYWORD_ALIAS ||
	 type == CIF_DEFINITION_CATEGORY || type == CIF_DEFINITION_ITEM  ||
	 type == CIF_ITEM_NAME  || type == CIF_KEYWORD_LOOP) {

    // Copy down the label for further usage
    if (type == CIF_KEYWORD_GLOBAL) {

      for (i=0; i<newCifFile->GetTokenValue()->Length(); i++) {
	if (newCifFile->GetTokenValue()->Text()[i] == CIF_DATA_PREFIX_CHARACTER) break;
      }

      if (i != newCifFile->GetTokenValue()->Length())
	label.Copy(&(newCifFile->GetTokenValue()->Text()[i+1]));

      newCifFile->GetNextCifToken(&cifDatablock, dic);

      do {
	if ( newCifFile->GetTokenType() == CIF_KEYWORD_LOOP || 
	     newCifFile->GetTokenType() == CIF_ITEM_NAME)  {
	  if (newCifFile->GetTokenType() == CIF_KEYWORD_LOOP) {
	    newCifFile->GetCifLoopedValue(NULL, &_globalInformation, &newCategory );
	  } else {
	    newCifFile->GetCifNonLoopedValue(NULL, &_globalInformation, &newCategory);
	  }
	  
	  
	  _globalInformation.InsertRowsFromFile(&_dataBlocks[dicDataBlockNo], 
						verify, 
						newCifFile->GetCurrLineNo(), 
						newCifFile->GetSaveOffset(), 
						&newCategory,
						NULL, NULL, NULL);
	  if (newCategory._items.Length() != 0) newCategory.DeleteElement();
	}
      } while (newCifFile->GetTokenType() == CIF_ITEM_NAME  ||
	       newCifFile->GetTokenType() == CIF_KEYWORD_LOOP);
    } else { 
      if (dicDataBlockNo != -1)  {
	cifDatablock.ReadDatablock(newCifFile, &_globalInformation, &_dataBlocks[dicDataBlockNo], 
				   verify);
	cifDatablock._dictionaryIndex = dicDataBlockNo;
      } else {
	cifDatablock.ReadDatablock(newCifFile, &_globalInformation, &cifDatablock, verify);
	cifDatablock._dictionaryIndex = _dataBlocks.Length();
      }
      _dataBlocks.Add(cifDatablock);
      cifDatablock.DeleteElement();
      cifDatablock._fileName.Copy(newCifFile->GetFileName());
      cifDatablock._fileOffset = (long) newCifFile->GetInMemoryOffset() - 
	(long) newCifFile->GetTokenValue()->Length();
    }
    type = newCifFile->GetTokenType();
  } // end while
  
  PermanentWrite(newCifFile->GetFileName()->Text());
  if (newCifFile->GetTokenType() != EOF) {
    delete newCifFile;
    return FAILURE;
  }
  delete newCifFile;
  return SUCCEED;
}



int CifFile:: WriteFile(const char *filename, const char *outputFileName,
			 const char type, const int write_comment,
			 const int esdFlag,
			 const char *dictionary,
			 const char *version)
{
  int ret, i;
  CifFileIo *newCifFile;
  CifString *dic, *dic_version;


  ret = FILE_OPERATION_SUCCEED;

  if (type != 'w' && type != 'W' && type != 'a' && type != 'A')
    return FILE_OPERATION_TYPE_DISALLOW  ;

  // Open given filename for reading
  newCifFile = new CifFileIo;
  if ((ret = newCifFile->OpenFile(outputFileName, type))!= FILE_OPERATION_SUCCEED ) {
    delete newCifFile;
    return ret;
  }

  if (dictionary != NULL && strcmp(dictionary, "")) dic = new CifString(dictionary);
  else dic  = NULL;
  if (version != NULL && strcmp(version,"")) dic_version = new CifString(version);
  else dic_version = NULL;

  if (_globalInformation._categories.Length() > 0) {
    newCifFile->FileIo::PrintF("%s%s\n", CIF_RESERVED_KEYWORD_GLOBAL, 
			     _globalInformation._dataBlockName.Text());
    _globalInformation.WriteDataBlock(newCifFile, write_comment, esdFlag, dic, dic_version);
  }
  for (i=0; i< _dataBlocks.Length(); i++) {
    if (!strcmp(_dataBlocks[i]._fileName.Text(), filename)) 
      
      _dataBlocks[i].WriteDataBlock(newCifFile, write_comment, esdFlag,
				   dic, dic_version,
				   &_dataBlocks[_dataBlocks[i]._dictionaryIndex]);
  }
  newCifFile->CloseFile();
  delete newCifFile;
  if (dic != NULL) 
    delete dic;
  if (dic_version != NULL)
    delete dic_version;
  return SUCCEED;
}


int CifFile:: WriteDataBlock(const char *filename, const char type, 
			      const char *datablock_name, const int write_comment,
			      const int esdFlag,
			      const char *dictionary,
			      const char *version )
{
  int ret, dic_no, datablock_no;
  CifFileIo *newCifFile;
  
  CifString *dic, *dic_version;

  ret = FILE_OPERATION_SUCCEED;

  if (type != 'w' && type != 'W' && type != 'a' && type != 'A')
    return FILE_OPERATION_TYPE_DISALLOW  ;
  // Open given filename for reading
  newCifFile = new CifFileIo;
  if ((ret = newCifFile->OpenFile(filename, type))!= FILE_OPERATION_SUCCEED ) {
    delete newCifFile;
    return ret;
  }

  datablock_no = GetIndex(datablock_name);
  if (datablock_no == -1) return CIF_DATABLOCK_NOT_EXIST;

  dic_no = GetDataBlockDictionaryIndex(datablock_no);

  if (dictionary != NULL && strcmp(dictionary,"")) dic = new CifString(dictionary);
  else dic  = NULL;
  if (version != NULL && strcmp(version,"")) dic_version = new CifString(version);
  else dic_version = NULL;
  if (dic_no != -1)
    _dataBlocks[datablock_no].WriteDataBlock(newCifFile, write_comment, esdFlag,
					    dic, dic_version,
					    &_dataBlocks[dic_no]);
  else
    _dataBlocks[datablock_no].WriteDataBlock(newCifFile, write_comment,esdFlag,
					    dic, dic_version);
  newCifFile->CloseFile();
  delete newCifFile;
  if (dic != NULL) 
    delete dic;
  if (dic_version != NULL)
    delete dic_version;
  return SUCCEED;
}

int CifFile:: MergeDataBlock(const char *new_blockname,
			       const int index1, const int index2)
{
  CifDataBlock *newblock;
  CifString message;

  int index;
  if (index1 < 0 || index1 >= _dataBlocks.Length() ||
      index2 < 0 || index2 >= _dataBlocks.Length() ||
      GetDataBlockDictionaryIndex(index1) != GetDataBlockDictionaryIndex(index2) ) 
    return -1;
  else {

    newblock = new CifDataBlock(_dataBlocks[index1]);
    
    if ((index = GetIndex(new_blockname)) != -1) {
      message.Clear();
      message += "Repeated datablock name at index ";
      message +=  index;
      message += "in file \'";
      message += _dataBlocks[index]._fileName;
      message += "\'";
      _dataBlocks[index].ErrorMessage(CIF_ERROR, 
					-1, message);
    }
      
    newblock->SetDatablockName(new_blockname);
    newblock->Merge(&_dataBlocks[_dataBlocks[index1]._dictionaryIndex], &_dataBlocks[index2]);
    if (_dataBlocks[index1]._fileName != _dataBlocks[index2]._fileName )
      newblock->_fileName.Clear();
    
    newblock->_fileOffset = 0;
    _dataBlocks.Add(*newblock);
    delete newblock;
    return _dataBlocks.Length()-1;
/*
    _dataBlocks[index1].SetDatablockName(new_blockname);
    _dataBlocks[index1].Merge(&_dataBlocks[index2]);
    _dataBlocks.DeleteAt(index2, 1);
    return SUCCEED;
*/
  }
}

void CifFile:: DeleteDataBlock(const int index)
{
  if (index < 0 || index >= _dataBlocks.Length())
    return;
  _dataBlocks.DeleteAt(index, 1);
  for (unsigned i=0; i< _dataBlocks.Length(); i++) {
    if (_dataBlocks[i]._dictionaryIndex == index) {
      _dataBlocks[i]._dictionaryIndex = -1;
      _dataBlocks[i]._dictionaryName.Copy("");
    }
    else if (_dataBlocks[i]._dictionaryIndex > index) 
      _dataBlocks[i]._dictionaryIndex--;
  }
}

void CifFile:: CheckDataBlock(const int index)
{
  CifDataBlock *dic;

  if (index < 0 || index >= _dataBlocks.Length())
    return;
  
  dic = GetDictionaryDataBlock(index);
  if (dic != NULL) 
    _dataBlocks[index].CheckDataBlock(dic, FALSE);
  else return;
}
CifDataBlock *CifFile::GetDictionaryDataBlock(const int index)
{
  int dicIndex;

  dicIndex = _dataBlocks[index]._dictionaryIndex;
  if ((dicIndex >=0 || dicIndex < _dataBlocks.Length() ) &&
      !CompareNoCase(_dataBlocks[dicIndex]._dataBlockName, 
		     _dataBlocks[index]._dictionaryName))
    return &_dataBlocks[dicIndex];
  else return NULL;
}


void CifFile::PermanentWrite(const char *fileName)
{
  int i, len, dicIndex;
  FILE *fp;
  DIR *dirp;
  CifString perFileName, dicFileName, dicName, message, dirName;
  
  dicName.Clear();
  for (i=0; i< _dataBlocks.Length(); i++) {
    if (!strcmp(_dataBlocks[i]._fileName.Text(), fileName)) {
      if (!strcmp(dicName.Text(),"")) 
	dicName.Copy(_dataBlocks[i]._dictionaryName);
      else {
	if (CompareNoCase(dicName, _dataBlocks[i]._dictionaryName)) {
	  message.Clear();
	  message += "Different dictionary name from the other datablock with the same file name";
	  _dataBlocks[i].ErrorMessage(CIF_ERROR, -1, message.Text());
	  break;
	}
      }
    }
  }
  if (i != _dataBlocks.Length()) return;
  dicIndex = GetIndex(dicName);
  if (dicIndex != -1)
    dicFileName.Copy(_dataBlocks[dicIndex]._fileName);
  else dicFileName.Clear();
    
  GetPermanentFileName(fileName, dicFileName, &perFileName, &dirName);
  dirp = opendir(dirName.Text());
  if (dirp == NULL) {
    i = mkdir(dirName.Text(), 0777);
    if (i == -1) {
      fprintf(stderr, "Creating directory %s failed\n", dirName.Text());
      return;
    }
    chmod (dirName.Text(), 0777);
  }
  else closedir(dirp);

  fp = fopen(perFileName.Text(), "w");
  if (fp != NULL) {
    //      _globalInformation.PermanentWrite(fp);
    len = 0;
    for (i=0; i< _dataBlocks.Length(); i++)
      if (!strcmp(_dataBlocks[i]._fileName.Text(), fileName))
	len ++;
    fprintf(fp, "%d\n", len);
    for (i=0; i< _dataBlocks.Length(); i++) {
      if (!strcmp(_dataBlocks[i]._fileName.Text(), fileName))
	_dataBlocks[i].PermanentWrite(fp);
    }
    fclose(fp);
    chmod (perFileName.Text(), 0666);
  }
  else
    fprintf(stderr, "Writing permanent file %s failed\n", perFileName.Text());
}


int CifFile::PermanentRead(const char *fileName, const char *dicFileName,
			    const char *dicDataBlockName)
{
  struct stat  stat1, stat2, dicStat1, dicStat2;
  int i, j, ret_stat1 = 1, ret_stat2 = 1, dicIndex, dicIndex1;
  CifString perFileName, dicPerFileName, dirName, dicName;
  FILE *fp;
  int tmplen;
  CifDataBlock tmpblock;
  
  if (dicFileName == NULL || !strcmp(dicFileName,""))
    dicName.Clear();
  else dicName.Copy(dicFileName);
      
  GetPermanentFileName(fileName, dicName, &perFileName, &dirName);
  if (stat(perFileName.Text(), &stat1) == 0 && stat(fileName, &stat2) == 0 ) {
    if (dicDataBlockName != NULL && strcmp(dicDataBlockName,"") ) {
      dicIndex = GetIndex(dicDataBlockName);
      if (dicIndex != -1) {
	ret_stat1 = stat(_dataBlocks[dicIndex]._fileName.Text(), &dicStat1);
	dicIndex1 = GetIndex(_dataBlocks[dicIndex]._dictionaryName);
	if (dicIndex1 != -1)
	  GetPermanentFileName(_dataBlocks[dicIndex]._fileName.Text(),
			       _dataBlocks[dicIndex1]._fileName, &dicPerFileName,
			     &dirName);
	ret_stat2 = stat(dicPerFileName.Text(), &dicStat2);
       
      }
    }
    if (stat1.st_mtime >= stat2.st_mtime &&
	(dicDataBlockName == NULL || 
	 ret_stat1 == 0 && dicStat1.st_mtime <= stat1.st_mtime &&
	 ret_stat2 == 0 && dicStat2.st_mtime <= stat1.st_mtime )) {
      fp = fopen(perFileName.Text(), "r");
      if (fp != NULL) {
	fscanf(fp, "%d\n", &tmplen);
	if (tmplen > 0) _dataBlocks.GrowBy(tmplen);
	for (i=0; i< tmplen; i++) {
	  tmpblock.DeleteElement();
	  tmpblock.PermanentRead(fp);
	  _dataBlocks.Add(tmpblock);
	}
	fclose(fp);
	for (i=0; i<_dataBlocks.Length(); i++) {
	  for (j=0; j<_dataBlocks.Length(); j++)
	    if (!CompareNoCase(_dataBlocks[i]._dictionaryName, _dataBlocks[j]._dataBlockName))
	      break;
	  if (j != _dataBlocks.Length()) 
	    _dataBlocks[i]._dictionaryIndex = j;
	  else return FALSE;
	}
	return TRUE;
      }
    }
  }
  return FALSE;
  
}


CifDataBlock *CifFile::AddDatablock(const int dictionaryIndex,
				    const char *datablockName)
{
  CifDataBlock *datablock;
  CifString message, *title;
  //  int index;

  if (datablockName == NULL || !strcmp(datablockName, ""))
    return NULL;
  if ( GetIndex(datablockName) != -1) {
/*
  if ((index = GetIndex(datablockName)) != -1) {
    message.Clear();
    message += "Datablock \'";
    message += datablockName;
    message += "\' has existed already";
    _dataBlocks[index].ErrorMessage(CIF_ERROR, "",
		    datablockName, -1, message.Text());
*/
    return (CifDataBlock *) NULL;
  }
  else {
    if (dictionaryIndex< 0 || dictionaryIndex >= _dataBlocks.Length()) {
      message.Clear();
      message += "Dictionary does not exist";
      _dataBlocks[0].ErrorMessage(CIF_ERROR, -1, message.Text());
	    
      return (CifDataBlock *) NULL;
    }
    else {
      datablock = new CifDataBlock;
      datablock->_dataBlockName.Copy(datablockName);
      datablock->_dictionaryIndex = dictionaryIndex;
      title = _dataBlocks[dictionaryIndex].GetDictionaryTitle();
      if (title != NULL)
	datablock->_dictionaryName.Copy(title->Text());
      title = _dataBlocks[dictionaryIndex].GetDictionaryVersion();
      if (title != NULL)
	datablock->_dictionaryVersion.Copy(title->Text());
      _dataBlocks.Add(*datablock);
      delete datablock;
      return &_dataBlocks[_dataBlocks.Length()-1];
    }
  }
}


CifCategory *CifFile::AddCategory(const int datablockIndex,
					       const char *categoryName)
{
  //  CifString message;
  
  if (categoryName == NULL || !strcmp(categoryName,""))
    return (CifCategory *) NULL;
  if (datablockIndex< 0 || datablockIndex >= _dataBlocks.Length()) 
    return (CifCategory *) NULL;

  return  _dataBlocks[datablockIndex].
    AddCategory(&_dataBlocks[_dataBlocks[datablockIndex]._dictionaryIndex],
		      categoryName);
}
CifDataItem *CifFile::AddDataItem(const int datablockIndex,
				     const int categoryIndex,
				     const char *itemName)
{
  //  CifString message;
  
  if (itemName == NULL || !strcmp(itemName,""))
    return (CifDataItem *) NULL;
  if (datablockIndex< 0 || datablockIndex >= _dataBlocks.Length()) {
    return (CifDataItem *) NULL;
  }
  return _dataBlocks[datablockIndex].
    AddDataItem(&_dataBlocks[_dataBlocks[datablockIndex]._dictionaryIndex],
		categoryIndex, itemName);
}


int CifFile::AddRow(const int dataBlockIndex, const int categoryIndex)
// ----------------------------------------------------------------------
//   AddDataItem() Gets itemValue from itemValues array
// --------------------------------------------------------------------- 
{
  if (dataBlockIndex< 0 || dataBlockIndex >= _dataBlocks.Length()) {
    return -1;
  }
  return _dataBlocks[dataBlockIndex].AddRow(categoryIndex);
}

