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

      Harmonic   harmonic        Harmonic
*/

#include <cdi.h>

#include "process_int.h"
#include "cdo_cdi_wrapper.h"
#include "cdo_vlist.h"
#include "param_conversion.h"
#include "util_files.h"
#include "array.h"

void *
Harmonic(void *process)
{
  int nrecs;
  int varID, levelID;
  size_t nmiss;
  int64_t vdate = 0;
  int vtime = 0;

  cdoInitialize(process);

  operatorInputArg("wave number and wave length of first harmonic in number of timesteps");

  operatorCheckArgc(2);

  auto n_out = parameter2int(cdoOperatorArgv(0));
  auto n = parameter2int(cdoOperatorArgv(1));

  if (n_out > 9) cdoAbort("Maximum number of wave numbers is 9!");

  if (n < 1 || n < 2 * n_out)
    cdoAbort("The wave length must be positive and smaller than 2 times the number of requested harmonics (=%d)!", n_out);

  const auto streamID1 = cdoOpenRead(0);

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

  VarList varList1, varList2;
  varListInit(varList1, vlistID1);
  varListInit(varList2, vlistID2);

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

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

  std::vector<CdoStreamID> streamIDs(n_out);

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

  for (int j = 0; j < n_out; ++j)
    {
      sprintf(filename + nchars, "%1d", j + 1);
      if (filesuffix[0]) sprintf(filename + nchars + 1, "%s", filesuffix);

      const auto streamID2 = cdoOpenWrite(filename);
      cdoDefVlist(streamID2, vlistID2);
      streamIDs[j] = streamID2;
    }

  const auto nvars = vlistNvars(vlistID1);

  Varray3D<double> out(n_out);
  Varray3D<double> work(2 * n_out);

  for (int j = 0; j < n_out; ++j)
    {
      out[j].resize(nvars);
      for (varID = 0; varID < nvars; ++varID)
        out[j][varID].resize(varList1[varID].nlevels * varList1[varID].gridsize);
    }

  for (int j = 0; j < n_out * 2; ++j)
    {
      work[j].resize(nvars);
      for (varID = 0; varID < nvars; ++varID)
        {
          const auto gridsize = varList1[varID].gridsize;
          const auto nlevels = varList1[varID].nlevels;
          work[j][varID].resize(gridsize * nlevels);
          varrayFill(gridsize * nlevels, work[j][varID], 0.0);
        }
    }

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

  int tsID = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      if (tsID == 0)
        {
          vdate = taxisInqVdate(taxisID1);
          vtime = taxisInqVtime(taxisID1);
        }

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

          if (nmiss) cdoAbort("Missing values are not allowed!");

          const auto gridsize = varList1[varID].gridsize;
          const auto offset = gridsize * levelID;

          for (int j = 0; j < n_out; ++j)
            {
              const auto scarg = 2 * M_PI * (((j + 1) * (tsID + 1)) % n) / n;
              const auto sine = std::sin(scarg);
              const auto cosine = std::cos(scarg);
              for (size_t i = 0; i < gridsize; i++)
                {
                  work[j][varID][i + offset] += array[i] * sine;
                  work[n_out + j][varID][i + offset] += array[i] * cosine;
                }
            }
        }

      tsID++;
    }

  const auto nts = tsID;

  cdoStreamClose(streamID1);

  if (nts % n)
    {
      cdoAbort("The length of first harmonic (=%d) does not divide the number of timesteps (=%d)!", n, nts);
    }

  for (int j = 0; j < n_out && 2 * (j + 1) < n; j++)
    {
      for (varID = 0; varID < nvars; varID++)
        {
          const auto gridsize = varList2[varID].gridsize;
          const auto nlevels = varList2[varID].nlevels;
          for (levelID = 0; levelID < nlevels; levelID++)
            {
              const auto offset = gridsize * levelID;
              for (size_t i = 0; i < gridsize; i++)
                {
                  const auto sqrwork1 = work[j][varID][i + offset] * work[j][varID][i + offset];
                  const auto sqrwork2 = work[n_out + j][varID][i + offset] * work[n_out + j][varID][i + offset];
                  out[j][varID][i + offset] = std::sqrt(sqrwork1 + sqrwork2) * 2 / nts;
                }
            }
        }
    }

  if (2 * n_out == n)
    {
      for (varID = 0; varID < nvars; varID++)
        {
          const auto gridsize = varList2[varID].gridsize;
          const auto nlevels = varList2[varID].nlevels;
          for (levelID = 0; levelID < nlevels; levelID++)
            {
              const auto offset = gridsize * levelID;
              for (size_t i = 0; i < gridsize; i++)
                out[n_out - 1][varID][i + offset] = work[2 * n_out - 1][varID][i + offset] / nts;
            }
        }
    }

  auto nout = n_out;

  taxisDefVdate(taxisID2, vdate);
  taxisDefVtime(taxisID2, vtime);
  for (int j = 0; j < nout; j++)
    {
      const auto streamID2 = streamIDs[j];
      cdoDefTimestep(streamID2, 0);

      for (varID = 0; varID < nvars; varID++)
        {
          const auto gridsize = varList2[varID].gridsize;
          const auto nlevels = varList2[varID].nlevels;
          for (levelID = 0; levelID < nlevels; levelID++)
            {
              const auto offset = gridsize * levelID;
              cdoDefRecord(streamID2, varID, levelID);
              cdoWriteRecord(streamID2, &out[j][varID][offset], 0);
            }
        }
    }

  for (int j = 0; j < n_out && 2 * (j + 1) < n; j++)
    {
      for (varID = 0; varID < nvars; varID++)
        {
          const auto gridsize = varList2[varID].gridsize;
          const auto nlevels = varList2[varID].nlevels;
          const auto missval = vlistInqVarMissval(vlistID2, varID);
          for (levelID = 0; levelID < nlevels; levelID++)
            {
              const auto offset = gridsize * levelID;
              for (size_t i = 0; i < gridsize; i++)
                {
                  const auto work1 = work[j][varID][i + offset];
                  const auto work2 = work[n_out + j][varID][i + offset];
                  const auto tmpatan2 = atan2(work1, work2) * n / (j + 1) / 2 / M_PI;
                  out[j][varID][i + offset] = work1 > 0. || work2 > 0. ? tmpatan2 : missval;
                  if (out[j][varID][i + offset] < 0) out[j][varID][i + offset] += n / (j + 1.);
                }
            }
        }
    }

  nout = n_out;
  if (2 * n_out == n) nout -= 1;

  taxisDefVdate(taxisID2, vdate);
  taxisDefVtime(taxisID2, vtime);
  for (int j = 0; j < nout; j++)
    {
      const auto streamID2 = streamIDs[j];
      cdoDefTimestep(streamID2, 1);

      for (varID = 0; varID < nvars; varID++)
        {
          const auto gridsize = varList2[varID].gridsize;
          const auto nlevels = varList2[varID].nlevels;
          const auto missval = vlistInqVarMissval(vlistID2, varID);
          for (levelID = 0; levelID < nlevels; levelID++)
            {
              const auto offset = gridsize * levelID;
              nmiss = arrayNumMV(gridsize, &out[j][varID][offset], missval);
              cdoDefRecord(streamID2, varID, levelID);
              cdoWriteRecord(streamID2, &out[j][varID][offset], nmiss);
            }
        }
    }

  for (int j = 0; j < n_out; j++) cdoStreamClose(streamIDs[j]);

  cdoFinish();

  return nullptr;
}
