function pick_ts_cands_v5(im21_input,im33_input)

%Fred Cross June 2016 The Rockefeller University

%

%save in csv Stinger file in global fid_out
global ninespots;
global source_plate;
global source_plate_name;
global target_plate;
global target_row;
global target_col;
global source_format;
global keep_picking;
global fid_out;

global data_directory;

global ID;
global fid_info;

global corners_x;
global corners_y;

global target_format;


 if source_format ==1536
       linewidth=1;
       linefactor=2;
   else
       linewidth=2;
       linefactor=2;
   end


source_format=(size(corners_x,1)-1)*(size(corners_x,2)-1);

im33=imadjust(im33_input);
im21=imadjust(im21_input);


comb(:,:,1)=im33;  
comb(:,:,2)=comb(:,:,1);
comb(:,:,3)=im21;


%put red where 21 image is low, for contrast
max_r=max(max(max(comb(:,:,1))));

max_b=max(max(max(comb(:,:,3))));

comb(:,:,1)=comb(:,:,1)+(max_b-comb(:,:,3))/2;
comb(:,:,1)=min(max_r,comb(:,:,1));

% At this point try having two matrices, comb (as written), and imcomb as
% uint8 for display. A quick test suggests this will make image refreshing
% much faster

imcomb=uint8(ceil(256*comb));




figure(1);clf;set(1,'Position',[  22         493        1124         806]);
imagesc(imcomb);


draw_grid_on_image(corners_x,corners_y);

while 1
    q=menu('Grid options','Change','Keep');
    if q==1
        disp('Change corners in Fig 301 to adjust grid');
        [corners_x,corners_y,bestangle]=adjust_corners(corners_x,corners_y,imcomb,source_format);
        title('Proceed to selection?');

        
    else
        disp('Proceed to selection');
        break
    end
end

top_of_grid=min(corners_y(1,:));
bottom_of_grid=max(corners_y(end,:));

left_of_grid=min(corners_x(:,1));
right_of_grid=max(corners_x(:,end));

try
%comb([1:max(1,top_of_grid-20),min(bottom_of_grid+20,size(im21,1)):end],:,:)=0;
%comb(:,[1:max(left_of_grid-20,1),min(right_of_grid+20,size(im21,2)):end],:)=0;

imcomb([1:max(1,top_of_grid-20),min(bottom_of_grid+20,size(im21,1)):end],:,:)=0;
imcomb(:,[1:max(left_of_grid-20,1),min(right_of_grid+20,size(im21,2)):end],:)=0;

catch
    disp('couldnt trim edges');
end

figure(1);clf;imagesc(imcomb);title('Calculating levels in cells');
draw_grid_on_image(corners_x,corners_y);

%make rowval and colval label matrices

label_im_rows=0*im21;
label_im_cols=0*im21;

%Determine pixel occupancy


repeat_p=mean(corners_y(end,:)-corners_y(1,:))/size(corners_y,1);
repeat_l=mean(corners_x(:,end)-corners_x(:,1))/size(corners_x,2);

edge_size=round((repeat_p+repeat_l)/20);  %i.e. about 5% off at top/bottom/left/right

%figure(4);set(4,'Position',[  1541         327         366         289  ]);

    for row_index=1:size(corners_x,1)-1
        for col_index=1:size(corners_x,2)-1
            
           
          
            [toprow,bottomrow,leftcol,rightcol]=get_square_borders(row_index,col_index,corners_x,corners_y,edge_size);
        
           
            label_im_rows(toprow:bottomrow,leftcol:rightcol)=row_index;
            label_im_cols(toprow:bottomrow,leftcol:rightcol)=col_index;
            
            vals21(row_index,col_index)=double(sum(sum(im21(toprow:bottomrow,leftcol:rightcol))));
            vals33(row_index,col_index)=double(sum(sum(im33(toprow:bottomrow,leftcol:rightcol))));
            
             

  %          if rand<0.05
   %             composite=[im21(toprow:bottomrow,leftcol:rightcol);ones(10,rightcol-leftcol+1);im33(toprow:bottomrow,leftcol:rightcol)];
    %            imagesc(composite);colormap gray;
     %       end
           
        end
        
    end
 %  close(4);
    

figure(1);clf;set(1,'Position',[  22         493        1124         806]);
imagesc(imcomb);
draw_grid_on_image(corners_x,corners_y);
title(sprintf('select wt position (or cell with ~maximum growth at 33) from image 1;\nif 33 is light, then better to take a mid-range one'));
figure(1);
while 1
    [x,y,button]=ginput(1);
    
    
    
    x=round(x);
    y=round(y);
    try
        picked_col=label_im_cols(y,x);
        picked_row=label_im_rows(y,x);
        wt_val21=vals21(picked_row,picked_col);
        vals21=vals21/wt_val21;
        wt_val33=vals33(picked_row,picked_col);
        vals33=vals33/wt_val33;
        break
    catch
        title('Need a high-growth standard, please pick one');shg;
    end
end
%    
    enough_21_thresh=0.2;
    enough_21_index=vals21>enough_21_thresh;
   
  
   [n21,xout21]=hist(vals21(enough_21_index),100);
   [n33,xout33]=hist(vals33(enough_21_index),100);
   
   maxval=max([xout21,xout33]);

max_33_ratio=0.25;
        
  setting_thresh=1;
 
  while setting_thresh
      
        picked_index=[];
%       
        ratios=vals33(enough_21_index)./( vals21(enough_21_index)+vals33(enough_21_index) );
  
        
        
        %show occupied cells:
        
       occ_cells=zeros(size(corners_x,1)-1,size(corners_x,2)-1);
        occ_cells(enough_21_index)=1;
   
        v21=vals21*0;v33=v21;
        v21(enough_21_index)=vals21(enough_21_index);
        v33(enough_21_index)=vals33(enough_21_index);
        
        
     %   figure(101);subplot(3,1,1);imagesc(v21);subplot(3,1,2);imagesc(v33);subplot(3,1,3);imagesc(max(0,(v21-v33)./(v21+10^-3)));colormap hot;impixelinfo;shg

        
        figure(1);clf;subplot(6,8,1:36);imagesc(imcomb);
        
        highlight_cells(occ_cells,corners_x,corners_y,'c',1,1);
       
        title('Preselecting candidates');shg;
       
        
        picked_index = find ( (vals21>=enough_21_thresh) & (vals33 < max_33_ratio * vals21) );
   
 
        picked_cells=zeros(size(corners_x,1)-1,size(corners_x,2)-1);
        picked_cells(picked_index)=1;
   
        highlight_cells(picked_cells,corners_x,corners_y,'k',linewidth,linefactor);
        mark_cells(picked_cells,corners_x,corners_y,'g',2*linewidth);
     %   highlight_cells(occ_cells,corners_x,corners_y,'c',1);
       
        
        [picked_cell_rows,picked_cell_cols]=ind2sub([size(corners_x,1)-1,size(corners_x,2)-1],picked_index);
        for index=1:length(picked_index)
            row_index=picked_cell_rows(index);
            col_index=picked_cell_cols(index);
        end


        q2=menu('Selection options','Accept (continue to manual pick)','Change thresholds','Clear all selections/manual pick');
        if q2==1
            setting_thresh=0;
        elseif q2==2
            prompt = {'min 21','max 33/21'};
            num_lines = 1;
            dlg_title='thresholds';
            def = {num2str(enough_21_thresh),num2str(max_33_ratio)};
            answer = inputdlg(prompt,dlg_title,num_lines,def);
            enough_21_thresh=str2num(answer{1});
            max_33_ratio=str2num(answer{2});
            enough_21_index=vals21>enough_21_thresh;
            
        elseif q2==3
            picked_cells=0*picked_cells;
            picked_index=[];
            clf;imagesc(imcomb);
            draw_grid_on_image(corners_x,corners_y);
            setting_thresh=0;
        end
  end
  fprintf(fid_info,'\nThresholds: min 21 %.0f, max 33/21 %.2f; %.0f cells over min 21 thresh\n',enough_21_thresh,max_33_ratio,sum(sum(enough_21_index)) );


picking=1;

figure(1);
set(1,'Position',[221          56        1627         919]);
subplot(6,8,1:36);
pick_axes=gca;
hold on;
%status_handle=text(500,-150,'PICK','FontSize',20,'Color','k');
    
while picking
   
   % set(status_handle,'String','PICK');
  %  set(status_handle,'Color','k');
  
   
     title(sprintf('Black currently selected.\nClick on Black to unselect, non-Black to select\nRight-click or click outside image to quit/save'));
     try 
        [x,y,button]=ginput(1);
        
        
    
    
   
    
   %     tic
    %    set(status_handle,'String','WORKING');
    
     %   set(status_handle,'Color','r');
  
   %toc
     catch
         continue
     end
     
    
    if x<0 | x > size(im21,2) | y<0 | y> size(im21,1) | button==3 | gca~=pick_axes
        
           
           title('See Options menu');
        
           q=menu('Options','Next plate','Unselect all','Continue picking this plate','Quit all plates');
           
           if q==1
               fprintf('Done picking\n\n');
               
               picking=0;
               
           elseif q==2
               
               disp('removing all selected cells');
               
               subplot(6,8,1:36);
             
                picked_cells=0*picked_cells;
                picked_index=[];
                imagesc(imcomb);
                draw_grid_on_image(corners_x,corners_y);
               
               continue;
               
           elseif q==3
               disp('continue picking');
               
               continue 
           elseif q==4
               picking=0;
               keep_picking=0;
               continue
           end
    end
    
  
    try
        % disp('Analyzing pick');
    x=round(x);
    y=round(y);
    picked_col=label_im_cols(y,x);
    picked_row=label_im_rows(y,x);
    title(sprintf('Selected row %d, col %d',picked_row,picked_col));
     
    
    [toprow,bottomrow,leftcol,rightcol]=get_square_borders(picked_row,picked_col,corners_x,corners_y,edge_size);
    rowletter=get_rowletter(picked_row,source_format);
   
   
    
    
    if picked_cells(picked_row,picked_col)==0
        picked_cells(picked_row,picked_col)=1;
        selunsel='Selected ';
        outline_clr='k';
        mark_clr='g';
        
        wd=2;
    else
        picked_cells(picked_row,picked_col)=0;
        selunsel='Unselected ';
        outline_clr='w';
        mark_clr='w';
        wd=2;
    end
    
       picked_index=find(picked_cells);
   
             
   
       
       
    composite=[im21(toprow:bottomrow,leftcol:rightcol),ones(bottomrow-toprow+1,10),ones(bottomrow-toprow+1,10),im33(toprow:bottomrow,leftcol:rightcol)];
    composite=uint8(floor(256*composite)); %convert to uint8 for speed (?)
   
    subplot(6,8,46:48);
    imagesc(composite);colormap gray;
    msg=(sprintf('%9s :\nCELL %4d%2s: \n21 :    %.2f of wt\n33: %.2f of wt\nRatio 33/21 %.2f',selunsel,picked_col,rowletter,vals21(picked_row,picked_col),vals33(picked_row,picked_col),(eps+vals33(picked_row,picked_col))/(eps+vals21(picked_row,picked_col))));
    

   text(-ceil(rightcol-leftcol),ceil((bottomrow-toprow)/2),msg);
    
   cells_to_mark=0*picked_cells;
   cells_to_mark(picked_row,picked_col)=1;
   
   
         
   
    
   subplot(6,8,1:36);
   
        highlight_cells(cells_to_mark,corners_x,corners_y,outline_clr,linewidth,linefactor);
        
        
        
        mark_cells(cells_to_mark,corners_x,corners_y,mark_clr,2*linewidth);
        
       
                ratio=vals33(picked_row,picked_col)/(vals33(picked_row,picked_col) + vals21(picked_row,picked_col)) ;

     
                
    catch
        disp('problem at 289');
        continue
    end
    
end    %DONE picking

hold off;
%%

[picked_cell_rows,picked_cell_cols]=ind2sub([size(corners_x,1)-1,size(corners_x,2)-1],picked_index);
fprintf('Collecting %d picked cells into csv file \n',length(picked_cell_rows));
fprintf(fid_info,'Completed selection from plate %s.  Collecting %d picked cells into Stinger file, starting target plate %d, row %d\n',source_plate_name,length(picked_cell_rows),target_plate,target_row+1);



for index=1:length(picked_index)
    
       source_row=picked_cell_rows(index);
       source_col=picked_cell_cols(index);

 %set target plate number, row and col
 
       new_plate=getnextpos_std;
      
    source_rowletter=get_rowletter(source_row,source_format);
    target_rowletter=get_rowletter(target_row,target_format);
    
    
    if new_plate
        
        
        csv_filename=sprintf('%s/%s_T%d.csv',data_directory,ID,target_plate);
        fid_out=fopen(csv_filename,'w');
        
        fprintf(fid_out,'SOURCEPLATEID,SOURCEDENSITY,SOURCECOLONYCOLUMN,SOURCECOLONYROW,TARGETPLATEID,TARGETDENSITY,TARGETCOLONYCOLUMN,TARGETCOLONYROW\n');
        
        
        fprintf('Starting new target plate %d\n',target_plate);
        fprintf(fid_info,'\nStarting new target plate %d\n',target_plate);

        
    end
    
        if target_format==100
            target_density=384;
        else
            target_density=target_format;
        end
   
        fprintf(fid_out,'%s,%d,%d,%s,Target_%d,%d,%d,%s\n',source_plate_name,source_format,...
            source_col,source_rowletter,target_plate,target_density,target_col,target_rowletter);

    
    fprintf(fid_info,'%s, format %d, %s %d to target plate %d %s %d\n',source_plate_name,source_format,...
        source_rowletter,source_col,target_plate,target_rowletter,target_col);
    
    fprintf('%s, format %d, %s %d to target plate %d %s %d\n',source_plate_name,source_format,...
        source_rowletter,source_col,target_plate,target_rowletter,target_col);
    
end
%%%%%%%%%%%%%%%%

function [toprow,bottomrow,leftcol,rightcol]=get_square_borders(row_index,col_index,corners_x,corners_y,edge_size)

left=round((corners_x(row_index,col_index)+corners_x(row_index+1,col_index))/2)+edge_size;

right=round((corners_x(row_index,col_index+1)+corners_x(row_index+1,col_index+1))/2)-edge_size;


top=round((corners_y(row_index,col_index)+corners_y(row_index,col_index+1))/2)+edge_size;

bottom=round((corners_y(row_index+1,col_index)+corners_y(row_index+1,col_index+1))/2)-edge_size;

lr_dist=right-left;
horz_border=round(lr_dist/20);

tb_dist=top-bottom;
vert_border=round(tb_dist/20);
toprow=top+vert_border;
bottomrow=bottom-vert_border;
leftcol=left+horz_border;
rightcol=right-horz_border;




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

function new_plate=getnextpos_std

%work on globals. Return flag when target plate is filled

global target_plate;
global target_row;
global target_col;
global target_format;


new_plate=0;

if target_format==100
    first_row=4;
    last_row=13;
    first_col=16;
    last_col=7;
else
    first_row=1;
    last_row=sqrt(target_format/6)*2;
    first_col=sqrt(target_format/6)*3;
    last_col=1;
end

%column-wise, left to right from BACK of plate


if target_row==0  %row out of range above; flag for the first plate, first pin
    new_plate=1; 
    target_row=first_row;
    target_col=first_col;
    target_plate=1;
    
else
    target_row=target_row+1;
    
    if target_row==last_row+1
        target_row=first_row;
        target_col=target_col-1;
        
        if target_col==last_col-1  %columns count down!
            target_col=first_col;
            target_plate=target_plate+1;
            new_plate=1;
            
            
        end
    end
end
