Refactored worker and main loop