Performance improvements and bug fixes.

This update has many performance improvements as well as MUCH more
simplified and organized code.