Refactor and rewrite