/***********************************************/
/**
* @file noiseSatelliteTracking.cpp
*
* @brief Apply GRACE differential filter to white noise and add the result to satellite tracking data.
*
* @author Torsten Mayer-Guerr
* @date 2003-01-26
*/
/***********************************************/

// Latex documentation
#define DOCSTRING docstring
static const char *docstring = R"(
This program adds noise to simulated satellite tracking data generated by \program{SimulateSatelliteTracking}.
See \configClass{noiseGenerator}{noiseGeneratorType} for details on noise generation.
)";

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

#include "programs/program.h"
#include "files/fileInstrument.h"
#include "classes/noiseGenerator/noiseGenerator.h"

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

/** @brief Apply GRACE differential filter to white noise and add the result to satellite tracking data.
* @ingroup programsGroup */
class NoiseSatelliteTracking
{
public:
  void run(Config &config, Parallel::CommunicatorPtr comm);
};

GROOPS_REGISTER_PROGRAM(NoiseSatelliteTracking, PARALLEL, "generate noise and add the result to satellite tracking data", Simulation, Noise, Instrument)

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

void NoiseSatelliteTracking::run(Config &config, Parallel::CommunicatorPtr comm)
{
  try
  {
    FileName          inName, outName;
    NoiseGeneratorPtr noiseRange, noiseRate, noiseAcc;

    readConfig(config, "outputfileSatelliteTracking", outName,    Config::MUSTSET,  "", "");
    readConfig(config, "inputfileSatelliteTracking",  inName,     Config::MUSTSET,  "", "");
    readConfig(config, "noiseRange",                  noiseRange, Config::DEFAULT,  "", "[m]");
    readConfig(config, "noiseRangeRate",              noiseRate,  Config::DEFAULT,  "", "[m/s]");
    readConfig(config, "noiseRangeAcceleration",      noiseAcc,   Config::DEFAULT,  "", "[m/s^2]");
    if(isCreateSchema(config)) return;

    logStatus<<"add noise to tracking data"<<Log::endl;
    InstrumentFile sstFile(inName);
    std::vector<Arc> arcList(sstFile.arcCount());

    Parallel::forEach(arcList, [&](UInt arcNo)
    {
      SatelliteTrackingArc sst = sstFile.readArc(arcNo);
      Matrix data = sst.matrix();
      data.column(1) += noiseRange->noise(data.rows());
      data.column(2) += noiseRate->noise(data.rows());
      data.column(3) += noiseAcc->noise(data.rows());
      return Arc(sst.times(), data, sst.getType());
    }, comm);

    if(Parallel::isMaster(comm))
    {
      logStatus<<"write tracking data to file <"<<outName<<">"<<Log::endl;
      InstrumentFile::write(outName, arcList);
      Arc::printStatistics(arcList);
    }
  }
  catch(std::exception &e)
  {
    GROOPS_RETHROW(e)
  }
}

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