Updated @megies' PR to include a test and some other tweaks.