/*
 * FtpSvr
 * Copyright(C) 1997-1999 Eiichiro Ito
*/
#define	STRICT
#include	<windows.h>
#include	<tchar.h>
#include	"tools.h"

void
chop_quote( LPTSTR dst )
{
	TCHAR	c ;
	BOOL	f_first = TRUE ;
	LPTSTR	src = dst, last_quote = 0 ;

	while ( c = *src++ ) {
		if ( c == TEXT('"') ) {
			last_quote = dst ;
			if ( f_first ) {
				f_first = FALSE ;
				continue ;
			}
		} else {
			f_first = FALSE ;
			if ( c != TEXT(' ') ) {
				last_quote = 0 ;
			}
		}
		*dst++ = c ;
	}
	*dst = 0 ;
	if ( last_quote ) {
		*last_quote = 0 ;
	}
}

void
slash2backslash( LPTSTR str )
{
	LPTSTR	ptr ;

	/* '/'を'\'に変換する */
	while ( ptr = _tcschr( str, TEXT('/') ) ) {
		*ptr = TEXT('\\') ;
	}
}

void
catdir( LPTSTR body, LPCTSTR adddir, LPTSTR pPrevDir )
{
	DWORD	len ;
	LPTSTR	ptr ;

	slash2backslash( body ) ;
	if ( pPrevDir ) {
		_tcscpy( pPrevDir, TEXT("..") ) ;
	}
	while ( *adddir ) {
		if ( _tcschr( TEXT("/\\"), *adddir ) ) {
			/* 先頭が"/"か"\"の場合は読み飛ばす */
			adddir ++ ;
			continue ;
		}
		if ( adddir[0] == TEXT('.') && adddir[1] == TEXT('.') ) {
			ptr = _tcsrchr( body, TEXT('\\') ) ;
			if ( ptr && pPrevDir ) {
				_tcscpy( pPrevDir, ptr + 1 ) ;
			}
			if ( ptr && ptr != body ) {
				*ptr = 0 ;
			} else {
				_tcscpy( body, TEXT("\\") ) ;
			}
			adddir += 2 ;
		} else if ( adddir[0] == TEXT('.') && (adddir[1] == TEXT('\\') || adddir[1] == TEXT('\0')) ) {
			adddir ++ ;
		} else {
			break ;
		}
	}
	if ( !*adddir ) {
		return ;
	}
	len = _tcslen( body ) ;
	if ( !len || body[ len - 1 ] != TEXT('\\') ) {
		body[ len ++ ] = TEXT('\\') ;
	}
	_tcscpy( &body[ len ], adddir ) ;
	slash2backslash( body ) ;
}

void
rel2absdir( LPCTSTR curDir, LPTSTR dst, DWORD chDst, LPCTSTR src )
{
	DWORD	len ;

	if ( !_tcschr( TEXT("/\\"), *src ) ) {
		_tcscpy( dst, curDir ) ;
		catdir( dst, src, NULL ) ;
	} else {
		while ( src[1] && _tcschr( TEXT("/\\"), src[1] ) ) {
			src ++ ;
		}
		_tcscpy( dst, src ) ;
	}
	len = _tcslen( dst ) ;
	slash2backslash( dst ) ;
	if ( len && dst[ len - 1 ] == TEXT('\\') ) {
		dst[ len - 1 ] = 0 ;
	}
}

BOOL
is_dir( LPCTSTR path )
{
	DWORD	attr = GetFileAttributes( path ) ;
	if ( attr == 0xFFFFFFFF ) {
		return FALSE ;
	} else if ( attr & FILE_ATTRIBUTE_DIRECTORY ) {
		return TRUE ;
	}
	return FALSE ;
}

BOOL
is_file( LPCTSTR path )
{
	DWORD	attr = GetFileAttributes( path ) ;
	if ( attr == 0xFFFFFFFF ) {
		return FALSE ;
	}
	return TRUE ;
}
