% This code is Anthony Ripa's adaptation of Prof Alex Berg's code

I = imread('pics\pic2.jpg'); %I is 640h x 243w with elements from 000-255
I = im2double(I);            %I is 640h x 243w with elements from 0.0-1.0
%I = round(I);       % Increase Contrast
[h,w] = size(I)
t = floor(h/3)
I1 = I(0*t+1:1*t,:); %I'm told this is Blue
I2 = I(1*t+1:2*t,:); %I'm told this is Green
I3 = I(2*t+1:3*t,:); %I'm told this is Red
x1 = 50
x2 = 200
y1 = 50
y2 = 150
ssd_offset = zeros(11,11)
for Xo = -5:5
    for Yo = -5:5
        b = I1(y1+Yo:y2+Yo,x1+Xo:x2+Xo);
        r = I3(y1   :y2   ,x1   :x2   );
        ssd_offset(Yo+6,Xo+6) = sum(sum((b-r).^2));
    end
end
ssd_offset
[Yo,Xo]=find(ssd_offset==min(ssd_offset(:)));
Xo=Xo-6
Yo=Yo-6
Blue = I1(1+6+Yo:end-6+Yo,1+6+Xo:end-6+Xo); 

ssd_offset = zeros(11,11)
for Xo = -5:5
    for Yo = -5:5
        g = I2(y1:y2,x1:x2);
        r = I3(y1+Yo:y2+Yo,x1+Xo:x2+Xo);
        ssd_offset(Yo+6,Xo+6) = sum(sum((g-r).^2));
    end
end
ssd_offset
[Yo,Xo]=find(ssd_offset==min(ssd_offset(:)));
Xo=Xo-6
Yo=Yo-6
Green = I2(1+6-Yo:end-6-Yo,1+6-Xo:end-6-Xo); 

Red = I3(1+6:end-6,1+6:end-6);
I = cat(3,Red,Green,Blue); % Blends in order R,G,B
%The following line shows the misaligned version of the picture
%I = cat(3,I3(1+6:end-6,1+6:end-6),I2(1+6:end-6,1+6:end-6),I1(1+6:end-6,1+6:end-6));
image(I)                   %I is 640h x 243w x 3c with elements from 0.0-1.0
%imwrite(I,'pic1align.jpg')