#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string>
#include "../source/gif.c"

#define NUM_RESOURCES       39

const char *resources[NUM_RESOURCES] = {
    "../data/final01.GIF",
    "../data/final02.GIF",
    "../data/final03.GIF",
    "../data/final04.GIF",
    "../data/final05.GIF",
    "../data/intro01.GIF",
    "../data/intro02.GIF",
    "../data/intro03.GIF",
    "../data/intro04.GIF",
    "../data/intro05.GIF",
    "../data/intro06.GIF",
    "../data/menuprin.gif",
    "../data/mort.gif",
    "../data/postfase.gif",
    "../data/prefase.gif",
    "../data/SEQ11.GIF",
    "../data/SEQ12.GIF",
    "../data/SEQ13.GIF",
    "../data/SEQ14.GIF",
    "../data/SEQ21.GIF",
    "../data/SEQ22.GIF",
    "../data/SEQ31.GIF",
    "../data/SEQ32.GIF",
    "../data/SEQ41.GIF",
    "../data/SEQ42.GIF",
    "../data/SEQ51.GIF",
    "../data/SEQ52.GIF",
    "../data/SEQ61.GIF",
    "../data/SEQ71.GIF",
    "../data/SEQ72.GIF",
    "../data/SEQ73.GIF",
    "../data/SEQ74.GIF",
    "../data/tiles.gif",
    "../data/boto.gif",
    "../data/marca.gif",
    "../data/marcador.gif",
    "../data/puerta.gif",
    "../data/sprites.gif",
    "../data/aigua.gif"
};

uint32_t main_palette[256];
int num_entries = 0;

int main(int argc, char *argv[])
{
    for (int i=0; i<256; ++i) main_palette[i]=0;

    for (int i = 0; i<NUM_RESOURCES; ++i)
    {
        const char *resourcename = resources[i];
        FILE *f = fopen(resourcename, "rb");
        fseek(f, 0, SEEK_END);
        int filesize = ftell(f);
        fseek(f, 0, SEEK_SET);
        uint8_t *buffer = (uint8_t *)malloc(filesize);
        fread(buffer, filesize, 1, f);
        fclose(f);
        uint16_t w, h;
        uint8_t *pixels = LoadGif(buffer, &w, &h);
        int paletteSize;
        uint32_t *pal = LoadPalette(buffer, &paletteSize);
        free(buffer);

        bool used[256];
        for (int i=0; i<256; ++i) used[i] = false;

        for (int y=0; y<h; ++y)
            for (int x=0; x<w; ++x)
                used[pixels[x+y*w]] = true;
        
        for (int i=0; i<256; ++i)
            if (used[i])
            {
                bool found = false;
                for (int j=0; j<256; ++j) if (main_palette[j] == pal[i]) found = true;
                if (!found) main_palette[num_entries++] = pal[i];
            }
        free(pixels);
        free(pal);
    }
    printf("Num entries: %i\n", num_entries);

    FILE *f = fopen("paleta.pal", "w");
    fprintf(f, "JASC-PAL\n");
    fprintf(f, "0100\n");
    fprintf(f, "%i\n", num_entries);
    for (int i=0; i<num_entries; ++i) fprintf(f, "%i %i %i\n", (main_palette[i]>>16)&0xff, (main_palette[i]>>8)&0xff, main_palette[i]&0xff);
    fclose(f);

    return 0;
}