moved reduction to correct loop nesting