/*
FILE:     TblFileObj.C
*/
/*
VERSION:  6.102
*/
/*
DATE:     9/15/2004
*/
/*
  Comments and Questions to: sw-help@rcsb.rutgers.edu
*/
/*
COPYRIGHT 1999-2004 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:    Class for tables management in persistent store
*/

#include "TblFileObj.h"
#include <string.h>

const int TblFileObj::TABLES_INCR   = 250;
const int TblFileObj::BLOCKS_INCR   = 100;
const int TblFileObj::MAKE_BIN      = 1;
const int TblFileObj::DONT_MAKE_BIN = 0;

TableInfo::TableInfo(){
  _block = NULL;
  _name = NULL;
  _id = NULL; 
  _objectId = 0;  
  _memId = 0;
  _numItems = 0;  
  _modified = 0;  
}
TableInfo::TableInfo(const char* c){
  
  _block = NULL;
  _name = NULL;
  _id = (char*)malloc(strlen(c)+1);     
  strcpy(_id,c);
  _objectId = 0;  
  _memId = 0;
  _numItems = 0;  
  _modified = 0;  
};

TableInfo::TableInfo(const TableInfo &t){
  
  if (t._block == NULL)
    _block = NULL;
  else {
    _block = (char*)malloc(strlen(t._block)+1);
    strcpy(_block,t._block);
  };
  if (t._name == NULL)
    _name = NULL;
  else {
    _name = (char*)malloc(strlen(t._name)+1);
    strcpy(_name,t._name);
  };
  if (t._id == NULL)
    _id = NULL;
  else {
    _id = (char*)malloc(strlen(t._id)+1);     
    strcpy(_id,t._id);
  };
  _objectId = t._objectId;  
  _memId = t._memId;     
  _numItems = t._numItems;
  _modified = t._modified;  
};

void TableInfo::DeleteElement() {
  Clear();
}
void TableInfo::Clear() {
  if (_block) free (_block);
  if (_name) free (_name);
  if (_id) free (_id);
};
void TableInfo::Print() {
  cout<<_id<<endl;
}
TableInfo::~TableInfo() {
  Clear();
};

void TableInfo::operator=(const TableInfo &t) {
  Clear();
  if (t._block == NULL)
    _block = NULL;
  else {
    _block = (char*)malloc(strlen(t._block)+1);
    strcpy(_block,t._block);
  };
  if (t._name == NULL)
    _name = NULL;
  else {
    _name = (char*)malloc(strlen(t._name)+1);
    strcpy(_name,t._name);
  };
  if (t._id == NULL)
    _id = NULL;
  else {
    _id = (char*)malloc(strlen(t._id)+1);     
    strcpy(_id,t._id);
  };
  _objectId = t._objectId;  
  _memId = t._memId;     
  _numItems = t._numItems; 
  _modified = t._modified;  
};

int TableInfo::operator<(const TableInfo &t) {
  int ret;

  ret = strcmp(_id,t._id);
  if (ret < 0)
    return 1;
  else
    return 0;
};

int TableInfo::operator==(const TableInfo &t) {
  int ret;

  ret = strcmp(_id,t._id);
  if (ret == 0)
    return 1;
  else
    return 0;
};


BlockInfo::BlockInfo(){
  _name = NULL;
}
BlockInfo::BlockInfo(const char* c){
  _name = (char*)malloc(strlen(c)+1);     
  strcpy(_name,c);
};

BlockInfo::BlockInfo(const BlockInfo &b){
  
  if (b._name == NULL)
    _name = NULL;
  else {
    _name = (char*)malloc(strlen(b._name)+1);
    strcpy(_name,b._name);
  };
};

void BlockInfo::DeleteElement() {
  Clear();
}
void BlockInfo::Clear() {
  if (_name) free (_name);
};
void BlockInfo::Print() {
  cout<<_name<<endl;
}
BlockInfo::~BlockInfo() {
  Clear();
};

void BlockInfo::operator=(const BlockInfo &b) {
  Clear();
  if (b._name == NULL)
    _name = NULL;
  else {
    _name = (char*)malloc(strlen(b._name)+1);
    strcpy(_name,b._name);
  };
};

int BlockInfo::operator<(const BlockInfo &b) {
  int ret;

  ret = strcmp(_name,b._name);
  if (ret < 0)
    return 1;
  else
    return 0;
};

int BlockInfo::operator==(const BlockInfo &b) {
  int ret;

  ret = strcmp(_name,b._name);
  if (ret == 0)
    return 1;
  else
    return 0;
};

void TblFileObj::SetDataBlock(const char *blockId) {
  if (blockId == NULL) return;
  if (_currentBlock) delete[] _currentBlock;
  _currentBlock = new char[strlen(blockId)+1];
  strcpy(_currentBlock, blockId);

}


TblFileObj::TblFileObj(char * filename, int openMode) {
  Clear();
  OpenFile(filename, openMode);

}

void TblFileObj::Clear() {
  _f = NULL;
  _filename = NULL;
  _currentBlock = NULL;
  _mode = -1;
  _fileIndex.numBlocks = 0;
  _fileIndex.numTables = 0;
  _fileIndex.tablesAllocated = 0;
  _tableObjs = NULL;
  _tablesAllocated = 0;
  _lastTableInMem = -1;
}

void TblFileObj::Reset() {
  unsigned int i,j;
  if (_f) delete _f;
  if (_filename)     delete[] _filename;
  if (_currentBlock) delete[] _currentBlock;

  if (_tableObjs) {
    for (i = 0, j=0; j < _fileIndex.numTables; i++) {  
      if (!(*_fileIndex.tables.Deleted())[i]) {
	if ((*_fileIndex.tables.Data())[i].GetMemId()>-1) {
	  if (_tableObjs[(*_fileIndex.tables.Data())[i].GetMemId()]) { 
	    delete _tableObjs[(*_fileIndex.tables.Data())[i].GetMemId()];
	    _tableObjs[(*_fileIndex.tables.Data())[i].GetMemId()] = NULL;
	  }
	}
	j++;
      }
    }
    delete[] _tableObjs; 
    _tableObjs = NULL;
  }
  Clear();
}


int TblFileObj::OpenFile(const char * filename, int openMode) {
  int ret;

  _mode = openMode;
  if (_mode == PERM_WRITE_MODE) openMode=WRITE_MODE;
  if (_filename) delete _filename;
  _filename = new char[strlen(filename)+1];
  strcpy(_filename, filename);

  if (_mode != WRITE_MODE) {
  FileNavigator * fnav = new FileNavigator();
    if (((ret = fnav->OpenFile(filename, openMode,0)) < 0) || ((ret = fnav->ReadFileHeader()) < 0)) {
      delete fnav;
      fnav = NULL;
      return ret;
    }

    if (!_f) {
      _f = fnav;
      fnav = NULL;
    } else {
      _f->CloseFile();
      delete _f;
      _f = fnav;
      fnav = NULL;
    }
    if (_mode!=PERM_WRITE_MODE)
      return _ReadFileIndex();
    else
      return 0;
  } else
    return 0;
}

void TblFileObj::CloseFile(int makeBinFile, int shrink) {
  unsigned int i, j;
  char * extblockname;
  int loc;


  if ((_mode == WRITE_MODE) && (makeBinFile)) {
    FileNavigator * fnav = new FileNavigator();
    fnav->OpenFile(_filename, _mode,0);
    fnav->ReadFileHeader();

    if (!_f) {
      _f = fnav;
      fnav = NULL;
    } else {
      _f->CloseFile();
      delete _f;
      _f = fnav;
      fnav = NULL;
    }
  }

  if (_f) {
    if ((_mode == UPDATE_MODE)|| (_mode == PERM_WRITE_MODE)){ //Write all modified tables 
      for (i=0; i < _fileIndex.numTables; i++) {
	if ((*_fileIndex.tables.Data())[i].GetModified()) {
	  extblockname = _GetExternalBlockName((*_fileIndex.tables.Data())[i].GetBlock());
	  _WriteTable(_tableObjs[(*_fileIndex.tables.Data())[i].GetMemId()],
		      extblockname,
		      (*_fileIndex.tables.Data())[i].GetName(),0);
	  if (extblockname) delete[] extblockname;
	}
      }
      _WriteFileIndex();
    }
    if (_mode == WRITE_MODE) {
  for (i = 0, j=0; j < _fileIndex.numTables; i++) {
    if ((*_fileIndex.tables.Deleted())[i] != 1) {
      loc = _tableObjs[j]->WriteObject(_f);
      (*_fileIndex.tables.Data())[i].SetObjectId(loc);
      j++;
    }

  }
      _WriteFileIndex();
    }


    _f->CloseFile();
    _mode = -1;
    delete _f;
    _f = NULL;
    if (shrink) _ShrinkFile(_filename);
  }
}

void TblFileObj::_AddDataBlock(const char *blockName) { // external block name ...
  if (!_IsBlockPresent(blockName)) {

    BlockInfo bi;
    if (blockName && strlen(blockName) > 0) {
      bi.SetName(blockName);
    } else {
      bi.SetName("");
    }
    _fileIndex.blocks.Add(bi);
    _fileIndex.numBlocks++;
  }
  return;
}



void TblFileObj::_ManageTableSpace() {
  int i;

  // is there room for the next in-memory table?

  if (_lastTableInMem  >= _tablesAllocated - 1) {
    while (_lastTableInMem  >= _tablesAllocated - 1) {
      _tablesAllocated += TABLES_INCR;
    }

    ISTable ** newTableList = new ISTable *[_tablesAllocated];  // new list of table pointers

    for (i = 0; i <= _lastTableInMem; i++) {
      newTableList[i] = _tableObjs[i];
    }

    for (i = _lastTableInMem + 1; i < _tablesAllocated; i++) {
      newTableList[i] = NULL;
    }
    delete[] _tableObjs;
    _tableObjs = newTableList;
    newTableList = NULL;
  }
  
}




int TblFileObj::_GetIndexFromId(const char * tableId) {  // search the internal identifier
  if (!tableId) return -100;
  if ((*_fileIndex.tables.Data()).Length()==0) return -1;

  TableInfo a(tableId);
  int ret = _fileIndex.tables.Seek(a);
  return ret;
}


int TblFileObj::_GetIndexFromName(const char *blockName, const char * tableName) {

  char *id=NULL;
  int ret;
  if (!_fileIndex.tables.Data()->Length()==0) return -1;
  if ((id=_BuildTableId(blockName,tableName))==NULL) return -1;
  ret=_GetIndexFromId(id);
  if (id) delete id;
  return(ret);

}


int TblFileObj::_IsTablePresent(const char * blockName, const char * tableName) {

  int ret;
  char *id=NULL;

  if (_fileIndex.tables.Data()->Length()==0) return 0;
  if ((id=_BuildTableId(blockName,tableName))==NULL) return 0;

  TableInfo a(id);
  ret = _fileIndex.tables.Seek(a);
  delete[] id;
  if (ret < 0) 
    return 0;
  else 
    return 1;
}


int TblFileObj::_IsBlockPresent(const char * blockName) { //external name

  int ret;

  if (_fileIndex.blocks.Data()->Length()==0) return 0;
  if (blockName==NULL)    return 0;

  BlockInfo a(blockName);
  ret = _fileIndex.blocks.Seek(a);
  if (ret < 0) 
    return 0;
  else 
    return 1;
}


char *TblFileObj::_GetInternalBlockId(const char *blockName) {
  int iorder;
  char *name = NULL;
  CifString blockNo;

  if (!blockName || (strlen(blockName) <= 0) ) return(name);
  iorder = GetBlockOrder(blockName);
  if (iorder >=0) {
    name = new char[10];
    blockNo.Clear(); blockNo += iorder;
    strcpy(name,blockNo.Text());
  }

  return(name);
}



char *TblFileObj::_GetExternalBlockName(const char *blockId) {
  int iorder;
  
  if (!blockId || (strlen(blockId) <= 0)) return NULL;
  iorder = atoi(blockId);
  return (GetBlockName(iorder));
}


char *TblFileObj::_BuildTableId(const char *blockName, const char *tableName, int flagBlockExternal) {

  int lb=0,lt=0;
  char *id=NULL, *blockId=NULL;
  

  id = NULL; 
  if ((tableName == NULL) || ((lt=strlen(tableName)) == 0)) return id; 

  if ((blockName == NULL) || ((lb=strlen(blockName)) == 0)) { // handle null block gracefully.
    id  = new char[lt + 3];  //  Here is id rule for NULL datablock name .. 
    strcpy(id,"__");
    strcat(id,tableName);
  } else {
    if (flagBlockExternal) { // Convert to internal block identifier.
      blockId=_GetInternalBlockId(blockName);
      if (blockId) {
	lb=strlen(blockId);
	id  = new char[lt + lb +3];
	strcpy(id,"_");
	strcat(id,blockId); 
      }
      else {
	id  = new char[lt + lb +3];
	strcpy(id,"_");
	strcat(id,blockName);
      }
    } else {
      id  = new char[lt + lb +3];
      strcpy(id,"_");
      strcat(id,blockName);
    }
    strcat(id,"_");
    strcat(id,tableName);
  }
  if (blockId) delete[] blockId; 
  return(id);
}


char ** TblFileObj::_GetTableIds(int & num) {
  num = 0;
  if ((_fileIndex.tables.Data()->Length()==0) || (_fileIndex.numTables == 0)) return NULL;

  char ** ret = new char *[_fileIndex.numTables];
  unsigned int i = 0, j=0;
  while(j < _fileIndex.numTables) {
    if ((*_fileIndex.tables.Deleted())[i] != 1) {
      if ((*_fileIndex.tables.Data())[i].GetId()) {
	ret[j] = new char[strlen((*_fileIndex.tables.Data())[i].GetId()) + 1];
	strcpy(ret[j], (*_fileIndex.tables.Data())[i].GetId());
      } else {
	ret[j] = new char[2];
	strcpy(ret[j], "");
      }
      j++;
    }
    i++;
  }
  num = _fileIndex.numTables;
  return ret;
}

char ** TblFileObj::GetTableNames(int & num) {
  num = 0;
  if ((_fileIndex.tables.Data()->Length()==0) || (_fileIndex.numTables == 0)) return NULL;

  char ** ret = new char *[_fileIndex.numTables];
  unsigned int i = 0, j = 0;
  while(j < _fileIndex.numTables) {
    if ((*_fileIndex.tables.Deleted())[i] != 1) {
      if ((*_fileIndex.tables.Data())[i].GetName()) {
	ret[j] = new char[strlen((*_fileIndex.tables.Data())[i].GetName()) + 1];
	strcpy(ret[j], (*_fileIndex.tables.Data())[i].GetName());
      } else {
	ret[j] = new char[2];
	strcpy(ret[j], "");
      }
      j++;
    }
    i++;
  }
  num = _fileIndex.numTables;
  return ret;
}

char ** TblFileObj::GetTableNames(const char *blockName, int & num) {
  num = 0;
  char *blockId=NULL;
  if ((_fileIndex.tables.Data()->Length()==0) || (_fileIndex.numTables == 0)) return NULL;
  if ( !blockName || ((blockId= _GetInternalBlockId(blockName)) == NULL)) return NULL;

  char ** ret = new char *[_fileIndex.numTables];
  unsigned int i = 0, j = 0, k = 0;
  while(k < _fileIndex.numTables) {
    if ((*_fileIndex.tables.Deleted())[i] != 1) {
      if ((*_fileIndex.tables.Data())[i].GetName() && (*_fileIndex.tables.Data())[i].GetBlock() && !strcmp(blockId,(*_fileIndex.tables.Data())[i].GetBlock())) {
	ret[j] = new char[strlen((*_fileIndex.tables.Data())[i].GetName()) + 1];
	strcpy(ret[j], (*_fileIndex.tables.Data())[i].GetName());
	j++;
      }
      k++;
    }
    i++;
  }
  num = j;
  if (blockId) delete[] blockId; 
  return ret;
}

char ** TblFileObj::_GetTableBlockNames(int & num) {
  num = 0;
  if ((_fileIndex.tables.Data()->Length()==0) || (_fileIndex.numTables == 0)) return NULL;

  char ** ret = new char *[_fileIndex.numTables];
  unsigned int i = 0, j = 0;
  while(j < _fileIndex.numTables) {
    if ((*_fileIndex.tables.Deleted())[i] != 1) {
      if ((*_fileIndex.tables.Data())[i].GetBlock()) {
	ret[j] = new char[strlen((*_fileIndex.tables.Data())[i].GetBlock()) + 1];
	strcpy(ret[j], (*_fileIndex.tables.Data())[i].GetBlock());
      } else {
	ret[j] = new char[2];
	strcpy(ret[j], "");
      }
      j++;
    }
    i++;
  }
  num = _fileIndex.numTables;
  return ret;
}


char ** TblFileObj::GetBlockNames(int & num) {
  num = 0;
  if (_fileIndex.blocks.Data()->Length()==0) return NULL;

  char ** ret = new char *[_fileIndex.numBlocks];
  unsigned int i = 0, j = 0;
  while(j < _fileIndex.numBlocks) {
    if ((*_fileIndex.blocks.Deleted())[i] != 1) {
      if ((*_fileIndex.blocks.Data())[i].GetName()) {
	ret[j] = new char[strlen((*_fileIndex.blocks.Data())[i].GetName()) + 1];
	strcpy(ret[j], (*_fileIndex.blocks.Data())[i].GetName());
      } else {
	ret[j] = new char[2];
	strcpy(ret[j], "");
      }
      j++;
    }
    i++;
  }
  num = _fileIndex.numBlocks;
  return ret;
}


char * TblFileObj::GetBlockName(int iOrgOrder) {
  char *ret = NULL;
  if (_fileIndex.blocks.Data()->Length()==0 || iOrgOrder>(int)(_fileIndex.numBlocks)) return NULL;
  
  ret= new char[strlen((*_fileIndex.blocks.Data())[iOrgOrder].GetName()) + 1];
  strcpy(ret, (*_fileIndex.blocks.Data())[iOrgOrder].GetName());
  return ret;
}


int TblFileObj::RenameBlock(const char *blockName, int iOrgOrder) {
  int ret = -1;
  char *OrgName;
  if (_fileIndex.blocks.Data()->Length()==0 || iOrgOrder>(int)(_fileIndex.numBlocks)) return ret;
  OrgName = GetBlockName(iOrgOrder);
  _fileIndex.blocks.Seek(OrgName);
  _fileIndex.blocks.ReplData(blockName);
  
  if (OrgName) delete[] OrgName;
  return 1;
}


int TblFileObj::GetBlockOrder(const char *blockName) {
  int ret = -1;
  if (_fileIndex.blocks.Data()->Length()==0) return -1;

  ret = _fileIndex.blocks.Seek(blockName);
  return ret;
}

ISTable * TblFileObj::_GetTablePtr(const char * tableId) {
  int ret;

  if ((tableId == NULL) || (strlen(tableId) == 0)) return NULL;
  int location = _GetIndexFromId(tableId);
  if (location < 0) return NULL;

  ret = (*_fileIndex.tables.Data())[location].GetMemId();
#if DEBUG
  cerr << "_GetTablePtr ret " << ret << " lastTableInMem " << _lastTableInMem << endl;
#endif
  if ((ret >= 0) && (ret <= _lastTableInMem)) {
    return _tableObjs[ret];
  } else {
    _ManageTableSpace();
    (*_fileIndex.tables.Data())[location].SetMemId(++_lastTableInMem);

    _tableObjs[_lastTableInMem] = new ISTable();
    _tableObjs[_lastTableInMem]->GetObject((*_fileIndex.tables.Data())[location].GetObjectId(), _f);

    //  number of file navigator logical index slots per table ...

    (*_fileIndex.tables.Data())[location].SetNumItems( 
      12 +  
      _tableObjs[_lastTableInMem]->GetNumColumns() + 
      _tableObjs[_lastTableInMem]->GetNumIndices()*
      (5+_tableObjs[_lastTableInMem]->GetNumRows()*6));      

    return _tableObjs[_lastTableInMem];
  }
}



ISTable * TblFileObj::GetTablePtr(const char *blockName, const char * tableName) {
  char *id=NULL;
  ISTable *s=NULL;
  id = _BuildTableId(blockName,tableName);
  if (!id) {
    delete id;
    return NULL;
  } else { 
    s = _GetTablePtr(id);
    delete[] id;
    return(s);
  }
}

ISTable * TblFileObj::_GetTable(const char * tableId) {
  int ret;
  ISTable *retSST;

  if ((tableId == NULL) || (strlen(tableId) == 0)) return NULL;
  int location = _GetIndexFromId(tableId);
  if (location < 0) return NULL;

  ret = (*_fileIndex.tables.Data())[location].GetMemId();
#if DEBUG
  cerr << "_GetTablePtr ret " << ret << " lastTableInMem " << _lastTableInMem << endl;
#endif
  if ((ret >= 0) && (ret <= _lastTableInMem)) {
    retSST = new ISTable();
    retSST->Copy(_tableObjs[ret]);
    return retSST;
  } else {
    retSST = new ISTable();
    retSST->GetObject((*_fileIndex.tables.Data())[location].GetObjectId(), _f);
    return retSST;
  }
}

ISTable * TblFileObj::GetTable(const char *blockName, const char * tableName) {
  char *id=NULL;
  ISTable *s=NULL;
  id = _BuildTableId(blockName,tableName);
  if (!id) {
    delete id;
    return NULL;
  } else { 
    s = _GetTable(id);
    delete[] id;
    return(s);
  }
}

int TblFileObj::WriteTable(ISTable * s, const char *blockName, const char *tableName) {  

  int ret;
  int index;
  char *blockId=NULL, *id=NULL;


  if ((!s) || (!tableName)) return -1;
  if (_mode == READ_MODE) return -177;
  
  if (_mode == UPDATE_MODE) {  // mark the file for 
    blockId = _GetInternalBlockId(blockName);
    id = _BuildTableId(blockId,tableName,0);
    if (blockId) delete[] blockId; 
    if (!id) return -1;
    index=_GetIndexFromId(id);
    delete[] id; 
    if (index >= 0) { 
      GetTablePtr(blockName,tableName);
      (*_fileIndex.tables.Data())[index].SetModified(1);
      if (_tableObjs[(*_fileIndex.tables.Data())[index].GetMemId()] != s)
	delete _tableObjs[(*_fileIndex.tables.Data())[index].GetMemId()];
      _tableObjs[(*_fileIndex.tables.Data())[index].GetMemId()] = s;
      ret= 1;
    } else 
      return _WriteTable(s,blockName,tableName,1); //-100;
  } else if ((_mode == WRITE_MODE) || (_mode == PERM_WRITE_MODE)) {
    ret=_WriteTable(s,blockName,tableName,1);
  } else {
    ret=-177;
  }

  return(ret);
}


int TblFileObj::_WriteTable(ISTable * s, const char *blockName, const char *tableName, 
			   int saveTablePtr) {  
  char *id = NULL;
  CifString blockS;
  int index;
  char *blockId;


  if (!s) return -1;
  if (_mode == READ_MODE) return -177;

  if (blockName && (strlen(blockName) >0)) {  // handle potentially multiple unnamed blocks.
    _AddDataBlock(blockName);
  } else {
    blockS.Clear();
    blockS.Copy("UNNAMED"); blockS += (int) _fileIndex.numBlocks;
    _AddDataBlock(blockS.Text());
  }

  blockId = _GetInternalBlockId(blockName);


  id = _BuildTableId(blockId,tableName,0);
  if (!id) {
  if (blockId) delete[] blockId; 
    return -1;
  }
  index=_GetIndexFromId(id);

  int loc = 0;
  if ((_mode == UPDATE_MODE) || (_mode == PERM_WRITE_MODE)) {
    loc = s->WriteObject(_f);
    if (loc < 0) return -344;
  }


  if (index >= 0 ) {                // rewrite/relocate existing table
    (*_fileIndex.tables.Data())[index].SetObjectId(loc);
    if ((saveTablePtr) && (_mode != PERM_WRITE_MODE)){
      _tableObjs[(*_fileIndex.tables.Data())[index].GetMemId()] = s;
    } else {
      (*_fileIndex.tables.Data())[index].SetMemId(-1);
      delete s;
    }
  } else {                                   // add new table to file index
    TableInfo ti;
    _ManageTableSpace();
    
    ti.SetObjectId(loc);
    if ((saveTablePtr) && (_mode != PERM_WRITE_MODE)){
      ti.SetMemId(++_lastTableInMem);
      _tableObjs[_lastTableInMem] = s;
      ti.SetNumItems(12 +  
		     _tableObjs[_lastTableInMem]->GetNumColumns() + 
		     _tableObjs[_lastTableInMem]->GetNumIndices()*
		     (5+_tableObjs[_lastTableInMem]->GetNumRows()*6));
      
    } else {
      ti.SetMemId(-1);
      ti.SetNumItems(12+s->GetNumColumns()+s->GetNumIndices()*(5+s->GetNumRows()*6));
      delete s;
    }

    ti.SetId(id);
  
    if (strlen(blockId)>0) {
      ti.SetBlock(blockId);
    } else {
      ti.SetBlock("");
    }

    
    if (tableName !=NULL && (strlen(tableName) > 0)) {
      ti.SetName(tableName);
    } else {
      ti.SetName("");
    }

    _fileIndex.numTables++;
    _fileIndex.tables.Add(ti);
    
  }
  if (blockId) delete[] blockId; 
  delete[] id;
  return loc;
}


int TblFileObj::_WriteFileIndex() {
  unsigned int i, j;
  int numTables, numBlocks, where = 0, ret = 0, err=0;

  if (!_f) return -1;
  if (_mode == READ_MODE) return -1;

  int * tableLocs = new int[_fileIndex.numTables];
  int * bOrder    = new int[1];
  int * tOrder    = new int[1];

  for (i = 0, j=0; j < _fileIndex.numTables; i++) {
    if ((*_fileIndex.tables.Deleted())[i] != 1) {
      tableLocs[j] = (*_fileIndex.tables.Data())[i].GetObjectId();
      j++;
    }
  }

  numTables = 0; numBlocks = 0;
  char ** tableIds     = _GetTableIds(numTables);
  char ** tableNames   =  GetTableNames(numTables);
  char ** tableBlockNames   =  _GetTableBlockNames(numTables);
  char ** blockNames        =  GetBlockNames(numBlocks);
  
  // Append the file index and clean up the in-memory table cache and index.

  err = _f->WriteStrings(tableIds,    _fileIndex.numTables, (Word &) where);
  err += _f->WriteStrings(tableNames,  _fileIndex.numTables, (Word &) ret);
  err += _f->WriteStrings(tableBlockNames,  _fileIndex.numTables, (Word &) ret);
  err += _f->WriteStrings(blockNames,  _fileIndex.numBlocks, (Word &) ret);
  err += _f->WriteWords((Word *) tOrder, 0, (Word &) ret);
  err += _f->WriteWords((Word *) bOrder, 0, (Word &) ret);
  err += _f->WriteWords((Word *) tableLocs, _fileIndex.numTables, (Word &) ret);

  // Clean-up  

  if (tableLocs) delete[] tableLocs;
  if (bOrder)    delete[] bOrder;
  if (tOrder)    delete[] tOrder;
  for (i = 0; i < _fileIndex.numTables; i++) {
    if (tableIds[i])        delete[] tableIds[i];
    if (tableBlockNames[i]) delete[] tableBlockNames[i];
    if (tableNames[i])      delete[] tableNames[i];
  }

  for (i = 0; i < _fileIndex.numBlocks; i++) {
    if (blockNames[i])      delete[] blockNames[i];
  }


  if (tableIds)   delete[] tableIds;
  if (tableNames) delete[] tableNames;
  if (tableBlockNames) delete[] tableBlockNames;
  if (blockNames) delete[] blockNames;

  return err;
}

void TblFileObj::PrintHeaderInfo() {
  unsigned int i, j;
  cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
  cout << "TblFileObj::PrintHeaderInfo*TblFileObj::PrintHeaderInfo*TblFileObj::PrintHeaderInfo" <<endl;
  cout << "File name: " << _filename << endl;
  cout << "File mode: " << _mode << endl;
  cout << "Current Data Block: " << _currentBlock << endl;
  cout << "numBlocks = " << _fileIndex.numBlocks << endl;
  cout << "numTables = " << _fileIndex.numTables << endl;
  cout << "numTablesAllocated  = " << _fileIndex.tablesAllocated << endl;

  for (i=0; i < _fileIndex.numBlocks; i++) {
    cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
    cout << "Block [" << i << "] " << (*_fileIndex.blocks.Data())[i].GetName() << endl; 
  }

  for (i=0,j=0; j < _fileIndex.numTables; i++) {
    if ((*_fileIndex.tables.Deleted())[i] != 1) {
    cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
    cout << "Table [" << i << "] " << (*_fileIndex.tables.Data())[i].GetId() << endl; 
    cout << "block = " << (*_fileIndex.tables.Data())[i].GetBlock() << endl; 
    cout << "name = " << (*_fileIndex.tables.Data())[i].GetName() << endl; 
    cout << "objectId = " << (*_fileIndex.tables.Data())[i].GetObjectId() << endl; 
    cout << "memId = " << (*_fileIndex.tables.Data())[i].GetMemId() << endl; 
    cout << "numItems = " << (*_fileIndex.tables.Data())[i].GetNumItems() << endl;   }
    j++;
  }


  cout << "TblFileObj::PrintHeaderInfo*TblFileObj::PrintHeaderInfo*TblFileObj::PrintHeaderInfo" <<endl;
  cout << "eod+eod+eod+eod+eod+eod+eod+eod+eod+eod+eod+eod+eod+eod+eod+eod+eod+eod+eod+eod+eod" <<endl;
}

int TblFileObj::_ReadFileIndex() {
  int err = 0, numTables = 0, numBlocks=0, where=-1;
  int bOrderLen, tOrderLen;
  unsigned int i;

  if (!_f) return FILE_NOT_OPEN;
  if ((_mode != READ_MODE) && (_mode != UPDATE_MODE)) return FILE_NOT_READ_MODE;

  where = _f->Length() - 7; 
  if (where <  0 )  {
    return FILE_HEADER_INCONSISTENCY;
  }
  char ** tableIds   = _f->GetStrings(where,   (uWord &) numTables, err);
  if (err < 0) return err;

  char ** tableNames = _f->GetStrings(where+1, (uWord &) numTables, err);
  if (err < 0) return err;

  char ** tableBlockNames = _f->GetStrings(where+2, (uWord &) numTables, err);
  if (err < 0) return err;

  char ** blockNames = _f->GetStrings(where+3, (uWord &) numBlocks, err);
  if (err < 0) return err;

  SetDataBlock(blockNames[0]);

  int * tOrder2 = (int *) _f->GetWords(where + 4, (uWord &) tOrderLen, err);
  if (err < 0) return err;

  int * bOrder2 = (int *) _f->GetWords(where + 5, (uWord &) bOrderLen, err);
  if (err < 0) return err;

  int * locs = (int *) _f->GetWords(where + 6, (uWord &) numTables, err);
  if (err < 0) return err;

  _ManageTableSpace();
  _fileIndex.numTables = numTables;

  if (tOrderLen==0){
  for (i = 0; i < _fileIndex.numTables; i++) {
    TableInfo ti;
    if (!tableIds[i]) {
      ti.SetId("");
    } else {
      ti.SetId(tableIds[i]);
    }
    if (!tableNames[i]) {
      ti.SetName("");
    } else {
      ti.SetName(tableNames[i]);
    }
    if (!tableBlockNames[i]) {
      ti.SetBlock("");
    } else {
      ti.SetBlock(tableBlockNames[i]);
    }
    ti.SetObjectId(locs[i]);
    ti.SetMemId(-1);
    ti.SetNumItems(-1);
    ti.SetModified(0);
    _fileIndex.tables.Add(ti);
  }
  }
  else {
	 int * tOrder = new int[_fileIndex.numTables];
	 for (i = 0; i < _fileIndex.numTables; i++) {
		tOrder[tOrder2[i]]=i;
	 }
	 for (i = 0; i < _fileIndex.numTables; i++) {
		TableInfo ti;
		if (!tableIds[tOrder[i]]) {
		  ti.SetId("");
		} else {
		  ti.SetId(tableIds[tOrder[i]]);
		}
		if (!tableNames[tOrder[i]]) {
		  ti.SetName("");
		} else {
		  ti.SetName(tableNames[tOrder[i]]);
		}
		if (!tableBlockNames[tOrder[i]]) {
		  ti.SetBlock("");
		} else {
		  ti.SetBlock(tableBlockNames[tOrder[i]]);
		}
		ti.SetObjectId(locs[tOrder[i]]);
		ti.SetMemId(-1);
		ti.SetNumItems(-1);
		ti.SetModified(0);
		_fileIndex.tables.Add(ti);
	 }
	 if (tOrder) delete[] tOrder; 
	 tOrder = NULL;
  }

  _fileIndex.numBlocks = numBlocks;
  if (bOrderLen==0){
  for (i = 0; i < _fileIndex.numBlocks; i++) {
    BlockInfo bi;
    if (!blockNames[i]) {
      bi.SetName("");
    } else {
      bi.SetName(blockNames[i]);
    }
    _fileIndex.blocks.Add(bi);
  }
  }
  else {
	 int * bOrder = new int[_fileIndex.numBlocks];
	 for (i = 0; i < _fileIndex.numBlocks; i++) {
		bOrder[bOrder2[i]]=i;
	 }
	 for (i = 0; i < _fileIndex.numBlocks; i++) {
		BlockInfo bi;
		if (!blockNames[bOrder[i]]) {
		  bi.SetName("");
		} else {
		  bi.SetName(blockNames[bOrder[i]]);
		}
		_fileIndex.blocks.Add(bi);
	 }
	 if (bOrder) delete[] bOrder; 
	 bOrder = NULL;
  }


  // Clean-up ... 

  if (locs) free(locs); 
  locs = NULL;

  if (tOrder2) free(tOrder2); 
  tOrder2 = NULL;

  if (bOrder2) free(bOrder2); 
  bOrder2 = NULL;

  if (tableIds) {
    for (i = 0; i < _fileIndex.numTables; i++) {
      if (tableIds[i]) free(tableIds[i]); 
    }
    free(tableIds); 
    tableIds = NULL;
  }

  if (tableBlockNames) {
    for (i = 0; i < _fileIndex.numTables; i++) {
      if (tableBlockNames[i]) free(tableBlockNames[i]);
    }
    free(tableBlockNames); 
    tableBlockNames = NULL;
  }


  if (tableNames) {
    for (i = 0; i < _fileIndex.numTables; i++) {
      if (tableNames[i]) free(tableNames[i]);
    }
    free(tableNames);
    tableNames = NULL;
  }

  if (blockNames) {
    for (i = 0; i < _fileIndex.numBlocks; i++) {
      if (blockNames[i]) free(blockNames[i]);
    }
    free(blockNames);
    blockNames = NULL;
  }

  return 0;
}

int TblFileObj::_ShrinkFile(char *filename) {
  if ((!filename) || !strcmp("", filename)) return -1;
  CifString fname(filename);
  fname += ".tmp";
  unsigned int i;

  TblFileObj   fobj(fname.Text(), WRITE_MODE);
  TblFileObj * source;


  source = new TblFileObj(_filename, READ_MODE);
  if (!source) return -2;

  int numTables = 0;
  ISTable * tmpTable = NULL;
  char **tableNames  = GetTableNames(numTables);
  char **blockNames  = _GetTableBlockNames(numTables);

  for (i = 0; i < (unsigned int)numTables; i++) {
    tmpTable = source->GetTablePtr(blockNames[i],tableNames[i]);
    if (tmpTable) fobj.WriteTable(tmpTable,blockNames[i],tableNames[i]);
    tmpTable = NULL;
  }
  fobj.CloseFile();  
  source->CloseFile();
  delete source;
  source = NULL;

  if (blockNames) {
    for (i = 0; i < _fileIndex.numTables; i++) {
      if (blockNames[i]) delete blockNames[i];
    }
    delete blockNames;
    blockNames = NULL;
  }


  if (tableNames) {
    for (i = 0; i < _fileIndex.numTables; i++) {
      if (tableNames[i]) delete tableNames[i];
    }
    delete tableNames;
    tableNames = NULL;
  }

  return rename(fname.Text(), filename);
}


int TblFileObj::_DeleteTable(const char * tableId) {

  int memLoc, fileLoc;

  if ((tableId == NULL) || (strlen(tableId) == 0)) return -1;

  int index = _GetIndexFromId(tableId);
  if ((index < 0)) return -1;

  // clean up the index entry ...

  // clean up any in-memory copy of the table 
  memLoc = (*_fileIndex.tables.Data())[index].GetMemId();
  if ((memLoc >= 0) && (memLoc <= _lastTableInMem)) {
    if (_tableObjs[memLoc]) delete _tableObjs[memLoc];   // Reference counting later.
    _tableObjs[memLoc] = NULL;
  }
  int j;
  if (_mode == UPDATE_MODE) {
  // delete the table from persistent store ..
  fileLoc = (*_fileIndex.tables.Data())[index].GetObjectId();
  for (j = 0; j < (*_fileIndex.tables.Data())[index].GetNumItems(); j++) {
    _f->Delete(fileLoc + j);
  }
  }

#if 1
  if (memLoc < _lastTableInMem) {
    memmove(&_tableObjs[memLoc], &_tableObjs[memLoc + 1], (_lastTableInMem - memLoc)* sizeof(ISTable *));
  }
  _tableObjs[_lastTableInMem--] = NULL;

  j=0;
  for (int i = 0; j < (int)(_fileIndex.numTables); i++) {
    if ((*_fileIndex.tables.Deleted())[i] != 1){
      if ((*_fileIndex.tables.Data())[i].GetMemId() > memLoc) (*_fileIndex.tables.Data())[i].SetMemId((*_fileIndex.tables.Data())[i].GetMemId()-1);
      j++;
      }
  }
  _fileIndex.numTables--;
  // Delete  the index from BTreeObj tables .
  TableInfo ti;
  ti.SetId(tableId);
  _fileIndex.tables.Seek(ti);
  _fileIndex.tables.Delete();

#endif
  return 0;
}

int TblFileObj::DeleteTable(const char *blockName, const char * tableName) {
  char *id=NULL;
  int ret;

  id = _BuildTableId(blockName,tableName);
  if (!id) return TABLE_NOT_FOUND;
  ret =_DeleteTable(id);
  delete[] id;
  return(ret);
}
