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

#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)
    {
      char *tablepath = getenv("CD_TABLEPATH");
      if (tablepath)
        {
          int len = sizeof(tablepath) + sizeof(tablename) + 3;
          char *tablefile = (char *) malloc(len * sizeof(char));
          strcpy(tablefile, tablepath);
          strcat(tablefile, "/");
          strcat(tablefile, tablename);
          if (FileUtils::file_exists(tablename)) tableID = tableRead(tablefile);
          free(tablefile);
        }
    }

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

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

  return tableID;
}
