//NIET ALLE INCLUDES ZIJN NODIG MAAR EVEN SNEL GEKOPIEERD UIT MIJN SOURCE
#include <math.h>
#include <hw/pci.h>
#include <hw/pci_devices.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <time.h>
#include <stdint.h>
#include <sched.h>
#include <unistd.h>
#include <hw/inout.h>
#include <sys/neutrino.h>
#include <sys/syspage.h>

int aantal_interrupts=0;
int irq_id = 0;
struct sigevent event;

const struct sigevent *ISR(void *arg, int id)
{
      //Clear interrupt FPGA
	out32(0x0000B404,0x00000002);
	
	//Test variabele
      aantal_interrupts++;
	
	//We hoeven niet te kijken of de interrupt voor ons is want dat weten we! 
	//(in de praktijk natuurlijk wel nodig maar PCI busaccess duurt maar .4us)
    	return (&event);
}

int main(int argc, char *argv)
{
	
	if (ThreadCtl( _NTO_TCTL_IO, NULL ) < 0)
	{
		printf( "ThreadCtl returned an error: %s\n", strerror(errno));
		return -1;
	}

  	event.sigev_notify = SIGEV_INTR;

	if ((irq_id = InterruptAttach(0x0B, ISR, NULL, 0, 0)) < 0 )
	{
		printf( "InterruptAttach() for IRQ %d returned an error: %s\n", 0, strerror(errno));
		return EXIT_FAILURE;
	}
	
	//Interrupt aanzetten
	out32(0x0000B404,0x00000002);
	
	//Tja prioriteit maar op 22 en duimen maar!
	setprio(getpgid(0),22);

	// 1 sec laten lopen (100000kHz)
	for(aantal_interrupts=0; aantal_interrupts<100000;)
	{
		//Wacht 100000x op een interrupt en doe verder helemaal niks
		InterruptWait( 0, NULL );
	}

	//That's it!
}