/* ----------------------------------------------------------------------------
 *         ATMEL Microcontroller Software Support
 * ----------------------------------------------------------------------------
 * Copyright (c) 2012, Atmel Corporation
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the disclaimer below.
 *
 * Atmel's name may not be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
 * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * ----------------------------------------------------------------------------
 */

/**
 *  \page single_snapshot Single Snapshot Demo
 *
 *  \section Purpose
 *
 *  This demo is to show how the system works in backup mode and is only
 *  activated when a pushbutton is pressed.  When capturing and displaying are
 *  finished, the system should go back to backup mode.
 *
 *  \section Requirements
 *
 *  This package can only be used with sam4s-wpir-rd.
 *
 *  \section Description
 *
 *  This demo is aimed to demonstrate the backup mode on SAM4S-WPIR-RD.
 *
 *  The purpose of backup mode is to achieve the lowest power consumption
 *  possible in a system.
 *
 *  Capturing and displaying can only be triggered by pressing BP1. The system
 *  goes to bakcup mode after the process.
 *
 *  Before entering backup mode, the sytem will be configured to save the total
 *  power consumption. After waked up, the following step are taken:
 *  1) switch MCK to PLLB from internal fast RC.
 *  2) initialize SRAM, PIO capture,Image sensor
 *  3) sychornize with vsync and take a  picture
 *  4) display to LCD if mounted
 *  5) go to backup mode
 *
 *  \section Usage
 *
 *  -# Build the program and download it inside the evaluation board. Please
 *     refer to the
 *     <a href="http://www.atmel.com/dyn/resources/prod_documents/doc6224.pdf">
 *     SAM-BA User Guide</a>,
 *     application note or to the
 *     <a href="ftp://ftp.iar.se/WWWfiles/arm/Guides/EWARM_UserGuide.ENU.pdf">
 *     IAR EWARM User Guide</a>,
 *     depending on your chosen solution.
 *  -# After downloading through SAM-BA or IAR flash loader, run the application.
 *  -# Press BP1 to trigger a snapshot which will be displayed on LCD.
 */

/** \file
 *
 *  This file contains all the specific code for the single_snapshot.
 */

/*----------------------------------------------------------------------------
 *        Headers
 *----------------------------------------------------------------------------*/

#include "board.h"

#include "board_low_level_backup.h"
#include <stdint.h>
#include <stdio.h>
#include <stdbool.h>

/*----------------------------------------------------------------------------
 *        Local definitions
 *----------------------------------------------------------------------------*/

/** lcd debug output support, uncomment to remove */
#define LCD_DEBUG_OUT

/** macro to controll the staying in each state permanently,comment for
    continuous transition */
//#define STATE_STAYED

/** display information on LCD during Step by step mode (uncomment STATE_STAYED).
    Uncomment for current measure*/
//#define LCD_DISPLAY_INFORMATION

#define IMAGE_WIDTH     (320)
#define IMAGE_HEIGHT    (240)
/** the captured data length per line in different color mode,double the size
in YUV full output*/
#define IMAGE_LINE_COLORED    (IMAGE_WIDTH * 2)
#define IMAGE_LINE_MONO  (IMAGE_WIDTH)

#define SRAM_BASE (0x60000000)
#define CAP_DEST  (SRAM_BASE)
// reserved for future use*/
//#define DISP_DEST (SRAM_BASE + 0x4000)

/** TWI clock frequency in Hz (400KHz) */
#define TWCK            400000

/** for power on or off*/
#define ON  true
#define OFF false

/** The output formats supported by the sensor*/
typedef enum {
    OUT_RGB,
    OUT_YUV
}OUT_FMT;

/** the system state for each mode*/
typedef enum{
    STATE_INIT, /*initalized*/
    STATE_WAKE_UP,/* wakeup from backup mode. No PLL Initialized*/
    STATE_LCD_INIT, /* LCD Initialization*/
    STATE_MCK_TO_PLL,/* swtich MCK to PLL*/
    STATE_CAPTURE_INIT,/*Capture Initialization*/
    STATE_CAPTURE_DONE,/* Capture done*/
    STATE_BACKUP,
    STATE_END/* reserved*/
}STATE_TYPE;

/** the default output mode is YUV422*/
#define DEFAULT_SENSOR_YUV422

/** uncomment for monochrome output*/
#define DEFAULT_MODE_COLORED

/** reserved for future*/
#define DEFAULT_MCK_FROM_RC  ((uint32_t)4000000)

/** wakeup Pin WKUP2*/
#define WAKEUPEN2_ID    (1<<2)

/** customized trigger event which stored in GPBR0*/
#define TRIGGER_PATTERN 0xFA5F5AA5

void Display_info(uint32_t state);

/** for current measurement*/
#ifdef STATE_STAYED
  #ifdef LCD_DISPLAY_INFORMATION
        #define WAIT_FOR_STATE(STATE) \
                PIO_Clear(&pinTest); \
                Display_info(STATE); \
                _WaitForState(STATE); \
                PIO_Set(&pinTest);

  #else
        #define WAIT_FOR_STATE(STATE) \
                PIO_Clear(&pinTest); \
                _WaitForState(STATE); \
                PIO_Set(&pinTest);
  #endif
#else
#define WAIT_FOR_STATE(STATE)
#endif

/*----------------------------------------------------------------------------
 *        Local variables
 *----------------------------------------------------------------------------*/
/** the output format of image sensor*/
OUT_FMT out_format = OUT_YUV;
/** the output color mode of image sensor*/
PIO_OUT_MODE out_mode = PIO_OUT_COLOR;

/** is displaying needed*/
bool isDisplayed = true;

/** capturing destination buffer*/
uint8_t *cap_dest_buf;

/** displaying destination buffer, RESERVED*/
uint8_t *disp_dest_buf;

/** cpaturing rows*/
uint16_t cap_rows = IMAGE_HEIGHT;

/** cap line length*/
uint16_t cap_line = IMAGE_LINE_COLORED;

/** VSYNC flag*/
volatile bool vsync_flag = false;

/** HSYNC flag RESERVED*/
bool hsync_flag = false;

/** TWI driver*/
static Twid twid;

/** BP1*/
const Pin pinBP1 = PIN_PUSHBUTTON_1;

/** use PIOA_5 for duration test*/
const Pin pinTest = { 1<<5,PIOA,ID_PIOA,PIO_OUTPUT_1,PIO_DEFAULT};

/** vsync pin*/
const Pin pinVSYNC = PIN_OV_VSYNC;

/** all the pins init state*/
const Pin pinInitA = {0x200802, PIOA, ID_PIOA, PIO_INPUT, PIO_PULLUP};
const Pin pinInitB = {0xd8, PIOB, ID_PIOB, PIO_INPUT, PIO_PULLUP};
const Pin pinInitC = {0x13200, PIOC, ID_PIOC, PIO_INPUT, PIO_PULLUP};

#ifdef STATE_STAYED
//do not configure PA5 pin because it is use for duration test in State_stayed
const Pin pinInitAOut = {0xffbff7db, PIOA, ID_PIOA, PIO_OUTPUT_0, PIO_DEFAULT};
#else
const Pin pinInitAOut = {0xffbff7fb, PIOA, ID_PIOA, PIO_OUTPUT_0, PIO_DEFAULT};
#endif
const Pin pinInitBOut = {0xffffff27, PIOB, ID_PIOB, PIO_OUTPUT_0, PIO_DEFAULT};
const Pin pinInitCOut = {0xfffecdff, PIOC, ID_PIOC, PIO_OUTPUT_0, PIO_DEFAULT};


/** current state*/
volatile STATE_TYPE cur_state = STATE_INIT;


/*----------------------------------------------------------------------------
 *        Local functions
 *----------------------------------------------------------------------------*/

/** for current vibration while executing in flash*/
#ifdef STATE_STAYED
static __ramfunc
void _WaitForState(uint32_t state)
{
    while(cur_state != state);
}
#endif

void Display_info(uint32_t state)
{
   switch (state)
   {
      case STATE_LCD_INIT:
        LCDD_ClearWindow(0,0,BOARD_LCD_WIDTH,BOARD_LCD_HEIGHT,COLOR_TURQUOISE);
        LCDD_DrawString(0,20,"LCD Initialized",COLOR_BLACK);
        LCDD_DrawString(0,80,"Press PB1 button to\ngo at the next\nstate",COLOR_BLACK);
      break;

      case STATE_MCK_TO_PLL:
        LCDD_ClearWindow(0,20,BOARD_LCD_WIDTH,20,COLOR_TURQUOISE);
        LCDD_DrawString(0,20,"Switch Mck to PLL\ndone",COLOR_BLACK);
      break;

      case STATE_CAPTURE_INIT:
        LCDD_ClearWindow(0,0,BOARD_LCD_WIDTH,BOARD_LCD_HEIGHT,COLOR_TURQUOISE);
        LCDD_DrawString(0,20,"Capture Initialized",COLOR_BLACK);
        LCDD_DrawString(0,80,"Press PB1 button to\ngo at the next\nstate",COLOR_BLACK);
      break;

      case STATE_CAPTURE_DONE:
        LCDD_ClearWindow(0,0,BOARD_LCD_WIDTH,BOARD_LCD_HEIGHT,COLOR_TURQUOISE);
        LCDD_DrawString(0,20,"Capture done",COLOR_BLACK);
        LCDD_DrawString(0,80,"Press PB1 button to\ndisplay picture and\nenter in backup mode",COLOR_BLACK);
      break;

      default:
         //do nothing
      break;
   }
}

/** Initialize a test pin for duration measurement*/
static void _TestPin_Init(void)
{
#ifdef STATE_STAYED
    PIO_Configure(&pinTest,1);
#endif
}

/** configure AD0,AD4,AD5 as analog inputs*/
static void _PIR_Init(void)
{
    /* set AD0(pa17),AD4(pb0),AD5(pb1) as anaalog input*/
    ADC_EnableChannel(ADC, 0);
    ADC_EnableChannel(ADC, 4);
    ADC_EnableChannel(ADC, 5);
}

/**
 * \brief Initialize the chip.
 */
static void _InitChip( void )
{
    /* Disable all the peripheral clocks */
    PMC_DisableAllPeripherals();

    /* Disable USB Clock */
    REG_PMC_SCDR = PMC_SCER_UDP;

    Pin pinsInitAllInput[]={ pinInitA, pinInitB, pinInitC };
    Pin pinsInitAllOutput[]={ pinInitAOut, pinInitBOut, pinInitCOut };

    /* Configure the following PIOs as input
          pa2 - USER_BP
          pa11 - SPI_NPCS0
          pa22 - NCS2_LCD
          pb3 - TSC_IRQ
          pb4 - ICE_TDI
          pb6 - ICE_TMS
          pb7 - ICE_TCK
          pc9 - SW_PSRAM
          pc12 - USER_LED
          pc13 - LCD_BL
          pc16 - SW_OVT
      */
    PIO_Configure(pinsInitAllInput,PIO_LISTSIZE(pinsInitAllInput));

    /* Configure the other PIOs as output */
    PIO_Configure(pinsInitAllOutput,PIO_LISTSIZE(pinsInitAllOutput));

    PMC_DisablePeripheral(ID_PIOA);
    PMC_DisablePeripheral(ID_PIOB);
    PMC_DisablePeripheral(ID_PIOC);
}

/** preparation for power saving*/
static void _LowPower_Prepare(void)
{
    _InitChip();
    _PIR_Init();
}

/** return the pushbutoon event prior to wakeup*/
static bool _IsTriggered(void)
{
    Gpbr *gpbr = GPBR;
    if(gpbr->SYS_GPBR0 == TRIGGER_PATTERN)
    {
      return true;
    }
    else
    {
      return false;
    }
}

/** triggere envent set*/
static void _TriggereEvent_Set(void)
{
     Gpbr *gpbr = GPBR;
     gpbr->SYS_GPBR0 = TRIGGER_PATTERN;
}

/**
 * \brief Enter Backup Mode.
 * Enter condition: (VROFF bit=1) + (SLEEPDEEP bit = 1)
 */
static void _EnterBackupMode( void )
{
    /* Enable the PIO for wake-up */
    SUPC->SUPC_WUIR = WAKEUPEN2_ID ;
    SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
    /* Set VROFF bit  */
    SUPC->SUPC_CR |= (SUPC_CR_KEY(0xA5) | SUPC_CR_VROFF_STOP_VREG);
}

/** entery for capturing*/
static void _DoCapture(void)
{
    uint8_t *buf;

    /* disable systick*/
    SysTick->CTRL &= ~(SysTick_CTRL_ENABLE_Msk);
    /* set capturing destination address*/
    cap_dest_buf = (uint8_t*)CAP_DEST;

    buf = cap_dest_buf;

    cap_rows = IMAGE_HEIGHT;

    /* sync with flag*/
    while(!vsync_flag)
    {
        /* enable vsync interrupt*/
        PIO_EnableIt(&pinVSYNC);

        /* enter sleep*/
        EnterSleepMode();

        /* disable first*/
        PIO_DisableIt(&pinVSYNC);
     }

     PIO_Capture_Switch(PIOA,ON);

     /* only using Vsync*/
     PIO_CaptureToBuffer(PIOA,buf, (cap_line * cap_rows)>>2);

     /* enable interrupt to wakeup the core  */
     PIOA->PIO_PCIER |= PIO_PCIER_RXBUFF;

     /* enter sleep*/
     EnterSleepMode();
     while(!PIO_Capture_BUFF(PIOA));

     PIO_Capture_Switch(PIOA,OFF);
     /* clear vsync flag*/
     vsync_flag = false;

}

#ifdef LCD_DEBUG_OUT
/** intialize LCD for debugging output*/
static void _Init_LCD(void)
{

    /* Initialize LCD */
   /* for lcd display, avoid interference from other ios*/
    /*
         Disable pull-up
         PC9 : SW_PSRAM
         PC12: USER_LED
         PC16: SW_OVT
      */
    PIO_PullUp_Disable(PIOC, 9);
    PIO_PullUp_Disable(PIOC, 12);
    PIO_PullUp_Disable(PIOC, 16);

    /*
         Enable pad pull-down
         PC9 : SW_PSRAM
         PC12: USER_LED
         PC16: SW_OVT
      */
    PIO_PullDown_Enable(PIOC, 9);
    PIO_PullDown_Enable(PIOC, 12);
    PIO_PullDown_Enable(PIOC, 16);

    #ifdef STATE_STAYED
   //do not configure PA5 pin because it is use for duration test in State_stayed
    PIO_Output_Disable_Mask(PIOA, 0xffffffdf);
    #else
    PIO_Output_Disable_Mask(PIOA, 0xffffffff);
    #endif

    PIO_Output_Disable_Mask(PIOB, 0xffff);
    PIO_Output_Disable_Mask(PIOC, 0xffffffff);

    LCDD_Initialize();
    LCD_On();
}

/** function for Draw black&white yuv data*/
static void _DrawFrame_YUV_BW8( void )
{
    volatile uint32_t dwCursor ;
    uint8_t *pucData ;

    pucData=(uint8_t*)cap_dest_buf ;

    LCD_SetDisplayLandscape(0);

    LCD_SetWindow(0,0,IMAGE_HEIGHT,IMAGE_WIDTH);
    LCD_SetCursor(0,0) ;
    LCD_WriteRAM_Prepare() ;
    for ( dwCursor=IMAGE_WIDTH*IMAGE_HEIGHT ; dwCursor != 0 ; dwCursor-- ,pucData++)
    {
        // Black and White using Y
        LCD_WriteRAMByte( *pucData ) ;
        LCD_WriteRAMByte( *pucData ) ;
        LCD_WriteRAMByte( *pucData ) ;

    }
}

/** normalization function*/
static inline uint8_t _clip( int32_t i )
{
    if ( i > 255 )
    {
        return 255 ;
    }
    if ( i < 0 )
    {
        return 0 ;
    }

    return (uint8_t)i ;
}

/** function for Draw color yuv data*/
static void _DrawFrame_YUV_ColorInt( void )
{
    uint32_t dwCursor ;
    int32_t C ;
    int32_t D ;
    int32_t E ;
    uint8_t* pucData ;

    pucData=(uint8_t*)cap_dest_buf ;

    LCD_SetDisplayLandscape(0);
    LCD_SetWindow( 0, 0,IMAGE_HEIGHT ,IMAGE_WIDTH  ) ;

    LCD_SetCursor( 0,0 ) ;
    LCD_WriteRAM_Prepare() ;
    for ( dwCursor=IMAGE_WIDTH*IMAGE_HEIGHT ; dwCursor != 0 ; dwCursor-=2, pucData+=4 )
    {
        C=pucData[0] ; // Y1
        C-=16 ;
        D=pucData[3] ; // U
        D-=128 ;
        E=pucData[1] ; // V
        E-=128 ;
        // BLUE
         LCD_WriteRAMByte( _clip(( 298 * C + 516 * D           + 128) >> 8) ) ;
        // GREEN
        LCD_WriteRAMByte( _clip(( 298 * C - 100 * D - 208 * E + 128) >> 8) ) ;
        // RED
        LCD_WriteRAMByte( _clip(( 298 * C           + 409 * E + 128) >> 8) ) ;

        C=pucData[2] ; // Y2
        C-=16 ;
        LCD_WriteRAMByte( _clip(( 298 * C + 516 * D           + 128) >> 8) ) ;
        LCD_WriteRAMByte( _clip(( 298 * C - 100 * D - 208 * E + 128) >> 8) ) ;
        LCD_WriteRAMByte( _clip(( 298 * C           + 409 * E + 128) >> 8) ) ;

    }
}

static void _Display(void)
{
    if(out_mode == PIO_OUT_COLOR)
    {
        _DrawFrame_YUV_ColorInt();
    }
    else
    {
        _DrawFrame_YUV_BW8();
    }
}
#endif

/** turn on or off image sensor power*/
static void _Turn_ImageSensor(bool on)
{
    Pin pinsPower[]={ PINS_OV };
    PIO_Configure(pinsPower,PIO_LISTSIZE(pinsPower));

    if(on)
    {
        PIO_Clear(&pinsPower[0]);
    }
    else
    {
        PIO_Set(&pinsPower[0]);
    }

}

/** Initialize Image Sensor*/
static void _Init_Image_Sensor(const EOV7740_Format eFormat)
{
    /* intitializ Master Clock to xvclk1*/
    Pin pinPCK = PIN_PCK0;
    const Pin pinsTWI[] = {PINS_TWI0};
    Pmc *pmc = (Pmc*) PMC;

    /* Power on*/
    _Turn_ImageSensor(ON);

    PIO_Configure(&pinPCK,1);

    /* PLLA is 96MHz so that PCK0 is 96MHz/4 = 24MHz*/
    pmc->PMC_PCK[0] = (PMC_PCK_PRES_DIV4 | PMC_PCK_CSS_PLLACLOCK);

    pmc->PMC_SCER = PMC_SCER_PCK0;

    while(!( pmc->PMC_SCSR & PMC_SCSR_PCK0));

    Wait(5);

    /* twi*/
    PIO_Configure(pinsTWI,PIO_LISTSIZE(pinsTWI));

    PMC_EnablePeripheral(ID_TWI0);

    TWI_ConfigureMaster(TWI0, TWCK, BOARD_MCK);

    TWID_Initialize(&twid, TWI0);

    /* Configure TWI interrupts */
    NVIC_DisableIRQ(TWI0_IRQn);
    NVIC_ClearPendingIRQ(TWI0_IRQn);
    NVIC_SetPriority(TWI0_IRQn, 0);
    NVIC_EnableIRQ(TWI0_IRQn);

    while( ov_init(&twid) == 0 );

    /* OV7740 configuration */
    ov_configure(&twid, eFormat);	

        /* first time*/
    if(!_IsTriggered())
    {
        Wait(3000);
        ov_sotre_manual(&twid,&(GPBR->SYS_GPBR2),2);
        /* TRIGGER EVENT should be set after capture initialization*/
        _TriggereEvent_Set();
    }
    else
    {
        ov_resotre_manual(&(GPBR->SYS_GPBR2),2);
        ov_configure_manual(&twid);
    }
}

/**
 *  \brief Handler for Button 1 rising edge interrupt.
 *
 *  Handle state transition.
 */
static void _Button1_Handler(const Pin* pin)
{
        switch (cur_state)
        {
            case STATE_INIT:
            cur_state = STATE_WAKE_UP;
            break;

            case STATE_WAKE_UP:
            cur_state = STATE_LCD_INIT;
            break;

            case STATE_LCD_INIT:
            cur_state = STATE_MCK_TO_PLL;
            break;

            case STATE_MCK_TO_PLL:
            cur_state = STATE_CAPTURE_INIT;
            break;

            case STATE_CAPTURE_INIT:
            cur_state = STATE_CAPTURE_DONE;
            break;

            case STATE_CAPTURE_DONE:
            cur_state = STATE_BACKUP;
            break;

            case STATE_BACKUP:
            cur_state = STATE_INIT;
            break;

            default:
            cur_state = STATE_END;
            break;
        }
}

/** interrupt handler for vsync*/
static void _Vsync_Handler(const Pin* pin)
{
    static bool bFirst = true;
    if(!bFirst)
    {
       vsync_flag = true;
    }
    else
    {
        bFirst = false;
    }
}

/** intialize fram marker signal response*/
static void _Init_HVSync_Interrupts(void)
{

    PIO_Configure(&pinVSYNC,1);

    PIO_ConfigureIt(&pinVSYNC, _Vsync_Handler);

    /* Enable PIO controller IRQs. */
    NVIC_EnableIRQ(PIOA_IRQn);

}

/** initialize pushbutton for state transition*/
static void _Init_Pushbutton_Trigger(void)
{
    /* Configure pios as inputs. */
    PIO_Configure( &pinBP1, 1 ) ;

    /* Adjust pio debounce filter patameters, uses 10 Hz filter. */
    PIO_SetDebounceFilter( &pinBP1, 10 ) ;

    /* Initialize pios interrupt handlers, see PIO definition in board.h. */
    PIO_ConfigureIt( &pinBP1, _Button1_Handler ) ; /* Interrupt on rising edge  */

    /* Enable PIO controller IRQs. */
    NVIC_EnableIRQ( (IRQn_Type)pinBP1.id ) ;

    /* Enable PIO line interrupts. */
    PIO_EnableIt( &pinBP1 ) ;

}

/** Initialziation of SRAM, PIO capture, VSynch handler,Image sensor*/
static void _Capture_Init(void)
{
    /* SET ios to default input */
    PIO_Output_Disable_Mask(PIOA, 0xffbff7db);

    /* OUTPUT color mode*/
#ifdef DEFAULT_MODE_COLORED
    out_mode = PIO_OUT_COLOR;
#else
    out_mode = PIO_OUT_MONO;
#endif

    TimeTick_Configure((BOARD_MCK));

    /* configure SRAM*/
    BOARD_ConfigureSRAM(SMC) ;

    /* intialize Frame signal*/
    _Init_HVSync_Interrupts();

    /* initialize PIODC*/
    PIODC_Capture_Init(PIOA, ID_PIOA, out_mode);

    /** intialize capturing line*/
    if(out_mode == PIO_OUT_COLOR)
    {
        cap_line = IMAGE_LINE_COLORED;
    }
    else if(out_mode == PIO_OUT_MONO)
    {
        cap_line = IMAGE_LINE_MONO;
    }
    else
    {
        cap_line = IMAGE_LINE_COLORED;
    }

#ifdef DEFAULT_SENSOR_YUV422
    _Init_Image_Sensor(QVGA_YUV422);
#endif
}

/*----------------------------------------------------------------------------
 *        Exported functions
 *----------------------------------------------------------------------------*/

/** system systick handler*/
void SysTick_Handler( void )
{
    TimeTick_Increment();
}

/** PIO capture handler*/
extern void PIO_CaptureHandler( void )
{
    PIOA->PIO_PCIDR |= PIO_PCIDR_RXBUFF;
}

/**
 *  \brief single_snapshot demo entry point.
 *
 *  \return Unused (ANSI-C compatibility).
 *  \callgraph
 */
extern int main( void )
{
    /* Disable watchdkog */
    WDT_Disable( WDT ) ;

    /* State: Enter Active Mode without PLL*/

    /* initialize for low power*/
    _LowPower_Prepare();

    /* for duration test*/
    _TestPin_Init();

    /* main procedure to do capturing and display (if needed) */
#ifdef STATE_STAYED
    /* intialize pushbutton for state transition */
    _Init_Pushbutton_Trigger();
#endif
    WAIT_FOR_STATE(STATE_WAKE_UP);


#ifdef LCD_DEBUG_OUT
    if(!_IsTriggered())
    {
      TimeTick_Configure( (DEFAULT_MCK_FROM_RC) );
      Wait(1000); // wait for 1s to be sure LCD is ready for initialization
      _Init_LCD();
      LCDD_Fill(COLOR_TURQUOISE);
      LCDD_DrawString(0,10,"Single snapshot demo",COLOR_BLACK);
      LCDD_DrawString( 0, 40,"Please Wait during\ninitializations", COLOR_BLACK );
    }
    else
    {
      TimeTick_Configure( (DEFAULT_MCK_FROM_RC) );
      _Init_LCD();
    }

    WAIT_FOR_STATE(STATE_LCD_INIT);
#endif

    /* State: Enter Active Mode PLL Enabled*/
    /* switch MCK to PLL*/
    SwitchMck2PLL();
    TimeTick_Configure((BOARD_MCK));
    WAIT_FOR_STATE(STATE_MCK_TO_PLL);


    /* State: Capture*/
    /*initizalize image sensor, piodc*/
    _Capture_Init();
    WAIT_FOR_STATE(STATE_CAPTURE_INIT);

    /* doing capture*/
    _DoCapture();
    /* State: Display (Note: valid only when LCD_DEBUG_OUT is uncommented)*/
    WAIT_FOR_STATE(STATE_CAPTURE_DONE);


#ifdef LCD_DEBUG_OUT
    _Display();
    WAIT_FOR_STATE(STATE_BACKUP);
#endif

    /* State: Initialization Wakeup Trigger*/
    _LowPower_Prepare();

#ifdef STATE_STAYED
      PIO_Clear(&pinTest);
#endif

    /* State: Enter Backup Moder*/
    _EnterBackupMode();
    return 0;
}


