clean up the code, while still don't know how to hook into shutdown event