
#include <avr/boot.h>
#include <inttypes.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>

#include "mmc.h"
#include "fat.h"
#include "megavar.h"

void (*app_start)(void) = 0x0000;


unsigned char uploadeeprom(char *filename)
{
	unsigned char Buffer[512];
	unsigned int tmp;
	unsigned int Clustervar=0;
	unsigned char Dir_Attrib = 0;
	unsigned long Size = 0;
	uint16_t filesector, j;
	uint8_t i;
	uint16_t *lpword;
	uint16_t adr;
	uint8_t gBuffer[SPM_PAGESIZE];
	if (mmc_init() !=0) return 1;
	fat_init();
	if (fat_search_file(filename,&Clustervar,&Size,&Dir_Attrib,Buffer) != 1) return 2;
	for (filesector = 0; filesector < SECTOR_FOR_READ ; filesector++)
	{
		lpword = (uint16_t*) Buffer;
		fat_read_file (Clustervar,Buffer,filesector);
		for (i=0; i<(512 / SPM_PAGESIZE); i++)
		{
			adr = (filesector * 512) + i * SPM_PAGESIZE;
			boot_page_erase(adr);
			while (boot_rww_busy())
				boot_rww_enable();
			for (j=0; j<SPM_PAGESIZE; j+=2)
				boot_page_fill(adr + j, *lpword++);
			boot_page_write(adr);
			while (boot_rww_busy())
				boot_rww_enable();
		}
	}
return 0;
}



int main(void)
{
char filename[]="mcc1.txt";
uploadeeprom(filename);
app_start();
}
