using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace BASIC
{
    class Variables
    {
        private Dictionary<string, int> dicVar = new Dictionary<string,int>();

        public int Get(string var)
        {
            if (!dicVar.ContainsKey(var)) dicVar.Add(var, 0);
            return dicVar[var];
        }

        public void Set(string var, int num)
        {
            if (!dicVar.ContainsKey(var)) dicVar.Add(var, 0);
            dicVar[var] = num;
        }
    }

    class Prikaz
    {
        private string prikaz;

        public Prikaz(string x)
        {
            prikaz = x;
        }

        public string Order
        {
            get
            {
                return prikaz;
            }
        }
    }

    class BASIC
    {
        private SortedDictionary<int, Prikaz> dicLine = new SortedDictionary<int,Prikaz>();
        SortedDictionary<int, Prikaz>.Enumerator execLine;
        private bool WasGoto;

        public void Add(string prikaz)
        {
            int num;
            string [] strings;
            strings = prikaz.Split(new char[] {' ','\t'},2,StringSplitOptions.RemoveEmptyEntries);
            if (strings.Length < 1) return;
            if (!Int32.TryParse(strings[0], out num)) throw new Exception("Line starting with invalid character!");
            if (strings.Length > 1)
            {
                dicLine.Add(num, new Prikaz(strings[1]));
            }
            else
            {
                dicLine.Add(num, new Prikaz("EMPTY"));
            }
        }

        public void SetAtStart()
        {
            execLine = dicLine.GetEnumerator();
            WasGoto = false;
        }

        public bool Next()
        {
            if (WasGoto)
            {
                WasGoto = false;
                return true;
            }
            else
            {
                return execLine.MoveNext();
            }
        }

        public Prikaz CurrentLine
        {
            get
            {
                return execLine.Current.Value;
            }
        }

        public int CurrentLineNumber
        {
            get
            {
                return execLine.Current.Key;
            }
        }

        public void JumpTo(int num)
        {
            if (dicLine.ContainsKey(num))
            {
                execLine = dicLine.GetEnumerator();
                while (execLine.MoveNext() && execLine.Current.Key != num) { };
                WasGoto = true;
            }
            else
            {
                throw new Exception("Wrong line specified");
            }
        }

        public void JumpAfter(int num)
        {
            if (dicLine.ContainsKey(num))
            {
                execLine = dicLine.GetEnumerator();
                while (execLine.MoveNext() && execLine.Current.Key != num) { };
            }
            else
            {
                throw new Exception("Wrong line specified");
            }
        }

    }


    struct ForCycle
    {
        public int lineNumber;
        public string control;
        public string B;
    }


    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.Error.WriteLine("Not enough parameters!");
                return;
            }
            //reading
            BASIC Bas = new BASIC();
            Dictionary<uint, string> dicLine = new Dictionary<uint, string>();
            FileInfo inputFI = new FileInfo(args[0]);
            if (!inputFI.Exists)
            {
                Console.Error.WriteLine("Could not open specified file!");
                return;
            }
            Stream fs = inputFI.OpenRead();
            StreamReader sr = new StreamReader(fs);
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                if (line.IndexOf('\'') >= 0) line = line.Remove(line.IndexOf('\''));
                if (line.Length > 0)
                {
                    try
                    {
                        Bas.Add(line);
                    }
                    catch(Exception ex)
                    {
                        Console.Error.WriteLine(ex.Message);
                        return;
                    }
                }
            }
                 
            //executing

            Bas.SetAtStart();
            Prikaz command;
            Variables vars = new Variables();
            Stack<int> stSub = new Stack<int>();
            Stack<ForCycle> stFor = new Stack<ForCycle>();
            int num, num1, num2;
            while (Bas.Next())
            {
                command = Bas.CurrentLine;
                //Console.WriteLine(command.Order);
                string[] parsedline = command.Order.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                try
                {
                    switch (parsedline[0])
                    {
                        case "EMPTY":
                            break;
                        case "PRINT":
                            if (parsedline.Length != 2) throw new Exception("Too many parameters for PRINT!");
                            if (parsedline[1].IndexOf('\"') == 0)
                            {
                                if (parsedline[1].LastIndexOfAny(new char[] { '\"' }) != parsedline[1].Length-1) throw new Exception("Strings must end with \" too!");
                                string printout = (parsedline[1].Split(new char[] { '\"' }))[1];
                                Console.WriteLine(printout);
                            }
                            else if (Int32.TryParse(parsedline[1], out num))
                            {
                                Console.WriteLine(num);
                            }
                            else
                            {
                                Console.WriteLine(vars.Get(parsedline[1]));
                            }
                            break;
                        case "INPUT":
                            if (parsedline.Length != 2) throw new Exception("Bad number of parameters for INPUT!");
                            string input = Console.ReadLine();
                            if (Int32.TryParse(input, out num))
                            {
                                vars.Set(parsedline[1], num);
                            }
                            else
                            {
                                throw new Exception("This was not a number!");
                            }
                            break;
                        case "LET":
                            if (parsedline.Length != 6) throw new Exception("Bad number of parameters for LET!");
                            if (parsedline[2] != "=") throw new Exception("Wrong parameters for LET!");
                            if (Int32.TryParse(parsedline[1],out num)) throw new Exception("Can not LET a number!");
                            if (!Int32.TryParse(parsedline[3], out num1)) num1 = vars.Get(parsedline[3]);
                            if (!Int32.TryParse(parsedline[5], out num2)) num2 = vars.Get(parsedline[5]);
                            switch (parsedline[4])
                            {
                                case "+":
                                    vars.Set(parsedline[1], num1 + num2);
                                    break;
                                case "*":
                                    vars.Set(parsedline[1], num1 * num2);
                                    break;
                                case "/":
                                    vars.Set(parsedline[1], num1 / num2);
                                    break;
                                case "-":
                                    vars.Set(parsedline[1], num1 - num2);
                                    break;
                                default:
                                    throw new Exception("Wrong parameters for LET!");
                                    break;
                            }
                            break;
                        case "SET":
                            if (parsedline.Length != 4) throw new Exception("Bad number of parameters for SET!");
                            if (parsedline[2] != "=") throw new Exception("Wrong parameters for SET!");
                            if (Int32.TryParse(parsedline[1], out num)) throw new Exception("Can not SET a number!");
                            if (!Int32.TryParse(parsedline[3], out num)) num = vars.Get(parsedline[3]);
                            vars.Set(parsedline[1], num);
                            break;
                        case "END":
                            return;
                            break;
                        case "GOTO":
                            if (parsedline.Length != 2) throw new Exception("Wrong number of parameters for GOTO!");
                            if (!Int32.TryParse(parsedline[1], out num)) throw new Exception("Parameter to GOTO must be number!");
                            Bas.JumpTo(num);
                            break;
                        case "IF":
                            if (parsedline.Length != 7) throw new Exception("Wrong number of parameters for IF!");
                            if (parsedline[4] != "THEN" || parsedline[5] != "GOTO" || !Int32.TryParse(parsedline[6], out num)) throw new Exception("Invalid syntax of IF!");
                            if (!Int32.TryParse(parsedline[1], out num1)) num1 = vars.Get(parsedline[1]);
                            if (!Int32.TryParse(parsedline[3], out num2)) num2 = vars.Get(parsedline[3]);
                            switch (parsedline[2])
                            {
                                case "<=":
                                    if (num1 <= num2) Bas.JumpTo(num);
                                    break;
                                case ">=":
                                    if (num1 >= num2) Bas.JumpTo(num);
                                    break;
                                case "<>":
                                    if (num1 != num2) Bas.JumpTo(num);
                                    break;
                                case "=":
                                    if (num1 == num2) Bas.JumpTo(num);
                                    break;
                                case ">":
                                    if (num1 > num2) Bas.JumpTo(num);
                                    break;
                                case "<":
                                    if (num1 < num2) Bas.JumpTo(num);
                                    break;
                                default:
                                    throw new Exception("Unknown relation operator!");
                                    break;
                            }
                            break;
                        case "GOSUB":
                            if(parsedline.Length != 2) throw new Exception("Wrong parameter count for GOSUB!");
                            if(!Int32.TryParse(parsedline[1],out num)) throw new Exception("Invalid GOSUB parameter!");
                            stSub.Push(Bas.CurrentLineNumber);
                            Bas.JumpTo(num);
                            break;
                        case "RETURN":
                            if(parsedline.Length != 1) throw new Exception("RETURN does not take any parameters!");
                            if(stFor.Count > 0) throw new Exception("RETURN inside FOR cycle!");
                            if(stSub.Count == 0) throw new Exception("RETURN without GOSUB call!");
                            Bas.JumpAfter(stSub.Pop());
                            break;
                        case "FOR":
                            if(parsedline.Length != 6) throw new Exception("Invalid argument count for FOR!");
                            if(parsedline[2] != "=" || parsedline[4] != "TO") throw new Exception("Invalid syntax of FOR!");
                            if (Int32.TryParse(parsedline[1], out num)) throw new Exception("FOR cannot be controled by a number!");
                            if (!Int32.TryParse(parsedline[3], out num1)) num1 = vars.Get(parsedline[3]);
                            if (!Int32.TryParse(parsedline[5], out num2)) num2 = vars.Get(parsedline[5]);
                            if (num1 > num2) throw new Exception("Invalid bounds for FOR cycle!");
                            ForCycle fc = new ForCycle();
                            fc.B = parsedline[5];
                            fc.control = parsedline[1];
                            fc.lineNumber = Bas.CurrentLineNumber;
                            vars.Set(parsedline[1], num1);
                            stFor.Push(fc);
                            break;
                        case "NEXT":
                            if (parsedline.Length != 1) throw new Exception("NEXT does not take any parameters!");
                            if (stFor.Count == 0) throw new Exception("NEXT without preceding FOR!");
                            ForCycle nc = stFor.Peek();
                            if (!Int32.TryParse(nc.B, out num1)) num1 = vars.Get(nc.B);
                            vars.Set(nc.control, vars.Get(nc.control) + 1);
                            if (vars.Get(nc.control) > num1)
                            {
                                stFor.Pop();
                            }
                            else
                            {
                                Bas.JumpAfter(nc.lineNumber);
                            }
                            break;
                        default:
                            throw new Exception("Unknown command!");
                            break;
                    } //switch
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex.Message);
                    return;
                }
            } //main while cycle
        }
    }
}