/* This function will take a path name string and FULLY expand it.
   It can be used prior to comparing path names to ensure that such
   paths as ".\file" will match "file". */

/* Copyright 1986 John Navas II, All Rights Reserved.
EXP_PATH is made available for personal, non-commercial use only.  You
are granted a limited license to use EXP_PATH, and to copy it and
distribute it, provided that no fee is charged for such copying and
distribution, and that it is ONLY distributed in its original,
unmodified state. */

/* Language: Microsoft C Version 3.00 */

#include <ctype.h>
#include <direct.h>
#include <dos.h>
#include <stdio.h>
#include <string.h>

char *exp_path( s )						/* EXPAND PATH NAME */
char *s;								/* path name */
{
	union REGS reg;
	register char *p, *q, *r;
	char cdr;									/* current drive */
	char drv;									/* drive number */
	char cwd[ 68 ];								/* current directory */
	char sav[ 13 ];								/* save file name */

	s[ strspn( s, "!#$%&'()*-./0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\
[\\]^_`abcdefghijklmnopqrstuvwxyz{}~" ) ] = 0;	/* force delimiter */

	if ( ( drv = ( *( q = s ) && *( q + 1 ) == ':' ) ?
			( toupper( *q ) - 'A' ) : -1 ) >= 0 ) {
		if ( ( cdr = (char) bdos( 0x19, 0, 0 ) ) != drv &&	/* get curr drv */
				(char) bdos( 0x0E, (unsigned int) drv, 0 ) <= drv )	/* swch */
			return s;							/* can't switch */
		q += 2;									/* drive number */
		}
	else cdr = -1;
	r = p = q;									/* path pointer */

	getcwd( cwd, 67 );							/* current directory */

	if ( ( *p == '\\' || *p == '/' ) && ! *( p + 1 ) )
		reg.h.cl = 0x80;						/* root directory */
	else {
		while ( ( q = strpbrk( p, "\\/" ) ) != NULL )
			p = q + 1;							/* find file/dir */
		if ( *p == '.' )
			reg.h.cl = 0x40;					/* special . or .. dir */
		else {
			reg.x.ax = 0x4300;					/* get file attributes */
			reg.x.dx = (unsigned int) s;
			intdos( &reg, &reg );
			reg.h.cl &= ( ! reg.x.cflag ) ?
				0x10 :		  					/* subdirectory bit only */
				0;			  					/* not found */
			}
		}
	if ( reg.h.cl ) p = strchr( p, 0 );			/* no file name if dir */

	strncpy( sav, p, 12 );						/* save file name */
	sav[ 12 ] = 0;								/* for safety */

	if ( p > r &&								/* path override */
			( *r != '.' || *( r + 1 ) || strlen( cwd ) > 3 ) ) {
		if ( *( q = ( p - 1 ) ) == '\\' || *q == '/' )
			*( ( p - 1 ) == r ? p : q ) = 0;	/* terminate path */
		if ( ! chdir( s ) ) {					/* try to switch directory */
			getcwd( s, 67 );					/* get full name */
			chdir( cwd );						/* go back */
			}
		}
	else strcpy( s, cwd );						/* get name no switch */

	if ( ( p = strchr( s, 0 ) ) != ( s + 3 ) )	/* pointer */
		++p;
	if ( *strcpy( p, sav ) )					/* restore file name */
		*( p - 1 ) = cwd[ 2 ];					/* delimiter if file */

	if ( cdr != drv )	  						/* if necessary */
		bdos( 0x0E, (unsigned int) cdr, 0 );	/* reselect current */

	return s;
	}
