/*
$Id: ReadTextFile.cc 1597 2006-06-30 07:17:31Z suzuki $
*/


#include "ReadTextFile.hh"
/////////////////////////////////////////
ReadTextFile::
ReadTextFile()
{
  StringBuffer = NULL;
  split = NULL;
}
/////////////////////////////////////////
ReadTextFile::
~ReadTextFile()
{
  if( StringBuffer != NULL ) delete StringBuffer;
  if( split != NULL )        delete split;
}
/////////////////////////////////////////
void ReadTextFile::
SetFileName( std::string TargetFileName )
{
  Size = CheckFile( TargetFileName );

  if( StringBuffer != NULL ){
    delete StringBuffer;
    StringBuffer = NULL;
  }
  if( split != NULL ){
    delete split;
    split = NULL;
  }

  if( Size >0 ){
    StringBuffer = new std::vector< std::string >;
    split = new SplitString();
  }

  Read( TargetFileName );
}
/////////////////////////////////////////
UInt4 ReadTextFile::
PutSize(){
  if( StringBuffer == NULL ){
    return 0;
  }
  return (UInt4)(StringBuffer->size());
}
/////////////////////////////////////////
void ReadTextFile::
Dump()
{
  UInt4 Length = (UInt4)(StringBuffer -> size());
  for( UInt4 l=0; l<Length; l++ ){
    std::cout << l << "\t" << ( *StringBuffer )[l] << std::endl;
  }
}
/////////////////////////////////////////
std::string ReadTextFile::
Put( UInt4 IndexNumber )
{
  if( IndexNumber >= StringBuffer->size() ){
    std::cout << "\"IndexNumber\" should be smaller than "
              << "the number of lines of the target file." << std::endl;
    return "zero";
  }
  return ( *StringBuffer )[IndexNumber];
}
//////////////////////////////////////////
std::vector<std::string> ReadTextFile::
Put( UInt4 IndexNumber, std::string Delimiter )
{
  return split -> PutStringArray( Put(IndexNumber), Delimiter );
}
//////////////////////////////////////////
UInt4 ReadTextFile::
CheckFile( std::string FileName )
{
  std::ifstream inputfile;
  inputfile.open( FileName.c_str() );
  if( !inputfile ){
    std::cout << "Cannot open " << FileName << " !" << std::endl;
    return 0;
  }

  UInt4 line = 0;
  char c;

  while( inputfile.get( c ) ){
    if( c == '\n' ){
      line++;
    }
  }

  inputfile.close();
  return line;
}
///////////////////////////////////////////
void  ReadTextFile::
Read( std::string FileName )
{
  std::ifstream inputfile;
  inputfile.open( FileName.c_str() );
  if( !inputfile ){
    std::cout << "Cannot open " << FileName << " !" << std::endl;
    return;
  }

  Char *c = new Char[2];
  c[0] = '\0';
  c[1] = '\0';

  std::string Buffer;
  Buffer.clear();

  while( inputfile.get( c[0] ) ){
    std::string cc( c );
    Buffer = Buffer + cc;
  }

  std::vector<std::string> v = split -> PutStringArray( Buffer, "\n" );
  UInt4 size = (UInt4)(v.size());
  for( UInt4 s=0; s<size; s++ ){
    StringBuffer -> push_back( v[s] );
  }

  inputfile.close();
  delete [] c;
}
///////////////////////////////////////////
