Some code improvements and bugfixes