Revised based on feedback from @dmitriyvolk