/*
  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 1warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
*/

/*
   This module contains the following operators:

      Change_e5slm      change_e5slm          Change ECHAM5 sea land mask
*/

#include <cdi.h>

#include "process_int.h"
#include "cdi_lockedIO.h"

void *
Change_e5slm(void *process)
{
  char name[CDI_MAX_NAME];
  int nrecs;
  int varID, levelID;
  size_t nmiss;

  cdoInitialize(process);

  const auto streamID1 = cdoOpenRead(0);

  const auto vlistID1 = cdoStreamInqVlist(streamID1);
  const auto taxisID1 = vlistInqTaxis(vlistID1);

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

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

  /* get filename of SLM */
  operatorInputArg("filename of the sea land mask");
  operatorCheckArgc(1);
  const char *fn_slm = cdoOperatorArgv(0).c_str();

  /* read SLM */
  const auto streamIDslm = streamOpenReadLocked(fn_slm);
  const auto vlistIDslm = streamInqVlist(streamIDslm);

  const auto gridsize = gridInqSize(vlistInqVarGrid(vlistIDslm, 0));

  Varray<double> array(gridsize);
  Varray<double> cland(gridsize);
  Varray<bool> lsea(gridsize);

  streamInqTimestep(streamIDslm, 0);

  streamInqRecord(streamIDslm, &varID, &levelID);
  streamReadRecord(streamIDslm, cland.data(), &nmiss);

  if (nmiss) cdoAbort("SLM with missing values are unsupported!");

  const auto mm = varrayMinMax(cland);
  if (mm.min < 0 || mm.max > 1)
    cdoWarning("Values of SLM out of bounds! (minval=%g, maxval=%g)", mm.min, mm.max);

  streamClose(streamIDslm);

  for (size_t i = 0; i < gridsize; ++i) lsea[i] = cland[i] <= 0;

  const auto nvars = vlistNvars(vlistID1);
  std::vector<short> codes(nvars);

  for (varID = 0; varID < nvars; ++varID)
    {
      if (gridsize != gridInqSize(vlistInqVarGrid(vlistID1, varID))) cdoAbort("gridsize differ!");

      auto code = vlistInqVarCode(vlistID1, varID);
      vlistInqVarName(vlistID1, varID, name);

      if (code < 0)
        {
          // clang-format off
          if      (cstrIsEqual(name, "SLM")      ) code = 172;
          else if (cstrIsEqual(name, "ALAKE")    ) code = 99;
          else if (cstrIsEqual(name, "WS")       ) code = 140;
          else if (cstrIsEqual(name, "AZ0")      ) code = 173;
          else if (cstrIsEqual(name, "ALB")      ) code = 174;
          else if (cstrIsEqual(name, "VGRAT")    ) code = 198;
          else if (cstrIsEqual(name, "FOREST")   ) code = 212;
          else if (cstrIsEqual(name, "FAO")      ) code = 226;
          else if (cstrIsEqual(name, "WSMX")     ) code = 229;
          else if (cstrIsEqual(name, "GLAC")     ) code = 232;
          else if (cstrIsEqual(name, "VLTCLIM")  ) code = 71;
          else if (cstrIsEqual(name, "VGRATCLIM")) code = 70;
          // clang-format on
        }

      codes[varID] = code;
    }

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

          auto code = codes[varID];
          if (code == 172)
            {
              cdoPrint("SLM changed!");
              for (size_t i = 0; i < gridsize; ++i) array[i] = cland[i];
            }
          else if (code == 99)
            {
              cdoPrint("ALAKE set all values to zero!");
              for (size_t i = 0; i < gridsize; ++i) array[i] = 0;
            }
          else if (code == 232)
            {
              cdoPrint("GLAC set sea points to %g!", array[0]);
              for (size_t i = 0; i < gridsize; ++i)
                if (cland[i] < 0.5) array[i] = array[0];
            }
          else if (code == 70 || code == 71 || code == 140 || code == 173 || code == 174 || code == 198 || code == 200
                   || code == 212 || code == 226 || code == 229)
            {
              cdoPrint("Code %d set sea points to %g!", code, array[0]);
              for (size_t i = 0; i < gridsize; ++i)
                if (lsea[i]) array[i] = array[0];
            }

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

      tsID++;
    }

  cdoStreamClose(streamID1);
  cdoStreamClose(streamID2);

  cdoFinish();

  return nullptr;
}
