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

#include <cdi.h>

#include "functs.h"
#include "process_int.h"

static void
checkUniqueZaxis(int vlistID)
{
  const auto nzaxis = vlistNzaxis(vlistID);
  const auto zaxisID = vlistZaxis(vlistID, 0);
  const auto nlevels = zaxisInqSize(zaxisID);
  for (int index = 1; index < nzaxis; ++index)
    {
      if (nlevels != zaxisInqSize(vlistZaxis(vlistID, index))) cdoAbort("Number of level differ!");
    }
}

static void
checkUniqueGridsize(int vlistID)
{
  const auto ngrids = vlistNgrids(vlistID);
  const auto gridID = vlistGrid(vlistID, 0);
  const auto gridsize = gridInqSize(gridID);
  for (int index = 0; index < ngrids; index++)
    {
      if (gridsize != gridInqSize(vlistGrid(vlistID, index))) cdoAbort("Horizontal gridsize differ!");
    }
}

static void
setAttributes(const VarList &varList1, int vlistID1, int vlistID2, int varID2, int operatorID)
{
  bool paramIsEqual = true;
  char name[CDI_MAX_NAME], zname[CDI_MAX_NAME];
  strcpy(name, varList1[0].name);
  const auto param = varList1[0].param;
  const auto nvars = vlistNvars(vlistID1);
  for (int varID = 1; varID < nvars; ++varID)
    {
      strcpy(zname, varList1[varID].name);
      const auto zparam = varList1[varID].param;
      if (param != zparam || !cdo_cmpstr(name, zname))
        {
          paramIsEqual = false;
          break;
        }
    }

  if (!paramIsEqual) strcpy(name, cdoOperatorName(operatorID));
  cdiDefKeyString(vlistID2, varID2, CDI_KEY_NAME, name);
  if (paramIsEqual)
    {
      if (param >= 0) vlistDefVarParam(vlistID2, varID2, param);
      zname[0] = 0;
      vlistInqVarLongname(vlistID1, 0, zname);
      if (*zname) cdiDefKeyString(vlistID2, varID2, CDI_KEY_LONGNAME, zname);
      zname[0] = 0;
      vlistInqVarUnits(vlistID1, 0, zname);
      if (*zname) cdiDefKeyString(vlistID2, varID2, CDI_KEY_UNITS, zname);
    }
}

static void
addOperators(void)
{
  // clang-format off
  cdoOperatorAdd("varsrange", func_range, 0, nullptr);
  cdoOperatorAdd("varsmin",   func_min,   0, nullptr);
  cdoOperatorAdd("varsmax",   func_max,   0, nullptr);
  cdoOperatorAdd("varssum",   func_sum,   0, nullptr);
  cdoOperatorAdd("varsmean",  func_mean,  0, nullptr);
  cdoOperatorAdd("varsavg",   func_avg,   0, nullptr);
  cdoOperatorAdd("varsvar",   func_var,   0, nullptr);
  cdoOperatorAdd("varsvar1",  func_var1,  0, nullptr);
  cdoOperatorAdd("varsstd",   func_std,   0, nullptr);
  cdoOperatorAdd("varsstd1",  func_std1,  0, nullptr);
  // clang-format on
}

void *
Varsstat(void *process)
{
  int nrecs;
  int varID, levelID;

  cdoInitialize(process);

  addOperators();

  const auto operatorID = cdoOperatorID();
  const auto operfunc = cdoOperatorF1(operatorID);

  operatorCheckArgc(0);

  const bool lrange = operfunc == func_range;
  const bool lmean = operfunc == func_mean || operfunc == func_avg;
  const bool lstd = operfunc == func_std || operfunc == func_std1;
  const bool lvarstd = operfunc == func_std || operfunc == func_var || operfunc == func_std1 || operfunc == func_var1;
  const int divisor = operfunc == func_std1 || operfunc == func_var1;

  const auto streamID1 = cdoOpenRead(0);
  const auto vlistID1 = cdoStreamInqVlist(streamID1);

  VarList varList1;
  varListInit(varList1, vlistID1);

  checkUniqueZaxis(vlistID1);
  const auto zaxisID = vlistZaxis(vlistID1, 0);
  const auto nlevels = zaxisInqSize(zaxisID);

  checkUniqueGridsize(vlistID1);
  const auto gridID = vlistGrid(vlistID1, 0);
  const auto gridsize = gridInqSize(gridID);

  const auto timetype = varList1[0].timetype;
  const auto nvars = vlistNvars(vlistID1);
  for (varID = 1; varID < nvars; ++varID)
    {
      if (timetype != varList1[varID].timetype) cdoAbort("Number of timesteps differ!");
    }

  const auto vlistID2 = vlistCreate();
  const auto varID2 = vlistDefVar(vlistID2, gridID, zaxisID, timetype);
  setAttributes(varList1, vlistID1, vlistID2, varID2, operatorID);

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

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

  Field field;
  field.resize(gridsize);

  FieldVector vars1(nlevels), samp1(nlevels), vars2;
  if (lvarstd || lrange) vars2.resize(nlevels);

  for (levelID = 0; levelID < nlevels; levelID++)
    {
      const auto missval = varList1[0].missval;

      vars1[levelID].grid = gridID;
      vars1[levelID].missval = missval;
      vars1[levelID].resize(gridsize);
      samp1[levelID].grid = gridID;
      samp1[levelID].missval = missval;
      if (lvarstd || lrange)
        {
          vars2[levelID].grid = gridID;
          vars2[levelID].missval = missval;
          vars2[levelID].resize(gridsize);
        }
    }

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

          vars1[levelID].nsamp++;
          if (lrange) vars2[levelID].nsamp++;

          if (varID == 0)
            {
              cdoReadRecord(streamID1, vars1[levelID].vec_d.data(), &vars1[levelID].nmiss);
              if (lrange)
                {
                  vars2[levelID].nmiss = vars1[levelID].nmiss;
                  vars2[levelID].vec_d = vars1[levelID].vec_d;
                }

              if (lvarstd) vfarmoq(vars2[levelID], vars1[levelID]);

              if (vars1[levelID].nmiss || !samp1[levelID].empty())
                {
                  if (samp1[levelID].empty()) samp1[levelID].resize(gridsize);

                  for (size_t i = 0; i < gridsize; i++)
                    samp1[levelID].vec_d[i] = !DBL_IS_EQUAL(vars1[levelID].vec_d[i], vars1[levelID].missval);
                }
            }
          else
            {
              cdoReadRecord(streamID1, field.vec_d.data(), &field.nmiss);
              field.size = vars1[levelID].size;
              field.grid = vars1[levelID].grid;
              field.missval = vars1[levelID].missval;

              if (field.nmiss || !samp1[levelID].empty())
                {
                  if (samp1[levelID].empty()) samp1[levelID].resize(gridsize, vars1[levelID].nsamp);

                  for (size_t i = 0; i < gridsize; i++)
                    if (!DBL_IS_EQUAL(field.vec_d[i], field.missval)) samp1[levelID].vec_d[i]++;
                }

              if (lvarstd)
                {
                  vfarsumq(vars2[levelID], field);
                  vfarsum(vars1[levelID], field);
                }
              else if (lrange)
                {
                  vfarmin(vars2[levelID], field);
                  vfarmax(vars1[levelID], field);
                }
              else
                {
                  vfarfun(vars1[levelID], field, operfunc);
                }
            }
        }

      for (levelID = 0; levelID < nlevels; levelID++)
        {
          if (vars1[levelID].nsamp)
            {
              if (lmean)
                {
                  if (!samp1[levelID].empty())
                    vfardiv(vars1[levelID], samp1[levelID]);
                  else
                    vfarcdiv(vars1[levelID], (double) vars1[levelID].nsamp);
                }
              else if (lvarstd)
                {
                  if (!samp1[levelID].empty())
                    {
                      if (lstd)
                        vfarstd(vars1[levelID], vars2[levelID], samp1[levelID], divisor);
                      else
                        vfarvar(vars1[levelID], vars2[levelID], samp1[levelID], divisor);
                    }
                  else
                    {
                      if (lstd)
                        vfarcstd(vars1[levelID], vars2[levelID], vars1[levelID].nsamp, divisor);
                      else
                        vfarcvar(vars1[levelID], vars2[levelID], vars1[levelID].nsamp, divisor);
                    }
                }
              else if (lrange)
                {
                  vfarsub(vars1[levelID], vars2[levelID]);
                }

              cdoDefRecord(streamID2, 0, levelID);
              cdoWriteRecord(streamID2, vars1[levelID].vec_d.data(), vars1[levelID].nmiss);
              vars1[levelID].nsamp = 0;
            }
        }

      tsID++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  vlistDestroy(vlistID2);

  cdoFinish();

  return nullptr;
}
