move duplicated residuals code into a utility function
reindent some code