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

void Tape::Append(char symbol)
{
    Cell *p = new Cell(symbol);

    if (last) {
        last->right = p;
        p->left = last;
    } else {
        first = p;
    }

    last = p;
}

void Tape::Prepend(char symbol)
{
    Cell *p = new Cell(symbol);

    if (first) {
        first->left = p;
        p->right = first;
    } else {
        last = p;
    }

    first = p;
}

Tape::Tape(const char *input)
    : first(0), last(0), head(0)
{
    for (const char *p = input; *p; ++p)
        Append(*p);

    if (!first)
        Append(blank);

    head = first;
}

Tape::~Tape()
{
    while (first) {
        Cell *next = first->right;
        delete first;
        first = next;
    }
}

void Tape::Move(char direction)
{
    if (direction == 'R') {
        if (!head->right)
            Append(blank);
        head = head->right;
    } else if (direction == 'L') {
        if (!head->left)
            Prepend(blank);
        head = head->left;
    }
}

void Tape::Print() const
{
    Cell *begin = first, *end = last;

    while (begin && begin->symbol == blank)
        begin = begin->right;
    while (end && end->symbol == blank)
        end = end->left;

    if (!begin) {
        puts("(blank tape)");
        return;
    }

    for (Cell *p = begin; p != end->right; p = p->right)
        putchar(p->symbol);

    putchar('\n');
}
