#include <fstream>
#include "jpgdecoder.h"
#include "bitmapimage.h"
#include "bmpencoder.h"

using namespace std ;
using namespace Colosseum ;

void Progress (BitmapImageCoder &coder,
               void *data,
               unsigned int currentpass,
               unsigned int passcount,
               unsigned int progress,
               bool &cancel)
{
  cout << currentpass << " of " << passcount << " " <<  progress << "%           \r" << flush ;
  return ;
}


void Usage (int argc, char *argv [])
{
  char *program ;
  if (argc != 0)
    program = argv [0] ;
  else
    program = "DECODER" ;

  cerr << "Usage: " << program << " [-flags] input.jpg output.bmp" << endl ;
  cerr << "Flags:  -v          Verbose" << endl ;
  cerr << "Flags:  -f          Use Filters" << endl ;
  exit (1) ;
}

int main(int argc, char *argv [])
{
  if (argc < 3)
  {
    Usage (argc, argv) ;
    return 1 ;
  }

  JpegDecoder decoder ;
  for (unsigned int ii = 1 ; ii < argc - 2 ; ++ ii)
  {
    if (argv [ii][0] != '-')
      Usage (argc, argv) ;

    switch (argv [ii][1])
    {
    case 'v':
      decoder.setVerbose (true) ;
      break ;
    case 'f':
      decoder.setUseFilters (true) ;
      break ;
    default:
      Usage (argc, argv) ;
    }
  }

  BitmapImage image ;
  cout << "Reading Image..." << endl ;
  try
  {
    string is = argv [argc-2] ;
    decoder.readImageFile (is.c_str (), image) ;
  }
  catch (GraphicsException &ee)
  {
    cerr << ee.what () << endl << flush ;
    return 1 ;
  }

  cout << "Writing Output..." << endl ;
  ofstream os (argv [argc-1], ios::binary|ios::trunc) ;
  if (! os)
  {
    cerr << "Can't open output file " << argv [argc-1] << endl ;
    return 1 ;
  }

  BmpEncoder bs ;
  try
  {
    string os = argv [argc-1] ;
  	bs.writeImageFile (os.c_str (), image) ;
  }
  catch (GraphicsException &ee)
  {
    cerr << ee.what () << endl << flush ;
    return 1 ;
  }
  cout << "Done..." << endl << flush ;

  return 0;
}
