#include "parse.h"

bool reset_parse = false;
char* parse_word = NULL;
int parse_line = 1;
int parse(char* l, size_t len, bool (*is_break)(char), bool debug)
{
    static char last_char;
    static int i = 0;
    static int nl = 0;
    if (reset_parse)
    {
        parse_line = 1;
        i = 0;
        nl = 0;
        last_char = 0;
        reset_parse = false;
    }

    parse_word = NULL;

    while (i < len)
    {
        char c = l[i];
        if (c == 0) c = last_char;
        i++;
        if (debug)
        {
            printf("Char@%d %d %c\n", i, c, c);
        }
        if (is_break(c) || c == '\n')
        {
            if (parse_word)
            {
                i--;
                l[i] = 0;
                last_char = c;
                nl = false;
                return WORD;
            }
            else if (c == '\n')
            {
                nl++;
                parse_line++;
                if (nl == 1)
                {
                    return NL;
                }
                else if (nl == 2)
                {
                    return BREAK;
                }
            }
        }
        else
        {
            if (parse_word == NULL) parse_word = l + (i - 1);
        }
    }

    if (parse_word) return WORD;

    return DONE;
}
