function [allprofiles,crosspeakranges] = plotgelprofiles_pickcrosspeakranges(imagex_align,xsel,xsel_ladder,mainband,POS_ArrayBOMB,bombres,colorcode,holdon,crosspeakranges)
figure(1)
clf;
if ~exist('bombres')
  bombres = intersect(POS_ArrayBOMB, find(xsel>0));
end
if ~exist('colorcode')
  colorcode = [0 0 0];
end
if ~exist('holdon')
  holdon = 0;
end
if ~exist('crosspeakranges')
  crosspeakranges = [];
end

endlabel = 1; % 5 prime labeled.
if (POS_ArrayBOMB(1)>POS_ArrayBOMB(2))
  endlabel = -1; % 3 prime labeled
end

%Sort bombres to go from bottom to top of gel:
[dummy, sortindex] = sort(-1*xsel(bombres));
bombres = bombres(sortindex);

numbombs = length(xsel);
numcolumns = 1;
whichcolumn = 1;
VERTICAL_SPACING = 1.0;
MAX_PROFILE = VERTICAL_SPACING*1.2;
 [allprofiles,allprofiles_offset,wheresignalstarts,wheresignalends,h_prof,h_point,plotmeanx,plotmeany,count] =  drawprofiles(bombres,imagex_align,xsel,xsel_ladder,mainband,colorcode,holdon,crosspeakranges,VERTICAL_SPACING,MAX_PROFILE);

stopinputcrosspeakranges = 0; 
while (~stopinputcrosspeakranges)
  [xpick1,ypick1,button]=ginput(1);
  switch button
   case 1 % Box a crosspeak
    count=count+1;
    finalRect = rbbox;                   % return figure units
    point2 = get(gca,'CurrentPoint');    % button up detected
    xpick2 = point2(1,1);
    ypick2 = point2(1,2);
    xcenter = (xpick1+xpick2)/2;
    ycenter = (ypick1+ypick2)/2;

    crosspeakranges(count,3) = round(min(xpick1,xpick2));
    crosspeakranges(count,4) = round(max(xpick1,xpick2));
    rangepoints =  crosspeakranges(count,3):crosspeakranges(count,4);
    [dummy,bestbombindex] = min( abs(ycenter - mean(allprofiles_offset(rangepoints,:),1)));
    crosspeakranges(count,1) = bombres(bestbombindex);

    [dummy,maxindex] = max(allprofiles(rangepoints,bestbombindex));
    xmax = rangepoints(maxindex);
    crosspeakranges(count,5) = xmax;
    [dummy,bestxindex] = min( abs( rangepoints(maxindex) - xsel_ladder) );
    crosspeakranges(count,2) = bestxindex;
    crosspeakranges(count,6) = 1;
    
     [h_prof,h_point,plotmeanx,plotmeany] =...
	 drawcrosspeakranges(crosspeakranges,count,allprofiles,allprofiles_offset, ...
		       bombres,h_prof,h_point,plotmeanx,plotmeany);   

   case 2 %Erase
    if (count>0)
      eraseindex = getclosestmarkedregion(xpick1,ypick1,plotmeanx,plotmeany);
      set(h_prof(eraseindex),'visible','off');
      set(h_point(eraseindex),'visible','off');
      newindex = [1:eraseindex-1 eraseindex+1:count];
      h_prof = h_prof(newindex);
      h_point = h_point(newindex);
      crosspeakranges = crosspeakranges(newindex,:);
      plotmeanx = plotmeanx(newindex);
      plotmeany = plotmeany(newindex);
      count = count-1;
    end
   case 3 %Mark as glitch
    if (count>0)
      i = getclosestmarkedregion(xpick1,ypick1,plotmeanx,plotmeany);
      set(h_prof(i),'visible','off');
      set(h_point(i),'visible','off');
      crosspeakranges(i,6) = 1 - crosspeakranges(i,6);
      [h_prof,h_point,plotmeanx,plotmeany] = ...
	  drawcrosspeakranges(crosspeakranges,i,allprofiles,allprofiles_offset,bombres,h_prof,h_point,plotmeanx,plotmeany);
    end
  end
  switch char(button)
   case {'q','Q','z','Z'}
    stopinputcrosspeakranges = 1;
   case {'b','B'}
    crosspeakranges = plotbackground(VERTICAL_SPACING,bombres,allprofiles,allprofiles_offset,wheresignalstarts,wheresignalends,crosspeakranges,endlabel);
    [allprofiles,allprofiles_offset,wheresignalstarts,wheresignalends,h_prof,h_point,plotmeanx,plotmeany,count] = drawprofiles(bombres,imagex_align,xsel,xsel_ladder,mainband,colorcode,1,crosspeakranges,VERTICAL_SPACING,MAX_PROFILE);
   case{'r','R'} % Refine maximum.
    if (count>0)
      i = getclosestmarkedregion(xpick1,ypick1,plotmeanx,plotmeany);
      set(h_prof(i),'visible','off');
      set(h_point(i),'visible','off');
      rangepoints = crosspeakranges(i,3): crosspeakranges(i,4);
      bestbombindex = find(bombres == crosspeakranges(i,1));
      [dummy,maxindex] = max(allprofiles(rangepoints,bestbombindex));
      xmax = rangepoints(maxindex);
      crosspeakranges(i,5) = xmax;
      [h_prof,h_point,plotmeanx,plotmeany] = ...
	  drawcrosspeakranges(crosspeakranges,i,allprofiles,allprofiles_offset,bombres,h_prof,h_point,plotmeanx,plotmeany);
    end    
  end;    
end
hold off

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


function i = getclosestmarkedregion(xpick1,ypick1,plotmeanx,plotmeany);
xlim = get(gca,'xlim');
ylim = get(gca,'ylim');
[dummy, i] = min((ypick1 - plotmeany).^2/(ylim(1)-ylim(2))^2 +...
		 (xpick1 - plotmeanx).^2/(xlim(1)-xlim(2))^2);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [allprofiles,allprofiles_offset,wheresignalstarts,wheresignalends,h_prof,h_point,plotmeanx,plotmeany,count] = drawprofiles(bombres,imagex_align,xsel,xsel_ladder,mainband,colorcode,holdon,crosspeakranges,VERTICAL_SPACING,MAX_PROFILE)
numbombres = size(bombres,2);
numpixels = size(imagex_align,2);
numpixelsy = size(imagex_align,1);

allprofiles = zeros(numpixels,numbombres);
allprofiles_offset = zeros(numpixels,numbombres);
for whichplot=1: numbombres
  vertical_offset = whichplot*VERTICAL_SPACING;
  imagepositions = xsel(bombres(whichplot));

  pos1 =  round((xsel(bombres(whichplot)+1) + xsel(bombres(whichplot)))/2);
  pos2 =  round((xsel(bombres(whichplot)-1) + xsel(bombres(whichplot)))/2);
  imagepositions = min(pos1,pos2):max(pos1,pos2);
      
  if length(imagepositions) == 0
    imagepositions = round(xsel(bombres(whichplot)));
  end
  imagepositions = min(imagepositions,numpixelsy-2);

  %Use average signal for this bomb to determine normalization.
  wheresignalstarts(whichplot) = round(mainband)+20;
  wheresignalends(whichplot)   = round(xsel_ladder(bombres(whichplot))) -  100;
  wheresignalends(whichplot) = max(wheresignalends(whichplot), wheresignalstarts(whichplot)+10);

  if (imagepositions>0)
    %Average over three rows to get better signal to noise:
    profilescans = mean(imagex_align(round(imagepositions),:),1);
    %    profilescans = imagex_align(round(imagepositions),:);
%    profilescans = smooth3(profilescans);
    badpoints = find( ~isfinite(profilescans));
    profilescans(badpoints) = 0.0;
    
    mainpeakintensities = mean(profilescans(:, wheresignalstarts(whichplot):wheresignalends(whichplot)),2);
    
    [mainpeakintensity, strongestpeak] = max(mainpeakintensities);
    profilescan = profilescans(strongestpeak,:)/mainpeakintensity;

    startprofile = round(mainband)+20;
    endprofile   = round(xsel_ladder(bombres(whichplot)))-10;
    actualmaxprofile = max(profilescan(startprofile+10: endprofile-100));
    if (actualmaxprofile> MAX_PROFILE) %Signal is too big!
      profilescan = profilescan*MAX_PROFILE/actualmaxprofile;
    end
    
    goodpixels = find(profilescan>0 & profilescan<=MAX_PROFILE);
    
    goodpixels = intersect(goodpixels, [startprofile:endprofile]);
    if (holdon) 
      hold on;
    end
    plot(goodpixels,...
	 profilescan(goodpixels)+vertical_offset,'color',colorcode); hold on

    allprofiles(goodpixels,whichplot) = profilescan(goodpixels);
    allprofiles_offset(:,whichplot) = vertical_offset;
    allprofiles_offset(goodpixels,whichplot) = profilescan(goodpixels)+vertical_offset;

    if length(goodpixels)>0
      text( max(goodpixels), profilescan(max(goodpixels))+vertical_offset,num2str(bombres(whichplot)));
    end
  end
end % Go through profiles

%Go through each plot and mark axes, etc.
hold off;
axis([mainband mainband+900 0 VERTICAL_SPACING*(numbombres+2)])
set(gca,'ytick',[]);

%Mark approximate residue positions along axis...
goodpoints = find(xsel_ladder>0);
goodpointsmod10 = intersect(goodpoints, [0:10:1000]);

% A little silly -- matlab needs tickmarkers to be in the right order.
[xmark_sort, order_sort] =sort(xsel_ladder(goodpointsmod10));

set(gca,'xtick', xmark_sort,'xticklabel',goodpointsmod10(order_sort),'xgrid','on', ...
	'ticklength', [0 0],'xaxislocation','bottom','fontsize',9);
xticklabel_rotate;


hold on
h_prof=[];h_point=[];plotmeanx=[];plotmeany=[];
count = size(crosspeakranges,1);
[h_prof,h_point,plotmeanx,plotmeany] = ...
    drawcrosspeakranges(crosspeakranges,1:count,allprofiles,allprofiles_offset,bombres,h_prof,h_point,plotmeanx,plotmeany);    

hold off

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function crosspeakranges = plotbackground(VERTICAL_SPACING,bombres,allprofiles,allprofiles_offset,wheresignalstarts,wheresignalends,crosspeakranges,endlabel)
clf;
hold on;

%Attempt to compute backgrounds:
numbombres = size(bombres,2);
numpixels = size(allprofiles,1);
for whichplot=1: numbombres
  vertical_offset = whichplot*VERTICAL_SPACING;
%Find a list of bomb residues, but without the closest neighbors
  disttootherbombs = abs(bombres(whichplot) - bombres);
  NEIGHBORCUTOFF = 4;
  goodforbackground = find(disttootherbombs > NEIGHBORCUTOFF);

% From that list choose the three that are closest. Note that
% I'm preferring ones that are further down the gel!
% Note that I use the information on 3' vs. 5' to figure out which
% way is down (endlabel).
  NUMBACKGROUND=5;
  disttootherbombs = abs(bombres(whichplot) - 1*endlabel - bombres); 
  [dummy,bestindex] = sort( disttootherbombs(goodforbackground));
  bestforbackground = goodforbackground( bestindex(1:NUMBACKGROUND) );

  backgroundprofiles = zeros(numpixels,NUMBACKGROUND);
  backgroundprofiles_interp = zeros(numpixels,NUMBACKGROUND);
  count = 0;
  for k = bestforbackground    
    count = count+1;
    %Find common ground between neighboring profile and target profile
    goodpixels = find(allprofiles(:,whichplot)>0 & ...
		      allprofiles(:,  k)>0);
    goodpixels = intersect(goodpixels, wheresignalstarts(k):wheresignalends(k));
    %Ignore areas where the neighboring profile may have a big peak!
    if size(crosspeakranges,1)>0
      relevantcrosspeaks = find( crosspeakranges(:,1) == bombres(k));
      %[bombres(whichplot) bombres(k) relevantcrosspeaks']
      for i = relevantcrosspeaks'
	goodpixels = setdiff(goodpixels, crosspeakranges(i,3): ...
					 crosspeakranges(i,4));
      end      
    end

    %Normalization is tricky ... look at shared points, that are
    %not too close to beginning or end
    %(wheresignalstarts/wheresignalends)
    % And also not here there may be a putative peak.
    goodpixels_fornorm = intersect(goodpixels, ...
				   wheresignalstarts(whichplot):wheresignalends(whichplot));
    if size(crosspeakranges,1)>0
      relevantcrosspeaks = find( crosspeakranges(:,1) == bombres(whichplot));
      for i = relevantcrosspeaks'
	goodpixels_fornorm = setdiff(goodpixels_fornorm, crosspeakranges(i,3): ...
					 crosspeakranges(i,4));
      end      
    end

    if length(goodpixels_fornorm)>2
      normfactor = mean(allprofiles(goodpixels_fornorm,whichplot))/...
	  mean(allprofiles(goodpixels_fornorm,k));
      
      %Interpolation       
      interpolatedprofile = normfactor*interp1(goodpixels, ...
					       allprofiles(goodpixels,k),1:numpixels);
      plot(1:numpixels,...
	   interpolatedprofile + vertical_offset,'.','markersize',1,'color',[0.8 0.8 0.8]);
      backgroundprofiles_interp(:,count) = normfactor*interp1(goodpixels, ...
						  allprofiles(goodpixels,k),1:numpixels,'linear','extrap');
      
      % Emphasize points that did not require interpolation.
      plot(goodpixels,...
	   normfactor*allprofiles(goodpixels,k) + vertical_offset,'.','markersize',1,'color',[0.5 0.5 0.5]);
      backgroundprofiles(goodpixels,count) = normfactor*allprofiles(goodpixels,k); 
    end
  end
  
  %Now that we've got some guesses for the background, go through
  %crosspeakranges, and estimate how many standard deviations each
  %putative peak rises above background.
  if size(crosspeakranges,1)>0
    relevantcrosspeaks = find( crosspeakranges(:,1) == bombres(whichplot));
    for i = relevantcrosspeaks'
	xmax = crosspeakranges(i,5);
	goodprofiles = find( backgroundprofiles(xmax,:)>0);
	backok = 2;
	if length(goodprofiles)>2
	  stdevprof = std( backgroundprofiles(xmax, goodprofiles));
	  meanprof  = mean( backgroundprofiles(xmax, goodprofiles));
	else %Attempt interpolation from other sources.
	  goodprofiles = find(backgroundprofiles_interp(xmax,:)>0);
	  if length(goodprofiles)>3
	    [dummy, sortindex] = sort(backgroundprofiles_interp(xmax,goodprofiles));
	    goodprofiles = goodprofiles(sortindex(1:3));
	  end
	  stdevprof = std( backgroundprofiles_interp(xmax, goodprofiles));
	  meanprof  = mean( backgroundprofiles_interp(xmax, goodprofiles));
	  backok = 1;
	end
	if (stdevprof<meanprof/10) %Something went wrong
	  stdevprof = meanprof/10;
	end
	
	%[crosspeakranges(i,[1:2]) meanprof stdevprof allprofiles(xmax,whichplot)]
	crosspeakranges(i,7) = (allprofiles(xmax,whichplot)-meanprof)/stdevprof;

	%Output to user.
	if crosspeakranges(i,6) == 1 %A putative real signal, not a
                                     %user-defined glitch
	  fprintf(1,'CROSSPEAK %d-%d : %5.2f sigma over background\n',...
		  crosspeakranges(i,1),crosspeakranges(i,2),crosspeakranges(i,7));
    	  if (backok == 1) 
	    %fprintf(1,['Warning: CROSSPEAK %d-%d uses backgd estimates' ...
		%       ' from interpolated profiles!\n'],crosspeakranges(i,1),crosspeakranges(i,2));
	  end
	end
    end   
  end  
end % Go through profiles

fprintf(1,'\n');
