rewrite some if/else logic, thanks to @ediosyncratic