Final working version - tested and commented 2014-06-17