/*
  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 "process_int.h"
#include "param_conversion.h"
#include "statistic.h"

void *
Tests(void *process)
{
  int nrecs;
  int varID, levelID;
  size_t nmiss;
  double degree_of_freedom = 0, p = 0, q = 0, n = 0, d = 0;

  cdoInitialize(process);

  // clang-format off
  const auto  NORMAL    = cdoOperatorAdd("normal",    0, 0, nullptr);
  const auto  STUDENTT  = cdoOperatorAdd("studentt",  0, 0, "degree of freedom");
  const auto  CHISQUARE = cdoOperatorAdd("chisquare", 0, 0, "degree of freedom");
  const auto  BETA      = cdoOperatorAdd("beta",      0, 0, "p and q");
  const auto  FISHER    = cdoOperatorAdd("fisher",    0, 0, "degree of freedom of nominator and of denominator");
  // clang-format on

  const auto operatorID = cdoOperatorID();

  if (operatorID == STUDENTT || operatorID == CHISQUARE)
    {
      operatorInputArg(cdoOperatorEnter(operatorID));

      operatorCheckArgc(1);

      degree_of_freedom = parameter2double(cdoOperatorArgv(0));

      if (degree_of_freedom <= 0) cdoAbort("degree of freedom must be positive!");
    }
  else if (operatorID == BETA)
    {
      operatorInputArg(cdoOperatorEnter(operatorID));

      operatorCheckArgc(2);

      p = parameter2double(cdoOperatorArgv(0));
      q = parameter2double(cdoOperatorArgv(1));

      if (p <= 0 || q <= 0) cdoAbort("p and q must be positive!");
    }
  else if (operatorID == FISHER)
    {
      operatorInputArg(cdoOperatorEnter(operatorID));

      operatorCheckArgc(2);

      n = parameter2double(cdoOperatorArgv(0));
      d = parameter2double(cdoOperatorArgv(1));

      if (n <= 0 || d <= 0) cdoAbort("both degrees must be positive!");
    }

  const auto streamID1 = cdoOpenRead(0);

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

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

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

  const auto gridsizemax = vlistGridsizeMax(vlistID1);
  Varray<double> array1(gridsizemax), array2(gridsizemax);

  VarList varList1;
  varListInit(varList1, vlistID1);

  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, array1.data(), &nmiss);

          const auto gridsize = varList1[varID].gridsize;
          const auto missval = varList1[varID].missval;

          if (operatorID == NORMAL)
            {
              for (size_t i = 0; i < gridsize; i++)
                array2[i] = DBL_IS_EQUAL(array1[i], missval) ? missval : cdo::normal(array1[i], processInqPrompt());
            }
          else if (operatorID == STUDENTT)
            {
              for (size_t i = 0; i < gridsize; i++)
                array2[i]
                  = DBL_IS_EQUAL(array1[i], missval) ? missval : cdo::student_t(degree_of_freedom, array1[i], processInqPrompt());
            }
          else if (operatorID == CHISQUARE)
            {
              for (size_t i = 0; i < gridsize; i++)
                array2[i]
                    = DBL_IS_EQUAL(array1[i], missval) ? missval : cdo::chi_square(degree_of_freedom, array1[i], processInqPrompt());
            }
          else if (operatorID == BETA)
            {
              for (size_t i = 0; i < gridsize; i++)
                {
                  if (array1[i] < 0 || array1[i] > 1) cdoAbort("Value out of range (0-1)!");

                  array2[i] = DBL_IS_EQUAL(array1[i], missval) ? missval : cdo::beta_distr(p, q, array1[i], processInqPrompt());
                }
            }
          else if (operatorID == FISHER)
            {
              for (size_t i = 0; i < gridsize; i++)
                array2[i] = DBL_IS_EQUAL(array1[i], missval) ? missval : cdo::fisher(n, d, array1[i], processInqPrompt());
            }
          else
            {
              cdoAbort("Internal problem, operator not implemented!");
            }

          cdoDefRecord(streamID2, varID, levelID);
          cdoWriteRecord(streamID2, array2.data(), nmiss);
        }

      tsID++;
    }

  cdoStreamClose(streamID1);
  cdoStreamClose(streamID2);

  vlistDestroy(vlistID2);

  cdoFinish();

  return nullptr;
}
