code cleanup and more error checking
license