private void btnGo_Click(object sender, EventArgs e)
        {
            try
            {
                Dictionary<MCCTestCase, int> testCasesWithPriority = new Dictionary<MCCTestCase, int>();

                foreach (MCCTestCase tc in this.checkedListBox1.CheckedItems)
                {
                    this.buildTestCasesWithPriority(ref testCasesWithPriority, tc);
                }
                MCCTestCase[] prioritizedTestCases = testCasesWithPriority.AsEnumerable().OrderBy(q => q.Value).Select(q => q.Key).ToArray();

                BackgroundWorker bgw = new BackgroundWorker();
                bgw.WorkerReportsProgress = true;
                bgw.DoWork += gbw_DoWork;
                bgw.ProgressChanged += bgw_ProgressChanged;
                bgw.RunWorkerCompleted += bgw_RunWorkerCompleted;

                this.rtOutput.Clear();
                this.LockUI();
                bgw.RunWorkerAsync(new object[] { 
                    this.tbServerName.Text, 
                    this.tbAppName.Text, 
                    this.tbDealerName.Text,
                    prioritizedTestCases
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Error: {0}, please retry.", ex.Message));
                this.UnlockUI();
            }
        }
        public string GetClosestColor(string color)
        {
            var c = ColorTranslator.FromHtml(color);
            double diff = 200000;
            var temp = new Dictionary<string, double>();

            foreach (var vColor in ColorConstants.MonoColors)
            {
                if (vColor.Value.Contains(color.Substring(1)))
                {
                    return color;
                }
                else
                {
                    foreach (string colorHex in vColor.Value)
                    {
                        Color validColor = ColorTranslator.FromHtml("#" + colorHex);

                        if (diff > (diff = Math.Pow(c.R - validColor.R, 2) + Math.Pow(c.G - validColor.G, 2) + Math.Pow(c.B - validColor.B, 2)))
                        {
                            if (temp.ContainsKey(colorHex))
                                temp[colorHex] = diff;
                            else
                                temp.Add(colorHex, diff);
                        }
                    }
                }
            }

            return string.Format("#{0}", temp.AsEnumerable().OrderBy(s => s.Value).First().Key);
        }
Example #3
0
        public static StartupServer Create(Uri baseAddress = null)
        {
            var appEnv = CallContextServiceLocator.Locator.ServiceProvider.GetRequiredService<IApplicationEnvironment>();

            var config = new ConfigurationBuilder();
            var configDict = new Dictionary<string, string>();
            configDict["Hosting:Environment"] = "Test";
            config.AddInMemoryCollection(configDict.AsEnumerable());
            var conf = config.Build();

            var env = new HostingEnvironment();
            env.Initialize($"{appEnv.ApplicationBasePath}/../../src/Accounting", conf);
            var startup = new Accounting.Startup(appEnv, env);

            var setup = new SetupObject();

            Action<IApplicationBuilder> buildApp = (app) =>
            {
                app.Use(async (context, next) =>
                {
                    var req = context.Request;
                        
                    if (req.Path == testSetupPathString && setup.Setup != null)
                    {
                        await setup.Setup(context);
                    }
                    else
                    {
                        await next();
                    }
                });
                startup.Configure(app);
            };

            Action<IServiceCollection> buildServices = (services) =>
            {
                startup.ConfigureServices(services);
                services.Remove(services.Where(sp => sp.ServiceType == typeof(IConfigureOptions<AntiforgeryOptions>)).First());
                services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<AntiforgeryOptions>, TestAntiforgeryOptionsSetup>());
                services.AddSingleton<IAntiforgeryTokenSerializer, TestAntiforgeryTokenSerializer>();
                services.AddSingleton<IAntiforgeryTokenGenerator, TestAntiforgeryTokenGenerator>();
            };

            StartupServer server = new StartupServer(CreateBuilder(conf, app => buildApp(app), services => buildServices(services)));
            server.setupObject = setup;
            server.BaseAddress = baseAddress;
            return server;
        }
Example #4
0
        private static async Task<ServerTransaction> Signin(TestServer server, string user, string password)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, $"{TestServerHelper.BaseUrl}/Auth/Signin");
            var dict = new Dictionary<string, string>();
            dict["username"] = user;
            dict["password"] = password;
            request.Content = new FormUrlEncodedContent(dict.AsEnumerable());
            var transaction = new ServerTransaction
            {
                Request = request,
                Response = await server.CreateClient().SendAsync(request),
            };

            if (transaction.Response.Headers.Contains("Set-Cookie"))
            {
                transaction.Cookies = TestServerHelper.GenerateCookies(transaction.Response.Headers.GetValues("Set-Cookie"));
            }

            transaction.ResponseText = await transaction.Response.Content.ReadAsStringAsync();

            return transaction;

        }
        public static string Convert_USGS_to_ClimateData(Period period, string climateFile)
        {

            string path = climateFile;
            StreamReader sreader;
            string centuryPath = "";
            // monthly and daily climates should be filled before in order to chack weather input climatefile can be processed as daily or monthly
            //List<string> montlyClimates;
            //List<string> DailyClimate;

            #region GCM Input file is Daily--- convert to monthly
            if (period == Period.Daily)
            {

                //string path = @"D:\PSU\Landis_II\amin-branch\USGS_Data\Hayhoe_Climate_Data1.csv";
                sreader = new StreamReader(path);
                string line;
                string[] fields;
                //string tempScenarioName = "";
                DataTable _dataTableDataByTime = new DataTable();
                int numberOfAllEcorigions = 0;
                line = sreader.ReadLine();
                fields = line.Split(',');
                //tempScenarioName = fields[0].Substring(1, fields[0].LastIndexOf("t") - 2);
                line = sreader.ReadLine();
                fields = line.Split(',');
                //int totalRows = 0;
                //string[,] wholedata;
                //string CurrentScenarioName = "";

                string CurrentScenarioType = "";
                Dictionary<string, double[]> century_climate_Dic = new Dictionary<string, double[]>();

                //string currentT;
                //string currentSTD;
                //string currentPart = "";
                //int totalRow = 0;
                string key = "";
                int IndexMax_MeanT = 0;
                //int IndexMax_MaxT = 1;
                int IndexMax_Var = 1;
                int IndexMax_STD = 2;
                int IndexMin_MeanT = 3;
                //int IndexMin_MaxT = 5;
                int IndexMin_Var = 4;
                int IndexMin_STD = 5;
                int IndexPrcp_MeanT = 6;
                //int IndexPrcp_MaxT = 9;
                int IndexPrcp_Var = 7;
                int IndexPrcp_STD = 8;

                //bool firstFlag = false;
                string currentYear = "";
                int currentTimeS = 0;
                int currentMonth = 1;
                int tempEco = 1;
                double AverageMax = 0;

                //double AverageMaxSTD = 0;
                double AverageMin = 0;
                //double AverageMinSTD = 0;
                double AveragePrecp = 0;

                double AverageSTDT = 0;
                double StdDevPpt = 0;
                //double AveragePrecSTD = 0;
                int numberOfDays = 0;
                double[] tempSum = new double[31];
                double[] tempPrp = new double[31];
                //double sums = 0;
                //double prpSums = 0;
                //double stdTemp = 0;
                //double stdPrp = 0;
                bool emptytxt = false;
                int updatedIndex = 0;

                foreach (string field in fields)
                {
                    if (field != "" && Convert.ToInt16(field) > numberOfAllEcorigions)
                    {
                        numberOfAllEcorigions = Convert.ToInt16(field);
                    }
                }
                //12 beacuse for each ecoriogn we need Max_MinT,Max_MaxT,Max_Var Max_Std, Min_MinT,Min_MaxT,Min_Var Min_Std, Prcp_MinT,Prcp_MaxT,Prcp_Var Prcp_Std
                int dicSize = numberOfAllEcorigions * 9;
                sreader.Close();
                StreamReader reader = new StreamReader(path);

                while (reader.Peek() >= 0)
                {
                    line = reader.ReadLine();
                    fields = line.Split(',');
                    foreach (string field in fields)
                    {
                        if (field.Contains("#"))
                        {
                            //tempScenarioName = CurrentScenarioName;
                            if (field.ToLower().Contains(maxTriggerWord) || field.ToLower().Contains(minTriggerWord))
                            {
                                //CurrentScenarioName = field.Substring(1, field.LastIndexOf("t") - 2);
                                if (field.ToLower().Contains(maxTriggerWord))
                                    CurrentScenarioType = maxTriggerWord;
                                if (field.ToLower().Contains(minTriggerWord))
                                    CurrentScenarioType = minTriggerWord;
                            }
                            if (field.ToLower().Contains(prcpTriggerWord))
                            {
                                //CurrentScenarioName = field.Substring(1, field.LastIndexOf("p") - 2);
                                CurrentScenarioType = prcpTriggerWord;

                            }

                            //if (tempScenarioName != CurrentScenarioName)// firstFlag == false)
                            //{
                            //    tempScenarioName = CurrentScenarioName;
                            //    //firstFlag = true;
                            //}



                            //line = reader.ReadLine();
                            //fields = line.Split(',');

                        }



                    }

                    if (fields[0] == string.Empty && !fields[0].Contains("#"))
                    {
                        line = reader.ReadLine();
                        fields = line.Split(',');

                        if (fields[0].Contains("TIME"))
                        {
                            line = reader.ReadLine();
                            fields = line.Split(',');

                            //now fill array 
                            //Get the lenght of array according to the number of ecorigions/
                            //

                        }
                    }
                    if (!fields[0].Contains("#"))
                    //if (CurrentScenarioName == tempScenarioName && !fields[0].Contains("#"))
                    {

                        key = fields[0].ToString();
                        if (CurrentScenarioType.Contains(maxTriggerWord))
                        {
                            IndexMax_MeanT = 0;
                            //IndexMax_MaxT = 1;
                            IndexMax_Var = 1;
                            IndexMax_STD = 2;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcorigions);
                            if (!century_climate_Dic.Keys.Contains(key))
                                century_climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });

                            //set index of max and maxSTD for each ecorigion
                            for (int i = 1; i <= numberOfAllEcorigions; i++)
                            {
                                //currentT = fields[i];
                                //if (indexofSTD < 26)
                                //{

                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[i]), IndexMax_MeanT);
                                updatedIndex += i + numberOfAllEcorigions;
                                //century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexMax_MaxT);
                                //updatedIndex +=  numberOfAllEcorigions;
                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexMax_Var);
                                updatedIndex += numberOfAllEcorigions;
                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexMax_STD);
                                IndexMax_MeanT = IndexMax_MeanT + 9;
                                //IndexMax_MaxT = IndexMax_MaxT + 12;
                                IndexMax_Var = IndexMax_Var + 9;
                                IndexMax_STD = IndexMax_STD + 9;
                                updatedIndex = 0;

                                //indexofSTD++;
                                //}

                            }
                        }
                        else if (CurrentScenarioType.Contains(minTriggerWord))
                        {
                            IndexMin_MeanT = 3;
                            //IndexMin_MaxT = 5;
                            IndexMin_Var = 4;
                            IndexMin_STD = 5;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcorigions);

                            // century_climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });
                            if (!century_climate_Dic.Keys.Contains(key))
                                century_climate_Dic.Add(key, new double[dicSize]);
                            //set index of max and maxSTD for each ecorigion
                            for (int i = 1; i <= numberOfAllEcorigions; i++)
                            {
                                //currentT = fields[i];
                                //if (indexofSTD < 26)
                                //{
                                //currentSTD = fields[indexofSTD];
                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[i]), IndexMin_MeanT);
                                updatedIndex += i + numberOfAllEcorigions;
                                //century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexMin_MaxT);
                                //updatedIndex += numberOfAllEcorigions;
                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexMin_Var);
                                updatedIndex += numberOfAllEcorigions;
                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexMin_STD);


                                //century_climate_Dic[key].SetValue(Convert.ToDouble(currentSTD), IndexSTD);
                                IndexMin_MeanT = IndexMin_MeanT + 9;
                                //IndexMin_MaxT = IndexMin_MaxT + 12;
                                IndexMin_Var = IndexMin_Var + 9;
                                IndexMin_STD = IndexMin_STD + 9;
                                updatedIndex = 0;
                                //    IndexSTD = IndexSTD + 6;
                                //    indexofSTD++;
                                //}

                            }
                        }
                        else if (CurrentScenarioType.Contains(prcpTriggerWord))
                        {
                            IndexPrcp_MeanT = 6;
                            //IndexPrcp_MaxT = 9;
                            IndexPrcp_Var = 7;
                            IndexPrcp_STD = 8;

                            //IndexSTD = 5;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcorigions);

                            // century_climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });
                            if (!century_climate_Dic.Keys.Contains(key))
                                century_climate_Dic.Add(key, new double[dicSize]);
                            //set index of max and maxSTD for each ecorigion
                            for (int i = 1; i <= numberOfAllEcorigions; i++)
                            {
                                //currentT = fields[i];
                                //if (indexofSTD < 26)
                                //{
                                //currentSTD = fields[indexofSTD];
                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[i]), IndexPrcp_MeanT);
                                updatedIndex += i + numberOfAllEcorigions;
                                //century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexPrcp_MaxT);
                                //updatedIndex += numberOfAllEcorigions;
                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexPrcp_Var);
                                updatedIndex += numberOfAllEcorigions;
                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexPrcp_STD);


                                //century_climate_Dic[key].SetValue(Convert.ToDouble(currentSTD), IndexSTD);
                                IndexPrcp_MeanT = IndexPrcp_MeanT + 9;
                                //IndexPrcp_MaxT = IndexPrcp_MaxT + 12;
                                IndexPrcp_Var = IndexPrcp_Var + 9;
                                IndexPrcp_STD = IndexPrcp_STD + 9;
                                updatedIndex = 0;
                                //IndexSTD = IndexSTD + 6;
                                //indexofSTD++;
                            }

                        }

                    }

                    //if (CurrentScenarioName != tempScenarioName || reader.EndOfStream)
                    if (reader.EndOfStream)
                    {
                        //tempScenarioName = CurrentScenarioName;
                        //Print file for one scenario then clear dictionary to use for another scenario

                        //Daily peiod
                        centuryPath = "Century_Climate_Inputs_Monthly.txt";
                        //int AverageMaxT = 0;
                        //int AverageMaxSTD = 1;
                        //int AverageMinT = 2;
                        //int AverageMinSTD = 3;
                        //int AveragePrec = 4;
                        //int AveragePrecSTD = 5;
                        IndexMax_MeanT = 0;
                        //IndexMax_MaxT = 1;
                        IndexMax_Var = 1;
                        IndexMax_STD = 2;
                        IndexMin_MeanT = 3;
                        //IndexMin_MaxT = 5;
                        IndexMin_Var = 4;
                        IndexMin_STD = 5;
                        IndexPrcp_MeanT = 6;
                        //IndexPrcp_MaxT = 9;
                        IndexPrcp_Var = 7;
                        IndexPrcp_STD = 8;


                        //int AverageMaxT = 0;
                        //int AverageMaxSTD = 1;
                        //int AverageMinT = 1;
                        //int AverageMinSTD = 3;
                        //int AveragePrec = 2;
                        //int AveragePrecSTD = 5;
                        using (System.IO.StreamWriter file = new System.IO.StreamWriter(centuryPath, emptytxt))
                        {
                            file.WriteLine("LandisData" + " \"Climate Data\" \n");
                            file.WriteLine("ClimateTable \n");
                            //file.WriteLine(tempScenarioName + "\n");
                            file.WriteLine(">>Eco" + "\t" + "Time" + "\t" + "Month" + "\t" + "AvgMinT" + "\t" + "AvgMaxT" + "\t" + "StdDevT" + "\t" + "AvgPpt" + "\t" + "StdDev" + "\t" + "PAR" + "\t" + "VarT" + "\t" + "VarPpt" + "\n");
                            file.WriteLine(">>Name" + "\t" + "Step" + "\t" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(k)" + "\t" + "(cm)" + "\t" + "Ppt" + "\t" + "µmol m-2 s-1" + "\t" + "(cm)" + "\t" + "(cm)" + "\n");
                            //file.WriteLine(">>Eco" + "\t" + "Time" + "\t" + "\t" + "AvgMaxT" + "\t" + "StdMaxT" + "\t" + "AvgMinT" + "\t" + "StdMinT" + "\t" + "AvgPpt" + "\t" + "StdDev" + "\n");
                            // file.WriteLine(">>Name" + "\t" + "Step" + "\t" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(C)" + "\n");
                            //initialize currentYear and month
                            currentYear = century_climate_Dic.First().Key.Substring(0, 4).ToString();
                            //starting timestep
                            currentTimeS = 0;
                            currentMonth = Convert.ToInt16(century_climate_Dic.First().Key.Substring(5, 2).ToString());
                            tempEco = 1;

                            int lastYear = century_climate_Dic.AsEnumerable().Select(ax => Convert.ToInt32(ax.Key.Substring(0, 4).ToString())).Distinct().ToList().Max();
                            int firstYear = century_climate_Dic.AsEnumerable().Select(ai => Convert.ToInt32(ai.Key.Substring(0, 4).ToString())).Distinct().ToList().Min();
                            if ((double)century_climate_Dic.Count / 12 > (double)lastYear - firstYear)
                                lastYear = lastYear - 1;

                            for (int j = firstYear; j <= lastYear; j++)
                            {
                                for (int i = 1; i <= numberOfAllEcorigions; i++)
                                {
                                    currentYear = j.ToString();

                                    foreach (KeyValuePair<string, double[]> row in century_climate_Dic)
                                    {

                                        if (currentYear == row.Key.Substring(0, 4).ToString())
                                        {

                                            if (currentMonth == Convert.ToInt16(row.Key.Substring(5, 2)))
                                            {

                                                //(row.Value[IndexMax_MaxT] + row.Value[IndexMax_MeanT])/2
                                                //AverageMin += (row.Value[IndexMin_MaxT] + row.Value[IndexMin_MeanT]) / 2;
                                                //AverageMax += (row.Value[IndexMax_MaxT] + row.Value[IndexMax_MeanT]) / 2;
                                                //AveragePrecp += (row.Value[IndexPrcp_MaxT] + row.Value[IndexPrcp_MeanT]) / 2;
                                                //AverageSTDT += (row.Value[IndexMax_Var] + row.Value[IndexMin_Var]) / 2;
                                                //AverageMaxSTD += Math.Round(Convert.ToDouble(row.Value[2]), 2);
                                                AverageMin += Math.Round(row.Value[IndexMin_MeanT], 2);
                                                AverageMax += Math.Round(row.Value[IndexMax_MeanT], 2);
                                                AveragePrecp += Math.Round(row.Value[IndexPrcp_MeanT], 2);
                                                AverageSTDT += Math.Round((row.Value[IndexMax_Var] + row.Value[IndexMin_Var]) / 2, 2);
                                                StdDevPpt += Convert.ToDouble(row.Value[IndexPrcp_Var]);


                                                numberOfDays++;

                                            }


                                            else
                                            {

                                                file.WriteLine("eco" + i.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(StdDevPpt), 2) + "\t" + "0.0" + "\t" + Math.Round(AverageSTDT / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt / numberOfDays, 2) + "\n");
                                                currentMonth = Convert.ToInt16(row.Key.Substring(5, 2));
                                                //if (tempMonth != currentMonth)

                                                AverageMax = 0;
                                                AverageMin = 0;
                                                AveragePrecp = 0;
                                                AverageSTDT = 0;
                                                StdDevPpt = 0;

                                                numberOfDays = 0;
                                                AverageMin += Math.Round(row.Value[IndexMin_MeanT], 2);
                                                AverageMax += Math.Round(row.Value[IndexMax_MeanT], 2);
                                                AveragePrecp += Math.Round(row.Value[IndexPrcp_MeanT], 2);
                                                AverageSTDT += Math.Round((row.Value[IndexMax_Var] + row.Value[IndexMin_Var]) / 2, 2);
                                                StdDevPpt += Convert.ToDouble(row.Value[IndexPrcp_Var]);

                                                numberOfDays++;
                                            }

                                        }
                                        else
                                        {
                                            //If ecorigion has been changed
                                            //if (tempEco != i && currentMonth == 12)
                                            //{
                                            //    file.WriteLine("eco" + tempEco.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(StdDevPpt), 2) + "\t" + "0.0" + "\n");
                                            //    currentTimeS = 0;
                                            //}
                                            if (currentMonth == 12)
                                            {
                                                file.WriteLine("eco" + i.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(StdDevPpt), 2) + "\t" + "0.0" + "\t" + Math.Round(AverageSTDT / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt / numberOfDays, 2) + "\n");
                                            }
                                            //else if (tempEco != i)
                                            //    currentTimeS = 0;


                                            //file.WriteLine("eco1" + "\t" + currentYear + "\t" + currentMonth + "\t" + Math.Round(AverageMaxT / numberOfDays, 2) + "\t" + Math.Round(AverageMaxSTD / numberOfDays, 2) + "\t" + Math.Round(AverageMinT / numberOfDays, 2) + "\t" + Math.Round(AverageMinSTD / numberOfDays, 2) + "\t" + Math.Round(AveragePrec / numberOfDays, 2) + "\t" + Math.Round(AveragePrecSTD / numberOfDays, 2) + "\n");

                                            //currentYear = row.Key.Substring(0, 4).ToString();

                                            tempEco = i;
                                            currentMonth = 1;
                                            AverageMax = 0;
                                            //AverageMaxSTD = 0;
                                            AverageMin = 0;
                                            //AverageMinSTD = 0;
                                            AveragePrecp = 0;
                                            //AveragePrecSTD = 0;

                                            AverageSTDT = 0;
                                            StdDevPpt = 0;

                                            numberOfDays = 0;
                                            AverageMin += Math.Round(row.Value[IndexMin_MeanT], 2);
                                            AverageMax += Math.Round(row.Value[IndexMax_MeanT], 2);
                                            AveragePrecp += Math.Round(row.Value[IndexPrcp_MeanT], 2);
                                            AverageSTDT += Math.Round((row.Value[IndexMax_Var] + row.Value[IndexMin_Var]) / 2, 2);
                                            StdDevPpt += Convert.ToDouble(row.Value[IndexPrcp_Var]);
                                            //sums = 0;
                                            //stdTemp = 0;
                                            //prpSums = 0;
                                            //stdPrp = 0;
                                            numberOfDays++;
                                        }


                                    }
                                    tempEco = i;

                                    currentMonth = 1;
                                    AverageMax = 0;
                                    //AverageMaxSTD = 0;
                                    AverageMin = 0;
                                    //AverageMinSTD = 0;
                                    AveragePrecp = 0;
                                    //AveragePrecSTD = 0;

                                    AverageSTDT = 0;
                                    StdDevPpt = 0;

                                    IndexMax_MeanT = IndexMax_MeanT + 9;
                                    //IndexMax_MaxT = IndexMax_MaxT + 12;
                                    IndexMax_Var = IndexMax_Var + 9;
                                    IndexMax_STD = IndexMax_STD + 9;
                                    IndexMin_MeanT = IndexMin_MeanT + 9;
                                    //IndexMin_MaxT = IndexMin_MaxT + 12;
                                    IndexMin_Var = IndexMin_Var + 9;
                                    IndexMin_STD = IndexMin_STD + 9;
                                    IndexPrcp_MeanT = IndexPrcp_MeanT + 9;
                                    //IndexPrcp_MaxT = IndexPrcp_MaxT + 12;
                                    IndexPrcp_Var = IndexPrcp_Var + 9;
                                    IndexPrcp_STD = IndexPrcp_STD + 9;
                                }
                                //file.WriteLine("eco" + numberOfAllEcorigions.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(StdDevPpt), 2) + "\t" + "0.0" + "\n");

                                tempEco = 1;
                                currentTimeS = currentTimeS + 1;
                                IndexMax_MeanT = 0;
                                //IndexMax_MaxT = 1;
                                IndexMax_Var = 1;
                                IndexMax_STD = 2;
                                IndexMin_MeanT = 3;
                                //IndexMin_MaxT = 5;
                                IndexMin_Var = 4;
                                IndexMin_STD = 5;
                                IndexPrcp_MeanT = 6;
                                //IndexPrcp_MaxT = 9;
                                IndexPrcp_Var = 7;
                                IndexPrcp_STD = 8;
                                currentMonth = 1;
                                AverageMax = 0;
                                //AverageMaxSTD = 0;
                                AverageMin = 0;
                                //AverageMinSTD = 0;
                                AveragePrecp = 0;
                                //AveragePrecSTD = 0;

                                AverageSTDT = 0;
                                StdDevPpt = 0;
                            }

                        }

                        //If file contains more than one scenario then these setting will be needed
                        century_climate_Dic.Clear();
                        emptytxt = true;
                        //tempScenarioName = CurrentScenarioName;

                    }
                }




            }
            #endregion


            #region PRISM Data
            else if (period == Period.Monthly)
            {


                //string path = @"D:\PSU\Landis_II\amin-branch\USGS_Data\Hayhoe_Climate_Data1.csv";
                sreader = new StreamReader(path);
                string line;
                string[] fields;
                //string tempScenarioName = "";
                DataTable _dataTableDataByTime = new DataTable();
                int numberOfAllEcorigions = 0;
                line = sreader.ReadLine();
                fields = line.Split(',');
                //tempScenarioName = fields[0].Substring(1, fields[0].LastIndexOf("t") - 2);
                //tempScenarioName = fields[0].Substring(1, 4);
                line = sreader.ReadLine();
                fields = line.Split(',');
                //int totalRows = 0;
                //string[,] wholedata;
                //string CurrentScenarioName = "";

                string CurrentScenarioType = "";
                Dictionary<string, double[]> century_climate_Dic = new Dictionary<string, double[]>();

                //string currentT;
                //string currentSTD;
                //string currentPart = "";
                //int totalRow = 0;
                string key = "";
                int IndexMax_MeanT = 0;
                //int IndexMax_MaxT = 1;
                int IndexMax_Var = 1;
                int IndexMax_STD = 2;
                int IndexMin_MeanT = 3;
                //int IndexMin_MaxT = 5;
                int IndexMin_Var = 4;
                int IndexMin_STD = 5;
                int IndexPrcp_MeanT = 6;
                //int IndexPrcp_MaxT = 9;
                int IndexPrcp_Var = 7;
                int IndexPrcp_STD = 8;

                //bool firstFlag = false;
                string currentYear = "";
                //starting timestep
                int currentTimeS = 0;
                int currentMonth = 1;
                int tempEco = 1;
                double AverageMax = 0;

                //double AverageMaxSTD = 0;
                double AverageMin = 0;
                //double AverageMinSTD = 0;
                double AveragePrecp = 0;

                double AverageSTDT = 0;
                double StdDevPpt = 0;
                //double AveragePrecSTD = 0;
                int numberOfDays = 0;
                double[] tempSum = new double[31];
                double[] tempPrp = new double[31];
                //double sums = 0;
                //double prpSums = 0;
                //double stdTemp = 0;
                //double stdPrp = 0;
                bool emptytxt = false;
                int updatedIndex = 0;

                foreach (string field in fields)
                {
                    if (field != "" && Convert.ToInt16(field) > numberOfAllEcorigions)
                    {
                        numberOfAllEcorigions = Convert.ToInt16(field);
                    }
                }
                //12 beacuse for each ecoriogn we need Max_MinT,Max_MaxT,Max_Var Max_Std, Min_MinT,Min_MaxT,Min_Var Min_Std, Prcp_MinT,Prcp_MaxT,Prcp_Var Prcp_Std
                int dicSize = numberOfAllEcorigions * 9;
                sreader.Close();
                StreamReader reader = new StreamReader(path);

                while (reader.Peek() >= 0)
                {
                    line = reader.ReadLine();
                    fields = line.Split(',');
                    foreach (string field in fields)
                    {
                        if (field.Contains("#"))
                        {
                            //tempScenarioName = CurrentScenarioName;
                            if (field.ToLower().Contains(prcpTriggerWord))
                            {
                                //CurrentScenarioName = field.Substring(1, 4);
                                CurrentScenarioType = prcpTriggerWord;

                            }

                            else if (field.ToLower().Contains(maxTriggerWord) || field.Contains(minTriggerWord))
                            {
                                //CurrentScenarioName = field.Substring(1, 4);
                                if (field.ToLower().Contains(maxTriggerWord))
                                    CurrentScenarioType = maxTriggerWord;
                                if (field.ToLower().Contains(minTriggerWord))
                                    CurrentScenarioType = minTriggerWord;
                            }


                            //if (tempScenarioName != CurrentScenarioName)// firstFlag == false)
                            //{
                            //    tempScenarioName = CurrentScenarioName;
                            //    //firstFlag = true;
                            //}



                            //line = reader.ReadLine();
                            //fields = line.Split(',');

                        }



                    }

                    if (fields[0] == string.Empty && !fields[0].Contains("#"))
                    {
                        line = reader.ReadLine();
                        fields = line.Split(',');

                        if (fields[0].Contains("TIME"))
                        {
                            line = reader.ReadLine();
                            fields = line.Split(',');

                            //now fill array 
                            //Get the lenght of array according to the number of ecorigions/
                            //

                        }
                    }
                    if (!fields[0].Contains("#"))//(CurrentScenarioName == tempScenarioName && !fields[0].Contains("#"))
                    {

                        key = fields[0].ToString();
                        if (CurrentScenarioType.Contains(prcpTriggerWord))
                        {
                            IndexPrcp_MeanT = 6;
                            //IndexPrcp_MaxT = 9;
                            IndexPrcp_Var = 7;
                            IndexPrcp_STD = 8;

                            //IndexSTD = 5;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcorigions);

                            // century_climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });
                            if (!century_climate_Dic.Keys.Contains(key))
                                century_climate_Dic.Add(key, new double[dicSize]);
                            //set index of max and maxSTD for each ecorigion
                            for (int i = 1; i <= numberOfAllEcorigions; i++)
                            {
                                //currentT = fields[i];
                                //if (indexofSTD < 26)
                                //{
                                //currentSTD = fields[indexofSTD];
                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[i]), IndexPrcp_MeanT);
                                updatedIndex += i + numberOfAllEcorigions;
                                //century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexPrcp_MaxT);
                                //updatedIndex += numberOfAllEcorigions;
                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexPrcp_Var);
                                updatedIndex += numberOfAllEcorigions;
                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexPrcp_STD);


                                //century_climate_Dic[key].SetValue(Convert.ToDouble(currentSTD), IndexSTD);
                                IndexPrcp_MeanT = IndexPrcp_MeanT + 9;
                                //IndexPrcp_MaxT = IndexPrcp_MaxT + 12;
                                IndexPrcp_Var = IndexPrcp_Var + 9;
                                IndexPrcp_STD = IndexPrcp_STD + 9;
                                updatedIndex = 0;
                                //IndexSTD = IndexSTD + 6;
                                //indexofSTD++;
                            }

                        }

                        else if (CurrentScenarioType.Contains(maxTriggerWord))
                        {
                            IndexMax_MeanT = 0;
                            //IndexMax_MaxT = 1;
                            IndexMax_Var = 1;
                            IndexMax_STD = 2;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcorigions);
                            if (!century_climate_Dic.Keys.Contains(key))
                                century_climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });

                            //set index of max and maxSTD for each ecorigion
                            for (int i = 1; i <= numberOfAllEcorigions; i++)
                            {
                                //currentT = fields[i];
                                //if (indexofSTD < 26)
                                //{

                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[i]), IndexMax_MeanT);
                                updatedIndex += i + numberOfAllEcorigions;
                                //century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexMax_MaxT);
                                //updatedIndex +=  numberOfAllEcorigions;
                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexMax_Var);
                                updatedIndex += numberOfAllEcorigions;
                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexMax_STD);
                                IndexMax_MeanT = IndexMax_MeanT + 9;
                                //IndexMax_MaxT = IndexMax_MaxT + 12;
                                IndexMax_Var = IndexMax_Var + 9;
                                IndexMax_STD = IndexMax_STD + 9;
                                updatedIndex = 0;

                                //indexofSTD++;
                                //}

                            }
                        }
                        else if (CurrentScenarioType.Contains(minTriggerWord))
                        {
                            IndexMin_MeanT = 3;
                            //IndexMin_MaxT = 5;
                            IndexMin_Var = 4;
                            IndexMin_STD = 5;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcorigions);

                            // century_climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });

                            //set index of max and maxSTD for each ecorigion
                            if (!century_climate_Dic.Keys.Contains(key))
                                century_climate_Dic.Add(key, new double[dicSize]);
                            for (int i = 1; i <= numberOfAllEcorigions; i++)
                            {
                                //currentT = fields[i];
                                //if (indexofSTD < 26)
                                //{
                                //currentSTD = fields[indexofSTD];
                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[i]), IndexMin_MeanT);
                                updatedIndex += i + numberOfAllEcorigions;
                                //century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexMin_MaxT);
                                //updatedIndex += numberOfAllEcorigions;
                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexMin_Var);
                                updatedIndex += numberOfAllEcorigions;
                                century_climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex]), IndexMin_STD);


                                //century_climate_Dic[key].SetValue(Convert.ToDouble(currentSTD), IndexSTD);
                                IndexMin_MeanT = IndexMin_MeanT + 9;
                                //IndexMin_MaxT = IndexMin_MaxT + 12;
                                IndexMin_Var = IndexMin_Var + 9;
                                IndexMin_STD = IndexMin_STD + 9;
                                updatedIndex = 0;
                                //    IndexSTD = IndexSTD + 6;
                                //    indexofSTD++;
                                //}

                            }
                        }


                    }

                    if (reader.EndOfStream)//CurrentScenarioName != tempScenarioName || reader.EndOfStream)
                    {
                        //tempScenarioName = CurrentScenarioName;
                        //Print file for one scenario then clear dictionary to use for another scenario

                        //Monthly peiod
                        centuryPath = "Century_Climate_Inputs_PRISM_Monthly.txt";
                        //int AverageMaxT = 0;
                        //int AverageMaxSTD = 1;
                        //int AverageMinT = 2;
                        //int AverageMinSTD = 3;
                        //int AveragePrec = 4;
                        //int AveragePrecSTD = 5;
                        IndexMax_MeanT = 0;
                        //IndexMax_MaxT = 1;
                        IndexMax_Var = 1;
                        IndexMax_STD = 2;
                        IndexMin_MeanT = 3;
                        //IndexMin_MaxT = 5;
                        IndexMin_Var = 4;
                        IndexMin_STD = 5;
                        IndexPrcp_MeanT = 6;
                        //IndexPrcp_MaxT = 9;
                        IndexPrcp_Var = 7;
                        IndexPrcp_STD = 8;


                        //int AverageMaxT = 0;
                        //int AverageMaxSTD = 1;
                        //int AverageMinT = 1;
                        //int AverageMinSTD = 3;
                        //int AveragePrec = 2;
                        //int AveragePrecSTD = 5;
                        using (System.IO.StreamWriter file = new System.IO.StreamWriter(centuryPath, emptytxt))
                        {
                            file.WriteLine("LandisData" + " \"Climate Data\" \n");
                            file.WriteLine("ClimateTable \n");
                            //file.WriteLine(tempScenarioName + "\n");

                            file.WriteLine(">>Eco" + "\t" + "Time" + "\t" + "Month" + "\t" + "AvgMinT" + "\t" + "AvgMaxT" + "\t" + "StdDevT" + "\t" + "AvgPpt" + "\t" + "StdDev" + "\t" + "PAR" + "\t" + "VarT" + "\t" + "VarPpt" + "\n");
                            file.WriteLine(">>Name" + "\t" + "Step" + "\t" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(k)" + "\t" + "(cm)" + "\t" + "Ppt" + "\t" + "µmol m-2 s-1" + "\t" + "(cm)" + "\t" + "(cm)" + "\n");
                            //file.WriteLine(">>Eco" + "\t" + "Time" + "\t" + "Month" + "\t" + "AvgMinT" + "\t" + "AvgMaxT" + "\t" + "StdDevT" + "\t" + "AvgPpt" + "\t" + "StdDev" + "\t" + "PAR" + "\n");
                            //file.WriteLine(">>Name" + "\t" + "Step" + "\t" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(k)" + "\t" + "(cm)" + "\t" + "Ppt" + "\t" + "µmol m-2 s-1" + "\n");
                            //file.WriteLine(">>Eco" + "\t" + "Time" + "\t" + "\t" + "AvgMaxT" + "\t" + "StdMaxT" + "\t" + "AvgMinT" + "\t" + "StdMinT" + "\t" + "AvgPpt" + "\t" + "StdDev" + "\n");
                            // file.WriteLine(">>Name" + "\t" + "Step" + "\t" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(C)" + "\n");
                            //initialize currentYear and month
                            currentYear = century_climate_Dic.First().Key.Substring(0, 4).ToString();
                            //starting timestep
                            currentTimeS = 0;
                            currentMonth = Convert.ToInt16(century_climate_Dic.First().Key.Substring(5, 2).ToString());
                            tempEco = 1;
                            int lastYear = century_climate_Dic.AsEnumerable().Select(ax => Convert.ToInt32(ax.Key.Substring(0, 4).ToString())).Distinct().ToList().Max();
                            int firstYear = century_climate_Dic.AsEnumerable().Select(ai => Convert.ToInt32(ai.Key.Substring(0, 4).ToString())).Distinct().ToList().Min();
                            if ((double)century_climate_Dic.Count / 12 > (double)lastYear - firstYear)
                                lastYear = lastYear - 1;
                            for (int j = firstYear; j <= lastYear; j++)
                            {
                                for (int i = 1; i <= numberOfAllEcorigions; i++)
                                {
                                    currentYear = j.ToString();
                                    foreach (KeyValuePair<string, double[]> row in century_climate_Dic)
                                    {

                                        if (currentYear == row.Key.Substring(0, 4).ToString())
                                        {
                                            if (currentMonth == Convert.ToInt16(row.Key.Substring(5, 2)))
                                            {
                                                AverageMin += Math.Round(row.Value[IndexMin_MeanT], 2);
                                                AverageMax += Math.Round(row.Value[IndexMax_MeanT], 2);
                                                AveragePrecp += Math.Round(row.Value[IndexPrcp_MeanT], 2);
                                                AverageSTDT += Math.Round((row.Value[IndexMax_Var] + row.Value[IndexMin_Var]) / 2, 2);
                                                StdDevPpt += Convert.ToDouble(row.Value[IndexPrcp_STD]);
                                                numberOfDays++;

                                            }
                                            else
                                            {
                                                file.WriteLine("eco" + i.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt, 2) + "\t" + "0.0" + "\t" + Math.Round(AverageSTDT / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt / numberOfDays, 2) + "\n");
                                                //file.WriteLine("eco1" + "\t" + currentYear + "\t" + currentMonth + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(AverageMaxSTD / numberOfDays, 2) + "\t" + Math.Round(AverageMinT / numberOfDays, 2) + "\t" + Math.Round(AverageMinSTD / numberOfDays, 2) + "\t" + Math.Round(AveragePrec / numberOfDays, 2) + "\t" + Math.Round(AveragePrecSTD / numberOfDays, 2) + "\n");
                                                //tempMonth = currentMonth;
                                                currentMonth = Convert.ToInt16(row.Key.Substring(5, 2));
                                                //if (tempMonth != currentMonth)

                                                AverageMax = 0;
                                                //AverageMaxSTD = 0;
                                                AverageMin = 0;
                                                //AverageMinSTD = 0;
                                                AveragePrecp = 0;
                                                //AveragePrecSTD = 0;
                                                AverageSTDT = 0;
                                                StdDevPpt = 0;
                                                numberOfDays = 0;
                                                AverageMin += Math.Round(row.Value[IndexMin_MeanT], 2);
                                                AverageMax += Math.Round(row.Value[IndexMax_MeanT], 2);
                                                AveragePrecp += Math.Round(row.Value[IndexPrcp_MeanT], 2);
                                                AverageSTDT += Math.Round((row.Value[IndexMax_Var] + row.Value[IndexMin_Var]) / 2, 2);
                                                StdDevPpt += Convert.ToDouble(row.Value[IndexPrcp_STD]);
                                                //sums = 0;
                                                //stdTemp = 0;
                                                //prpSums = 0;
                                                //stdPrp = 0;
                                                numberOfDays++;
                                            }
                                        }
                                        else //  currentYear != row.Key.Substring(0, 4).ToString())
                                        {
                                            //if (tempEco != i && currentMonth == 12)
                                            //    file.WriteLine("eco" + tempEco.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt, 2) + "\t" + "0.0" + "\n");

                                            if (currentMonth == 12)
                                                file.WriteLine("eco" + i.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt, 2) + "\t" + "0.0" + "\t" + Math.Round(AverageSTDT / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt / numberOfDays, 2) + "\n");
                                            ////if (currentTimeS == 0 && currentMonth == 12 && i==2)
                                            //    file.WriteLine("eco2" + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt, 2) + "\t" + "0.0" + "\n");

                                            //else if (tempEco != i)
                                            //    currentTimeS = 0;
                                            //file.WriteLine("eco1" + "\t" + currentYear + "\t" + currentMonth + "\t" + Math.Round(AverageMaxT / numberOfDays, 2) + "\t" + Math.Round(AverageMaxSTD / numberOfDays, 2) + "\t" + Math.Round(AverageMinT / numberOfDays, 2) + "\t" + Math.Round(AverageMinSTD / numberOfDays, 2) + "\t" + Math.Round(AveragePrec / numberOfDays, 2) + "\t" + Math.Round(AveragePrecSTD / numberOfDays, 2) + "\n");

                                            //currentYear = row.Key.Substring(0, 4).ToString();
                                            //currentTimeS = currentTimeS + 1;
                                            tempEco = i;
                                            currentMonth = 1;
                                            AverageMax = 0;
                                            //AverageMaxSTD = 0;
                                            AverageMin = 0;
                                            //AverageMinSTD = 0;
                                            AveragePrecp = 0;
                                            //AveragePrecSTD = 0;

                                            AverageSTDT = 0;
                                            StdDevPpt = 0;

                                            numberOfDays = 0;

                                        }
                                    }
                                    tempEco = i;
                                    currentMonth = 1;
                                    AverageMax = 0;
                                    //AverageMaxSTD = 0;
                                    AverageMin = 0;
                                    //AverageMinSTD = 0;
                                    AveragePrecp = 0;
                                    //AveragePrecSTD = 0;

                                    AverageSTDT = 0;
                                    StdDevPpt = 0;
                                    IndexMax_MeanT = IndexMax_MeanT + 9;
                                    //IndexMax_MaxT = IndexMax_MaxT + 12;
                                    IndexMax_Var = IndexMax_Var + 9;
                                    IndexMax_STD = IndexMax_STD + 9;
                                    IndexMin_MeanT = IndexMin_MeanT + 9;
                                    //IndexMin_MaxT = IndexMin_MaxT + 12;
                                    IndexMin_Var = IndexMin_Var + 9;
                                    IndexMin_STD = IndexMin_STD + 9;
                                    IndexPrcp_MeanT = IndexPrcp_MeanT + 9;
                                    //IndexPrcp_MaxT = IndexPrcp_MaxT + 12;
                                    IndexPrcp_Var = IndexPrcp_Var + 9;
                                    IndexPrcp_STD = IndexPrcp_STD + 9;

                                }

                                tempEco = 1;
                                currentTimeS = currentTimeS + 1;
                                IndexMax_MeanT = 0;
                                //IndexMax_MaxT = 1;
                                IndexMax_Var = 1;
                                IndexMax_STD = 2;
                                IndexMin_MeanT = 3;
                                //IndexMin_MaxT = 5;
                                IndexMin_Var = 4;
                                IndexMin_STD = 5;
                                IndexPrcp_MeanT = 6;
                                //IndexPrcp_MaxT = 9;
                                IndexPrcp_Var = 7;
                                IndexPrcp_STD = 8;
                                currentMonth = 1;
                                AverageMax = 0;
                                //AverageMaxSTD = 0;
                                AverageMin = 0;
                                //AverageMinSTD = 0;
                                AveragePrecp = 0;
                                //AveragePrecSTD = 0;

                                AverageSTDT = 0;
                                StdDevPpt = 0;
                            }


                            //    for (int i = 1; i <= numberOfAllEcorigions; i++)
                            //    {

                            //        foreach (KeyValuePair<string, double[]> row in century_climate_Dic)
                            //        {

                            //            //file.WriteLine("eco" + i.ToString() + "\t" + row.Key.Remove(10) + "\t" + Math.Round(row.Value[AverageMaxT], 2) +  "\t" + Math.Round(row.Value[AverageMinT], 2) +  "\t" + Math.Round(row.Value[AveragePrec], 2)  + "\n");
                            //            //file.WriteLine("eco" + i.ToString() + "\t" + row.Key.Remove(10) + "\t" + Math.Round(row.Value[AverageMaxT], 2) + "\t" + Math.Round(row.Value[AverageMaxSTD], 2) + "\t" + Math.Round(row.Value[AverageMinT], 2) + "\t" + Math.Round(row.Value[AverageMinSTD], 2) + "\t" + Math.Round(row.Value[AveragePrec], 2) + "\t" + Math.Round(row.Value[AveragePrecSTD], 2) + "\n");

                            //                if (currentYear == row.Key.Substring(0, 4).ToString())
                            //                {

                            //                    if (currentMonth == Convert.ToInt16(row.Key.Substring(5, 2)))
                            //                    {

                            //                        //(row.Value[IndexMax_MaxT] + row.Value[IndexMax_MeanT])/2
                            //                        //AverageMin += (row.Value[IndexMin_MaxT] + row.Value[IndexMin_MeanT]) / 2;
                            //                        //AverageMax += (row.Value[IndexMax_MaxT] + row.Value[IndexMax_MeanT]) / 2;
                            //                        //AveragePrecp += (row.Value[IndexPrcp_MaxT] + row.Value[IndexPrcp_MeanT]) / 2;
                            //                        //AverageSTDT += (row.Value[IndexMax_Var] + row.Value[IndexMin_Var]) / 2;
                            //                        //AverageMaxSTD += Math.Round(Convert.ToDouble(row.Value[2]), 2);
                            //                        AverageMin += Math.Round(row.Value[IndexMin_MeanT], 2);
                            //                        AverageMax += Math.Round(row.Value[IndexMax_MeanT], 2);
                            //                        AveragePrecp += Math.Round(row.Value[IndexPrcp_MeanT], 2);
                            //                        AverageSTDT += Math.Round((row.Value[IndexMax_Var] + row.Value[IndexMin_Var]) / 2, 2);
                            //                        StdDevPpt += Convert.ToDouble(row.Value[IndexPrcp_STD]);

                            //                        //AverageMinSTD += Math.Round(Convert.ToDouble(row.Value[4]), 2);
                            //                        //AveragePrecp += Math.Round(row.Value[AveragePrec], 2);
                            //                        //AveragePrecSTD += Math.Round(Convert.ToDouble(row.Value[6]), 2);

                            //                        //Calculating STD of Tempeture
                            //                        //tempSum[numberOfDays] = (row.Value[AverageMaxT] + row.Value[AverageMinT]) / 2;
                            //                        //stdTemp = 0;
                            //                        //stdPrp = 0;


                            //                        //Calculating STD of Prp
                            //                        //tempPrp[numberOfDays] = row.Value[AveragePrec];

                            //                        numberOfDays++;

                            //                    }


                            //                    else
                            //                    {
                            //                        //for (int j = 0; j < numberOfDays; j++)
                            //                        //{
                            //                        //    sums += Math.Pow((tempSum[j] - (((AverageMax / numberOfDays) + (AverageMin / numberOfDays)) / 2)), 2);
                            //                        //    prpSums += Math.Pow(tempPrp[j] - (AveragePrec / numberOfDays), 2);
                            //                        //}

                            //                        //stdTemp = Math.Sqrt(sums / (numberOfDays - 1));
                            //                        //stdPrp = Math.Sqrt(prpSums / (numberOfDays - 1));
                            //                        file.WriteLine("eco" + i.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt, 2) + "\t" + "0.0" + "\n");
                            //                        //file.WriteLine("eco1" + "\t" + currentYear + "\t" + currentMonth + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(AverageMaxSTD / numberOfDays, 2) + "\t" + Math.Round(AverageMinT / numberOfDays, 2) + "\t" + Math.Round(AverageMinSTD / numberOfDays, 2) + "\t" + Math.Round(AveragePrec / numberOfDays, 2) + "\t" + Math.Round(AveragePrecSTD / numberOfDays, 2) + "\n");
                            //                        //tempMonth = currentMonth;
                            //                        currentMonth = Convert.ToInt16(row.Key.Substring(5, 2));
                            //                        //if (tempMonth != currentMonth)

                            //                        AverageMax = 0;
                            //                        //AverageMaxSTD = 0;
                            //                        AverageMin = 0;
                            //                        //AverageMinSTD = 0;
                            //                        AveragePrecp = 0;
                            //                        //AveragePrecSTD = 0;
                            //                        AverageSTDT = 0;
                            //                        StdDevPpt = 0;

                            //                        numberOfDays = 0;
                            //                        AverageMin += Math.Round(row.Value[IndexMin_MeanT], 2);
                            //                        AverageMax += Math.Round(row.Value[IndexMax_MeanT], 2);
                            //                        AveragePrecp += Math.Round(row.Value[IndexPrcp_MeanT], 2);
                            //                        AverageSTDT += Math.Round((row.Value[IndexMax_Var] + row.Value[IndexMin_Var]) / 2, 2);
                            //                        StdDevPpt += Convert.ToDouble(row.Value[IndexPrcp_STD]);
                            //                        //sums = 0;
                            //                        //stdTemp = 0;
                            //                        //prpSums = 0;
                            //                        //stdPrp = 0;
                            //                        numberOfDays++;
                            //                    }

                            //                }
                            //                else
                            //                {
                            //                    //If ecorigion has been changed
                            //                    if (tempEco != i && currentMonth == 12)
                            //                    {
                            //                        file.WriteLine("eco" + tempEco.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt, 2) + "\t" + "0.0" + "\n");
                            //                        currentTimeS = 0;
                            //                    }

                            //                    else if (currentMonth == 12)
                            //                    {
                            //                        file.WriteLine("eco" + i.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt, 2) + "\t" + "0.0" + "\n");
                            //                        currentTimeS = currentTimeS + 1;
                            //                    }
                            //                    else if (tempEco != i)
                            //                        currentTimeS = 0;
                            //                    //file.WriteLine("eco1" + "\t" + currentYear + "\t" + currentMonth + "\t" + Math.Round(AverageMaxT / numberOfDays, 2) + "\t" + Math.Round(AverageMaxSTD / numberOfDays, 2) + "\t" + Math.Round(AverageMinT / numberOfDays, 2) + "\t" + Math.Round(AverageMinSTD / numberOfDays, 2) + "\t" + Math.Round(AveragePrec / numberOfDays, 2) + "\t" + Math.Round(AveragePrecSTD / numberOfDays, 2) + "\n");

                            //                    currentYear = row.Key.Substring(0, 4).ToString();
                            //                    //currentTimeS = currentTimeS + 1;
                            //                    tempEco = i;
                            //                    currentMonth = 1;
                            //                    AverageMax = 0;
                            //                    //AverageMaxSTD = 0;
                            //                    AverageMin = 0;
                            //                    //AverageMinSTD = 0;
                            //                    AveragePrecp = 0;
                            //                    //AveragePrecSTD = 0;

                            //                    AverageSTDT = 0;
                            //                    StdDevPpt = 0;

                            //                    numberOfDays = 0;
                            //                    AverageMin += Math.Round(row.Value[IndexMin_MeanT], 2);
                            //                    AverageMax += Math.Round(row.Value[IndexMax_MeanT], 2);
                            //                    AveragePrecp += Math.Round(row.Value[IndexPrcp_MeanT], 2);
                            //                    AverageSTDT += Math.Round((row.Value[IndexMax_Var] + row.Value[IndexMin_Var]) / 2, 2);
                            //                    StdDevPpt += Convert.ToDouble(row.Value[IndexPrcp_STD]);
                            //                    //sums = 0;
                            //                    //stdTemp = 0;
                            //                    //prpSums = 0;
                            //                    //stdPrp = 0;
                            //                    numberOfDays++;
                            //                }


                            //        }

                            //        IndexMax_MeanT = IndexMax_MeanT + 9;
                            //        //IndexMax_MaxT = IndexMax_MaxT + 12;
                            //        IndexMax_Var = IndexMax_Var + 9;
                            //        IndexMax_STD = IndexMax_STD + 9;
                            //        IndexMin_MeanT = IndexMin_MeanT + 9;
                            //        //IndexMin_MaxT = IndexMin_MaxT + 12;
                            //        IndexMin_Var = IndexMin_Var + 9;
                            //        IndexMin_STD = IndexMin_STD + 9;
                            //        IndexPrcp_MeanT = IndexPrcp_MeanT + 9;
                            //        //IndexPrcp_MaxT = IndexPrcp_MaxT + 12;
                            //        IndexPrcp_Var = IndexPrcp_Var + 9;
                            //        IndexPrcp_STD = IndexPrcp_STD + 9;
                            //    }
                            //    file.WriteLine("eco" + numberOfAllEcorigions.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt, 2) + "\t" + "0.0" + "\n");



                        }


                        //If file contains more than one scenario then these setting will be needed
                        //century_climate_Dic.Clear();
                        //emptytxt = true;
                        //tempScenarioName = CurrentScenarioName;

                    }
                }





            }

            #endregion

            return centuryPath;

        }
Example #6
0
 public IEnumerable<KeyValuePair<string, string>> MakeKeyValues()
 {
     var dictionary = new Dictionary<string, string> {{"key1", "value1"}, {"key2", "value2"}};
     return dictionary.AsEnumerable().OrderBy(p => p.Key);
 }
Example #7
0
        static void Main(string[] args)
        {

            Console.WriteLine("===========================================");
            Console.WriteLine("Concat");
            Console.WriteLine("===========================================");
            String[] First = { "One", "Two", "Three" };
            String[] Second = { "Four", "Five", "Six" };
            var ConCatQ = First.Concat<String>(Second);

            foreach (String val in ConCatQ)
            {
                Console.WriteLine(val);
            }

            Console.WriteLine("===========================================");
            Console.WriteLine("Concat");
            Console.WriteLine("===========================================");

            List<String> valList = new List<string>() { "1", "2", "3" , "4","5","6"};

            // take a list of strings containing numbers... 
            //   convert those to ints and apply a where clause to it to only get values greater than 3..
            //   then reconvert those values and cast them to the enum type...
            //   and finally (during output) call ToString to get them back to string for display.
            // the REAL tricking going on here is this little piece of magic:  NumToWord.One.ToString()
            // SNEAKY.
            var ConvertQ =
                (valList.AsEnumerable<String>()).Where(ThisElement => Convert.ToInt32(ThisElement) > 3).Select(ThisElement => (NumToWord)Convert.ToInt32(ThisElement));

            Console.WriteLine(" ");
            foreach (var ThisElement in ConvertQ)
            {
                Console.WriteLine(ThisElement.ToString());
            }

            Console.WriteLine("===========================================");
            Console.WriteLine("OfType");
            Console.WriteLine("===========================================");
            // Define a test object.    
            Dictionary<String, Object> TestData =       new Dictionary<string, object>();    
            // Fill the test object with data.    
            TestData.Add("One", 1);
            TestData.Add("Two", "Two");    
            TestData.Add("Three", 3);    
            TestData.Add("Four", "Four");    
            TestData.Add("Five", 5);    
            TestData.Add("Six", "Six");    
            // Create the query.    
            var ThisQuery = TestData.Values.OfType<String>();    
            // Display the output.    
            foreach (String ThisElement in ThisQuery)       
            {
                Console.WriteLine(ThisElement);
            }
            //note that you can't reuse a query here.. the typing
            // is retained on the var 'ThisQuery' after it is assigned from the above
            var ThisQuery2 = TestData.Values.OfType<int>();
            // Display the output.    
            foreach (int ThisElement in ThisQuery2)
            {
                Console.WriteLine(ThisElement);
            }

            Dictionary<int,string> myDict = new Dictionary<int,string>() {{1,"ONE"},{2,"TWO"},{3,"THREE"}};

            
            var Q2 = (myDict.AsEnumerable<KeyValuePair<int,string>>()).Where(ThisElement => ThisElement.Key > 1);
            foreach(KeyValuePair<int,string> ThisElement in Q2)
            {
                Console.WriteLine("found  key<{0}> value<{1}>",ThisElement.Key,ThisElement.Value);
            }

            
        }
Example #8
0
        private IEnumerable<SelectListItem> PopulateIssueTypes(CreateIssue model = null)
        {
            Dictionary<int, string> issues = new Dictionary<int, string> { { 0, "Story" }, { 1, "Task" }, { 2, "Test Task" }, { 3, "Bug" } };

            return issues.AsEnumerable().ToSelectListItems(value => value.Key.ToString(), text => text.Value, selected => model != null && model.IssueType == selected.Key);
        }
        public static void Convert_USGS_to_ClimateData(TemporalGranularity sourceTemporalGranularity, string climateFile, string climateFileFormat)
        {

            ClimateFileFormatProvider formatProvider = new ClimateFileFormatProvider(climateFileFormat);
            maxTriggerWord = formatProvider.MaxTempTriggerWord;
            minTriggerWord = formatProvider.MinTempTriggerWord;
            prcpTriggerWord = formatProvider.PrecipTriggerWord;
            rhTriggerWord = formatProvider.RhTriggerWord;
            windSpeedTriggerWord = formatProvider.WindSpeedTriggerWord;
            bool checkRHWindSpeed = false;


            string unmatched_TriggerWords;

            if (checkRHWindSpeed == false)
                unmatched_TriggerWords = maxTriggerWord + ", " + minTriggerWord + ", " + prcpTriggerWord;// +", " + rhTriggerWord + ", " + windSpeedTriggerWord;
            else
                unmatched_TriggerWords = maxTriggerWord + ", " + minTriggerWord + ", " + prcpTriggerWord + ", " + rhTriggerWord + ", " + windSpeedTriggerWord;

            int triggerWordsCheckingTime = 0;
            string path = climateFile;
            StreamReader sreader;
            string centuryPath = "";
            // monthly and daily climates should be filled before in order to chack weather input climatefile can be processed as daily or monthly
            //List<string> montlyClimates;
            //List<string> DailyClimate;

            climateFileFormat = climateFileFormat.ToLower();
            Climate.ModelCore.UI.WriteLine("   Converting raw data from text file: {0}, Format={1}, Temporal={2}.", climateFile, climateFileFormat, sourceTemporalGranularity);


            #region IPCC3 Input file 
            if (climateFileFormat == "ipcc3_daily" || climateFileFormat == "ipcc3_monthly") 
            {
                exportToTxtFormatFile = false;
                sreader = new StreamReader(path);
                string line;
                string[] fields;
                DataTable _dataTableDataByTime = new DataTable();
                line = sreader.ReadLine();
                fields = line.Split(',');
                line = sreader.ReadLine();
                fields = line.Split(',');

                string CurrentScenarioType = "";
                climate_Dic = new Dictionary<string, double[]>();


                string key = "";
                currentYear = "";
                int currentTimeS = 0;
                currentMonth = 1;
                int tempEco = 1;
                double AverageMax = 0;
                double AverageMin = 0;
                double SumPrecp = 0;

                double AverageSTDT = 0;
                double SumVarPpt = 0;
                int numberOfDays = 0;
                double[] tempSum = new double[31];
                double[] tempPrp = new double[31];
                //bool emptytxt = false;
                int updatedIndex = 0;

                //int ecoIndex = -1;
                climateFileActiveEcoregions = new SortedList<int, Core.IEcoregion>();

                foreach (string field in fields)
                {

                    if (field != "")
                    {
                        //if (Convert.ToInt16(field) > ecoIndex)
                        //{
                        //    ecoIndex = Convert.ToInt16(field);
                            IEcoregion eco = Climate.ModelCore.Ecoregions[field]; //.Where(P => P.Index == ecoIndex).FirstOrDefault();
                            //numberOfAllEcoregions = Convert.ToInt16(field);
                            if (eco != null && eco.Active)
                            {
                                if (!climateFileActiveEcoregions.ContainsKey(eco.Index))
                                    climateFileActiveEcoregions.Add(eco.Index, eco);
                            }
                            else
                            {
                                //Climate.ModelCore.UI.WriteLine("ClimateDataConvertor: Number of active ecoregions does not match the input file. The climate data for ecoregion with index {0} was ignored.", numberOfAllEcoregions);
                                Climate.ModelCore.UI.WriteLine("Error in ClimateDataConvertor: Converting {0} file into standard format; Number of active ecoregions does not match the input file.", climateFile);
                                throw new ApplicationException("Error in ClimateDataConvertor: Converting" + climateFile + "file into standard format; Number of active ecoregions does not match the input file.");
                            }

                        }
                }


                //12 beacuse for each ecoriogn we need Max_MinT,Max_MaxT,Max_Var Max_Std, Min_MinT,Min_MaxT,Min_Var Min_Std, Prcp_MinT,Prcp_MaxT,Prcp_Var Prcp_Std
                int dicSize = climateFileActiveEcoregions.Count * 15; 
                sreader.Close();
                StreamReader reader = new StreamReader(path);

                while (reader.Peek() >= 0)
                {
                    line = reader.ReadLine();
                    fields = line.Split(',');
                    foreach (string field in fields)
                    {
                        if (field.Contains("#"))
                        {
                            triggerWordsCheckingTime++;
                            if (triggerWordsCheckingTime > 1)
                                if (unmatched_TriggerWords == maxTriggerWord + ", " + minTriggerWord + ", " + prcpTriggerWord + ", " + rhTriggerWord + ", " + windSpeedTriggerWord && checkRHWindSpeed == true)
                                {
                                    Climate.ModelCore.UI.WriteLine("Error in ClimateDataConvertor: Converting {0} file into standard format; The following trigger words did not match the triggerwords in the given file: {1}." + "selected format: \"{2}\"", climateFile, unmatched_TriggerWords, formatProvider.SelectedFormat);
                                    throw new ApplicationException("Error in ClimateDataConvertor: Converting " + climateFile + " file into standard format; The following triggerWords did not match the triggerwords in the given file: " + unmatched_TriggerWords + "." + "selected format: \"" + formatProvider.SelectedFormat + "\"");
                                }
                                else if (unmatched_TriggerWords == maxTriggerWord + ", " + minTriggerWord + ", " + prcpTriggerWord && checkRHWindSpeed == false)
                                {
                                    Climate.ModelCore.UI.WriteLine("Error in ClimateDataConvertor: Converting {0} file into standard format; The following trigger words did not match the triggerwords in the given file: {1}." + "selected format: \"{2}\"", climateFile, unmatched_TriggerWords, formatProvider.SelectedFormat);
                                    throw new ApplicationException("Error in ClimateDataConvertor: Converting " + climateFile + " file into standard format; The following triggerWords did not match the triggerwords in the given file: " + unmatched_TriggerWords + "." + "selected format: \"" + formatProvider.SelectedFormat + "\"");
                                }

                            //tempScenarioName = CurrentScenarioName;
                            //if (field.ToLower().Contains(maxTriggerWord) || field.ToLower().Contains(minTriggerWord))
                            //{
                            //CurrentScenarioName = field.Substring(1, field.LastIndexOf("t") - 2);
                            if (field.ToLower().Contains(maxTriggerWord.ToLower()))
                            {
                                CurrentScenarioType = maxTriggerWord;
                                unmatched_TriggerWords = unmatched_TriggerWords.Replace(maxTriggerWord, "");
                            }
                            else if (field.ToLower().Contains(minTriggerWord.ToLower()))
                            {
                                CurrentScenarioType = minTriggerWord;
                                unmatched_TriggerWords = unmatched_TriggerWords.Replace(", " + minTriggerWord, "");
                            }
                            else if (field.ToLower().Contains(prcpTriggerWord.ToLower()))
                            {
                                //CurrentScenarioName = field.Substring(1, field.LastIndexOf("p") - 2);
                                CurrentScenarioType = prcpTriggerWord;
                                unmatched_TriggerWords = unmatched_TriggerWords.Replace(", " + prcpTriggerWord, "");
                            }
                            else if (field.ToLower().Contains(rhTriggerWord.ToLower()))
                            {
                                CurrentScenarioType = rhTriggerWord;
                                unmatched_TriggerWords = unmatched_TriggerWords.Replace(", " + rhTriggerWord, "");
                            }
                            else if (field.ToLower().Contains(windSpeedTriggerWord.ToLower()))
                            {
                                CurrentScenarioType = windSpeedTriggerWord;
                                unmatched_TriggerWords = unmatched_TriggerWords.Replace(", " + windSpeedTriggerWord, "");
                            }


                        }



                    }


                    if (fields[0] == string.Empty && !fields[0].Contains("#"))
                    {
                        line = reader.ReadLine();
                        fields = line.Split(',');

                        if (fields[0].Contains("TIME"))
                        {
                            line = reader.ReadLine();
                            fields = line.Split(',');

                            //now fill array 
                            //Get the lenght of array according to the number of ecorigions/
                            //

                        }
                    }
                    if (!fields[0].Contains("#"))
                    //if (CurrentScenarioName == tempScenarioName && !fields[0].Contains("#"))
                    {

                        key = fields[0].ToString();
                        if (CurrentScenarioType.ToLower().Contains(maxTriggerWord.ToLower()))
                        {
                            IndexMaxT_Mean = 0;
                            //IndexMax_MaxT = 1;
                            IndexMaxT_Var = 1;
                            IndexMaxT_STD = 2;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcoregions);
                            if (!climate_Dic.Keys.Contains(key))
                                climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });

                            //set index of max and maxSTD for each ecorigion
                            for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                            {
                                //currentT = fields[i+1];
                                //if (indexofSTD < 26)
                                //{

                                climate_Dic[key].SetValue(Convert.ToDouble(fields[i + 1]), IndexMaxT_Mean);
                                updatedIndex += i + climateFileActiveEcoregions.Count;
                                //climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexMax_MaxT);
                                //updatedIndex +=  numberOfAllEcoregions;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexMaxT_Var);
                                updatedIndex += climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexMaxT_STD);
                                IndexMaxT_Mean = IndexMaxT_Mean + 9;
                                //IndexMax_MaxT = IndexMax_MaxT + 12;
                                IndexMaxT_Var = IndexMaxT_Var + 9;
                                IndexMaxT_STD = IndexMaxT_STD + 9;
                                updatedIndex = 0;

                                //indexofSTD++;
                                //}

                            }
                        }
                        else if (CurrentScenarioType.ToLower().Contains(minTriggerWord.ToLower()))
                        {
                            IndexMinT_Mean = 3;
                            //IndexMin_MaxT = 5;
                            IndexMinT_Var = 4;
                            IndexMinT_STD = 5;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcoregions);

                            // climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });
                            if (!climate_Dic.Keys.Contains(key))
                                climate_Dic.Add(key, new double[dicSize]);
                            //set index of max and maxSTD for each ecorigion
                            for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                            {
                                //currentT = fields[i+1];
                                //if (indexofSTD < 26)
                                //{
                                //currentSTD = fields[indexofSTD];
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[i + 1]), IndexMinT_Mean);
                                updatedIndex += i + climateFileActiveEcoregions.Count;
                                //climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexMin_MaxT);
                                //updatedIndex += numberOfAllEcoregions;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexMinT_Var);
                                updatedIndex += climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexMinT_STD);


                                //climate_Dic[key].SetValue(Convert.ToDouble(currentSTD), IndexSTD);
                                IndexMinT_Mean = IndexMinT_Mean + 9;
                                //IndexMin_MaxT = IndexMin_MaxT + 12;
                                IndexMinT_Var = IndexMinT_Var + 9;
                                IndexMinT_STD = IndexMinT_STD + 9;
                                updatedIndex = 0;
                                //    IndexSTD = IndexSTD + 6;
                                //    indexofSTD++;
                                //}

                            }
                        }
                        else if (CurrentScenarioType.ToLower().Contains(prcpTriggerWord.ToLower()))
                        {
                            IndexPrcp_Mean = 6;
                            //IndexPrcp_MaxT = 9;
                            IndexPrcp_Var = 7;
                            IndexPrcp_STD = 8;

                            //IndexSTD = 5;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcoregions);

                            // climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });
                            if (!climate_Dic.Keys.Contains(key))
                                climate_Dic.Add(key, new double[dicSize]);
                            
                            //set index of Precipitation and STD for each ecoregion
                            for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                            {
                                //currentT = fields[i+1];
                                //if (indexofSTD < 26)
                                //{
                                //currentSTD = fields[indexofSTD];
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[i + 1]) / 10, IndexPrcp_Mean); //  /10 is for mm to cm conversion
                                updatedIndex += i + climateFileActiveEcoregions.Count;
                                //climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexPrcp_MaxT);
                                //updatedIndex += numberOfAllEcoregions;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]) / 10, IndexPrcp_Var); 
                                updatedIndex += climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]) / 10, IndexPrcp_STD); //NOTE: this might be a wrong conversion for converting IndexPrcp_STD from mm to cm because STD is calculate using root square.


                                //climate_Dic[key].SetValue(Convert.ToDouble(currentSTD), IndexSTD);
                                IndexPrcp_Mean = IndexPrcp_Mean + 9;
                                //IndexPrcp_MaxT = IndexPrcp_MaxT + 12;
                                IndexPrcp_Var = IndexPrcp_Var + 9;
                                IndexPrcp_STD = IndexPrcp_STD + 9;
                                updatedIndex = 0;
                                //IndexSTD = IndexSTD + 6;
                                //indexofSTD++;
                            }

                        }


                        //-----
                        else if (CurrentScenarioType.ToLower().Contains(rhTriggerWord.ToLower()))
                        {
                            IndexRH_Mean = 9;
                            IndexRH_Var = 10;
                            IndexRH_STD = 11;

                            //IndexSTD = 5;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcoregions);

                            // climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });
                            if (!climate_Dic.Keys.Contains(key))
                                climate_Dic.Add(key, new double[dicSize]);
                            //set index of max and maxSTD for each ecorigion
                            for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                            {

                                climate_Dic[key].SetValue(Convert.ToDouble(fields[i + 1]), IndexRH_Mean);
                                updatedIndex += i + climateFileActiveEcoregions.Count;

                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexRH_Var);
                                updatedIndex += climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexRH_STD);


                                IndexRH_Mean = IndexRH_Mean + 9;
                                IndexRH_Var = IndexRH_Var + 9;
                                IndexRH_STD = IndexRH_STD + 9;
                                updatedIndex = 0;

                            }

                        }

                        //-----
                        else if (CurrentScenarioType.ToLower().Contains(windSpeedTriggerWord.ToLower()))
                        {
                            IndexwindSpeed_Mean = 12;
                            IndexwindSpeed_Var = 13;
                            IndexwindSpeed_STD = 14;

                            //IndexSTD = 5;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcoregions);

                            // climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });
                            if (!climate_Dic.Keys.Contains(key))
                                climate_Dic.Add(key, new double[dicSize]);
                            //set index of max and maxSTD for each ecorigion
                            for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                            {

                                climate_Dic[key].SetValue(Convert.ToDouble(fields[i + 1]), IndexwindSpeed_Mean);
                                updatedIndex += i + climateFileActiveEcoregions.Count;

                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexwindSpeed_Var);
                                updatedIndex += climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexwindSpeed_STD);


                                IndexwindSpeed_Mean = IndexwindSpeed_Mean + 9;
                                IndexwindSpeed_Var = IndexwindSpeed_Var + 9;
                                IndexwindSpeed_STD = IndexwindSpeed_STD + 9;
                                updatedIndex = 0;

                            }

                        }
                        //-----


                    }  //end while


                    //if (CurrentScenarioName != tempScenarioName || reader.EndOfStream)
                    if (reader.EndOfStream)
                    {
                        //Print file for one scenario then clear dictionary to use for another scenario

                        //Daily period
                        centuryPath = "Century_Climate_Inputs_Monthly.txt";
                        setIndexed();
                        //using (System.IO.StreamWriter file = new System.IO.StreamWriter(centuryPath, emptytxt))
                        //{
                        //    if (exportToTxtFormatFile)
                        //    {
                        //        file.WriteLine("LandisData" + " \"Climate Data\" \n");
                        //        file.WriteLine("ClimateTable \n");
                        //        //file.WriteLine(tempScenarioName + "\n");
                        //        file.WriteLine(">>Eco" + "\t\t" + "Time" + "\t" + "Month" + "\t" + "AvgMinT" + "\t" + "AvgMaxT" + "\t" + "StdDevT" + "\t" + "AvgPpt" + "\t" + "StdDevPpt" + "\t" + "PAR" + "\t" + "VarT" + "\t" + "VarPpt" + "\n");
                        //        file.WriteLine(">>Name" + "\t\t" + "Step" + "\t" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(k)" + "\t" + "(cm)" + "\t" + "Ppt" + "\t" + "µmol m-2 s-1" + "\t" + "(cm)" + "\t" + "(cm)" + "\n");

                        //    }
                        //    else
                        //    {
                        //        file.WriteLine("This file is not generated when converting a Daily Climate to Monthly.");
                        //        file.WriteLine("To enable the generation of this file:");
                        //        file.WriteLine("set 'exportToTxtFormatFile = true;' in 'if (sourceTemporalGranularity == TemporalGranularity.Daily) \n { \n \t exportToTxtFormatFile = false; ' in ClimateDataConvertor class.");
                        //        file.WriteLine("Caution: Note that the right AnnualCliamte_Monthly will not be generated if this generated Monthly-climate txt file is used as a climate input file.");
                        //    }
                            currentYear = climate_Dic.First().Key.Substring(0, 4).ToString();
                            //starting timestep
                            currentTimeS = 0;
                            currentMonth = Convert.ToInt16(climate_Dic.First().Key.Substring(5, 2).ToString());
                            tempEco = 1;


                            lastYear = climate_Dic.AsEnumerable().Select(ax => Convert.ToInt32(ax.Key.Substring(0, 4).ToString())).Distinct().ToList().Max();
                            firstYear = climate_Dic.AsEnumerable().Select(ai => Convert.ToInt32(ai.Key.Substring(0, 4).ToString())).Distinct().ToList().Min();
                            if ((double)climate_Dic.Count / 12 > (double)lastYear - firstYear)
                                lastYear = lastYear - 1;

                            for (int j = firstYear; j <= lastYear; j++)
                            {
                                for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                                {
                                    currentYear = j.ToString();

                                    foreach (KeyValuePair<string, double[]> row in climate_Dic)
                                    {
                                        if (currentYear == row.Key.Substring(0, 4).ToString())
                                        {

                                            if (currentMonth == Convert.ToInt16(row.Key.Substring(5, 2)))
                                            {

                                                //(row.Value[IndexMax_MaxT] + row.Value[IndexMaxT_Mean])/2
                                                //AverageMin += (row.Value[IndexMin_MaxT] + row.Value[IndexMinT_Mean]) / 2;
                                                //AverageMax += (row.Value[IndexMax_MaxT] + row.Value[IndexMaxT_Mean]) / 2;
                                                //AveragePrecp += (row.Value[IndexPrcp_MaxT] + row.Value[IndexPrcp_Mean]) / 2;
                                                //AverageSTDT += (row.Value[IndexMaxT_Var] + row.Value[IndexMinT_Var]) / 2;
                                                //AverageMaxSTD += Math.Round(Convert.ToDouble(row.Value[2]), 2);
                                                AverageMin += Math.Round(row.Value[IndexMinT_Mean], 2);
                                                AverageMax += Math.Round(row.Value[IndexMaxT_Mean], 2);
                                                SumPrecp += (Math.Round(row.Value[IndexPrcp_Mean], 2));
                                                AverageSTDT += Math.Round((row.Value[IndexMaxT_Var] + row.Value[IndexMinT_Var]) / 2, 2);
                                                SumVarPpt += Convert.ToDouble(row.Value[IndexPrcp_Var]);


                                                numberOfDays++;

                                            }



                                            else
                                            {
                                                //if (exportToTxtFormatFile)
                                                //    file.WriteLine(climateFileActiveEcoregions.ElementAt(i).Value.Name + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(SumPrecp, 2) + "\t" + Math.Round(Math.Sqrt(SumVarPpt), 2) + "\t" + "0.0" + "\t" + Math.Round(AverageSTDT / numberOfDays, 2) + "\t" + Math.Round(SumVarPpt, 2) + "\n");
                                                currentMonth = Convert.ToInt16(row.Key.Substring(5, 2));
                                                //if (tempMonth != currentMonth)
                                                alldays += numberOfDays;
                                                AverageMax = 0;
                                                AverageMin = 0;
                                                SumPrecp = 0;
                                                AverageSTDT = 0;
                                                SumVarPpt = 0;

                                                numberOfDays = 0;
                                                AverageMin += Math.Round(row.Value[IndexMinT_Mean], 2);
                                                AverageMax += Math.Round(row.Value[IndexMaxT_Mean], 2);
                                                SumPrecp += (Math.Round(row.Value[IndexPrcp_Mean], 2));
                                                AverageSTDT += Math.Round((row.Value[IndexMaxT_Var] + row.Value[IndexMinT_Var]) / 2, 2);
                                                SumVarPpt += Convert.ToDouble(row.Value[IndexPrcp_Var]);

                                                numberOfDays++;
                                            }


                                        }
                                        else
                                        {
                                            if (currentMonth == 12)
                                            {
                                                alldays += numberOfDays;
                                                if (!yearsdays.Keys.Contains(j))
                                                {
                                                    yearsdays.Add(j, alldays);
                                                    alldays = 0;
                                                }

                                            }
                                            

                                            alldays = 0;
                                            tempEco = i;
                                            currentMonth = 1;
                                            AverageMax = 0;
                                            //AverageMaxSTD = 0;
                                            AverageMin = 0;
                                            //AverageMinSTD = 0;
                                            SumPrecp = 0;
                                            //AveragePrecSTD = 0;

                                            AverageSTDT = 0;
                                            SumVarPpt = 0;

                                            numberOfDays = 0;
                                            AverageMin += Math.Round(row.Value[IndexMinT_Mean], 2);
                                            AverageMax += Math.Round(row.Value[IndexMaxT_Mean], 2);
                                            SumPrecp += (Math.Round(row.Value[IndexPrcp_Mean], 2));
                                            AverageSTDT += Math.Round((row.Value[IndexMaxT_Var] + row.Value[IndexMinT_Var]) / 2, 2);
                                            SumVarPpt += Convert.ToDouble(row.Value[IndexPrcp_Var]);
                                            //sums = 0;
                                            //stdTemp = 0;
                                            //prpSums = 0;
                                            //stdPrp = 0;
                                            numberOfDays++;
                                        }


                                    }
                                    tempEco = i;

                                    currentMonth = 1;
                                    AverageMax = 0;
                                    //AverageMaxSTD = 0;
                                    AverageMin = 0;
                                    //AverageMinSTD = 0;
                                    SumPrecp = 0;
                                    //AveragePrecSTD = 0;

                                    AverageSTDT = 0;
                                    SumVarPpt = 0;

                                    IndexMaxT_Mean = IndexMaxT_Mean + 9;
                                    //IndexMax_MaxT = IndexMax_MaxT + 12;
                                    IndexMaxT_Var = IndexMaxT_Var + 9;
                                    IndexMaxT_STD = IndexMaxT_STD + 9;
                                    IndexMinT_Mean = IndexMinT_Mean + 9;
                                    //IndexMin_MaxT = IndexMin_MaxT + 12;
                                    IndexMinT_Var = IndexMinT_Var + 9;
                                    IndexMinT_STD = IndexMinT_STD + 9;
                                    IndexPrcp_Mean = IndexPrcp_Mean + 9;
                                    //IndexPrcp_MaxT = IndexPrcp_MaxT + 12;
                                    IndexPrcp_Var = IndexPrcp_Var + 9;
                                    IndexPrcp_STD = IndexPrcp_STD + 9;


                                    IndexRH_Mean = IndexRH_Mean + 9;
                                    IndexRH_Var = IndexRH_Var + 9;
                                    IndexRH_STD = IndexRH_STD + 9;

                                    IndexwindSpeed_Mean = IndexwindSpeed_Mean + 9;
                                    IndexwindSpeed_Var = IndexwindSpeed_Var + 9;
                                    IndexwindSpeed_STD = IndexwindSpeed_STD + 9;

                                }
                                //file.WriteLine("eco" + numberOfAllEcoregions.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(StdDevPpt), 2) + "\t" + "0.0" + "\n");

                                tempEco = 1;
                                currentTimeS = currentTimeS + 1;
                                IndexMaxT_Mean = 0;
                                //IndexMax_MaxT = 1;
                                IndexMaxT_Var = 1;
                                IndexMaxT_STD = 2;
                                IndexMinT_Mean = 3;
                                //IndexMin_MaxT = 5;
                                IndexMinT_Var = 4;
                                IndexMinT_STD = 5;
                                IndexPrcp_Mean = 6;
                                //IndexPrcp_MaxT = 9;
                                IndexPrcp_Var = 7;
                                IndexPrcp_STD = 8;

                                IndexRH_Mean = 9;
                                IndexRH_Var = 10;
                                IndexRH_STD = 11;

                                IndexwindSpeed_Mean = 12;
                                IndexwindSpeed_Var = 13;
                                IndexwindSpeed_STD = 14;

                                currentMonth = 1;
                                AverageMax = 0;
                                //AverageMaxSTD = 0;
                                AverageMin = 0;
                                //AverageMinSTD = 0;
                                SumPrecp = 0;
                                //AveragePrecSTD = 0;

                                AverageSTDT = 0;
                                SumVarPpt = 0;

                            }

                        }

                        //If file contains more than one scenario then these setting will be needed
                        //climate_Dic.Clear();
                        //emptytxt = true;
                        //tempScenarioName = CurrentScenarioName;

                    //}
                }
                //if (unmatched_TriggerWords != "")
                //{
                //    Climate.ModelCore.UI.WriteLine("Error in ClimateDataConvertor: Converting {0} file into standard format.", climateFile);
                //    Climate.ModelCore.UI.WriteLine("The following triggerWords did not match the triggerwords in the given file: {1}.  Selected format: {2}", unmatched_TriggerWords, formatProvider.SelectedFormat);
                //    throw new ApplicationException("Error in ClimateDataConvertor: See Log File."); //: Converting " + climateFile + " file into standard format; The following triggerWords did not match the triggerwords in the given file: " + unmatched_TriggerWords + "." + "selected format: \"" + formatProvider.SelectedFormat + "\"");
                //}

            }
            #endregion

            #region IPCC5 Input file
            else if (climateFileFormat == "ipcc5_monthly" || climateFileFormat == "ipcc5_daily") 
            {
                exportToTxtFormatFile = false;
                sreader = new StreamReader(path);
                string line;
                string[] fields;
                DataTable _dataTableDataByTime = new DataTable();
                line = sreader.ReadLine();
                fields = line.Split(',');
                line = sreader.ReadLine();
                fields = line.Split(',');

                string CurrentScenarioType = "";
                climate_Dic = new Dictionary<string, double[]>();


                string key = "";
                currentYear = "";
                int currentTimeS = 0;
                currentMonth = 1;
                int tempEco = 1;
                double AverageMax = 0;
                double AverageMin = 0;
                double SumPrecp = 0;

                double AverageSTDT = 0;
                double SumVarPpt = 0;
                int numberOfDays = 0;
                double[] tempSum = new double[31];
                double[] tempPrp = new double[31];
                //bool emptytxt = false;
                int updatedIndex = 0;

                //int ecoIndex = -1;
                climateFileActiveEcoregions = new SortedList<int, Core.IEcoregion>();

                foreach (string field in fields)
                {

                    if (field != "")
                        //if (Convert.ToInt16(field) > ecoIndex)
                        {
                            //ecoIndex = Convert.ToInt16(field);
                            IEcoregion eco = Climate.ModelCore.Ecoregions[field]; //.Where(P => P.Index == ecoIndex).FirstOrDefault();
                            if (eco != null && eco.Active)
                            {
                                if (!climateFileActiveEcoregions.ContainsKey(eco.Index))
                                    climateFileActiveEcoregions.Add(eco.Index, eco);
                            }
                            else
                            {
                                //Climate.ModelCore.UI.WriteLine("ClimateDataConvertor: Number of active ecoregions does not match the input file. The climate data for ecoregion with index {0} was ignored.", numberOfAllEcoregions);
                                Climate.ModelCore.UI.WriteLine("Error in ClimateDataConvertor: Converting {0} file into standard format; Number of active ecoregions does not match the input file.", climateFile);
                                throw new ApplicationException("Error in ClimateDataConvertor: Converting" + climateFile + "file into standard format; Number of active ecoregions does not match the input file.");
                            }

                        }
                }


                //12 beacuse for each ecoriogn we need Max_MinT,Max_MaxT,Max_Var Max_Std, Min_MinT,Min_MaxT,Min_Var Min_Std, Prcp_MinT,Prcp_MaxT,Prcp_Var Prcp_Std
                int dicSize = climateFileActiveEcoregions.Count * 15;
                sreader.Close();
                StreamReader reader = new StreamReader(path);

                while (reader.Peek() >= 0)
                {
                    line = reader.ReadLine();
                    fields = line.Split(',');
                    foreach (string field in fields)
                    {
                        if (field.Contains("#"))
                        {
                            triggerWordsCheckingTime++;
                            if (triggerWordsCheckingTime > 1)
                                if (unmatched_TriggerWords == maxTriggerWord + ", " + minTriggerWord + ", " + prcpTriggerWord + ", " + rhTriggerWord + ", " + windSpeedTriggerWord && checkRHWindSpeed == true)
                                {
                                    Climate.ModelCore.UI.WriteLine("Error in ClimateDataConvertor: Converting {0} file into standard format; The following triggerWords did not match the triggerwords in the given file: {1}." + "selected format: \"{2}\"", climateFile, unmatched_TriggerWords, formatProvider.SelectedFormat);
                                    throw new ApplicationException("Error in ClimateDataConvertor: Converting " + climateFile + " file into standard format; The following triggerWords did not match the triggerwords in the given file: " + unmatched_TriggerWords + "." + "selected format: \"" + formatProvider.SelectedFormat + "\"");
                                }
                                else if (unmatched_TriggerWords == maxTriggerWord + ", " + minTriggerWord + ", " + prcpTriggerWord && checkRHWindSpeed == false)
                                {
                                    Climate.ModelCore.UI.WriteLine("Error in ClimateDataConvertor: Converting {0} file into standard format; The following triggerWords did not match the triggerwords in the given file: {1}." + "selected format: \"{2}\"", climateFile, unmatched_TriggerWords, formatProvider.SelectedFormat);
                                    throw new ApplicationException("Error in ClimateDataConvertor: Converting " + climateFile + " file into standard format; The following triggerWords did not match the triggerwords in the given file: " + unmatched_TriggerWords + "." + "selected format: \"" + formatProvider.SelectedFormat + "\"");
                                }

                            //tempScenarioName = CurrentScenarioName;
                            //if (field.ToLower().Contains(maxTriggerWord) || field.ToLower().Contains(minTriggerWord))
                            //{
                            //CurrentScenarioName = field.Substring(1, field.LastIndexOf("t") - 2);
                            if (field.ToLower().Contains(maxTriggerWord.ToLower()))
                            {
                                CurrentScenarioType = maxTriggerWord;
                                unmatched_TriggerWords = unmatched_TriggerWords.Replace(maxTriggerWord, "");
                            }
                            else if (field.ToLower().Contains(minTriggerWord.ToLower()))
                            {
                                CurrentScenarioType = minTriggerWord;
                                unmatched_TriggerWords = unmatched_TriggerWords.Replace(", " + minTriggerWord, "");
                            }
                            else if (field.ToLower().Contains(prcpTriggerWord.ToLower()))
                            {
                                //CurrentScenarioName = field.Substring(1, field.LastIndexOf("p") - 2);
                                CurrentScenarioType = prcpTriggerWord;
                                unmatched_TriggerWords = unmatched_TriggerWords.Replace(", " + prcpTriggerWord, "");
                            }
                            else if (field.ToLower().Contains(rhTriggerWord.ToLower()))
                            {
                                CurrentScenarioType = rhTriggerWord;
                                unmatched_TriggerWords = unmatched_TriggerWords.Replace(", " + rhTriggerWord, "");
                            }
                            else if (field.ToLower().Contains(windSpeedTriggerWord.ToLower()))
                            {
                                CurrentScenarioType = windSpeedTriggerWord;
                                unmatched_TriggerWords = unmatched_TriggerWords.Replace(", " + windSpeedTriggerWord, "");
                            }


                        }



                    }


                    if (fields[0] == string.Empty && !fields[0].Contains("#"))
                    {
                        line = reader.ReadLine();
                        fields = line.Split(',');

                        if (fields[0].Contains("TIME"))
                        {
                            line = reader.ReadLine();
                            fields = line.Split(',');

                        }
                    }
                    if (!fields[0].Contains("#"))
                    {

                        key = fields[0].ToString();
                        if (CurrentScenarioType.ToLower().Contains(maxTriggerWord.ToLower()))
                        {
                            IndexMaxT_Mean = 0;
                            IndexMaxT_Var = 1;
                            IndexMaxT_STD = 2;
                            if (!climate_Dic.Keys.Contains(key))
                                climate_Dic.Add(key, new double[dicSize]);

                            //set index of max and maxSTD for each ecorigion
                            for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                            {
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[i + 1]) - 274.15, IndexMaxT_Mean);
                                updatedIndex += i + climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexMaxT_Var);
                                updatedIndex += climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexMaxT_STD);
                                IndexMaxT_Mean = IndexMaxT_Mean + 9;
                                IndexMaxT_Var = IndexMaxT_Var + 9;
                                IndexMaxT_STD = IndexMaxT_STD + 9;
                                updatedIndex = 0;


                            }
                        }
                        else if (CurrentScenarioType.ToLower().Contains(minTriggerWord.ToLower()))
                        {
                            IndexMinT_Mean = 3;
                            IndexMinT_Var = 4;
                            IndexMinT_STD = 5;

                            // climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });
                            if (!climate_Dic.Keys.Contains(key))
                                climate_Dic.Add(key, new double[dicSize]);
                            //set index of max and maxSTD for each ecorigion
                            for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                            {
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[i + 1]) - 274.15, IndexMinT_Mean);
                                updatedIndex += i + climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]) - 274.15, IndexMinT_Var);
                                updatedIndex += climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]) - 274.15, IndexMinT_STD);

                                IndexMinT_Mean = IndexMinT_Mean + 9;
                                IndexMinT_Var = IndexMinT_Var + 9;
                                IndexMinT_STD = IndexMinT_STD + 9;
                                updatedIndex = 0;

                            }
                        }
                        else if (CurrentScenarioType.ToLower().Contains(prcpTriggerWord.ToLower()))
                        {
                            IndexPrcp_Mean = 6;
                            IndexPrcp_Var = 7;
                            IndexPrcp_STD = 8;

                            if (!climate_Dic.Keys.Contains(key))
                                climate_Dic.Add(key, new double[dicSize]);

                            //set index of Precipitation and STD for each ecoregion
                            for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                            {
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[i + 1]) * 315360, IndexPrcp_Mean); 
                                updatedIndex += i + climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]) * 315360, IndexPrcp_Var);
                                updatedIndex += climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]) * 315360, IndexPrcp_STD); //NOTE: this might be a wrong conversion for converting IndexPrcp_STD from mm to cm because STD is calculate using root square.

                                IndexPrcp_Mean = IndexPrcp_Mean + 9;
                                IndexPrcp_Var = IndexPrcp_Var + 9;
                                IndexPrcp_STD = IndexPrcp_STD + 9;
                                updatedIndex = 0;
                            }

                        }


                        //-----
                        else if (CurrentScenarioType.ToLower().Contains(rhTriggerWord.ToLower()))
                        {
                            IndexRH_Mean = 9;
                            IndexRH_Var = 10;
                            IndexRH_STD = 11;

                            //IndexSTD = 5;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcoregions);

                            // climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });
                            if (!climate_Dic.Keys.Contains(key))
                                climate_Dic.Add(key, new double[dicSize]);
                            //set index of max and maxSTD for each ecorigion
                            for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                            {

                                climate_Dic[key].SetValue(Convert.ToDouble(fields[i + 1]), IndexRH_Mean);
                                updatedIndex += i + climateFileActiveEcoregions.Count;

                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexRH_Var);
                                updatedIndex += climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexRH_STD);


                                IndexRH_Mean = IndexRH_Mean + 9;
                                IndexRH_Var = IndexRH_Var + 9;
                                IndexRH_STD = IndexRH_STD + 9;
                                updatedIndex = 0;

                            }

                        }

                        //-----
                        else if (CurrentScenarioType.ToLower().Contains(windSpeedTriggerWord.ToLower()))
                        {
                            IndexwindSpeed_Mean = 12;
                            IndexwindSpeed_Var = 13;
                            IndexwindSpeed_STD = 14;

                            //IndexSTD = 5;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcoregions);

                            // climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });
                            if (!climate_Dic.Keys.Contains(key))
                                climate_Dic.Add(key, new double[dicSize]);
                            //set index of max and maxSTD for each ecorigion
                            for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                            {

                                climate_Dic[key].SetValue(Convert.ToDouble(fields[i + 1]), IndexwindSpeed_Mean);
                                updatedIndex += i + climateFileActiveEcoregions.Count;

                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexwindSpeed_Var);
                                updatedIndex += climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexwindSpeed_STD);


                                IndexwindSpeed_Mean = IndexwindSpeed_Mean + 9;
                                IndexwindSpeed_Var = IndexwindSpeed_Var + 9;
                                IndexwindSpeed_STD = IndexwindSpeed_STD + 9;
                                updatedIndex = 0;

                            }

                        }
                        //-----


                    }  //end while


                    //if (CurrentScenarioName != tempScenarioName || reader.EndOfStream)
                    if (reader.EndOfStream)
                    {
                        //Daily period
                        //centuryPath = "Century_Climate_Inputs_Monthly.txt";
                        setIndexed();
                        currentYear = climate_Dic.First().Key.Substring(0, 4).ToString();
                        //starting timestep
                        currentTimeS = 0;
                        currentMonth = Convert.ToInt16(climate_Dic.First().Key.Substring(5, 2).ToString());
                        tempEco = 1;


                        lastYear = climate_Dic.AsEnumerable().Select(ax => Convert.ToInt32(ax.Key.Substring(0, 4).ToString())).Distinct().ToList().Max();
                        firstYear = climate_Dic.AsEnumerable().Select(ai => Convert.ToInt32(ai.Key.Substring(0, 4).ToString())).Distinct().ToList().Min();
                        if ((double)climate_Dic.Count / 12 > (double)lastYear - firstYear)
                            lastYear = lastYear - 1;

                        for (int j = firstYear; j <= lastYear; j++)
                        {
                            for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                            {
                                currentYear = j.ToString();

                                foreach (KeyValuePair<string, double[]> row in climate_Dic)
                                {
                                    if (currentYear == row.Key.Substring(0, 4).ToString())
                                    {

                                        if (currentMonth == Convert.ToInt16(row.Key.Substring(5, 2)))
                                        {

                                            AverageMin += Math.Round(row.Value[IndexMinT_Mean], 2);
                                            AverageMax += Math.Round(row.Value[IndexMaxT_Mean], 2);
                                            SumPrecp += (Math.Round(row.Value[IndexPrcp_Mean], 2));
                                            AverageSTDT += Math.Round((row.Value[IndexMaxT_Var] + row.Value[IndexMinT_Var]) / 2, 2);
                                            SumVarPpt += Convert.ToDouble(row.Value[IndexPrcp_Var]);
                                            numberOfDays++;

                                        }
                                        else
                                        {
                                            //if (exportToTxtFormatFile)
                                            //    file.WriteLine(climateFileActiveEcoregions.ElementAt(i).Value.Name + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(SumPrecp, 2) + "\t" + Math.Round(Math.Sqrt(SumVarPpt), 2) + "\t" + "0.0" + "\t" + Math.Round(AverageSTDT / numberOfDays, 2) + "\t" + Math.Round(SumVarPpt, 2) + "\n");
                                            currentMonth = Convert.ToInt16(row.Key.Substring(5, 2));
                                            //if (tempMonth != currentMonth)
                                            alldays += numberOfDays;
                                            AverageMax = 0;
                                            AverageMin = 0;
                                            SumPrecp = 0;
                                            AverageSTDT = 0;
                                            SumVarPpt = 0;

                                            numberOfDays = 0;
                                            AverageMin += Math.Round(row.Value[IndexMinT_Mean], 2);
                                            AverageMax += Math.Round(row.Value[IndexMaxT_Mean], 2);
                                            SumPrecp += (Math.Round(row.Value[IndexPrcp_Mean], 2));
                                            AverageSTDT += Math.Round((row.Value[IndexMaxT_Var] + row.Value[IndexMinT_Var]) / 2, 2);
                                            SumVarPpt += Convert.ToDouble(row.Value[IndexPrcp_Var]);

                                            numberOfDays++;
                                        }


                                    }
                                    else
                                    {
                                        if (currentMonth == 12)
                                        {
                                            alldays += numberOfDays;
                                            //if (exportToTxtFormatFile)
                                            //    file.WriteLine(climateFileActiveEcoregions.ElementAt(i).Value.Name + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(SumPrecp, 2) + "\t" + Math.Round(Math.Sqrt(SumVarPpt), 2) + "\t" + "0.0" + "\t" + Math.Round(AverageSTDT / numberOfDays, 2) + "\t" + Math.Round(SumVarPpt, 2) + "\n");
                                            if (!yearsdays.Keys.Contains(j))
                                            {
                                                yearsdays.Add(j, alldays);
                                                alldays = 0;
                                            }
                                        }


                                        alldays = 0;
                                        tempEco = i;
                                        currentMonth = 1;
                                        AverageMax = 0;
                                        AverageMin = 0;
                                        SumPrecp = 0;

                                        AverageSTDT = 0;
                                        SumVarPpt = 0;

                                        numberOfDays = 0;
                                        AverageMin += Math.Round(row.Value[IndexMinT_Mean], 2);
                                        AverageMax += Math.Round(row.Value[IndexMaxT_Mean], 2);
                                        SumPrecp += (Math.Round(row.Value[IndexPrcp_Mean], 2));
                                        AverageSTDT += Math.Round((row.Value[IndexMaxT_Var] + row.Value[IndexMinT_Var]) / 2, 2);
                                        SumVarPpt += Convert.ToDouble(row.Value[IndexPrcp_Var]);
                                        numberOfDays++;
                                    }


                                }
                                tempEco = i;

                                currentMonth = 1;
                                AverageMax = 0;
                                //AverageMaxSTD = 0;
                                AverageMin = 0;
                                //AverageMinSTD = 0;
                                SumPrecp = 0;
                                //AveragePrecSTD = 0;

                                AverageSTDT = 0;
                                SumVarPpt = 0;

                                IndexMaxT_Mean = IndexMaxT_Mean + 9;
                                //IndexMax_MaxT = IndexMax_MaxT + 12;
                                IndexMaxT_Var = IndexMaxT_Var + 9;
                                IndexMaxT_STD = IndexMaxT_STD + 9;
                                IndexMinT_Mean = IndexMinT_Mean + 9;
                                //IndexMin_MaxT = IndexMin_MaxT + 12;
                                IndexMinT_Var = IndexMinT_Var + 9;
                                IndexMinT_STD = IndexMinT_STD + 9;
                                IndexPrcp_Mean = IndexPrcp_Mean + 9;
                                //IndexPrcp_MaxT = IndexPrcp_MaxT + 12;
                                IndexPrcp_Var = IndexPrcp_Var + 9;
                                IndexPrcp_STD = IndexPrcp_STD + 9;


                                IndexRH_Mean = IndexRH_Mean + 9;
                                IndexRH_Var = IndexRH_Var + 9;
                                IndexRH_STD = IndexRH_STD + 9;

                                IndexwindSpeed_Mean = IndexwindSpeed_Mean + 9;
                                IndexwindSpeed_Var = IndexwindSpeed_Var + 9;
                                IndexwindSpeed_STD = IndexwindSpeed_STD + 9;

                            }
                            //file.WriteLine("eco" + numberOfAllEcoregions.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(StdDevPpt), 2) + "\t" + "0.0" + "\n");

                            tempEco = 1;
                            currentTimeS = currentTimeS + 1;
                            IndexMaxT_Mean = 0;
                            //IndexMax_MaxT = 1;
                            IndexMaxT_Var = 1;
                            IndexMaxT_STD = 2;
                            IndexMinT_Mean = 3;
                            //IndexMin_MaxT = 5;
                            IndexMinT_Var = 4;
                            IndexMinT_STD = 5;
                            IndexPrcp_Mean = 6;
                            //IndexPrcp_MaxT = 9;
                            IndexPrcp_Var = 7;
                            IndexPrcp_STD = 8;

                            IndexRH_Mean = 9;
                            IndexRH_Var = 10;
                            IndexRH_STD = 11;

                            IndexwindSpeed_Mean = 12;
                            IndexwindSpeed_Var = 13;
                            IndexwindSpeed_STD = 14;

                            currentMonth = 1;
                            AverageMax = 0;
                            //AverageMaxSTD = 0;
                            AverageMin = 0;
                            //AverageMinSTD = 0;
                            SumPrecp = 0;
                            //AveragePrecSTD = 0;

                            AverageSTDT = 0;
                            SumVarPpt = 0;

                        }

                    }

                    //If file contains more than one scenario then these setting will be needed
                    //climate_Dic.Clear();
                    //emptytxt = true;
                    //tempScenarioName = CurrentScenarioName;

                    //}
                }
                //if (unmatched_TriggerWords != "")
                //{
                //    Climate.ModelCore.UI.WriteLine("Error in ClimateDataConvertor: Converting {0} file into standard format.", climateFile);
                //    Climate.ModelCore.UI.WriteLine("The following triggerWords did not match the triggerwords in the given file: {1}.  Selected format: {2}", unmatched_TriggerWords, formatProvider.SelectedFormat);
                //    throw new ApplicationException("Error in ClimateDataConvertor: See Log File."); //: Converting " + climateFile + " file into standard format; The following triggerWords did not match the triggerwords in the given file: " + unmatched_TriggerWords + "." + "selected format: \"" + formatProvider.SelectedFormat + "\"");
                //}

            }
            #endregion

            #region PRISM Monthly Data
            //else if (sourceTemporalGranularity == TemporalGranularity.Monthly)
            else if (climateFileFormat == "prism_monthly") 
            {

                //unmatched_TriggerWords = maxTriggerWord + ", " + minTriggerWord + ", " + prcpTriggerWord;// +", " + rhTriggerWord + ", " + windSpeedTriggerWord;

                sreader = new StreamReader(path);  // NEED TRY CATCH FILE OPEN HERE


                string line;
                string[] fields;
                checkRHWindSpeed = false;

                if (checkRHWindSpeed == false)
                    unmatched_TriggerWords = maxTriggerWord + ", " + minTriggerWord + ", " + prcpTriggerWord;// +", " + rhTriggerWord + ", " + windSpeedTriggerWord;
                else
                    unmatched_TriggerWords = maxTriggerWord + ", " + minTriggerWord + ", " + prcpTriggerWord + ", " + rhTriggerWord + ", " + windSpeedTriggerWord;

                //string tempScenarioName = "";
                DataTable _dataTableDataByTime = new DataTable();
                //int numberOfAllEcoregions = 0;
                line = sreader.ReadLine();
                fields = line.Split(',');
                //tempScenarioName = fields[0].Substring(1, fields[0].LastIndexOf("t") - 2);
                //tempScenarioName = fields[0].Substring(1, 4);
                line = sreader.ReadLine();
                fields = line.Split(',');
                //int totalRows = 0;
                //string[,] wholedata;
                //string CurrentScenarioName = "";

                string CurrentScenarioType = "";
                climate_Dic = new Dictionary<string, double[]>();

                //string currentT;
                //string currentSTD;
                //string currentPart = "";
                //int totalRow = 0;
                string key = "";
                int IndexMaxT_Mean = 0;
                //int IndexMax_MaxT = 1;
                int IndexMaxT_Var = 1;
                int IndexMaxT_STD = 2;
                int IndexMinT_Mean = 3;
                //int IndexMin_MaxT = 5;
                int IndexMinT_Var = 4;
                int IndexMinT_STD = 5;
                int IndexPrcp_Mean = 6;
                //int IndexPrcp_MaxT = 9;
                int IndexPrcp_Var = 7;
                int IndexPrcp_STD = 8;
                int IndexRH_Mean = 9;
                int IndexRH_Var = 10;
                int IndexRH_STD = 11;
                int IndexwindSpeed_Mean = 12;
                int IndexwindSpeed_Var = 13;
                int IndexwindSpeed_STD = 14;

                //bool firstFlag = false;
                currentYear = "";
                //starting timestep
                int currentTimeS = 0;
                currentMonth = 1;
                int tempEco = 1;
                double AverageMax = 0;

                //double AverageMaxSTD = 0;
                double AverageMin = 0;
                //double AverageMinSTD = 0;
                double SumPrecp = 0;

                double AverageSTDT = 0;
                double sumVarPpt = 0;
                //double AveragePrecSTD = 0;
                int numberOfDays = 0;
                double[] tempSum = new double[31];
                double[] tempPrp = new double[31];
                //double sums = 0;
                //double prpSums = 0;
                //double stdTemp = 0;
                //double stdPrp = 0;
                bool emptytxt = false;
                int updatedIndex = 0;


                // IEnumerable<Core.IEcoregion> activeEcoregions = Climate.ModelCore.Ecoregions.Where(P => P.Active);
                //int ecoIndex = -1;
                climateFileActiveEcoregions = new SortedList<int, Core.IEcoregion>();

                foreach (string field in fields)
                {
                    if (field != "")
                    {
                        //if (Convert.ToInt16(field) > ecoIndex)
                        //{
                        //    ecoIndex = Convert.ToInt16(field);
                            IEcoregion eco = Climate.ModelCore.Ecoregions[field]; //.Where(P => P.Index == ecoIndex).FirstOrDefault();
                            //numberOfAllEcoregions = Convert.ToInt16(field);
                            if (eco != null && eco.Active)
                            {
                                if (!climateFileActiveEcoregions.ContainsKey(eco.Index))
                                    climateFileActiveEcoregions.Add(eco.Index, eco);
                            }
                            else
                            {
                                //Climate.ModelCore.UI.WriteLine("ClimateDataConvertor: Number of active ecoregions does not match the input file. The climate data for ecoregion with index {0} was ignored.", numberOfAllEcoregions);
                                Climate.ModelCore.UI.WriteLine("Error in ClimateDataConvertor: Converting {0} file into standard format; Number of active ecoregions does not match the input file.", climateFile);
                                throw new ApplicationException("Error in ClimateDataConvertor: Converting" + climateFile + "file into standard format; Number of active ecoregions does not match the input file.");
                            }

                     }
                }


                //12 beacuse for each ecoriogn we need Max_MinT,Max_MaxT,Max_Var Max_Std, Min_MinT,Min_MaxT,Min_Var Min_Std, Prcp_MinT,Prcp_MaxT,Prcp_Var Prcp_Std
                int dicSize = climateFileActiveEcoregions.Count * 15;// Climate.ModelCore.Ecoregions.Count * 9;
                sreader.Close();
                StreamReader reader = new StreamReader(path);

                while (reader.Peek() >= 0)
                {
                    line = reader.ReadLine();
                    fields = line.Split(',');
                    foreach (string field in fields)
                    {
                        if (field.Contains("#"))
                        {

                            triggerWordsCheckingTime++;
                            if (triggerWordsCheckingTime > 1)
                                if (unmatched_TriggerWords == maxTriggerWord + ", " + minTriggerWord + ", " + prcpTriggerWord + ", " + rhTriggerWord + ", " + windSpeedTriggerWord && checkRHWindSpeed == true)
                                {
                                    Climate.ModelCore.UI.WriteLine("Error in ClimateDataConvertor: Converting {0} file into standard format; The following triggerWords did not match the triggerwords in the given file: {1}." + "selected format: \"{2}\"", climateFile, unmatched_TriggerWords, formatProvider.SelectedFormat);
                                    throw new ApplicationException("Error in ClimateDataConvertor: Converting " + climateFile + " file into standard format; The following triggerWords did not match the triggerwords in the given file: " + unmatched_TriggerWords + "." + "selected format: \"" + formatProvider.SelectedFormat + "\"");
                                }
                                else if (unmatched_TriggerWords == maxTriggerWord + ", " + minTriggerWord + ", " + prcpTriggerWord && checkRHWindSpeed == false)
                                {
                                    Climate.ModelCore.UI.WriteLine("Error in ClimateDataConvertor: Converting {0} file into standard format; The following triggerWords did not match the triggerwords in the given file: {1}." + "selected format: \"{2}\"", climateFile, unmatched_TriggerWords, formatProvider.SelectedFormat);
                                    throw new ApplicationException("Error in ClimateDataConvertor: Converting " + climateFile + " file into standard format; The following triggerWords did not match the triggerwords in the given file: " + unmatched_TriggerWords + "." + "selected format: \"" + formatProvider.SelectedFormat + "\"");
                                }


                            //tempScenarioName = CurrentScenarioName;
                            if (field.ToLower().Contains(prcpTriggerWord.ToLower()))
                            {
                                //CurrentScenarioName = field.Substring(1, 4);
                                CurrentScenarioType = prcpTriggerWord;
                                unmatched_TriggerWords = unmatched_TriggerWords.Replace(", " + prcpTriggerWord, "");
                            }

                            //else if (field.ToLower().Contains(maxTriggerWord.ToLower()) || field.ToLower().Contains(minTriggerWord.ToLower()))
                            //{
                            //CurrentScenarioName = field.Substring(1, 4);
                            else if (field.ToLower().Contains(maxTriggerWord.ToLower()))
                            {
                                CurrentScenarioType = maxTriggerWord;
                                unmatched_TriggerWords = unmatched_TriggerWords.Replace(maxTriggerWord, "");
                            }
                            else if (field.ToLower().Contains(minTriggerWord.ToLower()))
                            {
                                CurrentScenarioType = minTriggerWord.ToLower();
                                unmatched_TriggerWords = unmatched_TriggerWords.Replace(", " + minTriggerWord, "");
                            }
                            else if (field.ToLower().Contains(rhTriggerWord.ToLower()))
                            {
                                CurrentScenarioType = rhTriggerWord.ToLower();
                                unmatched_TriggerWords = unmatched_TriggerWords.Replace(", " + rhTriggerWord, "");
                            }
                            else if (field.ToLower().Contains(windSpeedTriggerWord.ToLower()))
                            {
                                CurrentScenarioType = windSpeedTriggerWord.ToLower();
                                unmatched_TriggerWords = unmatched_TriggerWords.Replace(", " + windSpeedTriggerWord, "");
                            }
                            //}


                            //if (tempScenarioName != CurrentScenarioName)// firstFlag == false)
                            //{
                            //    tempScenarioName = CurrentScenarioName;
                            //    //firstFlag = true;
                            //}



                            //line = reader.ReadLine();
                            //fields = line.Split(',');

                        }



                    }

                    if (fields[0] == string.Empty && !fields[0].Contains("#"))
                    {
                        line = reader.ReadLine();
                        fields = line.Split(',');

                        if (fields[0].Contains("TIME"))
                        {
                            line = reader.ReadLine();
                            fields = line.Split(',');

                            //now fill array 
                            //Get the lenght of array according to the number of ecorigions/
                            //

                        }
                    }
                    if (!fields[0].Contains("#"))//(CurrentScenarioName == tempScenarioName && !fields[0].Contains("#"))
                    {

                        key = fields[0].ToString();
                        if (CurrentScenarioType.ToLower().Contains(prcpTriggerWord.ToLower()))
                        {
                            IndexPrcp_Mean = 6;
                            //IndexPrcp_MaxT = 9;
                            IndexPrcp_Var = 7;
                            IndexPrcp_STD = 8;

                            //IndexSTD = 5;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcoregions);

                            // climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });
                            if (!climate_Dic.Keys.Contains(key))
                                climate_Dic.Add(key, new double[dicSize]);
                            //set index of max and maxSTD for each ecorigion
                            for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                            {
                                //currentT = fields[i+1];
                                //if (indexofSTD < 26)
                                //{
                                //currentSTD = fields[indexofSTD];
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[i + 1]) / 10, IndexPrcp_Mean); // /10 is for mm to cm conversion
                                updatedIndex += i + climateFileActiveEcoregions.Count;
                                //climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexPrcp_MaxT);
                                //updatedIndex += numberOfAllEcoregions;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]) / 10, IndexPrcp_Var);
                                updatedIndex += climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]) / 10, IndexPrcp_STD);


                                //climate_Dic[key].SetValue(Convert.ToDouble(currentSTD), IndexSTD);
                                IndexPrcp_Mean = IndexPrcp_Mean + 9;
                                //IndexPrcp_MaxT = IndexPrcp_MaxT + 12;
                                IndexPrcp_Var = IndexPrcp_Var + 9;
                                IndexPrcp_STD = IndexPrcp_STD + 9;
                                updatedIndex = 0;
                                //IndexSTD = IndexSTD + 6;
                                //indexofSTD++;
                            }

                        }

                        else if (CurrentScenarioType.ToLower().Contains(maxTriggerWord.ToLower()))
                        {
                            IndexMaxT_Mean = 0;
                            //IndexMax_MaxT = 1;
                            IndexMaxT_Var = 1;
                            IndexMaxT_STD = 2;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcoregions);
                            if (!climate_Dic.Keys.Contains(key))
                                climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });

                            //set index of max and maxSTD for each ecorigion
                            for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                            {
                                //currentT = fields[i+1];
                                //if (indexofSTD < 26)
                                //{

                                climate_Dic[key].SetValue(Convert.ToDouble(fields[i + 1]), IndexMaxT_Mean);
                                updatedIndex += i + climateFileActiveEcoregions.Count;
                                //climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexMax_MaxT);
                                //updatedIndex +=  numberOfAllEcoregions;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexMaxT_Var);
                                updatedIndex += climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexMaxT_STD);
                                IndexMaxT_Mean = IndexMaxT_Mean + 9;
                                //IndexMax_MaxT = IndexMax_MaxT + 12;
                                IndexMaxT_Var = IndexMaxT_Var + 9;
                                IndexMaxT_STD = IndexMaxT_STD + 9;
                                updatedIndex = 0;

                                //indexofSTD++;
                                //}

                            }
                        }
                        else if (CurrentScenarioType.ToLower().Contains(minTriggerWord.ToLower()))
                        {
                            IndexMinT_Mean = 3;
                            //IndexMin_MaxT = 5;
                            IndexMinT_Var = 4;
                            IndexMinT_STD = 5;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcoregions);

                            // climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });

                            //set index of max and maxSTD for each ecorigion
                            if (!climate_Dic.Keys.Contains(key))
                                climate_Dic.Add(key, new double[dicSize]);
                            for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                            {

                                //currentT = fields[i+1];
                                //if (indexofSTD < 26)
                                //{
                                //currentSTD = fields[indexofSTD];
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[i + 1]), IndexMinT_Mean);
                                updatedIndex += i + climateFileActiveEcoregions.Count;
                                //climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexMin_MaxT);
                                //updatedIndex += numberOfAllEcoregions;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexMinT_Var);
                                updatedIndex += climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexMinT_STD);


                                //climate_Dic[key].SetValue(Convert.ToDouble(currentSTD), IndexSTD);
                                IndexMinT_Mean = IndexMinT_Mean + 9;
                                //IndexMin_MaxT = IndexMin_MaxT + 12;
                                IndexMinT_Var = IndexMinT_Var + 9;
                                IndexMinT_STD = IndexMinT_STD + 9;
                                updatedIndex = 0;
                                //    IndexSTD = IndexSTD + 6;
                                //    indexofSTD++;
                                //}

                            }
                        }

                         //-----
                        else if (CurrentScenarioType.ToLower().Contains(rhTriggerWord.ToLower()))
                        {
                            IndexRH_Mean = 9;
                            IndexRH_Var = 10;
                            IndexRH_STD = 11;

                            //IndexSTD = 5;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcoregions);

                            // climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });
                            if (!climate_Dic.Keys.Contains(key))
                                climate_Dic.Add(key, new double[dicSize]);
                            //set index of max and maxSTD for each ecorigion
                            for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                            {

                                climate_Dic[key].SetValue(Convert.ToDouble(fields[i + 1]), IndexRH_Mean);
                                updatedIndex += i + climateFileActiveEcoregions.Count;

                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexRH_Var);
                                updatedIndex += climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexRH_STD);


                                IndexRH_Mean = IndexRH_Mean + 9;
                                IndexRH_Var = IndexRH_Var + 9;
                                IndexRH_STD = IndexRH_STD + 9;
                                updatedIndex = 0;

                            }

                        }

                        //-----
                        else if (CurrentScenarioType.ToLower().Contains(windSpeedTriggerWord.ToLower()))
                        {
                            IndexwindSpeed_Mean = 12;
                            IndexwindSpeed_Var = 13;
                            IndexwindSpeed_STD = 14;

                            //IndexSTD = 5;
                            //int indexofSTD = 0;
                            //indexofSTD = fields.Length - (numberOfAllEcoregions);

                            // climate_Dic.Add(key, new double[dicSize]);//{ currentT, currentSTD, 0, 0, 0, 0 });
                            if (!climate_Dic.Keys.Contains(key))
                                climate_Dic.Add(key, new double[dicSize]);
                            //set index of max and maxSTD for each ecorigion
                            for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                            {

                                climate_Dic[key].SetValue(Convert.ToDouble(fields[i + 1]), IndexwindSpeed_Mean);
                                updatedIndex += i + climateFileActiveEcoregions.Count;

                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexwindSpeed_Var);
                                updatedIndex += climateFileActiveEcoregions.Count;
                                climate_Dic[key].SetValue(Convert.ToDouble(fields[updatedIndex + 1]), IndexwindSpeed_STD);


                                IndexwindSpeed_Mean = IndexwindSpeed_Mean + 9;
                                IndexwindSpeed_Var = IndexwindSpeed_Var + 9;
                                IndexwindSpeed_STD = IndexwindSpeed_STD + 9;
                                updatedIndex = 0;

                            }

                        }


                    }

                    if (reader.EndOfStream)//CurrentScenarioName != tempScenarioName || reader.EndOfStream)
                    {
                        //tempScenarioName = CurrentScenarioName;
                        //Print file for one scenario then clear dictionary to use for another scenario

                        //Monthly peiod
                        centuryPath = "Century_Climate_Inputs_PRISM_Monthly.txt";
                        //int AverageMaxT = 0;
                        //int AverageMaxSTD = 1;
                        //int AverageMinT = 2;
                        //int AverageMinSTD = 3;
                        //int AveragePrec = 4;
                        //int AveragePrecSTD = 5;
                        IndexMaxT_Mean = 0;
                        //IndexMax_MaxT = 1;
                        IndexMaxT_Var = 1;
                        IndexMaxT_STD = 2;
                        IndexMinT_Mean = 3;
                        //IndexMin_MaxT = 5;
                        IndexMinT_Var = 4;
                        IndexMinT_STD = 5;
                        IndexPrcp_Mean = 6;
                        //IndexPrcp_MaxT = 9;
                        IndexPrcp_Var = 7;
                        IndexPrcp_STD = 8;
                        IndexRH_Mean = 9;
                        IndexRH_Var = 10;
                        IndexRH_STD = 11;

                        IndexwindSpeed_Mean = 12;
                        IndexwindSpeed_Var = 13;
                        IndexwindSpeed_STD = 14;


                        //int AverageMaxT = 0;
                        //int AverageMaxSTD = 1;
                        //int AverageMinT = 1;
                        //int AverageMinSTD = 3;
                        //int AveragePrec = 2;
                        //int AveragePrecSTD = 5;
                        using (System.IO.StreamWriter file = new System.IO.StreamWriter(centuryPath, emptytxt))
                        {
                            if (exportToTxtFormatFile)
                            {
                                file.WriteLine("LandisData" + " \"Climate Data\" \n");
                                file.WriteLine("ClimateTable \n");
                                //file.WriteLine(tempScenarioName + "\n");

                                file.WriteLine(">>Eco" + "\t\t" + "Time" + "\t" + "Month" + "\t" + "AvgMinT" + "\t" + "AvgMaxT" + "\t" + "StdDevT" + "\t" + "AvgPpt" + "\t" + "StdDevPpt" + "\t" + "PAR" + "\t" + "VarT" + "\t" + "VarPpt" + "\n");
                                file.WriteLine(">>Name" + "\t\t" + "Step" + "\t" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(k)" + "\t" + "(cm)" + "\t" + "Ppt" + "\t" + "µmol m-2 s-1" + "\t" + "(cm)" + "\t" + "(cm)" + "\n");
                                //file.WriteLine(">>Eco" + "\t" + "Time" + "\t" + "Month" + "\t" + "AvgMinT" + "\t" + "AvgMaxT" + "\t" + "StdDevT" + "\t" + "AvgPpt" + "\t" + "StdDev" + "\t" + "PAR" + "\n");
                                //file.WriteLine(">>Name" + "\t" + "Step" + "\t" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(k)" + "\t" + "(cm)" + "\t" + "Ppt" + "\t" + "µmol m-2 s-1" + "\n");
                                //file.WriteLine(">>Eco" + "\t" + "Time" + "\t" + "\t" + "AvgMaxT" + "\t" + "StdMaxT" + "\t" + "AvgMinT" + "\t" + "StdMinT" + "\t" + "AvgPpt" + "\t" + "StdDev" + "\n");
                                // file.WriteLine(">>Name" + "\t" + "Step" + "\t" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(C)" + "\t" + "(C)" + "\n");
                            }
                            //initialize currentYear and month
                            currentYear = climate_Dic.First().Key.Substring(0, 4).ToString();
                            //starting timestep
                            currentTimeS = 0;
                            currentMonth = Convert.ToInt16(climate_Dic.First().Key.Substring(5, 2).ToString());
                            tempEco = 1;
                            lastYear = climate_Dic.AsEnumerable().Select(ax => Convert.ToInt32(ax.Key.Substring(0, 4).ToString())).Distinct().ToList().Max();
                            firstYear = climate_Dic.AsEnumerable().Select(ai => Convert.ToInt32(ai.Key.Substring(0, 4).ToString())).Distinct().ToList().Min();
                            if ((double)climate_Dic.Count / 12 > (double)lastYear - firstYear)
                                lastYear = lastYear - 1;
                            for (int j = firstYear; j <= lastYear; j++)
                            {
                                for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
                                {
                                    currentYear = j.ToString();
                                    foreach (KeyValuePair<string, double[]> row in climate_Dic)
                                    {

                                        if (currentYear == row.Key.Substring(0, 4).ToString())
                                        {
                                            if (currentMonth == Convert.ToInt16(row.Key.Substring(5, 2)))
                                            {
                                                AverageMin += Math.Round(row.Value[IndexMinT_Mean], 2);
                                                AverageMax += Math.Round(row.Value[IndexMaxT_Mean], 2);
                                                SumPrecp += (Math.Round(row.Value[IndexPrcp_Mean], 2));
                                                AverageSTDT += Math.Round((row.Value[IndexMaxT_Var] + row.Value[IndexMinT_Var]) / 2, 2);
                                                sumVarPpt += Convert.ToDouble(row.Value[IndexPrcp_STD]);
                                                numberOfDays++;

                                            }
                                            else
                                            {
                                                if (exportToTxtFormatFile)
                                                    file.WriteLine(climateFileActiveEcoregions.ElementAt(i).Value.Name + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(SumPrecp, 2) + "\t" + Math.Round(sumVarPpt, 2) + "\t" + "0.0" + "\t" + Math.Round(AverageSTDT / numberOfDays, 2) + "\t" + Math.Round(sumVarPpt, 2) + "\n");
                                                //file.WriteLine("eco1" + "\t" + currentYear + "\t" + currentMonth + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(AverageMaxSTD / numberOfDays, 2) + "\t" + Math.Round(AverageMinT / numberOfDays, 2) + "\t" + Math.Round(AverageMinSTD / numberOfDays, 2) + "\t" + Math.Round(AveragePrec / numberOfDays, 2) + "\t" + Math.Round(AveragePrecSTD / numberOfDays, 2) + "\n");
                                                //tempMonth = currentMonth;
                                                currentMonth = Convert.ToInt16(row.Key.Substring(5, 2));
                                                //if (tempMonth != currentMonth)

                                                AverageMax = 0;
                                                //AverageMaxSTD = 0;
                                                AverageMin = 0;
                                                //AverageMinSTD = 0;
                                                SumPrecp = 0;
                                                //AveragePrecSTD = 0;
                                                AverageSTDT = 0;
                                                sumVarPpt = 0;
                                                numberOfDays = 0;
                                                AverageMin += Math.Round(row.Value[IndexMinT_Mean], 2);
                                                AverageMax += Math.Round(row.Value[IndexMaxT_Mean], 2);
                                                SumPrecp += (Math.Round(row.Value[IndexPrcp_Mean], 2)); 
                                                AverageSTDT += Math.Round((row.Value[IndexMaxT_Var] + row.Value[IndexMinT_Var]) / 2, 2);
                                                sumVarPpt += Convert.ToDouble(row.Value[IndexPrcp_STD]);
                                                //sums = 0;
                                                //stdTemp = 0;
                                                //prpSums = 0;
                                                //stdPrp = 0;
                                                numberOfDays++;
                                            }
                                        }
                                        else //  currentYear != row.Key.Substring(0, 4).ToString())
                                        {
                                            //if (tempEco != i && currentMonth == 12)
                                            //    file.WriteLine("eco" + tempEco.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt, 2) + "\t" + "0.0" + "\n");

                                            if (exportToTxtFormatFile)
                                                if (currentMonth == 12)
                                                    file.WriteLine(climateFileActiveEcoregions.ElementAt(i).Value.Name + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(SumPrecp, 2) + "\t" + Math.Round(sumVarPpt, 2) + "\t" + "0.0" + "\t" + Math.Round(AverageSTDT / numberOfDays, 2) + "\t" + Math.Round(sumVarPpt, 2) + "\n");
                                            ////if (currentTimeS == 0 && currentMonth == 12 && i==2)
                                            //    file.WriteLine("eco2" + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt, 2) + "\t" + "0.0" + "\n");

                                            //else if (tempEco != i)
                                            //    currentTimeS = 0;
                                            //file.WriteLine("eco1" + "\t" + currentYear + "\t" + currentMonth + "\t" + Math.Round(AverageMaxT / numberOfDays, 2) + "\t" + Math.Round(AverageMaxSTD / numberOfDays, 2) + "\t" + Math.Round(AverageMinT / numberOfDays, 2) + "\t" + Math.Round(AverageMinSTD / numberOfDays, 2) + "\t" + Math.Round(AveragePrec / numberOfDays, 2) + "\t" + Math.Round(AveragePrecSTD / numberOfDays, 2) + "\n");

                                            //currentYear = row.Key.Substring(0, 4).ToString();
                                            //currentTimeS = currentTimeS + 1;
                                            tempEco = i;
                                            currentMonth = 1;
                                            AverageMax = 0;
                                            //AverageMaxSTD = 0;
                                            AverageMin = 0;
                                            //AverageMinSTD = 0;
                                            SumPrecp = 0;
                                            //AveragePrecSTD = 0;

                                            AverageSTDT = 0;
                                            sumVarPpt = 0;

                                            numberOfDays = 0;

                                        }
                                    }
                                    tempEco = i;
                                    currentMonth = 1;
                                    AverageMax = 0;
                                    //AverageMaxSTD = 0;
                                    AverageMin = 0;
                                    //AverageMinSTD = 0;
                                    SumPrecp = 0;
                                    //AveragePrecSTD = 0;

                                    AverageSTDT = 0;
                                    sumVarPpt = 0;
                                    IndexMaxT_Mean = IndexMaxT_Mean + 9;
                                    //IndexMax_MaxT = IndexMax_MaxT + 12;
                                    IndexMaxT_Var = IndexMaxT_Var + 9;
                                    IndexMaxT_STD = IndexMaxT_STD + 9;
                                    IndexMinT_Mean = IndexMinT_Mean + 9;
                                    //IndexMin_MaxT = IndexMin_MaxT + 12;
                                    IndexMinT_Var = IndexMinT_Var + 9;
                                    IndexMinT_STD = IndexMinT_STD + 9;
                                    IndexPrcp_Mean = IndexPrcp_Mean + 9;
                                    //IndexPrcp_MaxT = IndexPrcp_MaxT + 12;
                                    IndexPrcp_Var = IndexPrcp_Var + 9;
                                    IndexPrcp_STD = IndexPrcp_STD + 9;

                                    IndexRH_Mean = IndexRH_Mean + 9;
                                    IndexRH_Var = IndexRH_Var + 9;
                                    IndexRH_STD = IndexRH_STD + 9;

                                    IndexwindSpeed_Mean = IndexwindSpeed_Mean + 9;
                                    IndexwindSpeed_Var = IndexwindSpeed_Var + 9;
                                    IndexwindSpeed_STD = IndexwindSpeed_STD + 9;

                                }

                                tempEco = 1;
                                currentTimeS = currentTimeS + 1;
                                IndexMaxT_Mean = 0;
                                //IndexMax_MaxT = 1;
                                IndexMaxT_Var = 1;
                                IndexMaxT_STD = 2;
                                IndexMinT_Mean = 3;
                                //IndexMin_MaxT = 5;
                                IndexMinT_Var = 4;
                                IndexMinT_STD = 5;
                                IndexPrcp_Mean = 6;
                                //IndexPrcp_MaxT = 9;
                                IndexPrcp_Var = 7;
                                IndexPrcp_STD = 8;

                                IndexRH_Mean = 9;
                                IndexRH_Var = 10;
                                IndexRH_STD = 11;

                                IndexwindSpeed_Mean = 12;
                                IndexwindSpeed_Var = 13;
                                IndexwindSpeed_STD = 14;

                                currentMonth = 1;
                                AverageMax = 0;
                                //AverageMaxSTD = 0;
                                AverageMin = 0;
                                //AverageMinSTD = 0;
                                SumPrecp = 0;
                                //AveragePrecSTD = 0;

                                AverageSTDT = 0;
                                sumVarPpt = 0;
                            }


                            //    for (int i = 1; i <= numberOfAllEcoregions; i++)
                            //    {

                            //        foreach (KeyValuePair<string, double[]> row in climate_Dic)
                            //        {

                            //            //file.WriteLine("eco" + i.ToString() + "\t" + row.Key.Remove(10) + "\t" + Math.Round(row.Value[AverageMaxT], 2) +  "\t" + Math.Round(row.Value[AverageMinT], 2) +  "\t" + Math.Round(row.Value[AveragePrec], 2)  + "\n");
                            //            //file.WriteLine("eco" + i.ToString() + "\t" + row.Key.Remove(10) + "\t" + Math.Round(row.Value[AverageMaxT], 2) + "\t" + Math.Round(row.Value[AverageMaxSTD], 2) + "\t" + Math.Round(row.Value[AverageMinT], 2) + "\t" + Math.Round(row.Value[AverageMinSTD], 2) + "\t" + Math.Round(row.Value[AveragePrec], 2) + "\t" + Math.Round(row.Value[AveragePrecSTD], 2) + "\n");

                            //                if (currentYear == row.Key.Substring(0, 4).ToString())
                            //                {

                            //                    if (currentMonth == Convert.ToInt16(row.Key.Substring(5, 2)))
                            //                    {

                            //                        //(row.Value[IndexMax_MaxT] + row.Value[IndexMaxT_Mean])/2
                            //                        //AverageMin += (row.Value[IndexMin_MaxT] + row.Value[IndexMinT_Mean]) / 2;
                            //                        //AverageMax += (row.Value[IndexMax_MaxT] + row.Value[IndexMaxT_Mean]) / 2;
                            //                        //AveragePrecp += (row.Value[IndexPrcp_MaxT] + row.Value[IndexPrcp_Mean]) / 2;
                            //                        //AverageSTDT += (row.Value[IndexMaxT_Var] + row.Value[IndexMinT_Var]) / 2;
                            //                        //AverageMaxSTD += Math.Round(Convert.ToDouble(row.Value[2]), 2);
                            //                        AverageMin += Math.Round(row.Value[IndexMinT_Mean], 2);
                            //                        AverageMax += Math.Round(row.Value[IndexMaxT_Mean], 2);
                            //                        AveragePrecp += Math.Round(row.Value[IndexPrcp_Mean], 2);
                            //                        AverageSTDT += Math.Round((row.Value[IndexMaxT_Var] + row.Value[IndexMinT_Var]) / 2, 2);
                            //                        StdDevPpt += Convert.ToDouble(row.Value[IndexPrcp_STD]);

                            //                        //AverageMinSTD += Math.Round(Convert.ToDouble(row.Value[4]), 2);
                            //                        //AveragePrecp += Math.Round(row.Value[AveragePrec], 2);
                            //                        //AveragePrecSTD += Math.Round(Convert.ToDouble(row.Value[6]), 2);

                            //                        //Calculating STD of Tempeture
                            //                        //tempSum[numberOfDays] = (row.Value[AverageMaxT] + row.Value[AverageMinT]) / 2;
                            //                        //stdTemp = 0;
                            //                        //stdPrp = 0;


                            //                        //Calculating STD of Prp
                            //                        //tempPrp[numberOfDays] = row.Value[AveragePrec];

                            //                        numberOfDays++;

                            //                    }


                            //                    else
                            //                    {
                            //                        //for (int j = 0; j < numberOfDays; j++)
                            //                        //{
                            //                        //    sums += Math.Pow((tempSum[j] - (((AverageMax / numberOfDays) + (AverageMin / numberOfDays)) / 2)), 2);
                            //                        //    prpSums += Math.Pow(tempPrp[j] - (AveragePrec / numberOfDays), 2);
                            //                        //}

                            //                        //stdTemp = Math.Sqrt(sums / (numberOfDays - 1));
                            //                        //stdPrp = Math.Sqrt(prpSums / (numberOfDays - 1));
                            //                        file.WriteLine("eco" + i.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt, 2) + "\t" + "0.0" + "\n");
                            //                        //file.WriteLine("eco1" + "\t" + currentYear + "\t" + currentMonth + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(AverageMaxSTD / numberOfDays, 2) + "\t" + Math.Round(AverageMinT / numberOfDays, 2) + "\t" + Math.Round(AverageMinSTD / numberOfDays, 2) + "\t" + Math.Round(AveragePrec / numberOfDays, 2) + "\t" + Math.Round(AveragePrecSTD / numberOfDays, 2) + "\n");
                            //                        //tempMonth = currentMonth;
                            //                        currentMonth = Convert.ToInt16(row.Key.Substring(5, 2));
                            //                        //if (tempMonth != currentMonth)

                            //                        AverageMax = 0;
                            //                        //AverageMaxSTD = 0;
                            //                        AverageMin = 0;
                            //                        //AverageMinSTD = 0;
                            //                        AveragePrecp = 0;
                            //                        //AveragePrecSTD = 0;
                            //                        AverageSTDT = 0;
                            //                        StdDevPpt = 0;

                            //                        numberOfDays = 0;
                            //                        AverageMin += Math.Round(row.Value[IndexMinT_Mean], 2);
                            //                        AverageMax += Math.Round(row.Value[IndexMaxT_Mean], 2);
                            //                        AveragePrecp += Math.Round(row.Value[IndexPrcp_Mean], 2);
                            //                        AverageSTDT += Math.Round((row.Value[IndexMaxT_Var] + row.Value[IndexMinT_Var]) / 2, 2);
                            //                        StdDevPpt += Convert.ToDouble(row.Value[IndexPrcp_STD]);
                            //                        //sums = 0;
                            //                        //stdTemp = 0;
                            //                        //prpSums = 0;
                            //                        //stdPrp = 0;
                            //                        numberOfDays++;
                            //                    }

                            //                }
                            //                else
                            //                {
                            //                    //If ecorigion has been changed
                            //                    if (tempEco != i && currentMonth == 12)
                            //                    {
                            //                        file.WriteLine("eco" + tempEco.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt, 2) + "\t" + "0.0" + "\n");
                            //                        currentTimeS = 0;
                            //                    }

                            //                    else if (currentMonth == 12)
                            //                    {
                            //                        file.WriteLine("eco" + i.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt, 2) + "\t" + "0.0" + "\n");
                            //                        currentTimeS = currentTimeS + 1;
                            //                    }
                            //                    else if (tempEco != i)
                            //                        currentTimeS = 0;
                            //                    //file.WriteLine("eco1" + "\t" + currentYear + "\t" + currentMonth + "\t" + Math.Round(AverageMaxT / numberOfDays, 2) + "\t" + Math.Round(AverageMaxSTD / numberOfDays, 2) + "\t" + Math.Round(AverageMinT / numberOfDays, 2) + "\t" + Math.Round(AverageMinSTD / numberOfDays, 2) + "\t" + Math.Round(AveragePrec / numberOfDays, 2) + "\t" + Math.Round(AveragePrecSTD / numberOfDays, 2) + "\n");

                            //                    currentYear = row.Key.Substring(0, 4).ToString();
                            //                    //currentTimeS = currentTimeS + 1;
                            //                    tempEco = i;
                            //                    currentMonth = 1;
                            //                    AverageMax = 0;
                            //                    //AverageMaxSTD = 0;
                            //                    AverageMin = 0;
                            //                    //AverageMinSTD = 0;
                            //                    AveragePrecp = 0;
                            //                    //AveragePrecSTD = 0;

                            //                    AverageSTDT = 0;
                            //                    StdDevPpt = 0;

                            //                    numberOfDays = 0;
                            //                    AverageMin += Math.Round(row.Value[IndexMinT_Mean], 2);
                            //                    AverageMax += Math.Round(row.Value[IndexMaxT_Mean], 2);
                            //                    AveragePrecp += Math.Round(row.Value[IndexPrcp_Mean], 2);
                            //                    AverageSTDT += Math.Round((row.Value[IndexMaxT_Var] + row.Value[IndexMinT_Var]) / 2, 2);
                            //                    StdDevPpt += Convert.ToDouble(row.Value[IndexPrcp_STD]);
                            //                    //sums = 0;
                            //                    //stdTemp = 0;
                            //                    //prpSums = 0;
                            //                    //stdPrp = 0;
                            //                    numberOfDays++;
                            //                }


                            //        }

                            //        IndexMaxT_Mean = IndexMaxT_Mean + 9;
                            //        //IndexMax_MaxT = IndexMax_MaxT + 12;
                            //        IndexMaxT_Var = IndexMaxT_Var + 9;
                            //        IndexMaxT_STD = IndexMaxT_STD + 9;
                            //        IndexMinT_Mean = IndexMinT_Mean + 9;
                            //        //IndexMin_MaxT = IndexMin_MaxT + 12;
                            //        IndexMinT_Var = IndexMinT_Var + 9;
                            //        IndexMinT_STD = IndexMinT_STD + 9;
                            //        IndexPrcp_Mean = IndexPrcp_Mean + 9;
                            //        //IndexPrcp_MaxT = IndexPrcp_MaxT + 12;
                            //        IndexPrcp_Var = IndexPrcp_Var + 9;
                            //        IndexPrcp_STD = IndexPrcp_STD + 9;
                            //    }
                            //    file.WriteLine("eco" + numberOfAllEcoregions.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt, 2) + "\t" + "0.0" + "\n");



                        }


                        //If file contains more than one scenario then these setting will be needed
                        //climate_Dic.Clear();
                        //emptytxt = true;
                        //tempScenarioName = CurrentScenarioName;

                    }
                }

                if (unmatched_TriggerWords != "")
                {
                    Climate.ModelCore.UI.WriteLine("Error in ClimateDataConvertor: Converting {0} file into standard format; The following triggerWords did not match the triggerwords in the given file: {1}." + "selected format: \"{2}\"", climateFile, unmatched_TriggerWords, formatProvider.SelectedFormat);
                    throw new ApplicationException("Error in ClimateDataConvertor: Converting " + climateFile + " file into standard format; The following triggerWords did not match the triggerwords in the given file: " + unmatched_TriggerWords + "." + "selected format: \"" + formatProvider.SelectedFormat + "\"");
                }

            }

            #endregion

            return; // centuryPath;

        }
            combineFuturesAndBondStatic(Dictionary<string/*isin*/, TimeSeriesBondStatic> bondstatic, 
                                        Frame<string,string> futstatic)
        //------------------------------------------------------------------------------------------------
        {

            bool bDeliverable = (bondstatic.Count != 0); // for non deliverable contracts, we don't feed in any bond static info
             
            var rowList = new List<KeyValuePair<int/*id*/, Series<string, object>/*row*/>>();

            int i = 0;
            foreach (var kvp in bondstatic)
            {
                TimeSeriesBondStatic staticRow = kvp.Value;
                var sb = new SeriesBuilder<string>();
                sb.Add("ISIN", staticRow.ISIN);
                sb.Add("Maturity", staticRow.Maturity.ToShortDateString());
                sb.Add("EffectiveDate", staticRow.EffectiveDate.ToShortDateString());
                sb.Add("FirstCouponDate", staticRow.FirstCouponDate.ToShortDateString());
                sb.Add("Coupon", staticRow.Coupon);

                rowList.Add(KeyValue.Create(i, sb.Series));
                ++i;
            }

            var df = Frame.FromRows(rowList);

            var bonddf = df.IsEmpty? null :df.IndexRows<string>("ISIN");

            // Change indexing structure to deal with futures
            Dictionary<string, Series<string, object>>
                      outputRows = new Dictionary<string, Series<string, object>>();


            foreach (string colkey in futstatic.RowKeys)
            {
                var row = futstatic.Rows[colkey];

                string ctdisin = row.GetAs<string>("fut_ctd_isin");

                // Let's check to make sure that all EffectiveDate, FirstCouponDate,Maturity etc are on the table
                // and ignore the bond static if so.
                DateTime maturity = row.TryGetAs<DateTime>("maturity").OrDefault(DateTime.MinValue);
                DateTime effDate  = row.TryGetAs<DateTime>("eff_dt").OrDefault(DateTime.MinValue);
                DateTime firstCpnDate = row.TryGetAs<DateTime>("first_cpn_dt").OrDefault(DateTime.MinValue);
                double coupon = row.TryGetAs<double>("cpn").OrDefault(double.NaN);

                if ( (maturity == DateTime.MinValue || effDate == DateTime.MinValue || firstCpnDate == DateTime.MinValue || double.IsNaN(coupon) ) && bDeliverable) 
                {
                    var bondstaticSrs = bonddf.Rows[ctdisin];
                    outputRows[colkey] = row.Merge(bondstaticSrs);
                }
                else
                {
                    var sb = new SeriesBuilder<string>();
                    sb.Add("ISIN", ctdisin);
                    sb.Add("Maturity", (maturity != DateTime.MinValue)? maturity.ToShortDateString():"-");
                    sb.Add("EffectiveDate", (effDate != DateTime.MinValue)? effDate.Date.ToShortDateString() :"-");
                    sb.Add("FirstCouponDate", (firstCpnDate != DateTime.MinValue) ? firstCpnDate.ToShortDateString():"-");
                    sb.Add("Coupon", coupon);

                    outputRows[colkey] = row.Merge(sb.Series);
                }
            }

            var output = Frame.FromRows(outputRows.AsEnumerable());

            //Log_.InfoFormat("Static Combined");
            //output.Print();


            return output.IndexRows<string>("ticker", keepColumn:true);
        }
		public static void RenderProxyTo(ProxyProvider r, Func<Color, Action<string>> ToColorWrite, Action<string> Write, TypeInfo Domain)
		{

			Action WriteLine = () => Write("\r\n");
			Action WriteSpace = () => Write(" ");

			#region Write<Color>
			Action<string> WriteBlue = ToColorWrite(Color.Blue);
			Action<string> WriteBlack = ToColorWrite(Color.Black);
			Action<string> WriteGray = ToColorWrite(Color.FromRGB(0x80, 0x80, 0x80));
			Action<string> WriteCyan = ToColorWrite(Color.FromRGB(0, 0x80, 0x80));
			Action<string> WriteGreen = ToColorWrite(Color.FromRGB(0, 0x80, 0));
			#endregion

			Action<string> WriteKeywordSpace =
				text =>
				{
					WriteBlue(text);
					WriteSpace();
				};

			int Indent = 0;

			Action WriteIdent = () => Write(new string(' ', 4 * Indent));

			#region CodeBlock
			Func<IDisposable> CodeBlock =
				delegate
				{
					WriteIdent();
					Write("{");
					WriteLine();

					Indent++;

					return new Disposable(
						delegate
						{
							Indent--;

							WriteIdent();
							Write("}");
							WriteLine();
						}
					);
				};
			#endregion



			#region Region
			Func<string, IDisposable> Namespace =
				text =>
				{
					WriteIdent();
					WriteBlue("namespace");
					WriteSpace();
					Write(text);
					WriteLine();

					return CodeBlock();
				};
			#endregion

			#region Region
			Func<string, IDisposable> Region =
				text =>
				{
					WriteIdent();
					WriteBlue("#region");
					WriteSpace();
					Write(text);
					WriteLine();

					return new Disposable(
						delegate
						{
							WriteIdent();
							WriteBlue("#endregion");
							WriteLine();
						}
					);
				};
			#endregion


			#region WriteSummary
			Action<string> WriteSummary =
				text =>
				{
					WriteIdent();
					WriteGray("/// <summary>");
					WriteLine();

					WriteIdent();
					WriteGray("/// ");
					WriteGreen(text);
					WriteLine();

					WriteIdent();
					WriteGray("/// </summary>");
					WriteLine();
				};
			#endregion


			#region WriteTypeName
			Action<string> WriteTypeName =
				text =>
				{
					var z = FixTypeName(text.Trim());

					if (CSharpKeywords.Contains(z))
						WriteBlue(z);
					else
						WriteCyan(z);
				};
			#endregion

			Action<string, string> WriteVariableDefinition =
				(TypeName, VariableName) =>
				{
					WriteTypeName(TypeName);
					WriteSpace();
					Write(FixVariableName(VariableName));
				};


			#region IndentLine
			Func<IDisposable> IndentLine =
				 () =>
				 {
					 WriteIdent();

					 return new Disposable(
						 delegate
						 {
							 WriteLine();
						 }
					 );
				 };
			#endregion

			Action<string> WriteAttributeLine =
				Name =>
				{
					using (IndentLine())
					{
						Write("[");
						WriteCyan(Name);
						Write("]");
					}
				};

			#region Conditional
			Func<string, IDisposable> Conditional =
				Expression =>
				{
					WriteGray("#if " + Expression);
					WriteLine();


					return new Disposable(
						delegate
						{
							WriteGray("#endif");
							WriteLine();
						}
					);
				};
			#endregion


			#region WriteCommentLine
			Action<string> WriteCommentLine =
				 text =>
				 {
					 using (IndentLine())
					 {
						 WriteGreen("// " + text);
					 }
				 };
			#endregion


			#region InlineCodeBlock
			Func<IDisposable> InlineCodeBlock =
				() =>
				{
					Write("{");
					WriteSpace();

					return new Disposable(
						delegate
						{
							WriteSpace();
							Write("}");
						}
					);
				};
			#endregion


			#region Parentheses
			Func<IDisposable> Parenthesis =
				 () =>
				 {
					 Write("(");


					 return new Disposable(
						 delegate
						 {
							 Write(")");
						 }
					 );
				 };
			#endregion

			#region Parentheses
			Func<IDisposable> Quotes =
				 () =>
				 {
					 Write("\"");


					 return new Disposable(
						 delegate
						 {
							 Write("\"");
						 }
					 );
				 };
			#endregion

			Action WriteAssignment =
				delegate
				{
					WriteSpace();
					Write("=");
					WriteSpace();
				};


			Action WriteEquals =
				delegate
				{
					WriteSpace();
					Write("==");
					WriteSpace();
				};

			Action WriteInequals =
				delegate
				{
					WriteSpace();
					Write("!=");
					WriteSpace();
				};

			Action<string, string> WriteStaticMethodName =
				(TypeName, MethodName) =>
				{
					WriteCyan(TypeName);
					Write(".");
					Write(MethodName);


				};

			Action<string, string> WriteInstanceMethodName =
				  (VariableName, MethodName) =>
				  {
					  Write(VariableName);
					  Write(".");
					  Write(MethodName);


				  };

			#region DefineType
			Func<TypeInfo, IDisposable> DefineType =
			   i =>
			   {
				   if (i == null)
					   return new Disposable(null);

				   var ns = default(IDisposable);

				   if (!string.IsNullOrEmpty(i.Namespace))
				   {
					   ns = Namespace(i.Namespace);
				   }

				   var re = Region(i.Name);

				   if (!i.NoAttributes)
				   {
					   //using (Conditional("!NoAttributes"))
					   WriteAttributeLine("Script");

					   WriteAttributeLine("CompilerGenerated");
				   }

				   WriteIdent();
				   WriteBlue("public");
				   WriteSpace();

				   if (i.IsSealed)
				   {
					   WriteBlue("sealed");
					   WriteSpace();
				   }

				   if (i.IsAbstract)
				   {
					   WriteBlue("abstract");
					   WriteSpace();
				   }

				   WriteBlue("partial");
				   WriteSpace();

				   if (i.IsInterface)
				   {
					   WriteBlue("interface");
				   }
				   else
				   {
					   WriteBlue("class");

				   }

				   WriteSpace();


				   WriteCyan(i.Name);

				   #region base types
				   var BaseTypeNames = new string[] { }.AsEnumerable();

				   if (i.BaseTypeName != null)
					   BaseTypeNames = BaseTypeNames.Concat(new[] { i.BaseTypeName });

				   if (i.BaseTypeNames != null)
					   BaseTypeNames = BaseTypeNames.Concat(i.BaseTypeNames);

				   var BaseTypeNamesArray = BaseTypeNames.Where(j => !string.IsNullOrEmpty(j)).ToArray();

				   for (int ii = 0; ii < BaseTypeNamesArray.Length; ii++)
				   {
					   if (ii == 0)
					   {
						   WriteSpace();
						   Write(":");
					   }
					   else
					   {
						   Write(",");
					   }

					   WriteSpace();
					   WriteCyan(BaseTypeNamesArray[ii]);
				   }
				   #endregion


				   WriteLine();

				   var c = CodeBlock();

				   if (i.Fields != null)
				   {
					   foreach (var f in i.Fields)
					   {
						   if (!string.IsNullOrEmpty(f.AccessedThroughProperty))
						   {
							   using (IndentLine())
							   {
								   Write("[");
								   WriteCyan("AccessedThroughProperty");

								   using (Parenthesis())
								   using (Quotes())
									   Write(f.AccessedThroughProperty);

								   Write("]");
							   }
						   }

						   using (IndentLine())
						   {
							   if (f.IsPrivate)
							   {
								   WriteBlue("private");
								   WriteSpace();
							   }
							   else
							   {
								   WriteBlue("public");
								   WriteSpace();
							   }

							   if (f.IsReadOnly)
							   {
								   WriteBlue("readonly");
								   WriteSpace();
							   }

							   WriteVariableDefinition(f.TypeName, f.FieldName);

							   if (f.IsProperty)
							   {
								   WriteSpace();
								   using (InlineCodeBlock())
								   {
									   WriteBlue("get");
									   Write(";");
									   WriteSpace();

									   WriteBlue("set");
									   Write(";");
								   }
							   }
							   else
							   {
								   if (!string.IsNullOrEmpty(f.DefaultValue))
								   {
									   WriteAssignment();
									   Write(f.DefaultValue);
								   }

								   Write(";");
							   }
						   }

					   }
				   }

				   return new Disposable(
					delegate
					{
						c.Dispose();
						re.Dispose();

						if (ns != null)
							ns.Dispose();
					}
				);
			   };
			#endregion

			Action<string> UsingNamespace =
				text =>
				{
					WriteIdent();
					WriteBlue("using");
					WriteSpace();
					Write(text);
					Write(";");
					WriteLine();
				};

			var UsingNamespaces = UsingNamespace.AsParamsAction();


			if (Domain != null)
			{

				UsingNamespaces(
					"System",
					"System.Collections.Generic",
					"System.Text",
					"System.Diagnostics",
					"System.Runtime.CompilerServices",
					"ScriptCoreLib.Shared.Nonoba"
				);

				UsingNamespace("ScriptCoreLib");

				WriteLine();

			}

			using (DefineType(Domain))
			{
				var MessagesEnumName = "Messages";

				#region Messages
				using (Region(MessagesEnumName))
				{
					//using (Conditional("!NoAttributes"))
					WriteAttributeLine("Script");

					WriteAttributeLine("CompilerGenerated");

					WriteIdent();
					WriteBlue("public");
					WriteSpace();
					WriteBlue("enum");
					WriteSpace();
					WriteCyan(MessagesEnumName);
					WriteLine();

					using (CodeBlock())
					{
						WriteIdent();
						Write("None");
						WriteAssignment();
						Write("100");
						Write(",");
						WriteLine();

						foreach (var v in r.MethodDefinitions)
						{
							WriteIdent();
							Write(v.Name);
							Write(",");
							WriteLine();
						}
					}
				}
				#endregion

				WriteLine();

				var WithUserArguments_user = new FieldInfo { FieldName = "user", TypeName = "int" };




				Func<ProxyProvider.MethodParametersInfo.ParamInfo, bool> IsUserParameter =
					i => i.Name == WithUserArguments_user.FieldName && i.TypeName == WithUserArguments_user.TypeName;

				var IsNotUserParameter = IsUserParameter.AsNegative();

				Func<ProxyProvider.MethodDefinition, bool> IsUserArguments =
					v => v.Name.StartsWith("User") && v.ParametersInfo.Parameters.Any(IsUserParameter);




				//public partial interface IEventsFromUserToOthers
				//{
				//    event Action<RemoteEvents.TeleportToArguments> TeleportTo;
				//}

				//public partial interface IMessagesFromUserToOthers
				//{
				//    void UserTeleportTo(int user, int x, int y);
				//}

				var MessagesToOthers = from MessageWithoutUser in r.MethodDefinitions
									   where !MessageWithoutUser.Name.StartsWith("User")
									   let MessageWithUserFilter = r.MethodDefinitions.Where(j => j.Name == "User" + MessageWithoutUser.Name)
									   let MessageWithUser = MessageWithUserFilter.FirstOrDefault(IsUserArguments)
									   where MessageWithUser != null
									   select new
									   {
										   MessageWithoutUser,
										   MessageWithUser
									   };

				var MessagesToOthersArray = MessagesToOthers.ToArray();




				var IMessages = new TypeInfo
				{
					IsInterface = true,

					Name = "IMessages"
				};

				var IEvents = new TypeInfo
				{
					IsInterface = true,

					Name = "IEvents"
				};


				// client -> server -> other clients
				// DoMyProcedure(...)
				// UserDoMyProcedure(..., int user, ...)
				var WithUserArguments =
					new TypeInfo
					{
						IsSealed = false,
						IsAbstract = true,
						Name = "WithUserArguments",
						Fields = new[]
                                 {
                                     WithUserArguments_user
                                 }.ToArray()
					};

				var WithUserArgumentsRouter_RemoveDelegates = "RemoveDelegates";
				var WithUserArgumentsRouter_CombineDelegates = "CombineDelegates";
				var WithUserArgumentsRouter_MulticastTarget = new FieldInfo { FieldName = "Target", TypeName = IMessages.Name };
				var WithUserArgumentsRouter_Multicast =
					new TypeInfo
					{
						IsSealed = true,
						Name = "WithUserArgumentsRouter_Broadcast",
						BaseTypeName = WithUserArguments.Name,
						Fields = new[]
                                     {
                                         WithUserArgumentsRouter_MulticastTarget
                                     }.ToArray()
					};

				var WithUserArgumentsRouter_SinglecastViewTarget = new FieldInfo { FieldName = "Target", TypeName = IMessages.Name };
				var WithUserArgumentsRouter_SinglecastView =
					new TypeInfo
					{
						IsSealed = true,
						Name = "WithUserArgumentsRouter_SinglecastView",
						BaseTypeName = WithUserArguments.Name,
						Fields = new[]
                                     {
                                         WithUserArgumentsRouter_SinglecastViewTarget
                                     }.ToArray()
					};

				var WithUserArgumentsRouter_SinglecastTarget = new FieldInfo { FieldName = "Target", TypeName = "System.Converter<int, IMessages>" };
				var WithUserArgumentsRouter_Singlecast =
					new TypeInfo
					{
						IsSealed = true,
						Name = "WithUserArgumentsRouter_Singlecast",
						BaseTypeName = WithUserArguments.Name,
						Fields = new[]
						 {
							 WithUserArgumentsRouter_SinglecastTarget
						 }.ToArray()
					};


				var RemoteEvents_DispatchTable = new FieldInfo { FieldName = "DispatchTable", TypeName = "Dictionary<" + MessagesEnumName + ", Action<IDispatchHelper>>", IsPrivate = true, IsReadOnly = true };
				var RemoteEvents_DispatchTableDelegates = new FieldInfo { FieldName = "DispatchTableDelegates", TypeName = "Dictionary<" + MessagesEnumName + ", Converter<object, Delegate>>", IsPrivate = true, IsReadOnly = true };
				var RemoteEvents_BroadcastRouter = new FieldInfo
				{
					FieldName = "_BroadcastRouter",
					TypeName = WithUserArgumentsRouter_Multicast.Name,
					IsPrivate = true,
					AccessedThroughProperty = "BroadcastRouter"
				};

				var RemoteEvents_SinglecastRouter = new FieldInfo
				{
					FieldName = "_SinglecastRouter",
					TypeName = WithUserArgumentsRouter_Singlecast.Name,
					IsPrivate = true,
					AccessedThroughProperty = "SinglecastRouter"
				};

				var RemoteEvents =
					new TypeInfo
					{
						IsSealed = true,
						Name = "RemoteEvents",
						BaseTypeNames = new[] { IEvents.Name/*, IPairedEvents.WithoutUser.Name, IPairedEvents.WithUser.Name*/ },
						Fields = new[]
                                {
                                    RemoteEvents_DispatchTable,
                                    RemoteEvents_DispatchTableDelegates,
                                    RemoteEvents_BroadcastRouter,
									RemoteEvents_SinglecastRouter
                                }
					};

				var RemoteMessages_Send = new FieldInfo { FieldName = "Send", TypeName = "Action<SendArguments>" };
				var RemoteMessages_VirtualTargets = new FieldInfo { FieldName = "VirtualTargets", TypeName = "Func<IEnumerable<IMessages>>" };
				var RemoteMessages =
					 new TypeInfo
						{
							IsSealed = true,
							Name = "RemoteMessages",
							BaseTypeNames = new[] { IMessages.Name/*, IPairedMessages.WithoutUser.Name, IPairedMessages.WithUser.Name*/ },
							Fields = new[]
							{
								RemoteMessages_Send,
								RemoteMessages_VirtualTargets
							}
						};

				using (DefineType(IMessages))
				{
				}

				using (DefineType(IEvents))
				{
					foreach (var v in r.MethodDefinitions)
					{
						using (IndentLine())
						{
							WriteBlue("event");
							WriteSpace();
							WriteCyan("Action<" + RemoteEvents.Name + "." + v.Name + "Arguments>");
							WriteSpace();
							Write(v.Name);
							Write(";");
						}
					}
				}





				WriteLine();

				#region RemoteMessages
				using (DefineType(RemoteMessages))
				{

					#region SendArguments
					using (DefineType(
							new TypeInfo
							{
								IsSealed = true,
								Name = "SendArguments",
								Fields = new[]
                            {
                                new FieldInfo { FieldName = "i", TypeName = MessagesEnumName },
                                new FieldInfo { FieldName = "args", TypeName = "object[]" },
                            }
							}
						))
					{

					}
					#endregion

					foreach (var v in r.MethodDefinitions)
					{
						//public void TeleportTo(int x, int y)

						#region signature
						using (IndentLine())
						{

							WriteBlue("public");
							WriteSpace();

							WriteBlue("void");
							WriteSpace();


							Write(v.Name);

							using (Parenthesis())
								v.ParametersInfo.Parameters.ForEach(
								 (p, k) =>
								 {
									 if (k > 0)
									 {
										 Write(",");
										 WriteSpace();
									 }

									 WriteVariableDefinition(p.TypeName, p.Name);
								 }
							   );

						}
						#endregion

						//{
						//    Send(new SendArguments { i = Messages.TeleportTo, args = new object[] { x, y } });
						//}

						using (CodeBlock())
						{
							#region Send if availible
							using (IndentLine())
							{
								WriteKeywordSpace("if");
								using (Parenthesis())
								{
									WriteBlue("this");
									Write(".");
									Write(RemoteMessages_Send.FieldName);
									WriteInequals();
									WriteBlue("null");
								}
							}
							using (CodeBlock())
							{

								#region Send(...)
								var SingleArray = v.ParametersInfo.SingleArrayParameter;
								var SingleObjectArray = SingleArray != null ? SingleArray.ElementTypeName == "object" : false;

								var SignleArrayConverted = SingleArray != null;

								// we should not try to convert (object[])
								SignleArrayConverted &= !SingleObjectArray;

								if (v.ParametersInfo.Parameters.Length > 1)
									if (SingleArray == null)
									{

										var AllPriorParametersAreNotArrays = true;

										for (int i = 0; i < v.ParametersInfo.Parameters.Length - 1; i++)
										{
											if (v.ParametersInfo.Parameters[i].IsArray)
												AllPriorParametersAreNotArrays = false;
										}

										if (AllPriorParametersAreNotArrays)
										{
											if (v.ParametersInfo.Parameters.Last().IsArray)
											{
												SingleArray = v.ParametersInfo.Parameters.Last();
												SignleArrayConverted = true;
											}
										}
									}

								if (SignleArrayConverted)
								{
									using (IndentLine())
									{
										WriteBlue("var");
										WriteSpace();
										Write("args");
										WriteAssignment();
										WriteBlue("new");
										WriteSpace();
										WriteBlue("object");
										Write("[");
										Write(SingleArray.Name);
										Write(".");
										Write("Length");
										WriteSpace();
										Write("+");
										WriteSpace();
										Write("" + (v.ParametersInfo.Parameters.Length - 1));
										Write("]");
										Write(";");
									}

									for (int i = 0; i < v.ParametersInfo.Parameters.Length - 1; i++)
									{
										using (IndentLine())
										{
											Write("args");
											Write("[");
											Write("" + i);
											Write("]");
											WriteAssignment();
											Write(v.ParametersInfo.Parameters[i].Name);
											Write(";");
										}
									}

									using (IndentLine())
									{
										WriteStaticMethodName("Array", "Copy");

										using (Parenthesis())
										{
											Write(SingleArray.Name);

											Write(",");
											WriteSpace();
											Write("0");

											Write(",");
											WriteSpace();
											Write("args");

											Write(",");
											WriteSpace();
											Write("" + (v.ParametersInfo.Parameters.Length - 1));

											Write(",");
											WriteSpace();
											WriteInstanceMethodName(SingleArray.Name, "Length");
										}

										Write(";");
									}
								}

								using (IndentLine())
								{
									WriteBlack(RemoteMessages_Send.FieldName);
									using (Parenthesis())
									{
										WriteBlue("new");
										WriteSpace();
										WriteCyan("SendArguments");
										WriteSpace();

										using (InlineCodeBlock())
										{
											Write("i");
											WriteAssignment();

											WriteCyan(MessagesEnumName);
											Write(".");
											Write(v.Name);

											Write(",");
											WriteSpace();

											Write("args");
											WriteAssignment();

											if (SignleArrayConverted)
											{
												Write("args");
											}
											else if (SingleObjectArray)
											{
												// the only parameter is object[]
												Write(SingleArray.Name);
											}
											else
											{
												// all parameters are non arrays

												WriteBlue("new");
												WriteSpace();
												WriteBlue("object");
												Write("[]");
												WriteSpace();

												using (InlineCodeBlock())
												{
													for (int k = 0; k < v.ParametersInfo.Parameters.Length; k++)
													{
														if (k > 0)
														{
															Write(",");
															WriteSpace();
														}

														Write(v.ParametersInfo.Parameters[k].Name);
													}
												}
											}
										}
									}
									Write(";");

								}
								#endregion

							}
							#endregion

							// if there are other targets, invoke them too
							using (IndentLine())
							{
								WriteKeywordSpace("if");
								using (Parenthesis())
								{
									WriteBlue("this");
									Write(".");
									Write(RemoteMessages_VirtualTargets.FieldName);
									WriteInequals();
									WriteBlue("null");
								}
							}
							using (CodeBlock())
							{
								const string Local_Target__ = "Target__";
								using (IndentLine())
								{
									WriteKeywordSpace("foreach");
									using (Parenthesis())
									{
										WriteKeywordSpace("var");
										Write(Local_Target__);
										WriteSpace();
										WriteKeywordSpace("in");
										WriteBlue("this");
										Write(".");
										Write(RemoteMessages_VirtualTargets.FieldName);
										Write("()");
									}
								}
								using (CodeBlock())
								using (IndentLine())
								{
									Write(Local_Target__);
									Write(".");
									Write(v.Name);
									using (Parenthesis())
									{
										v.ParametersInfo.Parameters.ForEach(
											(arg, index) =>
											{
												if (index > 0)
													Write(", ");

												Write(arg.Name);
											}
										);
									};
									Write(";");
								}
							}
						}
					}
				}
				#endregion


				WriteLine();










				#region RemoteEvents
				using (DefineType(RemoteEvents))
				{
					var KnownConverters = new Dictionary<string, string>
                    {
                        { "int", "GetInt32" },
                        { "double", "GetDouble" },
                        { "string", "GetString" },
                        
                        { "int[]", "GetInt32Array" },
                        { "double[]", "GetDoubleArray" },
                        { "string[]", "GetStringArray" },

						//{ "object[]", "GetArray" },

						{ "byte[]", "GetMemoryStream" },

                    };



					#region DispatchHelper
					using (DefineType(
							new TypeInfo
							{
								IsSealed = false,
								Name = "DispatchHelper",
								Fields =
									KnownConverters.AsEnumerable().Select(
										i => new FieldInfo { FieldName = i.Value, TypeName = "Converter<uint, " + i.Key + ">", IsProperty = true }
									).ToArray()
							}
						))
					{
					}
					#endregion

					// public bool Dispatch(Messages e, DispatchHelper h)
					//{
					//    if (!DispatchTable.ContainsKey(e))
					//        return false;

					//    DispatchTable[e](h);

					//    return true;
					//}

					#region Dispatch
					using (IndentLine())
					{
						WriteBlue("public");
						WriteSpace();

						WriteBlue("bool");
						WriteSpace();

						Write("Dispatch");

						using (Parenthesis())
						{
							WriteVariableDefinition(MessagesEnumName, "e");
							Write(",");
							WriteSpace();
							WriteVariableDefinition("IDispatchHelper", "h");

						}
					}

					using (CodeBlock())
					{
						using (IndentLine()) Write("if (!DispatchTableDelegates.ContainsKey(e)) return false;");
						using (IndentLine()) Write("if (DispatchTableDelegates[e](null) == null) return false;");
						using (IndentLine()) Write("if (!DispatchTable.ContainsKey(e)) return false;");
						using (IndentLine()) Write("DispatchTable[e](h);");
						using (IndentLine()) Write("return true;");
					}
					#endregion


					#region WithUserArguments



					using (DefineType(WithUserArguments))
					{
					}

					#endregion




					#region WithUserArgumentsRouter_Multicast
					using (DefineType(WithUserArgumentsRouter_Multicast))
					{
						#region Automatic Event Routing
						WriteLine();
						using (Region("Automatic Event Routing"))
						{
							#region CombineDelegates
							using (IndentLine())
							{
								WriteKeywordSpace("public");
								WriteKeywordSpace("void");

								Write(WithUserArgumentsRouter_CombineDelegates);

								using (Parenthesis())
								{
									// remove User prefix
									WriteVariableDefinition(IEvents.Name, "value");
								}
							}

							Action<ProxyProvider.MethodDefinition, Action> WriteEventRouting =
								(Method, WriteOperation) =>
								{
									// some user events really do not have their non-user counterpart

									var NonUserEventName = Method.Name.Substring(4);

									using (IndentLine())
									{
										WriteBlue("value");
										Write(".");
										Write(NonUserEventName);
										WriteSpace();
										WriteOperation();
										WriteSpace();

										Write("this");
										Write(".");
										Write(Method.Name);
										Write(";");
									}

								};

							using (CodeBlock())
							{
								//WriteEventRouting.FixLastParam(() => Write("+="));


								foreach (var v in MessagesToOthersArray)
								{
									WriteEventRouting(v.MessageWithUser, () => Write("+="));
								}
							}
							#endregion


							WriteLine();

							#region RemoveDelegates
							using (IndentLine())
							{
								WriteBlue("public");
								WriteSpace();

								WriteBlue("void");
								WriteSpace();

								Write(WithUserArgumentsRouter_RemoveDelegates);

								using (Parenthesis())
								{
									// remove User prefix
									WriteVariableDefinition(IEvents.Name, "value");
								}


							}

							using (CodeBlock())
							{
								foreach (var v in MessagesToOthersArray)
								{
									WriteEventRouting(v.MessageWithUser, () => Write("-="));
								}
							}
							#endregion

						}
						WriteLine();
						#endregion

						#region Routing
						using (Region("Routing"))
						{
							foreach (var _v in MessagesToOthersArray)
							{
								var v = _v.MessageWithUser;

								//public void UserTeleportTo(TeleportToArguments e)
								//{
								//    Target.UserTeleportTo(this.user, e.x, e.y);
								//}

								using (IndentLine())
								{
									WriteKeywordSpace("public");
									WriteKeywordSpace("void");

									Write(v.Name);

									using (Parenthesis())
									{
										// remove User prefix
										WriteVariableDefinition(_v.MessageWithoutUser.Name + "Arguments", "e");
									}
								}

								using (CodeBlock())
								using (IndentLine())
								{
									//WriteBlue("return");
									//WriteSpace();

									Write(WithUserArgumentsRouter_MulticastTarget.FieldName);
									Write(".");
									Write(v.Name);

									using (Parenthesis())
									{
										for (int i = 0; i < v.ParametersInfo.Parameters.Length; i++)
										{
											if (i > 0)
												Write(", ");

											var p = v.ParametersInfo.Parameters[i];

											if (p.Name == WithUserArguments_user.FieldName)
											{
												WriteBlue("this");
											}
											else
											{
												Write("e");
											}
											Write(".");
											Write(p.Name);
										}
									}

									Write(";");
								}

								//WriteCommentLine(v.Name);
							}
						}
						#endregion


					}
					#endregion

					#region WithUserArgumentsRouter_SinglecastView
					using (DefineType(WithUserArgumentsRouter_SinglecastView))
					{
						#region Routing
						using (Region("Routing"))
						{
							foreach (var v in r.MethodDefinitions.Where(IsUserArguments))
							{
								//public void UserPlayerAdvertise(UserPlayerAdvertiseArguments e)
								//{
								//    this.Target(e.user).UserPlayerAdvertise(this.user, e.name);
								//}
								const string Local_Arguments = "e";

								using (IndentLine())
								{
									WriteKeywordSpace("public");
									WriteKeywordSpace("void");

									Write(v.Name);

									using (Parenthesis())
									{
										for (int i = 1; i < v.ParametersInfo.Parameters.Length; i++)
										{
											if (i > 1)
												Write(", ");
											var p = v.ParametersInfo.Parameters[i];

											WriteVariableDefinition(p.TypeName, p.Name);
										}
									}
								}

								using (CodeBlock())
								{
									using (IndentLine())
									{
										WriteBlue("this");
										Write(".");
										Write(WithUserArgumentsRouter_SinglecastTarget.FieldName);
										Write(".");
										Write(v.Name);
										using (Parenthesis())
										{
											for (int i = 0; i < v.ParametersInfo.Parameters.Length; i++)
											{
												if (i > 0)
													Write(", ");

												var p = v.ParametersInfo.Parameters[i];

												if (p.Name == WithUserArguments_user.FieldName)
												{
													WriteBlue("this");
													Write(".");

												}

												Write(p.Name);
											}
										}
										Write(";");
									}
								}

								using (IndentLine())
								{
									WriteKeywordSpace("public");
									WriteKeywordSpace("void");

									Write(v.Name);

									using (Parenthesis())
									{
										WriteVariableDefinition(v.Name + "Arguments", Local_Arguments);
									}
								}

								using (CodeBlock())
								{
									using (IndentLine())
									{
										WriteBlue("this");
										Write(".");
										Write(WithUserArgumentsRouter_SinglecastTarget.FieldName);
										Write(".");
										Write(v.Name);
										using (Parenthesis())
										{
											for (int i = 0; i < v.ParametersInfo.Parameters.Length; i++)
											{
												if (i > 0)
													Write(", ");

												var p = v.ParametersInfo.Parameters[i];

												if (p.Name == WithUserArguments_user.FieldName)
												{
													WriteBlue("this");
												}
												else
												{
													Write("e");
												}
												Write(".");
												Write(p.Name);
											}
										}
										Write(";");
									}
								}
							}
						}
						#endregion


					}
					#endregion

					#region WithUserArgumentsRouter_Singlecast
					using (DefineType(WithUserArgumentsRouter_Singlecast))
					{
						#region Automatic Event Routing
						WriteLine();
						using (Region("Automatic Event Routing"))
						{
							#region CombineDelegates
							using (IndentLine())
							{
								WriteKeywordSpace("public");
								WriteKeywordSpace("void");

								Write(WithUserArgumentsRouter_CombineDelegates);

								using (Parenthesis())
								{
									// remove User prefix
									WriteVariableDefinition(IEvents.Name, "value");
								}
							}

							Action<ProxyProvider.MethodDefinition, Action> WriteEventRouting =
								(Method, WriteOperation) =>
								{
									// some user events really do not have their non-user counterpart

									using (IndentLine())
									{
										WriteBlue("value");
										Write(".");
										Write(Method.Name);
										WriteSpace();
										WriteOperation();
										WriteSpace();

										Write("this");
										Write(".");
										Write(Method.Name);
										Write(";");
									}

								};

							using (CodeBlock())
							{
								foreach (var v in r.MethodDefinitions.Where(IsUserArguments))
								{
									WriteEventRouting(v, () => Write("+="));
								}
							}
							#endregion


							WriteLine();

							#region RemoveDelegates
							using (IndentLine())
							{
								WriteBlue("public");
								WriteSpace();

								WriteBlue("void");
								WriteSpace();

								Write(WithUserArgumentsRouter_RemoveDelegates);

								using (Parenthesis())
								{
									WriteVariableDefinition(IEvents.Name, "value");
								}


							}

							using (CodeBlock())
							{
								foreach (var v in r.MethodDefinitions.Where(IsUserArguments))
								{
									WriteEventRouting(v, () => Write("-="));
								}
							}
							#endregion

						}
						WriteLine();
						#endregion

						#region Routing
						using (Region("Routing"))
						{
							foreach (var v in r.MethodDefinitions.Where(IsUserArguments))
							{
								//public void UserPlayerAdvertise(UserPlayerAdvertiseArguments e)
								//{
								//    this.Target(e.user).UserPlayerAdvertise(this.user, e.name);
								//}
								const string Local_Arguments = "e";


								using (IndentLine())
								{
									WriteKeywordSpace("public");
									WriteKeywordSpace("void");

									Write(v.Name);

									using (Parenthesis())
									{
										WriteVariableDefinition(v.Name + "Arguments", Local_Arguments);
									}
								}

								using (CodeBlock())
								{
									const string Local_target = "_target";

									using (IndentLine())
									{
										WriteBlue("var");
										WriteSpace();
										Write(Local_target);
										WriteAssignment();
										WriteBlue("this");
										Write(".");
										Write(WithUserArgumentsRouter_SinglecastTarget.FieldName);
										using (Parenthesis())
										{
											Write(Local_Arguments);
											Write(".");
											Write("user");
										}
										Write(";");
									}

									using (IndentLine())
									{
										WriteKeywordSpace("if");

										using (Parenthesis())
										{
											Write(Local_target);
											WriteEquals();
											WriteBlue("null");
										}

										WriteSpace();

										WriteBlue("return");
										Write(";");
									}

									using (IndentLine())
									{
										Write(Local_target);
										Write(".");
										Write(v.Name);
										using (Parenthesis())
										{
											for (int i = 0; i < v.ParametersInfo.Parameters.Length; i++)
											{
												if (i > 0)
													Write(", ");

												var p = v.ParametersInfo.Parameters[i];

												if (p.Name == WithUserArguments_user.FieldName)
												{
													WriteBlue("this");
												}
												else
												{
													Write("e");
												}
												Write(".");
												Write(p.Name);
											}
										}
										Write(";");
									}
								}
							}
						}
						#endregion

					}
					#endregion


					#region events
					foreach (var v in r.MethodDefinitions)
					{
						var SelectedArguments = default(TypeInfo);

						if (IsUserArguments(v))
						{
							SelectedArguments = new TypeInfo
							{
								IsSealed = true,
								Name = v.Name + "Arguments",
								BaseTypeName = WithUserArguments.Name,
								Fields = v.ParametersInfo.Parameters.Where(IsNotUserParameter).Select(i =>
									new FieldInfo { FieldName = i.Name, TypeName = i.TypeName }
								).ToArray()
							};
						}
						else
						{
							SelectedArguments = new TypeInfo
							{
								IsSealed = true,
								Name = v.Name + "Arguments",
								Fields = v.ParametersInfo.Parameters.Select(i =>
									new FieldInfo { FieldName = i.Name, TypeName = i.TypeName }
								).ToArray()
							};
						}

						#region ~Arguments
						using (DefineType(SelectedArguments))
						{
							// ToString

							WriteAttributeLine("DebuggerHidden");

							using (IndentLine())
							{
								WriteBlue("public");
								WriteSpace();
								WriteBlue("override");
								WriteSpace();
								WriteBlue("string");
								WriteSpace();
								Write("ToString");
								Write("()");
							}

							using (CodeBlock())
							using (IndentLine())
							{


								WriteBlue("return");
								WriteSpace();
								WriteBlue("new");
								WriteSpace();
								WriteCyan("StringBuilder");
								Write("()");

								for (int i = 0; i < v.ParametersInfo.Parameters.Length; i++)
								{
									var IsFirst = i == 0;
									var IsLast = i == v.ParametersInfo.Parameters.Length - 1;

									var p = v.ParametersInfo.Parameters[i];

									Write(".");
									Write("Append");

									using (Parenthesis())
									using (Quotes())
									{
										if (IsFirst)
											Write("{ ");
										else
											Write(", ");

										Write(p.Name);

										WriteAssignment();
									}

									Write(".");
									Write("Append");

									using (Parenthesis())
									{
										WriteBlue("this");
										Write(".");
										Write(p.Name);
									}

									if (IsLast)
									{
										Write(".");
										Write("Append");

										using (Parenthesis())
										using (Quotes())
										{
											Write(" }");
										}

									}
								}

								Write(".");
								Write("ToString");
								Write("()");
								Write(";");

							}

							//[DebuggerHidden]
							//public override string ToString()
							//{
							//    StringBuilder builder = new StringBuilder();
							//    builder.Append("{ bullets = ");
							//    builder.Append(this.<bullets>i__Field);
							//    builder.Append(", runaways = ");
							//    builder.Append(this.<runaways>i__Field);
							//    builder.Append(", gore = ");
							//    builder.Append(this.<gore>i__Field);
							//    builder.Append(", score = ");
							//    builder.Append(this.<score>i__Field);
							//    builder.Append(" }");
							//    return builder.ToString();
							//}





						}
						#endregion

						// public event Action<TeleportToArguments> TeleportTo;

						using (IndentLine())
						{
							WriteBlue("public");
							WriteSpace();
							WriteBlue("event");
							WriteSpace();
							WriteVariableDefinition("Action<" + v.Name + "Arguments" + ">", v.Name);
							Write(";");
						}

					}
					#endregion


					#region ctor
					using (IndentLine())
					{
						WriteBlue("public");
						WriteSpace();

						Write("RemoteEvents");

						using (Parenthesis())
						{
						}
					}
					using (CodeBlock())
					{
						#region DispatchTable
						using (IndentLine())
						{
							Write("DispatchTable");
							WriteAssignment();
							WriteBlue("new");
							WriteSpace();
							WriteCyan("Dictionary<" + MessagesEnumName + ", Action<IDispatchHelper>>");
						}

						Indent += 2;

						using (CodeBlock())
						{
							foreach (var v in r.MethodDefinitions)
							{
								using (IndentLine())
								{
									using (InlineCodeBlock())
									{
										WriteCyan(MessagesEnumName);
										Write(".");
										Write(v.Name);

										Write(",");
										WriteSpace();


										Write("e => ");

										using (InlineCodeBlock())
										{

											Write(v.Name);

											using (Parenthesis())
											{
												WriteBlue("new");
												WriteSpace();

												WriteCyan(v.Name + "Arguments");
												WriteSpace();

												using (InlineCodeBlock())
												{
													v.ParametersInfo.Parameters.ForEach(
														(p, k) =>
														{
															if (k > 0)
															{
																Write(",");
																WriteSpace();
															}


															Write(p.Name);
															WriteAssignment();
															Write("e");
															Write(".");



															Write(KnownConverters[p.TypeName]);

															using (Parenthesis())
																Write("" + k);

														}
													 );
												}


											}

											Write(";");
										}
									}

									Write(",");
								}

							}
						}

						Indent -= 2;

						using (IndentLine())
							Write(";");

						#endregion

						#region DispatchTableDelegates
						using (IndentLine())
						{
							Write("DispatchTableDelegates");
							WriteAssignment();
							WriteBlue("new");
							WriteSpace();
							WriteCyan(RemoteEvents_DispatchTableDelegates.TypeName);
						}
						Indent += 2;
						using (CodeBlock())
						{
							foreach (var v in r.MethodDefinitions)
							{
								using (IndentLine())
								{
									using (InlineCodeBlock())
									{
										WriteCyan(MessagesEnumName);
										Write(".");
										Write(v.Name);

										Write(",");
										WriteSpace();

										Write("e => ");

										Write(v.Name);
									}

									Write(",");
								}

							}
						}
						Indent -= 2;
						using (IndentLine())
							Write(";");

						#endregion

					}
					#endregion


					#region BroadcastRouter { get; set; }
					using (IndentLine())
					{
						WriteBlue("public");
						WriteSpace();
						WriteVariableDefinition(
							RemoteEvents_BroadcastRouter.TypeName,
							RemoteEvents_BroadcastRouter.AccessedThroughProperty
						);
					}



					using (CodeBlock())
					{
						#region get
						WriteAttributeLine("DebuggerNonUserCode");

						using (IndentLine())
							WriteBlue("get");

						using (CodeBlock())
						using (IndentLine())
						{
							WriteBlue("return");
							WriteSpace();
							WriteBlue("this");
							Write(".");
							Write(RemoteEvents_BroadcastRouter.FieldName);
							Write(";");
						}
						#endregion

						#region set
						WriteAttributeLine("DebuggerNonUserCode");

						using (IndentLine())
						{
							Write("[");
							WriteCyan("MethodImpl");

							using (Parenthesis())
							{
								WriteCyan("MethodImplOptions");
								Write(".");
								Write("Synchronized");
							}

							Write("]");
						}

						using (IndentLine())
							WriteBlue("set");

						using (CodeBlock())
						{
							// do like the vb does



							#region remove
							using (IndentLine())
							{
								WriteBlue("if");
								using (Parenthesis())
								{
									Write(RemoteEvents_BroadcastRouter.FieldName);
									WriteSpace();
									Write("!=");
									WriteSpace();
									WriteBlue("null");
								}
							}
							using (CodeBlock())
							{
								//_X.C -= action;
								//_X.B -= action2;
								//_X.A -= action3;

								using (IndentLine())
								{
									Write(RemoteEvents_BroadcastRouter.FieldName);
									Write(".");
									Write(WithUserArgumentsRouter_RemoveDelegates);

									using (Parenthesis())
									{
										WriteBlue("this");
									}
									Write(";");
								}


							}
							#endregion

							using (IndentLine())
							{
								Write(RemoteEvents_BroadcastRouter.FieldName);
								WriteAssignment();
								WriteBlue("value");
								Write(";");
							}

							#region add
							using (IndentLine())
							{
								WriteBlue("if");
								using (Parenthesis())
								{
									Write(RemoteEvents_BroadcastRouter.FieldName);
									WriteSpace();
									Write("!=");
									WriteSpace();
									WriteBlue("null");
								}
							}
							using (CodeBlock())
							{
								//_X.C += action;
								//_X.B += action2;
								//_X.A += action3;

								using (IndentLine())
								{
									Write(RemoteEvents_BroadcastRouter.FieldName);
									Write(".");
									Write(WithUserArgumentsRouter_CombineDelegates);

									using (Parenthesis())
									{
										WriteBlue("this");
									}
									Write(";");
								}


							}
							#endregion


						}

						#endregion

					}
					#endregion

					#region SinglecastRouter { get; set; }
					using (IndentLine())
					{
						WriteBlue("public");
						WriteSpace();
						WriteVariableDefinition(
							RemoteEvents_SinglecastRouter.TypeName,
							RemoteEvents_SinglecastRouter.AccessedThroughProperty
						);
					}



					using (CodeBlock())
					{
						#region get
						WriteAttributeLine("DebuggerNonUserCode");

						using (IndentLine())
							WriteBlue("get");

						using (CodeBlock())
						using (IndentLine())
						{
							WriteBlue("return");
							WriteSpace();
							WriteBlue("this");
							Write(".");
							Write(RemoteEvents_SinglecastRouter.FieldName);
							Write(";");
						}
						#endregion

						#region set
						WriteAttributeLine("DebuggerNonUserCode");

						using (IndentLine())
						{
							Write("[");
							WriteCyan("MethodImpl");

							using (Parenthesis())
							{
								WriteCyan("MethodImplOptions");
								Write(".");
								Write("Synchronized");
							}

							Write("]");
						}

						using (IndentLine())
							WriteBlue("set");

						using (CodeBlock())
						{
							// do like the vb does



							#region remove
							using (IndentLine())
							{
								WriteBlue("if");
								using (Parenthesis())
								{
									Write(RemoteEvents_SinglecastRouter.FieldName);
									WriteSpace();
									Write("!=");
									WriteSpace();
									WriteBlue("null");
								}
							}
							using (CodeBlock())
							{
								//_X.C -= action;
								//_X.B -= action2;
								//_X.A -= action3;

								using (IndentLine())
								{
									Write(RemoteEvents_SinglecastRouter.FieldName);
									Write(".");
									Write(WithUserArgumentsRouter_RemoveDelegates);

									using (Parenthesis())
									{
										WriteBlue("this");
									}
									Write(";");
								}


							}
							#endregion

							using (IndentLine())
							{
								Write(RemoteEvents_SinglecastRouter.FieldName);
								WriteAssignment();
								WriteBlue("value");
								Write(";");
							}

							#region add
							using (IndentLine())
							{
								WriteBlue("if");
								using (Parenthesis())
								{
									Write(RemoteEvents_SinglecastRouter.FieldName);
									WriteSpace();
									Write("!=");
									WriteSpace();
									WriteBlue("null");
								}
							}
							using (CodeBlock())
							{
								//_X.C += action;
								//_X.B += action2;
								//_X.A += action3;

								using (IndentLine())
								{
									Write(RemoteEvents_SinglecastRouter.FieldName);
									Write(".");
									Write(WithUserArgumentsRouter_CombineDelegates);

									using (Parenthesis())
									{
										WriteBlue("this");
									}
									Write(";");
								}


							}
							#endregion


						}

						#endregion

					}
					#endregion
				}
				#endregion


				#region bridge

				const string Bridge_VirtualLatencyDefaultImplemenetation = "VirtualLatencyDefaultImplemenetation";
				const string Bridge_VirtualLatency = "VirtualLatency";
				const string Bridge = "Bridge";

				using (DefineType(
					new TypeInfo
					{
						Name = Bridge,
						Fields = new[]
						{
							new FieldInfo { TypeName = "Action<Action>", FieldName = Bridge_VirtualLatency }
						},
						BaseTypeNames = RemoteEvents.BaseTypeNames.Concat(RemoteMessages.BaseTypeNames).ToArray()
					}))
				{
					#region ctor
					using (IndentLine())
					{
						WriteBlue("public");
						WriteSpace();
						Write(Bridge);

						using (Parenthesis())
						{
						}

					}

					using (CodeBlock())
					{
						using (IndentLine())
						{
							WriteBlue("this");
							Write(".");
							Write(Bridge_VirtualLatency);
							WriteAssignment();
							Write(Bridge_VirtualLatencyDefaultImplemenetation);
							Write(";");
						}
					}
					#endregion

					#region Bridge_VirtualLatencyDefaultImplemenetation
					using (IndentLine())
					{
						WriteBlue("public");
						WriteSpace();
						WriteBlue("void");
						WriteSpace();
						Write(Bridge_VirtualLatencyDefaultImplemenetation);

						using (Parenthesis())
						{
							WriteVariableDefinition("Action", "e");
						}

					}

					using (CodeBlock())
					{
						using (IndentLine())
						{
							Write("e");
							using (Parenthesis())
							{
							}
							Write(";");
						}
					}
					#endregion

					foreach (var v in r.MethodDefinitions)
					{
						using (IndentLine())
						{
							WriteBlue("public");
							WriteSpace();
							WriteBlue("event");
							WriteSpace();
							WriteVariableDefinition("Action<" + RemoteEvents.Name + "." + v.Name + "Arguments" + ">", v.Name);
							Write(";");
						}

						#region WriteExplicitImplementation
						Action<TypeInfo, Action> WriteExplicitImplementation =
							(DeclaringType, Code) =>
							{
								using (IndentLine())
								{

									WriteBlue("void");
									WriteSpace();

									WriteCyan(DeclaringType.Name);
									Write(".");
									Write(v.Name);

									using (Parenthesis())
										v.ParametersInfo.Parameters.ForEach(
										 (p, k) =>
										 {
											 if (k > 0)
											 {
												 Write(",");
												 WriteSpace();
											 }

											 WriteVariableDefinition(p.TypeName, p.Name);
										 }
									   );


								}
								using (CodeBlock())
								{
									Code();
								}
							};
						#endregion


						WriteExplicitImplementation(IMessages,
							delegate
							{
								using (IndentLine())
								{
									WriteBlue("if");

									using (Parenthesis())
									{
										Write(v.Name);
										WriteSpace();
										Write("==");
										WriteSpace();
										WriteBlue("null");
									}

									WriteSpace();
									WriteBlue("return");
									Write(";");
								}

								#region var v;
								using (IndentLine())
								{
									WriteBlue("var");
									WriteSpace();
									Write("v");
									WriteAssignment();

									WriteBlue("new");
									WriteSpace();
									WriteCyan(RemoteEvents.Name);
									Write(".");
									WriteCyan(v.Name + "Arguments");
									WriteSpace();

									using (InlineCodeBlock())
									{
										v.ParametersInfo.Parameters.ForEach(
											(p, k) =>
											{
												if (k > 0)
												{
													Write(",");
													WriteSpace();
												}


												Write(p.Name);
												WriteAssignment();
												Write(p.Name);


											}
										);

									}

									Write(";");
								}
								#endregion

								using (IndentLine())
								{
									WriteBlue("this");
									Write(".");
									Write(Bridge_VirtualLatency);
									using (Parenthesis())
									{
										Write("() => ");

										WriteBlue("this");
										Write(".");
										Write(v.Name);

										using (Parenthesis())
										{
											Write("v");
										}
									}

									Write(";");

								}
							}
						);

						#region RedirectToIMessages
						Action RedirectToIMessages =
							delegate
							{
								using (IndentLine())
								{
									using (Parenthesis())
									{
										using (Parenthesis())
											WriteCyan(IMessages.Name);
										WriteBlue("this");
									}
									Write(".");
									Write(v.Name);
									using (Parenthesis())
										v.ParametersInfo.Parameters.ForEach(
										 (p, k) =>
										 {
											 if (k > 0)
											 {
												 Write(",");
												 WriteSpace();
											 }

											 Write(p.Name);
										 }
									   );

									Write(";");
								}

							};
						#endregion

						//if (MessagesToOthersArray.Any(i => i.MessageWithUser.Name == v.Name))
						//    WriteExplicitImplementation(IPairedMessages.WithUser, RedirectToIMessages);

						//if (MessagesToOthersArray.Any(i => i.MessageWithoutUser.Name == v.Name))
						//    WriteExplicitImplementation(IPairedMessages.WithoutUser, RedirectToIMessages);

						WriteLine();
					}
				}

				#endregion
			}

		}