#include <stdint.h>
#include <stm32/stm32f4xx.h>
#include <cmsis/core_cm4.h>
#include "hex-parser.h"
#include <fatfs/ff.h>
#include <stdbool.h>

static volatile unsigned int wait_tick;

static void watchdog_ack(void)
{
	IWDG->KR = 0xAAAA;
}

void sdio_wait_ms(unsigned int ms)
{
	wait_tick = 0;
	while (wait_tick < ms);
}

static FATFS _fs;
#define fs (&_fs)

static void __attribute__((noreturn)) ram_code_exit(bool updated)
{
	(void)updated;

	NVIC_SystemReset();
	while(1);
}

int ram_code_main(void)
{
	FRESULT fres;

	SysTick_Config(168000UL);
	__enable_irq();
	
	fres = f_mount(fs, "0:/", 1);
	if (fres != FR_OK) {
		ram_code_exit(false);
	}

	while(1) {
		__WFI();
	}
	
	return 0;
}

void SysTick_Handler(void)
{
	static uint32_t tick_cnt = 0;
	
	wait_tick++;
	tick_cnt++;
	watchdog_ack();
	if (tick_cnt >= 250) {
		GPIOB->ODR ^= (1<<2);
		tick_cnt = 0;
	}
}
