/*
 *	getcwd
 *
 *	Amiga (Manx) Library
 *
 *	$Id: getcwd.c,v 1.2 90/01/16 10:25:37 crash Exp Locker: crash $
 */

#ifndef lint
static char RCSid[] = "$Id: getcwd.c,v 1.2 90/01/16 10:25:37 crash Exp Locker: crash $";
#endif /* lint */

#include <libraries/dos.h>
#include <exec/memory.h>

#ifdef MCH_AMIGA
# include <functions.h>		/* Manx */
#else
# include <proto/exec.h>	/* Lattice */
#endif

#ifdef TEST
# include <stdio.h>
#endif

#ifndef NULL
# define NULL 0L
#endif

char *malloc();

/*--------------------------------------------------------------*/
/*    GetCurrentPath: get full path of the current directory    */
/*--------------------------------------------------------------*/

static void GetCurrentPath( path )
register char *path;
{
	static char s1[ 512 ];
	static struct FileInfoBlock fib;

	char *name;
	register struct FileLock *locka, *lockb;

	locka = Lock("", ACCESS_READ );
	*path = s1[0] = '\0';
	while ( locka != NULL ) {
	    Examine( locka, &fib );
	    name = fib.fib_FileName;
	    if ( *name == '\0' )
			strcpy( path, "RAM" );		/* Patch for Ram disk bug */
	    else
			strcpy( path, name );
	    lockb = ParentDir( locka );
	    UnLock( locka );
	    
	    if ( lockb == NULL )
	        strcat( path, ":");
	    else
			if ( s1[0] != '\0' )
				strcat( path, "/");
	    strcat( path, s1 );
	    strcpy( s1, path );
	    locka = lockb;
	}
}

/*--------------------------------------------------------------*/
/*	getcwd: return the path name of the current directory		*/
/*--------------------------------------------------------------*/

char *getcwd( path, size )
char *path;
int size;
{
	if (!path) {
		if ( !(path = malloc(512)) ) {
#ifdef TEST
			fprintf(stderr,
				"getcwd:  malloc failed to get %d bytes\n", BUFSIZ);
#endif
			return NULL;
		}
	}
	GetCurrentPath( path );
	return path;
}

#ifdef TEST
main()
{
	fprintf( stderr, "%s\n", getcwd( NULL, 0 ));
}
#endif
