/*
 * Copyright (C) 2007-2008 Arnaud Ysmal <wiidevel@stacktic.org>
 *
 * filefunctions.c (TransferMii)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */
 
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include "tmii.h"

extern bool wm_read;

/* Reads mii from miifile */
bool fileRead(char *miifile)
{
	FILE *fd;
	struct stat filestat;

	if (stat(miifile, &filestat)) {
		fprintf(stderr, "%s : file reading error\n", miifile);
		return FALSE;
	}
	if (filestat.st_size != MII_SIZE) {
		fprintf(stderr, "%s : incorrect mii file\n", miifile);
		return FALSE;
	}
	
	printf("Reading mii from file %s...\n", miifile);
        if ((fd = fopen(miifile, "r"))) {
		if (fread(mii, MII_SIZE, 1, fd) != 1) {
			fprintf(stderr, "Can't read %s\n", miifile);
			fclose(fd);
			return FALSE;
		}
		fclose(fd);
	} else {
                fprintf(stderr, "Can't open %s\n", miifile);
		return FALSE;
	}
	return TRUE;
}

/* Writes mii to miifile */
/* Slot 0    : writes mii array */
/* Slot 1-10 : writes corresponding mii from miiblock */
bool fileWrite(char *miifile, int slot)
{
        FILE *fd;
	unsigned char *pmii;

	if (slot < 0 || slot > 10) {
		fprintf(stderr,
			"incorrect slot, must be between 0 and 10\n");
		return FALSE;
	}

	if (slot) {
		if (!wm_read && !wiimoteRead())
			return FALSE;
		pmii = miiAddress(slot);
	} else {
		pmii = mii;
	}

	if (!*(int*)pmii) {
		fprintf(stderr, "mii or slot empty\n");
		return FALSE;
	}

	printf("Writing file %s...\n", miifile);
        if ((fd = fopen(miifile, "w"))) {
		if (fwrite(pmii, MII_SIZE, 1, fd) != 1) {
			fprintf(stderr, "Can't write %s\n", miifile);
			fclose(fd);
			return FALSE;
		}
		fclose(fd);
	} else {
                fprintf(stderr, "Can't open %s\n", miifile);
                return FALSE;
        }
	return TRUE;
}

/* Displays information on miifile */
bool fileInfo(char *miifile)
{
	char name[MII_NAME_LENGTH_CHAR+1];
	
	if (!fileRead(miifile))
		return FALSE;
	getMiiNameAscii(name, 0);
      	printf("Mii's name : %s\t", name);
	getMiiCreatorAscii(name, 0);
	printf("Creator : %s\t", name);	
	printf("Sex : %s\n", (getMiiSex(0)=='F')?"Female":"Male");
	return TRUE;
}
