restructured, some more error checking