Implemented smart shutdown logic