Code cleanup and add onclose handler