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

char stack[100][10];
int top = -1;
int pos = 0;
char input[100];

void push(const char *s)
{
    strcpy(stack[++top], s);
}

void pop()
{
    top--;
}

void printStack()
{
    for (int i = 0; i <= top; i++)
        printf("%s", stack[i]);
    printf("\n");
}

int reduce(char lookahead)
{
    if (top >= 0 &&
        stack[top][0] >= 'a' &&
        stack[top][0] <= 'z')
    {
        pop();
        push("F");
        return 1;
    }

    if (top >= 2 &&
        strcmp(stack[top-2], "(") == 0 &&
        strcmp(stack[top-1], "E") == 0 &&
        strcmp(stack[top], ")") == 0)
    {
        pop(); pop(); pop();
        push("F");
        return 1;
    }

    if (top >= 2 &&
        strcmp(stack[top-2], "T") == 0 &&
        strcmp(stack[top-1], "*") == 0 &&
        strcmp(stack[top], "F") == 0)
    {
        pop(); pop(); pop();
        push("T");
        return 1;
    }

    if (top >= 0 &&
        strcmp(stack[top], "F") == 0)
    {
        if (lookahead == '*') return 0;
        pop();
        push("T");
        return 1;
    }

    if (top >= 2 &&
        strcmp(stack[top-2], "E") == 0 &&
        strcmp(stack[top-1], "+") == 0 &&
        strcmp(stack[top], "T") == 0)
    {
        if (lookahead == '*') return 0;
        pop(); pop(); pop();
        push("E");
        return 1;
    }

    if (top >= 0 &&
        strcmp(stack[top], "T") == 0)
    {
        if (lookahead == '+' || lookahead == '*') return 0;
        pop();
        push("E");
        return 1;
    }

    return 0;
}

int main()
{
    printf("Enter an Expression:\n");
    fgets(input, 100, stdin);

    while (input[pos])
    {
        if (isspace(input[pos]))
        {
            pos++;
            continue;
        }

        char temp[2] = {input[pos], '\0'};
        push(temp);
        pos++;

        printf("Shift: ");
        printStack();

        while (reduce(input[pos]))
        {
            printf("Reduce: ");
            printStack();
        }
    }

    while (reduce('\0'))
    {
        printf("Reduce: ");
        printStack();
    }

    if (top == 0 && strcmp(stack[0], "E") == 0)
        printf("String Accepted\n");
    else
        printf("String Rejected\n");

    return 0;
}