Fix for #215 and some other related improvements

please don't change indentation, whitespace, and things like that. Please limit your PR to the code improvements you suggest