Fixed #18

Note that this is quite slow, I would love to discuss a better solution before merging this pull request.