Refactor and comment

Try and avoid too many nested blocks.