I wrote a library recently that tackles this very problem.

http://timrwood.github.com/n7m/