Move error reporting/cleanup into discrete function