#include "data_path.h"
#include <stdio.h>
#ifdef WIN32
#include <io.h>
#else
#include <sys/stat.h>
#include <unistd.h>
#endif
#include <fcntl.h>

using namespace std;


// data files, for read only
FILE * data_path::fopen(std::string filename, const char * mode)
{

	for(unsigned int i=0; i < path.size(); i++)
	{
		std::string s = path[i] + "/" + filename;
		FILE * fp = ::fopen(s.c_str(), mode);

		if(fp != 0)
			return fp;
	}
	// no luck... return null
	return 0;
}

//  fill the file stats structure 
//  useful to get the file size and stuff
int data_path::fstat(std::string filename, 
#ifdef WIN32
		     struct _stat 
#else
		     struct stat
#endif
		     * stat)
{
	for(unsigned int i=0; i < path.size(); i++)
	{
		std::string s = path[i] + "/" + filename;
#ifdef WIN32
		int fh = ::_open(s.c_str(), _O_RDONLY);
#else
		int fh = ::open(s.c_str(), O_RDONLY);
#endif
		if(fh >= 0)
        {
#ifdef WIN32
            int result = ::_fstat( fh, stat );
#else
	    int result = ::fstat (fh,stat);
#endif
            if( result != 0 )
            {
                fprintf( stderr, "An fstat error occurred.\n" );
                return 0;
            }
#ifdef WIN32
            ::_close( fh );
#else
	    ::close (fh);
#endif
			return 1;
    	}
    }
    // no luck...
    return 0;
}
