function [Output] = LU_pix_by_pix(Image,Library)

% Linear Unmixing
% Silas J. Leavesley, PhD
% University of South Alabama
% Last Updated: 2/7/2017

% To visualize output data:
% figure(1)
% for i = 1:length(Output.data(1,1,:))
%   subplot(1,length(Output.data(1,1,:)),i)
%   imagesc(Output.data(:,:,i))
% end
% colormap(gray) % or any other colormap, as desired

tic

Image=double(Image);

[L M N]=size(Image);
[O P]=size(Library);

h=waitbar(0,'Please wait...');
for i=1:L
    waitbar(i/L,h,sprintf('Unmixing row %5.0f out of %5.0f',i,L))
    for j=1:M
        [x(:,i,j),resnorm,residual]=lsqnonneg(Library,permute(double(Image(i,j,:)),[3 1 2]));
        Output.Error.RMS(i,j)=(sum(residual.^2)/O)^0.5;
        RMS_signal(i,j)=(sum((Image(i,j,:).^2))/O)^0.5;
    end
end

Output.data=permute(x,[2 3 1]);
Output.Error.Percent_RMS=Output.Error.RMS./RMS_signal;
delete(h)
toc