Added an error printing function

Added an error printing function and removed about a 100 lines of
repeated code.