Varoious code improvements and bugfixes