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

      Setmiss    setmissval      Set a new missing value
      Setmiss    setctomiss      Set constant to missing value
      Setmiss    setmisstoc      Set missing value to constant
      Setmiss    setrtomiss      Set range to missing value
      Setmiss    setvrange       Set range of valid value
*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <cmath>
#include <cdi.h>

#include "process_int.h"
#include "param_conversion.h"

void *
Setmiss(void *process)
{
  int nrecs;
  int varID, levelID;
  size_t nmiss;
  double missval2 = 0;
  double rconst = 0, rmin = 0, rmax = 0;

  cdoInitialize(process);

  // clang-format off
  const auto SETMISSVAL = cdoOperatorAdd("setmissval", 0, 0, "missing value");
  const auto SETCTOMISS = cdoOperatorAdd("setctomiss", 0, 0, "constant");
  const auto SETMISSTOC = cdoOperatorAdd("setmisstoc", 0, 0, "constant");
  const auto SETRTOMISS = cdoOperatorAdd("setrtomiss", 0, 0, "range (min, max)");
  const auto SETVRANGE  = cdoOperatorAdd("setvrange",  0, 0, "range (min, max)");
  // clang-format on

  const auto operatorID = cdoOperatorID();

  if (operatorID == SETMISSVAL)
    {
      operatorCheckArgc(1);
      missval2 = parameter2double(cdoOperatorArgv(0));
    }
  else if (operatorID == SETCTOMISS || operatorID == SETMISSTOC)
    {
      operatorCheckArgc(1);
      rconst = parameter2double(cdoOperatorArgv(0));
    }
  else
    {
      operatorCheckArgc(2);
      rmin = parameter2double(cdoOperatorArgv(0));
      rmax = parameter2double(cdoOperatorArgv(1));
    }

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

  if (operatorID == SETMISSVAL)
    {
      const auto nvars = vlistNvars(vlistID2);
      for (varID = 0; varID < nvars; varID++) vlistDefVarMissval(vlistID2, varID, missval2);
    }
  else if (operatorID == SETMISSTOC)
    {
      const auto nvars = vlistNvars(vlistID2);
      for (varID = 0; varID < nvars; varID++)
        {
          const auto missval = vlistInqVarMissval(vlistID2, varID);
          if (DBL_IS_EQUAL(rconst, missval))
            {
              cdoWarning("Missing value and constant have the same value!");
              break;
            }
        }
    }

  /*
  if ( operatorID == SETVRANGE )
    {
      double range[2];
      range[0] = rmin;
      range[1] = rmax;

      nvars = vlistNvars(vlistID2);
      for ( varID = 0; varID < nvars; varID++ )
        cdiDefAttFlt(vlistID2, varID, "valid_range", CDI_DATATYPE_FLT64, 2,
  range);
    }
  */
  const auto streamID2 = cdoOpenWrite(1);
  cdoDefVlist(streamID2, vlistID2);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);
  Varray<double> array(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, array.data(), &nmiss);

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

          if (operatorID == SETMISSVAL)
            {
              nmiss = 0;
              for (size_t i = 0; i < gridsize; i++)
                if (DBL_IS_EQUAL(array[i], missval) || DBL_IS_EQUAL(array[i], (float) missval) || DBL_IS_EQUAL(array[i], missval2)
                    || DBL_IS_EQUAL(array[i], (float) missval2))
                  {
                    array[i] = missval2;
                    nmiss++;
                  }
            }
          else if (operatorID == SETCTOMISS)
            {
              if (std::isnan(rconst))
                {
                  for (size_t i = 0; i < gridsize; i++)
                    if (std::isnan(array[i]))
                      {
                        array[i] = missval;
                        nmiss++;
                      }
                }
              else
                {
                  for (size_t i = 0; i < gridsize; i++)
                    if (DBL_IS_EQUAL(array[i], rconst) || DBL_IS_EQUAL(array[i], (float) rconst))
                      {
                        array[i] = missval;
                        nmiss++;
                      }
                }
            }
          else if (operatorID == SETMISSTOC)
            {
              nmiss = 0;
              for (size_t i = 0; i < gridsize; i++)
                if (DBL_IS_EQUAL(array[i], missval) || DBL_IS_EQUAL(array[i], (float) missval))
                  {
                    array[i] = rconst;
                  }
            }
          else if (operatorID == SETRTOMISS)
            {
              for (size_t i = 0; i < gridsize; i++)
                if (array[i] >= rmin && array[i] <= rmax)
                  {
                    array[i] = missval;
                    nmiss++;
                  }
            }
          else if (operatorID == SETVRANGE)
            {
              for (size_t i = 0; i < gridsize; i++)
                if (array[i] < rmin || array[i] > rmax) array[i] = missval;

              nmiss = varrayNumMV(gridsize, array, missval);
            }

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

      tsID++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
