use totalwidth var, simplify looping logic