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

      Selyearidx    selyearidx         Select index of year
*/

#include <cdi.h>

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

void *
Selyearidx(void *process)
{
  int varID, levelID;
  int year, month, day;
  size_t nmiss;

  cdo_initialize(process);

  cdo_operator_add("selyearidx", 0, 0, nullptr);
  cdo_operator_add("seltimeidx", 1, 0, nullptr);

  const bool ltime = cdo_operator_f1(cdo_operator_id());

  const auto streamID1 = cdo_open_read(0);
  const int vlistID1 = cdo_stream_inq_vlist(streamID1);

  const int taxisID1 = vlistInqTaxis(vlistID1);

  const auto streamID2 = cdo_open_read(1);
  const auto vlistID2 = cdo_stream_inq_vlist(streamID2);
  const auto taxisID2 = vlistInqTaxis(vlistID2);

  vlist_compare(vlistID1, vlistID2, CMP_ALL);

  const auto vlistID3 = vlistDuplicate(vlistID2);
  const auto taxisID3 = taxisDuplicate(taxisID1);
  vlistDefTaxis(vlistID3, taxisID3);

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

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

  const auto maxrecs = vlistNrecs(vlistID1);
  std::vector<RecordInfo> recList(maxrecs);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);

  Varray<double> array(gridsizemax);

  FieldVector2D vars1, vars2;
  fields_from_vlist(vlistID1, vars1, FIELD_VEC);
  fields_from_vlist(vlistID2, vars2, FIELD_VEC);

  const int nvars = vlistNvars(vlistID1);
  for (varID = 0; varID < nvars; ++varID)
    {
      const auto gridsize = varList1[varID].gridsize;
      const auto nlevels = varList1[varID].nlevels;
      const auto missval = varList2[varID].missval;
      for (levelID = 0; levelID < nlevels; ++levelID)
        {
          for (size_t i = 0; i < gridsize; ++i) vars2[varID][levelID].vec_d[i] = missval;
        }
    }

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

      auto vdate = taxisInqVdate(taxisID1);
      cdiDecodeDate(vdate, &year, &month, &day);
      int year1 = year;

      const bool lexactdate = gridsizemax == 1 && nrecs == 1;

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

          if (tsID == 0)
            {
              recList[recID].varID = varID;
              recList[recID].levelID = levelID;
              recList[recID].lconst = varList1[varID].timetype == TIME_CONSTANT;
            }
        }

      int nrecs2;
      int nsets = 0;
      while ((nrecs2 = cdo_stream_inq_timestep(streamID2, tsID2)))
        {
          vdate = taxisInqVdate(taxisID2);
          cdiDecodeDate(vdate, &year, &month, &day);

          if (ltime == false && year1 != year) break;

          for (int recID = 0; recID < nrecs2; recID++)
            {
              cdo_inq_record(streamID2, &varID, &levelID);
              cdo_read_record(streamID2, array.data(), &nmiss);

              const size_t gridsize = varList2[varID].gridsize;
              for (size_t i = 0; i < gridsize; ++i)
                if (nsets == (int) std::lround(vars1[varID][levelID].vec_d[i]))
                  {
                    if (lexactdate) cdo_taxis_copy_timestep(taxisID3, taxisID2);
                    vars2[varID][levelID].vec_d[i] = array[i];
                  }
            }

          nsets++;
          tsID2++;
        }

      if (nsets)
        {
          if (!lexactdate) cdo_taxis_copy_timestep(taxisID3, taxisID1);
          cdo_def_timestep(streamID3, tsID3);

          for (int recID = 0; recID < maxrecs; recID++)
            {
              if (tsID && recList[recID].lconst) continue;

              varID = recList[recID].varID;
              levelID = recList[recID].levelID;
              cdo_def_record(streamID3, varID, levelID);
              cdo_write_record(streamID3, vars2[varID][levelID].vec_d.data(), field_num_miss(vars2[varID][levelID]));
            }

          tsID3++;
        }

      if (nsets == 0)
        {
          cdo_warning("First input stream has more timesteps than the second input stream!");
          break;
        }

      if (nrecs2 == 0) break;

      tsID++;
    }

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

  cdo_finish();

  return nullptr;
}
