#!/usr/bin/octave

H = load("H");
L = load("L") + 1;
R = load("R") + 1;
P = load("P") + 1;
Q = load("Q") + 1;
Ptot = load("Ptotal");
Qtot = load("Qtotal");
remaining = load("remaining");
mc = load("mc");
jackpot = load("jackpot");
Am = load("Am");
medc_idx = load("medc_idx");
Am(end+1) = mc;

colidx = 1:columns(H);

origH = repmat((H+1)/2, 1, 1, 3);

graphics_toolkit fltk;
figure


function snapshot()
  persistent x = 1;
  fname = sprintf("%02d.png", x);
  print("-dpng", fname);
  x++;
endfunction

for iter = 1:length(Am)
  if iter > rows(L)
    break
  endif

  ## Reset the image
  imgH = origH;

  ## Make greater-than red
  red = imgH(:,:,1);
  red(colidx < L(iter, :)') = 1;
  imgH(:, :, 1) = red;

  ## Make less-than blue
  blue = imgH(:,:,3);
  blue(colidx > R(iter, :)')  = 1;
  imgH(:, :, 3) = blue;

  printf("Remaining: %d\n", remaining(iter))
  imshow(imgH);
  snapshot;

  ## Make the guess yellow
  [i,j] = find(Am(iter) == H);
  imgH(i,j,1) = imgH(i,j,2) = 1;
  imgH(i,j,3) = 0;

  imshow(imgH);
  snapshot;

  if iter == length(Am)
    break
  endif

  ## Check the left side
  imgLeft = imgH;
  red = imgH(:, :, 1);
  green = imgH(:, :, 2);
  blue = imgH(:, :, 3);

  idx = colidx > P(iter,:)';

  ## Brighten blue
  blue(idx) = 1;

  ## Dim red and green
  red(idx) .*= 0.5;
  green(idx) .*= 0.5;

  imgLeft(:,:,2) = green;
  imgLeft(:,:,3) = blue;

  ## Make the guess yellow again
  [i,j] = find(Am(iter) == H);
  imgH(i,j,1) = imgH(i,j,2) = 1;
  imgH(i,j,3) = 0;

  imshow(imgLeft);
  snapshot;

  ## Check the right side
  imgRight = imgH;
  red = imgH(:, :, 1);
  green = imgH(:, :, 2);
  blue = imgH(:, :, 3);

  idx = colidx < Q(iter,:)';

  ## Brighten red
  blue(idx) = 1;

  ## Dim blue and green
  blue(idx) .*= 0.5;
  green(idx) .*= 0.5;

  imgRight(:,:,2) = green;
  imgRight(:,:,3) = blue;

  ## Make the guess yellow again
  [i,j] = find(Am(iter) == H);
  imgH(i,j,1) = imgH(i,j,2) = 1;
  imgH(i,j,3) = 0;
  imshow(imgRight);
  snapshot;

  imshow(imgH);
  printf("rank is between %d and %d (target: %d)\n",
         Ptot(iter), Qtot(iter), medc_idx)
  snapshot;

endfor

if (jackpot)
  printf("Jackpot!\n")
endif
snapshot;
