see below for what I think is a clean implementation