Code modified. See comments for further detail.