Some improvements, partially based on Pedro's suggestions.