/** 
* @file FCReadCache.cpp
* @author Erik Rodner
* @date 11/15/2007

*/
#include <iostream>

#include "vislearning/features/simplefeatures/FCReadCache.h"
#include "vislearning/baselib/Globals.h"

using namespace OBJREC;

using namespace std;
// refactor-nice.pl: check this substitution
// old: using namespace ice;
using namespace NICE;



FCReadCache::FCReadCache( const Config * conf ) : FeatureFactory ( conf )
{
    cachedir = conf->gS("cache", "root");
    cachemode = Globals::getCacheMode ( conf->gS("cache", "mode", "cat") );
    extension = conf->gS("cache", "feature_file_ext", "feature" );
    cache_debug = conf->gB("cache", "cache_debug", false );
    string feature_format_s = conf->gS("cache", "feature_format", "std");

    if ( feature_format_s == "std" ) 
	feature_format = FEATURE_FORMAT_STANDARD;
    else if ( feature_format_s == "simple" )
	feature_format = FEATURE_FORMAT_SIMPLE;
    else {
	fprintf (stderr, "FCReadCache: feature format %s unknown", feature_format_s.c_str() );
	exit(-1);
    }
}

FCReadCache::~FCReadCache()
{
}

int FCReadCache::readSimpleText ( ifstream & ifs, NICE::Vector & vec )
{
    vec.resize(128);

    unsigned int count = 0;
    while ( ifs.good() )
    {
	double value;
	if ( ! ( ifs >> value ) ) break;
	if ( count >= vec.size() ) 
	    vec.resize( 2*vec.size() );

	vec[count] = value;
	count++;
    }

    vec.resize(count);

    return vec.size();
}

int FCReadCache::convert ( const NICE::Image & img, NICE::Vector & vec )
{
    std::string filename = Globals::getCacheFilename ( cachedir, cachemode );
    std::string filename_feat = filename + "." + extension;

    if ( cache_debug )
	fprintf (stderr, "FCReadCache: reading feature from file %s ...\n", filename_feat.c_str() );

    ifstream ifs ( filename_feat.c_str(), ios::in );
    if ( ! ifs.good() )
    {
	fprintf (stderr, "FCReadCache: unable to read file %s\n",
	    filename_feat.c_str());
	exit(-1);
    }

    if ( feature_format == FEATURE_FORMAT_SIMPLE ) 
	readSimpleText ( ifs, vec );
    else
	ifs >> vec;

    ifs.close();

    if ( cache_debug ) 
	fprintf (stderr, "FCReadCache: feature successfully read\n" );

    return 0;
}