Refactor and remove unused code