Finished flag detection MATLAB port.