public UAReturn Execute(CommandRequest cmd)
 {
     UAReturn r;            
     ServerCommand srvCMD = new ServerCommand(_userSession.DefaultDispatcher, "", cmd.CommandSyntax);
     srvCMD.Execute();
     return srvCMD.Result;
 }
 public void ExecuteSynEdtrNonAnalysis(object commparam)
 {
     OnPreExecute(commparam);
     parameter = commparam;
     cmd = new CommandRequest();
     cmd.CommandSyntax = ((UAMenuCommand)commparam).bskycommand;
 }
        ////round bracket block parser////
        private string RoundBracketParser(string comm, int start, ref int end)
        {
            string str = string.Empty;//comm.Replace("))", ") )").Replace(";(", "(").Replace("(;", "(");
            int roundopen = 0, roundclose = 0;
            //if(start < comm.Length)
            for (int i = comm.IndexOf('(', start); i < comm.Length; i++)
            {
                if (i < 0)
                    continue;
                if (comm.ElementAt(i).Equals('(')) roundopen++;
                else if (comm.ElementAt(i).Equals(')')) roundclose++;

                if (roundopen == roundclose)//find ';' afer closing round bracket
                {
                    int idx = comm.IndexOf(";", i);
                    if (idx > i)
                    {
                        end = idx - start;
                        str = comm.Substring(start, end).Replace("))", ") )").Replace(";(", "(").Replace("(;", "(");
                    }
                    else
                    {
                        end = comm.Length - start;
                        str = comm.Substring(start, end).Replace("))", ") )").Replace(";(", "(").Replace("(;", "(");
                    }
                    break;
                }
            }
            if (roundopen != roundclose)
            {
                CommandRequest cmdprn = new CommandRequest();
                cmdprn.CommandSyntax = "write(\"Error in block declaration. Mismatch ( or )\",fp)";
                analytics.ExecuteR(cmdprn, false, false); /// for printing command in file
                return "ERROR";
            }
            str = str.Replace(";", " ");
            str = RemoveComments(str);
            return str;
        }
        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();
        }
 //Closes current graphics device
 private void CloseGraphicsDevice()
 {
         CommandRequest grpcmd = new CommandRequest();
         //09Jun2015 here if(dev.cur()[[1]] == 2) dev.off() means that if device 2 is active then close it. 
         //that is, only if device number 2 (which is PNG in our case) is set then only try closing the current graphic device.
         // graphic device 1 is always default graphic device which cannot be closed. You get error if you do so.
         grpcmd.CommandSyntax = "if(dev.cur()[[1]] == 2) dev.off()";//09Jun2015 "dev.off()"; // "graphic.off()"; //
         analytics.ExecuteR(grpcmd, false, false);
 }
        //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;

        }
        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
        }
        //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 ExecuteSplit(string command = null, FrameworkElement fe = null)
        {
            CommandRequest cr = new CommandRequest();
            cr.CommandSyntax = command;
            string stmt = command; //cmd.CommandSyntax;
            if (stmt.Contains("BSkySetDataFrameSplit("))///executes when SPLIT is fired from menu
            {
                bool setsplit = false;
                int startind = 0; int endind = 0;
                if (stmt.Contains("col.names"))
                {
                    startind = stmt.IndexOf("c(", stmt.IndexOf("col.names"));// index of c(
                }
                else
                {
                    startind = stmt.IndexOf("c(");// index of c(
                }
                if (startind > 0)
                    endind = stmt.IndexOf(")", startind);
                if (startind > 0 && endind > startind)
                {
                    int len = endind - startind + 1; // finding the length of  c(......)
                    string str = stmt.Substring(startind, len); // this will contain c('tg0','tg1') or just c()
                    string ch = null;
                    if (str.Contains("'")) ch = "'";
                    if (str.Contains('"')) ch = "\"";
                    if (ch != null && ch.Length > 0)
                    {
                        int i = str.IndexOf(ch);
                        int j = -1;
                        if (i >= 0) j = str.IndexOf(ch, i + 1);
                        if (j < 0) j = i + 1;
                        string sub = str.Substring(i + 1, (j - i - 1)).Trim();
                        if (i < 0)
                            i = str.IndexOf("'");
                        if (i >= 0)
                        {
                            if (sub.Length > 0)
                                setsplit = true;
                        }
                    }
                }
                //Executing the command in R///
                analytics.ExecuteR(cr,false,false);

                ////Creating a command output////11Jul2014

                CommandOutput splitCo = new CommandOutput();
                splitCo.NameOfAnalysis = "Split:#" + setsplit;
                splitCo.IsFromSyntaxEditor = false;

                AUParagraph aup = new AUParagraph();
                aup.FontSize = BSkyStyler.BSkyConstants.TEXT_FONTSIZE;//App.HEADER_FONTSIZE;
                aup.Text = stmt;
                aup.ControlType = "Header";// treenodename.Length < treenodecharlen ? treenodename : treenodename.Substring(0, treenodecharlen);
                splitCo.Add(aup);

                //////////  Setting/Unsetting Macro  for SPLIT //////////
                if (setsplit)
                {
                    OutputHelper.AddGlobalObject(string.Format("GLOBAL.{0}.SPLIT", UIController.GetActiveDocument().Name), fe);
                    //window.Template = null; //11Mar2013 release the XAML object. ie obj is no more child of window.
                    AddToSyntaxSession(splitCo);//11Jul2014 SendToOutputWindow(dialogTitle, stmt);
                    Refresh_Statusbar();// RefreshGrids();
                    return;// no need to do any thing further
                }
                else // unset split
                {
                    OutputHelper.DeleteGlobalObject(string.Format("GLOBAL.{0}.SPLIT", UIController.GetActiveDocument().Name));
                    //if (window != null && window.Template != null)
                    //    window.Template = null; //11Mar2013 release the XAML object. ie obj is no more child of window.
                    AddToSyntaxSession(splitCo);//11Jul2014 SendToOutputWindow(dialogTitle, stmt);
                    Refresh_Statusbar();// RefreshGrids();
                    return;// no need to do any thing further
                }
            }

        }
        public void ExecuteSynEdtrNonAnalysis(object commparam)
        {
            OnPreExecute(commparam);
            parameter = commparam;
            ////UIController = LifetimeService.Instance.Container.Resolve<IUIController>();
            ////ds = UIController.GetActiveDocument();
            ////if (ds == null)
            ////{
            ////    canExecute = false;
            ////    return;
            ////}
            ////Variables = new ObservableCollection<DataSourceVariable>(ds.Variables);
            cmd = new CommandRequest();
            cmd.CommandSyntax = ((UAMenuCommand)commparam).bskycommand;

            //ExecuteBSkyCommand(false); //False because command already got executed in Syntax Editor code. No need to execute again
            //if ((cmd.CommandSyntax.Contains("BSkySortDataframe(")))
            //{
            //    DatasetRefreshAndPrintTitle("Sort");
            //}
        }
        ////// For Analysis Command Execution from Syntax Editor ///// 
        public void ExecuteSyntaxEditor3(object param, bool selectedForDump)
        {
            parameter = param;
            OnPreExecute(parameter);
            if (!canExecute) return;
            object obj = null;
            string dialogcommandstr = null;
            try
            {
                //here TemplateFileName xaml will have same name as the analysis command function name
                // say- function called frm SynEdtr was 'bsky.my.func()' then in bin\Config\ 
                // dialog xaml, 'bsky.my.func.xaml' and
                // output template file 'bsky.my.func.xml' must exist
                // ie.. func name = xaml name = xml name
                XmlReader xmlr = XmlReader.Create(TemplateFileName);
                xmlr.ReadToFollowing("BSkyCanvas");
                xmlr.MoveToAttribute("CommandString");
                dialogcommandstr = xmlr.Value.Replace(" ", string.Empty).Replace('\"', '\'');
                xmlr.Close();
                obj = System.Windows.Markup.XamlReader.Load(XmlReader.Create(TemplateFileName));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not create template from " + TemplateFileName);
                logService.WriteToLogLevel("SynEdtr:Could not create template from " + TemplateFileName, LogLevelEnum.Error, ex);
                return;
            }
            element = obj as FrameworkElement;
            window = new BaseOptionWindow();
            window.Template = element;
            element.DataContext = this; // loading vars in left listbox(source)
            ///window.ShowDialog();
            commandwindow = element;
            ////////////test///////
            //// take two strings and then try to make merged dictionary. remove extra spaces. replace " with '
            //string bksytemplate="bsky.CrossTable(x=c({Rows}),y=c({columns}),layers=c({layers}),datasetname='{%DATASET%}',chisq={chisq})";
            //string bskycommand="bsky.CrossTable(x=c('store','contact'),y='regular',layers=c('gender'),datasetname='Dataset1',chisq=FALSE)";
            //string dialogcommandstr = "bsky.one.sm.t.test(vars=c({SelectedVars}),mu={testValue},conf.level=0.89,datasetname='{%DATASET%}',missing=0)";
            string bskycommand = ((UAMenuCommand)parameter).bskycommand.Replace(" ", string.Empty);//"bsky.one.sm.t.test(vars=c('tg0','tg2','tg3'),mu=30,conf.level=0.89,datasetname='Dataset1',missing=0)";

            Dictionary<string, string> dialogkeyvalpair = new Dictionary<string, string>();//like: key=mu, val= {testValue}
            Dictionary<string, string> bskycommandkeyvalpair = new Dictionary<string, string>();//like: key=mu, val= 30
            Dictionary<string, string> merged = new Dictionary<string, string>();//like: key=testValue, val = 30

            OutputHelper.getArgumentSetDictionary(dialogcommandstr, dialogkeyvalpair);
            OutputHelper.getArgumentSetDictionary(bskycommand, bskycommandkeyvalpair);
            OutputHelper.MergeTemplateCommandDictionary(dialogkeyvalpair, bskycommandkeyvalpair, merged);

            foreach (KeyValuePair<string, string> pair in merged)
            {
                if (!pair.Key.Contains("%"))
                {
                    OutputHelper.SetValueFromSynEdt(element, pair.Key, pair.Value);
                }
            }
            //foreach (Match m in mc)
            //{
            //    //Console.WriteLine(s.Index + " : " + s.ToString());// {SelectedVars} {testValue} {%DATASET%}
            //    if (!m.ToString().Contains("%"))
            //    {
            //        args = OutputHelper.getArgument(bskycommand, m.Index);
            //        uiElementName = m.ToString().Replace('{', ' ').Replace('}', ' ').Trim();
            //        OutputHelper.SetValueFromSynEdt(element, uiElementName, args);
            //    }
            //}
            //OutputHelper.SetValueFromSynEdt(element, "SelectedVars");
            //OutputHelper.SetValueFromSynEdt(element, "testValue");

            //For Chisq check box only
            //FrameworkElement chkElement = element.FindName("chisq") as FrameworkElement;
            if (true)//window.DialogResult.HasValue && window.DialogResult.Value)
            {
                //analytics can be sent from parent function(in SyntaxEditorWindow)
                //IAnalyticsService analytics = LifetimeService.Instance.Container.Resolve<IAnalyticsService>();
                //IConfigService confService = LifetimeService.Instance.Container.Resolve<IConfigService>();//23nov2012
                cmd = new CommandRequest();

                OutputHelper.Reset();
                OutputHelper.UpdateMacro("%DATASET%", UIController.GetActiveDocument().Name);

                ///////////for chisq //// 29Mar2012 ///
                //if ((chkElement != null) && (bool)((chkElement as CheckBox).IsChecked))
                //    OutputHelper.UpdateMacro("%CHISQ%", "chisq");
                /////////////for chisq //// 29Mar2012 ///

                BSkyCanvas canvas = element as BSkyCanvas;
                if (canvas != null && !string.IsNullOrEmpty(canvas.CommandString))
                {
                    UAMenuCommand command = (UAMenuCommand)parameter;
                    cmd.CommandSyntax = command.commandformat;//OutputHelper.GetCommand(canvas.CommandString, element);// can be used for "Paste" for syntax editor
                    UAReturn retval = null; //retval = new UAReturn(); retval.Data = LoadAnalysisBinary();
                    #region Execute BSky command
                    try
                    {
                        retval = analytics.Execute(cmd); // RService called and DOM returned for Analysis commands
                        cmd.CommandSyntax = command.commandtype;////for header area ie NOTES
                        //SaveAnalysisBinary(retval.Data);
                        ///Added by Anil///07Mar2012
                        bool myrun = false;
                        if (cmd.CommandSyntax.Contains("BSkySetDataFrameSplit("))///executes when SPLIT is fired from menu
                        {
                            bool setsplit = false;
                            int startind = 0;
                            if (cmd.CommandSyntax.Contains("col.names"))
                            {
                                startind = cmd.CommandSyntax.IndexOf("c(", cmd.CommandSyntax.IndexOf("col.names"));// index of c(
                            }
                            else
                            {
                                startind = cmd.CommandSyntax.IndexOf("c(");// index of c(
                            }

                            int endind = cmd.CommandSyntax.IndexOf(")", startind);
                            int len = endind - startind + 1; // finding the length of  c(......)
                            string str = cmd.CommandSyntax.Substring(startind, len); // this will contain c('tg0','tg1') or just c()
                            string ch = null;
                            if (str.Contains("'")) ch = "'";
                            if (str.Contains('"')) ch = "\"";
                            if (ch != null && ch.Length > 0)
                            {
                                int i = str.IndexOf(ch);
                                int j = -1;
                                if (i >= 0) j = str.IndexOf(ch, i + 1);
                                if (j < 0) j = i + 1;
                                string sub = str.Substring(i + 1, (j - i - 1)).Trim();
                                if (i < 0)
                                    i = str.IndexOf("'");
                                if (i >= 0)
                                {
                                    if (sub.Length > 0)
                                        setsplit = true;
                                }
                            }

                            //////////  Setting/Unsetting Macro  for SPLIT //////////
                            if (setsplit)
                            {
                                OutputHelper.AddGlobalObject(string.Format("GLOBAL.{0}.SPLIT", UIController.GetActiveDocument().Name), element);
                                return;// no need to do any thing further
                            }
                            else // unset split
                            {
                                OutputHelper.DeleteGlobalObject(string.Format("GLOBAL.{0}.SPLIT", UIController.GetActiveDocument().Name));
                                return;// no need to do any thing further
                            }
                        }
                        ////////////////////////////
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Couldn't Execute the command");
                        logService.WriteToLogLevel("Couldn't Execute the command", LogLevelEnum.Error, ex);
                        return;
                    }
                    #endregion
                    //UAReturn retval = new UAReturn();
                    retval.Success = true;
                    AnalyticsData data = new AnalyticsData();
                    data.SelectedForDump = selectedForDump;//10Jan2013
                    data.PreparedCommand = cmd.CommandSyntax;//storing command
                    data.Result = retval;
                    data.AnalysisType = cmd.CommandSyntax; //"T-Test"; For Parent Node name 02Aug2012
                    data.InputElement = element;
                    data.DataSource = ds;
                    data.OutputTemplate = ((UAMenuCommand)parameter).commandoutputformat;
                    UIController.AnalysisComplete(data);
                }
            }

            //OnPostExecute(parameter);
        }
 private void GenerateOutputTablesForNonXAML(object param)
 {
     if (param != null)
     {
         UAMenuCommand command = (UAMenuCommand)param;
         cmd = new CommandRequest();
         cmd.CommandSyntax = command.commandformat;
     }
     retval = analytics.Execute(cmd); //ExecuteBSkyCommand(true);
     ExecuteAnalysisCommands(); //fixed on 19Apr2014 for list of list formatting using BSkyFormat and BSkyFormat2
 }
        ////// For Analysis Command Execution from Syntax Editor /////28Mar2013 Using this one and not the other one below this method
        public void ExecuteSyntaxEditor(object param, bool SelectedForDump)
        {
            parameter = param;//set Global var.
            selectedForDump = SelectedForDump;//set Global var
            OnPreExecute(param);
            if (!canExecute) return;
            object obj = null;
            string dialogcommandstr = null;
            string HistMenuText = string.Empty;//29Mar2013
            try
            {
                if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: dialog xaml:" + TemplateFileName, LogLevelEnum.Info);
                //here TemplateFileName xaml will have same name as the analysis command function name
                // say- function called frm SynEdtr was 'bsky.my.func()' then in bin\Config\ 
                // dialog xaml, 'bsky.my.func.xaml' and
                // output template file 'bsky.my.func.xml' must exist
                // ie.. func name = xaml name = xml name
                XmlReader xmlr = XmlReader.Create(TemplateFileName);
                xmlr.ReadToFollowing("BSkyCanvas");

                //Following commented code can be used to Add command to "History" menu when executed from Syntax Editor
                //But "Title" from XAML may not same as "text" attr from menu.xml
                //So the same command executed from Syntax Editor and Main App's menu will show duplicate
                ////xmlr.MoveToAttribute("Title");//29Mar2013 For "History" Text
                ////HistMenuText = xmlr.Value;//29Mar2013 For "History" Text
                ////UAMenuCommand uam = (UAMenuCommand)param;
                ////uam.text = HistMenuText;
                ////parameter = uam;//set Global var

                xmlr.MoveToAttribute("CommandString");
                dialogcommandstr = xmlr.Value.Replace(" ", string.Empty).Replace('\"', '\'');
                if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: dialog command string:" + dialogcommandstr, LogLevelEnum.Info);
                xmlr.Close();
                obj = System.Windows.Markup.XamlReader.Load(XmlReader.Create(TemplateFileName));
            }
            catch (Exception ex)
            {
                //18Aug2014 Supressing this message box as we dont need it. But we still pass message in log.
                //MessageBox.Show("XAML missing or has improper format! Could not create template from " + TemplateFileName);
                logService.WriteToLogLevel("SynEdtr:Could not create template from " + TemplateFileName, LogLevelEnum.Error, ex);
                GenerateOutputTablesForNonXAML(param);
                return;
            }
            //obj = GetSessionDialog(); // same dialog cant be used as its child of the another parent in AUAnalysisCommandBase
            element = obj as FrameworkElement;
            window = new BaseOptionWindow();
            window.Template = element;
            element.DataContext = this; // loading vars in left listbox(source)
            ///window.ShowDialog();
            commandwindow = element;
            
            {
                if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Dialog controls value mapping.", LogLevelEnum.Info);
                ////////////test///////
                //// take two strings and then try to make merged dictionary. remove extra spaces. replace " with '
                //string bksytemplate="bsky.CrossTable(x=c({Rows}),y=c({columns}),layers=c({layers}),datasetname='{%DATASET%}',chisq={chisq})";
                //string bskycommand="bsky.CrossTable(x=c('store','contact'),y='regular',layers=c('gender'),datasetname='Dataset1',chisq=FALSE)";
                //string dialogcommandstr = "bsky.one.sm.t.test(vars=c({SelectedVars}),mu={testValue},conf.level=0.89,datasetname='{%DATASET%}',missing=0)";
                string bskycommand = ((UAMenuCommand)parameter).bskycommand.Replace(" ", string.Empty);//"bsky.one.sm.t.test(vars=c('tg0','tg2','tg3'),mu=30,conf.level=0.89,datasetname='Dataset1',missing=0)";
                if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Command:" + bskycommand, LogLevelEnum.Info);

                Dictionary<string, string> dialogkeyvalpair = new Dictionary<string, string>();//like: key=mu, val= {testValue}
                Dictionary<string, string> bskycommandkeyvalpair = new Dictionary<string, string>();//like: key=mu, val= 30
                Dictionary<string, string> merged = new Dictionary<string, string>();//like: key=testValue, val = 30

                OutputHelper.getArgumentSetDictionary(dialogcommandstr, dialogkeyvalpair);
                OutputHelper.getArgumentSetDictionary(bskycommand, bskycommandkeyvalpair);
                OutputHelper.MergeTemplateCommandDictionary(dialogkeyvalpair, bskycommandkeyvalpair, merged);

                foreach (KeyValuePair<string, string> pair in merged)
                {
                    if (AdvancedLogging)
                    {
                        string mapping = "Element:" + element.Name + ". Key:" + pair.Key + ". Value:" + pair.Value;
                        logService.WriteToLogLevel("ExtraLogs:\n" + mapping, LogLevelEnum.Info);
                    }
                    if (!pair.Key.Contains("%"))// This should only skip macros(words enclosed within %) and not other formats.
                    {
                        OutputHelper.SetValueFromSynEdt(element, pair.Key, pair.Value); //Filling dialog with values
                    }
                }
            }
            //foreach (Match m in mc)
            //{
            //    //Console.WriteLine(s.Index + " : " + s.ToString());// {SelectedVars} {testValue} {%DATASET%}
            //    if (!m.ToString().Contains("%"))
            //    {
            //        args = OutputHelper.getArgument(bskycommand, m.Index);
            //        uiElementName = m.ToString().Replace('{', ' ').Replace('}', ' ').Trim();
            //        OutputHelper.SetValueFromSynEdt(element, uiElementName, args);
            //    }
            //}
            //OutputHelper.SetValueFromSynEdt(element, "SelectedVars");
            //OutputHelper.SetValueFromSynEdt(element, "testValue");

            //For Chisq check box only
            //FrameworkElement chkElement = element.FindName("chisq") as FrameworkElement;
            if (true)//window.DialogResult.HasValue && window.DialogResult.Value)
            {
                //analytics can be sent from parent function(in SyntaxEditorWindow)
                cmd = new CommandRequest();

                OutputHelper.Reset();
                OutputHelper.UpdateMacro("%DATASET%", UIController.GetActiveDocument().Name);

                ///////////for chisq //// 29Mar2012 ///
                //if ((chkElement != null) && (bool)((chkElement as CheckBox).IsChecked))
                //    OutputHelper.UpdateMacro("%CHISQ%", "chisq");
                /////////////for chisq //// 29Mar2012 ///

                BSkyCanvas canvas = element as BSkyCanvas;
                if (canvas != null && !string.IsNullOrEmpty(canvas.CommandString))
                {
                    UAMenuCommand command = (UAMenuCommand)parameter;
                    cmd.CommandSyntax = command.commandformat;//OutputHelper.GetCommand(canvas.CommandString, element);// can be used for "Paste" for syntax editor
                    if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Getting DOM", LogLevelEnum.Info);
                    retval = analytics.Execute(cmd); //ExecuteBSkyCommand(true);
                    ExecuteXMLDefinedDialog(cmd.CommandSyntax);//no need to pass parameters here. Just to match func signature
                }
                //16Apr2013 till this point command has already been executed. So now we store this command for "History"
                // moved here from common function ExecuteBSkyCommand b'coz for command batch dialog SaveHistory should execute once.
                //SaveInHistory(); // not sure if needed to be commented
            }

            //OnPostExecute(parameter);

            //Cleanup. Remove Canvas children and make it null. then make Window.templace null
            BSkyCanvas canv = element as BSkyCanvas;
            int count = canv.Children.Count;
            canv.Children.RemoveRange(0, count);
            window.Template = null;
        }
        public void Execute(object param)
        {
            IAdvancedLoggingService advlog = LifetimeService.Instance.Container.Resolve<IAdvancedLoggingService>(); ;//01May2015
            advlog.RefreshAdvancedLogging();
            AdvancedLogging = AdvancedLoggingService.AdvLog;//01May2015
            bool reloaddiskfiledata = false;
            //26Jun2014 isXmlTemplateDefined = false;
            parameter = param;////set Global var
            selectedForDump = false; //this parameter is only for Analytics(or non-Analytics)commands exected from Syntax Editor
            OnPreExecute(parameter);
            if (!canExecute)
            {
                canExecute = true;//06Nov2012.Fixed. if no dataset loaded.run one smpl. then load dataset. cant run one sampl now.
                return;
            }

            //for getting dialog xaml filename in logs.
            logService.WriteToLogLevel("XAML name : " + TemplateFileName, LogLevelEnum.Info);

            object obj = null;
            string dialogkey = string.Empty;//13Feb2013
            bool isOldDialog = false;//13Feb2013
            try
            {
                //Added by Aaron 06/15/2014
                BSkyCanvas.applyBehaviors = false;

                /// TemplateFilename /// for XAML filename
                dialogkey = TemplateFileName + UIController.GetActiveDocument().FileName + UIController.GetActiveDocument().Name;
                //if obj is already in dictionary for particular dataset which is currently open
                //then load obj from dictionary
                if (sdc.SessionDialogList.ContainsKey(dialogkey))
                {
                    obj = sdc.SessionDialogList[dialogkey];//gets the exisiting dialog
                    isOldDialog = true;
                }
                else//else use XAML dialog file and create obj and then store obj in dictionary with dataset name.
                {

                    //Added by Aaron 06/15/2014
                    string CurrentDatasetName = UIController.GetActiveDocument().Name;
                    string changedxaml = string.Empty;

                    changedxaml = FixRadioGroupNameUsingFiling(TemplateFileName, CurrentDatasetName + Path.GetFileName(TemplateFileName));
                    /////////////////////////////

                    XmlReader xmlReader = XmlReader.Create(new StringReader(changedxaml));
                    obj = System.Windows.Markup.XamlReader.Load(xmlReader);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not create template from " + TemplateFileName);
                logService.WriteToLogLevel("Could not create template from " + TemplateFileName, LogLevelEnum.Error, ex);
                //GenerateOutputTablesForNonXAML(param);
                return;
            }

            BSkyCanvas cs = obj as BSkyCanvas;
            BSkyCanvas.applyBehaviors = true;
            BSkyCanvas.first = cs;
            var converter = new System.Windows.Media.BrushConverter();

            cs.Background = (Brush)converter.ConvertFrom("#FFEEefFf");

            cmd = new CommandRequest();//set Global var
            element = obj as FrameworkElement;////set Global var
            window = new BaseOptionWindow();////set Global var
            window.Template = element;
            element.DataContext = this; // loading vars in left listbox(source)


            // If a form is displayed as modal, the code following the ShowDialog method is not executed  
            // until the dialog box is closed. However, when a form is shown as modeless, the code following 
            // the Show method is executed immediately after the form is displayed.
            if (!cs.Command)//26Jun2014 !isCommandOnlyDialog)
                window.ShowDialog();
            //Added by Aaron 07/20/2014
            //If GetOverwrittenVars returns true tells me that a user has selected a dataset or variable to be created by the analytical command but that 
            //variable already exists. Hence the command should not be executed.
            if (window.GetOverwrittenVars()) return;
            /////13Feb2013 Store obj in dictionary if not already there ////
            if (!isOldDialog)
            {
                sdc.SessionDialogList.Add(dialogkey, obj);
            }

            commandwindow = element;

            OutputHelper.Reset();
            OutputHelper.UpdateMacro("%DATASET%", UIController.GetActiveDocument().Name);
            //OutputHelper.UpdateMacro("%DATASET%", "bskyCurrentDatasetSplitSliceObj"); //09Jun2014 in case of split slice name is Dataset name

            if ((window.DialogResult.HasValue && window.DialogResult.Value) || cs.Command)
            {
                BSkyCanvas canvas = element as BSkyCanvas;

                if (canvas != null && !string.IsNullOrEmpty(canvas.CommandString))
                {
                    //following is important as its substituting params with values.
                    cmd.CommandSyntax = OutputHelper.GetCommand(canvas.CommandString, element);// can be used for "Paste" for syntax editor
                    if (cmd.CommandSyntax.Contains("BSkyReloadDataset("))// if its relaod dataset commmand then prepare some parameter before executing the command
                    {
                        reloaddiskfiledata = true;
                        SubstituteFilenameAndType();//get filename and file type of disk file that is supposed to get reloaded.

                    }
                    CollectDialogProperties(canvas); // get all dialog properties

                    ShowMouseBusy();

                    #region Loading Dialog's required R Packages //30Apr2015
                    //following single line just for testing. Comment it and uncomment next line for production.
                    //string pkgs = "zoo;sem;aa;;nlme;bb;class;"; 
                    string pkgs = dlgprop.RequiredRPacakges;
                    if (!string.IsNullOrEmpty(pkgs))
                    {
                        bool packageMissing = false;
                        string statmsg = LoadDialogRPacakges(pkgs, out packageMissing);//pass semi colon separated list of R packages.
                        if (statmsg.Trim().Length > 0 && (statmsg.ToLower().Contains("error") || packageMissing))
                        {
                            // statmsg has message like : XYZ package not found. Please install it from CRAN
                            string lastmsg = "\nPlease install the above mentioned R package(s).\nGo To Tools -> Package -> Install package from CRAN.\nInstall missing R packages and execute the dialog again.";
                            MessageBox.Show(canvas.Title + " needs the following R package(s):\n\n" + statmsg + lastmsg, "Error: Missing R Package(s)", MessageBoxButton.OK, MessageBoxImage.Stop);
                            logService.WriteToLogLevel("Dialog's required R package loading error:\n" + statmsg, LogLevelEnum.Error);
                            if (window != null)
                                window.Template = null; //13Feb2013 release the XAML object. ie obj is no more child of window.
                            HideMouseBusy();
                            return;//Skip dialog execution further.(as all required packages failed to load. And dialog commands will not execute properly)
                        }
                    }
                    #endregion

                    #region PASTE clicked on the dialog
                    //Check if OK or Syntax was clicked
                    if (window.Tag != null && window.Tag.ToString().Equals("Syntax"))//21Jan2013
                    {
                        PasteInOutputSyntax();//06May2015 PasteSyntax();
                    }
                    #endregion

                    #region OK clicked on the dialog
                    if ((window.Tag != null && window.Tag.ToString().Equals("Ok")) || dlgprop.IsCommandOnly)//26Jun2014 isCommandOnlyDialog)//21Jan2013 Dont use else if is Syntax stay dialog workaround is in use.
                    {
                        dialogTitle = (window.Title != null) ? window.Title : string.Empty;
                        string batchcommtitle = dialogTitle;

                        dsvs = UIController.GetActiveDocument().Variables;//list of exisiting vars in active dataset

                        try
                        {
                            string dlgcommands = string.Join(";", dlgprop.Commands);
                            if (dlgcommands.Contains("BSkyIndSmTTest") || dlgcommands.Contains("BSkyOneSmTTest") || dlgcommands.Contains("BSkyCrossTable"))
                            {
                                //30Apr2015 This is block is probably needed because 3 of our Template based dialogs have internal split handler.
                                cmd.CommandSyntax = GetSliceSubstitutedCommands(dlgprop.Commands, 1);
                                PrintDialogTitle(dialogTitle);//30Apr2015

                                if(AdvancedLogging)logService.WriteToLogLevel("ExtraLogs: before executing in Syntax.", LogLevelEnum.Info);


                                ExecuteInSyntaxEditor(true, dialogTitle);

                                if(AdvancedLogging)logService.WriteToLogLevel("ExtraLogs: after executing in Syntax.", LogLevelEnum.Info);


                            }
                            else
                            {
                                if(AdvancedLogging)logService.WriteToLogLevel("ExtraLogs: before executing as BatchCommand.", LogLevelEnum.Info);


                                //this can handle template based dialogs but split handling may get tricky. To make it
                                //work here, probably, turn off split handling from within these template based dialogs.
                                //this is just ahint, we nned to try and make sure.
                                ExecuteBatch(dlgprop.Commands); //Execute single and multiple commands as batch commands(ie..execute in Syntax)

                                if(AdvancedLogging)logService.WriteToLogLevel("ExtraLogs: after executing as BatchCommand.", LogLevelEnum.Info);


                            }

                            //15Jan2015
                            //Following was the original code.But 'if/else' was introduced above just to resctrict XML templated 
                            //dialog to run differently in case of split set.
                            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: successful execution.", LogLevelEnum.Info);


                        }
                        catch (Exception e)
                        {
                            MessageBox.Show("Couldn't Execute the command");
                            logService.WriteToLogLevel("Couldn't Execute the command", LogLevelEnum.Error, e);
                            if (window != null)
                                window.Template = null; //25Mar2013 release the XAML object. ie obj is no more child of window.
                            return;
                        }
                        //save current dialog in 'History' menu
                        SaveInHistory();
                    }
                    #endregion

                    HideMouseBusy();
                }
            }

            // if its relaod dataset commmand then we need to refresh grid and status bar
            if (reloaddiskfiledata)// (cmd.CommandSyntax.Contains("BSkyReloadDataset("))
            {
                RefreshGridAndStatus();//uncomment this line if executing in Syntax. Comment it if executing using old method.
            }

            window.Template = null; //13Feb2013 release the XAML object. ie obj is no more child of window.
            OnPostExecute(parameter);
        }
        //For commands : Dialog may or may not be shown but surely XML template is not present.
        public void ExeuteSingleCommandWithtoutXML(string command = "")
        {
            if (command != null && command.Length > 0)
            {
                cmd = new CommandRequest();
                cmd.CommandSyntax = command;
            }
            if (cmd.CommandSyntax == null || cmd.CommandSyntax.Length < 1)
            {
                cmd = new CommandRequest();
                cmd.CommandSyntax = "print('No command to execute')";
            }

            if (cmd.CommandSyntax.Contains("BSkyReloadDataset("))// if its relaod dataset commmand then prepare some parameter before executing the command
            {
                DataSource tempds = UIController.GetActiveDocument();
                string filename = tempds.FileName.Replace("\\", "/").Trim();
                string filetype = tempds.FileType.Trim();
                string temp = new string(cmd.CommandSyntax.ToCharArray());

                cmd.CommandSyntax = temp.Replace("fullpathfilename", "fullpathfilename='" + filename + "'").Replace("filetype", "filetype='" + filetype + "'"); ;

                //Restting split if all data and attributes are loaded 
                int idx = temp.IndexOf("=", temp.IndexOf("loaddataonly")); // index of  '=' after 'loaddataonly'
                int idxcomma = temp.IndexOf(",", temp.IndexOf("loaddataonly")); // index of  ',' after 'loaddataonly'
                string boolvalue = temp.Substring(idx + 1, idxcomma - idx - 1).Trim();
                if (boolvalue.Equals("FALSE"))//loaddataonly = false then we need to reset SPLIT in C# also
                {
                    OutputHelper.DeleteGlobalObject(string.Format("GLOBAL.{0}.SPLIT", UIController.GetActiveDocument().Name));
                }
            }

            if (dlgprop != null)
            {
                if (!dlgprop.IsBatchCommand && dlgprop.IsCommandOnly && !dlgprop.IsXMLDefined && !cmd.CommandSyntax.Contains("BSkySetDataFrameSplit("))
                {
                    SendToOutputWindow(dialogTitle, cmd.CommandSyntax);
                    ExecuteInSyntaxEditor(true, dialogTitle);//GenerateOutputTablesForNonXAML(null);// ExecuteXMLDefinedDialog();
                }
            }
            else
            {
                retval = analytics.Execute(cmd);

                if (cmd.CommandSyntax.Contains("BSkySetDataFrameSplit(")) //split sets some MACRO in memory too. So its different from others.
                {
                    ExecuteSplit();
                }
                else
                {
                    if (cmd.CommandSyntax.Contains("BSkySortDataframe")) //11Apr2014 putting sort icon
                    {
                        //sort order 14Apr2014
                        string srtodr = string.Empty;
                        // descending=FALSE in command. There is just 1 boolean in sort so this 'if' will work
                        if (cmd.CommandSyntax.Contains("FALSE"))
                            srtodr = "asc";
                        else
                            srtodr = "desc";

                        //mulitiple col logic
                        List<string> collst = new List<string>();
                        int startidx = cmd.CommandSyntax.IndexOf("c(");
                        if (startidx == -1) //no items in target listbox. No need of this if sort dialog has OK disabled when no items in target
                        {
                            return;
                        }
                        int endidx = cmd.CommandSyntax.IndexOf(")", startidx + 1);
                        int leng = endidx - startidx - 1;
                        string selcols = cmd.CommandSyntax.Substring(startidx + 2, leng - 1).Replace("'", "");// +2 is the length of "c(", -1 for )
                        string[] cols = selcols.Split(',');
                        for (int j = 0; j < cols.Length; j++) //string s in cols)
                        {
                            collst.Add(cols[j]);
                        }
                        RefreshGrids(collst, srtodr);
                    }
                    else
                    {
                        RefreshGrids();
                    }

                    //16Apr2014
                    //must be excuted at the end after data is reloaded otherwise split is not refresh in statusbar. 
                    if (cmd.CommandSyntax.Contains("BSkyReloadDataset("))
                    {
                        Refresh_Statusbar();
                    }

                    //Finally show messages in output
                    SendToOutputWindow(dialogTitle, cmd.CommandSyntax);
                }
            }
        }
        private bool ExecuteBSkyLoadRefreshDataframe(string stmt)//13Feb2014

        {
            CommandRequest cmd = new CommandRequest();
            int start = stmt.IndexOf('(');
            int end = stmt.IndexOf(')');

            string parameters = stmt.Substring(start + 1, end - start - 1);

            //parameters can be 1 or 2 (if 2 params, then one is bool)
            // IMPORTANT :: Assumed that max parameters are 2. One is optional bool parameter.
            string[] eachparam = parameters.Split(',');
            string dataframename = string.Empty;
            string boolparam = string.Empty;
            if (eachparam.Length==2)
            {
                //either of the two is dataframe name
                if (eachparam[1].Contains("load.dataframe") || eachparam[1].Contains("TRUE") || eachparam[1].Contains("FALSE"))
                {
                    dataframename = eachparam[0];
                    boolparam = eachparam[1];
                }
                else // if bool is passed as first parameter and dataframe name as second param.
                {
                    dataframename = eachparam[1];
                    boolparam = eachparam[0];
                }

            }
            else if (eachparam.Length == 1)//only one madatory param is passed which is dataframe name
            {
                dataframename = eachparam[0];
                boolparam = "TRUE";
            }
            /////get dataframe name
            if (dataframename.Contains("="))//dframe="Dataset1"
            {
                dataframename = dataframename.Substring(dataframename.IndexOf("=") + 1);
            }
            dataframename = dataframename.Trim();

            //09Jun2015 if dataframename is not passed that means there is no need to load/refresh dataframe
            if (dataframename.Length < 1)
            {
                return true;
            }

            ///get bool parama value
            if (boolparam.Contains("="))//dframe="Dataset1"
            {
                boolparam = boolparam.Substring(boolparam.IndexOf("=") + 1);
            }
            boolparam = boolparam.Trim();            

            if (boolparam.Contains("FALSE"))//do not refresh dataframe
            {
                return true;
            }

            cmd.CommandSyntax = "exists('" + dataframename + "')";//check if that dataset exists in memory.
            object o1 = analytics.ExecuteR(cmd, true, false);
            if (o1.ToString().ToLower().Equals("true")) // if found, check if data.frame type. then load it
            {
                cmd.CommandSyntax = "is.data.frame(" + dataframename + ")";//check if its 'data.frame' type.
                object o2 = analytics.ExecuteR(cmd, true, false);
                if (o2.ToString().ToLower().Equals("true")) // if data.frame type
                {
                    FileOpenCommand foc = new FileOpenCommand();
                    return foc.OpenDataframe(dataframename);
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        private void ExecuteXMLTemplateDefinedCommands(string stmt)//10Jul2014
        {
            CommandRequest xmlgrpcmd = new CommandRequest();

            xmlgrpcmd.CommandSyntax = stmt;
            //o = analytics.ExecuteR(xmlgrpcmd, false, false);

            UAMenuCommand uamc = new UAMenuCommand();
            uamc.bskycommand = stmt;
            uamc.commandtype = stmt;
            CommandExecutionHelper auacb = new CommandExecutionHelper();
            auacb.MenuParameter = menuParameter;
            auacb.RetVal = analytics.Execute(xmlgrpcmd);
            auacb.ExecuteXMLDefinedDialog(stmt);
        }
        //For commands : Dialog may or may not be shown but surely XML template is not present.
        public void ExeuteSingleCommandWithtoutXML(string command = "")
        {
            if (command != null && command.Length > 0)
            {
                cmd = new CommandRequest();
                cmd.CommandSyntax = command;
            }
            if (cmd.CommandSyntax == null || cmd.CommandSyntax.Length < 1)
            {
                cmd = new CommandRequest();
                cmd.CommandSyntax = "print('No command to execute')";
            }

            if (cmd.CommandSyntax.Contains("BSkyReloadDataset("))// if its relaod dataset commmand then prepare some parameter before executing the command
            {
                DataSource tempds = UIController.GetActiveDocument();
                string filename = tempds.FileName.Replace("\\", "/");
                string filetype = tempds.FileType;
                string temp = new string(cmd.CommandSyntax.ToCharArray());

                cmd.CommandSyntax = temp.Replace("fullpathfilename", "fullpathfilename='" + filename + "'").Replace("filetype", "filetype='" + filetype + "'"); ;

                //Restting split if all data and attributes are loaded 
                int idx = temp.IndexOf("=", temp.IndexOf("loaddataonly")); // index of  '=' after 'loaddataonly'
                int idxcomma = temp.IndexOf(",", temp.IndexOf("loaddataonly")); // index of  ',' after 'loaddataonly'
                string boolvalue = temp.Substring(idx + 1, idxcomma - idx - 1).Trim();
                if (boolvalue.Equals("FALSE"))//loaddataonly = false then we need to reset SPLIT in C# also
                {
                    OutputHelper.DeleteGlobalObject(string.Format("GLOBAL.{0}.SPLIT", UIController.GetActiveDocument().Name));
                }
            }
            //retval = analytics.Execute(cmd);
            if (bdt != null)
                if (!bdt.IsBatchCommand && bdt.IsCommandOnly && !bdt.IsXMLDefined && !cmd.CommandSyntax.Contains("BSkySetDataFrameSplit("))
                {
                    SendToOutputWindow(dialogTitle, cmd.CommandSyntax);
                    ExecuteInSyntaxEditor(true, dialogTitle);//GenerateOutputTablesForNonXAML(null);// ExecuteXMLDefinedDialog();
                }

            if (cmd.CommandSyntax.Contains("BSkySortDataframe(") || cmd.CommandSyntax.Contains("BSkyComputeExpression(") ||
                         cmd.CommandSyntax.Contains("BSkyRecode("))
            {
                retval = analytics.Execute(cmd);
                OutputHelper.AnalyticsData.Result = retval;//putting latest DOM
                string[,] ew = OutputHelper.GetBSkyErrorsWarning(1, "normal");//08Nov2014

                if (cmd.CommandSyntax.Contains("BSkySortDataframe")) //11Apr2014 putting sort icon
                {
                    //single column logic
                    //int startidx = cmd.CommandSyntax.IndexOf("'");
                    //int endidx= cmd.CommandSyntax.IndexOf("'", startidx+1);
                    //int leng = endidx - startidx-1;
                    //string colname = cmd.CommandSyntax.Substring(startidx+1, leng);

                    //sort order 14Apr2014
                    string srtodr = string.Empty;
                    // descending=TRUE in command. There is just 1 boolean in sort so this 'if' will work
                    if (cmd.CommandSyntax.Contains("TRUE"))
                        srtodr = "desc";
                    else
                        srtodr = "asc";

                    //mulitiple col logic
                    List<string> collst = new List<string>();
                    int startidx = cmd.CommandSyntax.IndexOf("c(");
                    if (startidx == -1) //no items in target listbox. No need of this if sort dialog has OK disabled when no items in target
                    {
                        return;
                    }
                    int endidx = cmd.CommandSyntax.IndexOf(")", startidx + 1);
                    int leng = endidx - startidx - 1;
                    string selcols = cmd.CommandSyntax.Substring(startidx + 2, leng - 1).Replace("'", "");// +2 is the length of "c(", -1 for )
                    string[] cols = selcols.Split(',');
                    for (int j = 0; j < cols.Length; j++) //string s in cols)
                    {
                        collst.Add(cols[j]);
                    }
                    RefreshGrids(collst, srtodr);
                }
                else
                {
                    //testing something. If success, we dont need this. RefreshGrids();
                }

                //16Apr2014
                //must be excuted at the end after data is reloaded otherwise split is not refresh in statusbar. 
                if (cmd.CommandSyntax.Contains("BSkyReloadDataset("))
                {
                    Refresh_Statusbar();
                }

                ////Finally show messages in output
                //SendToOutputWindow(dialogTitle, cmd.CommandSyntax);
                //Show errors if any 08Nov2014
                if (ew != null && ew[0, 0] != null)
                {
                    //SendToOutputWindow("", ew[0, 2]);
                    CommandOutput ewmsg = new CommandOutput();
                    ewmsg.NameOfAnalysis = "Errors/Warnings";
                    ewmsg.IsFromSyntaxEditor = false;

                    AUParagraph ewtypeaup = new AUParagraph();
                    ewtypeaup.FontSize = BSkyStyler.BSkyConstants.TEXT_FONTSIZE;//App.TEXT_FONTSIZE;
                    ewtypeaup.Text = (ew[0, 0] != null)?ew[0, 0]:"no type info";
                    ewtypeaup.ControlType = "Type:";
                    ewmsg.Add(ewtypeaup);

                    AUParagraph usrmsgaup = new AUParagraph();
                    usrmsgaup.FontSize = BSkyStyler.BSkyConstants.TEXT_FONTSIZE;//App.TEXT_FONTSIZE;
                    usrmsgaup.Text = (ew[0, 1] != null) ? ew[0, 1] : "no user message info";
                    usrmsgaup.ControlType = "User Message:";
                    ewmsg.Add(usrmsgaup);

                    AUParagraph rmsgaup = new AUParagraph();
                    rmsgaup.FontSize = BSkyStyler.BSkyConstants.TEXT_FONTSIZE;//App.TEXT_FONTSIZE;
                    rmsgaup.Text = (ew[0, 2] != null) ? ew[0, 2] : "no R message info";
                    rmsgaup.ControlType = "R Message:";
                    ewmsg.Add(rmsgaup);

                    AddToSyntaxSession(ewmsg);
                }
            }
        }
        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
        }
        //30Sep2014 Refresh R side global vars etc..
        public void SetRDefaults()
        {
            IAnalyticsService analytics = LifetimeService.Instance.Container.Resolve<IAnalyticsService>();
            IConfigService confService = LifetimeService.Instance.Container.Resolve<IConfigService>();//23nov2012
            CommandRequest rcmd = new CommandRequest();

            //16Dec2013 read from config (this has priority, because it was set before closing BSky App
            string configdecidigits = confService.GetConfigValueForKey("noofdecimals");

            //Call R function to get Decimal digit. This will be used in case config does not have value set previously.
            rcmd.CommandSyntax = "BSkyGetDecimalDigitSetting()"; //get Decimal Digit
            object retres = analytics.ExecuteR(rcmd, true, false);
            string rdecidigits = retres != null ? retres.ToString() : string.Empty;

            int noofdecimaldigits;
            bool parsed;
            //Now use configdecidigits. If its not present then use rdecidigits instead.
            if (configdecidigits != null && configdecidigits.Trim().Length > 0)
            {
                parsed = Int32.TryParse(configdecidigits, out noofdecimaldigits);
            }
            else
            {
                parsed = Int32.TryParse(rdecidigits, out noofdecimaldigits);
            }

            //Call R function to set Decimal digit either from "C# config" or from R defaults.
            rcmd.CommandSyntax = "BSkySetDecimalDigitSetting(decimalDigitSetting = " + noofdecimaldigits + ")"; //Set Decimal Digit
            retres = analytics.ExecuteR(rcmd, false, false);
        }
        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 ExecuteSplit(string stmt)
        {
            //object o = null;
            CommandRequest cmd = new CommandRequest();

            CommandExecutionHelper ceh = new CommandExecutionHelper();
            UAMenuCommand uamc = new UAMenuCommand();
            uamc.bskycommand = stmt;
            uamc.commandtype = stmt;
            cmd.CommandSyntax = stmt;
            ceh.ExecuteSplit(stmt, FElement);
            ceh = null;
        }
        int  GraphicDeviceImageCounter = 0;//to keep track of the next image file name.
        //Openes new PNG graphics device. This function can be customised to open any graphics device.
        private void OpenGraphicsDevice(int imagewidth=0, int imageheight=0)//05May2013
        {
            DeleteOldGraphicFiles();//06May2013
            /////// These lines moved here from isGrap block to entertain multi graph in one image ////// 02May2013
            CommandRequest grpcmd = new CommandRequest();
            string synedtimg = Path.Combine(System.IO.Path.GetTempPath().Replace("\\", "/"), confService.GetConfigValueForKey("sinkimage"));//23nov2012
            // load default value if no path is set or invalid path is set
            if (synedtimg.Trim().Length == 0 || !IsValidFullPathFilename(synedtimg, false))
            {
                MessageBox.Show(this, "Key 'sinkimage' not found in config file. Aborting...");
                return;
            }

            //27May2015. if parameters are passed, parameter values will take over ( overrides the values set through 'Options'
            if (imageheight > 0 && imagewidth > 0)
            {
                _currentGraphicWidth = imagewidth;
                _currentGraphicHeight = imageheight;
            }
            else // use dimenstions set in 'Options' config. IF thats absent then use 580 as default.
            {
                _currentGraphicWidth = 580;
                _currentGraphicHeight = 580;//defaults
                //get image size from config
                string imgwidth = confService.GetConfigValueForKey("imagewidth");//
                string imgheight = confService.GetConfigValueForKey("imageheight");//

                // load default value if no value is set or invalid value is set
                if (imgwidth.Trim().Length != 0)
                {
                    Int32.TryParse(imgwidth, out _currentGraphicWidth);
                }
                if (imgheight.Trim().Length != 0)
                {
                    Int32.TryParse(imgheight, out _currentGraphicHeight);
                }

            }

            grpcmd.CommandSyntax = "png(\"" + synedtimg + "\", width=" + _currentGraphicWidth + ",height=" + _currentGraphicHeight + ")";
            analytics.ExecuteR(grpcmd, false, false);

            //close graphic device to get the size of empty image and reopen it to keep it open for rest of the graphic processing.
            CloseGraphicsDevice();
            
            // Basically, make sure to find the exact first image name(with full path) that is created when graphic device is opened.
            string tempimgname = synedtimg.Replace("%03d", "001");//this is hard code but should be good till you keep %03d. Otherwise write logic for substitution
            if (File.Exists(tempimgname))
            {
                EMPTYIMAGESIZE = new FileInfo(tempimgname).Length;
            }
            EMPTYIMAGESIZE = EMPTYIMAGESIZE + 10;//increase it by some bytes just to make sure comparision does not fail.

            //Now finally open graphic device to actually wait for graphic command to execute and capture it.
            grpcmd.CommandSyntax = "png(\"" + synedtimg + "\", width=" + _currentGraphicWidth + ",height=" + _currentGraphicHeight + ")";
            analytics.ExecuteR(grpcmd, false, false);
            GraphicDeviceImageCounter = 0;//09Jun2015
        }
 private void ExecuteBSkyCommand(string stmt)
 {
     CommandRequest cmd = new CommandRequest();
     if (IsAnalyticsCommand(stmt))
     {
         ResetSink();
         cmd.CommandSyntax = stmt;// command 
         object o = analytics.ExecuteR(cmd, false, false);//executing syntax editor commands
         SetSink();
     }
 }
 //check file size of PNG file generated by R
 private long GetGraphicSize()//05May2013
 {
     long size=0;
     CommandRequest grpcmd = new CommandRequest();
     string synedtimg = Path.Combine(System.IO.Path.GetTempPath().Replace("\\", "/"), confService.GetConfigValueForKey("sinkimage"));//23nov2012
     // load default value if no path is set or invalid path is set
     if (synedtimg.Trim().Length == 0 || !IsValidFullPathFilename(synedtimg, false))
     {
         MessageBox.Show(this,"Key 'sinkimage' not found in config file. Aborting...");
         return 0;
     }
     if(File.Exists(synedtimg))
     {
         size = new FileInfo(synedtimg).Length;
     }
     return size;
 }
        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
        }
 ////curly block parser////
 private string CurlyBracketParser(string comm, int start, ref int end)
 {
     string str = string.Empty;
     int curlyopen = 0, curlyclose = 0;
     for (int i = comm.IndexOf('{', start); i < comm.Length; i++)
     {
         if (comm.ElementAt(i).Equals('{')) curlyopen++;
         else if (comm.ElementAt(i).Equals('}')) curlyclose++;
         if (curlyopen == curlyclose)
         {
             end = i + 1 - start;
             //if(start < comm.Length)
             str = comm.Substring(start, end).Replace("}}", "} }").Replace(";{", "{").Replace("{;", "{").Replace("}", ";} ");
             start = i + 1;
             break;
         }
     }
     if (curlyopen != curlyclose)
     {
         CommandRequest cmdprn = new CommandRequest();
         cmdprn.CommandSyntax = "write(\"Error in block declaration. Mismatch { or }\",fp)";
         analytics.ExecuteR(cmdprn, false, false); /// for printing command in file
         return "ERROR";
     }
     str = Regex.Replace(str, @";+", ";");//multi semicolon to one ( no space between them)
     //str = Regex.Replace(str, @"}\s+;", "} ");//semicolon after close }
     str = Regex.Replace(str, @";\s*;", ";");//multi semicolon to one(space between them)
     str = Regex.Replace(str, @"}\s*;\s*}", "} }");//semicolon between two closing } }
     str = Regex.Replace(str, @"{\s*;", "{ ");//semicolon immediatly after opening {
     str = Regex.Replace(str, @";\s*{", "{ ");//semicolon immediatly after opening {
     if (str.Contains("else"))
     {
         str = Regex.Replace(str, @"}\s*;*\s*else", "} else");//semicolon before for is needed. Fix for weird bug.
         //str = Regex.Replace(str, @"\s*;*\s*else", "else");//semicolon before for is needed. Fix for weird bug.
     }
     ///if .. else if logic ///
     if ((str.Trim().StartsWith("if") || str.Trim().StartsWith("else")) && comm.Length > end + 1)
     {
         string elsestr = string.Empty;
         if (start + 1 < comm.Length)
             elsestr = comm.Substring(start + 1);
         int originalLen = elsestr.Length;
         elsestr = Regex.Replace(elsestr, @";*\s*else", " else").Trim();
         int newLen = elsestr.Length;
         if (elsestr.StartsWith("else"))
         {
             int end2 = 0;
             str = str + CurlyBracketParser(elsestr, 0, ref end2);
             end = end + end2 + (originalLen - newLen + 1);
         }
     }
     return str;
 }
 //30Sep2014
 // This var must be removed from R memory otherwise when next BSkyFormat fails, it actually formats older object thinking that it is the latest one.
 //To remove temp variable that holds BSkyFormat object.
 private void KillTempBSkyFormatObj(string varname)
 {
     object o;
     CommandRequest cmd = new CommandRequest();
     cmd.CommandSyntax = "exists('" + varname + "')";//removing var so that old obj from last session is not present.
     o = analytics.ExecuteR(cmd, true, false);
     if (o.ToString().ToLower().Equals("true")) // if found, remove it
     {
         cmd.CommandSyntax = "rm('" + varname + "')";//removing var so that old obj from last session is not present.
         o = analytics.ExecuteR(cmd, false, false);
     }
 }
        // 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);
        }
        private void ExecuteSinkBSkyFormatCommand(string stmt, ref int bskyfrmtobjcount, CommandOutput lst)
        {

            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;
            SplitBSkyFormat(stmt, out subcomm, out varname, out BSkyLeftVar);

            if (BSkyLeftVar.Trim().Length > 0) // if left var exists
            {
                BSkyLeftVar = BSkyLeftVar + " <- "; // so that BSkyLeftVar <- BSkyFormat(...) )
            }
            ////now execute subcomm first then pass varname in BSkyFormat(varname)
            if (varname.Length > 0)//will be > 0 only for BSkyFormat(osmt<-one.smt.tt(...) ) OR for BSkyFormat(df)
            {
                headername = varname.Trim();
                cmd.CommandSyntax = subcomm;// command: osmt<-one.smt.tt(...)
                if (!varname.Equals(subcomm))
                    o = analytics.ExecuteR(cmd, false, false);//executing sub-command; osmt<-one.smt.tt(...)
            }
            else //for BSkyFormat(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;
                }

                ////////////////////////////////////////////////////////////////////////
                //13Aug2012 headername = findHeaderName(subcomm); // data.frame / matrix / array header 
                varname = "bskytempvarname";
                //Find if bskytempvarname already exists. If it exists then remove from memory
                cmd.CommandSyntax = "exists('" + varname + "')";//removing var so that old obj from last session is not present.
                o = analytics.ExecuteR(cmd, true, false);
                if (o.ToString().ToLower().Equals("true")) // if found, remove it
                {
                    cmd.CommandSyntax = "rm('" + varname + "')";//removing var so that old obj from last session is not present.
                    o = analytics.ExecuteR(cmd, false, false);
                }

                //Now run command
                cmd.CommandSyntax = varname + " <- " + subcomm;// command: varname <- one.smt.tt(...)
                o = analytics.ExecuteR(cmd, false, false);//executing sub-command
                ////////////////////////////////////////////////////////////////////////
            }
            //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: " + varname + ", does not exists.";
                SendErrorToOutput(originalCommand + "\n" + ewmessage, ow); //03Jul2013
                return;
            }

            //Added extra parameter with TRUE value to fix problem related to uadatasets.sk$holdBSkyFormatObject getting back objeects.
            // when cmd executes in R, few line below. "analytics.ExecuteR(c..."
            stmt = "BSkyFormat(" + varname + ", bSkyFormatAppRequest = TRUE)";

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

            string objclass = "", objectname = "";

            if (stmt.Contains("BSkyFormat("))// Array, Matrix, Data Frame or BSkyObject(ie..Analytic commands)
            {
                bskyfrmtobjcount++;
                stmt = "bskyfrmtobj <- " + stmt;// +"$tables[[1]][[1]]";// +"$additional";//return value additional
                objectname = "bskyfrmtobj";// +bskyfrmtobjcount.ToString();
                cmd.CommandSyntax = stmt;// command 

                //Following statement brings back the objects of uadatasets.sk$holdBSkyFormatObject
                o = analytics.ExecuteR(cmd, false, false);//executing syntax editor commands

                #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 (objclass.ToString().ToLower().Equals("data.frame") || objclass.ToString().ToLower().Equals("matrix") || objclass.ToString().ToLower().Equals("array"))
                    {
                        //lst.NameOfAnalysis = originalCommand;//for tree Parent node 07Aug2012
                        if (headername != null && headername.Trim().Length < 1) //06May2014
                        {
                            headername = subcomm;
                        }

                        BSkyFormatDFMtxArr(lst, objectname, headername, null);
                    }
                    else if (objclass.ToString().Equals("list"))//BSkyObject returns "list"
                    {
                        //if (ow != null)//22May2014
                        SendToOutput("", ref lst, ow);
                        ///tetsing whole else if
                        objectname = "bskyfrmtobj";// +bskyfrmtobjcount.ToString();

                        cmd.CommandSyntax = "is.null(" + objectname + "$BSkySplit)";//$BSkySplit or $split in return structure
                        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
                        bool isNonBSkyList2 = false;
                        object isNonBSkyList2str = analytics.ExecuteR(cmd, true, false);
                        if (isNonBSkyList2str != null && isNonBSkyList2str.ToString().ToLower().Equals("true"))
                        {
                            isNonBSkyList2 = true;
                        }

                        /////////////////
                        if (!isNonBSkyList1)
                        {
                            RefreshOutputORDataset(objectname, cmd, originalCommand, ow); //list like one sample etc..
                        }
                        else if (!isNonBSkyList2)
                        {
                            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";
                        SendErrorToOutput(originalCommand + "\n" + ewmessage, ow);//03Jul2013
                    }
                }/// if leftvar is not assigned generate UI
                #endregion
            }

        }