#include <stdio.h>
// #include <sys/stat.h>
#include <stdlib.h>
#include <stdint.h>

const char* filename = "GLED_0201.bin";

static int ReadBinary(void)
{
    /* Declare Handle for file */ 
    FILE* BinFile;
    /* open file in read (r) and binary (b) mode */
    BinFile = fopen(filename, "rb");

    if (BinFile == NULL)
    {
       printf("Error! opening file\n");
       perror("fopen");

       // Program exits if the file pointer returns NULL.
       return 1;
   }

//    struct stat sb;
//    if (stat(filename, &sb) == -1)
//    {
//        perror(stat);
//        exit(1);
//    }
   
//    char* file_contents = malloc(sb.st_size);
//    fread(file_contents, sb.st_size, 1, BinFile);   

    fseek(BinFile, 0, SEEK_END);
    size_t file_size = ftell(BinFile);
    // printf("file size = %d bytes",file_size);
    fseek(BinFile, 0, SEEK_SET);

    uint8_t* file_buffer;
    file_buffer = malloc(file_size*sizeof(uint8_t));  //new uint8_t[file_size];

    for (int i=0;i<file_size; i++)
    {
        fread(&file_buffer[i], sizeof(uint8_t), 1, BinFile);
        printf("%02X", file_buffer[i]);
    }
    fclose(BinFile);

//    printf("\nfile size = %d bytes",file_size);

   return file_size;
}

static void WriteBinary(void)
{
    /* Declare Handle for file */ 
    FILE* write_hdl;
    /* open file in read (r) and binary (b) mode */
    write_hdl = fopen("write.bin", "wb");

    if (write_hdl == NULL)
    {
       printf("Error! opening file\n");
       perror("fopen");

       // Program exits if the file pointer returns NULL.
    //    return 1;
   }

   /* testing write*/
    int test_write_array[16] = {0x43, 0x43, 0x31, 0x33, 0x78, 0x32, 0x52, 0x31, 0xd0, 0x1d, 0x81, 0xe5, 0x03, 0x01, 0xbf, 0xff};

    for (int i=0;i<16; i++)
    {
        fwrite(&test_write_array[i], sizeof(uint8_t), 1, write_hdl);
    }
    fclose(write_hdl);
    printf("Done writing..!!!\n");
}

int main()
{

    size_t file_size1 = ReadBinary();
    printf("\nfile size = %d bytes",file_size1);

    // WriteBinary();

    return 0;
}