#include "decode.h"
#include <stdio.h>
#include <stdint.h>

int decode_main(int argc, char* argv[])
{
    FILE *input_file = fopen(argv[2], "rb");
    if (!input_file) {
        fprintf(stderr, "Error opening input file: %s\n", argv[2]);
        return 1;
    }
    FILE *output_file = fopen(argv[3], "wb");
    if (!output_file) {
        fprintf(stderr, "Error opening output file: %s\n", argv[3]);
        fclose(input_file);
        return 1;
    }

    uint8_t buffer[2048], decoded[1024];
    size_t bytes_read;
    //    // b_r 
    while ((bytes_read = fread(buffer, 1, sizeof(buffer), input_file)) > 0) {
        if (bytes_read % 2 != 0) { //odd check
            size_t extra = fread(buffer + bytes_read, 1, 1, input_file);
            if (extra == 1) { // successfully read 
                bytes_read++;
            } else { // error reading the extra byte
                fclose(input_file);
                fclose(output_file);
                return 1;
            }
        }

        size_t decoded_size = bytes_read / 2;
        for (size_t i = 0; i < decoded_size; i++) {
            decoded[i] = decode_combine_nibbles(buffer[i], buffer[i + decoded_size]);
        }
        fwrite(decoded, 1, decoded_size, output_file);
    }

    fclose(input_file);
    fclose(output_file);
    printf("Decoding completed successfully.\n");
    return 0;
}
