Fixed while loops inside of functions (after a few hours work)