New error checking and comments. Plus refactoring