Added some code to prevent infinite looping