/*
FILE:     CifFileIo.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 CifFileIo

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

#include "CifFileIo.h"
#include "CifCategory.h"
#include "CifDataBlock.h"
// *********************************************************************
//      Constructor, destructor, DeleteElement(), 
//      operators,  and Print()
// *********************************************************************


CifFileIo::CifFileIo()
// ---------------------------------------------------------------------
//   CifFileIo(): contructor initializes
// --------------------------------------------------------------------- 
{
  _token.Clear();
  _aliasName.Clear();
  _tokenType = 0;
  _syntaxError = FALSE;
  _firstSyntaxErrorLine = -1;
  _saveMark = 0;
  _tokenStatus = CIF_DATA_IS_VALID;
}
CifFileIo::CifFileIo(char *filename, char filetype)
// ---------------------------------------------------------------------
//   CifFileIo(): contructor initializes and open file
// --------------------------------------------------------------------- 
{
  _token.Clear();
  _aliasName.Clear();
  _tokenType = 0;
  _syntaxError = FALSE;
  _firstSyntaxErrorLine = -1;
  _tokenStatus = CIF_DATA_IS_VALID;
  _saveMark = 0;
  OpenFile(filename, filetype);
  
}

CifFileIo::CifFileIo(CifString filename, char filetype)
// ---------------------------------------------------------------------
//   CifFileIo(): contructor initializes and open file
// --------------------------------------------------------------------- 
{
  _token.Clear();
  _aliasName.Clear();
  _tokenType = 0;
  _syntaxError = FALSE;
  _firstSyntaxErrorLine = -1;
  _tokenStatus = CIF_DATA_IS_VALID;
  _saveMark = 0;
  OpenFile(filename.Text(), filetype);
}

CifFileIo::~CifFileIo()
// ---------------------------------------------------------------------
//   CifFileIo(): destructor
// --------------------------------------------------------------------- 
{
}


int CifFileIo::GetNextCifToken(CifDataBlock *datablock, CifDataBlock *dic)
// ------------------------------------------------------------------------
//   GetNextCifToken(): Get the next token and put it into the token buffer 
//                      return its _tokenType
//   Possible return itemValues: 
//       EOF                       end of file
//       CIF_KEYWORD_GLOBAL        reserved CIF keyword "global_"
//       CIF_KEYWORD_DATA          reserved CIF keyword "data_"
//       CIF_KEYWORD_SAVE_TRUE     reserved CIF keyword "save_"
//       CIF_KEYWORD_SAVE_FALSE    reserved CIF keyword "save_"
//       CIF_KEYWORD_INCLUDE       reserved CIF keyword "include_"
//       CIF_KEYWORD_LOOP          reserved CIF keyword "loop_"
//       CIF_ITEM_NAME             general keyword starts with '_'
//       CIF_STRING_VALUE          char strings or character
//       CIF_DEFINITION_ITEM       CIF item definition  "save__itemName"
//       CIF_DEFINITION_CATEGORY   CIF category definition "save_categoryName"
// ----------------------------------------------------------------------- */
{
  int c, prev_c, i, after_c;

  // Cleans token buffer 
  _tokenStatus = CIF_DATA_IS_VALID;
  _token.Clear();

  // Handle white space
  c = ' ';
  do {
    do {
      prev_c = c;
      c = GetChar();
    } while (c != EOF && ( c == ' ' || c == '\t' || c == '\n' )) ;
    
    // Comment
    while (c == '#') {
      do {
	prev_c = c;
	c = GetChar();
      } while (c != EOF && c != '\n');
      if (c != EOF) c = GetChar();
    }
  } while (c != EOF && (( c == ' ' || c == '\t' || c == '\n' ) ||
			( (c == '\'' || c == '\"' ) && 
			  (prev_c != ' ' && prev_c != '\t' && prev_c != '\n')))) ;
  // End of File
  
  if (c == EOF)  
    _tokenType = EOF;
  
  // Keywords 

  else if (c == '_') {
    do {
      if (c != EOF) {
	_token.InsertAt(_token.Length(), c);
	c = GetChar();
      }
    } while (c != EOF && c != '\n' && c != '\t' && c != ' ');
    _tokenType = CIF_ITEM_NAME;
    if (dic != NULL) {
      _aliasName.Copy(_token);
      dic->GetItemNameFromAlias(&_aliasName, &_token);
    }
    
    if (c != EOF) Seek((long) -1, 1);
  }
  
  // ItemValues or the reserved keywords
  // ItemValues are all assumed to be string, decide details later

  else { 
    
    // Multiple words 
    if (c == '\"' || c == '\'') { 
      if (c == '\"') {
	do {
	  prev_c = c;
	  c = GetChar();
	  if (c != EOF)
	    _token.InsertAt(_token.Length(), c);
	  if (c == '\"') {
	    after_c = GetChar();
	    if (after_c != ' ' && after_c != '\t' && after_c != '\n') {
	      if (after_c != '\"') {
		_token.InsertAt(_token.Length(), after_c);
		c = after_c;
	      }
	      else Seek((long) -1, 1);
	    }
	  }
	} while (c != EOF && c != '\n' &&
		 ((c != '\"' || after_c != ' ' && after_c != '\t' && after_c != '\n' 
		   || prev_c == '\\')));
	if (c != '\"') 
	  SetSyntaxError(datablock, "Unmatched \"");
	  
      }
      else {
	do {
	  prev_c = c;
	  c = GetChar();
	  if (c != EOF)
	    _token.InsertAt(_token.Length(), c);
	  if (c == '\'') {
	    after_c = GetChar();
	    if (after_c != ' ' && after_c != '\t' && after_c != '\n') {
	      if (after_c != '\'') {
		_token.InsertAt(_token.Length(), after_c);
		c = after_c;
	      }
	      else Seek((long) -1, 1);
	    }
	  }
	} while (c != EOF && c != '\n' && 
		 ((c != '\'' || after_c != ' ' && after_c != '\t' && after_c != '\n' 
		   || prev_c == '\\')));
	if (c != '\'')
	  SetSyntaxError(datablock, "Unmatched \'");
      }

      // delete the ending double quote or newline
	if (c != EOF) _token.DeleteAt(_token.Length()-1,1);  
      _tokenType = CIF_STRING_VALUE;
    }


    // Multiple lines 
    else if (c == ';') {
      do {
	prev_c = c;
	c = GetChar();
	if (c != EOF) 
	  _token.InsertAt(_token.Length(), c);
      } while (c != EOF && (c != ';' || prev_c != '\n'));
      // delete beginning and ending newlines and semicolon
	if (_token.Text()[0] == '\n')
	  _token.DeleteAt(0,1);  
      if (c != EOF) _token.DeleteAt(_token.Length()-2,2);  
      _tokenType = CIF_STRING_VALUE;
      if (c != EOF) Seek((long) 1, 1);
    }

    // Single word
    else { 
      do {
	if (c != EOF) {
	  _token.InsertAt(_token.Length(), c);
	  c = GetChar();
	}
      } while (c != EOF && c != '\n' && c != '\t' && c != ' ');
      if (c != EOF) Seek((long) -1, 1);

      // Reserved Keyword global_
      if (!CompareToken(CIF_RESERVED_KEYWORD_GLOBAL))  
	_tokenType = CIF_KEYWORD_GLOBAL;

      // Reserved Keyword data__
      else if (!CompareToken(CIF_RESERVED_KEYWORD_DATA) && 
	       CompareToken(CIF_DDL_CATEGORY_BLOCK))  {
	_tokenType = CIF_KEYWORD_DATA;
	_categoryNamesInSaveBlock.Clear();
      }
      // Reserved Keyword save
      else if (!CompareToken(CIF_RESERVED_KEYWORD_SAVE))  {
	_categoryNamesInSaveBlock.Clear();
	if (_saveMark == TRUE) {
	  if (_token.Length() == strlen(CIF_RESERVED_KEYWORD_SAVE)) {
	    _tokenType = CIF_KEYWORD_SAVE_FALSE;
	    _saveMark = FALSE;
	  }
	  else {
	    SetSyntaxError(datablock, "Reserved word \'save_\' missing");
	    for (i=0; i<_token.Length(); i++)
	      if (_token.Text()[i] == CIF_DATA_JOIN_CHARACTER) 
		break;
	    if (i == _token.Length()) 
	      _tokenType = CIF_DEFINITION_CATEGORY;
	    else
	      _tokenType = CIF_DEFINITION_ITEM;
	  }
	}
	else {
	  if (_token.Length() >strlen(CIF_RESERVED_KEYWORD_SAVE)) {
	    _saveMark = TRUE;
	    for (i=0; i<_token.Length(); i++)
	      if (_token.Text()[i] == CIF_DATA_JOIN_CHARACTER) 
		break;
	    _saveOffset =  _inMemoryOffset - (long) _token.Length() + 1;
	    if (i == _token.Length())  
	      _tokenType = CIF_DEFINITION_CATEGORY; 
	    else
	      _tokenType = CIF_DEFINITION_ITEM;
	  }
	  else {
	    _tokenType = CIF_KEYWORD_SAVE_FALSE;
	    SetSyntaxError(datablock, "Reserved word \'save\' redundent");
	  }
 	}
      }
      // Reserved Keyword include_
      else if (!CompareToken(CIF_RESERVED_KEYWORD_INCLUDE))  
	_tokenType = CIF_KEYWORD_INCLUDE;
      // Reserved Keyword loop_
      else if (!CompareToken(CIF_RESERVED_KEYWORD_LOOP))  
	_tokenType = CIF_KEYWORD_LOOP;
 
      // Assuning the rest are string itemValues, becuase data_type is unknown
      else {
	_tokenType = CIF_STRING_VALUE;
	if (!Compare(_token.Text(), (char *) CIF_DATA_NULL_CHAR))
	  _tokenStatus = CIF_DATA_IS_NULL;
	else if (!Compare(_token.Text(), (char *) CIF_DATA_NOT_APPROPRIATE_CHAR)) 
	  _tokenStatus = CIF_DATA_NOT_APPROPRIATE;
      }
    }
  }
  return _tokenType;
}


void CifFileIo:: GetCifLoopedValue(CifDataBlock *cifdic, CifDataBlock *datablock,
				   CifCategory *newCategory)
//--------------------------------------------------------------------------
//   Purpose:   GetCifLoopedItemValue() Get CIF looped ItemValue
//   Parameter: CifDataBlock *cifdic,
//              ReVarCifArray<CIF_ALIAS> alias list
//   Return:    Type of next _token
//---------------------------------------------------------------------------
{
  int keyword_id, i, categoryNameFound;
  int *keywordList, nkeyword;
  int itemValue_no, curr_itemValue_no;
  long offset = 0;
  int curr_keyword;
  CifDataItem tmpitem;
  CifItemValue itemValue, final_itemValue;
  CifString keyword;
  CifString message;
  //  int category_index, item_index;

  offset = GetInMemoryOffset();
  // Make sure loop_ is following with at least one keyword
    GetNextCifToken(datablock, cifdic);

  if (_tokenType != CIF_ITEM_NAME) {
    SetSyntaxError(datablock, "Item name expected");
    return;
  }
  categoryNameFound = FALSE;

  // Calculates number of keywords in this data block
  nkeyword = 1;
  while (_tokenType == CIF_ITEM_NAME) { 
    nkeyword ++;
    GetNextCifToken(datablock, cifdic);
  }
  keywordList = new int[nkeyword+1];
  Seek(-1 * (GetInMemoryOffset() - offset), 1);
  // Get looped keyword list 
  nkeyword = 0;
  keyword_id = 1;
  do {
    tmpitem.DeleteElement();
    offset = GetInMemoryOffset();
    GetNextCifToken(datablock, cifdic);
    if (_tokenType == CIF_ITEM_NAME) {
      if (categoryNameFound != TRUE)
	newCategory->SetCategoryName(_token.Text());
      if (!categoryNameFound) {
	if (newCategory->_categoryName.Length() < _token.Length()-2) {
	  categoryNameFound = TRUE;
	  CheckRepeatedCategoryInFile(_token, datablock);
	}
      }
      if (keyword_id != -1 && newCategory->_items.Length() != 0) {
	for (i=0; i<newCategory->_items.Length() ; i++)
	  if (!CompareNoCase(newCategory->_items[i]._itemAttribute._name, _token))
	    break;
	if (i != newCategory->_items.Length()) {
	  keyword_id = -1;
	  SetSyntaxError(datablock, "Duplicate item names");
	}
      }
      if (keyword_id != -1) {
	if (cifdic == NULL)
	  keyword_id = 1;
      }
      if (keyword_id != -1) {
	keyword.Copy(_token.Text());
	if (_token.Length() > newCategory->_categoryName.Length() +2 &&
	    !CompareNoCase(&_token.Text()[1], newCategory->_categoryName.Text(), 
			   newCategory->_categoryName.Length()) &&
	    _token.Text()[newCategory->_categoryName.Length()+1] == '.') {
	  
	  if (newCategory->_categoryName.Length() < _token.Length() -2 &&
	      !CompareNoCase(&_token.Text()[1], newCategory->_categoryName, 
			     newCategory->_categoryName.Length()) &&
	      
	      _token.Text()[newCategory->_categoryName.Length()+1] == '.') {
	    if (CompareNoCase(_aliasName, _token))
	      tmpitem.SetKeyword(newCategory->_categoryName.Text(),
				 &_token.Text()[newCategory->_categoryName.Length()+2],
				 _aliasName.Text()); 
	    else
	      tmpitem.SetKeyword(newCategory->_categoryName.Text(),
				 &_token.Text()[newCategory->_categoryName.Length()+2],
				 NULL); 
	  }
	  else
	    tmpitem.SetKeyword(newCategory->_categoryName.Text(),
			       _token.Text(), _aliasName.Text()); 
	  if (cifdic != datablock) 
	    cifdic->GetItemInfo(&tmpitem);
	  
	  newCategory->_items.Add(tmpitem);
	} else {
	  message.Clear();
	  message += "Item name \'";
	  message += _token;
	  message += "\' is not in the same category group \'";
	  message += newCategory->_categoryName;
	  message += '\'';
	  SetSyntaxError(datablock, message);
	  keyword_id = -1;
	}
      }
      if (keyword_id == -1)
	keywordList[nkeyword] = -1;
      else
	keywordList[nkeyword] = newCategory->_items.Length()-1;
      keyword_id = 1;
      nkeyword++;
    }
  } while (_tokenType == CIF_ITEM_NAME);
  
  if (_tokenType == EOF) {
    SetSyntaxError(datablock, "Item value expected");
  }
  
  /* 
   * Get looped itemValues list 
   */
  curr_keyword = 0;
  Seek(-1 * (GetInMemoryOffset() - offset), 1);
  do {
    keyword_id = keywordList[curr_keyword];
    
    if (keyword_id != -1) {
      itemValue_no = newCategory->_items[keyword_id]._itemAttribute._structureNumValue;
      if (newCategory->_items[keyword_id]._itemAttribute._structureNumValue > 1)
	final_itemValue._structureNumValue = 
	  newCategory->_items[keyword_id]._itemAttribute._structureNumValue;
    } else {
      itemValue_no = 1;
    }
    curr_itemValue_no = 0;
    
    while (_tokenType != EOF && curr_itemValue_no < itemValue_no) {
      GetNextCifToken(datablock, cifdic);
      if (keyword_id != -1) {
	if (_tokenType == CIF_STRING_VALUE) {
	  if (GetTokenStatus() == CIF_DATA_IS_NULL) 
	    itemValue.UpdateItemValue(newCategory->_items[keyword_id]._itemAttribute._dataType,
				      CIF_DATA_IS_NULL, (char *) NULL);
	  else if (GetTokenStatus() == CIF_DATA_NOT_APPROPRIATE) 
	    itemValue.UpdateItemValue(newCategory->_items[keyword_id]._itemAttribute._dataType,
				      CIF_DATA_NOT_APPROPRIATE, (char *) NULL);
	  else 
	    itemValue.UpdateItemValue(newCategory->_items[keyword_id]._itemAttribute._dataType,
				      CIF_DATA_IS_VALID, _token.Text());
	  
	  if (newCategory->_items[keyword_id]._itemAttribute._structureNumValue > 1) {
	    final_itemValue._status = CIF_DATA_IS_VALID;
	    final_itemValue._data._arrayVal->Add(itemValue);
	  }
	}
	else break;
      }
      curr_itemValue_no ++;
    }
    if (curr_itemValue_no > 0) {
      if (keyword_id != -1) {
	if (newCategory->_items[keyword_id]._itemAttribute._structureNumValue <= 1)
	  newCategory->_items[keyword_id].AppendItemValue(&itemValue);
	else 
	  newCategory->_items[keyword_id].AppendItemValue(&final_itemValue);
      }
      if (_tokenType == CIF_STRING_VALUE)      curr_keyword ++;
      if (curr_keyword == nkeyword) curr_keyword = 0;
      keyword_id = keywordList[curr_keyword];
    }
  }  while (_tokenType == CIF_STRING_VALUE);
  if (curr_keyword != 0) {
    SetSyntaxError(datablock,
		   "Number of item values does not match number of item names");
    
    for (; curr_keyword < nkeyword; curr_keyword++) {
      keyword_id = keywordList[curr_keyword];
      if (keyword_id != -1) {
	itemValue.UpdateItemValue(newCategory->_items[keyword_id]._itemAttribute._dataType,
				  CIF_DATA_IS_NULL, (char *) NULL);
	newCategory->_items[keyword_id].AppendItemValue(&itemValue);
      }
    }
  }
  delete [] keywordList;
}


void CifFileIo::GetCifNonLoopedValue(CifDataBlock *cifdic, 
				       CifDataBlock *datablock,
				       CifCategory *newCategory)
//--------------------------------------------------------------------------
//   Purpose:   GetCifNonLoopedItemValue() Get Cif Non Looped ItemValue
//   Parameter: CifDataBlock *cifdic,
//              CifFileIo *dic_files
//              ReVarCifArray<CIF_ALIAS> alias list
//   Return:    type for next _token
//---------------------------------------------------------------------------
{
  int keyword_id, i, categoryNameFound = FALSE;
  long offset;
  //  CifString tmptoken;
  CifDataItem tmpitem;
  CifItemValue itemValue; 
  CifString keyword;

  newCategory->SetCategoryName(_token.Text());

  keyword_id = -1;
  while (_tokenType == CIF_ITEM_NAME &&
	 !CompareNoCase(&_token.Text()[1], newCategory->_categoryName,
			newCategory->_categoryName.Length())  &&
	 (_token.Length() == newCategory->_categoryName.Length()+1 ||
	  _token.Text()[newCategory->_categoryName.Length()+1] == CIF_DATA_JOIN_CHARACTER )) {
    tmpitem.DeleteElement();
    if (!categoryNameFound)
      newCategory->SetCategoryName(_token.Text());
    if (newCategory->_categoryName.Length() < _token.Length()-2) {
      if (!categoryNameFound) {
	categoryNameFound = TRUE;
	CheckRepeatedCategoryInFile(_token, datablock);
      }
    }

    // Check keyword in the table or not
    if (newCategory->_items.Length() != 0) {
      for (i=0; i<newCategory->_items.Length() ; i++)
	if (!CompareNoCase(newCategory->_items[i]._itemAttribute._name, _token))
	  break;
      if (i != newCategory->_items.Length()) {
	keyword_id = -1;
	SetSyntaxError(datablock, "Duplicate item names");
      }
    }
    else i = 0;
    if (i == newCategory->_items.Length()) 
      keyword_id = newCategory->_items.Length();

    if (keyword_id != -1) {
      keyword.Copy(_token.Text());
      
      if (newCategory->_categoryName.Length() < _token.Length() -2 &&
	  !CompareNoCase(&_token.Text()[1], newCategory->_categoryName, 
			 newCategory->_categoryName.Length()) &&
	  _token.Text()[newCategory->_categoryName.Length()+1] == '.') {
	if (CompareNoCase(_aliasName, _token))
	  tmpitem.SetKeyword(newCategory->_categoryName.Text(),
			     &_token.Text()[newCategory->_categoryName.Length()+2],
			     _aliasName.Text()); 
	else
	  tmpitem.SetKeyword(newCategory->_categoryName.Text(),
			     &_token.Text()[newCategory->_categoryName.Length()+2],
			     NULL); 
      } else {
	tmpitem.SetKeyword(newCategory->_categoryName.Text(),
			   _token.Text(), _aliasName.Text());
      } 
      if (cifdic != datablock) 
	cifdic->GetItemInfo(&tmpitem);
      newCategory->_items.Add(tmpitem);
      
    }
    // Get ItemValue
    offset = GetInMemoryOffset();
    GetNextCifToken(datablock, cifdic);
    if (keyword_id != -1 && _tokenType == CIF_STRING_VALUE) {
      if (GetTokenStatus() == CIF_DATA_IS_NULL) 
	itemValue.UpdateItemValue(newCategory->_items[keyword_id]._itemAttribute._dataType,
				  CIF_DATA_IS_NULL, (char *) NULL);
      else if (GetTokenStatus() == CIF_DATA_NOT_APPROPRIATE) 
	itemValue.UpdateItemValue(newCategory->_items[keyword_id]._itemAttribute._dataType,
				  CIF_DATA_NOT_APPROPRIATE, (char *) NULL);
      else 
	itemValue.UpdateItemValue(newCategory->_items[keyword_id]._itemAttribute._dataType,
				  CIF_DATA_IS_VALID, _token.Text());
    }
    else if (keyword_id != -1){
      itemValue.UpdateItemValue(newCategory->_items[keyword_id]._itemAttribute._dataType,
				CIF_DATA_IS_NULL, (char *) NULL);
      SetSyntaxError(datablock, "Item value expected");
      // Roll back one _token, assuming the itemValue is missing
      Seek((offset - GetInMemoryOffset()) , 1); 
    }
    if (keyword_id != -1) 
      newCategory->_items[keyword_id].AppendItemValue(&itemValue);
    
    GetNextCifToken(datablock, cifdic);
  }
}


int CifFileIo::PrintF(const char *fmt ...)
// ---------------------------------------------------------------------
//   PrintF(): performs print CIF file
//         fmt %k %K :keyword 
//             %S : CifString   
//             the rest is the same as printf
//   Parameter: const char *fmt: Format for the following parameters
//            ... variables to print
//   return itemValue: Failure or number of characters was printed
// --------------------------------------------------------------------- 
{
  int  i, j, nchar, cval, ret,  multipleline;
  long ival;
  char tmpstring[100];
  //  CifString Sval;
  double dval;
  const char *p;
  char *sval;


  va_list ap;
  va_start(ap, fmt);

  if (fmt == NULL) return(FAILURE);

  // Calculate number of input arguments
  nchar = 0;
  ret = 1;
  for (p=fmt; *p && ret; p++) {

    if (*p != '%') {
      ret = PutChar(*p);
      continue;
    }

    // pointer forward
    ++p;
    // for ld or lf pointer p forward
    if (*p == 'l' && (*(p+1) == 'd' ||  *(p+1) == 'f')) ++p;
    switch(*p) {

      // Character:
    case 'c':
      cval = va_arg(ap, int);
      if (CountCurrLineChar() >= CIF_LINE_LENGTH -2)
	PutChar('\n');
      ret = PutChar(cval);
      if (ret)	nchar++;
      break;

      // Integer:
    case 'd':
      ival = va_arg(ap, long);
      memset(tmpstring, 0, 100);
      sprintf(tmpstring,"%d\0", ival);

      if (CountCurrLineChar()+strlen(tmpstring) >= CIF_LINE_LENGTH)
	PutChar('\n');
      for (i=0; i<strlen(tmpstring) && ret; i++, nchar ++)  {
	ret = PutChar(tmpstring[i]);
      }
      break;

      // Double:
    case 'f':
      dval = va_arg(ap, double);
      memset(tmpstring, 0, 100);
      sprintf(tmpstring,"%lf", dval);
      for (i=0; i<strlen(tmpstring); i++)
	if (tmpstring[i] == '.') break;
      for (j=strlen(tmpstring)-1; j > i+1 && isdigit(tmpstring[j]) && 
	   tmpstring[j] == '0' ; j--)
	tmpstring[j] = 0;
//      strncpy(&tmpstring[strlen(tmpstring)],"  ",2);
      if (CountCurrLineChar()+strlen(tmpstring) >= CIF_LINE_LENGTH)
	PutChar('\n');
      for (i=0; i<strlen(tmpstring) && ret; i++, nchar ++) {
	ret = PutChar(tmpstring[i]);
      }
      break;
      
      // Character CifString: CifString 
    case 's':
      sval = va_arg(ap, char*);
      PrintStrval(sval, &multipleline);
      break;

      // Character CifString: CifString 
/*
    case 'S':
      Sval = va_arg(ap, CifString);
      PrintStrval(Sval, &multipleline);
      break;
*/
      // keyword
    case 'k':
	sval = va_arg(ap, char*);
      FileIo::PrintF("%s",sval);
      break;
      // keyword CifString
/*
    case 'K':
      Sval = va_arg(ap, CifString );
      FileIo::PrintF("%S",Sval);
      break;
*/
      // Others
    default:
      ret = PutChar(*p);
      break;
    }
  }
  va_end(ap);
  return(nchar);
}

int CifFileIo::PrintComment(char* instrval, int tabno)
// ---------------------------------------------------------------------
//   PrintComment(): Print Comment for CIF file
//   Parameter: char *instrval input string
//              int tabno: number of tab in the front
//   return itemValue: Failure or SUCCEED
// --------------------------------------------------------------------- 
{
  int  i, j, k, str_len, linelimit;
  
  if (instrval == NULL) return FAILURE;
  str_len = strlen(instrval);
  for (i=0; i<str_len; i++) {
    linelimit = CIF_LINE_LENGTH;
    PutChar('#');
    for (j=0; j<tabno; j++) {
      PutChar('\t');
      linelimit -= (linelimit%8);
    }
    for (j=i+1; j<str_len &&  instrval[i] != '\n' && j -i < linelimit && 
	 instrval[j] != '\n'; j++);
    if (instrval[i] == '\n') j = i;
    if (j- i == linelimit && instrval[j] != ' ' && instrval[j] != '\t' &&
	instrval[j] != '\n') {
      for (k=j; k< str_len && k >i && instrval[k] != ' ' && 
	   instrval[k] != '\n' && instrval[k] != '\t'; k--);
      if (k != i) j = k;
    }
    for (k=i; k<j && k<str_len; k++) {
      if (k!=i || instrval[k] != ' ') 
	PutChar(instrval[k]);
    }
    PutChar('\n');
    if (j != i+1)
      i += (j-i);
  }
  return SUCCEED;
}

void CifFileIo::PrintSectionLine()
// ---------------------------------------------------------------------
//   PrintSectionLine(): Print section line
// --------------------------------------------------------------------- 
{
  PutChar('#');
  for (unsigned i=0; i< CIF_LINE_LENGTH -5; i++)
    PutChar('-');
  PutChar('\n');
}
int CifFileIo::PrintStrval(char* instrval, int *multipleline)
// ---------------------------------------------------------------------
//   PrintStrVal(): Print CifString ItemValue for CIF file, make sure the itemValue
//                  does not exceed 80 characters, and put quotes or
//                  semicolon if necessary (according to syntax)
//   Return itemValue: FAILURE or SUCCEED
// --------------------------------------------------------------------- 
{
  int i,j, nchar, tempnchar, curr_pos;
  int line_limit;

  if (instrval == NULL) return FAILURE;
  line_limit = CIF_LINE_LENGTH;
  *multipleline = FALSE;

  nchar =0;
  for (i=0; i<strlen(instrval); i++) {
    if (instrval[i] == '\t') nchar += (8- nchar %8);
    else nchar ++;
    if (instrval[i] == '\n' || instrval[i] == '"' || instrval[i] == '\'') 
      *multipleline = TRUE;
  }
  if (strlen(instrval) > line_limit - 2) *multipleline = TRUE;
  curr_pos = CountCurrLineChar();
  if (curr_pos + nchar > line_limit - 2 && *multipleline != TRUE ||
      *multipleline == TRUE && curr_pos != 0) {
    PutChar('\n');
    curr_pos = 0;
  }

  if (*multipleline == TRUE) 
    PrintF(";\n");
  else 
    PutChar('\'');
  
  for (nchar = curr_pos, i=0; instrval[i] ; i++) {
    if (nchar >= line_limit && instrval[i] != '\n') {
      for (tempnchar = nchar, j= i; tempnchar >=0 && j >=0; j--) {
	if (instrval[j] == '\t') {
	  tempnchar -= (tempnchar%8);
	  break;
	}
	else tempnchar --;
	if (instrval[j] == ' ') break;
      }
      Seek((j-i), 1);
      i = j;
      PutChar('\n');
      nchar = 0;
    }
    PutChar(instrval[i]); 
    if (instrval[i] == '\t') nchar += (8- nchar%8);
    else if (instrval[i] == '\n') nchar = 0;
    else nchar ++;
  }
  if (*multipleline == TRUE) 
    PrintF("\n;\n");
  else 
    PrintF("\'  ");

  return SUCCEED;
}

void CifFileIo::PrintComment(CifString title,
			       ReVarCifArray<CifString> *definitions)
// ---------------------------------------------------------------------
//   PrintDefinitionAndExamples(): Print Definition and Examples
//                  at comment lines for user friendly
//   Parameter char *keyword
//             CifFileIo *dic_files
//             int ndic_files
// --------------------------------------------------------------------- 
{
  int i;
  
  if (definitions->Length() > 0 ) {
    PrintComment(title, 1);
    for (i=0; i<definitions->Length(); i++) {
      if ((*definitions)[i].Text()[0] != '\t' && (*definitions)[i].Text()[0] != ' ')
	PrintComment((*definitions)[i].Text(), 2);
      else
	PrintComment((*definitions)[i].Text());
    }
  }
}

int CifFileIo::CompareToken(char *newkeyword)
{
  int i, len;
  len = strlen(newkeyword);
  for (i =0; i<len && i<_token.Length() ; i++)
    if (tolower(_token.Text()[i]) != newkeyword[i])
      break;
  if (i == len) return 0;
  else          return 1;
}

void  CifFileIo:: SetSyntaxError(CifDataBlock *datablock, CifString message) 
{
  if (_syntaxError != TRUE) {
    _syntaxError = TRUE; 
    _firstSyntaxErrorLine = _curLineNo;
  }
  datablock->ErrorMessage(CIF_ERROR, _curLineNo, message);
/*
  ErrorMessage(CIF_ERROR, filename->Text(), datablockName.Text(), _curLineNo,
		    message.Text());
*/
}

void  CifFileIo:: SetSyntaxError(CifDataBlock *datablock, char *message) 
{
  if (_syntaxError != TRUE) {
    _syntaxError = TRUE; 
    _firstSyntaxErrorLine = _curLineNo;
  }
  datablock->ErrorMessage(CIF_ERROR, _curLineNo, message);
/*
  ErrorMessage(CIF_ERROR, filename->Text(), datablockName.Text(), _curLineNo,
		  message);
*/
}

int CifFileIo::  CheckRepeatedCategoryInFile(const CifString itemName, 
					       CifDataBlock *datablock)
{
  int i;
  CifString message, categoryName;

  categoryName.Copy(itemName);
  if (categoryName[0] == '_') categoryName.DeleteAt(0, 1);
  for (i=0; i<categoryName.Length(); i++)
    if (categoryName[i] == '.')
      categoryName.DeleteAt(i, categoryName.Length()-i+1);

  for (i=0; i<_categoryNamesInSaveBlock.Length(); i++)
    if (!CompareNoCase(_categoryNamesInSaveBlock[i], categoryName))
	    break;
  if (i == _categoryNamesInSaveBlock.Length()) {
    _categoryNamesInSaveBlock.Add(categoryName);
    return 1;
  }
  else {
    message.Clear();
    message += "Repeated category \'";
    message += categoryName;
    message += "\' at item name \'";
    message += itemName.Text();
    message += "\'";
    SetSyntaxError(datablock, message);
    return 0;
  }
}
