#include <io.h>

/** quick check for file using findfirst */
static int AP_FileExists(const char * file)
{
        struct _finddata_t myFinddata;
        long hFile;

        int ok = ((hFile = _findfirst( file, &myFinddata )) != -1L);   
        if (ok) _findclose(hFile);
        return ((ok) && (!(myFinddata.attrib&_A_SUBDIR))) ;    
}

/** quick check for directory using findfirst */
static int AP_DirExists(const char * dir)
{
        if (!dir) return 0; // watch it, it's a pointer
        struct _finddata_t myFinddata;
        long hFile;     
       
        // may be called with trailing '\\'
        int length = strlen(dir);
        if (dir[length-1]=='\\')
        {
                char* buf = new char [length+1];
                strcpy(buf,dir); buf[length-1]=0;
                int ok = ( (hFile = _findfirst( buf, &myFinddata )) != -1L );      
                _findclose(hFile);
                delete [] buf;
                return (ok && (myFinddata.attrib&_A_SUBDIR));  
        }
        else
        {
                int ok = ( (hFile = _findfirst( dir, &myFinddata )) != -1L );   
                if (ok) _findclose(hFile);
                return (ok && (myFinddata.attrib&_A_SUBDIR));   
        }
}

/** check for drive with drive mask function */
inline bool AP_DriveExists(const char* path)
{
        if (path==0) return false;     
        if (path[0]==0) return false;
        if (strlen(path)<2) return false;       
        if (path[1]!=':') return true;    
       
        unsigned long uDriveMask = _getdrives();
        int index = tolower(path[0])-'a';
        return (uDriveMask & (1 << index))!=0
}

/** make sure path exists (recursive).
  * must have a ''\\' behind the last entry */

static bool AP_MakePath(const char *path)
{
        if (!path) return 0; // watch it, it's a pointer
        char dir[1024];
        strcpy(dir,path);
        char *p = strrchr(dir,'\\');
        if (p!=NULL)
        {
                *p=0;
                if (strlen(dir)<2) return true;  
                if (!AP_DirExists(dir))
                {
                        AP_MakePath(dir); // create previous, if neccesary
                        _mkdir(dir);      // create this
                }       
        }
        return true;
}

/** remove path recusively.
  * will remove only empty directories */

static bool AP_RemovePath(const char *path)
{
        if (!path) return 0; // watch it, it's a pointer
        char tmp[1024];
        strcpy(tmp,path);
        char *p = strrchr(tmp,'\\');
        if (p!=NULL)
        {
                *p=0;
                if (strlen(tmp)>3)
                {
                        AP_RemovePath(tmp);
                        if (_rmdir(tmp)!=0)
                                return true;       
                }
        }
        return true;
}