code cleanup + fix bug when control lost