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

#define MAX_INSTR 100
#define LEFT 0
#define RIGHT 1
#define SAME_AS 2
#define UNKNOWN -1


typedef struct{
    int operacao;
    int operando;
}instr_t;

void decodificar_instr(char *instr, int* operacao, int* operando){

    char sub_str[10];

    sscanf(instr,"%[^0-9]s",sub_str);
    if (strcmp(sub_str,"LEFT")==0){
        *operacao = LEFT;
        *operando = UNKNOWN;
    }
    else if (strcmp(sub_str,"RIGHT")==0){
        *operacao = RIGHT;
        *operando = UNKNOWN;
    }
    else if (strcmp(sub_str,"SAME AS ")==0){
        *operacao = SAME_AS;
        sscanf(instr+8,"%d",operando);
    }
    else{
        printf("Erro de compilacao\n");
        exit(1);
    }
}

void compilar_programa(char instr[MAX_INSTR][40], int n_instr, instr_t programa[]){
    int operacao, operando;
    for (int i=0;i<n_instr;i++){
        decodificar_instr(instr[i], &operacao, &operando);
        programa[i].operacao = operacao;
        if (operando != UNKNOWN){
            programa[i].operando = operando-1;
        }
        else{
            programa[i].operando = operando;
        }
    }
}

void dump_programa(instr_t programa[], int n_instr){
    for (int i=0;i<n_instr;i++){
        printf("%2d - %d %d\n",i, programa[i].operacao, programa[i].operando);
    }
}


void ler_programa(char instr[MAX_INSTR][40],int *n_instr){
    printf("Digite o numero de instrucoes\n");
    scanf("%d",n_instr);
    getc(stdin);

    printf("Digite as instrucoes\n");

    for (int i=0;i<*n_instr;i++){
        gets(instr[i]);
    }
}

int executar_programa(instr_t programa[MAX_INSTR], int n_instr){
    int posicao = 0;
    int i = 0;
    int operacao, operando;

    while (i<n_instr){

        operacao = programa[i].operacao;
        operando = programa[i].operando;

        while (operacao == SAME_AS){
            operacao = programa[operando].operacao;
            operando = programa[operando].operando;
        }

        if (operacao == LEFT){
            posicao--;
            i++;
        }
        else if (operacao == RIGHT){
            posicao++;
            i++;
        }
    }

    printf("%d\n",posicao);

    return 0;
}

int main(){

    int n_instr;
    char instr[MAX_INSTR][40];
    instr_t programa[MAX_INSTR];

    ler_programa(instr,&n_instr);
    compilar_programa(instr,n_instr,programa);
    dump_programa(programa,n_instr);
    executar_programa(programa,n_instr);
}
