I did it in python:
http://dpaste.com/hold/224803/
It's probably not well written, but works to me. There are no comments because I don't know whether it is useful or not. In that case I'll be glad to add them or write explainations right here.
<--->
Giacomo