/*
 * Copyright (c) 2019 Clementine Computing LLC.
 *
 * This file is part of PopuFare.
 * 
 * PopuFare is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * PopuFare is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with PopuFare.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <poll.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <time.h>

#include <openssl/md5.h>

#include <ctype.h>
#include <string.h>

#include "../common/common_defs.h"
#include "../commhub/commhub.h"
#include "../commhub/client_utils.h"

#include "fbutil.h"
#include "expat-2.0.1/lib/expat.h"
#include "menu.h" 

int diu_fd = -1;
int hub_fd = -1;

time_t last_hub_try = 0;
time_t last_diu_clock = 0;

gps_status my_gps_stat={0};

time_t mkgmtime(struct tm *tm);

int 	token_diag_serial = 0;
char 	token_diag_string[LINE_BUFFER_SIZE] = {0};

unsigned char menu_checksum[MD5_DIGEST_LENGTH];

int md5_of_file(char *filename, void *result)
{
    FILE *f = NULL;
    char chunk[LINE_BUFFER_SIZE]={0};
    int retval = 0;
    MD5_CTX ctx;
    
    if(!result)
        return -1;
    
    if(!filename)
        return -1;
        
    if(!MD5_Init(&ctx))
    {
        return -1;
    }
    
    f = fopen(filename, "rb");
    
    if(!f)
    {
        return -1;
    }
    
    while(1)
    {
        retval = fread(chunk, 1, LINE_BUFFER_SIZE, f);
        
        if(retval <= 0)
        {
            break;
        }
        else
        {
            MD5_Update(&ctx, chunk, retval);    
        }
    }
    
    fclose(f);
    
    MD5_Final((unsigned char *)result, &ctx);
    
    return 0;    
}

void set_diu_clock(int fd, time_t tt)
{
    struct tm t;
    char buffer[16];
    int n;
    
    localtime_r(&tt, &t);
    
    n = sprintf(buffer, "/C:%02d%02d\r", t.tm_hour, t.tm_min);
    
    write(fd, buffer, n);
}

//    This function takes a GPS timestamp (in gross GPS float format + gross integer date) and
//makes it into a sane UTC timestamp.  If we are more than MAX_GPS_CLOCK_DRIFT seconds off 
//from GPS time, it sets the system clock to GPS time.
int handle_gps_time(float gtime, int date)
{
    int day,month,year;
    int hour,min,sec,frac;
    int n = 0;
    time_t utc,now;
  
    char buffer[32] = {0};

    struct message_record outgoing_msg;
  
    now = time(NULL);
  
    day = month = year = 0;
    hour = min = sec = frac = 0;
  
  
    //    Just to be *ahem* clear, as per NMEA standard the date is encoded DDMMYY, and the time of day
    // is encoded HHMMSS[.frac] where there is an optional fractional second field denoted by a decimal point.
    // we must be able to decode the fractional seconds field but we discard the information since it is not
    // reliable enough to be worth the bother.
    //    Whoever thought that NMEA GPS should encode the time in this format ought to be shot...
    

    n = 0;	//Start out with zero parsed fields
    
    //    Construct and then re-parse the time from its icky format to discrete values (this should result 
    // in at least three (possibly four) fields.
    sprintf(buffer,"%010.3f", gtime);
    n += sscanf(buffer,"%02d%02d%02d.%d", &hour, &min, &sec, &frac);
    
    //Construct and then re-parse the date from its icky format to discrete values.  This should result in three fields.
    sprintf(buffer,"%06d", date);
    n += sscanf(buffer,"%02d%02d%02d", &day, &month, &year);
  
    if(n >= 6)	//if we scanned at all required fields
    {
        struct tm gpstm = {0};

        year += GPS_DATE_CENTURY;		//GPS date only uses two digits for year, so we must assume the century
    
        gpstm.tm_year = year - 1900;		//tm.tm_year is based on the year 1900
        gpstm.tm_mon = month - 1;		//January = month 0 in struct tm.tm_mon whereas January = month 1 in an NMEA GPS date.
        gpstm.tm_mday = day;
        gpstm.tm_hour = hour;
        gpstm.tm_min = min;
        gpstm.tm_sec = sec;
    
        utc = mkgmtime(&gpstm);			//Go and turn the struct tm we've just populated into an utc time stamp (seconds since epoch)
    
        my_gps_stat.gpstime = utc;		//Most importantly... Remember what the self-reported GPS time stamp is.
    
//      printf("%02d-%02d-%04d %02d:%02d:%02d\n",day,month,year,hour,min,sec);
//      printf("CALCULATED: %d\nSYSTEM    : %d\n\n",(int)utc,(int)time(NULL));

        if(abs(utc - now) > MAX_GPS_CLOCK_DRIFT)	//if we have more than MAX_GPS_CLOCK_DRIFT seconds of clock drift
        {
            struct timeval ts = {0};
      
            ts.tv_sec = utc;	//Set the timeval struct to the calculated utc timestamp from the GPS unit.
            ts.tv_usec = 0;
      
            settimeofday(&ts, NULL);	//Set the system clock from GPS time using said timeval struct.
            
            //system("/sbin/hwclock --systohc");	//Go and push the new system clock value into the hardware realtime clock chip.
            
            if( hub_fd >= 0)	//If we have a valid connection to the IPC hub
            {
                //Stick a message into the diagnostic log to record the fact that we've set the system clock from GPS
                format_log_message(&outgoing_msg, LOGLEVEL_DEBUG, "Set syatem clock from previous value (%d) to GPS time (%d).", (int)now, (int)utc );
                send_message(hub_fd, &outgoing_msg);        
            }
        }
    }
      
    return 0;
}


#ifdef CLEAR_GPS_ON_STALE
    static inline void clear_stale_gps_data()
    {
        my_gps_stat.lat = my_gps_stat.lon = my_gps_stat.heading = my_gps_stat.velocity = 0;
        my_gps_stat.num_sats = 0;
    }
#else
    static inline void clear_stale_gps_data()
    {
    }
#endif

static int handle_stale_gps_condition()
{
    //     This return code will be > 0 if this function generates a status change that 
    // will then need to be communicated to other modules in the system via a message to
    // MAILBOX_GPS_STATUS.
    int return_code = 0;
    
    //     This will hold the gps_good flag as it stood at the beginning of this subroutine 
    // previous to any adjustments we make.
    int previous_good_flag = my_gps_stat.gps_good;
    
    int stale_time = 0;
    
    time_t now = time(NULL);

    stale_time = (now - my_gps_stat.stamp);

    // If we have entered this function with the impression that we have a valid GPS fix...
    if(previous_good_flag > 0)
    {
        // If it has been at least GPS_STALE_THRESHOLD seconds since the last fix
        if( stale_time >= GPS_STALE_THRESHOLD ) 
        {
            clear_stale_gps_data();
            my_gps_stat.gps_good = 0;
            return_code |= 1;
        }
    
    }
    
    //     If we have determined that we need to declare the GPS data stale and invalid and
    // we have a valid connection to the IPC hub we should use that IPC hub connection to
    // add a note to the diagnostic log indicating that we've declared the GPS data stale.
    if( return_code && (hub_fd >= 0) )
    {
        struct message_record outgoing_msg;

        format_log_message(&outgoing_msg, LOGLEVEL_DEBUG, "GPS fix has been stale for %d seconds, setting GPS = NO.", stale_time);
        send_message(hub_fd, &outgoing_msg);
    }
    
    return return_code;
}

int update_gps(char *in)
{
    //     This will hold the number of matched variables populated by sscanf().
    int num = 0;

    //     This will allow us to know if we have made a transition from an invalid
    // GPS fix to a valid one so that we can log this information.
    int previous_good_flag = my_gps_stat.gps_good;

    //     This return code will be > 0 if this function generates a status change that 
    // will then need to be communicated to other modules in the system via a message to
    // MAILBOX_GPS_STATUS.
    int return_code = 0;


    if(!strncmp(in,"$GPRMC",6))
    {
        float f1=0;
        char f2=0;
        float f3=0;
        char f4=0;
        float f5=0;
        char f6=0;
        float f7=0;
        float f8=0;
        int f9=0;
        float f10=0;
        char f11=0;

        num = sscanf(in,"$GPRMC,%f,%c,%f,%c,%f,%c,%f,%f,%d,%f,%c",&f1,&f2,&f3,&f4,&f5,&f6,&f7,&f8,&f9,&f10,&f11);
      
        if(num == 11) //If we have a full GPRMC sentence we can consider setting the time
        {
            //     Require at least MIN_SATS_FOR_TIME satellites to accept a new system clock value from the GPS unit.
            // This is to keep a crummy GPS fix from generating a bogus or unstable system time.
            
            if(my_gps_stat.num_sats >= MIN_SATS_FOR_TIME)  	
            {
                //     Pass the time field (f1) and the date field (f9) in to the routine that sets the system clock if needed.
                // (this routine also stores the utc timestamp derived from the GPS date and time fields so it can be passed to
                // other modules that may have a need for this information).
                handle_gps_time(f1,f9);	
            }
        }

        if(num > 0)
        {       
            my_gps_stat.lat = f3 * ((f4 == 'N')?(1):(-1));	//update snapshot with latitude
        
            my_gps_stat.lon = f5 * ((f6 == 'E')?(1):(-1));		//longitude
        
            my_gps_stat.velocity = f7 / 1.94384449f;	//meters per second (converted from knots)
            my_gps_stat.heading = f8;		//course
        
            my_gps_stat.stamp = time(NULL);	//update snapshot's staledate
            
            return_code |= 1;
        }
    }
    else if(!strncmp(in,"$GPGGA",6))
    {
        int f1=0;
        float f2=0;
        char f3=0;
        float f4=0;
        char f5=0;
        int f6=0;
        int f7=0;
        float f8=0;
        float f9=0;
        char f10=0;
        float f11=0;
        char f12=0;

        num=sscanf(in,"$GPGGA,%d,%f,%c,%f,%c,%d,%d,%f,%f,%c,%f,%c",&f1,&f2,&f3,&f4,&f5,&f6,&f7,&f8,&f9,&f10,&f11,&f12);

        if(num == 12)
        {
            if ( f7 >= 3 )  // require 3 satellites minimum
            {
                my_gps_stat.gps_good = f6;			//store GPS valid flag in snapshot
                my_gps_stat.num_sats = f7;			//store number of satellites in view in snapshot

                //     Do NOT store the timestamp since we only want to remember timestamps of position 
                // fixes and the GPGGA message is all metadata (number of satellites, fix quality, etc...).
                // It is worth noting that GPGGA does report altitude, but that is not a piece of information
                // we track because the road is where the road is, and if a bus becomes airborn we have much
                // bigger problems than figuring out how far off the ground it is...

                return_code |= 1;
            }
        }

    }

    return_code |= handle_stale_gps_condition();

    //     If we have a connection to the IPC hub and we had previously not had a valid
    // GPS fix but we now do, make a note of it in the diagnostic log.
    if( (previous_good_flag == 0) && (my_gps_stat.gps_good != 0) && (hub_fd >= 0) )
    {
        struct message_record outgoing_msg;

        format_log_message(&outgoing_msg, LOGLEVEL_DEBUG, "GPS fix is now valid with %d satellites. Setting GPS = YES.", my_gps_stat.num_sats);
        send_message(hub_fd, &outgoing_msg);
    }

    return return_code;
}



void maintain_ipc_hub_connect(char *progname)
{
    struct message_record outgoing_msg;
    
    if(hub_fd < 0)	//if we have no connection to the IPC hub
    {
        if( (time(NULL) - last_hub_try) > HUB_RETRY_TIME )	//if we haven't tried the hub in a few seconds
        {
            last_hub_try = time(NULL);				//retry it
            
            hub_fd = connect_to_message_server(progname);    //try and get one
            
            if(hub_fd >= 0)
            {
                //Subscribe to the default status messages
                subscribe_to_default_messages(hub_fd);
        
                //Subscribe to our specific message
                prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_DRIVER_NOTIFY, strlen(MAILBOX_DRIVER_NOTIFY));
                send_message(hub_fd,&outgoing_msg);

                prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_PADDLE_ACK, strlen(MAILBOX_PADDLE_ACK));
                send_message(hub_fd,&outgoing_msg);
                
                prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_VAULT_DROP, strlen(MAILBOX_VAULT_DROP));
                send_message(hub_fd,&outgoing_msg);
                
                prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_TOKEN_MAG, strlen(MAILBOX_TOKEN_MAG));
                send_message(hub_fd,&outgoing_msg);
                
                prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_TOKEN_RFID, strlen(MAILBOX_TOKEN_RFID));
                send_message(hub_fd,&outgoing_msg);
                
                //Ask for a status update
                prepare_message(&outgoing_msg, MAILBOX_STATUS_REQUEST, "", 0);
                send_message(hub_fd,&outgoing_msg);
            }
            else
            {
                fprintf(stderr, "Cannot connect to IPC hub!\n");
            }
        }
    }
}

menutree *mt = NULL;
int redraw_flag = 0;


message_callback_return handle_status_request(struct message_record *msg, void *param)
{
    struct message_record outgoing_msg;
    
    if(hub_fd >= 0)
    {
        prepare_message(&outgoing_msg, MAILBOX_DRIVER_STATUS, &my_driver_status, sizeof(my_driver_status));
        send_message(hub_fd, &outgoing_msg);
        prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
        send_message(hub_fd, &outgoing_msg);
    }

    return MESSAGE_HANDLED_CONT;
}

message_callback_return handle_vault_drop(struct message_record *msg, void *param)
{
    
    if(diu_fd >= 0)
    {
        write(diu_fd, "/V:\r", 4);
    }

    return MESSAGE_HANDLED_CONT;
}

char dup_notify_str[MAX_PAYLOAD_LENGTH] = {0};
int dup_notify_count = 0;
long long dup_notify_usec = 0;


message_callback_return handle_driver_notify(struct message_record *msg, void *param)
{
    int is_dup;
    char dup_text[MAX_PAYLOAD_LENGTH] = {0};
    pixel bgcolor = FBCOLOR_WHITE;
    pixel textcolor = FBCOLOR_BLACK;
    long long dup_usec_delta = 0;
    

    if(strncmp((const char *)(msg->payload), dup_notify_str, MAX_PAYLOAD_LENGTH))
    {
        dup_notify_count = 1;
        strncpy(dup_notify_str, (const char *)(msg->payload), MAX_PAYLOAD_LENGTH - 1);
        dup_notify_str[MAX_PAYLOAD_LENGTH - 1] = '\0';
        is_dup = 0;
        dup_notify_usec = 0;
    }
    else
    {
        dup_notify_count++;
        is_dup = 1;
        dup_usec_delta = get_usec_time() - dup_notify_usec;
        dup_notify_usec = get_usec_time();    
    }

    switch(msg->payload[0])
    {
        case LOGLEVEL_EVENT:
            if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD))
            {
                DIU_ACK_BEEP(diu_fd);
            }
            break;
            
        case LOGLEVEL_REJECT:
            bgcolor = FBCOLOR_LTRED;
            if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD))
            {
                DIU_ERROR_BEEP(diu_fd);
            }
            break;
            
        case LOGLEVEL_ACCEPT:
            bgcolor = FBCOLOR_LTGREEN;
            if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD))
            {
                DIU_ACK_BEEP(diu_fd);
            }
            break;
    
        case LOGLEVEL_ERROR:
            bgcolor = FBCOLOR_RED;
            textcolor = FBCOLOR_CYAN;
            if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD))
            {
                DIU_CRITICAL_BEEP(diu_fd);
            }
            break;
    
        default:
            break;
    }
    
    if(is_dup)
    {
        snprintf(dup_text, MAX_PAYLOAD_LENGTH, "%d x %s", dup_notify_count, &msg->payload[1]);
        replace_diu_message(bgcolor, textcolor, dup_text);
    }
    else
    {
        add_diu_message(bgcolor, textcolor, (char *)(&(msg->payload[1])));
    }
    
    redraw_flag |= 1;
    
    return MESSAGE_HANDLED_CONT;
}

message_callback_return handle_paddle_ack(struct message_record *msg, void *param)
{
    set_paddle_req *pr = (set_paddle_req *)msg->payload;
    
    paddle_req.result = pr->result;
        
    return MESSAGE_HANDLED_CONT;
}

message_callback_return handle_token_diag(struct message_record *msg, void *param)
{
    strncpy(token_diag_string, (const char *)(msg->payload), sizeof(token_diag_string));
    token_diag_string[sizeof(token_diag_string) - 1] = '\0';

    token_diag_serial++;
    
    return MESSAGE_HANDLED_CONT;
}

//----------------------------------
time_t diu_error_burst = 0;
int    diu_error_counter = 0;

static inline int can_report_diu_error()
{
    time_t now = time(NULL);
 
    //If our last potential burst lockout has expired... 
    if( (now - diu_error_burst) >= DIU_ERROR_RATE_LIMIT)
    {
        diu_error_counter = 0;		//reset our burst counter
        diu_error_burst = now;		//and start the "potential burst" time at this message
    }
    
    if(diu_error_counter < DIU_ERROR_BURST_LIMIT)	//if we haven't hit our burst limit...
    {
        diu_error_counter++;				//count this message against our burst limit
        return 1;					//and allow it to pass
    }
    else						//if we have hit our limit
    {
        return 0;					//ignore this message
    }
}
//----------------------------------


int main(int argc, char **argv)
{
    char line[LINE_BUFFER_SIZE] = {0};

    struct message_record incoming_msg;
    struct message_record outgoing_msg;
    
    struct pollfd fds[2];
    int nfd;
    
    int poll_return;
    int read_return;
    
    int i;

    time_t down_time = 0;
    int calibration = 0;

    time_t now;

    int retval = 0;
    int tz = 0;
    int tx = 0;
    int ty = 0;

    time_t last_stale_gps_check = 0;


    if(open_framebuffer())
    {
        fprintf(stderr,"Cannot open framebuffer!\n");
    }

    mt = load_menutree(DRIVER_MENU_FILE);
    
    if(!mt)
    {
        fprintf(stderr, "Error loading %s\n", DRIVER_MENU_FILE);
        return -1;
    }
    else
    {
    
        //Remember a checksum so we don't have to boot a logged in driver for a system-wide HUP if
        //the menu tree hasn't indeed changed...
        md5_of_file(DRIVER_MENU_FILE, menu_checksum);
    
//        print_menu_tree(mt);
        if(init_menutree(mt))
        {
            fprintf(stderr, "Error initializing menu tree from %s\n", DRIVER_MENU_FILE);
        }
        redraw_flag = 1;
    }
    

    //Configure our signal handlers to deal with SIGINT, SIGTERM, etc... and make graceful exits while logging
    configure_signal_handlers(argv[0]);

    //Make an initial attempt to get in touch with the interprocess communication hub (it may not be up yet depending on the start order)
    maintain_ipc_hub_connect(argv[0]);	

    //Register our defualt system message processing callbacks
    register_system_status_callbacks();

    register_dispatch_callback(MAILBOX_STATUS_REQUEST, CALLBACK_USER(1), handle_status_request, NULL);
    register_dispatch_callback(MAILBOX_DRIVER_NOTIFY, CALLBACK_USER(2), handle_driver_notify, NULL);
    register_dispatch_callback(MAILBOX_PADDLE_ACK, CALLBACK_USER(3), handle_paddle_ack, NULL);
    register_dispatch_callback(MAILBOX_VAULT_DROP, CALLBACK_USER(4), handle_vault_drop, NULL);
    register_dispatch_callback(MAILBOX_TOKEN_MAG, CALLBACK_USER(5), handle_token_diag, NULL);
    register_dispatch_callback(MAILBOX_TOKEN_RFID, CALLBACK_USER(6), handle_token_diag, NULL);

    clear_diu_messages();
    

    while( exit_request_status == EXIT_REQUEST_NONE )	//loop until we get asked to exit...
    {

      //DEBUG
      printf("[%lli] heartbeat\n", get_usec_time());
      //DEBUG

        RESET_WATCHDOG();

        maintain_ipc_hub_connect(argv[0]);
    
        if(diu_fd < 0)
        {
            diu_fd = open_rs232_device(DRIVER_UI_PORT, USE_DEFAULT_BAUD, RS232_LINE); 
            
            if(diu_fd < 0)
            {
                fprintf(stderr, "Cannot open serial port %s for DIU!\n", DRIVER_UI_PORT);
            }
            else
            {
                write(diu_fd, "/Q:aK\r", 6);	//Turn on all messages except ACKs for sent commands
            }
        }
    
        now = time(NULL);
        
        //Every second, we want to update the DIU clock (even though it only shows minutes, this covers power events...)
        if((now - last_diu_clock) > 0)
        {
            if(diu_fd)
            {
                set_diu_clock(diu_fd, now);
                last_diu_clock = now;
            }
            
            //Also request a UI redraw if nothing else has, just so that status line gets redrawn
            redraw_flag |= 1;
        }
        
        //Every second we want to check to make sure that our GPS data have note gone stale...
        if((now - last_stale_gps_check) > 0)
        {
            //     If the stale check results in an update to my_gps_stat, we must update any other
            // modules which may be tracking GPS status via the IPC hub.
            if( handle_stale_gps_condition() > 0 )
            {
                //If we have a connection to the IPC hub
                if(hub_fd >= 0)
                {
                    //Go and toss the data to any other modules who happen to care about GPS
                    prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
                    send_message(hub_fd, &outgoing_msg);
                }
            }
            
            // Either way, remember that we did this stale check.
            last_stale_gps_check = now;          
        }
        
        if(hup_request_status)
        {
            unsigned char temp_menu_checksum[MD5_DIGEST_LENGTH];

            hup_request_status = 0;

            //Go and generate a checksum of the new menu file
            md5_of_file(DRIVER_MENU_FILE, temp_menu_checksum);
            
            //if it differs from the old one, reload the menu file...
            if(memcmp(menu_checksum, temp_menu_checksum, MD5_DIGEST_LENGTH))
            {
            
                //Update the remembered checksum to be that of the new menu...
                memcpy(menu_checksum, temp_menu_checksum, MD5_DIGEST_LENGTH);
            
                //Free the old menu tree
                if(mt)
                {
                    free_menutree(mt);
                    mt = NULL;
                }
        
                //Try and load the new one...
                mt = load_menutree(DRIVER_MENU_FILE);
    
                //If that failed, bitch about it!
                if(!mt)
                {
                    fprintf(stderr, "Error loading %s\n", DRIVER_MENU_FILE);
                    return -1;
                }
                else	//otherwise initialize the menu tree
                {
                    if(init_menutree(mt))
                    {
                        fprintf(stderr, "Error initializing menu tree from %s\n", DRIVER_MENU_FILE);
                    }
                    redraw_flag = 1;
                }
            }
        }
    
        //If it is time to send out a driver status update
        if(update_driver_status && (hub_fd >= 0))
        {
            //do so...
            prepare_message(&outgoing_msg, MAILBOX_DRIVER_STATUS, &my_driver_status, sizeof(my_driver_status));
            send_message(hub_fd, &outgoing_msg);
            update_driver_status = 0;
        }
    
        //If a paddle change request has resulted in a change
        if(check_paddle_request(mt))
        {
            //do a redraw of the UI
            redraw_flag |= 1;
        }
    
        //If we have to redraw the UI
        if(redraw_flag && !calibration)
        {
            //Redraw the menu reflecting any changes from the last touchscreen input
            //or other stimulus
            draw_menu(mt);			

            #ifdef TOUCHSCREEN_QUIET
                write(diu_fd, "/Q:t\r", 5);		//Un-Quiet the touch screen, now that we've responded to the user we want
            #endif                                      //to hear if they have any further input to give us...
            
            redraw_flag = 0;			//Clear the 'redraw required' flag
        }
        
        nfd = 0;
        
        if(hub_fd >= 0)
        {
            fds[nfd].fd = hub_fd;
            fds[nfd].events = POLLIN;
            fds[nfd].revents = 0;
            nfd++;
        }
        
        if(diu_fd >= 0)
        {
            fds[nfd].fd = diu_fd;
            fds[nfd].events = POLLIN;
            fds[nfd].revents = 0;
            nfd++;
        }
    
        if(nfd > 0)	//if we have any file descriptors, poll them
        {
            poll_return = poll(fds, nfd, POLL_TIMEOUT);
        }
        else		//otherwise, whistle and look busy
        {
            poll_return = 0;	//(this keeps us from buringing 100% cpu cycles if we don't have contact with either
            sleep(1);		//the IPC hub or the DIU hardware).
        }

        //--------------------------------------------------------------------------------------------------
    
        if(poll_return < 1)	//if poll didn't net us any work to do, 
        {
            continue;		//lets try again
        }    
    
        for(i = 0; i < nfd; i++)	//Loop through all polled file descriptors
        {
          
            if( fds[i].fd == diu_fd )		//If we're looking at the DIU...
            {

                if(fds[i].revents & (POLLHUP | POLLERR | POLLNVAL))	//if poll says our serial port has become bogus...
                {
                    fprintf(stderr, "This is very odd... Poll returned flags %d on our serial port...\n", fds[i].revents);
                    
                    close(diu_fd);	//close it
                    diu_fd = -1;	//flag it invalid
                    break;		//and break out of the for loop to allow the while to cycle
                }

                if(fds[i].revents & POLLIN)
                {
                    read_return = read(fds[i].fd, line, sizeof(line));
                    
                    if(read_return > 0)
                    {
                        char *trav = line;
                        
                        line[read_return] = '\0';
                        strip_crlf(line);
                        
                        while(*trav && (*trav != '/') )             //advance until EOL or we hit our start sentinel
                        {
                            trav++;
                        }
                        
                        //Check to see that our address header is intact...
                        if( (trav[0] == '/') && (trav[2] == ':') )
                        {
                            switch(trav[1])
                            {
                                case 'T':	//-----------------------------------"/T:" means it's a touchscreen event
                                    trav += 3;	//advance past the header
                                      
                                    retval = sscanf(trav, "%x,%x,%x", &tz, &tx, &ty);
                                    
                                    if(retval == 3)
                                    {
                                        if(tz)
                                        {
                                        
                                            if(down_time == 0)
                                            {
                                                down_time = time(NULL);
                                            }
                                            else
                                            {
                                                if( (time(NULL) - down_time) > TS_CALIB_HOLD_TIME)
                                                {
                                                    begin_touchscreen_calibration();
                                                    calibration = 1;
                                                }
                                            }
                                            
                                            
                                            if(!calibration)
                                            {                                        
                                                //printf("Touch at (%d, %d)\n", translate_ts_x(tx), translate_ts_y(ty));
                                                if(process_pen(mt, translate_ts_x(tx), translate_ts_y(ty), 1) > 0)
                                                {
                                                    #ifdef TOUCHSCREEN_QUIET
                                                        write(diu_fd, "/Q:T\r", 5);
                                                    #endif
                                                    redraw_flag = 1;
                                                }
                                            }
                                            else
                                            {
                                                if(advance_touchscreen_calibration(tx, ty, tz))
                                                {
                                                    calibration = 0;
                                                    redraw_flag = 1;
                                                }
                                                else
                                                {
                                                    draw_touchscreen_calibration();
                                                }
                                            }
                                        }
                                        else
                                        {
                                            down_time = 0;
                                            //printf("Touch Release\n");
                                            if(!calibration)
                                            {
                                                if(process_pen(mt, 0,0,0) > 0)
                                                {
                                                    #ifdef TOUCHSCREEN_QUIET
                                                        write(diu_fd, "/Q:T\r", 5);
                                                    #endif
                                                    redraw_flag = 1;
                                                }
                                            }
                                            else
                                            {
                                                if(advance_touchscreen_calibration(tx, ty, tz))
                                                {
                                                    calibration = 0;
                                                    redraw_flag = 1;
                                                }
                                                else
                                                {
                                                    draw_touchscreen_calibration();
                                                }
                                            }
                                        }
                                    }
                                      
                                    break;
                            
                                case 'G':	//-----------------------------------"/G:" means it is a new GPS input
                                    trav += 3;	//advance past the header
                                    
                                    //If this GPS update constitutes a meaningful piece of data
                                    if(update_gps(trav) > 0)	
                                    {
                                        //and we have a connection to the IPC hub
                                        if(hub_fd >= 0)
                                        {
                                            //Go and toss the data to any other modules who happen to care about GPS
                                            prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
                                            send_message(hub_fd, &outgoing_msg);
                                        }
                                        
                                        last_stale_gps_check = now;  //Remember that we did a stale GPS check as part of our update.
                                    }
                                    break;
                            
                                case '*':	//handle warnings
                                case '#':	//debugs
                                case '!':	//and errors
                                
                                    //If this DIU error/debug message has not run afoul of the rate limiting policy...
                                    if( can_report_diu_error() )
                                    {
                                        format_log_message(&outgoing_msg, trav[1], "DIU Reports: %s", trav + 3);	//send them all to the log server
                                        send_message(hub_fd, &outgoing_msg);			
                                    
                                        if(trav[1] == '!')	//but in the case of errors, send them to the driver too
                                        {
                                            format_driver_message(&outgoing_msg, trav[1], "DIU Reports: %s", trav + 3);
                                            send_message(hub_fd, &outgoing_msg);
                                        }
                                    }
                                    break;
                            
                                default:	//ignore any message addresses that we don't know what to do with
                                    printf("Ignoring command \"%s\"\n", trav);
                                    break;
                            }
                        }
                        else
                        {
//                            printf("Ignoring non-command line \"%s\"\n", trav);
                        }
                    }
                    else
                    {
                        fprintf(stderr, "Read from %s returned %d!\n", DRIVER_UI_PORT, read_return);
            
                        close(diu_fd);	//close it
                        diu_fd = -1;	//flag it invalid
                        break;		//and break out of the for loop to allow the while to cycle
                    }
                }
                
            }
            else if( fds[i].fd == hub_fd )	//If we're looking at the IPC hub...
            {
                if(fds[i].revents & (POLLHUP | POLLERR | POLLNVAL))	//if poll says our connection to the IPC hub has died...
                {
                    fprintf(stderr, "The connection to the IPC hub has gone away...\n");	//complain
                    
                    close(hub_fd);	//close it
                    hub_fd = -1;	//flag it dead
                    break;		//break out of the for loop
                }
                
                if(fds[i].revents & POLLIN)	//if we have mail in any of our mailboxes...
                {
                    read_return = get_message(hub_fd, &incoming_msg);
                    
                    if(read_return < 0)
                    {
                        fprintf(stderr, "The connection to the IPC hub has gone away...\n");	//complain
                    
                        close(hub_fd);	//close it
                        hub_fd = -1;	//flag it dead
                        break;		//break out of the for loop
                    }
                    else
                    {
                        message_callback_return msg_status;
                        msg_status = process_message(&incoming_msg);
                    }
                
                }
            
            } 
        }    
    }

    set_color(255,255,255);
    cls();
    present_framebuffer();
    close_framebuffer();
 
    if(hub_fd >= 0)
    {
        close(hub_fd);
    }
    
    if(diu_fd >= 0)
    {
        write(diu_fd, "/C:----\r",8);
        close(diu_fd);
    }
        
    return 0;
}

