some refactoring, some detail fixes, some error checking