/*
************************************************************************
*
*   CurrDir.c - get current directory
*
*   Copyright (c) 1994-97
*
*   ETH Zuerich
*   Institut fuer Molekularbiologie und Biophysik
*   ETH-Hoenggerberg
*   CH-8093 Zuerich
*
*   SPECTROSPIN AG
*   Industriestr. 26
*   CH-8117 Faellanden
*
*   All Rights Reserved
*
*   Date of last modification : 97/03/17
*   Pathname of SCCS file     : /local/home/kor/molmol/src/os/SCCS/s.CurrDir.c
*   SCCS identification       : 1.4
*
************************************************************************
*/

#include <curr_dir.h>

#include <stdlib.h>
#ifdef WIN32
#include <direct.h>
#include <string.h>
#else
#include <unistd.h>
#include <errno.h>
#endif

static char *CurrDir = NULL;

char *
CurrDirGet(void)
{
#ifdef WIN32
  int len, i;
#else
  int size = 10;
#endif

  if (CurrDir != NULL)
    return CurrDir;

#ifdef WIN32
  CurrDir = _getcwd(NULL, 0);
  if (CurrDir != NULL) {
    len = strlen(CurrDir);
    for (i = 0; i < len; i++)
      if (CurrDir[i] == '\\')
        CurrDir[i] = '/';
    return CurrDir;
  }
#else
  CurrDir = malloc(size);
  for (;;) {
    if (getcwd(CurrDir, size) != NULL)
      return CurrDir;
    if (errno != ERANGE)
      break;
    size *= 2;
    CurrDir = realloc(CurrDir, size);
  }
#endif

  /* cannot get current directory, return root directory */
  CurrDir = realloc(CurrDir, 2);
  CurrDir[0] = '/';
  CurrDir[1] = '\0';

  return CurrDir;
}
