Major rewrite/refactoring