private IEnumerable<string> GenerateNames(int ruleNum, string nameFormat, int currentChannel, int totalChannels) { var resultingNames = new List<string>(); if (lbRules.Items.Count < ruleNum || currentChannel > totalChannels) { return resultingNames; } var ruleEngine = _ruleEngines[ruleNum - 1]; if (ruleEngine.Iterations != 0) { var generatedNames = new List<string>(ruleEngine.GenerateNames()); for (var i = 0; (i < ruleEngine.Iterations || ruleEngine.IsUnlimited) && currentChannel + resultingNames.Count < totalChannels; i++) { var parts = new Regex("{" + (ruleNum - 1) + "[:]?[a-zA-Z0-9]*}").Match(nameFormat).ToString().Split(':'); var format = parts.Count() == 2 ? "{0:" + parts[1] : "{0}"; var replace = parts.Count() == 2 ? "{" + (ruleNum - 1) + ":" + parts[1] : "{" + (ruleNum - 1) + "}"; var replacementValue = ruleEngine.IsUnlimited ? ruleEngine.GenerateName(i) : generatedNames[i]; int numericReplacement; var formattingResult = nameFormat.Replace(replace, int.TryParse(replacementValue, out numericReplacement) ? string.Format(format, numericReplacement) : replacementValue); // Is this the last rule? if (ruleNum >= _ruleEngines.Count) { resultingNames.Add(formattingResult); } else { resultingNames.AddRange( GenerateNames(ruleNum + 1, formattingResult, currentChannel + resultingNames.Count, totalChannels).ToList()); } } } else { resultingNames.Add(ruleEngine.GenerateDefaultName()); } return resultingNames; }