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

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

  cdoInitialize(process);

  operatorCheckArgc(0);

  const auto streamID1 = cdoOpenRead(0);

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

  const auto streamID2 = cdoOpenWrite(1);
  if (1 != operatorArgc()) cdoAbort("Operator tee requires exactly 1 argument.");
  const auto streamID3 = streamOpenWrite(cdoOperatorArgv(0).c_str(), cdoFiletype());

  const auto vlistID2 = vlistDuplicate(vlistID1);
  const auto vlistID3 = vlistDuplicate(vlistID1);

  const auto taxisID2 = taxisDuplicate(taxisID1);
  const auto taxisID3 = taxisDuplicate(taxisID1);

  vlistDefTaxis(vlistID2, taxisID2);
  vlistDefTaxis(vlistID3, taxisID3);

  cdoDefVlist(streamID2, vlistID2);
  streamDefVlist(streamID3, vlistID3);

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

  int tsID = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      taxisCopyTimestep(taxisID2, taxisID1);
      taxisCopyTimestep(taxisID3, taxisID1);

      cdoDefTimestep(streamID2, tsID);
      streamDefTimestep(streamID3, tsID);

      for (int recID = 0; recID < nrecs; recID++)
        {
          cdoInqRecord(streamID1, &varID, &levelID);
          cdoReadRecord(streamID1, array.data(), &nmiss);

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

          streamDefRecord(streamID3, varID, levelID);
          streamWriteRecord(streamID3, array.data(), nmiss);
        }

      tsID++;
    }

  cdoStreamClose(streamID1);
  cdoStreamClose(streamID2);
  streamClose(streamID3);

  cdoFinish();

  return nullptr;
}
