#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>

#define BUFFER_SIZE 255
#define IN_MEM (inmem!=0)

typedef struct power_data {
    float power; // Power value
    long ts;     // Associated timestamp
    long nsecs;  // Associated nanosecs
} power_data;

int main(int argc, char *argv[])
{  
    if(argc != 4){
        printf("Usage: %s <device-id> <nread> <inmem>\n\
        \rFor <device-id>, see folder name in /sys/kernel/ina260/",argv[0]);
        exit(1);
    }

    char *deviceid=argv[1];
    int nread=atoi(argv[2]);
    int inmem=atoi(argv[3]);

    if(nread<=0){
        printf("<nread> must be greater than 0\n");
        exit(3);
    }

    // File to read
    char path[255];
    sprintf(path, "/sys/kernel/ina260/%s/power", deviceid);

    // Open file
    int fd;
    char buff[BUFFER_SIZE];
    fd = open(path, O_RDONLY);
    if(fd<0){
        perror(path);
        exit(2);
    }

    // Check if its in memory reading
    power_data *data;
    if(IN_MEM){
        data=malloc(sizeof(power_data)*nread);
        if(data == NULL){
            perror("Cannot allocate enough memory for in memory reads");
            exit(4);
        }
    }

    // Perform reads
    float power=-1;
    struct timespec power_ts;
    clock_gettime(CLOCK_REALTIME, &power_ts);

    printf("startat:%ld\n", power_ts.tv_sec);
    for(int i=0;i<nread;i++){
        read(fd, buff, BUFFER_SIZE);
        // Get power measurement timestamp:
        clock_gettime(CLOCK_REALTIME, &power_ts);
        power=atof(buff);
        if(IN_MEM){
            data[i].power=power;
            data[i].ts=power_ts.tv_sec;
            data[i].nsecs=power_ts.tv_nsec;
        }
        else{
            printf("%s %11ld %10ld> Power is %fW\n",deviceid, power_ts.tv_sec,power_ts.tv_nsec,power);
        }
        lseek(fd,0,SEEK_SET);
    }
    close(fd);

    if(IN_MEM){
        // We only print now (most I/O will happend at the end and this must be visible on the results)
        for(int i=0;i<nread;i++){
            printf("%s %11ld %10ld> Power is %fW\n",deviceid, data[i].ts, data[i].nsecs, data[i].power);
        }
        free(data);
    }
    printf("endat:%ld\n", time(NULL));
    return 0;
}
