Implement on_open/on_close and clean up

Made on_open and on_close callbacks actually work properly.  Also
removed trailing whitespace from everywhere.