#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 "dbtmpfeature.h"
#include <algorithm>
#include "som.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, "", "database");

      TCLAP::ValueArg<std::string> resume( "r", "resume", "resume file",
                                           false, "", "resume xml file");

      TCLAP::ValueArg<std::string> xml( "x", "xml", "xml out file", false,
                                        "", "resume out xml file");

#ifndef _NOMAGICK_
      Magick::Image mim;
#endif

      cmd.add(dbdir);
      cmd.add(resume);
      cmd.add(xml);

      cmd.parse(argc, argv);

      bdbenv bdb;
      dbtmpfeature fdb;
      som mysom;
      //      bdb.setcache( 1, 0 );
      bdb.setopenflags( DB_CREATE | DB_THREAD |
                        DB_INIT_LOG | DB_INIT_MPOOL |
                        DB_INIT_TXN | DB_PRIVATE );

      bdb.open( dbdir.getValue() );
      fdb.setrecsize( sizeof(double)*(32+6) );
      fdb.init( bdb.envptr() );

      bdb.adddb( &fdb );
      bdb.cleanlog();
      if( resume.getValue() == "" )
        {
          std::vector< int > dims;
          dims.push_back(6);
          dims.push_back(6);
          dims.push_back(6);
          mysom.init( &fdb, 32+6, dims );
          mysom.run( xml.getValue() );
        }
      else
        {
          mysom.init( &fdb, resume.getValue() );
          mysom.run( xml.getValue() );
        }
      fdb.close();
      bdb.close();
    }
  catch (TCLAP::ArgException &e)
    {
      std::cout << "ERROR: " << e.error() 
                << " for arg " << e.argId() << "\n";
      return 0;
    }
  return 0;
}
