abstracted a bunch of functionality, removed one while loop