This one supersedes #495 and #527

Rebased version with few more fixes by Dominic and me. Thanks all.