/*
  This file is part of CDO. CDO is a collection of Operators to manipulate and analyse Climate model Data.

  Author: Uwe Schulzweida

*/

/*
   This module contains the following operators:

      Monarith  monadd         Add monthly time series
      Monarith  monsub         Subtract monthly time series
      Monarith  monmul         Multiply monthly time series
      Monarith  mondiv         Divide monthly time series
*/

#include <cdi.h>

#include "process_int.h"
#include "cdo_vlist.h"
#include "field_functions.h"

static void
add_operators(void)
{
  cdo_operator_add("monadd", FieldFunc_Add, 0, nullptr);
  cdo_operator_add("monsub", FieldFunc_Sub, 0, nullptr);
  cdo_operator_add("monmul", FieldFunc_Mul, 0, nullptr);
  cdo_operator_add("mondiv", FieldFunc_Div, 0, nullptr);
}

class ModuleMonarith
{
  CdoStreamID streamID1;
  CdoStreamID streamID2;
  CdoStreamID streamID3;

  int taxisID1;
  int taxisID2;
  int taxisID3;

  FieldVector2D vars2;
  VarList varList1;
  Field field;

  int operfunc;

public:
  void
  init(void *process)
  {
    cdo_initialize(process);

    add_operators();

    auto operatorID = cdo_operator_id();
    operfunc = cdo_operator_f1(operatorID);

    operator_check_argc(0);

    streamID1 = cdo_open_read(0);
    streamID2 = cdo_open_read(1);

    auto vlistID1 = cdo_stream_inq_vlist(streamID1);
    auto vlistID2 = cdo_stream_inq_vlist(streamID2);
    auto vlistID3 = vlistDuplicate(vlistID1);

    vlist_unpack(vlistID3);

    vlist_compare(vlistID1, vlistID2, CmpVlist::All);

    varList_init(varList1, vlistID1);

    taxisID1 = vlistInqTaxis(vlistID1);
    taxisID2 = vlistInqTaxis(vlistID2);
    taxisID3 = taxisDuplicate(taxisID1);
    vlistDefTaxis(vlistID3, taxisID3);

    streamID3 = cdo_open_write(2);
    cdo_def_vlist(streamID3, vlistID3);

    fields_from_vlist(vlistID2, vars2, FIELD_VEC | FIELD_NAT);
  }

  void
  run()
  {
    int yearmon2 = -1;
    int tsID = 0;
    int tsID2 = 0;
    while (true)
      {
        auto nrecs = cdo_stream_inq_timestep(streamID1, tsID);
        if (nrecs == 0) break;

        auto vDate1 = taxisInqVdatetime(taxisID1).date;
        int year1, month1, day1;
        cdiDate_decode(vDate1, &year1, &month1, &day1);
        auto yearmon1 = year1 * 100 + month1;

        if (yearmon1 != yearmon2)
          {
            if (Options::cdoVerbose) cdo_print("Process: Year = %4d  Month = %2d", year1, month1);

            auto nrecs2 = cdo_stream_inq_timestep(streamID2, tsID2);
            if (nrecs2 == 0) cdo_abort("Missing year=%4d mon=%2d in %s!", year1, month1, cdo_get_stream_name(1));

            auto vDate2 = taxisInqVdatetime(taxisID2).date;
            int year2, month2, day2;
            cdiDate_decode(vDate2, &year2, &month2, &day2);
            yearmon2 = year2 * 100 + month2;
            if (yearmon1 != yearmon2)
              {
                cdo_abort("Timestep %d in %s has wrong date! Current year=%4d mon=%2d, expected year=%4d mon=%2d", tsID2 + 1,
                          cdo_get_stream_name(1), year2, month2, year1, month1);
              }

            for (int recID = 0; recID < nrecs2; ++recID)
              {
                int varID, levelID;
                cdo_inq_record(streamID2, &varID, &levelID);
                cdo_read_record(streamID2, vars2[varID][levelID]);
              }

            tsID2++;
          }

        cdo_taxis_copy_timestep(taxisID3, taxisID1);
        cdo_def_timestep(streamID3, tsID);

        for (int recID = 0; recID < nrecs; ++recID)
          {
            int varID, levelID;
            cdo_inq_record(streamID1, &varID, &levelID);
            field.init(varList1[varID]);
            cdo_read_record(streamID1, field);

            field2_function(field, vars2[varID][levelID], operfunc);

            cdo_def_record(streamID3, varID, levelID);
            cdo_write_record(streamID3, field);
          }

        tsID++;
      }
  }

  void
  close()
  {
    cdo_stream_close(streamID3);
    cdo_stream_close(streamID2);
    cdo_stream_close(streamID1);

    cdo_finish();
  }
};

void *
Monarith(void *process)
{
  ModuleMonarith monarith;
  monarith.init(process);
  monarith.run();
  monarith.close();

  return nullptr;
}
