Replace PR#2592

This includes Roberto's changes and cleans it up a little.