Updated code based on some review by james.