Slightly different implementation of hxim's idea. Take 4.