Merged two near-identical functions to save code repetition.