/* Arduino Due Startup Code */

#include <sam3xa.h>

extern void main(void);

void Reset_Handler(void)
{
	/* disable watchdog */
	WDT->WDT_MR = WDT_MR_WDDIS;

	/* point vector table to SRAM if run from SRAM */
	if((uint32_t)vector_table < 0x20000000) {
		*(uint32_t*)0xE000ED08 = (uint32_t)vector_table;
	}

	/* set SCK (slow clock) to external 32.768 kHz crystal */
	SUPC->SUPC_CR = SUPC_CR_KEY(0xA5) | SUPC_CR_XTALSEL;
	while(!(SUPC->SUPC_SR & SUPC_SR_OSCSEL));

	/* enable Main Crystal Oscillator as MAINCK */
//	PMC->CKGR_MOR = 0x0137FF01;

	PMC->CKGR_MOR = CKGR_MOR_MOSCSEL | CKGR_MOR_KEY(0x37) |
		CKGR_MOR_MOSCXTST(255) | CKGR_MOR_MOSCXTEN;
	while(!(PMC->PMC_SR & PMC_SR_MOSCXTS));

	/* set MCK as MAINCK, with prescaler zero */
	PMC->PMC_MCKR = PMC_MCKR_PRES(0) | PMC_MCKR_CSS(1);
	while(!(PMC->PMC_SR & PMC_SR_MCKRDY));

	/* now, the CPU should run at 12 MHz;
	   MAINF in CKGR_MCFR should read ca. 5859;
	   (lower 2 bytes at 0x400E0624 should read ca. 0x16E3) */

	/* blink TX led */
	PIOA->PIO_PER  = PIO_P21;		/* PIO Enable */
	PIOA->PIO_OER  = PIO_P21;		/* Output Enable */
	PIOA->PIO_PUER = PIO_P21;		/* Pullup Enable */
	while(1) {
		PIOA->PIO_SODR = PIO_P21;
		for(volatile int i = 0; i < 1000000; i++);
		PIOA->PIO_CODR = PIO_P21;
		for(volatile int i = 0; i < 1000000; i++);
	}
}
