Heavy refactoring and commenting as well as various fixes