/*************************
 * Owen Sullivan
 * CPSC 2310 Fall 22
 * Lab 8
 * Username: opsulli
 * Instructor: Dr. Yvon Feaster
*************************/

#include "functions.h"

int main(int argc, char **argv) {

    // Check that the correct number of command-line arguments are
    // supplied at runtime
    assert(argc == 3);

    // Open input and output files in binary mode
    FILE *inFile = fopen(argv[1], "rb");
    FILE *outFile = fopen(argv[2], "wb");

    // Check that both files opened successfully
    assert(inFile != NULL);
    assert(outFile != NULL);

    // Create a header_t object and set it to the return value of readHeader
    header_t header = readHeader(inFile);

    // Call writeHeader, passing the output file pointer and the header object
    writeHeader(outFile, header);

    // Create and allocate a pixel_t pointer object with the size of
    // the number of pixels (width * height)
    pixel_t *image = malloc(header.width * header.height * sizeof(pixel_t));

    int j = 0;
    // Loop until the end of the input file
    while (!feof(inFile)) {

        // Read the binary data for r, g, and b values
        fread(&image[j].r, sizeof(unsigned char), 1, inFile);
        fread(&image[j].g, sizeof(unsigned char), 1, inFile);
        fread(&image[j].b, sizeof(unsigned char), 1, inFile);

        j++;

    }

    // Loop through the number of pixels (minus 1 since j was incremented
    // again after reading the last pixel values)
    for (int i = 0; i < (j - 1); i++) {

        // Write the binary data for r, g, and b values to the output file
        fwrite(&image[i].r, sizeof(unsigned char), 1, outFile);
        fwrite(&image[i].g, sizeof(unsigned char), 1, outFile);
        fwrite(&image[i].b, sizeof(unsigned char), 1, outFile);

    }

    // Free the memory for the pixel_t pointer object
    free(image);

    return 0;

}