Fixed a bug where an inner loop would override an outer due to function scope