function [xsel,xsel_ladder,diagonalline,mainband] = definegrid2(imagex_align,POS_ArrayBOMB,startnum,xsel,xsel_ladder,sequence,Offset,diagonalline,xsel_ladder_calibrate,mainband,maxres);
%
% Define gridlines for 2D gel to allow quantitation..
% Rhiju Das, 29 November, 2004.
%
% Improvements in diagonal line fitting added Aug. 28, 2005.
%
% Also, now add functionality to use external calibration ladder
%  (how bands 105-260 run on a gel, for example) to annotate gel
%  between the point where the user stops and the "main band".
%

figure(1)
numlanes = size(imagex_align,2);
ContrastScale = sqrt(2);
if exist('pointertoaxis') axes(pointertoaxis); end;
subplot(1,1,1)
hold off;image(abs(imagex_align));hold on
maxprof = round(max(max(imagex_align))/80);
grayscaleon = 1;
setcolormap(grayscaleon, maxprof);   

axis off

sizex = size(imagex_align,2);
sizey = size(imagex_align,1);
totalBOMBres = length(POS_ArrayBOMB);
if ~exist('POS_ArrayLADDER') POS_ArrayLADDER=POS_ArrayBOMB;end;

totalLADDERres = length(POS_ArrayLADDER);

plottitle = [...
        'left button: set reference band    middle button (option-click): undo \newline',...
        'right button (apple-click): zoom in/out \newline',...
        '1,2,C: adjust colorscale    E,R:erase/refine       Q or Z:finished'];


%5' or 3' labeled?
whichdirection = sign(POS_ArrayBOMB(2) - POS_ArrayBOMB(1));

currentaxis = [1 sizex 1 sizey];
labelpos = -sizey/20;
axis(currentaxis);
stopinput = 0; zoomedin = 0; foundonepeak = 0;

%Define a diagonal line...
pixels=1:sizey;
if ~exist('diagonalline')
    diagonalline = pixels*(sizex/sizey);
end
if isempty(diagonalline)
    diagonalline = pixels*(sizex/sizey);
end
hold on;
h_diag = plot(diagonalline,pixels,'m','linewidth',2);

if ~exist('mainband')
    mainband=0;
end

%Draw any grid lines that have already been defined.
if ~exist('xsel'); xsel=[]; end;
if (length(xsel) == 0)
    xsel=[]; linelabels=[];linelabelsbomb=[];textlabelsbomb=[];
    countG = max(find(le(whichdirection*POS_ArrayBOMB,whichdirection*startnum)));
    prevG=countG;
else    
    xsel_pad = zeros(1,max(POS_ArrayBOMB)); xsel_pad(1: length(xsel)) = xsel;
    countG = max(find(xsel_pad(POS_ArrayBOMB)>0) )+1;   
    countG = min(countG, length(POS_ArrayBOMB));
    currentG = POS_ArrayBOMB(countG)
    [linelabels,h_main] = redraw_grid(xsel,sequence,Offset,labelpos,diagonalline,sizey,mainband);    
    if (countG>1)
        prevG = POS_ArrayBOMB(countG-1);
        foundonepeak = 1;
    end
end


while (stopinput == 0)
    ladderG=min(find(prevG<POS_ArrayLADDER));
    title( [plottitle,'\newline',...
            num2str(POS_ArrayBOMB(countG: min(countG+10,totalBOMBres) ))]);
%     title( [plottitle,'\newline',...
%             num2str(POS_ArrayBOMB(countG: min(countG+10,totalBOMBres) )),'\newline', ...
%             num2str(POS_ArrayLADDER(ladderG: min(ladderG+10,totalLADDERres) )) ]);
    updateaxislabel(xsel,diagonalline,sequence,Offset);    
    [xselpick,yselpick,button] = ginput(1);
    switch button
        case 1
            if (foundonepeak)                 
                xsel(POS_ArrayBOMB(countG)) = yselpick;
                currentG = POS_ArrayBOMB(countG);
            else %Special -- it's the first peak
                xsel(startnum) = yselpick; currentG = startnum;
            end
            endpoint=diagonalline(round(yselpick));
            linelabels(currentG,1) =plot( [0 endpoint],[yselpick yselpick]);
            linelabels(currentG,2) =plot( [endpoint endpoint],[yselpick sizey]);
            %what letter is this?
            letter = sequence(currentG-Offset); nucleotidecolor = getnucleotidecolor( letter);
            set(linelabels(currentG,:),'color',  nucleotidecolor,'clipping','on');
            
            if (foundonepeak) 
                [xsel,linelabels] = ...
                    fillingridlines(xsel,prevG,currentG,...
                    labelpos,linelabels,whichdirection,sequence,Offset,diagonalline,sizey); 
            end;
            foundonepeak = 1; prevG= currentG;
            countG = countG+1; 
            
        case 2 %user wants to undo last move...
            if (foundonepeak)
                countG = countG-2; 
                if (whichdirection>0) xsel    = xsel    (1:POS_ArrayBOMB(countG));
                else xsel(1: POS_ArrayBOMB(countG)-1) = 0*xsel(1: POS_ArrayBOMB(countG)-1);
                end
                countG = countG + 1;
                
                prevG = POS_ArrayBOMB(countG-1); currentG = POS_ArrayBOMB(countG);
                for k=prevG+whichdirection:whichdirection:currentG
                    set(linelabels(k,:),'visible','off');
                end
            end            
            
        case 3        
            if (zoomedin == 1)
                currentaxis = [0 sizex 1 sizey]; 
                axis(currentaxis);
                zoomedin = 0;
                        updateaxislabel(xsel,diagonalline,sequence,Offset);    

            else
                xselzoom = xselpick;
                yselzoom = yselpick;
                ymin = max(round(yselzoom - sizey/10),0);
                ymax = min(round(yselzoom + sizey/10),sizey);
                xmin = max(round(xselzoom - sizex/10),0);
                xmax = min(round(xselzoom + sizex/10),sizex);
                currentaxis=[xmin xmax ymin ymax ];
                axis(currentaxis);
                  updateaxislabel(xsel,diagonalline,sequence,Offset);    

                zoomedin = 1;
            end
    end;
    
    switch char(button)
        case '1'
            maxprof = maxprof/ContrastScale;
            setcolormap(grayscaleon, maxprof);    
        case '2'
            maxprof = maxprof*ContrastScale;
            setcolormap(grayscaleon, maxprof);    
        case {'c','C'}
            grayscaleon = 1 - grayscaleon;
            setcolormap(grayscaleon, maxprof);   
        case {'e','E'} %erase line
            [dummy, erasepeak] = min( (yselpick - xsel).^2 );
            if (erasepeak>1)
                k=erasepeak;
                set(linelabels(k),'visible','off');
                findG = find(POS_ArrayBOMB == k);
                [xselpeak,yselpick,button] = ginput(1);
                xsel(k) = yselpick;
                
                linelabels(k) = plot( [0 diagonalline(round(yselpick))],[yselpick yselpick]); 
                letter = sequence(k-Offset); nucleotidecolor = getnucleotidecolor( letter);
                %what letter is this?
                set(linelabels(k),'color',  nucleotidecolor,'clipping','on');
            end    
        case {'r','R'} %erase and refine line
            [dummy, erasepeak] = min( (yselpick - xsel).^2 );
            if (erasepeak>0)
                k=erasepeak;
                set(linelabels(k),'visible','off');
                findG = find(POS_ArrayBOMB == k);
                
                [xselpeak,yselpick,button] = ginput(1);
                xsel(k) = yselpick;
                linelabels(k) = plot( [0 diagonalline(round(yselpick))],[yselpick yselpick]); 
                letter = sequence(k-Offset); nucleotidecolor = getnucleotidecolor( letter);
                set(linelabels(k),'color',  nucleotidecolor,'clipping','on');
                
               if (~isempty(findG)) 
                    %user would like guessed band positions rescaled between this and neighboring G's.
                    if whichdirection==1
                        loGnum = max(find(POS_ArrayBOMB < k));
                        hiGnum = loGnum + 1;
                    else
                        loGnum = min(find(POS_ArrayBOMB < k));
                        hiGnum = loGnum - 1;
                    end                    
                    loG = POS_ArrayBOMB(loGnum);
                    hiG = POS_ArrayBOMB(hiGnum);
                    for n = loG+1 : k-1
                        set(linelabels(n),'visible','off');
                        xsel(n) =  xsel(loG) +  ((n-loG)/(k-loG))*(xsel(k)-xsel(loG));
                        linelabels(n) = plot( [0 diagonalline(round(xsel(n)))],[xsel(n) xsel(n)]); 
                        letter = sequence(n-Offset); nucleotidecolor = getnucleotidecolor( letter);
                        set(linelabels(n),'color',  nucleotidecolor,'clipping','on');
                    end    
                    for n = k+1: hiG-1
                        set(linelabels(n),'visible','off');
                        xsel(n) =  xsel(hiG) +  ((n-hiG)/(k-hiG))*(xsel(k)-xsel(hiG));
                        linelabels(n) = plot( [0 diagonalline(round(xsel(n)))],[xsel(n) xsel(n)]); 
                        letter = sequence(n-Offset); nucleotidecolor = getnucleotidecolor( letter);
                        set(linelabels(n),'color',  nucleotidecolor,'clipping','on');
                    end   
                end
            end    
        case{'d','D'} %Redraw line defining the "diagonal".
            %Zoom out, and just draw image..
            hold off;image(abs(imagex_align));hold on
            setcolormap(grayscaleon, maxprof);   
            currentaxis = [0 sizex 1 sizey]; 
            axis(currentaxis)
            zoomedin = 0;
            axis off            
            %User defines new diagonal.
            [xsel_pick,ysel_pick]=quickpolyxline(imagex_align,0,0,0,grayscaleon,maxprof,ContrastScale);
            
            [xsel_pick; ysel_pick]; hold on;
            plot(xsel_pick,ysel_pick,'b');
            diagonalline = interp1(ysel_pick,xsel_pick,pixels);
    %Now refine this diagonal.
%             xpixels = 1:sizex;
%             for i=1: sizey  
%                 [dummy, maxpt] = max( -(xpixels - diagonalline(i)).^4 + imagex_align(i,xpixels));  
%                 diagonalline_refine(i) = maxpt;    
%             end    
%             diagonalline = diagonalline_refine;

            %Redraw grid lines
            hold on; h_diag = plot(diagonalline,pixels,'m','linewidth',2);
            [linelabels,h_main] = redraw_grid(xsel,sequence,Offset,labelpos,diagonalline,sizey,mainband);    
        case{'m','M'} %Line through main bands.
            mainband = xselpick;
            if exist('h_main')
                set(h_main,'visible','off');
            end
            h_main = plot([mainband mainband],[1 sizey],'k');
        case {'q','Q','z','Z'}
            stopinput = 1;
        case {'l','L'}
            %Use calibration ladder to fill in further points.
            ladderres = find(xsel_ladder_calibrate>0); %Residues for which ladder is defined in gel 1.
            
            %Fill in ladder residues that have been preassigned.
            bomblanes =  find(xsel>0);
            diagonalpoints(bomblanes) = interp1(1:sizey,diagonalline,xsel(bomblanes));
            [dummy,index] = min(xsel(bomblanes));   
            lastbombres = bomblanes(index);
            xsel_ladder=zeros(1,maxres);
            xsel_ladder(bomblanes) = diagonalpoints(bomblanes);

            figure(4)
            subplot(1,1,1)
            plot(xsel_ladder,'g'); hold on
            
            xsel_ladder(maxres) = mainband;
            anchorpoint1 = maxres;
            anchorpoint2 = lastbombres;
            res1 = min(anchorpoint1, anchorpoint2);
            res2 = max(anchorpoint1, anchorpoint2);
            ladderres_assign = intersect( ladderres, res1:res2);
            xsel_ladder(ladderres_assign) = xsel_ladder(res1) + ...
                (xsel_ladder_calibrate(ladderres_assign)-xsel_ladder_calibrate(res1))*(xsel_ladder(res2)-xsel_ladder(res1))/...
                (xsel_ladder_calibrate(res2)-xsel_ladder_calibrate(res1));
            plot(xsel_ladder,'r');  hold off
            figure(1)        
    end
end

if isempty(xsel_ladder);
  fprintf(1,'xsel ladder not defined, using diagonal');
  xsel_ladder=xsel;
  bomblanes =  find(xsel>0);
  goodpoints = find( isfinite(diagonalline));
  diagonalpoints(bomblanes) = interp1(goodpoints,diagonalline(goodpoints),xsel(bomblanes));
  xsel_ladder(bomblanes) = diagonalpoints(bomblanes);
end 

title('Done assigning bands.');    
set(gcf,'Pointer','arrow');