Move logic from perl to python