#include "iostream.h"
#include "csmalloc.h"
#include "demodb.h"


////////////////////////////////////////////////////////////////////////
///////////////  Display Intro screen //////////////////////////////////
////////////////////////////////////////////////////////////////////////

void help(void)
{
      cout<<endl<<endl;
      cout<<"LOAD version 1.0 for "<<_CP_PLATFORM<<endl;
      cout<<"  Fills the database by parsing an input ASCII file."<<endl;
      cout<<"Copyright (c) ComBits, 1996"<<endl;
      cout<<"Compiled: "<<__DATE__<<",  "<<__TIME__<<endl<<endl;
      cout<<"SYNTAX:  load <filename>     "<<endl;
      cout<<"  filename: The name of the input file.  "<<endl<<endl;
      cout<<"EXAMPLE: load college.txt     "<<endl;
}

////////////////////////////////////////////////////////////////////////
///////////////  Main program //////////////////////////////////////////
////////////////////////////////////////////////////////////////////////



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



#define BUFFERLENGTH  200


  char	 LineBuffer[BUFFERLENGTH];
  char	 NameBuffer[BUFFERLENGTH];
  char	 DataBuffer[BUFFERLENGTH];


//alloc_logging(TRUE);	 // Uncomment if you like allocation logging.

  DEMO	 demo;	// An instance of the generated DEMO class.

  if(argc!=2)
  {
    help();
    return 1;
  }



////// Create Database and Indexes.
////// If they exist, they are OVERWRITTEN!

  if(!demo.define())
  {
     cout<<"Error, can't create database. "<<endl;
     return 8;
  }



////// Open the now existing Database and Indexes.

  if(!demo.open(100))  // Open with 100Kb buffers.
  {
     cout<<"Error, can't open databases. "<<endl;
     return 8;
  }




////// Open input file.


  FILE *fp;


  fp=fopen(argv[1],"r");

  if(fp==NULL)
  {

     cout<<"Error, can't open input file "<<argv[1]<<'.'<<endl;
     return 12;

  }



  cout<<endl<<endl;

////// Parse input file.


  while(!feof(fp))
  {

    if(fgets(LineBuffer,BUFFERLENGTH,fp))
    {
       trim_string(LineBuffer);   // Remove leading and trailing white space.
       if(strlen(LineBuffer))	  // Skipping empty lines.
       {

	  str_split(LineBuffer,' ',DataBuffer,NameBuffer);

	  trim_string(NameBuffer);
	  trim_string(DataBuffer);

	  demo.append();	  // Insert empty record.

	  demo.name(NameBuffer);  // Update name field.
	  demo.data(DataBuffer);  // Update data field.

	  if(demo.numrec()%713==1) // Update counter every 713 records.
	     cout<<"\r Record "<<demo.numrec()<<'.';

       }
    }

  }


  cout<<"\r Record "<<demo.numrec()<<'.'<<endl;


////// Close input file.

  fclose(fp);


////// Close Database and Indexes.

  if(!demo.close())
  {
     cout<<"Error, while closeing databases. "<<endl;
     return 8;
  }

////// Display errors IF ANY. Otherwise nothing is displayed.

  demo.display_error();


////// Return error level 0 to the command line.

  return 0;

}
