/***********************************************/
/**
* @file graceL1b2Time.cpp
*
* @brief Read GRACE L1B data.
*
* @author Beate Klinger
* @date 2017-02-02
*
*/
/***********************************************/

// Latex documentation
#define DOCSTRING docstring
static const char *docstring = R"(
This program converts time data (TIM1A or TIM1B) from the GRACE SDS format into \file{instrument file (MISCVALUE)}{instrument}.
For further information see \program{GraceL1b2Accelerometer}.
)";

/***********************************************/

#include "programs/program.h"
#include "files/fileInstrument.h"
#include "fileGrace.h"

/***** CLASS ***********************************/

/** @brief Read GRACE L1B data.
* @ingroup programsConversionGroup */
class GraceL1b2TimeOffset
{
public:
  void run(Config &config, Parallel::CommunicatorPtr comm);
};

GROOPS_REGISTER_PROGRAM(GraceL1b2TimeOffset, SINGLEPROCESS, "read GRACE L1B data (TIM1A or TIM1B)", Conversion, Grace, Instrument)

/***********************************************/

void GraceL1b2TimeOffset::run(Config &config, Parallel::CommunicatorPtr /*comm*/)
{
  try
  {
    FileName              fileNameOut;
    std::vector<FileName> fileNameIn;
    Double                fractionalScale;

    readConfig(config, "outputfileTime",  fileNameOut,     Config::MUSTSET,  "",     "MISCVALUE");
    readConfig(config, "fractionalScale", fractionalScale, Config::MUSTSET,  "1e-6", "1e-6 for GRACE, 1e-9 for GRACE-FO");
    readConfig(config, "inputfile",       fileNameIn,      Config::MUSTSET,  "",     "TIM1A or TIM1B");
    if(isCreateSchema(config)) return;

    // =============================================

    logStatus<<"read input files"<<Log::endl;
    Arc arc;
    for(UInt idFile=0; idFile<fileNameIn.size(); idFile++)
    {
      logStatus<<"read file <"<<fileNameIn.at(idFile)<<">"<<Log::endl;
      UInt numberOfRecords;
      FileInGrace file(fileNameIn.at(idFile), numberOfRecords);

      for(UInt idEpoch=0; idEpoch<numberOfRecords; idEpoch++)
      {
        Int32 obdh_time;
        Char  GRACE_id;
        Int32 TS_suppid, gpstime_intg, gpstime_frac, first_icu_blknr, final_icu_blknr;
        Byte  qualflg;

        try
        {
          file>>obdh_time>>GRACE_id>>TS_suppid>>gpstime_intg>>gpstime_frac>>first_icu_blknr>>final_icu_blknr>>FileInGrace::flag(qualflg);
        }
        catch(std::exception &/*e*/)
        {
          // GRACE-FO number of records issue
          logWarning<<arc.back().time.dateTimeStr()<<": file ended at "<<idEpoch<<" of "<<numberOfRecords<<" expected records"<<Log::endl;
          break;
        }

        if((gpstime_intg == 0) || (obdh_time == 0))
          continue;

        MiscValueEpoch epoch;
        epoch.time  = mjd2time(51544.5) + seconds2time(obdh_time);
        epoch.value = (gpstime_intg-obdh_time) + fractionalScale * gpstime_frac;
        arc.push_back(epoch);
      } // for(idEpoch)
    } // for(idFile)

    // =============================================

    logStatus<<"sort epochs"<<Log::endl;
    arc.sort();

    logStatus<<"eliminate duplicates"<<Log::endl;
    const UInt oldSize = arc.size();
    arc.removeDuplicateEpochs(TRUE/*keepFirst*/);
    if(arc.size() < oldSize)
      logInfo<<" "<<oldSize-arc.size()<<" duplicates removed!"<<Log::endl;

    Arc::printStatistics(arc);
    if(arc.size() == 0)
      return;

    if(!fileNameOut.empty())
    {
      logInfo<<"write data to <"<<fileNameOut<<">"<<Log::endl;
      InstrumentFile::write(fileNameOut, arc);
    }
  }
  catch(std::exception &e)
  {
    GROOPS_RETHROW(e)
  }
}

/***********************************************/
