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

  Copyright (C) 2003-2021 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:

      Ydayarith  ydayadd         Add multi-year daily time series
      Ydayarith  ydaysub         Subtract multi-year daily time series
      Ydayarith  ydaymul         Multiply multi-year daily time series
      Ydayarith  ydaydiv         Divide multi-year daily time series
*/

#include <cdi.h>

#include "cdo_vlist.h"
#include "datetime.h"
#include "process_int.h"

void *
Ydayarith(void *process)
{
  constexpr int MaxDays = 373;
  int varID, levelID;

  cdo_initialize(process);

  cdo_operator_add("ydayadd", FieldFunc_Add, 0, nullptr);
  cdo_operator_add("ydaysub", FieldFunc_Sub, 0, nullptr);
  cdo_operator_add("ydaymul", FieldFunc_Mul, 0, nullptr);
  cdo_operator_add("ydaydiv", FieldFunc_Div, 0, nullptr);

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

  operator_check_argc(0);

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

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

  vlist_compare(vlistID1, vlistID2, CMP_ALL);

  VarList varList1;
  varListInit(varList1, vlistID1);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);

  Field field;
  field.resize(gridsizemax);

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

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

  FieldVector2D vars2[MaxDays];

  int tsID = 0;
  while (true)
    {
      const auto nrecs = cdo_stream_inq_timestep(streamID2, tsID);
      if (nrecs == 0) break;

      const auto vdate = taxisInqVdate(taxisID2);
      const auto dayoy = decode_day_of_year(vdate);
      if (dayoy < 0 || dayoy >= MaxDays) cdo_abort("Day of year %d out of range (date=%d)!", dayoy, vdate);
      if (vars2[dayoy].size() > 0) cdo_abort("Day of year index %d already allocated (date=%d)!", dayoy, vdate);

      fields_from_vlist(vlistID2, vars2[dayoy], FIELD_VEC);

      for (int recID = 0; recID < nrecs; recID++)
        {
          size_t nmiss;
          cdo_inq_record(streamID2, &varID, &levelID);
          cdo_read_record(streamID2, vars2[dayoy][varID][levelID].vec_d.data(), &nmiss);
          vars2[dayoy][varID][levelID].nmiss = nmiss;
        }

      tsID++;
    }

  tsID = 0;
  while (true)
    {
      const auto nrecs = cdo_stream_inq_timestep(streamID1, tsID);
      if (nrecs == 0) break;

      const auto vdate = taxisInqVdate(taxisID1);
      const auto dayoy = decode_day_of_year(vdate);
      if (dayoy < 0 || dayoy >= MaxDays) cdo_abort("Day of year %d out of range (date=%d)!", dayoy, vdate);
      if (vars2[dayoy].size() == 0) cdo_abort("Day of year index %d not found (date=%d)!", dayoy, vdate);

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

      for (int recID = 0; recID < nrecs; recID++)
        {
          cdo_inq_record(streamID1, &varID, &levelID);
          cdo_read_record(streamID1, field.vec_d.data(), &field.nmiss);
          field.size = varList1[varID].gridsize;
          field.grid = varList1[varID].gridID;
          field.missval = varList1[varID].missval;

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

          cdo_def_record(streamID3, varID, levelID);
          cdo_write_record(streamID3, field.vec_d.data(), field.nmiss);
        }
      tsID++;
    }

  cdo_stream_close(streamID3);
  cdo_stream_close(streamID2);
  cdo_stream_close(streamID1);

  cdo_finish();

  return nullptr;
}
