% Usage: halftone = jarvis(original)
%
% Created by Ramesh Neelamani, Rice University on 11/9/99
%
% This gives the halftoned image of the input image using Jarvis, Judice and
% Ninke's method.
%
% \bibitem{Jarvis} 
% J.~Jarvis, C.~Judice, and W.~Ninke, ``A survey of techniques for the 
% display of continuous tone pictures on bilevel displays,'' 
% {\em Comp. Graph and Image  Proc.}, vol.~5, pp.~13--40, 1976.


function[halftoned]  = jarvis(x)
x = double(x);

[M,N] = size(x);
T = 127.5;
y = x;
error = 0;

y= [127.5*ones(M,2) y 127.5*ones(M,2) ; 127.5*ones(2,N+4)];
%y= [0*ones(M,2) y 0*ones(M,2) ; 0*ones(2,N+4)];
z = y;
for rows = 1:M  
  for cols = 3:N+2
    z(rows,cols) =255*(y(rows,cols)>=T);
    error = -z(rows,cols) + y(rows,cols);

    y(rows,cols+2) = 5/48 * error + y(rows,cols+2);
    y(rows,cols+1) = 7/48 * error + y(rows,cols+1);

    y(rows+1,cols+2) = 3/48 * error + y(rows+1,cols+2);
    y(rows+1,cols+1) = 5/48 * error + y(rows+1,cols+1);
    y(rows+1,cols+0) = 7/48 * error + y(rows+1,cols+0);
    y(rows+1,cols-1) = 5/48 * error + y(rows+1,cols-1);
    y(rows+1,cols-2) = 3/48 * error + y(rows+1,cols-2);
 
    y(rows+2,cols+2) = 1/48 * error + y(rows+2,cols+2);
    y(rows+2,cols+1) = 3/48 * error + y(rows+2,cols+1);
    y(rows+2,cols+0) = 5/48 * error + y(rows+2,cols+0);
    y(rows+2,cols-1) = 3/48 * error + y(rows+2,cols-1);
    y(rows+2,cols-2) = 1/48 * error + y(rows+2,cols-2);
  end
end

halftoned = z(1:M,3:N+2);
z = z(1:M,3:N+2);
y = y(1:M,3:N+2);
