/*
 *	lib.c
 *
 *	Amiga Library
 *
 *	$Id: lib.c,v 1.2 90/01/16 10:26:25 crash Exp Locker: crash $
 */

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

#include <stdio.h>
#include "host.h"

#ifndef _U
# include <ctype.h>
#endif /* _U */

#ifndef EACCES
# include <errno.h>
#endif /* EACCES */

#ifndef NULL
# define NULL 0L
#endif

char *index();
char *rindex();

MKDIR( path )
char * path;
{
	char * cp = path;

	if ( *cp == '\0' )
		return( 0 );

	/* see if we need to make any intermediate directories */
	while ( ( cp = index( cp, '/' ) ) != (char *) NULL ) {
		*cp = '\0';
		mkdir( path );
		*cp = '/';
		cp++;
	}
	/* make last dir */
	return( mkdir( path ) );
}

CHDIR( path )
char * path;
{
	char * cp = path;

	if ( *cp == '\0' )
		return( 0 );
	MKDIR( path );
	/* change to last directory */
	return( chdir( path ) );
}

FILE *FOPEN( name, mode, ftype )
char *name;
char *mode;
char ftype;
{
	char *last;
	FILE *results;

	/* are we opening for write or append */

	FILEMODE( ftype );
	results = fopen( name, mode );

	if ( results != (FILE *) NULL || *mode == 'r' )
		return( results );

	/* are we opening in sub-directory */
	last = rindex( name, '/' );

	/* let's just verify that all sub-dir's exist */
	if ( last != (char *) NULL ) {
		*last = '\0';
		MKDIR( name );
		*last = '/';
	}
	/* now try open again */
	return( fopen( name, mode ));
}

int CREAT( name, mode, ftyp )
char *name;
int mode;
char ftyp;
{
	char *last;
	int results;

	/* are we opening for write or append */
	FILEMODE( ftyp );
	results = creat( name, mode );

	if ( results != -1 )
		return( results );

	/* are we opening in sub-directory */
	last = rindex( name, '/' );

	/* lets just verify that all sub-dir's exist */
	if ( last != (char *) NULL ) {
		*last = '\0';
		MKDIR( name );
		*last = '/';
	}
	/* now try open again */
	return( creat( name, mode ) );
}

extern FILE *logfile;
extern int debuglevel;
extern int remote;

#define MASTER 1

/*
 *	getargs
 *		breaks up the argument 'line' into fields.  Uses
 *		whitespace as the field delimiters.
 */
int getargs( line, flds )
char *line;
char **flds;
{
	int i = 0;
	char *s;

	while ( *line && (*line != '\n')) {
		if ( isspace(*line) ) {
			line++;
			continue;
		}
		*flds++ = line;
		i++;
		while (!isspace(*line) && *line)
			line++;
		if (isspace(*line))
			*line++ = '\0';
	}
	return(i);
}


/*
 *	prt
 *		prints the argument 'str' using expanded notation, i.e.
 *		CTRL-A prints as ^A, etc.
 */
char *prt(str, len)
register char *str;
register int len;
{
	static char buff[ 512 ];
	register char *p = buff;
	register int i, ch;

	for (i=0; i++ < len && p < buff+500; str++) {
		if ((ch = *str & 0xFF) > 0x7E) {
			*p++ = '~';
			ch &= 0x7F;
		}
		if (ch < 0x20) {
			*p++ = '^';
			*p++ = (char) ch + '@';
		} else if (ch == 0x7F)
			*p++ = 'x';
		else
			*p++ = (char) ch;
	}
	*p = '\0';
	return( buff );
}
