/*
$Id: ReadWriteTextFile.cc 1562 2006-06-08 10:27:20Z suzuki $
*/

void OnFlock(int fd)
{

#ifdef LOCK_EX
  flock(fd, LOCK_EX);
#endif

}

#include "ReadWriteTextFile.hh"
///////////////////////////////////////////////
ReadWriteTextFile::
ReadWriteTextFile( std::string _FileName, UInt4 _LockFlag )
{
  FileName = _FileName;
  LockFlag = _LockFlag;
  v.clear();
  fin = NULL;

  if( ( fin = fopen( FileName.c_str() , "a" ) ) == NULL ){
    std::cout << "Failed to open " << FileName << std::endl;
  } // File open and lock it.
  if( LockFlag == 1 ) OnFlock( fileno( fin ) );
}
///////////////////////////////////////////////
ReadWriteTextFile::
~ReadWriteTextFile()
{
  // flock( fileno( fin ), LOCK_UN );
  fclose( fin );
}
///////////////////////////////////////////////
void ReadWriteTextFile::
ReSetTarget( std::string _FileName, UInt4 _LockFlag )
{
  if( fin != NULL ){
    fclose( fin );
  }

  FileName = _FileName;
  LockFlag = _LockFlag;
  v.clear();

  if( ( fin = fopen( FileName.c_str() , "a" ) ) == NULL ){
    std::cout << "Failed to open " << FileName << std::endl;
  } // File open and lock it.
  if( LockFlag == 1 ) OnFlock( fileno( fin ) );
}
///////////////////////////////////////////////
void ReadWriteTextFile::
Read()
{
  if( LockFlag == 1 ) OnFlock( fileno( fin ) );
  FILE* tmp=freopen( FileName.c_str() , "r", fin );
  if( LockFlag == 1 ) OnFlock( fileno( fin ) );

  v.clear();

  Int4 b;
  std::string StrBuf;

  while( ( b = fgetc( fin ) ) != EOF ){
    Char *c = ( Char* )( &b );

    if( *c == '\n' ){
      if( StrBuf.size() > 0 ){
        v.push_back( StrBuf );
      }
      StrBuf.clear();
    }

    else if( *c != '\0' ){
      StrBuf = StrBuf + std::string( c );
    }
  }
}
///////////////////////////////////////////////
void ReadWriteTextFile::
Write( std::vector<std::string> StrVec )
{
  if( LockFlag == 1 ) OnFlock( fileno( fin ) );
  FILE* tmp=freopen( FileName.c_str() , "w", fin );
  if( LockFlag == 1 ) OnFlock( fileno( fin ) );


  UInt4 Size = (UInt4)(StrVec . size());
  for( UInt4 i=0; i<Size; i++ ){
   std::fprintf( fin, "%s\n", ( StrVec[i] ).c_str() );
  }

}
///////////////////////////////////////////////
