Updated code based on Laurent's suggestion.