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

      Vertcum    vertcum         Vertical cumulative
      Vertcum    vertcumhl       Vertical cumulative on hybrid sigma half level
*/

#include <cdi.h>

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

#define IS_SURFACE_LEVEL(zaxisID) (zaxisInqType(zaxisID) == ZAXIS_SURFACE && zaxisInqSize(zaxisID) == 1)

static void
add_vars_mv(size_t gridsize, double missval, const Varray<double> &var1, const Varray<double> &var2, Varray<double> &var3)
{
  const auto missval1 = missval;
  const auto missval2 = missval;
  /*
  for ( size_t i = 0; i < gridsize; ++i )
    var3[i] = ADDMN(var2[i], var1[i]);
  */
  for (size_t i = 0; i < gridsize; ++i)
    {
      var3[i] = var2[i];
      if (!DBL_IS_EQUAL(var1[i], missval1))
        {
          if (!DBL_IS_EQUAL(var2[i], missval2))
            var3[i] += var1[i];
          else
            var3[i] = var1[i];
        }
    }
}

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

  cdoInitialize(process);

  // clang-format off
                  cdoOperatorAdd("vertcum",    0,  0, nullptr);
  int VERTCUMHL = cdoOperatorAdd("vertcumhl",  0,  0, nullptr);
  // clang-format on

  const auto operatorID = cdoOperatorID();

  operatorCheckArgc(0);

  const auto streamID1 = cdoOpenRead(0);

  const auto vlistID1 = cdoStreamInqVlist(streamID1);
  const auto vlistID2 = vlistDuplicate(vlistID1);

  int zaxisIDhl = -1;

  if (operatorID == VERTCUMHL)
    {
      std::vector<double> vct;
      bool lhybrid = false;
      const auto nzaxis = vlistNzaxis(vlistID1);
      for (int i = 0; i < nzaxis; ++i)
        {
          const auto zaxisID = vlistZaxis(vlistID1, i);
          const auto nlevs = zaxisInqSize(zaxisID);

          if (zaxisInqType(zaxisID) == ZAXIS_HYBRID && nlevs > 1)
            {
              int nvct = zaxisInqVctSize(zaxisID);
              if (nlevs == (nvct / 2 - 1))
                {
                  if (lhybrid == false)
                    {
                      lhybrid = true;
                      nlevshl = nlevs + 1;

                      vct.resize(nvct);
                      zaxisInqVct(zaxisID, vct.data());

                      zaxisIDhl = zaxisCreate(ZAXIS_HYBRID_HALF, nlevshl);
                      std::vector<double> levels(nlevshl);
                      for (levelID = 0; levelID < nlevshl; ++levelID) levels[levelID] = levelID + 1;
                      zaxisDefLevels(zaxisIDhl, levels.data());
                      zaxisDefVct(zaxisIDhl, nvct, vct.data());
                      vlistChangeZaxisIndex(vlistID2, i, zaxisIDhl);
                    }
                  else if (vct.size())
                    {
                      if (memcmp(vct.data(), zaxisInqVctPtr(zaxisID), nvct * sizeof(double)) == 0)
                        vlistChangeZaxisIndex(vlistID2, i, zaxisIDhl);
                    }
                }
            }
        }
    }

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

  const auto nvars = vlistNvars(vlistID1);
  std::vector<std::vector<size_t>> varnmiss(nvars);
  Varray3D<double> vardata1(nvars), vardata2(nvars);

  for (varID = 0; varID < nvars; varID++)
    {
      const auto gridsize = varList1[varID].gridsize;
      const auto nlevs = varList1[varID].nlevels;
      const auto nlevs2 = varList2[varID].nlevels;

      varnmiss[varID].resize(nlevs);
      vardata1[varID].resize(nlevs);
      vardata2[varID].resize(nlevs2);
      for (levelID = 0; levelID < nlevs; ++levelID) vardata1[varID][levelID].resize(gridsize);
      for (levelID = 0; levelID < nlevs2; ++levelID) vardata2[varID][levelID].resize(gridsize);
    }

  const auto taxisID1 = vlistInqTaxis(vlistID1);
  const auto taxisID2 = taxisDuplicate(taxisID1);
  vlistDefTaxis(vlistID2, taxisID2);

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

  int tsID = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      taxisCopyTimestep(taxisID2, taxisID1);
      cdoDefTimestep(streamID2, tsID);

      for (int recID = 0; recID < nrecs; recID++)
        {
          cdoInqRecord(streamID1, &varID, &levelID);
          cdoReadRecord(streamID1, &vardata1[varID][levelID][0], &varnmiss[varID][levelID]);
        }

      for (varID = 0; varID < nvars; ++varID)
        {
          const auto missval = varList2[varID].missval;
          const auto gridsize = varList2[varID].gridsize;
          const auto nlevs2 = varList2[varID].nlevels;

          if (operatorID == VERTCUMHL && nlevs2 == nlevshl)
            {
              for (size_t i = 0; i < gridsize; ++i) vardata2[varID][0][i] = 0;
            }
          else
            {
              for (size_t i = 0; i < gridsize; ++i) vardata2[varID][0][i] = vardata1[varID][0][i];
            }

          for (levelID = 1; levelID < nlevs2; ++levelID)
            {
              if (operatorID == VERTCUMHL && nlevs2 == nlevshl)
                add_vars_mv(gridsize, missval, vardata1[varID][levelID - 1], vardata2[varID][levelID - 1],
                            vardata2[varID][levelID]);
              else
                add_vars_mv(gridsize, missval, vardata1[varID][levelID], vardata2[varID][levelID - 1], vardata2[varID][levelID]);
            }

          if (operatorID == VERTCUMHL && nlevs2 == nlevshl)
            {
              const auto &var1 = vardata2[varID][nlevs2 - 1];
              for (levelID = 0; levelID < nlevs2; ++levelID)
                {
                  auto &var2 = vardata2[varID][levelID];
                  for (size_t i = 0; i < gridsize; ++i)
                    {
                      if (IS_NOT_EQUAL(var1[i], 0))
                        var2[i] /= var1[i];
                      else
                        var2[i] = 0;
                    }
                }
            }
        }

      for (varID = 0; varID < nvars; ++varID)
        {
          const auto missval = varList2[varID].missval;
          const auto gridsize = varList2[varID].gridsize;
          const auto nlevs2 = varList2[varID].nlevels;
          for (levelID = 0; levelID < nlevs2; ++levelID)
            {
              auto &single = vardata2[varID][levelID];
              nmiss = varrayNumMV(gridsize, single, missval);
              cdoDefRecord(streamID2, varID, levelID);
              cdoWriteRecord(streamID2, single.data(), nmiss);
            }
        }

      tsID++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  vlistDestroy(vlistID2);

  cdoFinish();

  return nullptr;
}
