More minor bugfixes and improvements.

Moved the UI declaration and events into a separate code file, as well
as cleaned up the main one. Only minor changes to the rest.