Fix illegal line and refactor for loop