#include <avr/eeprom.h>

#include "auto_track.h"
#include "uart_getchar.h"
#include "sw_timers.h"
#include "switches.h"
#include "rotor.h"
#include "main.h"

void rotor_pwr(struct rotor *, char);


void manual(struct rotor *p_rotor) {
    if(p_rotor->limit){
	// Have we encountered a hardware limit on the rotor?
        if(p_rotor->limit == CCW) p_rotor->pulse_count = 0;
        else if(p_rotor->calibrated) {
            p_rotor->pulse_count = p_rotor->pulses_per_rev;
        }
        else p_rotor->pulse_count = 36;
        p_rotor->deg_update = 0;
        p_rotor->bearing = p_rotor->pulse_count * p_rotor->deg_per_pulse;
        p_rotor->pwr_ctl(p_rotor, PWR_OFF);
        request_lcd_refresh = TRUE;
    }

    /********************************************************************
    Don't allow power to be applied in the direction of a limit stop
    before we have moved in the opposing direction first.
    ********************************************************************/
    if(switches.man_az_cw){
        if(!az_rotor.moving && az_rotor.limit != CW ) {
            az_rotor.limit = FALSE;
            az_rotor.pulse_timer = PULSE_TIMEOUT;
            az_rotor.pwr_ctl(&az_rotor, PWR_CW);
        }
    }
    else if(switches.man_az_ccw) {
        if(!az_rotor.moving && az_rotor.limit != CCW ) {
            az_rotor.limit = FALSE;
            az_rotor.pulse_timer = PULSE_TIMEOUT;
            az_rotor.pwr_ctl(&az_rotor, PWR_CCW);
        }
    }
    else {
	// Switch is off so stop the rotor if it is moving
        if(az_rotor.moving){
            az_rotor.pwr_ctl(&az_rotor, PWR_OFF);
        }
    }
    /********************************************************************
    Don't allow power to be applied in the direction of a limit stop
    before we have moved in the opposing direction first.
    ********************************************************************/
    if(switches.man_el_up){
        if(!el_rotor.moving && el_rotor.limit != CW ) {
            el_rotor.limit = FALSE;
            el_rotor.pulse_timer = PULSE_TIMEOUT;
            el_rotor.pwr_ctl(&el_rotor, PWR_CW);
        }
    }
    else if(switches.man_el_down) {
        if(!el_rotor.moving && el_rotor.limit != CCW ) {
            el_rotor.limit = FALSE;
            el_rotor.pulse_timer = PULSE_TIMEOUT;
            el_rotor.pwr_ctl(&el_rotor, PWR_CCW);
        }
    }
    else {
	// Switch is off so stop the rotor if it is moving
        if(el_rotor.moving){
            el_rotor.pwr_ctl(&el_rotor, PWR_OFF);
        }
    }
}
