This pull request closes #20. It was rewritten because I deemed that the merge of the stale pull-request #20 is harder than rewriting the whole thing.