Greatly simplified event handling and fixed more memory leaks.