/*
  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"
#include "percentiles.h"

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

static void
merKernel(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 nx = gridInqXsize(field1.grid);
  const auto ny = gridInqYsize(field1.grid);

  Varray<double> v(ny);

  for (size_t i = 0; i < nx; ++i)
    {
      for (size_t j = 0; j < ny; j++) v[j] = field1.vec_d[j * nx + i];

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

  field2.nmiss = rnmiss;
}

static void
mermin(const Field &field1, Field &field2)
{
  merKernel(field1, field2, varrayMin, varrayMinMV);
}

static void
mermax(const Field &field1, Field &field2)
{
  merKernel(field1, field2, varrayMax, varrayMaxMV);
}

static void
merrange(const Field &field1, Field &field2)
{
  merKernel(field1, field2, varrayRange, varrayRangeMV);
}

static void
mersum(const Field &field1, Field &field2)
{
  merKernel(field1, field2, varraySum, varraySumMV);
}

static void
mermeanw(const Field &field1, Field &field2)
{
  const auto missval = field1.missval;
  const auto nx = gridInqXsize(field1.grid);
  const auto ny = gridInqYsize(field1.grid);

  Varray<double> v(ny), w(ny);

  size_t rnmiss = 0;
  for (size_t i = 0; i < nx; ++i)
    {
      for (size_t j = 0; j < ny; j++) v[j] = field1.vec_d[j * nx + i];
      for (size_t j = 0; j < ny; j++) w[j] = field1.weightv[j * nx + i];

      const auto rmean = field1.nmiss ? varrayWeightedMeanMV(ny, v, w, missval) : varrayWeightedMean(ny, v, w, missval);
      if (DBL_IS_EQUAL(rmean, missval)) rnmiss++;
      field2.vec_d[i] = rmean;
    }

  field2.nmiss = rnmiss;
}

static void
meravgw(const Field &field1, Field &field2)
{
  const auto missval = field1.missval;
  const auto nx = gridInqXsize(field1.grid);
  const auto ny = gridInqYsize(field1.grid);

  Varray<double> v(ny), w(ny);

  size_t rnmiss = 0;
  for (size_t i = 0; i < nx; ++i)
    {
      for (size_t j = 0; j < ny; j++) v[j] = field1.vec_d[j * nx + i];
      for (size_t j = 0; j < ny; j++) w[j] = field1.weightv[j * nx + i];

      const auto ravg = field1.nmiss ? varrayWeightedAvgMV(ny, v, w, missval) : varrayWeightedMean(ny, v, w, missval);
      if (DBL_IS_EQUAL(ravg, missval)) rnmiss++;
      field2.vec_d[i] = ravg;
    }

  field2.nmiss = rnmiss;
}

static void
mervarw(const Field &field1, Field &field2)
{
  size_t rnmiss = 0;
  const auto missval = field1.missval;

  const auto nx = gridInqXsize(field1.grid);
  const auto ny = gridInqYsize(field1.grid);

  Varray<double> v(ny), w(ny);

  for (size_t i = 0; i < nx; i++)
    {
      for (size_t j = 0; j < ny; j++) v[j] = field1.vec_d[j * nx + i];
      for (size_t j = 0; j < ny; j++) w[j] = field1.weightv[j * nx + i];

      const auto rvar = varrayWeightedVar(ny, v, w, field1.nmiss, missval);
      if (DBL_IS_EQUAL(rvar, missval)) rnmiss++;
      field2.vec_d[i] = rvar;
    }

  field2.nmiss = rnmiss;
}

static void
mervar1w(const Field &field1, Field &field2)
{
  size_t rnmiss = 0;
  const auto missval = field1.missval;

  const auto nx = gridInqXsize(field1.grid);
  const auto ny = gridInqYsize(field1.grid);

  Varray<double> v(ny), w(ny);

  for (size_t i = 0; i < nx; i++)
    {
      for (size_t j = 0; j < ny; j++) v[j] = field1.vec_d[j * nx + i];
      for (size_t j = 0; j < ny; j++) w[j] = field1.weightv[j * nx + i];

      const auto rvar = varrayWeightedVar1(ny, v, w, field1.nmiss, missval);
      if (DBL_IS_EQUAL(rvar, missval)) rnmiss++;
      field2.vec_d[i] = rvar;
    }

  field2.nmiss = rnmiss;
}

static void
merstdw(const Field &field1, Field &field2)
{
  size_t rnmiss = 0;
  const auto missval = field1.missval;

  const auto nx = gridInqXsize(field1.grid);

  mervarw(field1, field2);

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

  field2.nmiss = rnmiss;
}

static void
merstd1w(const Field &field1, Field &field2)
{
  size_t rnmiss = 0;
  const auto missval = field1.missval;

  const auto nx = gridInqXsize(field1.grid);

  mervar1w(field1, field2);

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

  field2.nmiss = rnmiss;
}

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

  const auto nx = gridInqXsize(field1.grid);
  const auto ny = gridInqYsize(field1.grid);

  Varray<double> array2(nx);

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

          if (l > 0)
            {
              field2.vec_d[i] = percentile(array2.data(), l, p);
            }
          else
            {
              field2.vec_d[i] = missval;
              rnmiss++;
            }
        }
    }
  else
    {
      for (size_t i = 0; i < nx; i++)
        {
          if (ny > 0)
            {
              for (size_t j = 0; j < ny; j++) array2[j] = field1.vec_d[j * nx + i];
              field2.vec_d[i] = percentile(array2.data(), ny, p);
            }
          else
            {
              field2.vec_d[i] = missval;
              rnmiss++;
            }
        }
    }

  field2.nmiss = rnmiss;
}

void
merfun(const Field &field1, Field &field2, int function)
{
  // clang-format off
  switch (function)
    {
    case func_min:   mermin(field1, field2);    break;
    case func_max:   mermax(field1, field2);    break;
    case func_range: merrange(field1, field2);  break;
    case func_sum:   mersum(field1, field2);    break;
    case func_meanw: mermeanw(field1, field2);  break;
    case func_avgw:  meravgw(field1, field2);   break;
    case func_stdw:  merstdw(field1, field2);   break;
    case func_std1w: merstd1w(field1, field2);  break;
    case func_varw:  mervarw(field1, field2);   break;
    case func_var1w: mervar1w(field1, field2);  break;
    default: cdoAbort("%s: function %d not implemented!", __func__, function);
    }
  // clang-format on
}
