#ifndef _SPICon_H_
#define _SPICon_H_


void SPI4init(void);
void SPI2init (void);

#define SPI2_RBF SPI2STATbits.SPIRBF   //Recieve buffer full flag
#define SPI2_CHIPSELECT LATFbits.LATF3 //Chip select on our board
#define SPI2_CHIPSELECT_PIN TRISFbits.TRISF3 

void SPI4init(void)
{
    AD1PCFG = 0xFFFF;          //set analog pins to digital
    DDPCONbits.JTAGEN = 0;
    
    IEC1bits.SPI4EIE = 0;  //disable interrupts for SPI4 before initializing
    IEC1bits.SPI4RXIE = 0;
    IEC1bits.SPI4TXIE = 0;
    
    SPI4CONbits.ON = 0; //turn off to apply settings
    
    SPI4CONbits.ENHBUF = 0; //not turning on enhanced buffer mode
    
    IFS1bits.SPI4EIF = 0;   //clear the interrupt flags for SPI4
    IFS1bits.SPI4RXIF = 0;
    IFS1bits.SPI4TXIF = 0;
    IPC8bits.SPI4IP = 3;    //set interrupt priority to 1 and subpriority to 3 (not sure about this, just following spec sheet example)
    IPC8bits.SPI4IS = 1;
    IEC1bits.SPI4EIE = 1;   //enable the interrupts for SPI4
    IEC1bits.SPI4RXIE = 1;
    IEC1bits.SPI4TXIE = 1;
    
    SPI4STATbits.SPIROV = 0; //clear overflow bit
    
    SPI4CONbits.MSTEN = 0; //slave mode
    
    SPI4CONbits.CKP = 0; //have double checked the CKP and CKE settings with logic analyzer output
    SPI4CONbits.CKE = 0;
    SPI4CONbits.SMP = 0; //SMP = 0 for slave
    
    SPI4CONbits.SSEN = 1; //enable slave select bit (not sure if this is necessary)
    
    SPI4CONbits.ON = 1; //turn on now that settings are finished
    
    int data = 0;
    data = SPI4BUF; //clear buffer
}

void SPI2init (void){
    // Turn off the SPI to change registers 
    SPI2CONbits.ON = 0;
    // Set up SPI4_BRG
    SPI4BRG = 15;
    // Disable the JTAG Modes 
    DDPCONbits.JTAGEN = 0;
    //Disable the analog pins 
    AD1PCFG = 0xFFFF;
    // Set up the SPI to mode 0
    SPI2CONbits.CKE = 0;
    SPI2CONbits.CKP = 0;
    //Set to master
    SPI2CONbits.MSTEN = 1;
    // Set sampling to the middle of the output
    SPI2CONbits.SMP = 0;
    // clear overflow bit
    SPI2STATbits.SPIROV = 0;
    // Set the chip select pin to an output 
    SPI2_CHIPSELECT_PIN = 0;
    // Set the chip select high (low when sending/receiving)
    SPI2_CHIPSELECT = 1;
    // Turn on the SPI 
    SPI2CONbits.ON = 1;
}

#endif