/** 
* @file boviceObjectBankFeatures.cpp
* @brief convert ObjectBank features to a sparse BoV histogram representation
* @author Erik Rodner
* @date 01/23/2012

*/
#include <algorithm>
#include "core/basics/Config.h"
#include "vislearning/cbaselib/MultiDataset.h"
#include "vislearning/cbaselib/MutualInformation.h"
#include "vislearning/baselib/Globals.h"

using namespace std;
using namespace NICE;
using namespace OBJREC;

void boviceFeatures ( const Config & conf, const Vector & thresholds, 
                    const LabeledSet & ls, const string & srcExtension, const string & dstExtension )
{
  string cacheroot = conf.gS("cache", "root");

  LOOP_ALL_S ( ls ) 
  {
    EACH_S(classno, imgfn);
    Globals::setCurrentImgFN ( imgfn ); 
    string cachefn = Globals::getCacheFilename ( cacheroot, Globals::SORT_CATEGORIES ) + srcExtension;
    cerr << "processing " << cachefn << endl;

    vector<double> x;
    ifstream ifs ( cachefn.c_str(), ios::in );
    if ( ! ifs.good() )
      fthrow(Exception, "File not found: " << cachefn );
    while ( !ifs.eof() ) {
      double val = 0.0;
      if ( ifs >> val )
        x.push_back(val);
    }
    ifs.close();
   

    Vector xnew ( 177, 0.0 );
    for ( uint i = 0 ; i < 177; i++ )
      for ( uint j = 0 ; j < 252 ; j++ )
        xnew[i] += ( x[j + i*252] > thresholds[i] ) ? 1.0 : 0.0;

    xnew.normalizeL1();

    string dst_cachefn = Globals::getCacheFilename ( cacheroot, Globals::SORT_CATEGORIES ) + dstExtension;
    ofstream ofs ( dst_cachefn.c_str(), ios::out );
    if ( ! ofs.good() )
      fthrow(Exception, "Unable to write to " << dst_cachefn );
    ofs << xnew << endl;
    ofs.close ();
  }
    
}

/** 
    
    convert ObjectBank features to a sparse histogram representation 
    
*/
int main (int argc, char **argv)
{   
  std::set_terminate(__gnu_cxx::__verbose_terminate_handler);

  Config conf ( argc, argv );
    
  MultiDataset md ( &conf );
  const LabeledSet *train = md["train"];
  const LabeledSet *test = md["test"];
  string dstExtention = conf.gS("main", "dstext", ".txt");
  string threshFile = conf.gS("main", "threshfile");

  Vector thresholds ( 177 );
  ifstream ifs ( threshFile.c_str(), ios::in );
  if ( !ifs.good() )
    fthrow(Exception, "Unable to open threshold file!");

  int index = 0;
  while ( !ifs.eof() )
  {
    double val;
    if ( ifs >> val ) {
      if ( index >= thresholds.size() )
        fthrow(Exception, "Error parsing threshold file!");
      thresholds[index] = val;
    }
    index++;
  }

  ifs.close();

  boviceFeatures ( conf, thresholds, *train, ".jpg.feat", dstExtention );
  boviceFeatures ( conf, thresholds, *test, ".jpg.feat", dstExtention );
    
  return 0;
}