Full pull request for algorithmic optimizations with bug fix.

A revised full pull request with a now-correctly-tested set of the speed optimizations.