#include <libgen.h>
#include <stdio.h>
#include <string.h>
#include "parser.h"
char *base_directory = NULL;
char base_directory_storage[256];
FILE *open_file(char *name) {
char temppath[256];
char *environ = NULL;
char paths[4096];
char *path;
FILE *file = NULL;
int len = 0;
int i;
if (name[0] == '/') {
return fopen(name, "r");
}
file = fopen(name, "r");
if (file != NULL) {
return file;
}
if (base_directory != NULL) {
strcpy(temppath, base_directory);
strcat(temppath, "/");
strcat(temppath, name);
file = fopen(temppath, "r");
if (file != NULL) {
return file;
}
}
environ = getenv("JOYMAP_PATH");
if (environ == NULL) {
return fopen(name, "r");
}
strcpy(paths, environ);
len = strlen(paths);
for (i=0; i<len; i++) {
if (paths[i] == ':') {
paths[i] = '\0';
}
}
path = paths;
i = 0;
while (i<len) {
strcpy(temppath, path);
strcat(temppath, "/");
strcat(temppath, name);
file = fopen(temppath, "r");
if (file != NULL) {
return file;
}
i += strlen(path) + 1;
path = paths + i;
}
return fopen(name, "r");
}
void set_base_directory(char *filename) {
char temppath[256];
char *dir = NULL;
if (filename == NULL) {
base_directory = NULL;
return;
}
strcpy(temppath, filename);
dir = dirname(temppath);
strcpy(base_directory_storage, dir);
base_directory = base_directory_storage;
}