/*
-- This file is  free  software, which  comes  along  with  SmallEiffel. This
-- software  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. You can modify it as you want, provided
-- this header is kept unaltered, and a notification of the changes is added.
-- You  are  allowed  to  redistribute  it and sell it, alone or as a part of 
-- another product.
--          Copyright (C) 1994-98 LORIA - UHP - CRIN - INRIA - FRANCE
--            Dominique COLNET and Suzanne COLLIN - colnet@loria.fr 
--                       http://www.loria.fr/SmallEiffel
--
*/
/*
  This file (basic_directory.c) is automatically included when some external
  "SmallEiffel" feature of class BASIC_DIRECTORY is live.
*/

/*
  The current active entry while scanning a directory :
*/
static struct dirent* se_dir_entry = NULL;

void* se_dir_open(void* path) {
  /* Try to open directory `path'. */
  DIR* dirstream = opendir(((char*) path));

  if (dirstream != NULL) {
    se_dir_entry = readdir((DIR*) dirstream);
  }
  else {
    se_dir_entry = NULL;
  }
  return ((void*) dirstream);
}

void* se_dir_name(void* dirstream) {
  /* Return the name of the current entry. */
  char* entry;

  if (se_dir_entry != NULL) {
    entry = se_dir_entry->d_name;
    return entry;
  }
  else {
    return NULL;
  }
}

void* se_dir_next(void* dirstream_pointer) {
  /* Try to read the next entry. */
  DIR* dirstream = dirstream_pointer;

  if (se_dir_entry != NULL) {
    se_dir_entry = readdir(dirstream);
    if (se_dir_entry == NULL) {
      closedir(dirstream);
      return NULL;
    }
    else {
      return dirstream;
    }
  }
  else {
    return NULL;
  }
}

void* se_dir_gcwd(int unused) {
  static char* buf = NULL;
  static size_t size = 0;
  if (buf == NULL) {
    size = 256;
    buf = (char*)malloc(size);
  }
  if (getcwd(buf,size) != NULL) {
    return buf;
  }
  else {
    free(buf);
    size = size * 2;
    buf = (char*)malloc(size);
    return se_dir_gcwd(0);
  }
}
