#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <yafl_rnt.h>
#include "dbx_rnt.h"
#include "dbx_worl.h"
#include "dbx_stri.h"
#include "dbx_cfg.h"

#define MAX_WORLDS 100
static dbx_world world_table[MAX_WORLDS];
static unsigned used_worlds = 0;

static char delimiters[] = ":;";

/* CAUTION: this string is system-dependant */
static char separator[] = "/";

#define MAX_ENVIRONS 100

int fexists YPARAMS2(char *, file_name)
{
  FILE *f;
  assertp (file_name);
  f = fopen(file_name, "r");
  if (f)
  {
    fclose(f);
    return (1);
  }
  else
  {
    return (0);
  }
}

void dump_worlds YPARAMS0 
{
  int i;
  dbx_world *p;
  emit_stdout("dbx_world\n\n");
  for (i = 0;i < used_worlds;i++)
  {
    p = &world_table[i];
    emit_stdout(p->path_name);
    emit_nl();
  }
  emit_nl();
}

/* converts the name of a module to the name of the corresponding */
/* source file according to the rules of the current system */
/* caution ! this conversion function is machine dependant */
static void module_to_file YPARAMS4(char *,  mn,
                                   char *,  fn)
{
  char *p;
  assertp(mn);
  assertp(fn);
  strcpy(fn, mn);
  fn[8] = 0;
  p = fn;
  while (*p)
    {
      *p = tolower(*p);
      p ++;
    }
  strcat (fn, ".yy");
}

char *find_absolute_name YPARAMS2(char *, module_name)
{
  static char file_name[100];
  char *absolute_name;
  int i;
  assertp(module_name);
  module_to_file(module_name, file_name);
  for (i = 0; i < used_worlds; i++)
  {
    absolute_name = strjoin3(world_table[i].path_name, separator, file_name);
    if (fexists(absolute_name))
      return absolute_name;
     else
      free(absolute_name);
  }
  return NULL;
}

static void add_world YPARAMS2(char *, path_name)
{
  assertp(path_name);
  assert (used_worlds < MAX_WORLDS);
  world_table[used_worlds].path_name = path_name;
  used_worlds++;
}

static void add_worlds YPARAMS2(char *, path_list)
{
  char *p;
  char *path_name;
  assertp(path_list);
  p = strclone(path_list);
  path_name = strtok(p, delimiters);
  while (path_name)
  {
    add_world(strclone(path_name));
    path_name = strtok(NULL, delimiters);
  }
}

static void do_init YPARAMS0
{
  char *p;
  int i;
  char environ_name[50];
  add_world(".");
  p = getenv("YWORLDS");
  if (p)
  {
    add_worlds(p);
  }
  for (i = 0;i < MAX_ENVIRONS;i++)
  {
    sprintf(environ_name, "YWORLDS%d", i);
    p = getenv(environ_name);
    if (p)
    {
      add_worlds(p);
    }
  }
  p = get_cfg_param("YWORLDS");
  if (p)
  {
    add_worlds(p);
  }
  for (i = 0;i < MAX_ENVIRONS;i++)
  {
    sprintf(environ_name, "YWORLDS%d", i);
    p = get_cfg_param(environ_name);
    if (p)
      add_worlds(p);
  }
}

void init_dbx_worl YPARAMS0
{
  static int initialized;
  if (!initialized)
  {
    init_dbx_cfg();
    do_init();
    initialized = 1;
  }
}

void term_dbx_worl YPARAMS0
{
}
