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

  Copyright (C) 2003-2021 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"

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

  operator_check_argc(0);

  const auto streamID = cdo_open_read(0);
  const auto vlistID = cdo_stream_inq_vlist(streamID);

  auto gridID = vlistGrid(vlistID, 0);

  const auto gridsize = gridInqSize(gridID);

  gridID = generate_full_cell_grid(gridID);

  if (!gridHasCoordinates(gridID)) cdo_abort("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;
    }

  write_n_cgrid(cdo_get_stream_name(1), gridID, mask.data());

  cdo_stream_close(streamID);

  cdo_finish();

  return nullptr;
}
