Fixed subtle bug resulting from nested loop using global instead of locally scoped index variables.