Fix a nasty bug with nested loops