#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

#include "ciff.h"
#include "caff.h"

int main(int argc, char **argv)
{
    if (argc != 3 || (strcmp(argv[1], "-ciff") != 0 && strcmp(argv[1], "-caff") != 0))
    {
        printf("Usage: %s <-ciff|-caff> <input.ciff|input.caff>\n", argv[0]);
        return -1;
    }
    bool is_caff = strcmp(argv[1], "-caff") == 0;
    char *input_path = argv[2];
    char jpg_path[MAX_PATH_LEN + 1];
    strncpy(jpg_path, input_path, MAX_PATH_LEN-1);
    char *extension = strrchr(jpg_path, '.');
    if (extension)
    {
        strncpy(extension, ".jpeg", MAX_PATH_LEN - (extension - jpg_path));
    }
    printf("%s\n", jpg_path);
    CIFF *ciff = NULL;
    CAFF *caff = NULL;
    if (is_caff)
    {
        caff = caff_parse_file(input_path);
        if(caff != NULL && caff->animations.length >= 1) {
            ciff = caff->animations.array[0].ciff;
        }
    }
    else
    {
        FILE *ciff_file = fopen(input_path, "rb");
        ciff = read_ciff(ciff_file);
        fclose(ciff_file);
    }
    if (!ciff)
    {
        printf("Failed to read CIFF file: %s\n", input_path);
        return -1;
    }

    generate_jpg(ciff, jpg_path);
    if (is_caff)
    {
        caff_free(caff);
    }
    else
    {
        free_ciff(ciff);
    }

    return 0;
}