Fixed the code so that app works 99% of the time