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

#define NUM_LEVELS  30

#define GETBYTE() (*(p++))

int main(int argc, char *argv[])
{
    FILE *f = fopen("../data/MAPES.BAL", "rb");
    fseek(f, 0, SEEK_END);
    int filesize = ftell(f);
    fseek(f, 0, SEEK_SET);
    char *buffer = (char *)malloc(filesize);
    fread(buffer, filesize, 1, f);
    fclose(f);
    char *p = buffer;

    FILE *fp = fopen("../data/mapes.txt", "w");

    for (int i = 0; i<NUM_LEVELS; ++i)
    {
        fprintf(fp, "LEVEL %i\n", i);

        fprintf(fp, "\n");

        fprintf(fp, "tileset = %i\n", GETBYTE());
        p++;
        fprintf(fp, "orientacio = %i\n", GETBYTE());
        fprintf(fp, "arounders = %i\n", GETBYTE());
        fprintf(fp, "necessaris = %i\n", GETBYTE());

        fprintf(fp, "\n");

        fprintf(fp, "parar = %i\n", GETBYTE());
        fprintf(fp, "cavar = %i\n", GETBYTE());
        fprintf(fp, "escalar = %i\n", GETBYTE());
        fprintf(fp, "perforar = %i\n", GETBYTE());
        fprintf(fp, "escalera = %i\n", GETBYTE());
        fprintf(fp, "pasarela = %i\n", GETBYTE());
        fprintf(fp, "corda = %i\n", GETBYTE());

        fprintf(fp, "\n");

        char tiles[200];
        for (int x=0; x<20; ++x)
            for (int y=0; y<10; ++y)
                tiles[x+y*20] = GETBYTE();

        for (int y=0; y<10; ++y)
            for (int x=0; x<20; ++x)
                if (tiles[x+y*20] == -3) fprintf(fp, "inici = %i %i\n", x, y);

        for (int y=0; y<10; ++y)
            for (int x=0; x<20; ++x)
                if (tiles[x+y*20] == -2) fprintf(fp, "final = %i %i\n", x, y);

        fprintf(fp, "\n");

        for (int y=0; y<10; ++y) {
            for (int x=0; x<20; ++x) {
                const char tile = tiles[x+y*20]<0 ? 0 : tiles[x+y*20]+1;
                fprintf(fp, "%i ", tile);
            }
            fprintf(fp, "\n");
        }
        fprintf(fp, "\n");
        fprintf(fp, "\n");
    }
    fclose(fp);
    free(buffer);

    return 0;
}