/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "MvHovmFrame.h"

// Constructors
ParamInfo::ParamInfo(): param_(0), level_(0.), date_(0.), expver_("_"),
                        paramName_(" "), paramLongName_(" "), units_(" ")
{
// empty
}

ParamInfo::ParamInfo( int i1, double i2, double i5, string ev, string pn, string pln, string un) :
                     param_(i1), level_(i5), date_(i2), expver_(ev),
                     paramName_(pn), paramLongName_(pln), units_(un)
{
// empty
}

// Deletes all info about a parameter, including all space used
// for the level data.
ParamInfo::~ParamInfo()
{
   for ( IndexIterator ii = indexes_.begin(); ii != indexes_.end(); ii++ )
   {
      if ((*ii).second )
         delete [] (*ii).second->values_;
   }
}

string ParamInfo::LevelTitle()
{
   ostrstream oss;
   oss << level_ << " hPa" << ends;

   return oss.str();
}

string ParamInfo::ExpVerTitle()
{
   if( expver_ == "_" )     //-- missing ExpVer is stored as "_"
      return string("");
   else
      return string( "Expver " ) + expver_;
}

// Fill in data related to an index/entry in the IndexesMap. Generate
// the values if needed, and delete any old values from the entry.
void ParamInfo::FillIndex(double* x, const string& index, int n)
{
   // Save data for one entry
   IndexIterator ii = indexes_.find(index);
   if ( ii == indexes_.end() )
   {
      double ind = atof(index.substr(12,HOV_STEPSIZE).c_str());
      indexes_[ index ] = new IndexesInfo( ind );
      ii = indexes_.find(index);
   }
   else
   {
      if ( (*ii).second->values_ )
      {
         delete [] (*ii).second->values_;
         (*ii).second->values_ = 0;
      }
   }

   if (  (*ii).second->values_ == 0 )
      (*ii).second->values_ = new double[n];

   double *xx = (*ii).second->values_;
   for (int i = 0; i < n; i++)
      xx[i] = x[i] < DBL_MAX ? x[i] : HMISSING_VALUE;
}

void ParamInfo::AddIndex(string& index) 
{
   if ( indexes_.find(index) == indexes_.end() )
   {
      double ind = atof(index.substr(12,HOV_STEPSIZE).c_str());
      indexes_[ index ] = new IndexesInfo(ind);
   }
}
