Rewrite bizarre code in a way that makes more sense