#include <string.h>
#include <io.h>
#include <stdio.h>
#include <rtos.h>
#include <filename.h>

#if defined(__DJGPP__)
#include <unistd.h>
#endif

//----------------------------------------------------------------------
// FileGetPath - copies a file's path (but not file name) to a new location
void FileGetPath( char *filename, char *buffer )
{
    char *p;

    strcpy( buffer, filename );

    /* look for last \, the one preceding the filename */
    if ( (p = strrchr(buffer,'\\' )) == NULL ) {
        if ( buffer[1] == ':' ) p = buffer + 2;
        else p = buffer;
    }
    *p = 0;
}


//----------------------------------------------------------------------
// FileGetName - copies a file's name (discarding path) and ext to new location
void FileGetName( char *filename, char *buffer )
{
    int len;

    /* start by finding length of the path */
    FileGetPath( filename, buffer );
    len = strlen( buffer );
    /* and note that '\' must be skipped */
    if ( filename[ len ] == '\\' ) len++;

    strcpy( buffer, filename + len );
}

//----------------------------------------------------------------------
// FileGetExt - returns pointer to extension within this filename
//            - if no extension, returns pointer to "\0" so still usable string
char *FileGetExt( char *filename )
{
    char *p, *q;
    /* look for \ preceding filename */
    if ( (p = strrchr(filename,'\\' )) == NULL ) p = filename;

    /* p now points to filename, or x: but past all preceding .'s */
    if ( ( q = strchr( p, '.' )) == NULL )
        q = strchr( p, 0 );
    return( q );
}


//----------------------------------------------------------------------
// FileChangeExt - copy apply a new extension to a file name
//               - accepts .ext or ext
void FileChangeExt( const char *filename, const char *newext, char *buffer )
{
    char *q;

    strcpy( buffer, filename );

    /* q points to . or terminating zero */
    q = FileGetExt( buffer );

    if ( *newext != '.' ) *q++ = '.';
    strcpy( q, newext );
}

//----------------------------------------------------------------------
// FileExists - returns 1 if true
int FileExists( const char *filename )
{
    int result ;
    dos_enter();
    result = access( filename, 0 ) == 0 ;
    dos_exit();
    return( result );
}

//----------------------------------------------------------------------
// FileRenameExt - renames file to a given extension in same directory
int FileRenameExt( char *filename, char *newext )
{
    char *buffer;
    int result = 0;

    if ( (buffer = kcalloc( 128 , 1 )) == NULL ) return( 0 );

    do {
        FileChangeExt( filename, newext, buffer );

        if ( FileExists( buffer ))
            if ( unlink( buffer ) ) break;

        result = !rename( filename, buffer );
    } while ( 0 );
    kfree( buffer );
    return( result );
}


