OutputWindow
Inheritance: System.Windows.Window, System.Windows.Markup.IComponentConnector
        private void ExecuteCommandsAndCreateSinkFile(OutputWindow ow, CommandOutput lst, string seltext)//sending message and output to sink file
        {
            string objectname;
            seltext = seltext.Replace('\n', ';').Replace('\r', ' ').Trim();
            seltext = JoinCommaSeparatedStatment(seltext);
            string stmt = "";
            //////wrap in sink////////
            string sinkfilefullpathname = Path.Combine(System.IO.Path.GetTempPath().Replace("\\", "/"), confService.GetConfigValueForKey("tempsink"));//23nov2012
            // load default value if no path is set or invalid path is set
            if (sinkfilefullpathname.Trim().Length == 0 || !IsValidFullPathFilename(sinkfilefullpathname, false))
            {
                //sinkfilefullpathname = confService.DefaultSettings["tempsink"];
                MessageBox.Show(this, "Key 'tempsink' not found in config file. Aborting...");
                return;
            }
            OpenSinkFile(@sinkfilefullpathname, "wt");
            SetSink();
            string _command = string.Empty;//05May2013
            int bskyfrmtobjcount = 0;
            bool breakfor = false;//, continuefor=false;//14Nov2013
            for (int start = 0, end = 0; start < seltext.Length; start = start + end + 1) //28Jan2013 final condition was start < seltext.Length-1
            {
                objectname = "";
                end = seltext.IndexOf(';', start) - start;
                if (end < 0) // if ; not found
                    end = seltext.IndexOf('\n', start) - start;
                if (end < 0)// if new line not found
                    end = seltext.Length - start;
                stmt = seltext.Substring(start, end).Replace('\n', ' ').Replace('\r', ' ').Trim();

                if (stmt.Trim().Length < 1 || stmt.Trim().IndexOf('#') == 0)
                    continue;

                if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Syntax going to execute : " + stmt, LogLevelEnum.Info);

                if (stmt.Trim().IndexOf('#') > 1) //12May2014 if any statment has R comments in the end in same line.
                    stmt = stmt.Substring(0, stmt.IndexOf("#"));

                object o = null;


                if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Categorizing command before execution.", LogLevelEnum.Info);

                _command = ExtractCommandName(stmt);//07sep2012
                RCommandType rct = GetRCommandType(_command);

                if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Syntax command category : " + rct.ToString(), LogLevelEnum.Info);

                try
                {
                    switch (rct)
                    {
                        case RCommandType.CONDITIONORLOOP:  //Block Commands
                            int end2 = end;
                            stmt = CurlyBracketParser(seltext, start, ref end);
                            if (stmt.Equals("ERROR"))
                            {
                                breakfor = true;
                            }
                            else
                            {
                                SendCommandToOutput(stmt, "R-Command");
                                ExecuteOtherCommand(ow, stmt);
                            }

                            //02Dec2014
                            ResetSink();
                            CloseSinkFile();
                            CreateOuput(ow);
                            OpenSinkFile(@sinkfilefullpathname, "wt");
                            SetSink();
                            ///02Dec2015 Now add graphic (all of them, from temp location)
                            CreateAllGraphicOutput(ow);//get all grphics and send to output
                            break;
                        case RCommandType.GRAPHIC:
                            CommandRequest grpcmd = new CommandRequest();

                            grpcmd.CommandSyntax = "write(\"" + stmt.Replace("<", "&lt;").Replace('"', '\'') + "\",fp)";// http://www.w3schools.com/xml/xml_syntax.asp
                            o = analytics.ExecuteR(grpcmd, false, false); //for printing command in file
                            CloseGraphicsDevice();
                            //GetGraphicSize()
                            ResetSink();
                            CloseSinkFile();
                            CreateOuput(ow);
                            OpenSinkFile(@sinkfilefullpathname, "wt");
                            SetSink();
                            OpenGraphicsDevice();//05May2013
                            //continuefor = true;
                            //continue;
                            break;
                        case RCommandType.GRAPHICXML:
                            ExecuteXMLTemplateDefinedCommands(stmt);
                            break;
                        case RCommandType.BSKYFORMAT:
                            ResetSink();
                            CloseSinkFile();
                            CreateOuput(ow);
                            SendCommandToOutput(stmt, "BSkyFormat");//26Aug2014 blue colored
                            ExecuteBSkyFormatCommand(stmt, ref bskyfrmtobjcount, ow); // this should be out of block and so "TRUE" must be passed in BSkyFormat
                            OpenSinkFile(@sinkfilefullpathname, "wt");
                            SetSink();
                            break;
                        case RCommandType.BSKYLOADREFRESHDATAFRAME: //BSkyLoadRefreshDataframe(dfname)
                            ResetSink();
                            CloseSinkFile();
                            CreateOuput(ow);
                            SendCommandToOutput(stmt, "Load-Refresh Dataframe");//26Aug2014 blue colored
                            bool success = ExecuteBSkyLoadRefreshDataframe(stmt);
                            if (!success)
                                SendErrorToOutput("Error:Cannot Load/Refresh Dataset. Dataframe does not exists. OR not 'data.frame' type.", ow); //03Jul2013
                            OpenSinkFile(@sinkfilefullpathname, "wt");
                            SetSink();
                            break;
                        case RCommandType.BSKYREMOVEREFRESHDATAFRAME: //BSkyRemoveRefreshDataframe(dfname)
                            ResetSink();
                            CloseSinkFile();
                            CreateOuput(ow);
                            ExecuteBSkyRemoveRefreshDataframe(stmt);
                            OpenSinkFile(@sinkfilefullpathname, "wt");
                            SetSink();
                            break;
                        case RCommandType.SPLIT: // set/remove split and refresh status bar in main window showing split vars
                            ResetSink();
                            CloseSinkFile();
                            CreateOuput(ow);
                            ExecuteSplit(stmt);
                            OpenSinkFile(@sinkfilefullpathname, "wt");
                            SetSink();
                            break;
                        case RCommandType.RCOMMAND:
                            SendCommandToOutput(stmt, "R-Command");

                            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Categorized. Before execution.", LogLevelEnum.Info);

                            ExecuteOtherCommand(ow, stmt);

                            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Categorized. After execution.", LogLevelEnum.Info);

                            ResetSink();
                            CloseSinkFile();
                            CreateOuput(ow);
                            OpenSinkFile(@sinkfilefullpathname, "wt");
                            SetSink();

                            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Categorized. Before getting graphic if any.", LogLevelEnum.Info);
                            ///02Dec2015 Now add graphic (all of them, from temp location)
                            CreateAllGraphicOutput(ow);//get all grphics and send to output
                            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Categorized. After getting graphic if any.", LogLevelEnum.Info);

                            break;
                        
                        case RCommandType.RDOTNET:
                            InitializeRDotNet();
                            RDotNetOpenDataset();
                            RDotNetExecute(ow);
                            DisposeRDotNet();
                            break;
                        default:
                            break;
                    }//switch
                }
                catch (Exception exc)
                {
                    SendCommandToOutput(exc.Message, "Error:");
                    logService.WriteToLogLevel("Error executing: " + _command, LogLevelEnum.Error);
                    logService.WriteToLogLevel(exc.Message, LogLevelEnum.Error);
                }

                if (breakfor)
                    break;
            }/////for

           //////wrap in sink////////
            ResetSink();
            CloseSinkFile();
        }
        // reading back sink file and creating & displaying output; for non-BSkyFormat commands
        private void CreateOuput(OutputWindow ow)
        {
            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Started creating output.", LogLevelEnum.Info);

            //////////////////// for fetching BSkyFormat object Queue and process each object //////////////////////
            int bskyformatobjectindex = 0;
            bool bskyQFetched = false;
            CommandRequest fetchQ = null;
            string sinkfileBSkyFormatMarker = "[1] \"BSkyFormatInternalSyncFileMarker\"";
            string sinkfileBSkyGraphicFormatMarker = "[1] \"BSkyGraphicsFormatInternalSyncFileMarker\""; //09Jun2015 
            //used to maintain the sequence of print in between BSkyFormats in case of block BSkyFormat
            bool isBlockCommand = false;
            //09Jun2015 used to maintain the sequence of print in between BSkyGraphicFormats in case of block commands
            bool isBlockGraphicCommand = false;

            //for deciding when to send output to output window in case of block BSkyFormat
            //for block BSkyFormat we wait and create all different UI elements first so as to maintain sequence and then send them to output
            //for non-block BSkFormat we send immediately after execution. No stacking up of UI elements ( AUXGrid, AUPara etc..)
            bool isBlock = false;
            ////////////////////////////////////////////////////////////////////////////////////////////////////////

            //if (true) return;
            CommandOutput lst = new CommandOutput(); ////one analysis////////
            CommandOutput grplst = new CommandOutput();//21Nov2013 Separate for Graphic. So Parent node name will be R-Graphic
            lst.IsFromSyntaxEditor = true;//lst belongs to Syn Editor
            if (saveoutput.IsChecked == true)//10Jan2013
                lst.SelectedForDump = true;
            XmlDocument xd = null;
            //string auparas = "";
            StringBuilder sbauparas = new StringBuilder("");
            //////////////// Read output ans message from file and create output then display /////
            //// read line by line  /////
            string sinkfilefullpathname = Path.Combine(System.IO.Path.GetTempPath().Replace("\\", "/"), confService.GetConfigValueForKey("tempsink"));//23nov2012
            // load default value if no path is set or invalid path is set
            if (sinkfilefullpathname.Trim().Length == 0 || !IsValidFullPathFilename(sinkfilefullpathname, true))
            {
                MessageBox.Show(this, "Key 'tempsink' not found in config file. Aborting...");
                return;
            }
            System.IO.StreamReader file = new System.IO.StreamReader(sinkfilefullpathname);// OpenSinkFile(@sinkfilefullpathname, "rt");
            object linetext = null; string line;
            bool insideblock = false;//20May2014
            bool readSinkFile = true;
            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Started reading sink", LogLevelEnum.Info);
            //int imgcount = GraphicDeviceImageCounter;//couter that keeps track of how many images already got processed. Helps in creating a image filename.
            while ((line = file.ReadLine()) != null)//(readSinkFile)
            {
                {
                    linetext = line;
                }

                if (linetext == null || linetext.ToString().Equals("EOF"))
                {
                    break;
                }
                if (linetext != null && linetext.Equals("NULL") && lastcommandwasgraphic)//27May2015 to supress NULL for some listed graphic commands
                {
                    continue;
                }
                if (linetext.ToString().Trim().Contains(sinkfileBSkyFormatMarker))//Contains("[1] \"BSkyFormat\"")) //14Jun2014 if it is BSkyFormat in block (read from sink file)
                {
                    isBlockCommand = true;
                }
                else if (linetext.ToString().Trim().Contains(sinkfileBSkyGraphicFormatMarker))//Contains("[1] \"BSkyGraphicsFormat\"")) //09Jun2015 if it is BSkyGraphicsFormat in block (read from sink file)
                {
                    isBlockGraphicCommand = true;
                }
                else
                {
                    isBlockCommand = false;
                }
                //////// create XML doc /////////
                if (linetext != null)//06May2013 we need formatting so we print blank lines.. && linetext.ToString().Length > 0)
                {
                    /////// Trying to extract command from print //////
                    string commnd = linetext.ToString();
                    int opncurly = commnd.IndexOf("{");
                    int closcurly = commnd.IndexOf("}");
                    int lencommnd = closcurly - opncurly - 1;
                    if (opncurly != -1 && closcurly != -1)
                        commnd = commnd.Substring(opncurly + 1, lencommnd);//could be graphic or BSkyFormat in sink file.
                    if (false)//11Aug2015 fix for BSkyFormat not printed if inside R function. if (commnd.Contains("BSkyFormat("))//09Jun2015 || isGraphicCommand(_command)) // is BSKyFormat or isGraphic Command
                    {
                        SendToOutput(sbauparas.ToString(), ref lst, ow);//22May2014
                        sbauparas.Clear();
                    }
                    else if (isBlockCommand)//14Jun2014 for Block BSkyFormat.
                    {
                        if (sbauparas.Length > 0)
                        {
                            createAUPara(sbauparas.ToString(), lst);//Create & Add AUPara to lst 
                            sbauparas.Clear();
                        }
                    }
                    else
                    {
                        if (sbauparas.Length < 1)
                        {
                            sbauparas.Append(linetext.ToString());//First Line of AUPara. Without \n
                            if (sbauparas.ToString().Trim().IndexOf("BSkyFormat(") == 0)//21Nov2013
                                lst.NameOfAnalysis = "BSkyFormat-Command";
                        }
                        else
                        {
                            //auparas = auparas.Replace("<", "&lt;") + "\n" + linetext.ToString();//all lines separated by new line
                            sbauparas.Append("\n" + linetext.ToString());//all lines separated by new line
                        }
                    }



                    ////for graphics////   //09Jun2015 This whole 'if' may not be needed
                    if (false)
                    {
                        SendToOutput(commnd, ref lst, ow);
                        //////////// Here is new code///////20May2014
                        CommandRequest grpcmd = new CommandRequest();
                        CloseGraphicsDevice();
                        OpenGraphicsDevice();//05May2013
                        grpcmd.CommandSyntax = commnd;// linetext.ToString();
                        analytics.ExecuteR(grpcmd, false, false);
                        CloseGraphicsDevice();
                        insideblock = true;
                        //////////////////////////////////////////////////////////////////////////////////
                        //// add auparas first to lst to maintain order///
                        if (sbauparas.Length > 0)
                        {
                            createAUPara(sbauparas.ToString(), lst);//Create & Add AUPara to lst and empty dommid
                            sbauparas.Clear();
                        }
                        ////// now add image to lst ////
                        string synedtimg = Path.Combine(System.IO.Path.GetTempPath().Replace("\\", "/"), confService.GetConfigValueForKey("sinkimage"));//23nov2012
                        /////03May2013  Create zero padding string //// %03d means 000,  %04d means 0000
                        int percentindex = synedtimg.IndexOf("%");
                        int dindex = synedtimg.IndexOf("d", percentindex);
                        string percentstr = synedtimg.Substring(percentindex, (dindex - percentindex + 1));
                        string numbr = synedtimg.Substring(percentindex + 1, (dindex - percentindex - 1));
                        int zerocount = Convert.ToInt16(numbr);

                        string zeropadding = string.Empty;
                        for (int zeros = 1; zeros <= zerocount; zeros++)
                        {
                            zeropadding = zeropadding + "0";
                        }
                        int img_count = 0;//number of images to load in output
                        for (; ; )//03May2013 earlier there was no for loop for following code
                        {
                            img_count++;
                            string tempsynedtimg = synedtimg.Replace(percentstr, img_count.ToString(zeropadding));
                            // load default value if no path is set or invalid path is set
                            if (tempsynedtimg.Trim().Length == 0 || !IsValidFullPathFilename(tempsynedtimg, true))
                            {
                                break;
                            }
                            string source = @tempsynedtimg;
                            long imgsize = new FileInfo(synedtimg).Length;//find size of the imagefile
                            Image myImage = new Image();
                            ///////////RequestCachePolicy uriCachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheOnly);
                            var bitmap = new BitmapImage();
                            try
                            {
                                var stream = File.OpenRead(source);
                                bitmap.BeginInit();
                                bitmap.CacheOption = BitmapCacheOption.OnLoad;
                                bitmap.StreamSource = stream;
                                bitmap.EndInit();
                                stream.Close();
                                stream.Dispose();
                                myImage.Source = bitmap;
                                bitmap.StreamSource.Close(); //trying to close stream 03Feb2014

                                if (isBlockCommand)
                                    createBSkyGraphic(myImage, lst); //20May2014 If graphic is inside block or loop
                                else
                                    createBSkyGraphic(myImage, grplst); //if graphic is outside block or loop
                                DeleteFileIfPossible(@tempsynedtimg);
                            }
                            catch (Exception ex)
                            {
                                logService.WriteToLogLevel("Error reading Image file " + source + "\n" + ex.Message, LogLevelEnum.Error);
                                MessageBox.Show(this, ex.Message);
                            }

                        }
                        if (img_count < 1) ////03May2013 if no images were added to output lst. then return.
                        {
                            return;
                        }

                    }
                    if (isBlockGraphicCommand)//for block graphics //09Jun2015
                    {
                        CloseGraphicsDevice();
                        insideblock = true;

                        ////// now add image to lst ////
                        string synedtimg = Path.Combine(System.IO.Path.GetTempPath().Replace("\\", "/"), confService.GetConfigValueForKey("sinkimage"));//23nov2012
                        /////03May2013  Create zero padding string //// %03d means 000,  %04d means 0000
                        int percentindex = synedtimg.IndexOf("%");
                        int dindex = synedtimg.IndexOf("d", percentindex);
                        string percentstr = synedtimg.Substring(percentindex, (dindex - percentindex + 1));
                        string numbr = synedtimg.Substring(percentindex + 1, (dindex - percentindex - 1));
                        int zerocount = Convert.ToInt16(numbr);

                        string zeropadding = string.Empty;
                        for (int zeros = 1; zeros <= zerocount; zeros++)
                        {
                            zeropadding = zeropadding + "0";
                        }

                        {
                            GraphicDeviceImageCounter++;//imgcount++;
                            string tempsynedtimg = synedtimg.Replace(percentstr, GraphicDeviceImageCounter.ToString(zeropadding));
                            // load default value if no path is set or invalid path is set
                            if (tempsynedtimg.Trim().Length == 0 || !IsValidFullPathFilename(tempsynedtimg, true))
                            {

                                isBlockGraphicCommand = false; //09Jun2015 reset, as we dont know what next command is. May or may not be graphic marker
                                // not needed if one graphic for one graphic marker imgcount--;
                                break;
                            }
                            string source = @tempsynedtimg;

                            Image myImage = new Image();

                            var bitmap = new BitmapImage();
                            try
                            {
                                var stream = File.OpenRead(source);
                                bitmap.BeginInit();
                                bitmap.CacheOption = BitmapCacheOption.OnLoad;
                                bitmap.StreamSource = stream;
                                bitmap.EndInit();
                                stream.Close();
                                stream.Dispose();
                                myImage.Source = bitmap;
                                bitmap.StreamSource.Close(); //trying to close stream 03Feb2014

                                if (isBlockGraphicCommand)
                                    createBSkyGraphic(myImage, lst); //20May2014 If graphic is inside block or loop
                                else
                                    createBSkyGraphic(myImage, grplst); //if graphic is outside block or loop
                                DeleteFileIfPossible(@tempsynedtimg);
                            }
                            catch (Exception ex)
                            {
                                logService.WriteToLogLevel("Error reading Image file " + source + "\n" + ex.Message, LogLevelEnum.Error);
                                MessageBox.Show(this, ex.Message);
                            }

                        }
                        if (GraphicDeviceImageCounter < 1) ////03May2013 if no images were added to output lst. then return.
                        {
                            sbauparas.Clear();//resetting
                            isBlockGraphicCommand = false;
                            return;
                        }
                        sbauparas.Clear();//resetting
                        isBlockGraphicCommand = false;
                    }
                    else if (isBlockCommand)// (linetext.ToString().Trim().Contains("[1] \"BSkyFormat\""))//21may2014
                    {
                        int bskyfrmtobjcount = 0;
                        if (!bskyQFetched)
                        {
                            fetchQ = new CommandRequest();
                            fetchQ.CommandSyntax = "BSkyQueue = BSkyGetHoldFormatObjList()";// Fetch Queue object
                            analytics.ExecuteR(fetchQ, false, false);

                            fetchQ.CommandSyntax = "is.null(BSkyQueue)";// check if Queue is null
                            object o = analytics.ExecuteR(fetchQ, true, false);//return false or true
                            if (o.ToString().ToLower().Equals("false"))//Queue has elements
                            {
                                bskyQFetched = true;
                            }
                        }
                        if (bskyQFetched)
                        {
                            bskyformatobjectindex++;
                            commnd = "BSkyFormat(BSkyQueue[[" + bskyformatobjectindex + "]])";

                            ExecuteSinkBSkyFormatCommand(commnd, ref bskyfrmtobjcount, lst);
                            lst = new CommandOutput();//"Child already has parent" error, fix
                            isBlock = true;
                        }
                        isBlockCommand = false;//09Jun2015 next command may or may not be BSkyFormat marker.
                    }
                }//if linetext!null
            }//while EOF sink file
            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Finished reading sink", LogLevelEnum.Info);
            file.Close(); //CloseSinkFile();
            SendToOutput(sbauparas.ToString(), ref lst, ow, isBlock);//send output to window or disk file
            SendToOutput(null, ref grplst, ow, isBlock);//21Nov2013. separate node for graphic
            if (lst != null && lst.Count > 0 && isBlock) // Exceutes when there is block command
            {
                sessionlst.Add(lst);//15Nov2013
                lst = new CommandOutput();//after adding to session new object is allocated for futher output creation
            }

            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Finished creating output.", LogLevelEnum.Info);
        }
        //For Painting Output window for BSKyFormated object. And/Or to refresh datagrid for non-analytics commands like sort, compute
        private void RefreshOutputORDataset(string objectname, CommandRequest cmd, string originalCommand, OutputWindow ow)
        {
            UAMenuCommand uamc = new UAMenuCommand();
            cmd.CommandSyntax = "is.null(" + objectname + "$BSkySplit)";//$BSkySplit or $split in return structure
            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info);
            // is it just a list(non Bsky) or its a list that contains tables (user tables or Bsky Stat result tables)
            bool isNonBSkyList = false;
            object isNonBSkyListstr = analytics.ExecuteR(cmd, true, false);
            if (isNonBSkyListstr != null && isNonBSkyListstr.ToString().ToLower().Equals("true"))
            {
                isNonBSkyList = true;
            }
            if (isNonBSkyList)
            {
                string ewmessage = "This Object cannot be formatted using BSKyFormat. BSkyFormat can be used on Array, Matrix, Data Frame and BSky List objects only.";
                SendErrorToOutput(ewmessage, ow);//03Jul2013
                return;
            }
            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: $BSkySplit Result (false means non-bsky list): " + isNonBSkyList, LogLevelEnum.Info);

            cmd.CommandSyntax = objectname + "$uasummary[[7]]";
            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info);

            string bskyfunctioncall = (string)analytics.ExecuteR(cmd, true, false);//actual call with values
            if (bskyfunctioncall == null)
            {
                bskyfunctioncall = ""; //24Apr2014 This is when no Dataset is open. And Syntax editor is open.Not returning, instead putting blank.
            }
            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: $uasummary[[7]] Result : " + bskyfunctioncall, LogLevelEnum.Info);
            string bskyfunctionname = "";
            if (bskyfunctioncall.Length > 0)
            {
                if (bskyfunctioncall.Contains("("))
                    bskyfunctionname = bskyfunctioncall.Substring(0, bskyfunctioncall.IndexOf('(')).Trim();
                else
                    bskyfunctionname = bskyfunctioncall;
            }
            uamc.commandformat = objectname;// object that stores the result of analysis
            uamc.bskycommand = bskyfunctioncall.Replace('\"', '\'');// actual BSkyFunction call. " quotes replaced by '
            uamc.commandoutputformat = bskyfunctionname.Length > 0 ? string.Format(@"{0}", BSkyAppData.BSkyDataDirConfigBkSlash) + bskyfunctionname + ".xml" : "";//23Apr2015 
            uamc.commandtemplate = bskyfunctionname.Length > 0 ? string.Format(@"{0}", BSkyAppData.BSkyDataDirConfigBkSlash) + bskyfunctionname + ".xaml" : "";//23Apr2015 

            uamc.commandtype = originalCommand;
            CommandExecutionHelper auacb = new CommandExecutionHelper();
            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: CommandExecutionHelper: " , LogLevelEnum.Info);
            auacb.ExecuteSyntaxEditor(uamc, saveoutput.IsChecked == true ? true : false);//10JAn2013 edit
            auacb = null;

        }
 //22Nov2013 for sending session contents to output window.
 //This gives us control to send output each time "RUN" is clicked and for batch command 
 //this method can be called when last slice contents get appended to sessionlist
 public void DisplayAllSessionOutput(string sessionheader = "", OutputWindow selectedOW=null)//06May2015 slectedOW param added
 {
     sessionlst.NameOfSession = sessionheader;
     sessionlst.isRSessionOutput = true;
     //if (sessionheader.Trim().Length > 1)
     if(sessionlst.Count>0)//07Nov2014
     {
         if (selectedOW == null)
         {
             //for dialog batch commads say 'lm' sessionheader will have some dialog title like 'lm'
             ow.AddSynEdtSessionOutput(sessionlst);//send output to 'Active' marked output window.
         }
         else
         {
             selectedOW.AddSynEdtSessionOutput(sessionlst);//send output to specific window from where command was executed
         }
     }
     sessionlst = new SessionOutput();//28Nov2013 for creating  new instance and not deleting old one
 }
        private void SendErrorToOutput(string ewmessage, OutputWindow ow) //03Jul2013 error warning message
        {
            object o;
            CommandRequest cmd = new CommandRequest();
            string sinkfilefullpathname = Path.Combine(System.IO.Path.GetTempPath().Replace("\\", "/"), confService.GetConfigValueForKey("tempsink"));//23nov2012
            // load default value if no path is set or invalid path is set
            if (sinkfilefullpathname.Trim().Length == 0 || !IsValidFullPathFilename(sinkfilefullpathname, false))
            {
                MessageBox.Show(this, "Key 'tempsink' not found in config file. Aborting...");
                return;
            }
            OpenSinkFile(@sinkfilefullpathname, "wt"); //06sep2012
            SetSink(); //06sep2012

            cmd.CommandSyntax = "write(\"" + ewmessage + ".\",fp)";// command 
            o = analytics.ExecuteR(cmd, false, false);

            ResetSink();//06sep2012
            CloseSinkFile();//06sep2012
            CreateOuput(ow);//06sep2012
        }
        private void ExecuteOtherCommand(OutputWindow ow, string stmt)
        {

            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Before Executing in R.", LogLevelEnum.Info);


            #region Check open close brackets before executing
            string unbalmsg;
            if (!AreBracketsBalanced(stmt, out unbalmsg))//if unbalanced brackets
            {
                CommandRequest errmsg = new CommandRequest();
                string fullmsg = "Error : " + unbalmsg;
                errmsg.CommandSyntax = "write(\"" + fullmsg.Replace("<", "&lt;").Replace('"', '\'') + "\",fp)";//
                analytics.ExecuteR(errmsg, false, false); //for printing command in file
                return;
            }
            #endregion
            ///if command is for loading dataset //
            if (stmt.Contains("UAloadDataset"))
            {
                int indexofopening = stmt.IndexOf('(');
                int indexofclosing = stmt.IndexOf(')');
                string[] parameters = stmt.Substring(indexofopening + 1, indexofclosing - indexofopening - 2).Split(',');
                string filename = string.Empty;
                foreach (string s in parameters)
                {
                    if (s.Contains('/') || s.Contains('\\'))
                        filename = s.Replace('\"', ' ').Replace('\'', ' ');
                }
                if (filename.Contains("="))
                {
                    filename = filename.Substring(filename.IndexOf("=") + 1);
                }
                FileOpenCommand fo = new FileOpenCommand();
                fo.FileOpen(filename.Trim());
                return;
            }

            object o = null;
            CommandRequest cmd = new CommandRequest();

            if (stmt.Contains("BSkySortDataframe(") ||
                stmt.Contains("BSkyComputeExpression(") || stmt.Contains("BSkyRecode("))
            {
                CommandExecutionHelper auacb = new CommandExecutionHelper();
                UAMenuCommand uamc = new UAMenuCommand();
                uamc.bskycommand = stmt;
                uamc.commandtype = stmt;
                auacb.ExeuteSingleCommandWithtoutXML(stmt);//auacb.ExecuteSynEdtrNonAnalysis(uamc);
                auacb.Refresh_Statusbar();
                //auacb = null;
            }
            else
            {

                if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing in R.", LogLevelEnum.Info);

 
                 isVariable(ref stmt);///for checking if its variable then it must be enclosed within print();
                                      
                //27May2015 check if command is graphic and get its height width and then reopen graphic device with new dimensions
                 if (lastcommandwasgraphic)//listed graphic
                 {
                     if (imgDim!=null && imgDim.overrideImgDim)
                     {
                         CloseGraphicsDevice();
                         OpenGraphicsDevice(imgDim.imagewidth, imgDim.imageheight); // get image dimenstion from external source for this particular graphic.
                     }
                 }


                cmd.CommandSyntax = stmt;// command 
                o = analytics.ExecuteR(cmd, false, false);   //// get Direct Result and write in sink file

                CommandRequest cmdprn = new CommandRequest();
                if (o != null && o.ToString().Contains("Error"))//for writing some of the errors those are not taken care by sink.
                {
                    cmdprn.CommandSyntax = "write(\"" + o.ToString() + "\",fp)";// http://www.w3schools.com/xml/xml_syntax.asp
                    o = analytics.ExecuteR(cmdprn, false, false); /// for printing command in file
                    
                    ///if there is error in assignment, like RHS caused error and LHS var is never updated
                    ///Better make LHS var null.
                    string lhvar = string.Empty;
                    GetLeftHandVar(stmt, out lhvar);
                    if (lhvar != null)
                    {
                        cmd.CommandSyntax = lhvar+" <- NULL";// assign null 
                        o = analytics.ExecuteR(cmd, false, false);
                    }
                }
            }

            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: After Executing in R.", LogLevelEnum.Info);

            
        }
        private void RDotNetExecute(OutputWindow ow)
        {
            CommandOutput lst = new CommandOutput();
            lst.IsFromSyntaxEditor = true;

            engine.Evaluate("BSky_One_Way_Anova = as.data.frame (summary(dd <- aov(mpg ~ year,data=Dataset1))[[1]])");
            engine.Evaluate("bskyfrmtobj <- BSkyFormat(BSky_One_Way_Anova)");
            CharacterMatrix cmatrix = engine.Evaluate("bskyfrmtobj").AsCharacterMatrix();
            string[,] mtx = new string[cmatrix.RowCount, cmatrix.ColumnCount];
            for (int r = 0; r < cmatrix.RowCount; r++)
            {
                for (int c = 0; c < cmatrix.ColumnCount; c++)
                {
                    mtx[r, c] = cmatrix[r, c];
                }
            }
            string objectname = "bskyfrmtobj";
            string headername = "This is generated in R.NET";

            CommandRequest cmddf = new CommandRequest();
            int dimrow = 1, dimcol = 1;
            bool rowexists = false, colexists = false;
            string dataclassname = string.Empty;

            //Find class of data passed. data.frame, matrix, or array
            cmddf.CommandSyntax = "class(" + objectname + ")"; // Row exists
            object retres = engine.Evaluate(cmddf.CommandSyntax).AsCharacter()[0];

            if (retres != null)
                dataclassname = retres.ToString();

            //find if dimension exists
            cmddf.CommandSyntax = "!is.na(dim(" + objectname + ")[1])"; // Row exists
            rowexists = engine.Evaluate(cmddf.CommandSyntax).AsLogical()[0];

            cmddf.CommandSyntax = "!is.na(dim(" + objectname + ")[2])";// Col exists
            colexists = engine.Evaluate(cmddf.CommandSyntax).AsLogical()[0];

            /// Find size of matrix(objectname) & initialize data array ///
            if (rowexists)
            {
                cmddf.CommandSyntax = "dim(" + objectname + ")[1]";
                retres = engine.Evaluate(cmddf.CommandSyntax).AsInteger()[0];
                if (retres != null)
                    dimrow = Int16.Parse(retres.ToString());
            }
            if (colexists)
            {
                cmddf.CommandSyntax = "dim(" + objectname + ")[2]";
                retres = engine.Evaluate(cmddf.CommandSyntax).AsInteger()[0];
                if (retres != null)
                    dimcol = Int16.Parse(retres.ToString());
            }
            string[,] data = new string[dimrow, dimcol];
            //// now create FlexGrid and add to lst ///
            /////////finding Col headers /////
            cmddf.CommandSyntax = "colnames(" + objectname + ")";
            CharacterVector colhdrobj = engine.Evaluate(cmddf.CommandSyntax).AsCharacter();
            string[] colheaders;
            if (colhdrobj != null && !colhdrobj.ToString().Contains("Error"))
            {
                if (true)//colhdrobj.GetType().IsArray)
                {
                    int siz = colhdrobj.Count();
                    colheaders = new string[siz];
                    for (int ri = 0; ri < siz; ri++)
                    {
                        colheaders[ri] = colhdrobj[ri];
                    }

                }
                else
                {
                    colheaders = new string[1];
                    colheaders[0] = colhdrobj.ToString();
                }
            }
            else
            {
                colheaders = new string[dimcol];
                for (int i = 0; i < dimcol; i++)
                    colheaders[i] = (i + 1).ToString();
            }

            /////////finding Row headers /////

            //read configuration and then decide to pull row headers

            bool shownumrowheaders = true; /// 

            cmddf.CommandSyntax = "rownames(" + objectname + ")";
            CharacterVector rowhdrobj =  engine.Evaluate(cmddf.CommandSyntax).AsCharacter();
            string[] rowheaders;// = (string[])rowhdrobj;//{ "11", "22", "33" };
            if (rowhdrobj != null && !rowhdrobj.ToString().Contains("Error"))
            {
                if (true)//rowhdrobj.GetType().IsArray)
                {
                    int siz = rowhdrobj.Count();
                    rowheaders = new string[siz];
                    for (int ri = 0; ri < siz; ri++)
                    {
                        rowheaders[ri] = rowhdrobj[ri];
                    }

                    //rowheaders = (string[])rowhdrobj;//{ "Aa", "Bb", "Cc" };//
                }
                else
                {
                    rowheaders = new string[1];
                    rowheaders[0] = rowhdrobj.ToString();
                }
            }
            else
            {
                rowheaders = new string[dimrow];
                //Type 1.//filling number for row header if rowheader is not present
                for (int i = 0; i < dimrow; i++)
                    rowheaders[i] = (i + 1).ToString();

            }

            bool isnumericrowheaders = true; // assuming that row headers are numeric
            short tnum;
            for (int i = 0; i < dimrow; i++)
            {
                if (!Int16.TryParse(rowheaders[i], out tnum))
                {
                    isnumericrowheaders = false; //row headers are non-numeric
                    break;
                }
                //if (i == 10)//just cheking first 10 numbers for being int. Not cheking all the row headers.
                //    break;
            }

            if (isnumericrowheaders && !shownumrowheaders)
            {
                //Type 2.//filling empty values for row header if rowheader is not present
                for (int i = 0; i < dimrow; i++)
                    rowheaders[i] = "";
            }

            /// Populating array using data frame data
            bool isRowEmpty = true;//for Virtual. 
            int emptyRowCount = 0;//for Virtual. 
            List<int> emptyRowIndexes = new List<int>(); //for Virtual.
            string cellData = string.Empty;
            for (int r = 1; r <= dimrow; r++)
            {
                isRowEmpty = true;//for Virtual. 
                for (int c = 1; c <= dimcol; c++)
                {
                    if (dimcol == 1 && !dataclassname.ToLower().Equals("data.frame"))
                        cmddf.CommandSyntax = "as.character(" + objectname + "[" + r + "])";
                    else
                        cmddf.CommandSyntax = "as.character(" + objectname + "[" + r + "," + c + "])";

                    object v = engine.Evaluate(cmddf.CommandSyntax).AsCharacter()[0];
                    cellData = (v != null) ? v.ToString().Trim() : "";
                    data[r - 1, c - 1] = cellData;// v.ToString().Trim();

                    //for Virtual. // cell is non-empty in row, means row is non empty because of atleast 1 col
                    if (cellData.Length > 0)
                        isRowEmpty = false;
                }

                //for Virtual. // counting empty rows for virtual
                if (isRowEmpty)
                {
                    emptyRowCount++;
                    emptyRowIndexes.Add(r - 1);//making it zero based as in above nested 'for'
                }
            }

            // whether you want C1Flexgrid to be generated by using XML DOM or by Virtual class(Dynamic)
            bool DOMmethod = false;
            if (DOMmethod)
            {
                //12Aug2014 Old way of creating grid using DOM and then creating and filling grid step by step
                XmlDocument xdoc = createFlexGridXmlDoc(colheaders, rowheaders, data);
                //string xdoc = "<html><body><table><thead><tr><th class=\"h\"></th><th class=\"c\">A</th><th class=\"c\">B</th></tr></thead><tbody><tr><td class=\"h\">X</td><td class=\"c\">5</td><td class=\"c\">6</td></tr><tr><td class=\"h\">Y</td><td class=\"c\">8</td><td class=\"c\">9</td></tr></tbody></table></body></html>";
                createFlexGrid(xdoc, lst, headername);// headername = 'varname' else 'leftvarname' else 'objclass'
            }
            else//virutal list method
            {
                //There is no logic to remove empty rows in this vitual list method so
                //here we try to send data with non-empty rows by dropping empty ones first.
                if (emptyRowCount > 0)
                {
                    int nonemptyrowcount = dimrow - emptyRowCount;
                    string[,] nonemptyrowsdata = new string[nonemptyrowcount, dimcol];
                    string[] nonemptyrowheaders = new string[nonemptyrowcount];
                    for (int rr = 0, rrr = 0; rr < data.GetLength(0); rr++)
                    {
                        if (emptyRowIndexes.Contains(rr))//skip empty rows.
                            continue;
                        for (int cc = 0; cc < data.GetLength(1); cc++)
                        {
                            nonemptyrowsdata[rrr, cc] = data[rr, cc];//only copy non-empty rows
                        }
                        nonemptyrowheaders[rrr] = rowheaders[rr];//copying row headers too.
                        rrr++;
                    }
                    //Using Dynamic Class creation and then populating the grid. //12Aug2014
                    CreateDynamicClassFlexGrid(headername, colheaders, nonemptyrowheaders, nonemptyrowsdata, lst);
                }
                else
                {
                    //Using Dynamic Class creation and then populating the grid. //12Aug2014
                    CreateDynamicClassFlexGrid(headername, colheaders, rowheaders, data, lst);
                }
            }
            if (ow != null)//22May2014
                SendToOutput("", ref lst, ow);//send dataframe/matrix/array to output window or disk file
        }
 //No Need of following. Logic changed
 //15Apr2014. List location 1 will have listname and number of tables it caontains. Location 2 onwards are tables. 1 table per location.
 private void FormatBSkyList2(CommandOutput lst, string objectname, string headername, OutputWindow ow) // for BSky list2 processing
 {
     MessageBox.Show(this, "BSkyList2 Processing... close this box");
 }
        private void ExecuteBSkyFormatCommand(string stmt, ref int bskyfrmtobjcount, OutputWindow ow)
        {
            KillTempBSkyFormatObj("bskytempvarname");
            KillTempBSkyFormatObj("bskyfrmtobj");

            string originalCommand = stmt;
            CommandOutput lst = new CommandOutput(); ////one analysis////////
            lst.IsFromSyntaxEditor = true;//lst belongs to Syn Editor
            if (saveoutput.IsChecked == true)//10Jan2013
                lst.SelectedForDump = true;

            object o;
            CommandRequest cmd = new CommandRequest();
            /// find argument passed in BSkyFormat(argu) and var name  ////
            /// eg.. BSkyFormat(osmt <-one.smt.t.test(....) )
            /// subcomm will be : osmt<-one.smt.t.test(....) 
            /// varname will be : osmt
            string subcomm = string.Empty, varname = string.Empty, BSkyLeftVar = string.Empty, headername = string.Empty;
            string firstparam = string.Empty, restparams = string.Empty, leftvarname = string.Empty;//23Sep2014
            string userpassedtitle = string.Empty;
            //SplitBSkyFormat(stmt, out subcomm, out varname, out BSkyLeftVar);
            SplitBSkyFormatParams(stmt, out firstparam, out restparams, out userpassedtitle);//23Spe2014
            if (userpassedtitle.Trim().Length > 0)//user passed title has the highest priority
            {
                headername = userpassedtitle.Trim();
            }
            
            {
                //23Sep2014 if firstParam is of the type obj<-OSMT(...) OR obj<-obj2
                if (firstparam.Contains("<-") || firstparam.Contains("=")) //if it has assignment
                {
                    int idxassign=-1, idxopenbrket=-1;
                    if(firstparam.Contains("("))// if obj<-OSMT(...)
                    {
                        idxopenbrket = firstparam.IndexOf("(");
                        string firsthalf = firstparam.Substring(0,idxopenbrket);// "obj <- OSMT("
                        idxassign = firsthalf.IndexOf("<-");
                        if (idxassign == -1)// '<-' not present(found in half)
                            idxassign = firsthalf.IndexOf("=");
                    }

                    if (idxassign > -1 && idxopenbrket > -1 && idxopenbrket > idxassign)
                    {
                        leftvarname = firstparam.Substring(0, idxassign);
                        headername = leftvarname.Trim();
                        cmd.CommandSyntax = firstparam;// command: osmt<-one.smt.tt(...)
                        o = analytics.ExecuteR(cmd, false, false);//executing sub-command; osmt<-one.smt.tt(...)

                    }
                    else if (idxopenbrket < 0 )//type obj <- obj2
                    {
                        idxassign = firstparam.IndexOf("<-");
                        if (idxassign == -1)// '<-' not present
                            idxassign = firstparam.IndexOf("=");
                        if (idxassign > -1)//if assignment is there
                        {
                            leftvarname = firstparam.Substring(0, idxassign);
                            headername = leftvarname.Trim();
                            cmd.CommandSyntax = firstparam;// command: osmt<-one.smt.tt(...)
                            o = analytics.ExecuteR(cmd, false, false);//executing sub-command; osmt<-one.smt.tt(...)
                        }
                    }
                }

                /////25Feb2013 for writing errors in OutputWindow////
                string sinkfilefullpathname = Path.Combine(System.IO.Path.GetTempPath().Replace("\\", "/"), confService.GetConfigValueForKey("tempsink")); //23nov2012
                // load default value if no path is set or invalid path is set
                if (sinkfilefullpathname.Trim().Length == 0 || !IsValidFullPathFilename(sinkfilefullpathname, false))
                {
                    MessageBox.Show(this, "Key 'tempsink' not found in config file. Aborting...");
                    return; //return type was void before 22May2014
                }
                OpenSinkFile(@sinkfilefullpathname, "wt"); //06sep2012
                SetSink(); //06sep2012

                ////////////////////////////////////////////////////////////////////////
                //13Aug2012 headername = findHeaderName(subcomm); // data.frame / matrix / array header 
                varname = "bskytempvarname";
                KillTempBSkyFormatObj(varname);

                //Now run command
                firstparam = (leftvarname.Trim().Length>0? leftvarname : firstparam);
                //23Sep2014 cmd.CommandSyntax = varname + " <- " + subcomm;// command: varname <- one.smt.tt(...)
                cmd.CommandSyntax = varname + " <- " + firstparam;// varname <- obj OR OSMT()
                o = analytics.ExecuteR(cmd, false, false);//executing sub-command
                ////////////////////////////////////////////////////////////////////////

                /////25Feb2013 for writing errors in OutputWindow////
                ResetSink();
                CloseSinkFile();
                CreateOuput(ow);
            }

            //if var does not exists then there could be error in command execution.
            cmd.CommandSyntax = "exists('" + varname + "')";
            o = analytics.ExecuteR(cmd, true, false);
            if (o.ToString().ToLower().Equals("false"))//possibly some error occured
            {
                string ewmessage = "Object cannot be formatted using BSKyFormat. Object: " + firstparam + ", does not exists.";
                //if (ow != null)//22May2014
                SendErrorToOutput(originalCommand + "\n" + ewmessage, ow); //03Jul2013
                return; //return type was void before 22May2014
            }

            //Check if varname is null
            cmd.CommandSyntax = "is.null(" + varname + ")";
            o = analytics.ExecuteR(cmd, true, false);
            if (o.ToString().ToLower().Equals("true"))//possibly some error occured
            {
                string ewmessage = "Object cannot be formatted using BSKyFormat. Object: " + firstparam + ", is null.";
                SendErrorToOutput(originalCommand + "\n" + ewmessage, ow); //03Jul2013
                return; //return type was void before 22May2014
            }


            //setting up flag for showing default ("1","2","3" )row headers.
            //This will not work if BSkyReturnStructure is returned(in varname).
            bsky_no_row_header = false;
            cmd.CommandSyntax = "is.null(row.names(" + varname + ")[1])";
            o = analytics.ExecuteR(cmd, true, false);
            if (o.ToString().ToLower().Equals("false"))//row name at [1] exists
            {
                cmd.CommandSyntax = "row.names(" + varname + ")[1]";
                o = analytics.ExecuteR(cmd, true, false);
                if (o.ToString().Trim().ToLower().Equals("bsky_no_row_header"))
                {
                    bsky_no_row_header = true;
                }
            }

            //one mandatory parameter
            string mandatoryparamone = ", bSkyFormatAppRequest = TRUE";
            if (restparams.Trim().Length > 0 && restparams.Trim().Contains("bSkyFormatAppRequest"))//if parameter is already present, no need to add it.
            {
                mandatoryparamone = string.Empty;
            }

            //second mandatory parameter
            string mandatoryparamtwo = ", singleTableOutputHeader = '" + headername + "'"; //   \"c(\\\"a\\\")\" )"
            if (restparams.Trim().Length > 0 && restparams.Trim().Contains("singleTableOutputHeader"))//if parameter is already present, no need to add it.
            {
                mandatoryparamtwo = string.Empty;
            }

            //create BSkyFormat command for execution and execute
            if(restparams.Trim().Length > 0)
                stmt = "BSkyFormat(" + varname + mandatoryparamone + mandatoryparamtwo +","+restparams+")";//stmt = "BSkyFormat(" + varname + ")";
            else
                stmt = "BSkyFormat(" + varname + mandatoryparamone + mandatoryparamtwo+" )";

            stmt = BSkyLeftVar + stmt;// command is BSkyLeftVar <- BSkyFormat(varname)
            /// BSkyLeftVar <- can be blank if user has no assigned leftvar to BSkyFormat

            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Command reconstructed : " + stmt, LogLevelEnum.Info);

            string objclass = "", objectname = "";

            if (stmt.Contains("BSkyFormat("))// Array, Matrix, Data Frame or BSkyObject(ie..Analytic commands)
            {
                bskyfrmtobjcount++;
                stmt = "bskyfrmtobj <- " + stmt; // BSkyFormat has BSkyFormat2 call inside of it
                objectname = "bskyfrmtobj";// +bskyfrmtobjcount.ToString();
                cmd.CommandSyntax = stmt;// command 
                o = analytics.ExecuteR(cmd, false, false);//executing BSkyFormat

                ///Check if returned object is null
                cmd.CommandSyntax = "is.null(" + objectname + ")";
                o = analytics.ExecuteR(cmd, true, false);
                if (o.ToString().ToLower().Equals("true"))//possibly some error occured
                {
                    string ewmessage = "Object cannot be formatted using BSKyFormat. Type not supported. Supported types are :\n array, matrix dataframe and BSky return structure.";
                    SendErrorToOutput(originalCommand + "\n" + ewmessage, ow); //03Jul2013
                    return; //return type was void before 22May2014
                }

                #region Generate UI for data.frame/ matrix / array and analytics commands
                if (BSkyLeftVar.Trim().Length < 1) // if left var does not exists then generate UI tables
                {
                    lst.NameOfAnalysis = originalCommand.Contains("BSkyFormat") ? "BSkyFormat-Command" : originalCommand;
                    //cmd.CommandSyntax = "class(bskyfrmtobj" + bskyfrmtobjcount.ToString() + ")";
                    cmd.CommandSyntax = "class(bskyfrmtobj)";
                    objclass = (string)analytics.ExecuteR(cmd, true, false);

                    if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: BSkyFormat object type : " + objclass, LogLevelEnum.Info);

                    if (objclass.ToString().ToLower().Equals("data.frame") || objclass.ToString().ToLower().Equals("matrix") || objclass.ToString().ToLower().Equals("array"))
                    {
                        if (headername != null && headername.Trim().Length < 1) //06May2014
                            headername = subcomm;
                        if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: BSkyFormatting DF/Matrix/Arr : " + objclass, LogLevelEnum.Info);
                        BSkyFormatDFMtxArr(lst, objectname, headername, ow);
                    }
                    else if (objclass.ToString().ToLower().Equals("list"))//BSkyObject returns "list"
                    {
                        if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: BSkyFormatting : " + objclass, LogLevelEnum.Info);
                        SendToOutput("", ref lst, ow);
                        ///tetsing whole else if
                        objectname = "bskyfrmtobj";// +bskyfrmtobjcount.ToString();
                        
                        cmd.CommandSyntax = "is.null(" + objectname + "$BSkySplit)";//$BSkySplit or $split in return structure
                        if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info);
                        bool isNonBSkyList1=false;
                        object isNonBSkyList1str = analytics.ExecuteR(cmd, true, false);
                        if (isNonBSkyList1str != null && isNonBSkyList1str.ToString().ToLower().Equals("true"))
                        {
                            isNonBSkyList1 = true;
                        }
                        cmd.CommandSyntax = "is.null(" + objectname + "$list2name)";//another type pf BSky list
                        if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info);
                        bool isNonBSkyList2=false ;
                        object isNonBSkyList2str = analytics.ExecuteR(cmd, true, false);
                        if (isNonBSkyList2str != null && isNonBSkyList2str.ToString().ToLower().Equals("true"))
                        {
                            isNonBSkyList2 = true;
                        }

                        if (!isNonBSkyList1)
                        {
                            //if there was error in execution, say because non scale field has scale variable
                            // so now if we first check if $executionstatus = -2, we know that some error has occured.
                            cmd.CommandSyntax = objectname + "$executionstatus";//$BSkySplit or $split in return structure
                            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info);
                            object errstat = analytics.ExecuteR(cmd, true, false);
                            if (errstat != null && (errstat.ToString().ToLower().Equals("-2") || errstat.ToString().ToLower().Equals("-1")))
                            {
                                if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Execution Stat : " + errstat, LogLevelEnum.Info);
                                if(errstat.ToString().ToLower().Equals("-2"))
                                    SendErrorToOutput("Critical Error Occurred!", ow);//15Jan2015
                                else
                                    SendErrorToOutput("Error Occurred!", ow);//03Jul2013
                            }

                            cmd.CommandSyntax = objectname + "$nooftables";//$nooftables=0, means no data to display. Not even error warning tables are there.
                            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info);
                            object retval = analytics.ExecuteR(cmd, true, false);
                            if (retval != null && retval.ToString().ToLower().Equals("0"))
                            {
                                if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: No of Tables : " + retval, LogLevelEnum.Info);
                                SendErrorToOutput("No tables to show in output!", ow);//03Jul2013
                            }

                            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Start creating actual UI tables : ", LogLevelEnum.Info);
                            //finally we can now format the tables of BSkyReturnStruture list
                            RefreshOutputORDataset(objectname, cmd, originalCommand, ow); //list like one sample etc..
                        }
                        else if (!isNonBSkyList2)
                        {
                            //if (ow != null)//22May2014
                            FormatBSkyList2(lst, objectname, headername, ow); //list that contains tables 2nd location onwards
                        }
                    }
                    else // invalid format
                    {
                        /// put it in right place
                        string ewmessage = "This Object cannot be formatted using BSKyFormat. BSkyFormat can be used on Array, Matrix, Data Frame and BSky List objects only";
                        //if (ow != null)//22May2014
                        SendErrorToOutput(originalCommand + "\n" + ewmessage, ow);//03Jul2013
                    }
                }/// if leftvar is not assigned generate UI
                #endregion
            }
            return;//22May2014
        }
        //pulled out from ExecuteBSkyFromatCommand() method above. For BskyFormat DataFrame Matrix Array
        private void BSkyFormatDFMtxArr(CommandOutput lst, string objectname, string headername, OutputWindow ow)
        {
            CommandRequest cmddf = new CommandRequest();
            int dimrow = 1, dimcol = 1;
            bool rowexists = false, colexists = false;
            string dataclassname = string.Empty;

            //Find class of data passed. data.frame, matrix, or array
            cmddf.CommandSyntax = "class(" + objectname + ")"; // Row exists
            object retres = analytics.ExecuteR(cmddf, true, false);
            if (retres != null)
                dataclassname = retres.ToString();

            //find if dimension exists
            cmddf.CommandSyntax = "!is.na(dim(" + objectname + ")[1])"; // Row exists
            retres = analytics.ExecuteR(cmddf, true, false);
            if (retres != null && retres.ToString().ToLower().Equals("true"))
                rowexists = true;
            cmddf.CommandSyntax = "!is.na(dim(" + objectname + ")[2])";// Col exists
            retres = analytics.ExecuteR(cmddf, true, false);
            if (retres != null && retres.ToString().ToLower().Equals("true"))
                colexists = true;
            /// Find size of matrix(objectname) & initialize data array ///
            if (rowexists)
            {
                cmddf.CommandSyntax = "dim(" + objectname + ")[1]";
                retres = analytics.ExecuteR(cmddf, true, false);
                if (retres != null)
                    dimrow = Int16.Parse(retres.ToString());
            }
            if (colexists)
            {
                cmddf.CommandSyntax = "dim(" + objectname + ")[2]";
                retres = analytics.ExecuteR(cmddf, true, false);
                if (retres != null)
                    dimcol = Int16.Parse(retres.ToString());
            }
            string[,] data = new string[dimrow, dimcol];
            //// now create FlexGrid and add to lst ///
            /////////finding Col headers /////
            cmddf.CommandSyntax = "colnames(" + objectname + ")";
            object colhdrobj = analytics.ExecuteR(cmddf, true, false);
            string[] colheaders;
            if (colhdrobj != null && !colhdrobj.ToString().Contains("Error"))
            {
                if (colhdrobj.GetType().IsArray)
                    colheaders = (string[])colhdrobj;//{ "Aa", "Bb", "Cc" };//
                else
                {
                    colheaders = new string[1];
                    colheaders[0] = colhdrobj.ToString();
                }
            }
            else
            {
                colheaders = new string[dimcol];
                for (int i = 0; i < dimcol; i++)
                    colheaders[i] = (i + 1).ToString();
            }

            /////////finding Row headers /////

            //read configuration and then decide to pull row headers

            string numrowheader = confService.AppSettings.Get("numericrowheaders");
            // load default value if no value is set 
            if (numrowheader.Trim().Length == 0)
                numrowheader = confService.DefaultSettings["numericrowheaders"];
            bool shownumrowheaders = numrowheader.ToLower().Equals("true") ? true : false; /// 

            cmddf.CommandSyntax = "rownames(" + objectname + ")";
            object rowhdrobj = analytics.ExecuteR(cmddf, true, false);
            string[] rowheaders;// = (string[])rowhdrobj;//{ "11", "22", "33" };
            if (rowhdrobj != null && !rowhdrobj.ToString().Contains("Error"))
            {
                if (rowhdrobj.GetType().IsArray)
                    rowheaders = (string[])rowhdrobj;//{ "Aa", "Bb", "Cc" };//
                else
                {
                    rowheaders = new string[1];
                    rowheaders[0] = rowhdrobj.ToString();
                }
            }
            else
            {
                rowheaders = new string[dimrow];
                //Type 1.//filling number for row header if rowheader is not present
                for (int i = 0; i < dimrow; i++)
                    rowheaders[i] = (i + 1).ToString();

            }

            bool isnumericrowheaders = true; // assuming that row headers are numeric
            short tnum;
            for (int i = 0; i < dimrow; i++)
            {
                if (!Int16.TryParse(rowheaders[i], out tnum))
                {
                    isnumericrowheaders = false; //row headers are non-numeric
                    break;
                }
            }

            if (isnumericrowheaders && !shownumrowheaders)
            {
                //Type 2.//filling empty values for row header if rowheader is not present
                for (int i = 0; i < dimrow; i++)
                    rowheaders[i] = "";
            }

            /// Populating array using data frame data
            
            bool isRowEmpty = true;//for Virtual. 
            int emptyRowCount = 0;//for Virtual. 
            List<int> emptyRowIndexes = new List<int>(); //for Virtual.
            string cellData = string.Empty;
            for (int r = 1; r <= dimrow; r++)
            {
                isRowEmpty = true;//for Virtual. 
                for (int c = 1; c <= dimcol; c++)
                {
                    if (dimcol == 1 && !dataclassname.ToLower().Equals("data.frame"))
                        cmddf.CommandSyntax = "as.character(" + objectname + "[" + r + "])";
                    else
                        cmddf.CommandSyntax = "as.character(" + objectname + "[" + r + "," + c + "])";

                    object v = analytics.ExecuteR(cmddf, true, false);
                    cellData = (v != null) ? v.ToString().Trim() : "";
                    data[r - 1, c - 1] = cellData;// v.ToString().Trim();

                    //for Virtual. // cell is non-empty in row, means row is non empty because of atleast 1 col
                    if (cellData.Length > 0)
                        isRowEmpty = false;
                }

                //for Virtual. // counting empty rows for virtual
                if (isRowEmpty)
                {
                    emptyRowCount++;
                    emptyRowIndexes.Add(r - 1);//making it zero based as in above nested 'for'
                }
            }

            // whether you want C1Flexgrid to be generated by using XML DOM or by Virtual class(Dynamic)
            bool DOMmethod = false;
            if (DOMmethod)
            {
                //12Aug2014 Old way of creating grid using DOM and then creating and filling grid step by step
                XmlDocument xdoc = createFlexGridXmlDoc(colheaders, rowheaders, data);
                //string xdoc = "<html><body><table><thead><tr><th class=\"h\"></th><th class=\"c\">A</th><th class=\"c\">B</th></tr></thead><tbody><tr><td class=\"h\">X</td><td class=\"c\">5</td><td class=\"c\">6</td></tr><tr><td class=\"h\">Y</td><td class=\"c\">8</td><td class=\"c\">9</td></tr></tbody></table></body></html>";
                createFlexGrid(xdoc, lst, headername);// headername = 'varname' else 'leftvarname' else 'objclass'
            }
            else//virutal list method
            {
                //There is no logic to remove empty rows in this vitual list method so
                //here we try to send data with non-empty rows by dropping empty ones first.
                if (emptyRowCount > 0)
                {
                    int nonemptyrowcount = dimrow - emptyRowCount;
                    string[,] nonemptyrowsdata = new string[nonemptyrowcount, dimcol];
                    string[] nonemptyrowheaders = new string[nonemptyrowcount];
                    for (int rr = 0, rrr = 0; rr < data.GetLength(0); rr++)
                    {
                        if (emptyRowIndexes.Contains(rr))//skip empty rows.
                            continue;
                        for (int cc = 0; cc < data.GetLength(1); cc++)
                        {
                            nonemptyrowsdata[rrr, cc] = data[rr, cc];//only copy non-empty rows
                        }
                        nonemptyrowheaders[rrr] = rowheaders[rr];//copying row headers too.
                        rrr++;
                    }
                    //Using Dynamic Class creation and then populating the grid. //12Aug2014
                    CreateDynamicClassFlexGrid(headername, colheaders, nonemptyrowheaders, nonemptyrowsdata, lst);
                }
                else
                {
                    //Using Dynamic Class creation and then populating the grid. //12Aug2014
                    CreateDynamicClassFlexGrid(headername, colheaders, rowheaders, data, lst);
                }
            }
            if (ow != null)//22May2014
                SendToOutput("", ref lst, ow);//send dataframe/matrix/array to output window or disk file
        }
        public void RunCommands(string commands, BSkyDialogProperties dlgprop = null) //30Apr2013
        {
            try
            {
                ShowMouseBusy();

                AdvancedLogging = AdvancedLoggingService.AdvLog;//01May2015
                logService.WriteToLogLevel("Adv Log Flag:" + AdvancedLogging.ToString(), LogLevelEnum.Info);

                DlgProp = dlgprop;

                #region Load registered graphic commands from GraphicCommandList.txt 18Sep2012
                // loads each time run is clicked. Performance will be effected, as we read file each time.
                string grplstfullfilepath = confService.GetConfigValueForKey("sinkregstrdgrph");//23nov2012
                //if graphic file does not exists the n create one.
                if (!IsValidFullPathFilename(grplstfullfilepath, true))//17Jan2014
                {
                    string text = "plot";
                    System.IO.File.WriteAllText(@grplstfullfilepath, text);
                }

                // load default value if no path is set or invalid path is set
                if (grplstfullfilepath.Trim().Length == 0 || !IsValidFullPathFilename(grplstfullfilepath, true))
                {
                    //grplstfullfilepath = confService.DefaultSettings["sinkregstrdgrph"];
                    MessageBox.Show(this, "Key 'sinkregstrdgrph' not found in config file. You cannot run Graphics from Command Editor.");
                    //return;
                }
                else
                {
                    LoadRegisteredGraphicsCommands(@grplstfullfilepath);
                }
                #endregion

                #region Save to Disk
                if (saveoutput.IsChecked == true)
                {
                    if (fullpathfilename.Text != null && fullpathfilename.Text.Trim().Length > 0)
                    {
                        fullfilepathname = fullpathfilename.Text;///setting filename
                        bool fileExists = File.Exists(fullfilepathname); fileExists = false;
                        if (fullfilepathname.Contains('.') && !fileExists)
                        {
                            string extension = Path.GetExtension(fullfilepathname).ToLower();// fullfilepathname.Substring(fullfilepathname.LastIndexOf('.'));
                            if (extension.Equals(".csv"))
                            { fileformat = C1.WPF.FlexGrid.FileFormat.Csv; extratags = false; }
                            else if (extension.Equals(".html"))
                            { fileformat = C1.WPF.FlexGrid.FileFormat.Html; extratags = false; }
                            else if (extension.Equals(".bsoz"))
                            { fileformat = C1.WPF.FlexGrid.FileFormat.Html; extratags = true; }
                            else
                            { fileformat = C1.WPF.FlexGrid.FileFormat.Html; extratags = true; fullfilepathname = fullfilepathname + ".bsoz"; }
                        }
                        else
                        {
                            MessageBox.Show(this, "Output File Already Exists! Provide different name in Command Editor window.");
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show(this, "Please provide new output filename and fileformat by clicking 'Browse' in Command Editor for saving the output.", "Save Output is checked...", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                        return;
                    }
                }
                #endregion

                #region Get Active output Window
                //////// Active output window ///////
                OutputWindowContainer owc = (LifetimeService.Instance.Container.Resolve<IOutputWindowContainer>()) as OutputWindowContainer;
                ow = owc.ActiveOutputWindow as OutputWindow; //get currently active window
                if (saveoutput.IsChecked == true)
                {
                    ow.ToDiskFile = true;//save lst to disk. Dump
                }
                #endregion

                #region Executing Syntax Editors Commands
                ///// Now statements from Syntax Editor will be executed ////
                CommandOutput lst = new CommandOutput(); ////one analysis////////
                lst.IsFromSyntaxEditor = true;
                if (saveoutput.IsChecked == true)//10Jan2013
                    lst.SelectedForDump = true;

                ////03Oct2014 We should remove R comments right here, before proceeding with execution.
                string nocommentscommands = RemoveCommentsFromCommands(commands);

                ExecuteCommandsAndCreateSinkFile(ow, lst, nocommentscommands);
                bool s = true;
                if (s) CreateOuput(ow); /// for last remaining few non BSkyFormat commands, if any.
                /// 

                #endregion

                #region Saving to Disk
                //////Dumping results from Syntax Editor ////08Aug2012
                if (saveoutput.IsChecked == true)
                    ow.DumpAllAnalyisOuput(fullfilepathname, fileformat, extratags);
                #endregion
            }
            catch (Exception ex)
            {
                logService.WriteToLogLevel("Exeception:" + ex.Message, LogLevelEnum.Error);
            }
            finally
            {
                HideMouseBusy();
            }
        }
        private void SendToOutput(string auparas, ref CommandOutput lst, OutputWindow ow, bool isBlockCommand = false)//, bool last=false)
        {
            if (auparas != null && auparas.Trim().Length > 0)
            {
                this.createAUPara(auparas, lst);//Create & Add AUPara to lst and empty dommid
                auparas = null;

            }
            if (lst != null && lst.Count > 0 && !isBlockCommand) //if non block command, then sent to output
            {
                sessionlst.Add(lst);//15Nov2013
                lst = new CommandOutput();//after adding to session new object is allocated for futher output creation
                //15Nov2013 ow.AddAnalyisFromSyntaxEditor(lst);//, last);/// send to output and/or dump file
            }
        }
        private void CreateAllGraphicOutput(OutputWindow ow)
        {
            CommandOutput grplst = new CommandOutput();
            long EmptyImgSize = EMPTYIMAGESIZE;//size(in bytes) of empty png file
            CloseGraphicsDevice();
            ////// now add image to lst ////
            string synedtimg = Path.Combine(System.IO.Path.GetTempPath().Replace("\\", "/"), confService.GetConfigValueForKey("sinkimage"));//23nov2012
            /////03May2013  Create zero padding string //// %03d means 000,  %04d means 0000
            int percentindex = synedtimg.IndexOf("%");
            int dindex = synedtimg.IndexOf("d", percentindex);
            string percentstr = synedtimg.Substring(percentindex, (dindex - percentindex + 1));
            string numbr = synedtimg.Substring(percentindex + 1, (dindex - percentindex - 1));
            int zerocount = Convert.ToInt16(numbr);

            string zeropadding = string.Empty;
            for (int zeros = 1; zeros <= zerocount; zeros++)
            {
                zeropadding = zeropadding + "0";
            }
            int imgcount = GraphicDeviceImageCounter;//number of images to load in output
            for (; ; )//03May2013 earlier there was no for loop for following code
            {
                imgcount++;
                string tempsynedtimg = synedtimg.Replace(percentstr, imgcount.ToString(zeropadding));
                // load default value if no path is set or invalid path is set
                if (tempsynedtimg.Trim().Length == 0 || !IsValidFullPathFilename(tempsynedtimg, true))
                {
                    break;
                }
                string source = @tempsynedtimg;
                long imgsize = new FileInfo(source).Length;//find size of the imagefile
                if (imgsize > EmptyImgSize)//if image is not an empty image
                {
                    Image myImage = new Image();

                    var bitmap = new BitmapImage();
                    try
                    {
                        var stream = File.OpenRead(source);
                        bitmap.BeginInit();
                        bitmap.CacheOption = BitmapCacheOption.OnLoad;
                        bitmap.StreamSource = stream;
                        bitmap.EndInit();
                        stream.Close();
                        stream.Dispose();
                        myImage.Source = bitmap;
                        bitmap.StreamSource.Close(); //trying to close stream 03Feb2014

                        createBSkyGraphic(myImage, grplst); //add graphic
                        DeleteFileIfPossible(@tempsynedtimg);
                    }
                    catch (Exception ex)
                    {
                        logService.WriteToLogLevel("Error reading Image file " + source + "\n" + ex.Message, LogLevelEnum.Error);
                        MessageBox.Show(this, ex.Message);
                    }

                }

            }
            if (imgcount < 1) ////03May2013 if no images were added to output lst. then return.
            {
                return;
            }
            SendToOutput(null, ref grplst, ow, false);//send all graphic to output
            OpenGraphicsDevice();//in case of errors or no errors, you must open graphic device
        }
 void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
     switch (connectionId)
     {
     case 1:
     this.outwin = ((BlueSky.OutputWindow)(target));
     
     #line 5 "..\..\OutputWindow.xaml"
     this.outwin.SizeChanged += new System.Windows.SizeChangedEventHandler(this.outwin_SizeChanged);
     
     #line default
     #line hidden
     
     #line 6 "..\..\OutputWindow.xaml"
     this.outwin.Closing += new System.ComponentModel.CancelEventHandler(this.outwin_Closing);
     
     #line default
     #line hidden
     
     #line 7 "..\..\OutputWindow.xaml"
     this.outwin.Closed += new System.EventHandler(this.outwin_Closed);
     
     #line default
     #line hidden
     
     #line 8 "..\..\OutputWindow.xaml"
     this.outwin.Loaded += new System.Windows.RoutedEventHandler(this.outwin_Loaded);
     
     #line default
     #line hidden
     return;
     case 2:
     this.parentgrid = ((System.Windows.Controls.Grid)(target));
     return;
     case 3:
     this.top = ((System.Windows.Controls.RowDefinition)(target));
     return;
     case 4:
     this.bottom = ((System.Windows.Controls.RowDefinition)(target));
     return;
     case 5:
     this.leftmost = ((System.Windows.Controls.ColumnDefinition)(target));
     return;
     case 6:
     this.rightmost = ((System.Windows.Controls.ColumnDefinition)(target));
     return;
     case 7:
     this.outputgrid = ((System.Windows.Controls.Grid)(target));
     return;
     case 8:
     this.outputborder = ((System.Windows.Controls.Border)(target));
     return;
     case 9:
     this.outputsubgrid = ((System.Windows.Controls.Grid)(target));
     return;
     case 10:
     this.OutputTitle = ((System.Windows.Controls.TextBlock)(target));
     return;
     case 11:
     this.menu1 = ((System.Windows.Controls.Menu)(target));
     return;
     case 12:
     
     #line 69 "..\..\OutputWindow.xaml"
     ((System.Windows.Controls.MenuItem)(target)).Click += new System.Windows.RoutedEventHandler(this.open_Click);
     
     #line default
     #line hidden
     return;
     case 13:
     
     #line 70 "..\..\OutputWindow.xaml"
     ((System.Windows.Controls.MenuItem)(target)).Click += new System.Windows.RoutedEventHandler(this.dump_Click);
     
     #line default
     #line hidden
     return;
     case 14:
     
     #line 71 "..\..\OutputWindow.xaml"
     ((System.Windows.Controls.MenuItem)(target)).Click += new System.Windows.RoutedEventHandler(this.MenuItemClose_Click);
     
     #line default
     #line hidden
     return;
     case 15:
     this.vertical = ((System.Windows.Controls.MenuItem)(target));
     
     #line 81 "..\..\OutputWindow.xaml"
     this.vertical.Click += new System.Windows.RoutedEventHandler(this.flip_Click);
     
     #line default
     #line hidden
     return;
     case 16:
     this.horizontal = ((System.Windows.Controls.MenuItem)(target));
     
     #line 82 "..\..\OutputWindow.xaml"
     this.horizontal.Click += new System.Windows.RoutedEventHandler(this.flip_Click);
     
     #line default
     #line hidden
     return;
     case 17:
     this.navtreemi = ((System.Windows.Controls.MenuItem)(target));
     
     #line 83 "..\..\OutputWindow.xaml"
     this.navtreemi.Click += new System.Windows.RoutedEventHandler(this.navtreemi_Click);
     
     #line default
     #line hidden
     return;
     case 18:
     this.dialogtoolbar = ((System.Windows.Controls.ToolBar)(target));
     return;
     case 19:
     this.outwingrid = ((System.Windows.Controls.Grid)(target));
     return;
     case 20:
     this.navtreecol = ((System.Windows.Controls.ColumnDefinition)(target));
     return;
     case 21:
     this.NavTree = ((System.Windows.Controls.TreeView)(target));
     return;
     case 22:
     this.scrollviewer = ((System.Windows.Controls.ScrollViewer)(target));
     return;
     case 23:
     this.panelcontainer = ((System.Windows.Controls.Grid)(target));
     return;
     case 24:
     this.mypanel = ((System.Windows.Controls.StackPanel)(target));
     return;
     case 25:
     this.gridSplitter1 = ((System.Windows.Controls.GridSplitter)(target));
     return;
     case 26:
     this.horizontalsplit = ((System.Windows.Controls.GridSplitter)(target));
     return;
     case 27:
     this.verticalsplit = ((System.Windows.Controls.GridSplitter)(target));
     return;
     case 28:
     this.syntaxgrid = ((System.Windows.Controls.Grid)(target));
     return;
     case 29:
     this.syntaxborder = ((System.Windows.Controls.Border)(target));
     return;
     case 30:
     this.syntaxsubgrid = ((System.Windows.Controls.Grid)(target));
     return;
     case 31:
     this.rowdefsyntax = ((System.Windows.Controls.RowDefinition)(target));
     return;
     case 32:
     this.titlegrid = ((System.Windows.Controls.Grid)(target));
     return;
     case 33:
     this.splitimg = ((System.Windows.Controls.Image)(target));
     
     #line 154 "..\..\OutputWindow.xaml"
     this.splitimg.MouseDown += new System.Windows.Input.MouseButtonEventHandler(this.Image_MouseDown);
     
     #line default
     #line hidden
     return;
     case 34:
     this.SyntaxTitle = ((System.Windows.Controls.TextBlock)(target));
     return;
     case 35:
     this.belowsynaxtitlegrid = ((System.Windows.Controls.Grid)(target));
     return;
     case 36:
     this.SMenu = ((System.Windows.Controls.Menu)(target));
     return;
     case 37:
     
     #line 169 "..\..\OutputWindow.xaml"
     ((System.Windows.Controls.MenuItem)(target)).Click += new System.Windows.RoutedEventHandler(this.MenuItemNew_Click);
     
     #line default
     #line hidden
     return;
     case 38:
     
     #line 170 "..\..\OutputWindow.xaml"
     ((System.Windows.Controls.MenuItem)(target)).Click += new System.Windows.RoutedEventHandler(this.MenuItemOpen_Click);
     
     #line default
     #line hidden
     return;
     case 39:
     
     #line 171 "..\..\OutputWindow.xaml"
     ((System.Windows.Controls.MenuItem)(target)).Click += new System.Windows.RoutedEventHandler(this.MenuItemSave_Click);
     
     #line default
     #line hidden
     return;
     case 40:
     
     #line 172 "..\..\OutputWindow.xaml"
     ((System.Windows.Controls.MenuItem)(target)).Click += new System.Windows.RoutedEventHandler(this.MenuItemSaveAs_Click);
     
     #line default
     #line hidden
     return;
     case 41:
     this.findreplace = ((System.Windows.Controls.MenuItem)(target));
     
     #line 181 "..\..\OutputWindow.xaml"
     this.findreplace.Click += new System.Windows.RoutedEventHandler(this.findreplace_Click);
     
     #line default
     #line hidden
     return;
     case 42:
     
     #line 185 "..\..\OutputWindow.xaml"
     ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.MenuItemNew_Click);
     
     #line default
     #line hidden
     return;
     case 43:
     
     #line 193 "..\..\OutputWindow.xaml"
     ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.MenuItemOpen_Click);
     
     #line default
     #line hidden
     return;
     case 44:
     
     #line 201 "..\..\OutputWindow.xaml"
     ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.MenuItemSave_Click);
     
     #line default
     #line hidden
     return;
     case 45:
     
     #line 212 "..\..\OutputWindow.xaml"
     ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.runButton_Click);
     
     #line default
     #line hidden
     return;
     case 46:
     
     #line 220 "..\..\OutputWindow.xaml"
     ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.Refresh_Click);
     
     #line default
     #line hidden
     return;
     case 47:
     this.inputTextbox = ((System.Windows.Controls.TextBox)(target));
     
     #line 271 "..\..\OutputWindow.xaml"
     this.inputTextbox.TextChanged += new System.Windows.Controls.TextChangedEventHandler(this.inputTextbox_TextChanged);
     
     #line default
     #line hidden
     return;
     }
     this._contentLoaded = true;
 }
        void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)
        {
            switch (connectionId)
            {
            case 1:
                this.outwin = ((BlueSky.OutputWindow)(target));

            #line 5 "..\..\OutputWindow.xaml"
                this.outwin.SizeChanged += new System.Windows.SizeChangedEventHandler(this.outwin_SizeChanged);

            #line default
            #line hidden

            #line 6 "..\..\OutputWindow.xaml"
                this.outwin.Closing += new System.ComponentModel.CancelEventHandler(this.outwin_Closing);

            #line default
            #line hidden

            #line 7 "..\..\OutputWindow.xaml"
                this.outwin.Closed += new System.EventHandler(this.outwin_Closed);

            #line default
            #line hidden

            #line 8 "..\..\OutputWindow.xaml"
                this.outwin.Loaded += new System.Windows.RoutedEventHandler(this.outwin_Loaded);

            #line default
            #line hidden
                return;

            case 2:
                this.parentgrid = ((System.Windows.Controls.Grid)(target));
                return;

            case 3:
                this.top = ((System.Windows.Controls.RowDefinition)(target));
                return;

            case 4:
                this.bottom = ((System.Windows.Controls.RowDefinition)(target));
                return;

            case 5:
                this.leftmost = ((System.Windows.Controls.ColumnDefinition)(target));
                return;

            case 6:
                this.rightmost = ((System.Windows.Controls.ColumnDefinition)(target));
                return;

            case 7:
                this.outputgrid = ((System.Windows.Controls.Grid)(target));
                return;

            case 8:
                this.outputborder = ((System.Windows.Controls.Border)(target));
                return;

            case 9:
                this.outputsubgrid = ((System.Windows.Controls.Grid)(target));
                return;

            case 10:
                this.OutputTitle = ((System.Windows.Controls.TextBlock)(target));
                return;

            case 11:
                this.menu1 = ((System.Windows.Controls.Menu)(target));
                return;

            case 12:

            #line 69 "..\..\OutputWindow.xaml"
                ((System.Windows.Controls.MenuItem)(target)).Click += new System.Windows.RoutedEventHandler(this.open_Click);

            #line default
            #line hidden
                return;

            case 13:

            #line 70 "..\..\OutputWindow.xaml"
                ((System.Windows.Controls.MenuItem)(target)).Click += new System.Windows.RoutedEventHandler(this.dump_Click);

            #line default
            #line hidden
                return;

            case 14:

            #line 71 "..\..\OutputWindow.xaml"
                ((System.Windows.Controls.MenuItem)(target)).Click += new System.Windows.RoutedEventHandler(this.MenuItemClose_Click);

            #line default
            #line hidden
                return;

            case 15:
                this.vertical = ((System.Windows.Controls.MenuItem)(target));

            #line 81 "..\..\OutputWindow.xaml"
                this.vertical.Click += new System.Windows.RoutedEventHandler(this.flip_Click);

            #line default
            #line hidden
                return;

            case 16:
                this.horizontal = ((System.Windows.Controls.MenuItem)(target));

            #line 82 "..\..\OutputWindow.xaml"
                this.horizontal.Click += new System.Windows.RoutedEventHandler(this.flip_Click);

            #line default
            #line hidden
                return;

            case 17:
                this.navtreemi = ((System.Windows.Controls.MenuItem)(target));

            #line 83 "..\..\OutputWindow.xaml"
                this.navtreemi.Click += new System.Windows.RoutedEventHandler(this.navtreemi_Click);

            #line default
            #line hidden
                return;

            case 18:
                this.dialogtoolbar = ((System.Windows.Controls.ToolBar)(target));
                return;

            case 19:
                this.outwingrid = ((System.Windows.Controls.Grid)(target));
                return;

            case 20:
                this.navtreecol = ((System.Windows.Controls.ColumnDefinition)(target));
                return;

            case 21:
                this.NavTree = ((System.Windows.Controls.TreeView)(target));
                return;

            case 22:
                this.scrollviewer = ((System.Windows.Controls.ScrollViewer)(target));
                return;

            case 23:
                this.panelcontainer = ((System.Windows.Controls.Grid)(target));
                return;

            case 24:
                this.mypanel = ((System.Windows.Controls.StackPanel)(target));
                return;

            case 25:
                this.gridSplitter1 = ((System.Windows.Controls.GridSplitter)(target));
                return;

            case 26:
                this.horizontalsplit = ((System.Windows.Controls.GridSplitter)(target));
                return;

            case 27:
                this.verticalsplit = ((System.Windows.Controls.GridSplitter)(target));
                return;

            case 28:
                this.syntaxgrid = ((System.Windows.Controls.Grid)(target));
                return;

            case 29:
                this.syntaxborder = ((System.Windows.Controls.Border)(target));
                return;

            case 30:
                this.syntaxsubgrid = ((System.Windows.Controls.Grid)(target));
                return;

            case 31:
                this.rowdefsyntax = ((System.Windows.Controls.RowDefinition)(target));
                return;

            case 32:
                this.titlegrid = ((System.Windows.Controls.Grid)(target));
                return;

            case 33:
                this.splitimg = ((System.Windows.Controls.Image)(target));

            #line 154 "..\..\OutputWindow.xaml"
                this.splitimg.MouseDown += new System.Windows.Input.MouseButtonEventHandler(this.Image_MouseDown);

            #line default
            #line hidden
                return;

            case 34:
                this.SyntaxTitle = ((System.Windows.Controls.TextBlock)(target));
                return;

            case 35:
                this.belowsynaxtitlegrid = ((System.Windows.Controls.Grid)(target));
                return;

            case 36:
                this.SMenu = ((System.Windows.Controls.Menu)(target));
                return;

            case 37:

            #line 169 "..\..\OutputWindow.xaml"
                ((System.Windows.Controls.MenuItem)(target)).Click += new System.Windows.RoutedEventHandler(this.MenuItemNew_Click);

            #line default
            #line hidden
                return;

            case 38:

            #line 170 "..\..\OutputWindow.xaml"
                ((System.Windows.Controls.MenuItem)(target)).Click += new System.Windows.RoutedEventHandler(this.MenuItemOpen_Click);

            #line default
            #line hidden
                return;

            case 39:

            #line 171 "..\..\OutputWindow.xaml"
                ((System.Windows.Controls.MenuItem)(target)).Click += new System.Windows.RoutedEventHandler(this.MenuItemSave_Click);

            #line default
            #line hidden
                return;

            case 40:

            #line 172 "..\..\OutputWindow.xaml"
                ((System.Windows.Controls.MenuItem)(target)).Click += new System.Windows.RoutedEventHandler(this.MenuItemSaveAs_Click);

            #line default
            #line hidden
                return;

            case 41:
                this.findreplace = ((System.Windows.Controls.MenuItem)(target));

            #line 181 "..\..\OutputWindow.xaml"
                this.findreplace.Click += new System.Windows.RoutedEventHandler(this.findreplace_Click);

            #line default
            #line hidden
                return;

            case 42:

            #line 185 "..\..\OutputWindow.xaml"
                ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.MenuItemNew_Click);

            #line default
            #line hidden
                return;

            case 43:

            #line 193 "..\..\OutputWindow.xaml"
                ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.MenuItemOpen_Click);

            #line default
            #line hidden
                return;

            case 44:

            #line 201 "..\..\OutputWindow.xaml"
                ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.MenuItemSave_Click);

            #line default
            #line hidden
                return;

            case 45:

            #line 212 "..\..\OutputWindow.xaml"
                ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.runButton_Click);

            #line default
            #line hidden
                return;

            case 46:

            #line 220 "..\..\OutputWindow.xaml"
                ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.Refresh_Click);

            #line default
            #line hidden
                return;

            case 47:
                this.inputTextbox = ((System.Windows.Controls.TextBox)(target));

            #line 271 "..\..\OutputWindow.xaml"
                this.inputTextbox.TextChanged += new System.Windows.Controls.TextChangedEventHandler(this.inputTextbox_TextChanged);

            #line default
            #line hidden
                return;
            }
            this._contentLoaded = true;
        }