Major refactoring done. Much cleaner but not perfect.