Fixed problem with nested loops