Improvements based on Lucas's suggestion.