matlab code from Jim for comparison. Not octave-portable