python implementation, clean up merge code