Changes from for to while and other changes to make code working