This is far from a complete coverage, but should catch most of potential issues when rewriting this code.