Some refactorings and cleanups. Code's still a mess though :)