Some code improvements and bugfix