/*
 * edlib v1.1 Copyright 1989 Edwin Hoogerbeets
 * This code is freely redistributable as long as no charge other than
 * reasonable copying fees are levied for it.
 */
#include "edlib.h"
#include <libraries/dos.h>
#include <exec/memory.h>
#include <errno.h>

#define NULL                0L
#define FIBSIZE             sizeof(struct FileInfoBlock)
extern char                 *malloc();
extern struct FileInfoBlock *AllocMem();
extern struct FileLock      *ParentDir();
extern struct FileLock      *Lock();

char *getcwd(buf,size)
char *buf;
int size;
{
  register struct FileLock *lock;
  register int malloced = 0;

  if ( !buf ) {
    if ( !(buf = malloc(size)) ) {
      errno = ENOMEM;
      return(NULL);
    }
    malloced = 1;
  }

  /* get a lock on the current working directory */
  lock = Lock("",ACCESS_READ);

  buf[0] = '\0';

  if ( !follow(lock,buf,size) ) {

    if ( malloced ) {
      free(buf);
    }

    UnLock(lock);

    return(NULL);
  }

  UnLock(lock);

  return(buf);
}

static int follow(lock,buf,size)
struct FileLock *lock;
char *buf;
int size;
{
  register struct FileInfoBlock *fib;
  register struct FileLock *newlock;

  /* at end of road */
  if ( !lock ) {
    return(1);
  }

  fib = AllocMem(FIBSIZE,MEMF_CLEAR);

  if ( !fib )
    return(0);

  newlock = ParentDir(lock);

  if ( !follow(newlock,buf,size) ) {
    FreeMem(fib,FIBSIZE);
    return(0);
  }

  if ( Examine(lock,fib) ) {
    register char c;

    if ( strlen(buf) + strlen(fib->fib_FileName) + 2 > size ) {
      FreeMem(fib,FIBSIZE);
      return(0);
    }

    if ( newlock && (c = buf[strlen(buf)-1]) != ':' && c != '/' ) {
      strcat(buf,"/");
    }

    strcat(buf,&fib->fib_FileName[0]);

    if ( !newlock) {
      strcat(buf,":");
    }
  }

  FreeMem(fib,FIBSIZE);

  return(1);
}

