Ported from perl to python with 004.p*