public string Substitute(string str)
{
Match m;
int istart = 0;
while ((m = iden.Match(str, istart)).Success)
{
MacroEntry me = (MacroEntry)macroTable[m.Value];
if (me != null)
{
string subst = me.Subst;
if (me.Parms != null)
{
int i = m.Index + m.Length; // points to char just beyond match
while (i < str.Length && str[i] != '(')
i++;
i++; // just past '('
int parenDepth = 1;
string[] actuals = new string[me.Parms.Length];
int idx = 0, isi = i;
while (parenDepth > 0 && i < str.Length)
{
char ch = str[i];
if (parenDepth == 1 && (ch == ',' || ch == ')'))
{
actuals[idx] = str.Substring(isi, i - isi);
idx++;
isi = i + 1; // past ',' or ')'
}
// understands commas within braces or square brackets (e.g. 'matrix' indexing)
if (ch == '(' || ch == '{' || ch == '[') parenDepth++;
else
if (ch == ')' || ch == '}' || ch == ']') parenDepth--;
i++;
}
if (parenDepth != 0)
{
return "**Badly formed macro call**";
}
subst = ReplaceParms(me, actuals);
istart = m.Index;
str = str.Remove(istart, i - istart);
str = str.Insert(istart, subst);
}
else
{
str = iden.Replace(str, subst, 1, istart);
}
}
else
istart = m.Index + m.Length;
}
return str;
}