// ---------------------------------------------------------------------
// $Id: gaffitter.cc 230 2008-08-14 01:45:04Z daaugusto $
//
//   gaffitter.cc (created on Tue Aug 23 01:08:35 BRT 2005)
// 
//   Genetic Algorithm File Fitter (gaffitter)
//
//   Copyright (C) 2005-2008 Douglas A. Augusto
// 
// This file is part of gaffitter.
// 
// gaffitter is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3 of the License, or (at
// your option) any later version.
// 
// gaffitter is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with gaffitter; if not, see <http://www.gnu.org/licenses/>.
//
// ---------------------------------------------------------------------

#include "Optimizer.h"
#include "optimizers/GeneticAlgorithm.h"
#include "optimizers/BestFit.h"
#include "optimizers/Split.h"

#include "Params.h"
#include "Input.h"
#include "util/Exception.h"
#include "util/CmdLineException.h"

//----------------------------------------------------------------------
int main( int argc, char** argv ) 
{
   try {
      // read the options
      Params parameters( argc, argv );

      // just ShowUsage()?
      if( !parameters.Initialize() ) return 0;

      // read the filenames
      Input input( parameters );

      Optimizer* gaffitter = 0;

      try {
         // create the GA optimizer
         if( parameters.m_approximate )
            gaffitter = new BestFit( input );
         else if( parameters.m_split )
            gaffitter = new Split( input );
         else
            gaffitter = new GeneticAlgorithm( input );

         // evolve
         gaffitter->Evolve();

         // print the results
         gaffitter->Output();
      }
      catch( ... ) {
         delete gaffitter;
         throw;
      }

      delete gaffitter;
   }
   catch( const CmdLine::E_Exception& e ) {
      std::cerr << e;
      return 1;
   } 
   catch( const E_Exception& e ) 
   {
      std::cerr << e;
      return 2;
   } 
   catch( const std::exception& e )
   {
      std::cerr << '\n' << "> Error: " << e.what() << std::endl;
      return 3;
   }
   catch( ... ) {
      std::cerr << '\n' << "> Error: " << "An unknown error occurred." 
                << std::endl;
      return 4;
   }

   return 0; // ok, no errors
}
