added some err checking for up and down casting, also other minor edits