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

     Timsort    timsort         Sort over the time
*/

#include <algorithm> // sort

#include <cdi.h>

#include "process_int.h"
#include "cdo_vlist.h"
#include "cdo_cdi_wrapper.h"
#include "cdo_options.h"
#include "cimdOmp.h"


void *
Timsort(void *process)
{
  int nrecs;
  int varID, levelID;
  int nalloc = 0;
  size_t nmiss;

  cdoInitialize(process);

  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 = cdoTaxisCreate(TAXIS_ABSOLUTE);
  vlistDefTaxis(vlistID2, taxisID2);

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

  VarList varList;
  varListInit(varList, vlistID1);

  const auto nvars = vlistNvars(vlistID1);
  FieldVector3D vars;
  std::vector<int64_t> vdate;
  std::vector<int> vtime;

  int tsID = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      if (tsID >= nalloc)
        {
          constexpr int NALLOC_INC = 1024;
          nalloc += NALLOC_INC;
          vdate.resize(nalloc);
          vtime.resize(nalloc);
          vars.resize(nalloc);
        }

      vdate[tsID] = taxisInqVdate(taxisID1);
      vtime[tsID] = taxisInqVtime(taxisID1);

      fieldsFromVlist(vlistID1, vars[tsID]);

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

      tsID++;
    }

  int nts = tsID;

  Varray2D<double> sarray(Threading::ompNumThreads);
  for (int i = 0; i < Threading::ompNumThreads; i++) sarray[i].resize(nts);

  for (varID = 0; varID < nvars; varID++)
    {
      if (vlistInqVarTimetype(vlistID1, varID) == TIME_CONSTANT) continue;

      auto gridsize = varList[varID].gridsize;
      const auto nlevels = varList[varID].nlevels;
      for (levelID = 0; levelID < nlevels; levelID++)
        {
#ifdef _OPENMP
#pragma omp parallel for default(none) shared(gridsize, nts, sarray, vars, varID, levelID)
#endif
          for (size_t i = 0; i < gridsize; i++)
            {
              const auto ompthID = cdo_omp_get_thread_num();

              for (int t = 0; t < nts; t++) sarray[ompthID][t] = vars[t][varID][levelID].vec_d[i];

              std::sort(sarray[ompthID].begin(), sarray[ompthID].end());

              for (int t = 0; t < nts; t++) vars[t][varID][levelID].vec_d[i] = sarray[ompthID][t];
            }
        }
    }

  for (tsID = 0; tsID < nts; tsID++)
    {
      taxisDefVdate(taxisID2, vdate[tsID]);
      taxisDefVtime(taxisID2, vtime[tsID]);
      cdoDefTimestep(streamID2, tsID);

      for (varID = 0; varID < nvars; varID++)
        {
          const auto nlevels = varList[varID].nlevels;
          for (levelID = 0; levelID < nlevels; levelID++)
            {
              if (!vars[tsID][varID][levelID].empty())
                {
                  nmiss = vars[tsID][varID][levelID].nmiss;
                  cdoDefRecord(streamID2, varID, levelID);
                  cdoWriteRecord(streamID2, vars[tsID][varID][levelID].vec_d.data(), nmiss);
                }
            }
        }
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
