added a lot of error checking
fixed refactoring typo