Misc fixes, refactorings and commenting