Refactor some horrible code