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

      Split      splitrec        Split records
*/

#include <cdi.h>

#include "cdo_options.h"
#include "process_int.h"
#include "util_files.h"
#include "cdi_lockedIO.h"

void *
Splitrec(void *process)
{
  int nrecs;
  int varID, levelID;
  size_t nmiss;

  cdoInitialize(process);

  if (processSelf().m_ID != 0) cdoAbort("This operator can't be combined with other operators!");

  operatorCheckArgc(0);

  const auto lcopy = unchangedRecord();

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

  char filename[8192];
  strcpy(filename, cdoGetObase());
  int nchars = strlen(filename);

  auto refname = cdoGetStreamName(0);
  char filesuffix[32] = { 0 };
  cdoGenFileSuffix(filesuffix, sizeof(filesuffix), cdoInqFiletype(streamID1), vlistID1, refname);

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

  int index = 0;
  int tsID = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      for (int recID = 0; recID < nrecs; recID++)
        {
          cdoInqRecord(streamID1, &varID, &levelID);

          vlistClearFlag(vlistID1);
          vlistDefFlag(vlistID1, varID, levelID, true);

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

          index++;
          sprintf(filename + nchars, "%06d", index);
          if (filesuffix[0]) sprintf(filename + nchars + 6, "%s", filesuffix);

          if (Options::cdoVerbose) cdoPrint("create file %s", filename);

          const auto streamID2 = cdoOpenWrite(filename);

          cdoDefVlist(streamID2, vlistID2);

          const auto varID2 = vlistFindVar(vlistID2, varID);
          const auto levelID2 = vlistFindLevel(vlistID2, varID, levelID);

          cdoDefTimestep(streamID2, 0);
          cdoDefRecord(streamID2, varID2, levelID2);
          if (lcopy)
            {
              cdoCopyRecord(streamID2, streamID1);
            }
          else
            {
              cdoReadRecord(streamID1, array.data(), &nmiss);
              cdoWriteRecord(streamID2, array.data(), nmiss);
            }

          cdoStreamClose(streamID2);
          vlistDestroy(vlistID2);
        }

      tsID++;
    }

  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
