implemented a lot more error checking
fixed global variable bug