Refactoring and major rewrite