Refactor a bit, formatting and comments