added while loop and cleaned up stmts sequence