Refactor and format code