Added typeerror checking
changed code structure