#include "CifFileObj.h"

#include <iostream.h>


int main(int argc, char *argv[]) {

  char *diags=NULL;
  CifFileObj * fobjR = NULL;
  char *pname=NULL;
  char *iFile=NULL, *oFile=NULL;
  char *blockId=NULL;
  ISTable *t = NULL;
  int i;

  pname = argv[0];

  if (argc < 4) {
    cerr << pname << ":  usage = -f <inputfile> -o <outputfile> " << endl;
    exit(1);
  }
  

  for (i=1; i < argc; i++) {
    if ( argv[i][0] == '-' ) {
      if (strcmp(argv[i],"-f") == 0 ) {
	i++;
	iFile = (char *) calloc(strlen(argv[i]) + 1, sizeof(char));
	strcpy(iFile,argv[i]);          
      }	else if (strcmp(argv[i],"-o") == 0 ) {
	i++;
	oFile = (char *) calloc(strlen(argv[i]) + 1, sizeof(char));
	strcpy(oFile,argv[i]);          
      } else {
	cerr << pname << ":  usage = -f <inputfile> -o <outputfile> " << endl;
	exit(1);
      }
    } else {
      cerr << pname << ":  usage = -f <inputfile> -o <outputfile> " << endl;
      exit(1);
    }
  }
  fobjR = new CifFileObj("./test/tmp-cifparse.odb", WRITE_MODE, 80, "?", 0);
  fobjR->Read(iFile,diags);
  if (diags) cout << " Diagnostics [" << strlen(diags) << "] " << diags << endl;  
  fobjR->Write(oFile,1);
  fobjR->CloseFile(1);
  if (fobjR) delete fobjR;


  for (i=0; i < 10; i++) {
    cout << "--------------------STARTING CYCLE " << i << endl;

    fobjR = new CifFileObj("./test/tmp-cifparse.odb", UPDATE_MODE, 80, "?", 0);
    if (diags) cout << " Diagnostics [" << strlen(diags) << "] " << diags << endl;  
    blockId = fobjR->GetBlockName(0);    
    t = fobjR->GetTablePtr(blockId,"cell");
    cout << "--------------------AFTER READ ON CYCLE " << i << endl;
    cout << "Table name is " << t->GetName() << endl;
    ReVarCifArray<CifString> *qcolNames = t->GetItemNames();
    if (qcolNames) {
      for (int j=0; j < (int)qcolNames->Length(); j++){
	cout << (*qcolNames)[j].Text() << endl;
      }
      delete qcolNames;
    }

    fobjR->WriteTable(t,blockId,"cell");

    cout << "--------------------AFTER WRITE ON CYCLE " << i << endl;
    cout << "Table name is " << t->GetName() << endl;
    ReVarCifArray<CifString> *qqcolNames = t->GetItemNames();
    if (qcolNames) {
      for (int j=0; j < (int)qqcolNames->Length(); j++){
	cout << (*qqcolNames)[j].Text() << endl;
      }
      delete qqcolNames;
    }
    fobjR->CloseFile(1);
    if (fobjR) delete fobjR;
    if (blockId) delete[] blockId;
  }
  
  if (iFile) free(iFile);
  if (oFile) free(oFile);

  exit(0);
}

