## Copyright (C) 2015 by Daniel Kraft <d@domob.eu>
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program.  If not, see <http://www.gnu.org/licenses/>.

clear ("all");
page_screen_output (false);

global crop colThreshold pics suff;
crop = [1, 1, 1800, 1080];
colThreshold = 0.72;
pics = 1 : 3 : 6502;
suff = "";

function p = normalise (p)
  global crop colThreshold;

  p = p(crop(2) : crop(4), crop(1) : crop(3), :);
  p = max (p, [], 3);
  p = 1 - (p > colThreshold);
endfunction

% Apply the filtering process, optionally writing out
% the output images (if an output directory is given).
function cnt = apply (tt, dt, outdir)
  global diffStep pics suff;

  aboveThresholdFor = 0;
  cnt = 0;
  assert (isna (diffStep(1)));
  for i = 2 : length (diffStep)
    if (diffStep(i) > dt)
      ++aboveThresholdFor;
    else
      if (aboveThresholdFor > tt)
        ++cnt;
        if (nargin > 2)
          printf ("Writing output image %d...\n", cnt);
          p = imread (sprintf ("Frames%s/%05d.jpg", suff, pics(i)));
          p = double (p) / 255;
          imwrite (normalise (p), sprintf ("%s%s/%05d.png", outdir, suff, cnt));
        endif
      endif
      aboveThresholdFor = 0;
    endif
  endfor
endfunction

% Manually normalise and write out a particular frame.  This is used to
% correct or add manually found frames.
function writeFrame (ind, outnum)
  global suff;

  printf ("Manually writing frame %d as output %d...\n", ind, outnum);
  p = imread (sprintf ("Frames%s/%05d.jpg", suff, ind));
  p = double (p) / 255;
  imwrite (normalise (p), sprintf ("Output%s/%05d.png", suff, outnum));
endfunction

global diffStep;
lastPic = [];
diffStep = NA (size (pics));
for i = 1 : length (pics)
  printf ("Image %d of %d...\n", i, length (pics));

  p = imread (sprintf ("Frames%s/%05d.jpg", suff, pics(i)));
  p = double (p) / 255;
  %pn = normalise (p);

  if (numel (lastPic) > 0)
    diffStep(i) = norm (p(:) - lastPic(:)) / norm (p(:));
  endif
  lastPic = p;
endfor
