/// @file pic24.c
/// @authors k. Headley
/// @date 05 dec 2018
/// PIC24 peripheral
/// @sa doxygen-examples.c for more examples of Doxygen markup
/// Terms of use
/// Copyright Information
/// Copyright 2002-2017 MBARI
/// Monterey Bay Aquarium Research Institute, all rights reserved.
/// Terms of Use
/// This program is free software; you can redistribute it and/or modify
/// it under the terms of the GNU General Public License as published by
/// the Free Software Foundation; either version 3 of the License, or
/// (at your option) any later version. You can access the GPLv3 license at
/// http:/// www.gnu.org/licenses/gpl-3.0.html
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
/// GNU General Public License for more details
/// (http:/// www.gnu.org/licenses/gpl-3.0.html)
/// MBARI provides the documentation and software code "as is", with no warranty,
/// express or implied, as to the software, title, non-infringement of third party
/// rights, merchantability, or fitness for any particular purpose, the accuracy of
/// the code, or the performance or results which you may obtain from its use. You
/// assume the entire risk associated with use of the code, and you agree to be
/// responsible for the entire cost of repair or servicing of the program with
/// which you are using the code.
/// In no event shall MBARI be liable for any damages, whether general, special,
/// incidental or consequential damages, arising out of your use of the software,
/// including, but not limited to, the loss or corruption of your data or damages
/// of any kind resulting from use of the software, any prohibited use, or your
/// inability to use the software. You agree to defend, indemnify and hold harmless
/// MBARI and its officers, directors, and employees against any claim, loss,
/// liability or expense, including attorneys' fees, resulting from loss of or
/// damage to property or the injury to or death of any person arising out of the
/// use of the software.
/// The MBARI software is provided without obligation on the part of the
/// Monterey Bay Aquarium Research Institute to assist in its use, correction,
/// modification, or enhancement.
/// MBARI assumes no responsibility or liability for any third party and/or
/// commercial software required for the database or applications. Licensee agrees
/// to obtain and maintain valid licenses for any additional third party software
/// required.

/// Headers  
#include "pic24.h"

/// Macros

#ifndef USE_MCC_CHIP_CONFIG
/// JTAG                     : off
/// Code Protect             : off
/// Write Protect            : off
/// Clip-on Emulation mode   : off
/// Watchdog Timer           : off
/// ICD pins                 : 17 & 18 (set#2)
/// _CONFIG1(JTAGEN_OFF & GCP_OFF & GWRP_OFF & COE_OFF & FWDTEN_OFF & ICS_PGx2)
/// Watchdog Timer Postscaler (1:32,768)
#pragma config WDTPS = PS32768
/// WDT Prescaler (Prescaler ratio of 1:128)
#pragma config FWPSA = PR128
/// Watchdog Timer Window (Standard Watchdog Timer is enabled,(Windowed-mode is disabled))
#pragma config WINDIS = OFF
/// Watchdog Timer Enable (Watchdog Timer is disabled)
#pragma config FWDTEN = OFF
/// Comm Channel Select (Emulator functions are shared with PGEC2/PGED2)
#pragma config ICS = PGD2 //PGx2
/// Background Debug->Device resets into Operational mode
//#pragma config BKBUG = OFF
/// General Code Segment Write Protect (Writes to program memory are allowed)
#pragma config GWRP = OFF
/// General Code Segment Code Protect (Code protection is disabled)
//#pragma config GCP = OFF
/// JTAG Port Enable (JTAG port is disabled)
#pragma config JTAGEN = OFF
/// Clock switching and monitor  : off
/// Use OSCO pin for RC15 I/O    : off
/// Oscillator type              : XT oscillator
/// Clock source                 : Primary oscillator
/// _CONFIG2(FCKSM_CSDCMD & OSCIOFNC_OFF & POSCMOD_XT & FNOSC_PRI)
/// Primary Oscillator Select (XT oscillator mode selected)
#pragma config POSCMOD = XT
/// IOLOCK One-Way Set Enable bit (Write RP Registers Once)
#pragma config IOL1WAY = ON
/// Primary Oscillator Output Function (OSCO functions as CLKO (FOSC/2))
//#pragma config OSCIOFNC = OFF
/// Clock Switching and Monitor (Both Clock Switching and Fail-safe Clock Monitor are disabled)
#pragma config FCKSM = CSDCMD
/// Oscillator Select (Primary oscillator (XT, HS, EC))
#pragma config FNOSC = PRI
/// Internal External Switch Over Mode (IESO mode (Two-speed start-up)disabled)
#pragma config IESO = OFF
/// Note: the following settings are to keep the bootloader from bricking
/// itself and do not necessarily need to be set for a non-bootloader
/// application
/// Write Protect from page 0 to WPFP    : on
/// Write Protect Configuration Page     : on
/// Segmented write protection           : on
/// Write protected end page             : 2
/// _CONFIG3(WPEND_WPSTARTMEM & WPCFG_WPCFGEN & WPDIS_WPEN & WPFP_WPFP2)
/// Write Protection Flash Page Segment Boundary (Page 2 (0x800))
//#pragma config WPFP = WPFP2
/// Segment Write Protection Disable bit (Segmented code protection enabled)
/// #pragma config WPDIS = WPEN
/// Segment Write Protection Disable bit (Segmented code protection disabled) <-FOR DEBUG
//#pragma config WPDIS = WPDIS
/// Configuration Word Code Page Protection Select bit (Last page and Flash configuration words are code-protected)
/// #pragma config WPCFG = WPCFGEN
/// Configuration Word Code Page Protection Select bit (Last page and Flash configuration words aren't code-protected)<-FOR DEBUG
//#pragma config WPCFG = WPCFGDIS
/// Segment Write Protection End Page Select bit (Write Protect from page 0 to WPFP)
//#pragma config WPEND = WPSTARTMEM
#endif /// USE_MCC_CHIP_CONFIG

/// Declarations 

/// Imports

/// Module Global Variables

////    PORTB,
////    PORTC,
////    PORTD,
////    PORTE,
////    PORTF,
////    PORTG
volatile uint16_t *p24_port_table[6];

////    LATB,
////    LATC,
////    LATE,
////    LATE,
////    LATF,
////    LATG,
volatile uint16_t *p24_lat_table[6];

static int ucCriticalNesting = 0;
/// Function Definitions

/// @fn void enterCriticalSection(void)
/// @brief disable interrupts
void enterCriticalSection(void) {
    // if you're not in a critical section disable interrupts 
    if (ucCriticalNesting == 0)
        __asm__ volatile("disi #0x3FFF");

    // increment critical section nesting count 
    ++ucCriticalNesting;
}


/// @fn void exitCriticalSection(void)
/// @brief enable interrupts
void exitCriticalSection(void) {
    // decrement critical section nesting count 
    --ucCriticalNesting;

    // if you've nested all the way out
//    of critical sections enable interrupts 
    if (ucCriticalNesting == 0)
        __asm__ volatile("disi #0x0000");
}

void initClock(void)
{
    // extend/override MCC config
    return;
}
void initGPIO()
{
    // extend/override MCC config

    // populate port/lat tables
    p24_port_table[0] = &PORTB;
    p24_port_table[1] = &PORTC;
    p24_port_table[2] = &PORTD;
    p24_port_table[3] = &PORTE;
    p24_port_table[4] = &PORTF;
    p24_port_table[5] = &PORTG;
    
    p24_lat_table[0]  = &LATB;
    p24_lat_table[1]  = &LATC;
    p24_lat_table[2]  = &LATD;
    p24_lat_table[3]  = &LATE;
    p24_lat_table[4]  = &LATF;
    p24_lat_table[5]  = &LATG;
    
    // enable SPI bus    
    P24_SPI1_EN();

    return;
}

void initADC()
{
   // extend/override MCC config
    return;
}

void initUARTS()
{
    // extend/override MCC config
    return;
}

void initTimers()
{
    // extend/override MCC config
    // disable the interrupt, clear status bit
    TMR2_Start();
    return;
}

void initExInt()
{
    // extend/override MCC config
    return;
}

void initInterrupts()
{
    // extend/override MCC config
    return;
}

void initSPI()
{
    // extend/override MCC config
    return;
}

/// These are intended to extend/override MCC config
/// and should be called after MCC init (SYSTEM_initialize())
/// and before IO is used. 
/// Order is significant - change with care.
void pic24_init() 
{
    initGPIO();
    initClock();
    initInterrupts();
    initUARTS();
    initSPI();
    initADC();
    initTimers();
    initExInt();
}


