Remove code duplication. Based on a patch by Matthieu Castet.