Example #1
0
 /// <summary>
 ///
 /// </summary>
 public NxtRobot(bool connectNow, EventHandler onConnected = null, EventHandler onDisconnected = null, EventHandler onSensorModeChanged = null, EventHandler onBatteryValueUpdate = null, EventyList <Variable> .OnActionEventHandler onVariablesListChanged = null, string comPort = "")
 {
     // create public list for pattern classification categories
     Variables = new VariablesList();
     // create sensor-dependant pattern classification variables and add to list
     _reflectedLight         = new Variable("Reflected Light", new PercentValue(), this);
     _ambientLight           = new Variable("Ambient Light", new PercentValue(), this);
     _soundIntensityDb       = new Variable("Sound Intensity (dB)", new PercentValue(), this);
     _soundIntensityDba      = new Variable("Sound Intensity (dBA)", new PercentValue(), this);
     _ultrasonicCm           = new Variable("Distance (CM)", new ByteValue(), this);
     _batteryLevelMillivolts = new Variable("Battery Level (mV)", new GenericValue(0, 15000, "Millivolts"), this);
     // init sensor variables
     Variables.AddRange(new[] { _reflectedLight, _ambientLight, _soundIntensityDb, _soundIntensityDba, _ultrasonicCm, _batteryLevelMillivolts });
     InitializeSensorVariables();
     // subscribe to important events
     Connected                += onConnected;
     Disconnected             += onDisconnected;
     SensorModeHasChanged     += onSensorModeChanged;
     NewBatteryLevelAvailable += onBatteryValueUpdate;
     Variables.OnAction       += onVariablesListChanged;
     // connect
     if (!connectNow)
     {
         return;
     }
     Connect(comPort);
     if (!IsConnected)
     {
         throw new ApplicationException("Could not connect!");
     }
 }
Example #2
0
 /// <summary>
 /// Action triggered when button clicked
 /// </summary>
 public void ButtonClicked()
 {
     //List<float> list = new List<float>(new float[]{ 460, 12, 420, 5 });
     //PythonFun.RunPython("pi*((dk+a)^2-(d1+2*r)^2)/4",list, "dk+a+d1+r", 6);
     VariablesList.Add(Structure.UpdateList(VariableInput, VariablesList.ToList()).Last());
     VariableInput = new Variable();
 }
Example #3
0
        public Vec Clone()
        {
            var array  = VariablesList.ToArray();
            var result = new Vec(array);

            result.Sign = Sign;

            return(result);
        }
Example #4
0
 /// <summary>
 /// Get value from particular variable
 /// </summary>
 /// <param name="name">Name of variable</param>
 public static object GetVariableValue(string name)
 {
     if (IsExistVariable(name))
     {
         return(VariablesList.Single(var => var.name == name).value);
     }
     else
     {
         throw new Exception("No variables with this name exist");
     }
 }
Example #5
0
        public Vec ReplaceVarWithVec(Vec vec, int basicVarNumber)
        {
            Vec result = new Vec(VariablesList.ToArray());

            result.Sign = Sign;

            result = result.AddFunc(vec.Mul(result[basicVarNumber]));
            result[basicVarNumber] = 0;

            return(result);
        }
Example #6
0
        public Vec Mul(double ratio)
        {
            Vec result = new Vec(VariablesList.ToArray());

            result.Sign = Sign;

            for (int i = 0; i <= VariablesCount; i++)
            {
                result[i] *= ratio;
            }

            return(result);
        }
Example #7
0
        public Vec AddFunc(Vec vec)
        {
            Vec result = new Vec(VariablesList.ToArray());

            result.Sign = Sign;

            for (int i = 0; i <= VariablesCount; i++)
            {
                result[i] += vec[i];
            }

            return(result);
        }
Example #8
0
 /// <summary>
 ///
 /// </summary>
 public NxtRobot(bool connectNow, string comPort = "")
 {
     // create public list for pattern classification categories
     Variables = new VariablesList();
     // create sensor-dependant pattern classification variables and add to list
     _reflectedLight         = new Variable("Reflected Light", new PercentValue(), this);
     _ambientLight           = new Variable("Ambient Light", new PercentValue(), this);
     _soundIntensityDb       = new Variable("Sound Intensity (dB)", new PercentValue(), this);
     _soundIntensityDba      = new Variable("Sound Intensity (dBA)", new PercentValue(), this);
     _ultrasonicCm           = new Variable("Distance (CM)", new ByteValue(), this);
     _batteryLevelMillivolts = new Variable("Battery Level (mV)", new GenericValue(0, 15000, "Millivolts"), this);
     // init sensor variables
     Variables.AddRange(new[] { _reflectedLight, _ambientLight, _soundIntensityDb, _soundIntensityDba, _ultrasonicCm, _batteryLevelMillivolts });
     InitializeSensorVariables();
 }
Example #9
0
 private void BtnNew_Click(object sender, EventArgs e)
 {
     var form = new frmNew();
     form.btnCreate.Click += (ls, le) =>
     {
         if (string.IsNullOrEmpty(form.tbNewName.Text)) return;
         if (GetSaves().Contains(form.tbNewName.Text))
         {
             Utils.Alert("Error", "List name is already taken.");
             return;
         }
         variablesList.Save();
         tab.ChangeVariablesList(variablesList = new VariablesList(savesPath, form.tbNewName.Text));
         form.Close();
     };
     form.ShowDialog();
 }
Example #10
0
        private void _find_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_findText.Text))
            {
                return;
            }

            var index = VariablesList.Text.IndexOf(_findText.Text, StringComparison.Ordinal);

            if (index == -1)
            {
                return;
            }
            VariablesList.Select();
            VariablesList.SelectionStart  = index;
            VariablesList.SelectionLength = _findText.Text.Length;
            VariablesList.ScrollToCaret();
        }
Example #11
0
        public Vec GetTagretFunc(IList <Vec> vecList, IList <int> basicVarNumbers)
        {
            if (basicVarNumbers == null)
            {
                return(null);
            }

            Vec target = new Vec(VariablesList.ToArray());

            target.Sign = Sign;

            for (int i = 0; i < vecList.Count; i++)
            {
                var limit = vecList[i].Solve(basicVarNumbers[i]);
                target = target.ReplaceVarWithVec(limit, basicVarNumbers[i]);
            }

            return(target);
        }
Example #12
0
        public Vec Solve(int varNum)
        {
            double ratio = 1 / this[varNum];

            Vec result = new Vec(VariablesList.ToArray());

            result.Sign = Sign;

            for (int i = 0; i <= VariablesCount; i++)
            {
                if (i == varNum)
                {
                    result[i] = 0;
                    continue;
                }

                result[i] *= -ratio;
            }

            return(result);
        }
Example #13
0
        public void OnLoad()
        {
            try
            {
                page = new TabPage("Composer Variables");
                page.ImageIndex = (int) SessionIcons.Script;

                tab = new Tab();
                tab.ChangeVariablesList(variablesList = new VariablesList(savesPath, defaultSaveName));
                tab.Dock = DockStyle.Fill;
                tab.btnLoad.Click += BtnLoad_Click;
                tab.btnNew.Click += BtnNew_Click;
                tab.btnSave.Click += BtnSave_Click;
                page.Controls.Add(tab);

                FiddlerApplication.UI.tabsViews.TabPages.Add(page);
            }
            catch
            {
                Utils.Alert("Error", "Failed to initialize addon.");
            }
        }
Example #14
0
 public void ChangeVariablesList(VariablesList variablesList)
 {
     bs.DataSource = variablesList;
     tbFilename.Text = variablesList.SaveName;
 }
Example #15
0
 public void AddVariable(double value)
 {
     VariablesList.Add(value);
 }
Example #16
0
 /// <summary>
 /// Remove all variables from variables list
 /// </summary>
 public static void RemoveAllVariables()
 {
     VariablesList.Clear();
 }
Example #17
0
 /// <summary>
 /// Check the variables list for particular variable by name
 /// </summary>
 /// <param name="name">Name of variable</param>
 public static bool IsExistVariable(string name)
 {
     return(VariablesList.Any(var => var.name == name));
 }
Example #18
0
        public async Task Run()
        {
            // Build the C# script if in Stack or LoliCode mode
            if (config.Mode == ConfigMode.Stack || config.Mode == ConfigMode.LoliCode)
            {
                config.CSharpScript = config.Mode == ConfigMode.Stack
                    ? Stack2CSharpTranspiler.Transpile(config.Stack, config.Settings)
                    : Loli2CSharpTranspiler.Transpile(config.LoliCodeScript, config.Settings);
            }

            if (options.UseProxy && !options.TestProxy.Contains(':'))
            {
                throw new InvalidProxyException(options.TestProxy);
            }

            if (!options.PersistLog)
            {
                logger.Clear();
            }

            // Close any previously opened browsers
            if (lastPuppeteerBrowser != null)
            {
                await lastPuppeteerBrowser.CloseAsync();
            }

            if (lastSeleniumBrowser != null)
            {
                lastSeleniumBrowser.Quit();
            }

            options.Variables.Clear();
            IsRunning = true;
            cts       = new CancellationTokenSource();
            var sw = new Stopwatch();

            var wordlistType = RuriLibSettings.Environment.WordlistTypes.First(w => w.Name == options.WordlistType);
            var dataLine     = new DataLine(options.TestData, wordlistType);
            var proxy        = options.UseProxy ? Proxy.Parse(options.TestProxy, options.ProxyType) : null;

            var providers = new Bots.Providers(RuriLibSettings)
            {
                RNG = RNGProvider
            };

            if (!RuriLibSettings.RuriLibSettings.GeneralSettings.UseCustomUserAgentsList)
            {
                providers.RandomUA = RandomUAProvider;
            }

            // Build the BotData
            var data = new BotData(providers, config.Settings, logger, dataLine, proxy, options.UseProxy)
            {
                CancellationToken = cts.Token
            };

            using var httpClient = new HttpClient();
            data.SetObject("httpClient", httpClient);
            var runtime  = Python.CreateRuntime();
            var pyengine = runtime.GetEngine("py");
            var pco      = (PythonCompilerOptions)pyengine.GetCompilerOptions();

            pco.Module &= ~ModuleOptions.Optimized;
            data.SetObject("ironPyEngine", pyengine);
            data.AsyncLocker = new();

            dynamic globals = new ExpandoObject();

            var script = new ScriptBuilder()
                         .Build(config.CSharpScript, config.Settings.ScriptSettings, PluginRepo);

            logger.Log($"Sliced {dataLine.Data} into:");
            foreach (var slice in dataLine.GetVariables())
            {
                var sliceValue = data.ConfigSettings.DataSettings.UrlEncodeDataAfterSlicing
                    ? Uri.EscapeDataString(slice.AsString())
                    : slice.AsString();

                logger.Log($"{slice.Name}: {sliceValue}");
            }

            // Initialize resources
            Dictionary <string, ConfigResource> resources = new();

            // Resources will need to be disposed of
            foreach (var opt in config.Settings.DataSettings.Resources)
            {
                try
                {
                    resources[opt.Name] = opt switch
                    {
                        LinesFromFileResourceOptions x => new LinesFromFileResource(x),
                        RandomLinesFromFileResourceOptions x => new RandomLinesFromFileResource(x),
                        _ => throw new NotImplementedException()
                    };
                }
                catch
                {
                    logger.Log($"Could not create resource {opt.Name}", LogColors.Tomato);
                }
            }

            // Add resources to global variables
            globals.Resources = resources;
            var scriptGlobals = new ScriptGlobals(data, globals);

            // Set custom inputs
            foreach (var input in config.Settings.InputSettings.CustomInputs)
            {
                (scriptGlobals.input as IDictionary <string, object>).Add(input.VariableName, input.DefaultAnswer);
            }

            // [LEGACY] Set up the VariablesList
            if (config.Mode == ConfigMode.Legacy)
            {
                var slices = new List <Variable>();

                foreach (var slice in dataLine.GetVariables())
                {
                    var sliceValue = data.ConfigSettings.DataSettings.UrlEncodeDataAfterSlicing
                        ? Uri.EscapeDataString(slice.AsString())
                        : slice.AsString();

                    slices.Add(new StringVariable(sliceValue)
                    {
                        Name = slice.Name
                    });
                }

                var legacyVariables = new VariablesList(slices);

                foreach (var input in config.Settings.InputSettings.CustomInputs)
                {
                    legacyVariables.Set(new StringVariable(input.DefaultAnswer)
                    {
                        Name = input.VariableName
                    });
                }

                data.SetObject("legacyVariables", legacyVariables);
            }

            try
            {
                sw.Start();
                Started?.Invoke(this, EventArgs.Empty);

                if (config.Mode != ConfigMode.Legacy)
                {
                    var state = await script.RunAsync(scriptGlobals, null, cts.Token);

                    foreach (var scriptVar in state.Variables)
                    {
                        try
                        {
                            var type = DescriptorsRepository.ToVariableType(scriptVar.Type);

                            if (type.HasValue && !scriptVar.Name.StartsWith("tmp_"))
                            {
                                var variable = DescriptorsRepository.ToVariable(scriptVar.Name, scriptVar.Type, scriptVar.Value);
                                variable.MarkedForCapture = data.MarkedForCapture.Contains(scriptVar.Name);
                                options.Variables.Add(variable);
                            }
                        }
                        catch
                        {
                            // The type is not supported, e.g. it was generated using custom C# code and not blocks
                            // so we just disregard it
                        }
                    }
                }
                else
                {
                    // [LEGACY] Run the LoliScript in the old way
                    var loliScript = new LoliScript(config.LoliScript);
                    var lsGlobals  = new LSGlobals(data);

                    do
                    {
                        if (cts.IsCancellationRequested)
                        {
                            break;
                        }

                        await loliScript.TakeStep(lsGlobals);

                        options.Variables.Clear();
                        var legacyVariables = data.TryGetObject <VariablesList>("legacyVariables");
                        options.Variables.AddRange(legacyVariables.Variables);
                        options.Variables.AddRange(lsGlobals.Globals.Variables);
                    }while (loliScript.CanProceed);
                }
            }
            catch (OperationCanceledException)
            {
                data.STATUS = "ERROR";
                logger.Log($"Operation canceled", LogColors.Tomato);
            }
            catch (Exception ex)
            {
                data.STATUS = "ERROR";

                var logErrorMessage = RuriLibSettings.RuriLibSettings.GeneralSettings.VerboseMode
                    ? ex.ToString()
                    : ex.Message;

                logger.Log($"[{data.ExecutionInfo}] {ex.GetType().Name}: {logErrorMessage}", LogColors.Tomato);
                IsRunning = false;
                throw;
            }
            finally
            {
                sw.Stop();

                logger.Log($"BOT ENDED AFTER {sw.ElapsedMilliseconds} ms WITH STATUS: {data.STATUS}");

                // Save the browsers for later use
                lastPuppeteerBrowser = data.TryGetObject <Browser>("puppeteer");
                lastSeleniumBrowser  = data.TryGetObject <OpenQA.Selenium.WebDriver>("selenium");

                // Dispose stuff in data.Objects
                data.DisposeObjectsExcept(new[] { "puppeteer", "puppeteerPage", "puppeteerFrame", "selenium" });

                // Dispose resources
                foreach (var resource in resources.Where(r => r.Value is IDisposable)
                         .Select(r => r.Value).Cast <IDisposable>())
                {
                    resource.Dispose();
                }

                data.AsyncLocker.Dispose();
            }

            IsRunning = false;
            Stopped?.Invoke(this, EventArgs.Empty);
        }
Example #19
0
 private void BtnLoad_Click(object sender, EventArgs e)
 {
     var form = new frmLoad(GetSaves().ToArray());
     form.btnLoad.Click += (ls, le) =>
     {
         if (form.lbSaves.SelectedIndex < 0) return;
         var saveName = form.lbSaves.SelectedItem as string;
         if (string.IsNullOrEmpty(saveName)) return;
         tab.ChangeVariablesList(variablesList = new VariablesList(savesPath, saveName));
         form.Close();
     };
     form.ShowDialog();
 }
Example #20
0
 public void InsertAndReplace(int varNum)
 {
     VariablesList.Insert(varNum + 1, -this[varNum]);
 }
Example #21
0
        public static MethodBodyBlock Convert(MethodEx method)
        {
            if (!method.IsVerified)
            {
                throw new ConvertionException();
            }
            MethodInfoExtention _method_  = new MethodInfoExtention(method.Method);
            MethodBodyBlock     mainBlock = new MethodBodyBlock(_method_.GetReturnType().type);

            mainBlock.Options["StackTypes"] = new StackTypes();
            Block currentBlock = mainBlock;

            Node[] heads = new Node[method.Count];
            Node[] tails = new Node[method.Count];
            Node   head = null;
            Node   tail = null;
            Node   firstBlock = null;
            Node   lastBlock = null;
            int    iNum, iNumNext;

            Variable[]    locals        = new Variable[method.Locals.Count];
            Variable[]    args          = new Variable[_method_.ArgCount];
            VariablesList methodVarList = mainBlock.Variables;

            for (int i = 0; i < args.Length; i++)
            {
                args[i]      = methodVarList.CreateVar(_method_.GetArgType(i).type, VariableKind.Parameter);
                args[i].Name = "Arg" + i;
//				methodVarList.Add(args[i]);
            }
            for (int i = 0; i < locals.Length; i++)
            {
                locals[i]      = methodVarList.CreateVar(method.Locals[i], VariableKind.Local);
                locals[i].Name = "Loc" + i;
//				methodVarList.Add(locals[i]);
            }

            BlockType nextBlockType;
            int       nextBlockStart = -1;
            int       nextBlockEnd   = 1 << 30;
            int       nextBlockIndex;
            Type      nextCatchBlockType;
            Hashtable tryBlocks    = new Hashtable();
            Hashtable filterBlocks = new Hashtable();
            Stack     blockEnds    = new Stack();

            blockEnds.Push(method.Count);
            FindNextBlockStart(method.EHClauses, out nextBlockType, ref nextBlockStart, ref nextBlockEnd, out nextCatchBlockType, out nextBlockIndex);

            //Nodes and blocks creation, blocks linkage
            for (iNum = 0; iNum < method.Count; iNum++)
            {
                while (iNum == (int)blockEnds.Peek())
                {
                    currentBlock = currentBlock.Parent;
                    blockEnds.Pop();
                }

                firstBlock = null;
                lastBlock  = null;
                Node thisBlock = null;
                while (iNum == nextBlockStart)
                {
                    Block currentBlockOld = currentBlock;

                    switch (nextBlockType)
                    {
                    case BlockType.Try:
                        currentBlock = new ProtectedBlock();
                        break;

                    case BlockType.Catch:
                        currentBlock = new CatchBlock(nextCatchBlockType);
                        break;

                    case BlockType.Finally:
                        currentBlock = new FinallyBlock(false);
                        break;

                    case BlockType.Filter:
                        currentBlock = new FilterBlock();
                        break;

                    case BlockType.FilteredCatch:
                        currentBlock = new UserFilteredBlock();
                        break;
                    }

                    currentBlock.setParent(currentBlockOld);

                    blockEnds.Push(nextBlockEnd);
                    if (thisBlock == null)
                    {
                        thisBlock = firstBlock = currentBlock;
                    }
                    else
                    {
                        thisBlock.Next = currentBlock;
                        thisBlock      = currentBlock;
                    }
                    switch (nextBlockType)
                    {
                    case BlockType.Try:
                        tryBlocks.Add(new Segment(nextBlockStart, nextBlockEnd), thisBlock);
                        break;

                    case BlockType.Filter:
                        filterBlocks.Add(new Segment(nextBlockStart, nextBlockEnd), thisBlock);
                        break;

                    case BlockType.Finally:
                    case BlockType.Catch:
                    {
                        Segment        tryBlockKey = FindProtectedBlock(method.EHClauses, nextBlockIndex);
                        ProtectedBlock tryBlock    = tryBlocks[tryBlockKey] as ProtectedBlock;
                        tryBlock.AddHandler(thisBlock as EHBlock);
                    }       break;

                    case BlockType.FilteredCatch:
                    {
                        Segment        tryBlockKey = FindProtectedBlock(method.EHClauses, nextBlockIndex);
                        ProtectedBlock tryBlock    = tryBlocks[tryBlockKey] as ProtectedBlock;
                        tryBlock.AddHandler(thisBlock as EHBlock);

                        Segment     filterKey   = FindFilterBlock(method.EHClauses, nextBlockIndex);
                        FilterBlock filterBlock = filterBlocks[filterKey] as FilterBlock;
                        (thisBlock as UserFilteredBlock).Filter = filterBlock;
                    }       break;
                    }
                    FindNextBlockStart(method.EHClauses, out nextBlockType, ref nextBlockStart, ref nextBlockEnd, out nextCatchBlockType, out nextBlockIndex);
                }
                lastBlock = thisBlock;

                Instruction i = method[iNum];
                switch (i.Code)
                {
                case InstructionCode.NEG:
                case InstructionCode.NOT:
                {
                    head = tail = new UnaryOp(UnaryOpFromCode(i.Code));
                    /*!*/ head.setParent(currentBlock);
                } break;

                case InstructionCode.ADD:
                case InstructionCode.AND:
                case InstructionCode.CEQ:
                case InstructionCode.CGT:
                case InstructionCode.CLT:
                case InstructionCode.DIV:
                case InstructionCode.MUL:
                case InstructionCode.OR:
                case InstructionCode.REM:
                case InstructionCode.SHL:
                case InstructionCode.SHR:
                case InstructionCode.SUB:
                case InstructionCode.XOR:
                {
                    head = tail = new BinaryOp(BinaryOpFromCode(i.Code), i.OverflowFlag, i.UnsignedFlag);
                    /*!*/ head.setParent(currentBlock);
                } break;

                case InstructionCode.LDC:
                    head = tail = new LoadConst(i.Param);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDARG:
                    head = tail = new LoadVar(args[(int)(i.Param)]);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDLOC:
                    head = tail = new LoadVar(locals[(int)(i.Param)]);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDARGA:
                    head = tail = new LoadVarAddr(args[(int)(i.Param)]);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDLOCA:
                    head = tail = new LoadVarAddr(locals[(int)(i.Param)]);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDIND:
                    head = tail = new LoadIndirect(i.TypeBySuffixOrParam());
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDFLD:
                {
                    FieldInfo field = i.Param as FieldInfo;
                    if (field.IsStatic)
                    {
                        head = new RemoveStackTop();
                        /*!*/ head.setParent(currentBlock);
                        //remove the object instance when accessing the static field with LDFLD
                        tail = new LoadField(field);
                        /*!*/ tail.setParent(currentBlock);
                        head.Next = tail;
                    }
                    else
                    {
                        head = tail = new LoadField(field);
                        /*!*/ head.setParent(currentBlock);
                    }
                }       break;

                case InstructionCode.LDFLDA:
                {
                    FieldInfo field = i.Param as FieldInfo;
                    if (field.IsStatic)
                    {
                        head = new RemoveStackTop();
                        /*!*/ head.setParent(currentBlock);
                        tail = new LoadFieldAddr(field);
                        /*!*/ tail.setParent(currentBlock);
                        head.Next = tail;
                    }
                    else
                    {
                        head = tail = new LoadFieldAddr(field);
                        /*!*/ head.setParent(currentBlock);
                    }
                }       break;

                case InstructionCode.LDSFLD:
                    head = tail = new LoadField(i.Param as FieldInfo);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDSFLDA:
                    head = tail = new LoadFieldAddr(i.Param as FieldInfo);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDELEM:
                    head = tail = new LoadElement(i.TypeBySuffixOrParam());
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDELEMA:
                    head = tail = new LoadElementAddr(i.TypeBySuffixOrParam());
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDOBJ:
                    head = tail = new LoadIndirect(i.Param as Type);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.SIZEOF:
                    head = tail = new LoadSizeOfValue(i.Param as Type);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDLEN:
                    head = tail = new LoadLength();
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDTOKEN:
                    if (i.Param is Type)
                    {
                        head = tail = new LoadConst((i.Param as Type).TypeHandle);
                    }
                    else if (i.Param is MethodBase)
                    {
                        head = tail = new LoadConst((i.Param as MethodBase).MethodHandle);
                    }
                    else if (i.Param is FieldInfo)
                    {
                        head = tail = new LoadConst((i.Param as FieldInfo).FieldHandle);
                    }
                    else
                    {
                        throw new ConvertionException();
                    }
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDNULL:
                    head = tail = new LoadConst(null);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDSTR:
                    head = tail = new LoadConst(i.Param);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.STARG:
                    head = tail = new StoreVar(args[(int)(i.Param)]);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.STLOC:
                    head = tail = new StoreVar(locals[(int)(i.Param)]);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.STIND:
                    head = tail = new StoreIndirect(i.TypeBySuffixOrParam());
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.STFLD:
                {
                    FieldInfo field = i.Param as FieldInfo;
                    if (field.IsStatic)
                    {
                        head = new StoreField(field);
                        /*!*/ head.setParent(currentBlock);
                        tail = new RemoveStackTop();
                        /*!*/ tail.setParent(currentBlock);
                        head.Next = tail;
                    }
                    else
                    {
                        head = tail = new StoreField(i.Param as FieldInfo);
                        /*!*/ head.setParent(currentBlock);
                    }
                }       break;

                case InstructionCode.STSFLD:
                    head = tail = new StoreField(i.Param as FieldInfo);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.STELEM:
                    head = tail = new StoreElement(i.TypeBySuffixOrParam());
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.STOBJ:
                    head = tail = new StoreIndirect(i.Param as Type);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.CPOBJ:
                    head = new LoadIndirect(i.Param as Type);
                    /*!*/ head.setParent(currentBlock);
                    tail = new StoreIndirect(i.Param as Type);
                    /*!*/ tail.setParent(currentBlock);
                    head.Next = tail;
                    break;

                case InstructionCode.DUP:
                    head = tail = new DuplicateStackTop();
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.CALL:
                    head = tail = new CallMethod(i.Param as MethodBase, false, i.HasTail);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.CALLVIRT:
                    MethodInfo callee = i.Param as MethodInfo;
                    head = tail = new CallMethod(callee, callee.IsVirtual, i.HasTail);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.NEWOBJ:
                { ConstructorInfo ctor = i.Param as ConstructorInfo;
                  if (Verifier.IsDelegate(ctor.DeclaringType))
                  {
                      if (Verifier.IsInstanceDispatch(method, iNum))
                      {
                          heads[iNum - 1] = tails[iNum - 1] = null;
                          head            = tail = new CreateDelegate(ctor, method[iNum - 1].Param as MethodInfo, false);
                      }
                      else if (Verifier.IsVirtualDispatch(method, iNum))
                      {
                          heads[iNum - 2] = tails[iNum - 2] = null;
                          heads[iNum - 1] = tails[iNum - 1] = null;
                          head            = tail = new CreateDelegate(ctor, method[iNum - 1].Param as MethodInfo, true);
                      }
                  }
                  else
                  {
                      head = tail = new NewObject(ctor);
                  }
                  /*!*/ head.setParent(currentBlock); }       break;

                case InstructionCode.NEWARR:
                    head = tail = new NewArray(i.Param as Type);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.INITOBJ:
                    head = tail = new InitValue(i.Param as Type);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.ISINST:
                    head = tail = new CastClass(i.Param as Type, false);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.CASTCLASS:
                    head = tail = new CastClass(i.Param as Type, true);
                    /*!*/ head.setParent(currentBlock);
                    break;


                case InstructionCode.BOX:
                    head = tail = new BoxValue(i.Param as Type);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.UNBOX:
                    head = tail = new UnboxValue(i.Param as Type);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.CONV:
                    head = tail = new ConvertValue(i.TypeBySuffixOrParam(), i.OverflowFlag, i.UnsignedFlag);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.POP:
                    head = tail = new RemoveStackTop();
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.BEQ:
                    head = new BinaryOp(BinaryOp.ArithOp.CEQ, false, false);
                    /*!*/ head.setParent(currentBlock);
                    tail = new Branch();
                    /*!*/ tail.setParent(currentBlock);
                    head.Next = tail;
                    break;

                case InstructionCode.BNE:
                    head = new BinaryOp(BinaryOp.ArithOp.CEQ, false, false);
                    /*!*/ head.setParent(currentBlock);
                    tail = new Branch();
                    /*!*/ tail.setParent(currentBlock);
                    head.Next = tail;
                    break;

                case InstructionCode.BGE:
                    if (TypeFixer.IsFloatOrCompatible(i.Stack.Top()))
                    {
                        head = new BinaryOp(BinaryOp.ArithOp.CLT, false, !i.UnsignedFlag);
                    }
                    else
                    {
                        head = new BinaryOp(BinaryOp.ArithOp.CLT, false, i.UnsignedFlag);
                    }
                    tail = new Branch();
                    /*!*/ head.setParent(currentBlock);
                    /*!*/ tail.setParent(currentBlock);
                    head.Next = tail;
                    break;

                case InstructionCode.BGT:
                    head = new BinaryOp(BinaryOp.ArithOp.CGT, false, i.UnsignedFlag);
                    tail = new Branch();
                    /*!*/ head.setParent(currentBlock);
                    /*!*/ tail.setParent(currentBlock);
                    head.Next = tail;
                    break;

                case InstructionCode.BLE:
                    if (TypeFixer.IsFloatOrCompatible(i.Stack.Top()))
                    {
                        head = new BinaryOp(BinaryOp.ArithOp.CGT, false, !i.UnsignedFlag);
                    }
                    else
                    {
                        head = new BinaryOp(BinaryOp.ArithOp.CGT, false, i.UnsignedFlag);
                    }
                    tail = new Branch();
                    /*!*/ head.setParent(currentBlock);
                    /*!*/ tail.setParent(currentBlock);
                    head.Next = tail;
                    break;

                case InstructionCode.BLT:
                    head = new BinaryOp(BinaryOp.ArithOp.CLT, false, i.UnsignedFlag);
                    tail = new Branch();
                    /*!*/ head.setParent(currentBlock);
                    /*!*/ tail.setParent(currentBlock);
                    head.Next = tail;
                    break;

                case InstructionCode.BRTRUE:
                    head = tail = new Branch();
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.BRFALSE:
                    head = tail = new Branch();
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.SWITCH:
                    head = tail = new Switch((i.Param as int[]).Length);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.BR:
                case InstructionCode.NOP:
                case InstructionCode.BREAK:
                case InstructionCode.LDFTN:                             // Expecting further delegate construction...
                case InstructionCode.LDVIRTFTN:                         //
                    head = tail = new DummyNode();
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.THROW:
                    head = tail = new ThrowException();
                    /*!*/ head.setParent(currentBlock);
                    break;


                case InstructionCode.RET:
                case InstructionCode.ENDFINALLY:
                case InstructionCode.ENDFILTER:
                case InstructionCode.LEAVE:
                    head = tail = new Leave();
                    /*!*/ head.setParent(currentBlock);
                    break;

                default:
                    throw new ConvertionException();
                }
                if (head != null)
                {
                    head.Options["StackTypes"] = i.Stack.Clone() as StackTypes;
                }
                if (head != tail)                //=>   head :: BinaryOp, tail :: Branch
                //||   head :: LoadIndirect, tail :: StoreIndirect
                {
                    if (head is BinaryOp && tail is Branch)
                    {
                        StackTypes stack = i.Stack.Clone() as StackTypes;
                        stack.Pop();
                        stack.Pop();
                        stack.Push(typeof(int));
                        tail.Options["StackTypes"] = stack;
                    }
                    else if (head is LoadIndirect && tail is StoreIndirect)
                    {
                        StackTypes stack = i.Stack.Clone() as StackTypes;
                        TypeEx     type  = stack.Pop();                    //type == S&
                        stack.Push(type.type.GetElementType());
                        tail.Options["StackTypes"] = stack;
                    }
                }
                if (firstBlock != null)
                {
                    lastBlock.Next = head;
                    for (Node n = firstBlock; n != head; n = n.Next)
                    {
                        n.Options["StackTypes"] = i.Stack.Clone() as StackTypes;
                    }
                    head = firstBlock;
                    if (tail == null)
                    {
                        tail = lastBlock;                         //This may occure what the NOP instruction starts some block
                    }
                }
                heads[iNum] = head;
                tails[iNum] = tail;
            }            //for
            mainBlock.Next = heads[0];
            //Control flow linkage
            for (iNum = 0; iNum < method.Count; iNum++)
            {
                if (heads[iNum] == null)
                {
                    throw new ConvertionException();                     //impossible :)
                }
                Instruction i = method[iNum];

                switch (i.Code)
                {
                case InstructionCode.BR:
                case InstructionCode.LEAVE:
                    tails[iNum].Next = heads[(int)i.Param];
                    break;

                case InstructionCode.RET:
                case InstructionCode.ENDFINALLY:
                case InstructionCode.ENDFILTER:
                case InstructionCode.THROW:
                case InstructionCode.RETHROW:
                    break;

                case InstructionCode.BRFALSE:                     //false
                case InstructionCode.BGE:                         //false
                case InstructionCode.BLE:                         //false
                case InstructionCode.BNE:                         //false
                    tails[iNum].Next            = heads[(int)i.Param];
                    (tails[iNum] as Branch).Alt = heads[iNum + 1];
                    break;

                case InstructionCode.BRTRUE:                      //true
                case InstructionCode.BEQ:                         //true
                case InstructionCode.BGT:                         //true
                case InstructionCode.BLT:                         //true
                    tails[iNum].Next            = heads[iNum + 1];
                    (tails[iNum] as Branch).Alt = heads[(int)i.Param];
                    break;

                case InstructionCode.SWITCH:
                    tails[iNum].Next = heads[iNum + 1];
                    Switch node = tails[iNum] as Switch;
                    int[]  alt  = i.Param as int[];
                    for (int j = 0; j < node.Count; j++)
                    {
                        node[j] = heads[alt[j]];
                    }
                    break;

                default:
                    tails[iNum].Next = heads[iNum + 1];
                    break;
                }
            }

            //Removing DummyNodes
            for (iNum = 0; iNum < method.Count; iNum++)
            {
                if (heads[iNum] is DummyNode)
                {
                    Node   dummy = heads[iNum];
                    Node[] prev  = new Node[dummy.PrevArray.Count];
                    for (int j = 0; j < prev.Length; j++)
                    {
                        prev[j] = dummy.PrevArray[j];
                    }
                    for (int j = 0; j < prev.Length; j++)
                    {
                        prev[j].NextArray[prev[j].NextArray.IndexOf(dummy)] = dummy.Next;
                    }
                    dummy.RemoveFromGraph();
                }
            }


            return(mainBlock);
        }