First revision, not extensively tested, but should work as the Java one does.