Initial patch by Fabian Deutsch, with a few fixes added
Looks good.
Pull-Request has been merged by mikeb