static void Main(string[] args)
        {
            int                      index = 0;
            List <string>            list1 = null;
            List <string>            list2 = null;
            Dictionary <string, int> dict1 = new Dictionary <string, int>()
            {
                { "A", 5 },
                { "B", 2 },
                { "C", 3 },
                { "D", 4 },
                { "E", 1 }
            };

            index = ReturnSmallestDiffIndex(dict1.AsEnumerable().Select(x => x.Value).ToList());
            list1 = dict1.AsEnumerable().Take(index).Select(x => x.Key).ToList();
            list2 = dict1.AsEnumerable().Skip(index).Take(dict1.Count - index).Select(x => x.Key).ToList();
            Dictionary <string, int> dict2 = new Dictionary <string, int>()
            {
                { "A", 1 },
                { "B", 1 },
                { "C", 1 },
                { "D", 1 },
                { "E", 9 }
            };

            index = ReturnSmallestDiffIndex(dict2.AsEnumerable().Select(x => x.Value).ToList());
            list1 = dict1.AsEnumerable().Take(index).Select(x => x.Key).ToList();
            list2 = dict1.AsEnumerable().Skip(index).Take(dict1.Count - index).Select(x => x.Key).ToList();
        }
        public double TabelaNormal(double porcentagem)
        {
            porcentagem /= 2;
            if (TabelaNormalData.ContainsKey(porcentagem))
            {
                return(TabelaNormalData[porcentagem]);
            }

            // Calculando o mais proximo
            var menorTstudent = new TNormal(TabelaNormalData.AsEnumerable().First(), porcentagem);

            foreach (var(key, value) in TabelaNormalData.AsEnumerable())
            {
                var testeMenor = Math.Abs(key - porcentagem);

                // Compliquei aqui....
                if (testeMenor < menorTstudent.Diferenca)
                {
                    menorTstudent.Diferenca = testeMenor;
                    menorTstudent.Key       = key;
                    menorTstudent.Value     = value;
                }
            }

            return(menorTstudent.Value);
        }
        public void GetOrAdd_CreateEntity_IfNotPresent()
        {
            var res = _Dictionary.GetOrAdd("Key", _ => "value");

            res.Item.Should().Be("value");
            res.CollectionStatus.Should().Be(CollectionStatus.Created);
            _Dictionary.AsEnumerable().Should().BeEquivalentTo(new[] { new KeyValuePair <string, string>("Key", "value") });
        }
Example #4
0
    public List <Client> GetClientsByAgent(Employee agent)
    {
        // Using LINQ to filter the internal dictionary _list based on the provided Agent.
        var result = from dictItem in _list.AsEnumerable()
                     where dictItem.Value.Agent.EmployeeId == agent.EmployeeId
                     select dictItem.Value;

        // Converting the result above to List<Client> and returning it.
        return(result.ToList());
    }
Example #5
0
        private string RetornaValorCelulaPelaColuna(int IndiceLinhaGrid, Dictionary <int, string> dicionarioSequenciaGrid, string CampoComboBox)
        {
            string pegaCampo = "";

            if (dicionarioSequenciaGrid.AsEnumerable().Any(pair => pair.Value == CampoComboBox))
            {
                var indiceCampo = dicionarioSequenciaGrid.AsEnumerable().First(pair => pair.Value == CampoComboBox);//pega qual coluna tem o campo
                pegaCampo = dataGridView1.Rows[IndiceLinhaGrid].Cells[indiceCampo.Key].FormattedValue.ToString();
            }
            return(pegaCampo);
        }
Example #6
0
        private void AddSectionTags(StringBuilder sb, Dictionary <DateTime, string> tags)
        {
            var tagsOrdered = tags.AsEnumerable().OrderByDescending(kvp => kvp.Key).ThenBy(kvp => kvp.Value);

            sb.AppendLine("<div class=\"row\">");
            sb.AppendLine("<div class=\"col-md-4\">");
            sb.AppendLine("<h2>Tags</h2>");
            sb.AppendLine("<table class=\"table pull-left\" style=\"width: auto\">");
            sb.AppendLine("<tr><th>Tag</th><th>Commit date</th></tr>");
            var tagDates = new List <ScatterPoint>();

            foreach (var kvp in tagsOrdered)
            {
                var tag           = kvp.Value;
                var tagCommitDate = kvp.Key.ToString("yyyy-MM-dd");
                sb.AppendLine($"<tr><td>{WebUtility.HtmlEncode(tag)}</td><td>{tagCommitDate}</td></tr>");
                var date = $"new Date('{tagCommitDate}')";
                tagDates.Add(new ScatterPoint
                {
                    Date    = date,
                    UserId  = 1,
                    ToolTip = $"'{tag}, {tagCommitDate}'"
                });
            }
            sb.AppendLine("</table>");
            sb.AppendLine("</div>");
            sb.AppendLine("<div class=\"col-md-8\">");
            AddTagsScatterplotJavascript(sb, tagDates);
            sb.AppendLine("    <div id=\"scatterChartTags\" \" class=\"spinner\"></div>");
            sb.AppendLine("</div></div>");
        }
Example #7
0
        private void AddSectionFileTypes(StringBuilder sb, Dictionary <string, int> fileTypes)
        {
            var fileTypesOrdered = fileTypes.AsEnumerable().OrderByDescending(kvp => kvp.Value).ThenBy(kvp => kvp.Key);

            sb.AppendLine("<div class=\"row\">");
            sb.AppendLine("<div class=\"col\">");
            sb.AppendLine("<h2>Number of files of each type</h2>");
            sb.AppendLine("<table class=\"table pull-left\" style=\"width: auto\">");
            sb.AppendLine("<tr><th class=\"text-right\">File type</th><th>Count</th></tr>");
            int rowCounter = 1;

            foreach (var kvp in fileTypesOrdered)
            {
                var icon = FileIcon("a" + kvp.Key);
                sb.AppendLine($"<tr><td class=\"text-right\"><i class=\"{icon} iw\"></i>{WebUtility.HtmlEncode(kvp.Key)}</td><td class=\"text-right\">{kvp.Value}</td></tr>");
                if (rowCounter++ % 10 == 0)
                {
                    sb.AppendLine("</table>");
                    sb.AppendLine("<table class=\"table pull-left\" style=\"width: auto\">");
                    sb.AppendLine("<tr><th class=\"text-right\">File type</th><th>Count</th></tr>");
                }
            }
            sb.AppendLine("</table>");
            sb.AppendLine("</div></div>");
        }
Example #8
0
        private void AddCodeAgeChartJavascript(StringBuilder sb, Dictionary <int, int> codeAge)
        {
            sb.AppendLine("<script type=\"text/javascript\">");
            sb.AppendLine("google.charts.load('current', { 'packages':['corechart']});");
            sb.AppendLine("google.charts.setOnLoadCallback(drawChart);");
            sb.AppendLine("function drawChart() {");
            sb.AppendLine($"var data = new google.visualization.DataTable();");
            sb.AppendLine($"data.addColumn('number', 'Code age');");
            sb.AppendLine($"data.addColumn('number', 'Filechanges');");
            sb.AppendLine($"data.addColumn({{ type: 'string', role: 'tooltip'}});");
            sb.AppendLine($"data.addColumn({{ type: 'string', role: 'annotation'}});");
            sb.AppendLine($"data.addRows([");
            var maxAge = codeAge.AsEnumerable().OrderByDescending(kvp => kvp.Key).First().Key;

            for (var month = 0; month <= maxAge; month++)
            {
                var fileChanges = codeAge.ContainsKey(month) ? codeAge[month] : 0;
                sb.AppendLine($"      [{month}, {fileChanges}, 'Age: {month} months, Changes: {fileChanges}', '{fileChanges}'],");
            }
            sb.AppendLine("   ]);");
            sb.AppendLine("   var options = { width: 1200, height: 500, legend: 'none', hAxis: { title: 'Codeage'}, vAxis: { title: 'Filechanges' } }; ");
            sb.AppendLine("   var element = document.getElementById('codeAgeChart');");
            sb.AppendLine("   element.classList.remove(\"spinner\");");
            sb.AppendLine("   element.style = \"width: 1200px; height: 500px;\"");
            sb.AppendLine("   var chart = new google.visualization.ColumnChart(element);");
            sb.AppendLine("   chart.draw(data, options);");
            sb.AppendLine("}");
            sb.AppendLine("</script>");
        }
Example #9
0
        private void Morelistbox_DoubleClick(object sender, EventArgs e)
        {
            var selitem = (TabTableTabEx)morelistbox.SelectedItem;

            this.morelistbox.Visible    = false;
            this.morelistbox.DataSource = null;

            if (selitem != null)
            {
                var pos = Math.Max(this.TabPages.Count - this.moretabtablelist.Count - 1, 0);

                for (var i = pos; i >= 0; i--)
                {
                    this.tabExDic[i].TabIndex--;
                }

                var lasttabex = this.tabExDic.AsEnumerable().ToArray()[pos].Value;
                selitem.TabIndex = pos;

                selitem.TabIndex = pos;
                if (pos != 0)
                {
                    tabExDic[0].TabIndex = tabExDic.Count;
                }
                var tabs = tabExDic.AsEnumerable().OrderBy(p => p.Value.TabIndex).Select(p => p.Value.TabPage).ToArray();
                this.tabExDic.Clear();
                this.TabPages.Clear();
                this.TabPages.AddRange(tabs);
                this.SelectedTab = selitem.TabPage;

                this.Invalidate();
            }
        }
Example #10
0
        public WordsCalcer(IEnumerable <KeyValuePair <string, string> > input)
        {
            Dictionary <string, int> words = new Dictionary <string, int>();
            var keyValuePairs = input as KeyValuePair <string, string>[] ?? input.ToArray();

            foreach (var a in keyValuePairs)
            {
                foreach (var b in a.Key.Split())
                {
                    if (!string.IsNullOrEmpty(b))
                    {
                        if (words.ContainsKey(b))
                        {
                            words[b]++;
                        }
                        else
                        {
                            words.Add(b, 1);
                        }
                    }
                }
            }
            _indexMap          = words.AsEnumerable().Where(x => x.Value < 5).ToDictionary(x => x.Key, x => _count++);
            _arraysWithAnswers = keyValuePairs.Select(x => new KeyValuePair <int[], string>(GetStringArray(x.Key), x.Value)).ToList();
        }
Example #11
0
        public async static Task <AddressValidateResponse> VerifyAddressAsync(Address address)
        {
            var serializer = new XmlSerializer(typeof(AddressValidateResponse));
            var client     = new HttpClient()
            {
            };

            var body = new Dictionary <string, string>
            {
                { "API", "Verify" },
                { "XML", $@"<AddressValidateRequest USERID = ""737TENAN6421""><Address ID = ""0""><Address1>{address.Line2}</Address1><Address2>{address.Line1}</Address2><City>{address.City}</City><State>{address.State}</State><Zip5>{address.PostalCode}</Zip5><Zip4></Zip4></Address></AddressValidateRequest>" }
            };


            var content = new FormUrlEncodedContent(body.AsEnumerable() !);

            var response = await client.PostAsync(URIBASE, content);

            var stream = await response.Content.ReadAsStreamAsync();

            var addressSerial = (AddressValidateResponse)serializer.Deserialize(stream);

            Console.WriteLine(stream);
            return(addressSerial);
        }
        private void ComputaTabelaNormal()
        {
            var tabelaNormalData = new Dictionary <double, List <Tuple <double, double> > >();

            // Le os valores
            var matriz = AbreCsv("tabela_normal.csv");

            for (var i = 1; i < matriz.Count - 1; i++)
            {
                for (var j = 1; j < matriz[i].Count - 1; j++)
                {
                    if (tabelaNormalData.ContainsKey(matriz[i][j]))
                    {
                        tabelaNormalData[matriz[i][j]].Add(new Tuple <double, double>(matriz[0][j], matriz[i][0]));
                    }
                    else
                    {
                        var lista = new List <Tuple <double, double> >();
                        lista.Add(new Tuple <double, double>(matriz[0][j], matriz[i][0]));
                        tabelaNormalData.Add(matriz[i][j], lista);
                    }
                }
            }

            foreach (var(key, value) in tabelaNormalData.AsEnumerable())
            {
                var media = value.Sum(e => e.Item1 + e.Item2) / value.Count;
                TabelaNormalData.Add(key, media);
            }
        }
Example #13
0
        public IActionResult Create()
        {
            Dictionary <int, string> months = Tools.MonthsList();

            ViewBag.Months = new SelectList(months.AsEnumerable(), "Key", "Value");
            return(View());
        }
Example #14
0
        public DictionaryBehavior()
        {
            Behavior <TKey, TValue> bhv1 = new Behavior <TKey, TValue>((k, v) => _dico[k] = v);
            Behavior <IActor, TKey> bhv2 = new Behavior <IActor, TKey>((a, k) =>
            {
                bool result = _dico.TryGetValue(k, out TValue v);
                a.SendMessage(result, k, v);
            });
            Behavior <TKey>   bhv3 = new Behavior <TKey>(k => _dico.Remove(k));
            Behavior <IActor> bhv4 = new Behavior <IActor>(a =>
            {
                a.SendMessage(_dico.AsEnumerable <KeyValuePair <TKey, TValue> >());
            });
            Behavior <DictionaryBehaviorOrder> bhv5 = new Behavior <DictionaryBehaviorOrder>
                                                      (
                o => o == DictionaryBehaviorOrder.clear,
                o => _dico.Clear()
                                                      );

            AddBehavior(bhv1);
            AddBehavior(bhv2);
            AddBehavior(bhv3);
            AddBehavior(bhv4);
            AddBehavior(bhv5);
        }
Example #15
0
        internal async Task <string> GetRandomFuckOffMessage()
        {
            string[] keys  = requestDictionary.AsEnumerable().Select(kvp => kvp.Key).ToArray();
            int      index = new Random().Next(0, keys.Length);

            return(await GetMessage(keys[index]));
        }
    public IList <string> FindRepeatedDnaSequences(string s)
    {
        //pre condition
        if (s.Length <= 10)
        {
            return(new List <string>());
        }

        //normal condition
        Dictionary <string, int> dict = new Dictionary <string, int>();

        for (int i = 0; i < s.Length - 9; i++)
        {
            string current_sub = s.Substring(i, 10);

            if (dict.Keys.Contains(current_sub))
            {
                dict[current_sub]++;
            }
            else
            {
                dict[current_sub] = 1;
            }
        }

        return(dict.AsEnumerable().Where(x => x.Value > 1).Select(x => x.Key).ToList());
    }
Example #17
0
        public IRequestStateModel RefreshSpotifyToken(string refreshToken)
        {
            var data = new Dictionary <string, string>();

            data.Add("refresh_token", refreshToken);
            data.Add("grant_type", "refresh_token");
            data.Add("client_id", "a42c9625d0534a27911d6d708531b4b9");
            data.Add("client_secret", "94618a312bf14e478c0e7c77d29312be");

            using (var httpClient = new HttpClient())
            {
                using (var content = new FormUrlEncodedContent(data.AsEnumerable()))
                {
                    content.Headers.Clear();
                    content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                    var response        = httpClient.PostAsync("https://accounts.spotify.com/api/token", content).Result;
                    var responseContent = response.Content.ReadAsStringAsync().Result;
                    if (responseContent.Contains("error"))
                    {
                        var json = JObject.Parse(responseContent);
                        return(new RequestFailedModel()
                        {
                            Error = (string)json["error_description"]
                        });
                    }
                    return(JsonConvert.DeserializeObject <SpotifyTokenModel>(responseContent));
                }
            }
        }
        /// <summary>
        /// Generates the OAuth authorization URL to use for authentication.
        /// </summary>
        /// <param name="clientID">The ID of the client application</param>
        /// <param name="scopes">The authorization scopes to request</param>
        /// <param name="redirectUri">The redirect URL for the client application</param>
        /// <param name="forceApprovalPrompt">Whether to force an approval from the user</param>
        /// <returns>The authorization URL</returns>
        public static async Task <string> GetAuthorizationCodeURLForOAuthBrowser(string clientID, IEnumerable <OAuthClientScopeEnum> scopes, string redirectUri, bool forceApprovalPrompt = false)
        {
            Validator.ValidateString(clientID, "clientID");
            Validator.ValidateList(scopes, "scopes");
            Validator.ValidateString(redirectUri, "redirectUri");

            string url = "https://accounts.google.com/o/oauth2/v2/auth";

            Dictionary <string, string> parameters = new Dictionary <string, string>()
            {
                { "client_id", clientID },
                { "scope", YouTubeConnection.ConvertClientScopesToString(scopes) },
                { "response_type", "code" },
                { "redirect_uri", redirectUri },
            };

            if (forceApprovalPrompt)
            {
                parameters.Add("force_verify", "force");
            }

            FormUrlEncodedContent content = new FormUrlEncodedContent(parameters.AsEnumerable());

            return(url + "?" + await content.ReadAsStringAsync());
        }
        private void AddSectionTagsAndBranches(ExcelWorksheet sheet, Dictionary <DateTime, string> tags, List <string> branches)
        {
            var tagsOrdered = tags.AsEnumerable().OrderByDescending(kvp => kvp.Key).ThenBy(kvp => kvp.Value);

            Header(sheet, "Tags");

            int rowCounter = 3;

            TableHeader(sheet, rowCounter, 1, "Tag", 24);
            TableHeader(sheet, rowCounter, 2, "Commit date", 11);

            rowCounter++;
            foreach (var kvp in tagsOrdered)
            {
                var tag           = kvp.Value;
                var tagCommitDate = kvp.Key.ToString("yyyy-MM-dd");
                sheet.Cells[rowCounter, 1].Value = tag;
                sheet.Cells[rowCounter, 2].Value = tagCommitDate;
                rowCounter++;
            }

            Header(sheet, "Branches", 1, 4);

            rowCounter = 3;
            TableHeader(sheet, rowCounter, 4, "Branch", 24);

            rowCounter++;
            foreach (var branch in branches)
            {
                sheet.Cells[rowCounter, 4].Value = branch;
                rowCounter++;
            }
        }
        private void UpdateGameForNextGen(Dictionary <Vector2, Cell> liveNeighbors, Func <int, bool, bool> generationFunction)
        {
            foreach (KeyValuePair <Vector2, Cell> keyValuePair in liveNeighbors.AsEnumerable())
            {
                Vector2 tilePos           = keyValuePair.Key;
                int     liveNeighborCount = keyValuePair.Value.liveNeighborCount;
                bool    isAlive           = keyValuePair.Value.alive;
                bool    aliveNextGen      = generationFunction(liveNeighborCount, isAlive);
                bool    diggable          = Game1.currentLocation.doesTileHaveProperty((int)tilePos.X, (int)tilePos.Y, "Diggable", "Back") != null;
                if (aliveNextGen && diggable)
                {
                    bool hasNoBlockingFeature = HandleBlockingFeatures(tilePos);
                    bool hasNoBlockingObject  = HandleBlockingObjects(tilePos);

                    if (Config.HoeDirt && hasNoBlockingFeature && (hasNoBlockingObject || Config.HoeUnderObjects))
                    {
                        Game1.currentLocation.makeHoeDirt(tilePos, true);
                    }
                    if (Game1.currentLocation.terrainFeatures.TryGetValue(tilePos, out TerrainFeature feature) && feature is HoeDirt dirt)
                    {
                        dirt.state.Value = 1;
                    }
                }
            }
        }
Example #21
0
        public IRequestStateModel RefreshRedditToken(Token token)
        {
            var    data     = new Dictionary <string, string>();
            string authInfo = "hfTIumnrQMLA_A:9wp2Hj1WzmAMSmS1srmgi99UdYM";

            authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
            data.Add("refresh_token", token.RefreshToken);
            data.Add("grant_type", "refresh_token");

            using (var httpClient = new HttpClient())
            {
                using (var content = new FormUrlEncodedContent(data.AsEnumerable()))
                {
                    content.Headers.Clear();
                    content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                    content.Headers.Add("Authorization", "Basic " + authInfo);

                    var response        = httpClient.PostAsync(@"https://www.reddit.com/api/v1/access_token", content).Result;
                    var responseContent = response.Content.ReadAsStringAsync().Result;
                    Console.WriteLine(responseContent);
                    if (responseContent.Contains("error"))
                    {
                        var json = JObject.Parse(responseContent);
                        return(new RequestFailedModel()
                        {
                            Error = (string)json["error_description"]
                        });
                    }
                    return(JsonConvert.DeserializeObject <RedditTokenModel>(responseContent));
                }
            }
        }
        private void AddSectionCodeAge(ExcelWorksheet sheet, Dictionary <int, int> codeAge)
        {
            Header(sheet, "Code age");

            int rowCounter = 3;

            TableHeader(sheet, rowCounter, 1, "Code age (months)", 14);
            TableHeader(sheet, rowCounter, 2, "Filechanges", 12);

            rowCounter++;
            var maxAge = codeAge.AsEnumerable().OrderByDescending(kvp => kvp.Key).First().Key;

            for (var month = 0; month <= maxAge; month++)
            {
                var fileChanges = codeAge.ContainsKey(month) ? codeAge[month] : 0;
                sheet.Cells[rowCounter, 1].Value = month;
                sheet.Cells[rowCounter, 2].Value = fileChanges;
                rowCounter++;
            }
            var chart = sheet.Drawings.AddChart("CodeAge", OfficeOpenXml.Drawing.Chart.eChartType.ColumnClustered);

            chart.SetSize(600, 400);
            chart.SetPosition(0, 250);
            var series1 = chart.Series.Add($"$B$4:$B${rowCounter}", $"$A$4:$A${rowCounter}");

            chart.Legend.Remove();
            chart.XAxis.Title.Text      = "Code age (months)";
            chart.XAxis.Title.Font.Size = 12;
        }
        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);
        }
        /// <summary>
        /// Creates a default display for a given Element Template and Element instance.
        /// </summary>
        /// <param name="elementTemplate">The element template on which the display will be based</param>
        /// <param name="initialContextElementPath">The element which will be the display's initial context</param>
        /// <param name="includedCategories">Optional list of categories to include. By default, all categories are included, as is the set of attributes not in a category. If specifying categories, the name @None will explicitly include uncategorized attributes.</param>
        /// <returns>A reference to the created display</returns>
        public Task <DisplayRevision> CreateDefaultDisplayAsync(AFElementTemplateSlim elementTemplate, string initialContextElementPath, ICollection <string> includedCategories = null)
        {
            //If the path is not escaped, do so here. TODO does this need to be URL encoded?
            if (!initialContextElementPath.Contains(@"\\\\"))
            {
                initialContextElementPath = initialContextElementPath.Replace(@"\", @"\\");
            }

            string name = string.Format("{0} default display", elementTemplate.Name); //TODO check collisions
            CoresightDisplayBuilder displayBuilder = new CoresightDisplayBuilder(CoresightBaseUri, name);

            IEnumerable <AFAttributeTemplateSlim> includedAttributes = elementTemplate.AllAttributes.Where(a => !a.IsHidden && ValueTypeHelper.TypeIsSupported(a.TypeName));
            Dictionary <string, IEnumerable <AFAttributeTemplateSlim> > attributesByCategory = AFAttributeTemplateSlim.GroupByCategory(includedAttributes, includedCategories);

            //If an explicit collection of included categories is specified, preserve its order
            bool explicitCategoriesSpecified = includedCategories != null && includedCategories.Count > 0;
            var  attributesByCategoryOrdered = !explicitCategoriesSpecified?
                                               attributesByCategory.AsEnumerable() :
                                                   includedCategories.Select(c => new KeyValuePair <string, IEnumerable <AFAttributeTemplateSlim> >(c, attributesByCategory[c]));

            foreach (var category in attributesByCategoryOrdered)
            {
                string titleText = AFAttributeTemplateSlim.NullCategory.Equals(category.Key, StringComparison.OrdinalIgnoreCase) ?
                                   "Uncategorized" :
                                   category.Key;
                titleText = attributesByCategory.Count < 2 ? null : titleText;

                AddAttributeGroup(displayBuilder, category.Value, initialContextElementPath, titleText);
            }

            return(displayBuilder.SaveAsync());
        }
Example #25
0
        public IRequestStateModel RefreshYoutubeToken(Token code)
        {
            var data = new Dictionary <string, string>();

            data.Add("grant_type", "refresh_token");
            data.Add("refresh_token", code.RefreshToken);
            data.Add("client_id", "473291186491-5tiqjh1gb7uoiv717utbf8ibjgcvfbj0.apps.googleusercontent.com");
            data.Add("client_secret", "yEQlGF5mlNqW_zCrm4fkT2kB");

            using (var httpClient = new HttpClient())
            {
                using (var content = new FormUrlEncodedContent(data.AsEnumerable()))
                {
                    content.Headers.Clear();
                    content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                    var response        = httpClient.PostAsync("https://www.googleapis.com/oauth2/v4/token", content).Result;
                    var responseContent = response.Content.ReadAsStringAsync().Result;
                    Console.WriteLine(responseContent);
                    if (responseContent.Contains("error"))
                    {
                        var json = JObject.Parse(responseContent);
                        return(new RequestFailedModel()
                        {
                            Error = (string)json["error_description"]
                        });
                    }
                    return(JsonConvert.DeserializeObject <YoutubeRefreshTokenModel>(responseContent));
                }
            }
        }
Example #26
0
        public async Task <Tuple <string, int> > GetServiceInstance(Version minVersion = null, Version maxVersion = null, Version exactVersion = null, int msTimeout = Timeout.Infinite)
        {
            await _loadedTask;

            var listOfServices = _serviceListings.AsEnumerable();

            if (minVersion != null)
            {
                listOfServices = listOfServices.Where(s => s.Value.Any(v => v > minVersion));
            }
            if (maxVersion != null)
            {
                listOfServices = listOfServices.Where(s => s.Value.Any(v => v < maxVersion));
            }
            if (exactVersion != null)
            {
                listOfServices = listOfServices.Where(s => s.Value.Any(v => v == exactVersion));
            }

            var matchingServices = listOfServices.ToArray();

            if (matchingServices.Length == 0)
            {
                return(null);
            }

            var service = matchingServices[random.Value.Next(0, matchingServices.Length)];

            return(Tuple.Create(service.Key.Address, service.Key.Port));
        }
        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 static async Task <string> GetAuthorizationCodeURLForOAuthBrowser(string clientID, string clientSecret, IEnumerable <OAuthClientScopeEnum> scopes, string redirectUri, bool forceApprovalPrompt = false)
        {
            Validator.ValidateString(clientID, "clientID");
            Validator.ValidateList(scopes, "scopes");
            Validator.ValidateString(redirectUri, "redirectUri");

            string url = "https://mixer.com/oauth/authorize";

            Dictionary <string, string> parameters = new Dictionary <string, string>()
            {
                { "client_id", clientID },
                { "scope", MixerConnection.ConvertClientScopesToString(scopes) },
                { "response_type", "code" },
                { "redirect_uri", redirectUri },
            };

            if (!string.IsNullOrEmpty(clientSecret))
            {
                parameters.Add("client_secret", clientSecret);
            }

            if (forceApprovalPrompt)
            {
                parameters.Add("approval_prompt", "force");
            }

            FormUrlEncodedContent content = new FormUrlEncodedContent(parameters.AsEnumerable());

            return(url + "?" + await content.ReadAsStringAsync());
        }
Example #29
0
        private static void AddEntry(string _category, ObserverEntry _entry)
        {
#if UNITY_EDITOR
            KeyValuePair <ObserverCategory, List <ObserverEntry> > kvp = (from k in Entries.AsEnumerable()
                                                                          where k.Key.CategoryName == _category
                                                                          select k).FirstOrDefault();
            // If we have category
            if (kvp.Key != null)
            {
                // Get Entry list from Corresponding category
                List <ObserverEntry> entryList = kvp.Value;

                // Try to find existing Entry
                ObserverEntry entry = entryList.FirstOrDefault(name => name.EntryName == _entry.EntryName);

                // Add new or update existing entry
                if (entry == null)
                {
                    entryList.Add(_entry);
                }
                else
                {
                    entry.Value = _entry.Value;
                }
            }
            else
            {
                Entries.Add(new ObserverCategory(_category), new List <ObserverEntry> {
                    _entry
                });
            }
#endif
        }
        public IEnumerator <KeyValuePair <ulong, IReadOnlyList <IInstruction> > > GetEnumerator()
        {
            var enumerator = m_map.AsEnumerable();
            IEnumerable <KeyValuePair <ulong, IReadOnlyList <IInstruction> > > newEnumerator = (IEnumerable <KeyValuePair <ulong, IReadOnlyList <IInstruction> > >)enumerator;

            return(newEnumerator.GetEnumerator());
        }
Example #31
0
        public string GetScriptText()
        {
            string buildxml = Path.Combine(Directory.GetCurrentDirectory(), WORKSPACE_FOLDER, TEMPLATE_FOLDER, MSBUILD_TEMPLATE);

            if (File.Exists(buildxml))
            {
                StringBuilder sb_xml = new StringBuilder(File.ReadAllText(buildxml));

                sb_xml.Replace("#{assembly}", base64assembly);

                foreach (KeyValuePair <string, string> kp in arg.AsEnumerable())
                {
                    sb_xml.Replace(kp.Key, kp.Value);
                }

                Console.WriteLine("[*] Replace end");

                return(sb_xml.ToString());
            }
            else
            {
                Console.WriteLine("[x] Template not found");
                return("");
            }
        }
Example #32
0
 public async Task OnGet()
 {
     test = new Dictionary <Game, double> {
     };
     var calculate = new Dictionary <Game, getReviewModel> {
     };
     await Task.Run(() =>
     {
         var query = from r in context.Review
                     orderby r.GameId
                     select r;
         foreach (var r in query)
         {
             var game = gamedb.GetById(r.GameId);
             int good = r.Recommended ? 1 : 0;
             int bad  = r.Recommended ? 0 : 1;
             if (calculate.ContainsKey(game))
             {
                 getReviewModel getReview = new getReviewModel
                 {
                     total = calculate[game].total + 1,
                     good  = calculate[game].good + good,
                     bad   = calculate[game].bad + bad
                 };
                 calculate[game] = null;
                 calculate[game] = getReview;
             }
             else
             {
                 getReviewModel getReview = new getReviewModel
                 {
                     total = 1,
                     good  = good,
                     bad   = bad
                 };
                 calculate.Add(game, getReview);
             }
             Console.WriteLine("Test: " + game.GameName + " Value:" + good.ToString() + ", " + bad.ToString());
         }
         if (calculate.Any())
         {
             Console.WriteLine("Test: " + calculate.Count);
             var boopbeep = calculate.AsEnumerable();
             foreach (var item in boopbeep)
             {
                 test.Add(item.Key, (double)item.Value.good / (double)item.Value.total);
             }
             var order = from r in test
                         where r.Value >= 0.5
                         orderby r.Value descending, r.Key.Price
             select r;
             test = new Dictionary <Game, double> {
             };
             foreach (var item in order)
             {
                 test.Add(item.Key, item.Value);
             }
         }
     });
 }
Example #33
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 #34
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;

        }
            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 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;

        }
Example #37
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 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
			}

		}
        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 #40
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 #41
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);
            }

            
        }