/*This code was written by Chilalin for ShadowStorm (telnet://beyond.kyndig.com:5500)
 *This is so useful for all rom muds. It works slightly different from fopen, ect. Instead of the
 if( ( fp = fopen("../data/cmd.dat", "w" ) ) == NULL ) ect. You use 
 if(file_exists("../data/cmd.dat" ) ){ file_open("../data/cmd.dat", "w" );. If any of you
 are having memory problems with fpReserve, this will fix it. Davion. Make sure to add the prototypes!*/
 
FILE *file_open(const char *path, const char *mode)
{
    FILE *fp = NULL;
    char buf[MAX_STRING_LENGTH];

    /* If fpReserve is open, attempt to close it. */
    if (fpReserve)
    {
	/* If fclose returns an error, catch it and abort. */
	if (fclose(fpReserve))
	{
	    /* Error occured closing fpReserve.
	     * If the error is ENOENT (No such file or directory)
	     * and we are on unix, ignore it. This is because closing
	     * a file that was opened on /dev/null nearly always returns
	     * this error, so it's safe to ignore.
	     */
#ifdef unix
	    if( errno != ENOENT )
#endif
	    {
		sprintf(buf, "Error (%d) closing fpReserve:", errno);
		perror(buf);
		abort();
	    }
	}
	fpReserve = NULL;
    }

    if (!(fp = fopen(path,mode)))
    {
	sprintf( buf, "file_open(%s,%s):", path, mode );
	perror(buf);
	abort();
    }

    return fp;
}

void file_close( FILE *fp )
{
    /* Make sure fp is at least not null */
    if( !fp )
	return;

    /* Attempt to close the file. */
    if( fclose(fp) )
    {
	/* Error occured closing the file. Let's print the error message and exit. */
	perror( "file_close():" );
	abort();
    }

    /* Attempt to reopen fpReserve, if it's not already open */
    if (!fpReserve)
    {
	if (!(fpReserve = fopen(NULL_FILE, "r")))
	{
	    /* Error occured opening fpReserve. Let's print the error message and exit. */
	    perror( "Error opening fpReserve:" );
	    abort();
	}
    }

    return;
}

bool file_exists( const char *path )
{
    FILE *fp = NULL;
    char buf[MAX_STRING_LENGTH];

    /* If fpReserve is open, attempt to close it. */
    if (fpReserve)
    {
	/* If fclose returns an error, catch it and abort. */
	if (fclose(fpReserve))
	{
	    /* Error occured closing fpReserve.
	     * If the error is ENOENT (No such file or directory)
	     * and we are on unix, ignore it. This is because closing
	     * a file that was opened on /dev/null nearly always returns
	     * this error, so it's safe to ignore.
	     */
#ifdef unix
	    if( errno != ENOENT )
#endif
	    {
		sprintf(buf, "Error (%d) closing fpReserve:", errno);
		perror(buf);
		abort();
	    }
	}
	fpReserve = NULL;
    }

    if((fp = fopen(path, "r")) != NULL)
    {
	file_close(fp);
	return TRUE;
    }

    return FALSE;
}