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

  Copyright (C) 2003-2020 Uwe Schulzweida, <uwe.schulzweida AT mpimet.mpg.de>
  See COPYING file for copying and redistribution conditions.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; version 2 of the License.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
*/

/*
   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 "cdo_options.h"
#include "functs.h"
#include "process_int.h"
#include "cdo_vlist.h"

void *
Monarith(void *process)
{
  int nrecs, nrecs2;
  int varID, levelID;
  int yearmon2 = -1;

  cdoInitialize(process);

  cdoOperatorAdd("monadd", func_add, 0, nullptr);
  cdoOperatorAdd("monsub", func_sub, 0, nullptr);
  cdoOperatorAdd("monmul", func_mul, 0, nullptr);
  cdoOperatorAdd("mondiv", func_div, 0, nullptr);

  const auto operatorID = cdoOperatorID();
  const auto operfunc = cdoOperatorF1(operatorID);

  operatorCheckArgc(0);

  const auto streamID1 = cdoOpenRead(0);
  const auto streamID2 = cdoOpenRead(1);

  const auto vlistID1 = cdoStreamInqVlist(streamID1);
  const auto vlistID2 = cdoStreamInqVlist(streamID2);
  const auto vlistID3 = vlistDuplicate(vlistID1);

  vlistCompare(vlistID1, vlistID2, CMP_ALL);

  VarList varList1;
  varListInit(varList1, vlistID1);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);

  Field field1, field2;
  field1.resize(gridsizemax);
  field2.resize(gridsizemax);

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

  const auto streamID3 = cdoOpenWrite(2);
  cdoDefVlist(streamID3, vlistID3);

  FieldVector2D vars2;
  fieldsFromVlist(vlistID2, vars2, FIELD_VEC);

  int tsID = 0;
  int tsID2 = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      auto vdate = taxisInqVdate(taxisID1);
      const int yearmon1 = vdate / 100;

      if (yearmon1 != yearmon2)
        {
          const int year1 = yearmon1 / 100;
          const int mon1 = yearmon1 - (yearmon1 / 100) * 100;
          if (Options::cdoVerbose) cdoPrint("Process: Year = %4d  Month = %2d", year1, mon1);

          nrecs2 = cdoStreamInqTimestep(streamID2, tsID2);
          if (nrecs2 == 0) cdoAbort("Missing year=%4d mon=%2d in %s!", year1, mon1, cdoGetStreamName(1));

          vdate = taxisInqVdate(taxisID2);
          yearmon2 = vdate / 100;

          if (yearmon1 != yearmon2)
            {
              const int year2 = yearmon2 / 100;
              const int mon2 = yearmon2 - (yearmon2 / 100) * 100;
              cdoAbort("Timestep %d in %s has wrong date! Current year=%4d mon=%2d, expected year=%4d mon=%2d", tsID2 + 1,
                       cdoGetStreamName(1), year2, mon2, year1, mon1);
            }

          for (int recID = 0; recID < nrecs2; recID++)
            {
              size_t nmiss;
              cdoInqRecord(streamID2, &varID, &levelID);
              cdoReadRecord(streamID2, vars2[varID][levelID].vec_d.data(), &nmiss);
              vars2[varID][levelID].nmiss = nmiss;
            }

          tsID2++;
        }

      taxisCopyTimestep(taxisID3, taxisID1);
      cdoDefTimestep(streamID3, tsID);

      for (int recID = 0; recID < nrecs; recID++)
        {
          cdoInqRecord(streamID1, &varID, &levelID);
          cdoReadRecord(streamID1, field1.vec_d.data(), &field1.nmiss);
          field1.grid = varList1[varID].gridID;
          field1.missval = varList1[varID].missval;

          vfarfun(field1, vars2[varID][levelID], operfunc);

          cdoDefRecord(streamID3, varID, levelID);
          cdoWriteRecord(streamID3, field1.vec_d.data(), field1.nmiss);
        }

      tsID++;
    }

  cdoStreamClose(streamID3);
  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
