changed loop function, cleaned up variables