Refactor

@rytaft You should take a quick look over this and make sure it is ok.