Many fixes, a bit of refactoring and formatting issues