function imagex_out = calculate_alignedprofiles_2Dgel(imagex,anchorlines,diagonalline,mainband);

[sizex,sizey] = size( imagex);  

numanchorlines = size(anchorlines,2);
imagex_out = imagex;

if (numanchorlines == 0) return;end;

%Need these to be integers, as they will determine indices.
anchorlines = round(anchorlines);
diagonalline = round(diagonalline);
mainband = round(mainband);

%In an earlier step, I accidentally left some of the diagonalline
% values as nan...
badpoints = find(~isfinite(diagonalline));
diagonalline(badpoints) = sizey;
badpoints = find(~isfinite(imagex));
imagex(badpoints) = 0;

for k=1:sizex
  goodpoints = find(anchorlines(k,:,1) <= diagonalline(k) & ...
		    anchorlines(k,:,1) >= mainband);
  if (length(goodpoints)>0 )
    [dummy, sortindex] = sort( anchorlines(k,goodpoints,1) );
    currentanchors =   anchorlines(k,goodpoints(sortindex),1);
    gotoanchors =      anchorlines(k,goodpoints(sortindex),2);

    for i = 1: length(currentanchors)-1
      currentbins   = currentanchors(i)  : min(currentanchors(i+1)+1,sizey);
      gotobins      = gotoanchors(i)     : gotoanchors(i+1)+1;
      scalefactor = (max(currentbins) - min(currentbins))/(max(gotobins)-min(gotobins));

      imagex_out(k,gotobins) = interp1(currentbins-currentbins(1), imagex(k,currentbins), ...
				     (gotobins-gotobins(1)) * scalefactor );    
    end  
  end
end
