         
function  [pixOut,ctrlOut] = AvgFilter(pixIn,ctrlIn)
%AvgFilter
% Calculates the average pixel value for each 3x3 kernel
% pixIn and pixOut are scalar uint8 pixel values.
% ctrlIn and ctrlOut are structures that contain control signals associated
% with the pixel.
% You can generate HDL code from this function.

  persistent linemem;
  if isempty(linemem)
     linemem = visionhdl.LineBuffer;
  end
  persistent dataShiftReg; 
  if isempty(dataShiftReg)
      % use typeof(pixIn)?
     dataShiftReg = fi(zeros(3,3),0,8,0);
  end
  % HDL code gen does not support arrays of structs
  persistent controlShiftReg1;
  persistent controlShiftReg2;    
  persistent controlShiftReg3;
  if isempty(controlShiftReg1)
     controlShiftReg1 = pixelcontrolstruct();
     controlShiftReg2 = pixelcontrolstruct();
     controlShiftReg3 = pixelcontrolstruct();
  end
  
  persistent div9;
  if isempty(div9)
      div9 = fi(1/9,0,12,15);
  end

 % Advance shift registers 
 dataShiftReg(:,2:end) = dataShiftReg(:,1:end-1);
 controlShiftReg3 = controlShiftReg2;
 controlShiftReg2 = controlShiftReg1;
 
 % Fetch next column
 [dataShiftReg(:,1),controlShiftReg1] = linemem(fi(pixIn,0,8,0),ctrlIn);
 
 % Calculate the average over the neighborhood
 pixOut = uint8((sum(dataShiftReg(:),'native')).*div9);
 ctrlOut = controlShiftReg3;

end