## MolWgt - A Molecular Weight Calculator

This program analyzes a chemical formula to calculate the molecular weight (more properly, the molar mass). The program is written in Tcl and is run within a terminal window. Currently, it assumes that tclsh is available.

#### Algorithm

1. If two uppercase letters are next to each other, or an uppercase letter is followed by a "(" or ")", insert a "+" between them.
2. If a lowercase letter is followed by an uppercase letter, or by a "(" or ")", insert a "+" between them.
3. Precede each capital letter (the beginning of an element symbol) with a "\$". This creates a variable out of symbol. For example, Ca becomes \$Ca, which contains calcium's atomic mass value.
4. Insert a "*" (for multiplication) before each number and a "+" (for addition) after each number.
5. Change any "+)" sequences (created in the previous step) to ")".
6. Trim off the trailing "+" sign (if any).
7. Evaluate the resulting algebraic expression.

The above steps transform the original chemical formula into an algebraic expression which can be evaluated.

The program makes use of Tcl's regular expression substitution (regsub) command. Steps 2 - 7 are handled by one line of code!

#### Example: H3PO4

1. H3P+O4
2. H3P+O4
3. \$H3\$P+\$O4
4. \$H*3+\$P+\$O*4+
5. \$H*3+\$P+\$O*4+
6. \$H*3+\$P+\$O*4
7. Result: H3PO4 97.995181

#### Example: (NH4)2SO4

1. (N+H4)2S+O4
2. (N+H4)2S+O4
3. (\$N+\$H4)2\$S+\$O4
4. (\$N+\$H*4+)*2+\$S+\$O*4+
5. (\$N+\$H*4)*2+\$S+\$O*4+
6. (\$N+\$H*4)*2+\$S+\$O*4
7. Result: (NH4)2SO4 132.1406

Cool, isn't it?