/****************************************************************

 The idea of this is that you have something that can load a file
  of any type into a generic format buffer. This version is a 
  direct load used for text files.

Method summary:

   int LoadFile( Accumulator * buffer, char * fileName);
 //int SaveFile( Accumulator * buffer, char * fileName); // Later...
 

 ????       dan, created 
 mar 05 2002 dan, switched to class from header
 jul 05 2002 dan, using new accumulator methods.
 aug 02 2002 dan, added save method

****************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include "accumulator2.h"
#include "filefilter.h"


FileFilter1::FileFilter1( void ) {
}

FileFilter1::~FileFilter1( void ) {
}


/************************************

Load a file into the given Accumulator

I think I know why streams were invented.

In:  
  buffer   An Accumulator to load into.
  FileName The path/filename of a file to load.
  
Out: 
  0 = failure right now I dont care why it failed.
  1 = success

************************************/

int FileFilter1::LoadFile( Accumulator * buffer, char * FileName ){

  FILE *input;

  //open file
  if (( input = fopen ( FileName, "rb" )) == NULL) { 
      printf("Unable to open %s for input.\n", FileName);
      return 0;
  }

  // get file size
  fseek ( input, 0,  SEEK_END);
  long fsize = ftell ( input );

   // copy it into the buffer
  fseek ( input, 0, SEEK_SET );

  char * tempBuff; 
  long vol;
  size_t chunk;

  tempBuff = new char[1026];
  
  for(vol = fsize; vol > 0; ) {
    vol -= (chunk = fread(tempBuff, 1, 1024, input));
    // printf("chunk is %ld\n", chunk);
    buffer->SetN(buffer->GetSize()-1, 0, tempBuff, chunk); 
  }
  buffer->SetN(buffer->GetSize()-1, 0, "\0", 1); // null termination, ironic...

  delete[] tempBuff;

  //close file
  fclose ( input );
  return 1;

}

CESError_t FileFilter1::SaveFile( Accumulator * buffer, char * FileName ){

 FILE *output;

  printf("EEEk, your calling the untested file write function!\n"); // sigh...

  //open file
  if (( output = fopen ( FileName, "w+b" )) == NULL) { 
      printf("Unable to open %s for output. bailing\n", FileName);
      return OutputError;
  }

  char * tempBuff; 
  long   vol      = 0;
  size_t chunk;

  tempBuff = new char[1026];
  
  while((chunk = buffer->ReadN( vol, tempBuff, 1024)) > 0 ) {
    vol += chunk;
    // printf("chunk is %ld\n", chunk);
    fwrite( &tempBuff, 1, chunk, output ); 
  }
  
  delete[] tempBuff;

  //close file
  fclose ( output );
  return NoError;

  
}
	
