code that works in all cases, minor cosmetic edits too