refactored main function