Original code by Mason Chang posted on bug 970751; modified by Kartikaya Gupta for use in bug 1049136.