Fixing issue #8: Added a try..finally block around main loop to ensure clean-up commands are executed.