Bugfixes and reformat of the code