Add the autostart function and clean up code