Refactored the code: removed most of the printfs