Added some error checking
Added function that should be called in the main loop