Vairous bugfixes, code cleanings and refactorings.