/********************************************************************
Function        az_rotor_pulse
Responsibility: Maintain data regarding rotor position:

                The number of rotor pulses from the CCW physical stop.
                    az_rotor,pulse_count

                The mumber of degrees the rotor has moved since the
                last rotor pulse.
                    az_rotor.deg_update

Returns:        True(non-zero)if a new information was recorded
                False(zero) if information has not changed
Author:         Bill (N9CX)

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

#include "gpr.h"
#include "switches.h"
#include "rotor.h"
#include "main.h"
#include "sw_timers.h"


static unsigned int tic_tmp;

char az_rotor_position(void){
    int tmp;
    char result = FALSE;
    if(az_rotor.new_pulse){
        // A pulse, indicating rotor movement, detected 

        if(az_rotor.cw) {
            ++az_rotor.pulse_count;
        }

        if(az_rotor.ccw) {
            if(az_rotor.pulse_count){
                --az_rotor.pulse_count;
            }
        }

        // reset the degree update data since we want to resync every pulse
        az_rotor.deg_update = 0;
        result = TRUE;

        az_rotor.new_pulse = 0;
        az_rotor.pulse_timer = PULSE_TIMEOUT;
    }
    else if(az_rotor.moving) {
        // We are between rotor pulses so compute interpulse correction
        // degrees since last pulse
        tic_tmp = (PULSE_TIMEOUT - az_rotor.pulse_timer);
        if(tic_tmp >= az_rotor.tics_per_degree){
            tmp = tic_tmp/az_rotor.tics_per_degree;
            if(tmp != az_rotor.deg_update){
                az_rotor.deg_update = tmp;
                result = TRUE;
            }
        }
    }
return result;
}
