function [f,chromosomeConsensus] = plot_per_chromosome(barcodeGen, overlapStruct,best_chromosomes,layerwidth, chromosome,highlight_overlap,font_size,threshold,consensus_line)
% Similar to whole_genome_coverage
% one window per chromosome 

%  based on: plot_best_match
    %  barcodeGen - all original barcodes&bargroups+theories *typically cGen used here
    %  overlapStruct - oS generated by an mp of all in barcodeGen *or a mini version    
    %  best_chromosomes - list of best theories per experiment/bargroup
    %  layerwidth -  vertical offset for plotting (width of each "layer")
    %  chromosome - which chromosome to focus in (0 = all)
    %  highlight_overlap - do we want to see the overlap highlighted on the theory? (0/1)

   

    %   Returns:
    %       f,chromosomeConsensus
    %
    if nargin <9
    consensus_line=0;
    end
    if nargin <8
    threshold=0.7;
    end
    if nargin <7
    font_size=12;
    end

    if nargin <6
    highlight_overlap=0;
    end

    if nargin <5
          chromosome=0;
    end
    if nargin <4
          layerwidth=0;
    end
      barStruct=barcodeGen;
    if iscell(barStruct)
        barStruct = cell2struct([cellfun(@(x) double(x.rawBarcode),barStruct,'un',false);...
        cellfun(@(x) x.rawBitmask,barStruct,'un',false)]',{'rawBarcode','rawBitmask'},2);
    end

% Lets loop for each chromosome
if chromosome==0
    chromosomes_to_search=1:width(overlapStruct);
else
    chromosomes_to_search=chromosome;
end
g=0;
for chr=chromosomes_to_search
g=g+1;
% get experiments that had chromosome chr as best
exps=find(best_chromosomes==chr);

if (~isempty(exps))

f=figure;hold on


colors = lines(length(exps));

theoryBar = barStruct(height(overlapStruct)+chr).rawBarcode(logical(barStruct(height(overlapStruct)+chr).rawBitmask));
% we plot chromosome once
h_main=plot(1:length(theoryBar),zscore(theoryBar),'Color',[0.5 0.5 0.5],'LineWidth',2)    ;
legendEntries={};
legendhandles = [];
legendhandles(1)=h_main;
try
legendEntries{1} = ['chr = ' num2str(barcodeGen{height(overlapStruct)+chr}.name)];
catch
legendEntries{1} = ['chr = ' num2str(chr)];

end
c=0;
pA=[];
pB=[];
pAl=[];
expBar=[];
norm_expBar=[];
local_expBar=[];
keep=[];
k=0;
layers = {};
  for bar=exps
c=c+1;


        lenA=overlapStruct(bar,chr).lenA;
        lenB=overlapStruct(bar,chr).lenB;
        score=overlapStruct(bar,chr).score;
        partialScore=overlapStruct(bar,chr).partialScore;
        partialLength=overlapStruct(bar,chr).partialLength;
        h = overlapStruct(bar,chr).h;
        % p-value for full
        import Zeromodel.beta_ev_cdf;
        pvalfun = @(x,l1,l2,nuF) 1-beta_ev_cdf(x,nuF*h,1,2*max(l2,l1),0);
        minL = 50;
        pval = pvalfun(score,lenA,lenB,0.07); %whats this 0.07 doing?!
        %p-pvalue for single
        import Zeromodel.beta_cdf;
        pvalfunLeftover = @(x,l1,nuF) 1-beta_cdf(x,nuF*l1,1,0);
        pvalLeftOver = NaN;
            if partialLength > minL
                pvalLeftOver = pvalfunLeftover(partialScore,partialLength,0.07);
            end
        pvalCombined = (norminv(1-pval)+norminv(1-pvalLeftOver))/sqrt(2);
        pvalCombined(isnan(pvalCombined)) = (norminv(1-pval(isnan(pvalCombined))));


        if pvalCombined >= threshold 
%        if pval <= 0.95 
%        if pvalCombined >= 0 
        k=k+1;
        keep(k)=c;
        pA{c} = overlapStruct(bar,chr).pA ;
        pB{c} = overlapStruct(bar,chr).pB ;
        orr = overlapStruct(bar,chr).or ;
        bS =  overlapStruct(bar,chr).bestBarStretch;
        fullscore = overlapStruct(bar,chr).fullscore;
    



       % resizing depends on how barcodes were defined. For PCC, we resize
        % first, and then apply bitmask. For MP we cut first then resize!

        expBar = imresize(barStruct(bar).rawBarcode(logical(barStruct(bar).rawBitmask)),'Scale' ,[1 bS]);   

    if orr~=1
        expBar = fliplr(expBar);
    end
      norm_expBar{c}=(expBar-mean(expBar,'omitnan' ))./std(expBar,1,'omitnan' );
    % layers implementation 
    % we get xstart and end first
    xStart = pB{c} - pA{c} + 1;
    xEnd   = xStart + length(expBar) - 1;  
    % Find a layer where it fits without overlap
    placed = false;
    for layerNum = 1:numel(layers)
        occupiedRanges = layers{layerNum};
        overlaps = any(arrayfun(@(i) ...
            max(xStart, occupiedRanges(i,1)) <= min(xEnd, occupiedRanges(i,2)), ...
            1:size(occupiedRanges,1)));
        if ~overlaps
            % Place here
            layers{layerNum} = [layers{layerNum}; [xStart, xEnd]];
            yOffset = (layerNum) * layerwidth+5; % keep your amplitude-safe offset
            placed = true;
            break;
        end
    end
    % ifno free layer, make a newone
        if ~placed
        layers{end+1} = [xStart, xEnd];
        yOffset = (numel(layers)) * layerwidth+5;
        end
     
      
      hold on
      if highlight_overlap==1
          h_main=plot(xStart:xEnd,(expBar-mean(expBar,'omitnan' ))./std(expBar,1,'omitnan' )+yOffset,'Color', colors(k, :));      
          plot(pB{c}:pB{c}+h-1,norm_expBar{c}(pA{c}:pA{c}+h-1)+yOffset,'Color','black')

      else
         if  highlight_overlap==2
          h_main=plot(pB{c}:pB{c}+h-1,norm_expBar{c}(pA{c}:pA{c}+h-1)+yOffset,'Color','black');

         else
               h_main=plot(xStart:xEnd,(expBar-mean(expBar,'omitnan' ))./std(expBar,1,'omitnan' )+yOffset,'Color', colors(k, :));
         end
      end  
    local_expBar{c}=norm_expBar{c}(pA{c}:pA{c}+h-1);
    pAl{c}=1;
    pcc = zscore(theoryBar(pB{c}:pB{c}+h-1),1)*zscore(expBar(pA{c}:pA{c}+h-1),1)'/h;
     
    
    % do full overlap
    lpA = length(expBar); lpB = length(theoryBar);

    st = min(pA{c},pB{c}); % which barcode is more to the left
    stop = min(lpA-pA{c}+1,lpB-pB{c}+1);
    
    aFul = theoryBar(pB{c}-st+1:pB{c}+stop-1);
    bFul = expBar(pA{c}-st+1:pA{c}+stop-1);
    
    aFul = aFul(~isnan(bFul));

    bFul = bFul(~isnan(bFul));
    
    fullscore = zscore(bFul,1)*zscore(aFul,1)'./length(bFul);

    % texts saying score
    text(xStart,3+yOffset,strcat('bar=', num2str(bar)),'Color', colors(c, :))
    %text(pB{c}+length(theoryBar)*0.1,3+offset*c,strcat('full cc= ',num2str(fullscore)),'Color', colors(c, :))
    try
    entryStr = strcat(['bargroup ' num2str(barcodeGen{bar}.bargroupid) ' local=', num2str(score, '%.2f'), ', global=', num2str(fullscore, '%.2f'), ', SF=', num2str(bS, '%.2f')]);
    catch
    try
    entryStr = strcat(['bargroup ' num2str(barcodeGen{bar}.idx) ' local=', num2str(score, '%.2f'), ', global=', num2str(fullscore, '%.2f'),', SF=', num2str(bS, '%.2f')]);
    
    catch
    try
    entryStr = strcat(['barcode ' num2str(barcodeGen{bar}.index) ' local=', num2str(score, '%.2f'), ', global=', num2str(fullscore, '%.2f'),', SF=', num2str(bS, '%.2f')]);
    catch
    entryStr = strcat(['barcode ' num2str(bar) ' local=', num2str(score, '%.2f'), ', global=', num2str(fullscore, '%.2f'),', SF=', num2str(bS, '%.2f')]);     
    end
    end
    end
    legendEntries{end+1} = entryStr;
    legendhandles(end+1) = h_main;   
     end % threshold end
  end
  % Place consensus gen here
  norm_expBar=norm_expBar(keep);
  pA=pA(keep);
  pB=pB(keep);
  exps=exps(keep);
  chromosomeConsensus{g}.consensusMatrix=consensusMatrix(norm_expBar,pA,pB,zscore(theoryBar));
  chromosomeConsensus{g}.forcedconsensus=nanmean(chromosomeConsensus{g}.consensusMatrix(1:end-1,:),1);
  try
  chromosomeConsensus{g}.theory=num2str(barcodeGen{height(overlapStruct)+chr}.name);
  catch
  chromosomeConsensus{g}.theory=num2str(chr);

  end
  chromosomeConsensus{g}.expbars=exps;

  local_expBar=local_expBar(keep);
  pAl=pAl(keep);
  chromosomeConsensus{g}.localconsensusMatrix=consensusMatrix(local_expBar,pAl,pB,zscore(theoryBar));
  chromosomeConsensus{g}.localforcedconsensus=nanmean(chromosomeConsensus{g}.localconsensusMatrix(1:end-1,:),1);

  
legend(legendhandles, legendEntries, 'Location', 'southeastoutside', 'Interpreter', 'latex','FontSize', font_size);
if consensus_line == 1
hold on
consensus_offset=0;
chrC=chromosomeConsensus;
% thanks to "extension" theory might not start at 1, we want it to start at 1
non_nan_idx = find(~isnan(chrC{g}.consensusMatrix(end,:)));
left_extension = non_nan_idx(1) - 1;


cons = chrC{g}.forcedconsensus;
x_cons = (1:length(cons)) - left_extension;
y_cons = cons + consensus_offset;

x_theory = 1:length(theoryBar);
xmin = min(x_theory);
xmax = max(x_theory);
overlap_idx   = x_cons >= xmin & x_cons <= xmax;
extension_idx = ~overlap_idx;

idx_overlap = find(overlap_idx);

if ~isempty(idx_overlap)
    first_overlap = idx_overlap(1);
    last_overlap  = idx_overlap(end);

    extension_idx(first_overlap) = true;
    extension_idx(last_overlap)  = true;
end



y_black = y_cons;
y_black(~overlap_idx) = NaN;

y_mag = y_cons;
y_mag(~extension_idx) = NaN;


plot(x_cons, y_mag, 'Color',[30/255 136/255 229/255],'LineWidth',2)
plot(x_cons, y_black, 'k','LineWidth',2)

% Lets highlight uncovered
covered = false(size(theoryBar));

valid_cons = ~isnan(cons);
true_support = overlap_idx & valid_cons;
theory_positions = x_cons(true_support);

% Ensure integer indexing safety
theory_positions = theory_positions( ...
    theory_positions >= 1 & ...
    theory_positions <= length(theoryBar));
covered(theory_positions) = true;

uncovered = ~covered;
y_theory = zscore(theoryBar);

y_red = y_theory;
y_red(~uncovered) = NaN;

plot(1:length(theoryBar), y_red, ...
     'Color',[255/255 193/255 7/255], 'LineWidth',2)

end %end of consensus line1

if consensus_line ==2
    hold on 
    consensus_offset=0;
    chrC=chromosomeConsensus;
    non_nan_idx = find(~isnan(chrC{g}.localconsensusMatrix(end,:)));
    left_extension = non_nan_idx(1) - 1;
    plot(1-left_extension:length(chrC{g}.localforcedconsensus)-left_extension,chrC{g}.localforcedconsensus-consensus_offset*2,'Color','blue','LineWidth',2) % local forced consensus
end %consensus 2

end % end of is there any matches even?

end %end of which chromosomes to search


end

