#include <fstream>
#include <time.h>
#include "pngencoder.h"
#include "bmpdecoder.h"

using namespace std ;
using namespace Colosseum ;

void Progress (BitmapImageCoder &, void*, unsigned int pass, unsigned int passcount,
               unsigned int percent, bool &)
{
  unsigned int value = 100 * (pass - 1) / passcount + percent / passcount ;
  cout << value << "%                \r" << flush ;
}

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

  cerr << "Usage: " << program << " [-P -F -M -f] input.bmp output.png" << endl ;

  exit (1) ;
  return ;
}


main (int argc, char *argv [])
{
  time_t start = time (NULL) ;

  if (argc < 3)
    Usage (argc, argv) ;

  PngEncoder encoder ;

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

    switch (argv [ii][1])
    {
    case 'f':
      encoder.setUseFilters (true) ;
      break ;
    case 'F':
      encoder.setCompressionLevel (DeflateEncoder::FASTESTCOMPRESSION) ;
      break ;
    case 'M':
      encoder.setCompressionLevel (DeflateEncoder::MAXIMUMCOMPRESSION) ;
      break ;
    case 'P':
      encoder.setProgressFunction (Progress, 0) ;
      break ;
    default:
      Usage (argc, argv) ;
    }
  }

  BmpDecoder decoder ;
  BitmapImage image ;
  try
  {
    string input = argv [argc-2] ;
    decoder.readImageFile (input.c_str (), image) ;
  }
  catch (exception &ee)
  {
    cerr << ee.what () << endl ;
	throw ;
  }

  ofstream output (argv [argc-1], ios::binary) ;
  if (! output)
  {
    cerr << "Can't open output file " << argv [argc-1] << endl ;
    exit (1) ;
  }

  try
  {
    string output = argv [argc-1] ;
    encoder.writeImageFile (output.c_str (), image) ;
  }
  catch (exception &ee)
  {
    cerr << ee.what () << endl ;
  }
  time_t elapsed = time (NULL) - start ;
  cout << endl << elapsed << " Seconds" << endl ;
  return 0 ;
}
