lists:mapfoldl/3 marginally more elegant here.