#include <stdio.h>
#include "tape.hpp"
#include "program.hpp"

enum {
    start_state = 0,
    halt_state  = -1,
    rule_fields = 5
};

enum read_status {
    read_ok,
    read_end,
    read_error
};

static read_status read_rule(FILE *file, rule &r)
{
    int fields = fscanf(file, " %d %c %c %c %d",
                        &r.state, &r.read, &r.write, &r.move, &r.next);

    switch (fields) {
    case rule_fields:
        return read_ok;
    case EOF:
        return read_end;
    default:
        return read_error;
    }
}

static bool valid_move(char move)
{
    return move == 'L' || move == 'R' || move == 'S';
}

static bool read_program(FILE *file, Program &program)
{
    rule r;
    read_status status;

    while ((status = read_rule(file, r)) == read_ok) {
        if (!valid_move(r.move)) {
            fprintf(stderr, "Invalid movement: %c\n", r.move);
            return false;
        }
        program.Add(r);
    }

    if (status == read_error || program.Empty()) {
        fprintf(stderr, "Invalid or empty rule file\n");
        return false;
    }

    return true;
}

static bool load_program(const char *filename, Program &program)
{
    FILE *file = fopen(filename, "r");
    if (!file) {
        perror(filename);
        return false;
    }

    bool ok = read_program(file, program);
    fclose(file);
    return ok;
}

static bool run(const Program &program, Tape &tape)
{
    int state = start_state;

    while (state != halt_state) {
        const rule *r = program.Find(state, tape.Read());
        if (!r) {
            fprintf(stderr, "No rule for state %d, symbol '%c'\n",
                    state, tape.Read());
            return false;
        }

        tape.Write(r->write);
        tape.Move(r->move);
        state = r->next;
    }

    return true;
}

int main(int argc, char **argv)
{
    if (argc != 3) {
        fprintf(stderr, "Usage: %s rules.txt input\n", argv[0]);
        return 1;
    }

    Program program;
    bool ok = load_program(argv[1], program);
    if (!ok)
        return 1;

    Tape tape(argv[2]);

    ok = run(program, tape);
    if (!ok)
        return 1;

    tape.Print();
    return 0;
}
