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

  Author: Uwe Schulzweida

*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <cdi.h>

#include "process_int.h"
#include "cdo_vlist.h"
#include "param_conversion.h"
#include "statistic.h"
#include "cdo_options.h"
#include "datetime.h"
#include "cimdOmp.h"
#include "field_functions.h"


void *
Timfill(void *process)
{
  DateTimeList dtlist;

  cdo_initialize(process);

  cdo_operator_add("setmisstonntime", 0, 0, nullptr);

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

  VarList varList;
  varListInit(varList, vlistID1);

  const auto nvars = vlistNvars(vlistID1);
  FieldVector3D vars;

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

      constexpr size_t NALLOC_INC = 1024;
      if ((size_t) tsID >= vars.size()) vars.resize(vars.size() + NALLOC_INC);

      dtlist.taxis_inq_timestep(taxisID1, tsID);

      fields_from_vlist(vlistID1, vars[tsID]);

      for (int recID = 0; recID < nrecs; ++recID)
        {
          int varID, levelID;
          cdo_inq_record(streamID1, &varID, &levelID);
          auto &field = vars[tsID][varID][levelID];
          field.init(varList[varID]);
          cdo_read_record(streamID1, field);
        }

      tsID++;
    }

  const auto nts = tsID;
  if (nts <= 1) cdo_abort("Number of time steps <= 1!");

  std::vector<JulianDate> julianDates(nts);
  for (tsID = 0; tsID < nts; ++tsID)
    {
      julianDates[tsID] = julianDate_encode(calendar, dtlist.get_vDateTime(tsID));
    }

  Varray2D<double> data2D(Threading::ompNumThreads);
  for (auto &data : data2D) data.resize(nts);

  for (int varID = 0; varID < nvars; ++varID)
    {
      auto fieldMemType = varList[varID].memType;
      const auto gridsize = varList[varID].gridsize;
      const auto missval = varList[varID].missval;
      for (int levelID = 0; levelID < varList[varID].nlevels; ++levelID)
        {
#ifdef _OPENMP
#pragma omp parallel for default(shared) schedule(static)
#endif
          for (size_t i = 0; i < gridsize; ++i)
            {
              const auto ompthID = cdo_omp_get_thread_num();
              auto &data = data2D[ompthID];

              if (fieldMemType == MemType::Float)
                for (int t = 0; t < nts; ++t) data[t] = vars[t][varID][levelID].vec_f[i];
              else
                for (int t = 0; t < nts; ++t) data[t] = vars[t][varID][levelID].vec_d[i];

              int i0 = -1;
              int in = -1;
              for (int t = 0; t < nts; ++t)
                {
                  if (dbl_is_equal(data[t], missval))
                    {
                      for (int k = t + 1; k < nts; ++k)
                        {
                          if (!dbl_is_equal(data[k], missval))
                            {
                              in = k;
                              break;
                            }
                        }

                      if (i0 == -1 && in != -1)
                        {
                          for (int k = t; k < in; ++k) data[k] = data[in];
                          t = in;
                          i0 = in;
                          in = -1;
                        }
                      else if (i0 != -1 && in != -1)
                        {
                          for (int k = i0 + 1; k < in; ++k)
                            {
                              const auto jdelta1 = julianDate_to_seconds(julianDate_sub(julianDates[k], julianDates[i0]));
                              const auto jdelta2 = julianDate_to_seconds(julianDate_sub(julianDates[in], julianDates[k]));
                              data[k] = data[(jdelta1 <= jdelta2) ? i0 : in];
                            }
                          t = in;
                          i0 = in;
                          in = -1;                          
                        }
                      else if (i0 != -1 && in == -1)
                        {
                          for (int k = t; k < nts; ++k) data[k] = data[i0];
                          break;
                        }
                       else if (i0 == -1 && in == -1)
                        {
                          break;
                        }
                    }
                  else
                    {
                      i0 = t;
                    }
                }

              if (fieldMemType == MemType::Float)
                for (int t = 0; t < nts; ++t) vars[t][varID][levelID].vec_f[i] = data[t];
              else
                for (int t = 0; t < nts; ++t) vars[t][varID][levelID].vec_d[i] = data[t];
            }
        }
    }

  const auto streamID2 = cdo_open_write(1);
  cdo_def_vlist(streamID2, vlistID2);

  for (tsID = 0; tsID < nts; ++tsID)
    {
      dtlist.taxis_def_timestep(taxisID2, tsID);
      cdo_def_timestep(streamID2, tsID);

      for (int varID = 0; varID < nvars; ++varID)
        {
          for (int levelID = 0; levelID < varList[varID].nlevels; ++levelID)
            {
              auto &field = vars[tsID][varID][levelID];
              if (field.hasData())
                {
                  cdo_def_record(streamID2, varID, levelID);
                  cdo_write_record(streamID2, field);
                }
            }
        }
    }

  cdo_stream_close(streamID2);
  cdo_stream_close(streamID1);

  cdo_finish();

  return nullptr;
}
