A generalization of Gallagher's lemma for exponential sums