#include "HMMLogger.hh"
#include "HMM.hh"

#ifdef DEBUG_LOGGER
#include "Syslog.h"
#endif

/*
 * class HMMLogger
 */

// structors :

HMMLogger::HMMLogger(char *name,HMM *hmm)
  :DataLogWriter(name, DataLog::BinaryFormat, AutoTimeStamp),
   m_hmm(hmm),lastobs("lastobs"),m_name(strdup(name))
{
  ssdbg(DBG_LOAD)("creating HMMLogger with name %s",m_name);
  lastobs.setLongName("Latest observation");
  lastobs.setUnits("UNITLESS");
  addField(&lastobs);
}

HMMLogger::~HMMLogger() {
  DoubleData *tmp;
  ssdbg(DBG_CLEAN)("destroying HMMLogger with name %s",m_name);
  free((void *)m_name);
  while(curstate.size()){
    tmp = curstate.back();
    curstate.pop_back();
    delete(tmp);
  }
}

// Modifiers :

void HMMLogger::addstate(const char *name, double init)
{
  DoubleData *dp = new DoubleData(name);
  char longname[64];
  sprintf(longname,"%s state",name);
  dp->setLongName(longname);
  dp->setUnits("Probability");
  addField(dp);
  curstate.push_back(dp);
}

// This is a little silly, but the main data logger always writes the
// log file even if there's a change.  Instead, we do our setFields
// updating in the callWrite function, then skip the call to
// DataLogWriter::write if there's no change.
void HMMLogger::setFields() {}

void HMMLogger::callWrite(){
  int i;

  if(m_hmm->updatelog()){
    for(i=0;i<curstate.size();i++){
      curstate[i]->setValue((double)m_hmm->statecur(i));
    }
    lastobs.setValue((short)m_hmm->curobs());
#ifdef DEBUG_LOGGER
    Syslog::write("HMMLogger -- Calling write function.");
#endif
    write();
}else{
#ifdef DEBUG_LOGGER
    Syslog::write("HMMLogger -- No new data.  Skip write.");
#endif
  }
}
