/*
FILE:     ciflib_structure.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:      Miscellaneous functions.
   * **************************************************************** */

#include <stdlib.h>

#include "CifFile.h"
#include "CifFileIo.h"
#include "ciflib_structure.h"
#include "ciflib_interface.h"
#include "CifErrorCodes.h"

extern CifFile *theCifFiles;
char *cifGetItemDataTypeCodeByIndex(const int dataBlockIndex, const int categoryIndex,
				    const int itemIndex)
/* -------------------------------------------------------------------------
   cifGetItemDataTypeCodeByIndex():
   Parametrers: const int dataBlockIndex, categoryIndex, itemIndex
   Return: char *default itemValue
   ------------------------------------------------------------------------- */
{
  CifString *dataTypeCode;
  char *itemValue;
  
  itemValue = NULL;
  dataTypeCode =theCifFiles->GetItemDataTypeCode(dataBlockIndex, categoryIndex, itemIndex);
  if (dataTypeCode != NULL) {
    itemValue = (char *) calloc(dataTypeCode->Length()+1, sizeof(char));
    strcpy(itemValue, dataTypeCode->Text());
  }
  return itemValue;
}

char *cifGetItemDataTypeCode(const char *datablockName, const char *categoryName,
			     const char *itemKeyword)
/* -------------------------------------------------------------------------
   cifGetItemDataTypeCodes():
   Parametrers: const int dataBlockIndex, 
                const char *categoryName, itemKeyword
   Return: char *default itemValue
   ------------------------------------------------------------------------- */
{
  int dataBlockIndex;
  CifCategoryIndex *tableIndex;
  

  dataBlockIndex = cifGetDataBlockIndex(datablockName);
  tableIndex = theCifFiles->GetTableIndex(dataBlockIndex, categoryName, itemKeyword);
  if (tableIndex == NULL) return NULL;

  else return cifGetItemDataTypeCodeByIndex(dataBlockIndex,  
				       tableIndex->GetCategoryIndex(),
				       tableIndex->GetItemIndex()); 
}
char *cifGetItemPrimitiveCode(const char *datablockName, const char *categoryName,
			     const char *itemKeyword)
/* -------------------------------------------------------------------------
   cifGetItemDataTypeCodes():
   Parametrers: const int dataBlockIndex, 
                const char *categoryName, itemKeyword
   Return: char *default itemValue
   ------------------------------------------------------------------------- */
{
  int dataBlockIndex;
  CifCategoryIndex *tableIndex;
  

  dataBlockIndex = cifGetDataBlockIndex(datablockName);
  tableIndex = theCifFiles->GetTableIndex(dataBlockIndex, categoryName, itemKeyword);
  if (tableIndex == NULL) return NULL;

  else return cifGetItemPrimitiveCodeByIndex(dataBlockIndex,  
				       tableIndex->GetCategoryIndex(),
				       tableIndex->GetItemIndex()); 
}

char *cifGetItemPrimitiveCodeByIndex(const int dataBlockIndex, const int categoryIndex,
				    const int itemIndex)
/* -------------------------------------------------------------------------
   cifGetItemDataTypeCodeByIndex():
   Parametrers: const int dataBlockIndex, categoryIndex, itemIndex
   Return: char *default itemValue
   ------------------------------------------------------------------------- */
{
  CifString *dataTypeCode;
  char *itemValue;
  
  itemValue = NULL;
  dataTypeCode =theCifFiles->GetItemPrimitiveCode(dataBlockIndex, categoryIndex, itemIndex);
  if (dataTypeCode != NULL) {
    itemValue = (char *) calloc(dataTypeCode->Length()+1, sizeof(char));
    strcpy(itemValue, dataTypeCode->Text());
  }
  return itemValue;
}


int cifGetItemStructureIndexByIndex(const int datablockIndex, const int categoryIndex,
				    const int itemIndex)
/* -------------------------------------------------------------------------
   cifGetItemStructureIndexByIndex():
   Parametrers: const int datablockIndex, categoryIndex, itemIndex
   Return: int structure index
   ------------------------------------------------------------------------- */
{
  return theCifFiles->GetItemStructureIndex(datablockIndex, categoryIndex, itemIndex);
}

int cifGetItemStructureIndex(const char *DatablockName, const char *categoryName,
			     const char *itemKeyword)
/* -------------------------------------------------------------------------
   cifGetItemStructureIndex():
   Parametrers: const int datablockIndex, 
                const char * categoryName, itemKeyword
   Return: int structure index
   ------------------------------------------------------------------------- */
{
  CifString category(categoryName), item(itemKeyword);
  int datablockIndex;

  datablockIndex = cifGetDataBlockIndex(DatablockName);
  return theCifFiles->GetItemStructureIndex(datablockIndex, category, item);
}

int cifGetItemStructureNumValueByIndex(const int datablockIndex, 
					const int categoryIndex,
					const int itemIndex)
/* -------------------------------------------------------------------------
   cifGetItemStructureNumValueByIndex():
   Parametrers: const int datablockIndex, categoryIndex, itemIndex
   Return: int number of itemValues
   ------------------------------------------------------------------------- */
{
  return theCifFiles->GetItemStructureNumValue(datablockIndex, categoryIndex, itemIndex);
}

int cifGetItemStructureNumValue(const char *DatablockName, const char *categoryName,
				 const char *itemKeyword)
/* -------------------------------------------------------------------------
   cifGetItemStructureNumValue():
   Parametrers: const int datablockIndex, 
                const char *categoryName, itemKeyword
   Return: int number of itemValues
   ------------------------------------------------------------------------- */
{
  CifString category(categoryName), item(itemKeyword);
  int datablockIndex;

  datablockIndex = cifGetDataBlockIndex(DatablockName);
  return theCifFiles->GetItemStructureNumValue(datablockIndex, category, item);
}

int cifGetItemStructureDimensionByIndex(const int datablockIndex, const int categoryIndex,
					const int itemIndex)
/* -------------------------------------------------------------------------
   cifGetItemStructureDimenstionByIndex():
   Parametrers: const int datablockIndex, categoryIndex, itemIndex
   Return: int structure dimension
   ------------------------------------------------------------------------- */
{
  return theCifFiles->GetItemStructureDimension(datablockIndex, categoryIndex, itemIndex);
}

int cifGetItemStructureDimension(const char *DatablockName, const char *categoryName,
				 const char *itemKeyword)
/* -------------------------------------------------------------------------
   cifGetItemStructureDimension():
   Parametrers: const int datablockIndex, 
                const char *categoryName, itemKeyword
   Return: int structure dimension
   ------------------------------------------------------------------------- */
{
  CifString category(categoryName), item(itemKeyword);
  int datablockIndex;

  datablockIndex = cifGetDataBlockIndex(DatablockName);
  return theCifFiles->GetItemStructureDimension(datablockIndex, category, item);
}
int cifGetItemStructureOrganizationByIndex(const int datablockIndex, const int categoryIndex,
					   const int itemIndex)
/* -------------------------------------------------------------------------
   cifGetItemStructureOrganizationByIndex():
   Parametrers: const int datablockIndex, categoryIndex, itemIndex
   Return: int structure organization 
   ------------------------------------------------------------------------- */
{
  return theCifFiles->GetItemStructureOrganization(datablockIndex, categoryIndex, itemIndex);
}

int cifGetItemStructureOrganization(const char *DatablockName, const char *categoryName,
				    const char *itemKeyword)
/* -------------------------------------------------------------------------
   cifGetItemStructureOrganization():
   Parametrers: const int datablockIndex, 
                const char *categoryName, itemKeyword
   Return: int structure organization 
   ------------------------------------------------------------------------- */
{
  CifString category(categoryName), item(itemKeyword);
  int datablockIndex;

  datablockIndex = cifGetDataBlockIndex(DatablockName);
  return theCifFiles->GetItemStructureOrganization(datablockIndex, category, item);
}

int cifGetMatrixItemValuesByIndex(char ***itemValue, const int datablockIndex,
			       const int categoryIndex,
			       const int itemIndex, 
			       const int rowIndex, int *numItemValue)
/* -------------------------------------------------------------------------
   cifGetMatrixItemValuesByIndex() Gets a whole matrix itemValues by category and 
                   item names
   Parameter: char **itemValue the address of string itemValue
              int datablockIndex, categoryIndex, itemIndex, rowIndex, 
              int *numItemValue return number of itemValues
    Return ItemValue:  gets SUCCEED or error code if failed
   ------------------------------------------------------------------------- */
{
  CifItemValue *cifItemValue;
  char **tmpItemValue;
  int  ret;
  
  ret = theCifFiles->GetItemValue(&cifItemValue, datablockIndex, categoryIndex, itemIndex,
			      rowIndex);
  if (ret == CIF_DATA_IS_VALID) {
    if (cifItemValue->GetStructureNumValue() == 0) {
      *numItemValue = 1;
      tmpItemValue =  (char **) calloc(1, sizeof(char));
      tmpItemValue[0] = (char *) calloc(cifItemValue->_buf.Length() +1, sizeof(char));
      strcpy(tmpItemValue[0],  cifItemValue->_buf.Text());
    }
    else {
      *numItemValue = cifItemValue->_data._arrayVal->Length();
      tmpItemValue =  (char **) calloc(*numItemValue, sizeof(char *));
      for (unsigned i = 0; i<*numItemValue; i++) {
	tmpItemValue[i] = (char *) 
	  calloc((*cifItemValue->_data._arrayVal)[i]._buf.Length()+1, sizeof(char));
	strcpy(tmpItemValue[i], (*cifItemValue->_data._arrayVal)[i]._buf.Text());
      }
    }
  }
  else *itemValue = NULL;
  *itemValue = tmpItemValue;
  return ret;
}
int cifGetMatrixItemValues(char ***itemValue, const char *DatablockName, 
		       const char *categoryName, const char *itemKeyword, 
		       const int rowIndex, int *numItemValue)
/* -------------------------------------------------------------------------
   cifGetMatrixItemValues() Gets a whole matrix itemValues by category and item names
   Parameter: char **itemValue the address of string itemValue
              int datablockIndex, rowIndex
              char *categoryname, itemKeyword
              int *numItemValue return number of itemValues
   Return ItemValue:  gets SUCCEED or error code if failed
   ------------------------------------------------------------------------- */
{
  CifCategoryIndex *tableIndex;
  int datablockIndex;

  datablockIndex = cifGetDataBlockIndex(DatablockName);
  tableIndex = theCifFiles->GetTableIndex(datablockIndex, categoryName, itemKeyword);
  if (tableIndex == NULL) return CIF_KEYWORD_NOT_EXIST;
  else 
    return cifGetMatrixItemValuesByIndex(itemValue, datablockIndex, 
				       tableIndex->GetCategoryIndex(), 
				       tableIndex->GetItemIndex(),
				       rowIndex, numItemValue);
  
}


int  cifUpdateMatrixItemValuesByIndex(char **itemValues, const int datablockIndex, 
				  const int categoryIndex, const int itemIndex, 
				  const int rowIndex, const int numItemValue)
/* -------------------------------------------------------------------------
   cifUpdateMatrixItemValues() Gets a itemValue by category and item names
   Parameter: char **itemValue the address of string itemValue
              int datablockIndex, categoryIndex, itemIndex, rowIndex
   Return ItemValue:  gets SUCCEED or error code if failed
   ------------------------------------------------------------------------- */
{
  CifItemValue *cifItemValue = NULL, *finalItemValue;
  int dataType, StructureNumValue, ret, itemValueNo, caseSensitivity;
  
  if (itemValues == NULL) return FAILURE;
  StructureNumValue = theCifFiles->GetItemStructureNumValue(datablockIndex, 
							     categoryIndex, itemIndex);
  if (StructureNumValue == 1) 
    return cifUpdateItemValueByIndex(itemValues[0], datablockIndex, 
				 categoryIndex, itemIndex, rowIndex);
  
  dataType = theCifFiles->GetItemDataType(datablockIndex, categoryIndex, itemIndex);
  
  caseSensitivity = 
    theCifFiles->GetItemCaseSensitivity(datablockIndex, categoryIndex, itemIndex);
  if (dataType != CIF_INTEGER_VALUE && dataType != CIF_DOUBLE_VALUE && 
      dataType != CIF_STRING_VALUE) 
    return FAILURE;
  itemValueNo = 0;
  finalItemValue = new CifItemValue(dataType, StructureNumValue, caseSensitivity);
  while (itemValueNo < StructureNumValue && itemValueNo < numItemValue) {
    if (itemValues[itemValueNo] == (char *) NULL || !strcmp(itemValues[itemValueNo],"")) 
      cifItemValue = new CifItemValue(dataType,  caseSensitivity, CIF_DATA_IS_NULL, (char *) NULL);
    else if (!strcmp(itemValues[itemValueNo], ".")) 
      cifItemValue = new CifItemValue(dataType, caseSensitivity, CIF_DATA_NOT_APPROPRIATE, 
			       NULL);
    else 
      cifItemValue = new CifItemValue(dataType, caseSensitivity, CIF_DATA_IS_VALID, 
			       itemValues[itemValueNo]);
    
    finalItemValue->_data._arrayVal->Add(*cifItemValue);
    finalItemValue->_status = CIF_DATA_IS_VALID;
    delete cifItemValue;
    itemValueNo ++;
  }
  
  ret = theCifFiles->UpdateItemValue(finalItemValue, datablockIndex, categoryIndex, itemIndex, 
				 rowIndex, TRUE);
  delete finalItemValue;
  
  return ret;
}
int  cifUpdateMatrixItemValues(char **itemValues,  const char * DatablockName, 
			   const char *categoryName, const char *itemKeyword, 
			   const int rowIndex, const int numItemValue)
/* -------------------------------------------------------------------------
   cifUpdateMatrixItemValues() Gets a itemValue by category and item names
   Parameter: char **itemValue the address of string itemValue
              int datablockIndex, rowIndex
              char *categoryName, itemKeyword
   Return ItemValue:  gets SUCCEED or error code if failed
   ------------------------------------------------------------------------- */
{
  CifCategoryIndex *tableIndex;
  int datablockIndex;

  datablockIndex = cifGetDataBlockIndex(DatablockName);
  tableIndex = theCifFiles->GetTableIndex(datablockIndex, categoryName, itemKeyword);
  if (tableIndex == NULL) return CIF_KEYWORD_NOT_EXIST;
  else 
    return cifUpdateMatrixItemValuesByIndex(itemValues, datablockIndex, 
					tableIndex->GetCategoryIndex(), 
					tableIndex->GetItemIndex(),
					rowIndex, numItemValue);
}

int*  cifGetParentRow(char ***newItemValues,  int *newCategoryIndex, 
				int *newItemIndex, int *newRowIndex,
				const char *DatablockName, 
				const char *categoryName, const char* itemKeyword,
				const int  parentIndex,  const char *mapItemValue, 
				int *numItemValue)
/* -------------------------------------------------------------------------
   cifGetParentRow() Gets a row of itemValues of parent of given item name
     
   Parameters:
   char ***newItemValues: the address of the string array.
   int  *newCategoryIndex, *newItemIndex, *newRowIndex:  the address of 
            the parent's category, item, and row indexes
   const int  dataBlockIndex:  which Datablock to process
   const char *categoryName, itemKeyword: category, and item keyword of the one 
                                         getting parent itemValues
   const int parentIndex: the index in link parent list(indicating which parent)
   const char *mapItemValue:  what itemValue of parent to map to
   int *numItemValue:  the address to keep the number of the itemValues,
                    it should be the same as mumber of items in the new category.
   Return ItemValue:  A list of SUCCEED or error codes 
                   or NULL if fails
   ------------------------------------------------------------------------- */
{
  CifString category(categoryName), item(itemKeyword), tmpMapItemValue;
  ReVarCifArray <CifCategoryIndex> *parents = NULL;
  CifItemValue  *newCifItemValue;
  int *rets, ret,  caseSensitivity;
  int dataBlockIndex;

  dataBlockIndex = cifGetDataBlockIndex(DatablockName);
  
  
  *newItemValues = NULL;
  *newCategoryIndex = -1;
  *newItemIndex = -1;
  *newRowIndex = -1;
  *numItemValue = 0;
  parents = theCifFiles->GetLinkParents(dataBlockIndex, category, item);
  if (parents == NULL)
    return NULL;
  
  if (parentIndex < 0 || parentIndex >= parents ->Length())
    return NULL;
  

  *newRowIndex  = 0;
  caseSensitivity = 
    theCifFiles->GetItemCaseSensitivity(dataBlockIndex, 
				       (*parents)[parentIndex].GetCategoryIndex(),
				       (*parents)[parentIndex].GetItemIndex());
  if (!caseSensitivity) {
    tmpMapItemValue.Copy(mapItemValue);
    tmpMapItemValue.ToLower();
  }
  do {
    ret = theCifFiles->GetItemValue(&newCifItemValue, dataBlockIndex, 
				(*parents)[parentIndex].GetCategoryIndex(),
				(*parents)[parentIndex].GetItemIndex(), *newRowIndex);
    if (caseSensitivity && !Compare(newCifItemValue->_buf.Text(), mapItemValue) ||
	!caseSensitivity && !CompareNoCase(newCifItemValue->_buf, tmpMapItemValue)) {
      *newCategoryIndex =  (*parents)[parentIndex].GetCategoryIndex();
      *newItemIndex =  (*parents)[parentIndex].GetItemIndex();
      rets = cifGetRowByIndex(newItemValues, dataBlockIndex, 
				    *newCategoryIndex, *newRowIndex, numItemValue);
      break;
    }
    (*newRowIndex) ++;
  } while ( ret < CIF_OUT_OF_RANGE_ERROR_CODE_START) ;
  if ( ret > CIF_OUT_OF_RANGE_ERROR_CODE_START) {
    (*newRowIndex) = -1;
    *newCategoryIndex =  (*parents)[parentIndex].GetCategoryIndex();
    *newItemIndex =  (*parents)[parentIndex].GetItemIndex();
    rets = cifGetRowByIndex(newItemValues, dataBlockIndex, 
				  *newCategoryIndex, 0, numItemValue);
    for (unsigned i=0; i< *numItemValue; i++) {
      rets[i] = CIF_VALUE_NOT_EXIST;
      if ((*newItemValues)[i] != NULL) free ((*newItemValues)[i]);
      (*newItemValues)[i] = NULL;
    }
  }
  return rets;
  
  
}


int*  cifGetChildRow(char ***newItemValues, int *newCategoryIndex, 
			       int *newItemIndex,int *newRowIndex,
			       const int childRowOrder, const char *DatablockName, 
			       const char * categoryName, const char* itemKeyword,
			       const int childIndex, const char *mapItemValue, 
			       int *numItemValue)
/* -------------------------------------------------------------------------
   cifGetChildRow() Gets the row of itemValues of child of given item name
                          which matches its itemValue at the childRowOrder-th times.
   Parameters:
   char ***newItemValues: the address of the string array.
   const int childRowOrder: 1, get the first row of the children matched itemValue,
                            2, get the second row of the children matched itemValue,
   int  *newCategoryIndex, newItemIndex, newRowIndex:  the address of category 
                         item, row indexes of the new itemValues.
   const int  dataBlockIndex:  which Datablock to process
   const char *categoryName, itemKeyword: category name and item keyword of 
                                   the one which is getting child
   const int childIndex: the index in link child list
   const char *mapItemValue:  which itemValue of the child to map to 
   int *numItemValue:  the address to keep the number of the itemValues,
                    it should be the same as mumber of items in the new category.
                
   Return ItemValue:  gets a list of SUCCEED or error codes 
                       or NULL if nothing found

   Example: errorCodes = cifGetChildRow(&newItemValues,
     					      &childCategoryIndex,
                                              &childItemIndex, 
                                              &childRowIndex, 2, 
                                              1, "category", "id", 
                                              3, "category_group", &numItemValue)
     this procedure will search the item_list to find the third child of
     _category.id (third child is _item.category_id in the current ddl) 
     and then map the itemValue "category_group" against table "item" column 
     "category_id" when the second time it matchs the mapItemValue, it copies 
     the itemValues of this row to newItemValues,  and makes
     newCategoryIndex the index of category "item", 
     newItemIndex the index of item "category_id" in category "item", 
     and newRowIndex the new row index of new table "item"
   ------------------------------------------------------------------------- */
{
  CifString category(categoryName), item(itemKeyword);
  ReVarCifArray <CifCategoryIndex> *children = NULL;
  CifItemValue  *newCifItemValue;
  int *rets, ret, found, caseSensitivity;
  CifString tmpMapItemValue;
  int dataBlockIndex;

  dataBlockIndex = cifGetDataBlockIndex(DatablockName);
  
  *newItemValues = NULL;
  *newCategoryIndex = -1;
  *newItemIndex = -1;
  *newRowIndex = -1;
  *numItemValue = 0;
  children = theCifFiles->GetLinkChildren(dataBlockIndex, category, item);
  if (children == NULL)
    return NULL;
  
  if (childIndex < 0 || childIndex >= children->Length())
    return NULL;
  
  found = 0;
  *newRowIndex  = 0;
  caseSensitivity = 
    theCifFiles->GetItemCaseSensitivity(dataBlockIndex, 
					(*children)[childIndex].GetCategoryIndex(),
					(*children)[childIndex].GetItemIndex());
  if (!caseSensitivity) {
    tmpMapItemValue.Copy(mapItemValue);
    tmpMapItemValue.ToLower();
  }
  do {
    ret = theCifFiles->GetItemValue(&newCifItemValue, dataBlockIndex, 
				(*children)[childIndex].GetCategoryIndex(),
				(*children)[childIndex].GetItemIndex(), *newRowIndex);
    if (caseSensitivity && !Compare(newCifItemValue->_buf.Text(), mapItemValue) ||
	!caseSensitivity && !CompareNoCase(newCifItemValue->_buf, tmpMapItemValue)) {
      found ++;
      if (found == childRowOrder) {
	*newCategoryIndex =  (*children)[childIndex].GetCategoryIndex();
	*newItemIndex =  (*children)[childIndex].GetItemIndex();
	rets = cifGetRowByIndex(newItemValues, dataBlockIndex, 
					  *newCategoryIndex, *newRowIndex, numItemValue);
	break;
      }
    }
    (*newRowIndex) ++;
  } while ( ret < CIF_OUT_OF_RANGE_ERROR_CODE_START) ;
  
  if (ret > CIF_OUT_OF_RANGE_ERROR_CODE_START || found != childRowOrder) {
    (*newRowIndex) = -1;
    if (found != 0 && found != childRowOrder) {
      *newCategoryIndex =  (*children)[childIndex].GetCategoryIndex();
      *newItemIndex =  (*children)[childIndex].GetItemIndex();
      rets = cifGetRowByIndex(newItemValues, dataBlockIndex, 
				    *newCategoryIndex, 0, numItemValue);
      for (unsigned i=0; i< *numItemValue; i++) {
	rets[i] = CIF_VALUE_NOT_EXIST;
	if ((*newItemValues)[i] != NULL) free ((*newItemValues)[i]);
	(*newItemValues)[i] = NULL;
      }
    }
  }
  return rets;
  
  
}


int cifAddDataBlockByIndex(const char *newDatablockName, const int dicdataBlockIndex)
/* -------------------------------------------------------------------------
   cifAddDataBlockByIndex(): Add a new datablock
   ------------------------------------------------------------------------- */
{
  CifDataBlock *datablock;
  datablock = theCifFiles->AddDatablock(dicdataBlockIndex, newDatablockName);
  if (datablock == NULL) return -1;
  else return cifCountDataBlocks()-1;
}

int cifAddCategoryByIndex(const char *newCategoryName, const int dataBlockIndex)
/* -------------------------------------------------------------------------
   cifAddCategoryByIndex(): Add a new Category
   ------------------------------------------------------------------------- */
{
  CifCategory *category_table;
  category_table = theCifFiles->AddCategory(dataBlockIndex, newCategoryName);
  if (category_table == NULL) return -1;
  else return cifCountCategoriesByIndex(dataBlockIndex)-1;
}

int cifAddDataItemByIndex(const char *newItemKeyword, const int dataBlockIndex, 
			  const int categoryIndex)
/* -------------------------------------------------------------------------
   cifAddDataItemByIndex(): Add a new itemColumn
   ------------------------------------------------------------------------- */
{
  CifDataItem *dataItem;
  dataItem = theCifFiles->AddDataItem(dataBlockIndex, categoryIndex, newItemKeyword);
  if (dataItem == NULL) return -1;
  else return cifCountColumnsByIndex(dataBlockIndex, categoryIndex)-1;
}

int cifAddRowByIndex(const int dataBlockIndex, 
		     const int categoryIndex)
/* -------------------------------------------------------------------------
   cifAddDataItemByIndex(): Add a new itemColumn
   ------------------------------------------------------------------------- */
{
  return theCifFiles->AddRow(dataBlockIndex, categoryIndex);
}

