Factor out mapping code to function and call from proper place