/*
  This file is part of CDO. CDO is a collection of Operators to manipulate and analyse Climate model Data.

  Author: Uwe Schulzweida

*/

/*
   This module contains the following operators:

      Transpose  transxy         Transpose X/Y
*/

#include <cdi.h>

#include "process_int.h"
#include "matrix_view.h"

void
transxy(int gridID, const Varray<double> &v1, Varray<double> &v2)
{
  const auto nx = gridInqXsize(gridID);
  const auto ny = gridInqYsize(gridID);
  const auto gridsize = gridInqSize(gridID);

  if (gridsize == (nx * ny))
    {
      MatrixView<const double> mV1(v1.data(), ny, nx);
      MatrixView<double > mV2(v2.data(), nx, ny);

      for (size_t j = 0; j < ny; ++j)
        for (size_t i = 0; i < nx; ++i) mV2[i][j] = mV1[j][i];
    }
  else
    {
      for (size_t i = 0; i < gridsize; ++i) v2[i] = v1[i];
    }
}

void *
Transpose(void *process)
{
  cdo_initialize(process);

  operator_check_argc(0);

  const auto streamID1 = cdo_open_read(0);

  const auto vlistID1 = cdo_stream_inq_vlist(streamID1);
  const auto vlistID2 = vlistDuplicate(vlistID1);

  const auto ngrids = vlistNgrids(vlistID1);
  for (int index = 0; index < ngrids; index++)
    {
      const auto gridID1 = vlistGrid(vlistID1, index);
      const auto nx = gridInqXsize(gridID1);
      const auto ny = gridInqYsize(gridID1);
      const auto gridsize = gridInqSize(gridID1);
      if (gridsize == (nx * ny))
        {
          const auto gridID2 = gridCreate(GRID_GENERIC, gridsize);
          gridDefXsize(gridID2, ny);
          gridDefYsize(gridID2, nx);
          vlistChangeGridIndex(vlistID2, index, gridID2);
        }
    }

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

  const auto streamID2 = cdo_open_write(1);
  cdo_def_vlist(streamID2, vlistID2);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);

  Varray<double> array1(gridsizemax), array2(gridsizemax);

  int tsID = 0;
  while (true)
    {
      const auto nrecs = cdo_stream_inq_timestep(streamID1, tsID);
      if (nrecs == 0) break;

      cdo_taxis_copy_timestep(taxisID2, taxisID1);
      cdo_def_timestep(streamID2, tsID);

      for (int recID = 0; recID < nrecs; recID++)
        {
          size_t nmiss;
          int varID, levelID;
          cdo_inq_record(streamID1, &varID, &levelID);
          cdo_read_record(streamID1, array1.data(), &nmiss);

          const auto gridID = vlistInqVarGrid(vlistID1, varID);
          transxy(gridID, array1, array2);

          cdo_def_record(streamID2, varID, levelID);
          cdo_write_record(streamID2, array2.data(), nmiss);
        }

      tsID++;
    }

  cdo_stream_close(streamID2);
  cdo_stream_close(streamID1);

  cdo_finish();

  return nullptr;
}
