Could the Schwartzian Transform be applied to this problem? I'm definitely not the one to write the code for you(way too unfamiliar with the inner workings of the ST for me to start recommending how others should use it), but if I'm not mistaken as to its purpose, it seems like it would work for this application.