Remove complex local sub-functions mutating function-global variables. Simplify counting used for progress output.