rewrite of the rewrite tool from perl to python