Minor bugfixes. Some code cleanup