Refactor and code cleanup