% Dima Damen
% November 1st 2007

% This code is responsible for drawing the bounding box onto the actual
% frames retrieved from the original video frames.

function bbFile = ReflectBBOntoImages2 (newMedianFile, bags, shift, rescaleFactor, centredImages, foundFrames, params)

  bbFile = zeros (0, 7);
  
  % parameters
  personWidth = params.Results.personWidth;
  personHeight = params.Results.personHeight;
  minHeight = params.Results.minHeight;
    
  [m,n] = size (bags);
  if (m == 0 || n == 0)
      return;
  end;
  
  count = 1;
  for f = foundFrames';
      [rowNo, n] = find (newMedianFile(:,1) == f);
      croppedImg = centredImages(:,:,count);
      count = count + 1;
      [t,n] = find (croppedImg);
      if (max (t) - min (t) < minHeight)
              continue;
      end;

      medianPoint = newMedianFile(rowNo,4:5);
      for i = 1:m
          bagBoundingBox(1) = ceil (bags(i,1)) - shift (2);
          bagBoundingBox(2) = ceil (bags(i,2)) - shift (1);
          bagBoundingBox(3) = floor (bags(i,3));
          bagBoundingBox(4) = floor (bags(i,4));
          croppedImg2 = croppedImg;
          croppedImg2 (1:personHeight, 1:bagBoundingBox(1)) = 0;
          croppedImg2 (1:bagBoundingBox(2), 1:personWidth) = 0;
          croppedImg2 (1:personHeight, bagBoundingBox(1)+bagBoundingBox(3):personWidth) = 0;
          croppedImg2 (bagBoundingBox(2)+bagBoundingBox(4):personHeight, 1:personWidth) = 0;
          [t,n] = find (croppedImg2);
          if (size (t,1) == 0)
              continue;
          end;
          BB(1) = min (n) + medianPoint (1) - personWidth/2;
          BB(2) = min (t) + medianPoint (2) - personHeight/2;
          BB(3) = max (n) + medianPoint (1) - personWidth/2;
          BB(4) = max (t) + medianPoint (2) - personHeight/2;
          BB = BB ./ rescaleFactor;
          bbFile = [bbFile; [(f) (f) BB (i)]];
      end;
  end;
end