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

     Deltat    deltat         Delta t
*/

#include <cdi.h>

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

void *
Deltat(void *process)
{
  cdo_initialize(process);

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

  const auto operatorID = cdo_operator_id();
  const bool ldivdt = cdo_operator_f2(operatorID);

  operator_check_argc(0);

  const auto streamID1 = cdo_open_read(0);

  const auto vlistID1 = cdo_stream_inq_vlist(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 = cdo_open_write(1);
  cdo_def_vlist(streamID2, vlistID2);

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

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

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

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

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

  tsID++;
  int tsID2 = 0;
  while (true)
    {
      nrecs = cdo_stream_inq_timestep(streamID1, tsID);
      if (nrecs == 0) break;

      const auto juldate1 = julian_date_encode(calendar, taxisInqVdate(taxisID1), taxisInqVtime(taxisID1));
      const double idt_in_sec = ldivdt ? 1. / julian_date_to_seconds(julian_date_sub(juldate1, juldate0)) : 1;
      juldate0 = juldate1;

      cdo_taxis_copy_timestep(taxisID2, taxisID1);
      cdo_def_timestep(streamID2, tsID2);

      for (int recID = 0; recID < nrecs; ++recID)
        {
          int varID, levelID;
          cdo_inq_record(streamID1, &varID, &levelID);
          size_t nmiss;
          cdo_read_record(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 = varray_num_mv(fieldsize, array2, missval);
            }
          else
            {
              for (size_t i = 0; i < fieldsize; ++i) array2[i] = (array1[i] - array0[i]) * idt_in_sec;
            }

          varray_copy(fieldsize, array1, array0);

          cdo_def_record(streamID2, varID, levelID);
          cdo_write_record(streamID2, array2.data(), nmiss);
        }

      tsID++;
      tsID2++;
    }

  cdo_stream_close(streamID2);
  cdo_stream_close(streamID1);

  cdo_finish();

  return nullptr;
}
