Changes to determine optimal partitioning.

Also includes broad refactoring of the code.