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

      Intyear    intyear         Year interpolation
*/

#include <cdi.h>

#include "cdo_rlimit.h"
#include "process_int.h"
#include "cdo_vlist.h"
#include "util_files.h"
#include "param_conversion.h"

size_t
intyear(double fac1, double fac2, size_t gridsize, const Varray<double> &array1, const Varray<double> &array2, Varray<double> &array3,
        bool withMissval, double missval1, double missval2)
{
  size_t nmiss3 = 0;

  if (withMissval)
    {
      for (size_t i = 0; i < gridsize; i++)
        {
          if (!DBL_IS_EQUAL(array1[i], missval1) && !DBL_IS_EQUAL(array2[i], missval2))
            {
              array3[i] = array1[i] * fac1 + array2[i] * fac2;
            }
          else
            {
              array3[i] = missval1;
              nmiss3++;
            }
        }
    }
  else
    {
      for (size_t i = 0; i < gridsize; i++) array3[i] = array1[i] * fac1 + array2[i] * fac2;
    }

  return nmiss3;
}

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

  operator_input_arg("years");

  const auto iyears = cdo_argv_to_int(cdo_get_oper_argv());
  const int nyears = iyears.size();

  cdo::set_numfiles(nyears + 8);

  std::vector<CdoStreamID> streamIDs(nyears);

  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);

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

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

  char filename[8192];
  strcpy(filename, cdo_get_obase().c_str());
  const int nchars = strlen(filename);

  auto refname = cdo_get_stream_name(0);
  char filesuffix[32] = { 0 };
  FileUtils::gen_suffix(filesuffix, sizeof(filesuffix), cdo_inq_filetype(streamID1), vlistID1, refname);

  for (int iy = 0; iy < nyears; iy++)
    {
      sprintf(filename + nchars, "%04d", iyears[iy]);
      if (filesuffix[0]) sprintf(filename + nchars + 4, "%s", filesuffix);

      streamIDs[iy] = cdo_open_write(filename);
      cdo_def_vlist(streamIDs[iy], vlistID3);
    }

  VarList varList1, varList2;
  varListInit(varList1, vlistID1);
  varListInit(varList2, vlistID2);

  int tsID = 0;
  while (true)
    {
      auto nrecs = cdo_stream_inq_timestep(streamID1, tsID);
      if (nrecs == 0) break;
      nrecs = cdo_stream_inq_timestep(streamID2, tsID);
      if (nrecs == 0) cdo_abort("Too few timesteps in second inputfile!");

      const auto vtime = taxisInqVtime(taxisID1);
      const auto vdate1 = taxisInqVdate(taxisID1);
      const auto year1 = vdate1 / 10000;
      const auto vdate2 = taxisInqVdate(taxisID2);
      const auto year2 = vdate2 / 10000;

      for (int iy = 0; iy < nyears; iy++)
        {
          if (iyears[iy] < year1 || iyears[iy] > year2)
            cdo_abort("Year %d out of bounds (first year %d; last year %d)!", iyears[iy], year1, year2);

          const auto vdate3 = vdate1 - year1 * 10000 + iyears[iy] * 10000;
          taxisDefVdate(taxisID3, vdate3);
          taxisDefVtime(taxisID3, vtime);
          cdo_def_timestep(streamIDs[iy], tsID);
        }

      for (int recID = 0; recID < nrecs; recID++)
        {
          int varID, levelID;
          cdo_inq_record(streamID1, &varID, &levelID);
          cdo_inq_record(streamID2, &varID, &levelID);

          size_t nmiss1, nmiss2;
          cdo_read_record(streamID1, array1.data(), &nmiss1);
          cdo_read_record(streamID2, array2.data(), &nmiss2);

          const auto gridsize = varList1[varID].gridsize;
          const auto missval1 = varList1[varID].missval;
          const auto missval2 = varList2[varID].missval;
          const auto withMissval = (nmiss1 || nmiss2);

          for (int iy = 0; iy < nyears; iy++)
            {
              const auto fac1 = ((double) year2 - iyears[iy]) / (year2 - year1);
              const auto fac2 = ((double) iyears[iy] - year1) / (year2 - year1);

              const auto nmiss3 = intyear(fac1, fac2, gridsize, array1, array2, array3, withMissval, missval1, missval2);

              cdo_def_record(streamIDs[iy], varID, levelID);
              cdo_write_record(streamIDs[iy], array3.data(), nmiss3);
            }
        }

      tsID++;
    }

  for (int iy = 0; iy < nyears; iy++) cdo_stream_close(streamIDs[iy]);

  cdo_stream_close(streamID2);
  cdo_stream_close(streamID1);

  cdo_finish();

  return nullptr;
}
