patch by Mukund Sivaraman, modified by me to make it simpler and to use my coding style).
Attach a file by drag & drop or click to upload