#include <fstream>
#include <iostream>
#include <sstream>
#include "str_tok.h"

using namespace std;

#ifdef NO_MAIN
extern "C" {
extern int dec2bin_main(int argc, char ** argv);
}
int dec2bin_main(int argc, char ** argv)
#else
int main(int argc, char ** argv)
#endif
{
   if(argc != 3) {
      cerr << "usage: dec2bin <text-input-file> <binary-output-file>\n"; 
      return 1;
   }
   int rc = 0;
   fstream fin(argv[1], ios::in);
   fstream fout(argv[2], ios::out | ios::ate | ios::trunc | ios::binary);
   if(!fin.fail() && !fout.fail()) {
      fin.seekg(0L, ios::end);
      size_t sz = fin.tellg();
      fin.seekg(0L, ios::beg);
      char * buffer = new char[sz+1];
      memset(buffer, 0, sz+1);
      fin.read(buffer, sz);
      string_tokenizer stok(buffer, ",\r\n ");
      long count = 1;
      while(stok.has_next()) {
         string num = stok.get_next();
         stringstream str;
         str << num;
         int intval;
         str >> intval;
         char ch = intval;
         fout.write(&ch,sizeof(char)); 
         if((count % 1024) == 0) {
            fout.flush();
         }
         count++;
      }
      delete [] buffer;
      fin.close();
      fout.flush();
      fout.close();
   }
   else {
      cerr << "not found..." << endl;
      rc = 1;
   }
   return rc;
}
