Three commits: a straight refactor, a new unit test, then an optimization.
This makes OP_CHECKMULTISIG more efficient, only recomputing the transaction signature hash once-per-different-SIGHASH-used-by-its-signatures.
Insignificant for small transactions, but could be as much as a 2x speedup for very large transactions spending 1-of-3 multisig inputs.
Thanks to Sergio Demian Lerner for warning that an attacker might try to mount a CPU exhaustion attack using OP_CHECKMULTISIG.
This fix is low priority (post-0.8.0) because transaction fees are high enough to make a CPU exhaustion attack based on this economically irrational.