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

  Author: Uwe Schulzweida

*/

#include <stdlib.h>
#include <string>

#include <cdi.h>
#include "cdo_output.h"
#include "util_files.h"

int
define_table(const char *tablearg)
{
  const char *tablename = tablearg;

  int tableID = FileUtils::file_exists(tablename) ? tableRead(tablename) : CDI_UNDEFID;

  if (tableID == CDI_UNDEFID)
    {
      const std::string tablepath = getenv("CD_TABLEPATH");
      if (tablepath.size())
        {
          const std::string tablefile = tablepath + "/" + tablename;
          if (FileUtils::file_exists(tablefile)) tableID = tableRead(tablefile.c_str());
        }
    }

  if (tableID == CDI_UNDEFID) tableID = tableInq(-1, 0, tablename);

  if (tableID == CDI_UNDEFID) cdo_abort("table <%s> not found", tablename);

  return tableID;
}
