Refactor code into more sensible structure