Move/rewrite code for efficiency/clarity as suggested by Marco