Clean-up and optimization

This is an improved version of your pull-request, if you accept it, it will be updated in your own pull-request. Everybody wins :-)