lots of small changes to detect errors

add a bunch of error detection and handling