#include <ti/devices/msp432p4xx/driverlib/driverlib.h>
#include <stdio.h>
#include <math.h>
#include <stdint.h>
#include <stdbool.h>

// Stack size is increased to 1024
// 1. define CHECKRET under Properties -> Build -> ARM Compiler -> Predefined Symbols
//    to check whether part of memory banks are retained or not
// 2. define RETALL to retain all banks 0-7, otherwise only banks 0-1 are retained
// 3. define CHECKRUN to verify the program is resuming after waking up
//    note that energytrace has a bug when the program runs with CHECKRUN

#ifdef CHECKRUN
#define RETALL 1 // printf() needs more memory banks alive
#include <stdio.h>
#endif // CHECKRUN

#ifdef CHECKRET
int *ptr = (int *)0x20008000;
#endif // CHECKRET


/* Statics */
#define FIR_LENGTH 17
float COEFF[FIR_LENGTH] =
{
 -0.000091552734, 0.000305175781, 0.004608154297, 0.003356933594, -0.025939941406,
 -0.044006347656, 0.063079833984, 0.290313720703, 0.416748046875, 0.290313720703,
 0.063079833984, -0.044006347656, -0.025939941406, 0.003356933594, 0.004608154297,
 0.000305175781, -0.000091552734
};

/* The following array simulates input A/D converted values */
unsigned int INPUT[] =
{
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0400, 0x0800, 0x0C00, 0x1000, 0x1400, 0x1800, 0x1C00, 0x2000,
0x2400, 0x2000, 0x1C00, 0x1800, 0x1400, 0x1000, 0x0C00, 0x0800,
0x0400, 0x0400, 0x0800, 0x0C00, 0x1000, 0x1400, 0x1800, 0x1C00,
0x2000, 0x2400, 0x2000, 0x1C00, 0x1800, 0x1400, 0x1000, 0x0C00,
0x0800, 0x0400, 0x0400, 0x0800, 0x0C00, 0x1000, 0x1400, 0x1800,
0x1C00, 0x2000, 0x2400, 0x2000, 0x1C00, 0x1800, 0x1400, 0x1000,
0x0C00, 0x0800, 0x0400
};

uint32_t flag = 0;

/* Application Data */
volatile uint32_t curPowerState, ledBlinkCount;
volatile bool stateChange;

/* Timer_A UpMode Configuration Parameter */
const Timer_A_UpModeConfig upConfig =
{
        TIMER_A_CLOCKSOURCE_ACLK,               // ACLK Clock SOurce
        TIMER_A_CLOCKSOURCE_DIVIDER_1,          // ACLK/1
        16000,                                  // 16000 tick period
        TIMER_A_TAIE_INTERRUPT_DISABLE,         // Disable Timer interrupt
        TIMER_A_CCIE_CCR0_INTERRUPT_ENABLE ,    // Enable CCR0 interrupt
        TIMER_A_SKIP_CLEAR                      // Clear value
};

/* List of power states to toggle through */
/*#define NUMBER_OF_POWER_STATES    13
const uint32_t powerStates[NUMBER_OF_POWER_STATES] =
{ PCM_AM_LDO_VCORE0, PCM_AM_LDO_VCORE1, PCM_AM_DCDC_VCORE0, PCM_AM_DCDC_VCORE1, PCM_AM_LF_VCORE0,
        PCM_AM_LF_VCORE1, PCM_LPM0_LDO_VCORE0, PCM_LPM0_LDO_VCORE1, PCM_LPM0_DCDC_VCORE0, PCM_LPM0_DCDC_VCORE1,
        PCM_LPM0_LF_VCORE0, PCM_LPM0_LF_VCORE1, PCM_LPM3 };*/
#define NUMBER_OF_POWER_STATES    2
const uint32_t powerStates[NUMBER_OF_POWER_STATES] =
{ PCM_AM_DCDC_VCORE0, PCM_LPM3 };

void TerminateGPIO(void);

int main(void)
{
#ifdef CHECKRUN
    int k=0;
#endif // CHECKRUN

    /* Halting the Watchdog */
    MAP_WDT_A_holdTimer();

    /* Initializing Variables */
    curPowerState = MAP_PCM_getPowerState();
    stateChange = false;
    ledBlinkCount = 0;

    /* Setting the Reference Oscillator to 128KHz. For Low Frequency modes, the
     * MCLK frequency is required to be scaled back to 128KHz.
     */
    MAP_CS_setReferenceOscillatorFrequency(CS_REFO_32KHZ);


    /* Setting up Timer_A to be sourced from ACLK and for ACLK to be sourced from
     * the 128Khz REFO. Since the frequency of MCLK will be changed when we go
     * into LF mode, we want to make our LED blink look consistent.
     */
    MAP_CS_initClockSignal(CS_ACLK, CS_REFOCLK_SELECT, CS_CLOCK_DIVIDER_1);
    MAP_Timer_A_configureUpMode(TIMER_A0_BASE, &upConfig);
    MAP_Timer_A_enableCaptureCompareInterrupt(TIMER_A0_BASE,
            TIMER_A_CAPTURECOMPARE_REGISTER_0);

    /* Setting P1.0 as LED Output and P1.1 as input switch */
    MAP_GPIO_setAsInputPinWithPullUpResistor(GPIO_PORT_P1, GPIO_PIN1);
    MAP_GPIO_clearInterruptFlag(GPIO_PORT_P1, GPIO_PIN1);
    MAP_GPIO_enableInterrupt(GPIO_PORT_P1, GPIO_PIN1);
    MAP_GPIO_setAsOutputPin(GPIO_PORT_P1, GPIO_PIN0);
    MAP_GPIO_setAsOutputPin(GPIO_PORT_P2, GPIO_PIN1);
    MAP_GPIO_setOutputLowOnPin(GPIO_PORT_P1, GPIO_PIN0);
    MAP_GPIO_setOutputLowOnPin(GPIO_PORT_P2, GPIO_PIN1);
    MAP_Interrupt_enableInterrupt(INT_PORT1);
    MAP_Interrupt_enableMaster();

    MAP_Interrupt_disableSleepOnIsrExit();

#ifdef CHECKRET
    *ptr = 0x1234;
#endif // CHECKRET

    /* Enabling and Disabling SRAM Bank Retention */
#ifdef RETALL
    MAP_SysCtl_enableSRAMBankRetention(SYSCTL_SRAM_BANK1|SYSCTL_SRAM_BANK2|SYSCTL_SRAM_BANK3|SYSCTL_SRAM_BANK4|SYSCTL_SRAM_BANK5|SYSCTL_SRAM_BANK6|SYSCTL_SRAM_BANK7);
#else // BANK 0,1 Retention
    MAP_SysCtl_enableSRAMBankRetention(SYSCTL_SRAM_BANK1);
    MAP_SysCtl_disableSRAMBankRetention(SYSCTL_SRAM_BANK2|SYSCTL_SRAM_BANK3|SYSCTL_SRAM_BANK4|SYSCTL_SRAM_BANK5|SYSCTL_SRAM_BANK6|SYSCTL_SRAM_BANK7);
#endif // RETALL

    MAP_Interrupt_enableMaster();
    while (1)
    {
        /* If we have a state change request... */
        if (stateChange)
        {
            MAP_Interrupt_disableMaster();

            stateChange = false;

            /* If we are going to switch our power state into a Low Frequency
             * Mode, we have to scale back our MCLK frequency to 128KHz.
             */
            if (powerStates[curPowerState] == PCM_AM_LF_VCORE0
                    || powerStates[curPowerState] == PCM_AM_LF_VCORE1
                    || powerStates[curPowerState] == PCM_LPM0_LF_VCORE0
                    || powerStates[curPowerState] == PCM_LPM0_LF_VCORE1)
            {
                MAP_CS_initClockSignal(CS_MCLK, CS_REFOCLK_SELECT,
                        CS_CLOCK_DIVIDER_1);
            } else
            {
                MAP_CS_initClockSignal(CS_MCLK, CS_DCOCLK_SELECT,
                        CS_CLOCK_DIVIDER_1);
            }
//![Simple PCM Config]
            /* Re-enabling port pin interrupt */
            MAP_GPIO_clearInterruptFlag(GPIO_PORT_P1, GPIO_PIN1);
            MAP_Interrupt_enableInterrupt(INT_PORT1);
            MAP_Interrupt_enableMaster();

            MAP_PCM_setPowerState(powerStates[curPowerState]);



#ifdef CHECKRUN
        int i, y, j; /* Loop counters */
        volatile float OUTPUT[36],sum;

        //for(j=0; j < 1000; j++){
        for(y = 0; y < 10; y++)
        {
         sum=0;
         for(i = 0; i < FIR_LENGTH/2; i++)
         {
         sum = sum+COEFF[i] * ( INPUT[y + 16 - i] + INPUT[y + i] );
         }
         OUTPUT[y] = sum + (INPUT[y + FIR_LENGTH/2] * COEFF[FIR_LENGTH/2] );
         printf("Output[%d] = %f\n", y, OUTPUT[y]);

         printf("%d\n",k++);
#endif // CHECKRUN
         /* Change to new power state */

        }
//![Simple PCM Config]
        }
    }
}

/*
 * Port 6 interrupt handler. This handler is called whenever the switch attached
 * to P6.7 is pressed. A status flag is set to signal for the main application
 * to change power states
 */
void PORT1_IRQHandler(void)
{
    uint32_t status = MAP_GPIO_getEnabledInterruptStatus(GPIO_PORT_P1);
    MAP_GPIO_clearInterruptFlag(GPIO_PORT_P1, status);

    /* Toggling the output on the LED */
#ifdef CHECKRET //retention Àß µÇ´ÂÁö Ã¼Å©ÇÏ´Â ÄÚµå
    if (status & GPIO_PIN1 && *ptr==0x1234)
    {
        MAP_Interrupt_disableInterrupt(INT_PORT1);

        if (powerStates[curPowerState] == PCM_LPM3)
        {
            //MAP_GPIO_setOutputHighOnPin(GPIO_PORT_P1, GPIO_PIN0);
            curPowerState = 0;
            printf("wake\n");

        }
        else
        {
            printf("sleep\n");
            //MAP_GPIO_setOutputLowOnPin(GPIO_PORT_P1, GPIO_PIN0);
            curPowerState++;

        }

        ledBlinkCount = 0;
        MAP_Interrupt_enableInterrupt(INT_TA0_0);
        MAP_Timer_A_startCounter(TIMER_A0_BASE,TIMER_A_UP_MODE);

    }
#else
    if(status & GPIO_PIN1)
#endif // CHECKRET
    {
        //MAP_GPIO_toggleOutputOnPin(GPIO_PORT_P1, GPIO_PIN0);
    }


}



/* Flashes LED */
void TA0_0_IRQHandler(void)
{
    MAP_Timer_A_clearCaptureCompareInterrupt(TIMER_A0_BASE,
            TIMER_A_CAPTURECOMPARE_REGISTER_0);

    //MAP_GPIO_toggleOutputOnPin(GPIO_PORT_P1, GPIO_PIN0);

    ledBlinkCount++;

     if(ledBlinkCount == 6)
     {
         stateChange = true;
         MAP_Timer_A_stopTimer(TIMER_A0_BASE);
         MAP_Interrupt_disableInterrupt(INT_TA0_0);
     }
}



