Fixed a load of bugs (and added residual calculation).