Changed logic for loops and error checking