/********************************************************************
Function        rotor_position
Parameters:     p_rotor  -- A pointer to a rotor structure
Responsibility: Maintain the following data in a rotor structure: 

                The number of rotor pulses from the CCW physical stop.
                    p_rotor->pulse_count

                The mumber of degrees the rotor has moved since the
                last rotor pulse.
                    p_rotor->deg_update

Returns:        True(non-zero) if 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"

extern void update_display(void);


char rotor_position(struct rotor *p_rotor){
    int tmp;
    char result = FALSE;
    if(p_rotor->new_pulse){
        // A pulse, indicating rotor movement, detected 

        if(p_rotor->cw) {
            ++p_rotor->pulse_count;
        }

        if(p_rotor->ccw) {
            if(p_rotor->pulse_count){
                --p_rotor->pulse_count;
            }
        }

        // reset the degree update data since we want to resync every pulse
        p_rotor->deg_update = 0;
        result = TRUE;

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