Clean up code. Fixed bug with attaching events