Improve processing of remaining frames and fix bug in loop detection