/*
  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 <vector>
#include <algorithm>

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

static size_t
fillReducedPoints(const int gridID, const size_t ny, std::vector<int> &reducedPoints, std::vector<int> &cumreducedPoints)
{
  reducedPoints.resize(ny);
  cumreducedPoints.resize(ny);
  gridInqReducedPoints(gridID, reducedPoints.data());
  cumreducedPoints[0] = 0;
  for (size_t j = 1; j < ny; j++) cumreducedPoints[j] = cumreducedPoints[j - 1] + reducedPoints[j - 1];
  size_t nx = reducedPoints[0];
  for (size_t j = 1; j < ny; j++)
    if (reducedPoints[j] > (int) nx) nx = reducedPoints[j];
  return nx;
}

typedef double funcType(size_t, const Varray<double> &);
typedef double funcTypeMV(size_t, const Varray<double> &, double);

static void
zonKernel(const Field &field1, Field &field2, funcType func, funcTypeMV funcMV)
{
  size_t rnmiss = 0;
  const auto nmiss = field1.nmiss;
  const auto missval = field1.missval;

  const auto ny = gridInqYsize(field1.grid);
  const bool lreduced = gridInqType(field1.grid) == GRID_GAUSSIAN_REDUCED;
  std::vector<int> reducedPoints, cumreducedPoints;
  auto nx = lreduced ? fillReducedPoints(field1.grid, ny, reducedPoints, cumreducedPoints) : gridInqXsize(field1.grid);

  Varray<double> v(nx);

  for (size_t j = 0; j < ny; ++j)
    {
      if (lreduced) nx = reducedPoints[j];
      const size_t offset = lreduced ? cumreducedPoints[j] : j * nx;
      std::copy(field1.vec_d.begin() + offset, field1.vec_d.begin() + offset + nx, v.begin());

      const auto result = nmiss ? funcMV(nx, v, missval) : func(nx, v);
      if (DBL_IS_EQUAL(result, missval)) rnmiss++;
      field2.vec_d[j] = result;
    }

  field2.nmiss = rnmiss;
}

void
zonmin(const Field &field1, Field &field2)
{
  zonKernel(field1, field2, varrayMin, varrayMinMV);
}

void
zonmax(const Field &field1, Field &field2)
{
  zonKernel(field1, field2, varrayMax, varrayMaxMV);
}

void
zonrange(const Field &field1, Field &field2)
{
  zonKernel(field1, field2, varrayRange, varrayRangeMV);
}

void
zonsum(const Field &field1, Field &field2)
{
  zonKernel(field1, field2, varraySum, varraySumMV);
}

void
zonmean(const Field &field1, Field &field2)
{
  zonKernel(field1, field2, varrayMean, varrayMeanMV);
}

void
zonavg(const Field &field1, Field &field2)
{
  zonKernel(field1, field2, varrayMean, varrayAvgMV);
}

void
zonvar(const Field &field1, Field &field2)
{
  size_t rnmiss = 0;
  const auto nmiss = field1.nmiss;
  const auto missval1 = field1.missval;

  const auto ny = gridInqYsize(field1.grid);
  const bool lreduced = gridInqType(field1.grid) == GRID_GAUSSIAN_REDUCED;
  std::vector<int> reducedPoints, cumreducedPoints;
  auto nx = lreduced ? fillReducedPoints(field1.grid, ny, reducedPoints, cumreducedPoints) : gridInqXsize(field1.grid);

  Varray<double> v(nx);

  for (size_t j = 0; j < ny; j++)
    {
      if (lreduced) nx = reducedPoints[j];
      const size_t offset = lreduced ? cumreducedPoints[j] : j * nx;
      std::copy(field1.vec_d.begin() + offset, field1.vec_d.begin() + offset + nx, v.begin());

      const auto rvar = varrayVar(nx, v, nmiss, missval1);
      if (DBL_IS_EQUAL(rvar, missval1)) rnmiss++;
      field2.vec_d[j] = rvar;
    }

  field2.nmiss = rnmiss;
}

void
zonvar1(const Field &field1, Field &field2)
{
  size_t rnmiss = 0;
  const auto nmiss = field1.nmiss;
  const auto missval1 = field1.missval;

  const auto ny = gridInqYsize(field1.grid);
  const bool lreduced = gridInqType(field1.grid) == GRID_GAUSSIAN_REDUCED;
  std::vector<int> reducedPoints, cumreducedPoints;
  auto nx = lreduced ? fillReducedPoints(field1.grid, ny, reducedPoints, cumreducedPoints) : gridInqXsize(field1.grid);

  Varray<double> v(nx);

  for (size_t j = 0; j < ny; j++)
    {
      if (lreduced) nx = reducedPoints[j];
      const size_t offset = lreduced ? cumreducedPoints[j] : j * nx;
      std::copy(field1.vec_d.begin() + offset, field1.vec_d.begin() + offset + nx, v.begin());

      const auto rvar = varrayVar1(nx, v, nmiss, missval1);
      if (DBL_IS_EQUAL(rvar, missval1)) rnmiss++;
      field2.vec_d[j] = rvar;
    }

  field2.nmiss = rnmiss;
}

void
zonstd(const Field &field1, Field &field2)
{
  size_t rnmiss = 0;
  const auto missval = field1.missval;
  const auto ny = gridInqYsize(field1.grid);

  zonvar(field1, field2);

  for (size_t j = 0; j < ny; j++)
    {
      const auto rstd = varToStd(field2.vec_d[j], missval);
      if (DBL_IS_EQUAL(rstd, missval)) rnmiss++;
      field2.vec_d[j] = rstd;
    }

  field2.nmiss = rnmiss;
}

void
zonstd1(const Field &field1, Field &field2)
{
  size_t rnmiss = 0;
  const auto missval = field1.missval;
  const auto ny = gridInqYsize(field1.grid);

  zonvar1(field1, field2);

  for (size_t j = 0; j < ny; j++)
    {
      const auto rstd = varToStd(field2.vec_d[j], missval);
      if (DBL_IS_EQUAL(rstd, missval)) rnmiss++;
      field2.vec_d[j] = rstd;
    }

  field2.nmiss = rnmiss;
}

void
zonpctl(const Field &field1, Field &field2, const int p)
{
  size_t rnmiss = 0;
  const auto missval = field1.missval;

  const auto ny = gridInqYsize(field1.grid);
  const bool lreduced = gridInqType(field1.grid) == GRID_GAUSSIAN_REDUCED;
  std::vector<int> reducedPoints, cumreducedPoints;
  auto nx = lreduced ? fillReducedPoints(field1.grid, ny, reducedPoints, cumreducedPoints) : gridInqXsize(field1.grid);

  Varray<double> v(nx);

  if (field1.nmiss)
    {
      Varray<double> array2(nx);

      for (size_t j = 0; j < ny; j++)
        {
          if (lreduced) nx = reducedPoints[j];
          const size_t offset = lreduced ? cumreducedPoints[j] : j * nx;
          std::copy(field1.vec_d.begin() + offset, field1.vec_d.begin() + offset + nx, v.begin());

          size_t l = 0;
          for (size_t i = 0; i < nx; i++)
            if (!DBL_IS_EQUAL(field1.vec_d[j * nx + i], missval)) array2[l++] = v[i];

          if (l > 0)
            {
              field2.vec_d[j] = percentile(array2.data(), l, p);
            }
          else
            {
              field2.vec_d[j] = missval;
              rnmiss++;
            }
        }
    }
  else
    {
      for (size_t j = 0; j < ny; j++)
        {
          if (lreduced) nx = reducedPoints[j];
          const size_t offset = lreduced ? cumreducedPoints[j] : j * nx;
          std::copy(field1.vec_d.begin() + offset, field1.vec_d.begin() + offset + nx, v.begin());

          if (nx > 0)
            {
              field2.vec_d[j] = percentile(v.data(), nx, p);
            }
          else
            {
              field2.vec_d[j] = missval;
              rnmiss++;
            }
        }
    }

  field2.nmiss = rnmiss;
}

void
zonfun(const Field &field1, Field &field2, int function)
{
  // clang-format off
  switch (function)
    {
    case func_min:   zonmin(field1, field2);    break;
    case func_max:   zonmax(field1, field2);    break;
    case func_range: zonrange(field1, field2);  break;
    case func_sum:   zonsum(field1, field2);    break;
    case func_mean:  zonmean(field1, field2);   break;
    case func_avg:   zonavg(field1, field2);    break;
    case func_std:   zonstd(field1, field2);    break;
    case func_std1:  zonstd1(field1, field2);   break;
    case func_var:   zonvar(field1, field2);    break;
    case func_var1:  zonvar1(field1, field2);   break;
    default: cdoAbort("%s: function %d not implemented!",  __func__, function);
    }
  // clang-format on
}
