Major overhaul. Refactors and fixes all around.