rearrange code to use events