/***************************************************************************

  common.c

  Generic functions used in different emulators.
  There's not much for now, but it could grow in the future... ;-)

***************************************************************************/

#include <stdio.h>
#include "common.h"


/***************************************************************************

  Read ROMs into memory.

  Arguments:
  unsigned char *dest - Pointer to the start of the memory region
                        where the ROMs will be loaded.

  const struct RomModule *romp - pointer to an array of Rommodule structures,
                                 as defined in common.h.

  const char *basename - Name of the directory where the files are
                         stored. The function also supports the
						 control sequence %s in file names: for example,
						 if the RomModule gives the name "%s.bar", and
						 the basename is "foo", the file "foo/foo.bar"
						 will be loaded.

***************************************************************************/
int readroms(unsigned char *dest,const struct RomModule *romp,const char *basename)
{
	FILE *f;
	char buf[100];
	char name[100];


	while (romp->name)
	{
		sprintf(buf,romp->name,basename);
		sprintf(name,"%s/%s",basename,buf);

		if ((f = fopen(name,"rb")) == 0)
		{
			printf("Unable to open file %s\n",name);
			return 1;
		}
		if (fread(dest + romp->offset,1,romp->size,f) != romp->size)
		{
			printf("Unable to read file %s\n",name);
			fclose(f);
			return 1;
		}
		fclose(f);

		romp++;
	}

	return 0;
}
