MATLAB CODE
written by John Bardsley
(unless otherwise noted)