General bugfixing and style tidy up