Refactoring and commenting some more. also small bug fixes.