#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"
#include "dbalnimage.h"
#include "alignimage.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> track("t", "trackdb", "tracker sqlite file", true, "", "tracker output");
      TCLAP::ValueArg<int> upgrade("u", "upgrade", "db upgrade flag", false, 0, "upgrade flag");
      TCLAP::ValueArg<int> rebuild("r", "rebuild", "rebuild all indecies", false, 0, "index rebuild");

      //      clustermanager cm;
#ifndef _NOMAGICK_
      Magick::Image mim;
#endif

      cmd.add( track );
      cmd.add( upgrade );
      cmd.add( rebuild );

      cmd.parse(argc, argv);

      psotracker psostat;
      std::string trackdbname;
      trackdbname = track.getValue();
      if( upgrade.getValue() == 1 )
        psostat.upgrade( trackdbname );
      if( rebuild.getValue() == 1 )
        psostat.init( trackdbname, 1 );
      else
        psostat.init( trackdbname, 0 );
      psostat.printavgmiscore();
      psostat.printsearched();
      psostat.printpoints(400);
      double lowx, lowy, highx, highy;
      psostat.printsliceparticles( lowx, lowy, highx, highy );
      int sx, sy;
      sx = (int)( highx - lowx + 1 );
      sy = (int)( highy - lowy + 1 );
      image2d sp;
      sp.create( sx, sy );
      double totalsp = sx*sy;
      std::vector< psoparticle > particles;
      for( int i = 0; i < 400; i++ )
        {
          particles.clear();
          psostat.getparticles( i, particles );
          for( unsigned j = 0; j < particles.size(); j++ )
            sp.setpixel( (int)particles[j].x-lowx, (int)particles[j].y-lowy, 1 );
          std::cout << i << ": " << sp.sum()/totalsp << "\n";
        }

      //psostat.printsliceparticles( 400 );
      std::cout << "SEARCHED REGION: " << psostat.searched() << "\n";
      psostat.close();
    }
  catch (TCLAP::ArgException &e)
    {
      std::cout << "ERROR: " << e.error() 
                << " for arg " << e.argId() << "\n";
      return 0;
    }
  return 0;
}
