Refactor and optimise code