Reorganized, fleshed out control flow.
Bug fixes.