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

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

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

      TCLAP::ValueArg<int>
        sr("r", "row", "Row", true, 0, "stack");
      TCLAP::ValueArg<int>
        sa("a", "cola", "column of stack A", true, 0, "stack");
      TCLAP::ValueArg<int>
        sb("b", "colb", "column of stack B", true, 1, "stack");

      TCLAP::ValueArg<int>
        si("s", "slice", "slice", true, 1, "1");

      TCLAP::ValueArg<std::string> dbdir("d", "db", "database dirctory", true, "", "databaase");
#ifndef _NOMAGICK_
      Magick::Image mim;
#endif
      cmd.add(sr);
      cmd.add(sa);
      cmd.add(sb);
      cmd.add(si);
      cmd.add(dbdir);

      cmd.parse(argc, argv);

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

      image2d ima;
      image2d imb;
      int ret;
      ret = imstore.getimage( sr.getValue(),sa.getValue(), si.getValue(),
                              2, ima );
      if( ret != 0 )
        exit(0);

      ret = imstore.getimage( sr.getValue(), sb.getValue(), si.getValue(),
                              2, imb );
      //      ima.logmult( 50000 );
      //      imb.logmult( 50000 );
      histequalize heq;
      heq.init( QUANTIZEFACTOR );
      heq.addimage( &ima );
      heq.addimage( &imb );
      heq.equalize( &ima );
      heq.equalize( &imb );
      //      ima.gaussian( 5 );
      //      imb.gaussian( 5 );
#ifndef _NOMAGICK_
      ima.getimage( mim );
      mim.write( "ima.jpg" );
      imb.getimage( mim );
      mim.write( "imb.jpg" );
#endif
      imagealign imaln;
      imaln.init( ima, imb, 0 );
      int goodoff;
      imagealign::transform it;
      goodoff = imaln.searchmultires( it );
#ifndef _NOMAGICK_
      imaln.write( ima, imb, it, mim);
      mim.write( "result.png" );    
#endif
    }
  catch (TCLAP::ArgException &e)
    {
      std::cout << "ERROR: " << e.error() 
                << " for arg " << e.argId() << "\n";
      return 0;
    }
  return 0;
}
