#ifndef TIMER_H
#define TIMER_H

#include "config.h"

/* Setup a 16-bit timer to overflow at the specified frequency
     timer = 1-9
     freq = Hz, or 0 to disable the timer.
     ie = 1 to enable interrupt, 0 to disable
*/
int timer_setup_16bit(int timer, uint32_t freq, int ie);

#define TISR_HANDLER(x) \
	__attribute__((__interrupt__,auto_psv)) _T##x##Interrupt(void)

/* Clear TxIF corresponding to a timer */
#define timer_clear_txif(timer) do {			\
		if ((timer) == 1) IFS0bits.T1IF = 0;	\
		if ((timer) == 2) IFS0bits.T2IF = 0;	\
		if ((timer) == 3) IFS0bits.T3IF = 0;	\
		if ((timer) == 4) IFS1bits.T4IF = 0;	\
		if ((timer) == 5) IFS1bits.T5IF = 0;	\
		if ((timer) == 6) IFS2bits.T6IF = 0;	\
		if ((timer) == 7) IFS3bits.T7IF = 0;	\
		if ((timer) == 8) IFS3bits.T8IF = 0;	\
		if ((timer) == 9) IFS3bits.T9IF = 0;	\
	} while(0)


/* Set timer interrupt priority, 1-7.  Default is 4, 7 is highest */
#define timer_set_priority(timer, pri) do { \
		if ((timer) == 1) IPC0bits.T1IP = (pri);	\
		if ((timer) == 2) IPC1bits.T2IP = (pri);	\
		if ((timer) == 3) IPC2bits.T3IP = (pri);	\
		if ((timer) == 4) IPC6bits.T4IP = (pri);	\
		if ((timer) == 5) IPC7bits.T5IP = (pri);	\
		if ((timer) == 6) IPC11bits.T6IP = (pri);	\
		if ((timer) == 7) IPC12bits.T7IP = (pri);	\
		if ((timer) == 8) IPC12bits.T8IP = (pri);	\
		if ((timer) == 9) IPC13bits.T9IP = (pri);	\
	} while(0)

/* sleep for between "ms" and "ms+1" milliseconds */
void msleep(int ms);

#endif
