/*
 * This file is part of the GNO libc replacement written by
 * Devin Reade <gdr@eddore.myrias.com>.
 *
 * $Id: getcwd.c,v 1.1 1996/11/28 06:16:32 gdr Exp $
 */

#include <types.h>
#include <gsos.h>
#include <orca.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#ifdef __GNO__
#include <unistd.h>
#endif

#define CWD "0:"      /* Gsh for GNO v2.0.4 doesn't set prefix 8 ... */

extern int _mapErr(int);

char *
getcwd(char *buf, size_t size)
{
	GSString255 inputPath;
  ResultBuf255 outputPath;
  ExpandPathRecGS rec = { 2, &inputPath, &outputPath, 0 };
  int i;
  size_t length;
	char *result;

	outputPath.bufSize = 255;
  inputPath.length = strlen(CWD);
  strncpy(inputPath.text, CWD, inputPath.length);

  ExpandPathGS (&rec);
  if ((i = toolerror()) != 0) {
	   errno = _mapErr(i);
     return NULL;
  }

  length = outputPath.bufString.length + 1;
  if (buf == NULL) {

	   /* user provided no buffer */
	   if (size <= 0) {
	      /* allocate buffer as large as necessary */
	      if ((result = malloc(length)) == NULL) {
	         return NULL;
        }
     } else if (size < length) {
	      /* specified size not large enough; error */
        errno = ERANGE;
        return NULL;
     } else {
	      /* allocate buffer of requested size */
        if ((result = malloc(size)) == NULL) {
	         return NULL;
        }
     }
	} else {

	   /* user provided a buffer */
     if (size < length) {
	      errno = ERANGE;
	      return NULL;
     }
	   result = buf;
  }
  strncpy (result, outputPath.bufString.text, length-1);
  result[length-1] = '\0';

  return result;
}

#ifdef TEST_CASE

#include <stdio.h>
#include <assert.h>

#define BUFFERSIZE  1024
#define BUFFERSIZE2 15

int main (int argc, char **argv) {
	static char buffer[BUFFERSIZE];
	static char buffer2[BUFFERSIZE2];

	char *p, *buf;
  int i, len;

  for (i=0; i<3; i++) {
  	switch (i) {
     case 0:  buf = NULL;    len = 0;           break; /* should pass */
     case 1:  buf = buffer;  len = BUFFERSIZE;  break; /* should pass */
     case 2:  buf = buffer2; len = BUFFERSIZE2; break; /* should fail */
     default: assert(0);
     }
  	p = getcwd(buf, len);
  	if (p == NULL) {
	   	perror("getcwd failed");
  	} else {
  		printf("cwd is \"%s\"\n", p);
  	}
  }   
  return 0;                    
}

#endif /* TEST_CASE */
