refactoring. Fixed an issue with the main loop
improving it