refactor with error cleanup. still need to refactor