#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <avr/io.h>
#include <avr/eeprom.h>

#include "lcd.h"
#include "uart_getchar.h"
#include "rotor.h"
#include "main.h"
#include "sw_timers.h"

void init_uart(void );
int out_queue(void);
void initialize(void);
void init_timer1(void);
void init_rotor_ctl_io(void);

extern FILE lcd_out;

void update_display(void);

void initialize()  {

    init_rotor_ctl_io();
    init_uart();    // Initializes the UART transmit buffer


    /* initialize LCD display */
    lcd_init(LCD_DISP_ON_BLINK);

    /* clear display and home cursor */
    lcd_clrscr();

    init_timer1();


    //Read back the saved rotor structure(s) as a starting point

    eeprom_read_block (&az_rotor, &ee_az_rotor, sizeof(struct rotor));
    eeprom_read_block (&el_rotor, &ee_el_rotor, sizeof(struct rotor));

    /***********************************************
    Just in case the rotors are not Calibrated
    reload constants into the rotor structures.
    ***********************************************/
    az_rotor.pwr_off = AZ_PWR_OFF_MASK;
    az_rotor.pwr_cw = AZ_PWR_CW_MASK;
    az_rotor.pwr_ccw = AZ_PWR_CCW_MASK;
    el_rotor.pwr_off = EL_PWR_OFF_MASK;
    el_rotor.pwr_cw = EL_PWR_CW_MASK;
    el_rotor.pwr_ccw = EL_PWR_CCW_MASK;

    /************************************************
    Set a sw timer to detect rotor malfunctions.
    I should see a rotor pulse in less than 4 seconds if
    a rotor is moving.
    ************************************************/
    az_rotor.pulse_timer = PULSE_TIMEOUT;
    el_rotor.pulse_timer = PULSE_TIMEOUT;

    new_auto_bearing = FALSE;

    az_rotor.cal_submode = INITIAL;
    az_rotor.detect_submode = START;
    el_rotor.cal_submode = INITIAL;
    el_rotor.detect_submode = START;

    /**********************************************
    Load the address of the rotor power control
    function into the rotor structures.
    **********************************************/
    void rotor_pwr(struct rotor *, char);
    az_rotor.pwr_ctl = rotor_pwr;
    el_rotor.pwr_ctl = rotor_pwr;


    //enable timer/counter 1 interrupts
    TIMSK = _BV(TOIE1);
}
