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

void *
Seloperator(void *process)
{
  int nrecs;
  int varID, levelID;
  int nlevs, code, zaxisID;
  bool selfound = false;
  int levID, ltype = 0;
  int varID2, levelID2;
  bool sellevel, selcode, selltype;
  size_t nmiss;
  double slevel = 0, level;

  cdoInitialize(process);

  const auto lcopy = unchangedRecord();

  operatorInputArg("code, ltype, level");

  const auto scode = parameter2int(cdoOperatorArgv(0));
  const auto sltype = parameter2int(cdoOperatorArgv(1));

  if (operatorArgc() == 3) slevel = parameter2double(cdoOperatorArgv(2));

  const auto streamID1 = cdoOpenRead(0);
  const auto vlistID1 = cdoStreamInqVlist(streamID1);

  const auto nvars = vlistNvars(vlistID1);
  for (varID = 0; varID < nvars; varID++)
    {
      code = vlistInqVarCode(vlistID1, varID);
      zaxisID = vlistInqVarZaxis(vlistID1, varID);
      nlevs = zaxisInqSize(zaxisID);

      ltype = zaxis2ltype(zaxisID);

      for (levID = 0; levID < nlevs; levID++)
        {
          level = cdoZaxisInqLevel(zaxisID, levID);

          if (operatorArgc() == 3)
            sellevel = IS_EQUAL(level, slevel);
          else
            sellevel = true;

          selcode = scode == -1 || scode == code;

          selltype = sltype == -1 || sltype == ltype;

          if (selcode && selltype && sellevel)
            {
              vlistDefFlag(vlistID1, varID, levID, true);
              selfound = true;
            }
        }
    }

  if (!selfound) cdoWarning("Code %d, ltype %d, level %g not found!", scode, sltype, slevel);

  const auto vlistID2 = vlistCreate();
  cdoVlistCopyFlag(vlistID2, vlistID1);

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

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

  Varray<double> array;
  if (!lcopy)
    {
      const auto gridsizemax = vlistGridsizeMax(vlistID1);
      array.resize(gridsizemax);
    }

  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);
          if (vlistInqFlag(vlistID1, varID, levelID) == true)
            {
              varID2 = vlistFindVar(vlistID2, varID);
              levelID2 = vlistFindLevel(vlistID2, varID, levelID);

              cdoDefRecord(streamID2, varID2, levelID2);

              if (lcopy)
                {
                  cdoCopyRecord(streamID2, streamID1);
                }
              else
                {
                  cdoReadRecord(streamID1, array.data(), &nmiss);
                  cdoWriteRecord(streamID2, array.data(), nmiss);
                }
            }
        }

      tsID++;
    }

  cdoStreamClose(streamID1);
  cdoStreamClose(streamID2);

  vlistDestroy(vlistID2);

  cdoFinish();

  return nullptr;
}
