#include "scalespace.h"
#include "imagesift.h"
#include "dbimage.h"
#include "bdbenv.h"
#include "dbalnimage.h"
#include <tclap/CmdLine.h>
#include <string>

int main( int argc, char *argv[] )
{

#ifndef _NOMAGICK_
  try
    {
      ///set up the command line parsing
      TCLAP::CmdLine cmd("Image alignment program", ' ', "0.001");

      TCLAP::ValueArg< int >
        aid("a", "aid", "tile id", true, 0, "id");
      TCLAP::ValueArg<int>
        fs("m", "median", "median filter size", true, 0, "filter size");

      TCLAP::ValueArg<int> si("i", "id", "image d", true, 0, "0" );
      TCLAP::ValueArg<int> ch("c", "channel", "channel", true, 0, "0" );
      TCLAP::ValueArg<std::string> dbdir("d", "db", "database dirctory", true, "", "databaase");
      cmd.add(aid);
      cmd.add(si);
      cmd.add(ch);
      cmd.add(fs);
      cmd.add(dbdir);

      bdbenv bdb;
      dbimage imstore;
      dbalnimage dba;

      cmd.parse(argc, argv);

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

      int myaid;
      std::cout << "checking aid\n";
      myaid = aid.getValue();

      Magick::Image mim1;

      if( dba.checkaid( myaid ) == 1 )
        {
          std::set<int> channels;
          std::cout << "getting channels\n";
          dba.get_channels(myaid, channels );
          std::cout << "checking for valid channel\n";
          int mych;
          mych = ch.getValue();
          if( channels.count( mych ) > 0 )
            {
              image2d im;
              dba.get_aligned_image( myaid, si.getValue(), mych, &im );
              scalespace ss;
              im.getimage_normalized( mim1 );
              ss.analyze( im, 0.005 );
              std::cout << "printing\n" << std::flush;
              ss.print( mim1 );
              mim1.write( "output.png" );
            }
          else
            {
              std::cout << "invalid channel\n";
            }
        }
      else
        {
          std::cout << "invalid aid\n";
        }

      dba.close();
      imstore.close();
      bdb.close();
    }
  catch (TCLAP::ArgException &e)
    {
      std::cout << "ERROR: " << e.error() 
                << " for arg " << e.argId() << "\n";
      return 0;
    }
  
#else
  std::cout << "compiled with no image magick\n";
#endif
  return 0;
}
