/**************************************************************************
Function Name   - rotor_bearing 
Parameters      - The address of a rotor structure
Responsibility  - Calculate the rotor bearing/position in degrees.
                
Notes           - 
Returns         - Nothing
Author          - Bill (N9CX)
**************************************************************************/
#include <inttypes.h>
#include <avr/eeprom.h>

#include "rotor.h"
#include "main.h"

void rotor_bearing(struct rotor *p_rotor){

    // was the last movement in a CW direction?
    if(p_rotor->cw) p_rotor->bearing =  (p_rotor->pulse_count *
                                        p_rotor->deg_per_pulse) +
                                        p_rotor->deg_update;
    else if(p_rotor->pulse_count){
        /*
        The last movement was in the CCW direction
        and the rotor is not against the physical stop
        */
        p_rotor->bearing =  (p_rotor->pulse_count *
                            p_rotor->deg_per_pulse) -
                            p_rotor->deg_update;
    }
    /*******************************************************************
    Otherwise, the rotor last moved CCW and the pulse count is 0.
    So, it is at, or close to, a physical stop.
    Since the bearing is decreasing and deg_update is the correction 
    factor that is normally subtracted from the pulse_count the fromula 
    is now  deg_per_pulse -  deg_update
    *******************************************************************/
    else p_rotor->bearing = p_rotor->deg_per_pulse - p_rotor->deg_update;

    /******************************************************************
    defensive code - just in case we slipped a tic or two.
                     A tic is one timer counter interrupt.
    *******************************************************************/
    if(p_rotor->bearing < 0) {
        p_rotor->bearing = 0;
        p_rotor->deg_update = 0;
    }
    if(p_rotor->bearing > 360){
        p_rotor->bearing = 360;
        p_rotor->deg_update = 0;
    }
}
