Rebased and enhanced version of #184