#ifndef _NOMAGICK_
#include <Magick++.h>
#endif

#include <iostream>
#include <string>
#include <fstream>
#include <math.h>
#include "imagealign.h"
#include "image2d.h"
#include <fftw3.h>
#include <tclap/CmdLine.h>
#include "bdbenv.h"
#include "dbimage.h"
#include "pso.h"
#include "histequalize.h"
#include "tile.h"
#include "tileimage.h"

int main( int argc, char *argv[] )
{
  try
    {
      ///set up the command line parsing
      TCLAP::CmdLine cmd("Image alignment program", ' ', "0.001");

      TCLAP::ValueArg<std::string> dbdir("d", "db", "database dirctory", true, "", "databaase");

      TCLAP::ValueArg<char> col("c", "column", "column number", true, '0', "column number");
      TCLAP::ValueArg<char> row("r", "row", "row number", true, 'a', "row number");

      TCLAP::ValueArg<int> slice( "s", "slice", "slice number", true, 0, "slice number");
      TCLAP::ValueArg<int> channel("l", "channel", "channel number", true, 0, "channel number");

      cmd.add(dbdir);
      cmd.add( row );
      cmd.add(col);
      cmd.add(slice);
      cmd.add(channel);

      cmd.parse(argc, argv);

      bdbenv bdb;
      dbimage imstore;

      bdb.open( dbdir.getValue() );
      imstore.init( bdb.envptr() );
      bdb.adddb( &imstore );
      bdb.cleanlog();

      image2d myim;
      imstore.getimage( row.getValue(), col.getValue(), slice.getValue(), channel.getValue(), myim ); 

#ifndef _NOMAGICK_
      Magick::Image mim;
      char buffer[512];
      sprintf( buffer, "original_%c_%c_%i_%i.png", row.getValue(), col.getValue(), slice.getValue(), channel.getValue() );
      myim.getimage_normalized( mim );
      mim.write( buffer );
      histequalize heq;
      heq.init( QUANTIZEFACTOR );
      heq.addimage( &myim );
      heq.equalize( &myim );
      myim.getimage( mim );
      sprintf( buffer, "equalized_%c_%c_%i_%i.png", row.getValue(), col.getValue(), slice.getValue(), channel.getValue() );
      mim.write(buffer);
#endif
      imstore.close();
      bdb.close();
    }
  catch (TCLAP::ArgException &e)
    {
      std::cout << "ERROR: " << e.error() 
                << " for arg " << e.argId() << "\n";
      return 0;
    }

  return 0;
}
