/*  Tilem, TI-Linux Emulator
 *  Copyright (C) 2001 Solignac Julien <x1cygnus@xcalc.org>
 *  Portions copyright (C) 2004 Benjamin Moody <benjamin@ecg.mit.edu>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "../../config.h"

#include<sys/types.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<glib.h>
#ifndef __WIN32__
# include<unistd.h>
# include<pwd.h>
#else
# include<io.h>
#endif

char* ahome(const char *text)
{
 	char *fpath;
#ifdef __WIN32__
	fpath = malloc(4 + strlen(text));
	sprintf(fpath, "../%s", text);
#else
	uid_t uid;
	struct passwd *p;
	
	uid = getuid();
 	if (!(p = getpwuid(uid)))
		g_error("unable to access user info\n");

	fpath = malloc(9 + strlen(p->pw_dir) + strlen(text));

	sprintf(fpath, "%s/.TilEm/%s", p->pw_dir, text);
#endif
	return(fpath);
}


char* ashare(const char *file)
{
	char *fpath;
#ifdef __WIN32__

	fpath = malloc(100);
	snprintf(fpath, 100, "..\\pixmaps\\%s", file);

#else
	uid_t uid;
	struct passwd *p;

	uid = getuid();
	if (!(p = getpwuid(uid)))
		g_error("unable to access user info\n");

	fpath = malloc(100);
	snprintf(fpath, 100, "../pixmaps/%s", file);

	if (access(fpath, R_OK))
		snprintf(fpath, 100, "%s/.TilEm/pixmaps/%s", p->pw_dir, file);

	if (access(fpath, R_OK))
		snprintf(fpath, 100, "%s/tilem/pixmaps/%s", SHARE_DIR, file);
#endif
	if (access(fpath, R_OK) != 0)
		g_error("unable to access '%s'\n", file);

	return(fpath);
}

int check_extension(const char *filename, const char *extn)
{
	const char *s = strrchr(filename, '.');

	if (s==NULL)
		return 0;
	else
		return (0==strcasecmp(s, extn));
}

const char *next_rom_file(GDir *dir)
{
	const char *s;

	do
		s = g_dir_read_name(dir);
	while (s && (!check_extension(s, ".rom"))
	       && (!check_extension(s, ".clc"))
	       && (!check_extension(s, ".bin")));

	return s;
}
