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

#include "cdo_varlist.h"

void
varListInit(VarList &vl, int vlistID)
{
  const auto nvars = vlistNvars(vlistID);
  vl.resize(nvars);

  for (int varID = 0; varID < nvars; ++varID)
    {
      vlistInqVarName(vlistID, varID, vl[varID].name);
      vl[varID].gridID = vlistInqVarGrid(vlistID, varID);
      vl[varID].zaxisID = vlistInqVarZaxis(vlistID, varID);
      vl[varID].timetype = vlistInqVarTimetype(vlistID, varID);
      vl[varID].tsteptype = vlistInqVarTsteptype(vlistID, varID);
      vl[varID].gridsize = gridInqSize(vl[varID].gridID);
      vl[varID].nlevels = zaxisInqSize(vl[varID].zaxisID);
      vl[varID].datatype = vlistInqVarDatatype(vlistID, varID);
      vl[varID].missval = vlistInqVarMissval(vlistID, varID);
      vl[varID].code = vlistInqVarCode(vlistID, varID);
      vl[varID].param = vlistInqVarParam(vlistID, varID);
      vl[varID].nwpv = vlistInqVarNumber(vlistID, varID);
      if (Options::CDO_Memtype == MemType::Native)
        vl[varID].memType = (vl[varID].datatype == CDI_DATATYPE_FLT32 || vl[varID].datatype == CDI_DATATYPE_CPX32)
                                ? MemType::Float
                                : MemType::Double;
      else
        vl[varID].memType = Options::CDO_Memtype;
    }
}

void
varListSetUniqueMemtype(VarList &vl)
{
  const int nvars = vl.size();
  if (nvars)
    {
      const auto memtype = vl[0].memType;
      int varID;
      for (varID = 1; varID < nvars; ++varID)
        {
          if (vl[varID].memType != memtype) break;
        }
      if (varID < nvars) varListSetMemtype(vl, MemType::Double);
    }
}

void
varListSetMemtype(VarList &vl, MemType memType)
{
  for (auto &var : vl) var.memType = memType;
}
