Moved useful functions outside main loop