Numerous fixes and code reorganisation