function EECS_203A_HW4_computer_prob_a
%
% Solve HW4, EECS 203A, computer problem a.
% Apply Laplace method of sharpeing.
% Filter image with laplace, then subtract from
% original image and scale.
%
% by Nasser Abbasi
% EECS 203A, UCI, Fall 2004.
%
A=[1 1 1; 1 -8 1; 1 1 1];  % laplace filter

nRow=480;  % rows
nCol=640;  % columns

fileName='triangle.raw';
 
fid=fopen(fileName,'r');
f=fread(fid,[nCol,nRow],'uint8');
fclose(fid);

f=f';

figure;
imagesc(f,[0 255]);
colormap gray;
colorbar;
title(sprintf('Original raster file %s',fileName));

% I could use the following matlab function called
% filter2 to do the job, but instruction said to 
% use our code so I can have the new image smaller
%
% Y1=filter2(A,f);
% figure;
% imagesc(Y1,[0 255]);
% colormap gray;
% colorbar;
% title(sprintf('laplace filtering using matlab code'));
%

nRow2=nRow-2;
nCol2=nCol-2;

Y2=zeros(nRow2,nCol2);
for(i=1:nRow2)
    for(j=1:nCol2)
        ii=i+1;
        jj=j+1;
        Y2(i,j)=f(ii-1,jj-1)*A(1,1) + f(ii-1,jj)*A(1,2) + f(ii-1,jj+1)*A(1,3) ...
               +f(ii,jj-1)*A(2,1)   + f(ii,jj)*A(2,2)   + f(ii,jj+1)*A(2,3)   ...
               +f(ii+1,jj-1)*A(3,1) + f(ii+1,jj)*A(3,2) + f(ii+1,jj+1)*A(3,3);
    end
end

figure;
imagesc(Y2,[0 255]);
colormap gray;
colorbar;
title(sprintf('result of applying laplace filter, before scaling'));

s  = min(min(Y2));
s  = abs(s);
Y2 = Y2+s;
m  = max(max(Y2));
delta = m/255;
Y2 = 1/delta .* Y2;
Y2 = round(Y2);

figure;
imagesc(Y2);
colormap gray;
colorbar;
title(sprintf('result of applying laplace filter after scaling'));

%scale the sharp image
f(2:end-1,2:end-1) = f(2:end-1,2:end-1) - Y2;
s  = min(min(f));
s  = abs(s);
f = f+s;
m  = max(max(f));
delta = m/255;
f = 1/delta .* f;
f = round(f);

figure;
imagesc(f);
colormap gray;
colorbar;
title(sprintf('result of sharpining'));

fileName='triangle_scaled_laplace.raw';
fid=fopen(fileName,'wb');
count=fwrite(fid,Y2','uint8');
fclose(fid);
fprintf('written %d elements to file %s\n',count,fileName);

fileName='triangle_sharp.raw';
fid=fopen(fileName,'wb');
count=fwrite(fid,f','uint8');
fclose(fid);
fprintf('written %d elements to file %s\n',count,fileName);

end