First steps in refactoring this hunk of junk
Further refactoring