#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdint.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>

void bail();
void sig_handler(int signum);

int src = -1;


int main(int argc, char *argv[]){
    
    if (argc != 2){
        fprintf(stderr,"USAGE:\n %s source-file\n", argv[0]);
        return -1;
    }
    
    // Register Signal Handler
    signal(SIGINT, sig_handler);
    signal(SIGTERM, sig_handler);
    
    // Open Destination File
    src = open(argv[1], O_RDONLY);
    if(src == -1){
        perror("Failed to open file");
        bail();
        return -1;
    }
    
    char buffer[8];
    char* buffer_p;
    uint16_t* data;
    size_t cnt, bufflen;
    
    while(1){
        buffer_p = buffer;
        cnt = 0;
        bufflen = 8;

        do {
            cnt = read(src, buffer_p, bufflen);
            buffer_p    += cnt;
            bufflen     -= cnt;
            //No data available, wait and retry
            if(cnt == 0){
                usleep(500000);
                continue;
            }
            //Error, bail out
            else if(cnt < 0){
                perror("Read failed");
                bail();
                return -1;
            }
        } while (bufflen > 0);
        
        
        data = buffer;
        
        printf("\nADC_DATA1_MAX: %u\nADC_DATA2_MAX: %u\nSCALER_MAX: %u\nDAC_MAX: %u\n", data[0], data[1], data[3], data[2]);
    }
    
    //Never Reached
    bail();
    return -1;
}

void bail(){
    if(src != -1){
        (void)close(src);
    }
}

void sig_handler(int signum){
    printf("Caught signal %d, terminating\n", signum);
    bail();
    exit(0);
}
