Copied phasing code over from Examination and cleaned up