Fix bug causing segmentation fault when using nested loops
Add test case for nested loops