code cleanup+revision, added some data validation and error checking