bugfixes and tidying up code