clearer implementation based on wedaly's suggestions