#include "parser.h"

/*
    I've separated this out into its own file
    so it can be used anywhere, and be compiled
    with any C standard that supports strtok_r.

*/

size_t get_file_len(FILE *file) {
    fseek(file, 0, SEEK_END);
    unsigned int len = ftell(file);
    fseek(file, 0, SEEK_SET);
    return len;
}

/*
    loads a files and mallocates a buffer 
    and returns a pointer to it.

    remember to free the buffer when you're done.
*/
char *load_file(const char *path) {
    FILE *file = fopen(path, "r");
    if (file == NULL) {
        printf("%s\n", "Could not open file.");
        return NULL;
    }

    size_t len = get_file_len(file);

    char *buffer = malloc(len);

    #pragma GCC diagnostic ignored "-Wunused-result"
    fread(buffer, len, 1, file);
    fclose(file);
    return buffer;
}

char *get_next_line(char* buffer, bool clear) {
    static char* saveptr;
    static char *line;

    if (clear) {
        saveptr = NULL;
        line = NULL;
        return NULL;
    }

    if (saveptr == NULL) {
        line = strtok_r(buffer, "\n", &saveptr);
    } else {
        if (line == NULL) {
            saveptr = NULL;
            return NULL;
        }

        line = strtok_r(NULL, "\n", &saveptr);
    }

    return line;
}

char *get_next_token(char *buffer, char *delim, bool clear) {
    static char *saveptr;
    static char *token;

    if (clear) {
        saveptr = NULL;
        token = NULL;
        return NULL;
    }

    if (saveptr == NULL) {
        token = strtok_r(buffer, delim, &saveptr);
    } else {
        if (token == NULL) {
            saveptr = NULL;
            return NULL;
        }

        token = strtok_r(NULL, delim, &saveptr);
    }

    return token;
}