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

#include <cdi.h>

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

void *
CDItest(void *process)
{
  int nrecs;
  int varID, levelID;
  size_t nmiss;
  int max_copy = 3;

  cdoInitialize(process);

  const auto lcopy = false;
  // bool lcopy = unchangedRecord();

  const auto NCOPY = cdoOperatorAdd("ncopy", 0, 0, nullptr);
  (void) (NCOPY);  // CDO_UNUSED

  const auto operatorID = cdoOperatorID();
  (void) (operatorID);  // CDO_UNUSED

  //  operatorInputArg("Number of copies");
  if (operatorArgc() == 1) max_copy = parameter2int(cdoOperatorArgv(0));

  const auto startTime = cdo_get_wtime();

  int n = 0;
  while (true)
    {
      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);

      const auto gridsize = vlistGridsizeMax(vlistID1);
      Varray<double> array(gridsize);

      int tsID1 = 0;
      int tsID2 = 0;
      while ((nrecs = cdoStreamInqTimestep(streamID1, tsID1)))
        {
          taxisCopyTimestep(taxisID2, taxisID1);

          cdoDefTimestep(streamID2, tsID2);

          for (int recID = 0; recID < nrecs; recID++)
            {
              cdoInqRecord(streamID1, &varID, &levelID);
              cdoDefRecord(streamID2, varID, levelID);

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

          tsID1++;
          tsID2++;
        }

      cdoStreamClose(streamID1);
      cdoStreamClose(streamID2);

      vlistDestroy(vlistID2);
      taxisDestroy(taxisID2);

      n++;

      cdoPrint("Copy number %d: %.2fs", n, cdo_get_wtime() - startTime);

      if (n == max_copy) break;
    }

  cdoFinish();

  return nullptr;
}
