/*
  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:

     Deltat    deltat         Delta t
*/

#include <cdi.h>

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

void *
Deltat(void *process)
{
  int varID, levelID;
  size_t nmiss;

  cdoInitialize(process);

  // clang-format off
  cdoOperatorAdd("deltat",            0,     0, nullptr);
  cdoOperatorAdd("timederivative",    0,     1, nullptr);
  // clang-format on

  const auto operatorID = cdoOperatorID();
  const bool ldivdt = cdoOperatorF2(operatorID);

  operatorCheckArgc(0);

  const auto streamID1 = cdoOpenRead(0);

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

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

  const auto calendar = taxisInqCalendar(taxisID1);

  const auto streamID2 = cdoOpenWrite(1);
  cdoDefVlist(streamID2, vlistID2);

  FieldVector2D vars;
  fieldsFromVlist(vlistID1, vars, FIELD_VEC);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);
  Varray<double> array1(gridsizemax), array2(gridsizemax);

  int tsID = 0;
  auto nrecs = cdoStreamInqTimestep(streamID1, tsID);

  auto juldate0 = julianDateEncode(calendar, taxisInqVdate(taxisID1), taxisInqVtime(taxisID1));

  for (int recID = 0; recID < nrecs; ++recID)
    {
      cdoInqRecord(streamID1, &varID, &levelID);
      cdoReadRecord(streamID1, vars[varID][levelID].vec_d.data(), &nmiss);
      vars[varID][levelID].nmiss = nmiss;
    }

  tsID++;
  int tsID2 = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      const auto juldate1 = julianDateEncode(calendar, taxisInqVdate(taxisID1), taxisInqVtime(taxisID1));
      const double idt_in_sec = ldivdt ? 1. / julianDateToSeconds(julianDateSub(juldate1, juldate0)) : 1;
      juldate0 = juldate1;

      taxisCopyTimestep(taxisID2, taxisID1);
      cdoDefTimestep(streamID2, tsID2);

      for (int recID = 0; recID < nrecs; ++recID)
        {
          cdoInqRecord(streamID1, &varID, &levelID);
          cdoReadRecord(streamID1, array1.data(), &nmiss);

          const auto missval = vars[varID][levelID].missval;
          const auto fieldsize = vars[varID][levelID].size;
          auto &array0 = vars[varID][levelID].vec_d;
          if (nmiss || vars[varID][levelID].nmiss)
            {
              for (size_t i = 0; i < fieldsize; ++i)
                {
                  if (DBL_IS_EQUAL(array0[i], missval) || DBL_IS_EQUAL(array1[i], missval))
                    array2[i] = missval;
                  else
                    array2[i] = (array1[i] - array0[i]) * idt_in_sec;
                }

              nmiss = varrayNumMV(fieldsize, array2, missval);
            }
          else
            {
              for (size_t i = 0; i < fieldsize; ++i) array2[i] = (array1[i] - array0[i]) * idt_in_sec;
            }

          varrayCopy(fieldsize, array1, array0);

          cdoDefRecord(streamID2, varID, levelID);
          cdoWriteRecord(streamID2, array2.data(), nmiss);
        }

      tsID++;
      tsID2++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
