#include "cccc_met.h"
#include "cccc.h"
#include <fstream.h>

Metric_Treatment::Metric_Treatment(istream& is)
{
  char namebuf[1000];
  lower_threshold=0;
  upper_threshold=0;
  numerator_threshold=0;
  width=0;
  precision=0;

  is >> code;

  if(is.good())
    {
  is >> lower_threshold >> upper_threshold >> numerator_threshold;
  is >> width >> precision;
  is.getline(namebuf,100);
  name=namebuf;
    }
}

Metric_Treatment_Table::Metric_Treatment_Table(istream& is)
{
  int nrec=0;
  while( !is.eof() && is.good() && nrec<MAX_TREATMENT_RECORDS )
    {
      // skip comment lines
      while(is.peek() == '#')
	{
	  char linebuf[1024];
	  is.getline(linebuf,1024);
	}
      records[nrec]=new Metric_Treatment(is);
      nrec++;
      is >> ws;
    }
  records[nrec]=NULL;
  if(nrec==MAX_TREATMENT_RECORDS)
  {
    cerr << "Warning: treatment record table truncated after "
	 << nrec << " entries" << endl;
  }
}
  
Metric_Treatment* Metric_Treatment_Table::lookup(const CCCC_String& metric_code)
{
  Metric_Treatment *retval=NULL, **record_ptr;
  record_ptr=&records[0];
  while(*record_ptr != NULL)
  {
    if(strcmp((*record_ptr)->code,metric_code)==0) { retval=*record_ptr; }
    record_ptr++;
  }
  return retval;
}

const CCCC_String& CCCC_Metric::value_string() const
{
  static CCCC_String retval;
  CCCC_String numerator_too_low="---";
  CCCC_String infinity="***";
  
  MAKE_STRSTREAM(valuestr);
  valuestr.setf(ios::fixed);
  int width=6, precision=0;
  float n_threshold=0, low_threshold=1e9, high_threshold=1e9;
  if(treatment!=NULL)
    {
      width=treatment->width;
      precision=treatment->precision;
      n_threshold=treatment->numerator_threshold;
      low_threshold=treatment->lower_threshold;
      high_threshold=treatment->upper_threshold;
    }
  valuestr.width(width);
  valuestr.precision(precision);
  if(numerator<n_threshold)
    {
      valuestr << numerator_too_low;
    }
  else if(denominator==0)
    {
      valuestr << infinity;
    }
  else
    {
      float result=numerator;
      result/=denominator;
      valuestr << result;
    }
  valuestr << ends;
  retval=valuestr.str();
  RELEASE_STRSTREAM(valuestr);
  return retval;
}

#ifdef UNIT_TEST
#include "cccc_db.h"
#include "cccc_htm.h"

main()
{
  CCCC_Metric m1, m2, m3, m4, m5;
  m1.set_treatment("LOC"); m1.set_ratio(14);
  m2.set_treatment("MVG"); m2.set_ratio(45,12);
  m3.set_treatment("L_C"); m3.set_ratio(9,4);
  m4.set_treatment("M_C"); m4.set_ratio(100,0);
  m5.set_treatment("LOC"); m5.set_ratio(7);

  CCCC_Project prj;
  CCCC_Html_Stream os(prj,"test.dat");
  os << m1 << m2 << m3 << m4 << m5 << "\n";

  return 0;
}
#endif











