Attempt to refactor some ugly code