re-ordered a few lines to deal with errors earlier