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

      writegrid Write grid
*/

#include <cdi.h>

#include "process_int.h"
#include <mpim_grid.h>
#include "griddes.h"
#include "gridreference.h"

void *
Writegrid(void *process)
{
  cdoInitialize(process);

  operatorCheckArgc(0);

  const auto streamID = cdoOpenRead(0);
  const auto vlistID = cdoStreamInqVlist(streamID);

  auto gridID = vlistGrid(vlistID, 0);

  const auto gridtype = gridInqType(gridID);
  const auto gridsize = gridInqSize(gridID);

  if (gridtype == GRID_GME) gridID = gridToUnstructured(gridID, 1);

  if (gridtype != GRID_CURVILINEAR && gridtype != GRID_UNSTRUCTURED) gridID = gridToCurvilinear(gridID, 1);

  if (gridtype == GRID_UNSTRUCTURED && !gridHasCoordinates(gridID))
    {
      const auto reference = dereferenceGrid(gridID);
      if (reference.isValid) gridID = reference.gridID;
      if (!reference.notFound) cdoAbort("Reference to source grid not found!");
    }

  if (!gridHasCoordinates(gridID)) cdoAbort("Cell corner coordinates missing!");

  std::vector<int> mask(gridsize);

  if (gridInqMask(gridID, nullptr))
    {
      gridInqMask(gridID, mask.data());
    }
  else
    {
      for (size_t i = 0; i < gridsize; i++) mask[i] = 1;
    }

  writeNCgrid(cdoGetStreamName(1), gridID, mask.data());

  cdoStreamClose(streamID);

  cdoFinish();

  return nullptr;
}
