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

namespace textfile
{
    char *buffer = nullptr;
    int fsize = 0;
    int p = 0;

    const bool open(std::string filename)
    {
        FILE *f = fopen(filename.c_str(), "rb");
        if (!f) { printf("ERROR AL OBRIR EL ARXIU\n"); return false; }
        fseek(f, 0, SEEK_END);
        fsize = ftell(f);
        fseek(f, 0, SEEK_SET);
        buffer = (char*)malloc(fsize);
        fread(buffer, fsize, 1, f);
        fclose(f);
        p = 0;

        return true;
    }

    void close()
    {
        free(buffer);
    }

    std::string getNextToken()
    {
        char token[255];
        int tpos = 0;

        // Ignore whitespace
        while (p<fsize && buffer[p]<=32 ) p++;

        // Grab token
        while (p<fsize && buffer[p]>32 ) token[tpos++]=buffer[p++];
        token[tpos]=0;

        return std::string(token);
    }

    const bool searchToken(std::string token)
    {
        while (p<fsize && getNextToken() != token) p++;
        return p<fsize;
    }

    std::string getStringValue(std::string token)
    {
        textfile::searchToken(token);
        textfile::searchToken("=");
        return textfile::getNextToken();
    }

    const int getIntValue(std::string token)
    {
        return std::stoi(getStringValue(token));
    }
}

int main(int argc, char *argv[])
{
    textfile::open("../data/mapes.txt");
    int num;

    do {
        textfile::searchToken("LEVEL");
        std::string token = textfile::getNextToken();
        num = std::stoi(token);
    } while (num != std::stoi(std::string(argv[1])));

    printf("tileset = %i\n", textfile::getIntValue("tileset") );
    printf("orientacio = %i\n", textfile::getIntValue("orientacio") );
    printf("arounders = %i\n", textfile::getIntValue("arounders") );
    printf("necessaris = %i\n", textfile::getIntValue("necessaris") );

    printf("parar = %i\n", textfile::getIntValue("parar") );
    printf("cavar = %i\n", textfile::getIntValue("cavar") );
    printf("escalar = %i\n", textfile::getIntValue("escalar") );
    printf("perforar = %i\n", textfile::getIntValue("perforar") );
    printf("escalera = %i\n", textfile::getIntValue("escalera") );
    printf("pasarela = %i\n", textfile::getIntValue("pasarela") );
    printf("corda = %i\n", textfile::getIntValue("corda") );

    int a = textfile::getIntValue("inici");
    int b = std::stoi(textfile::getNextToken());
    printf("inici = %i, %i\n", a, b );

    a = textfile::getIntValue("final");
    b = std::stoi(textfile::getNextToken());
    printf("final = %i, %i\n", a, b );

    textfile::close();
    return 0;
}