based on a deiff from rsadowski@ with some tweaks from me. positive feedback from Adriano Barbosa and Caspar Schutijser