some improvements as suggested by @stefanpenner