Fix #13 and #14

OK. I had another look but couldn't work it out, so I've updated the pull request with the code I think you want me to have instead in comments, and the apparently working code still there.