Refactor and remove dead code