Fix bugs to hopefully make it all actually work.
Code maid tidy up.