Bug fixes and some reorganisation