Refactor and cleanup code