function [f,chromosomeConsensus] =  bargroup_detail_vs_reference(barcodeGen, overlapStruct,best_chromosomes,layerwidth, chromosome,highlight_overlap,font_size,threshold,consensus_line,unmask,horizontalgap,alphaN1,alphaN2,alphaNu1,alphaNu2)
    
    % Plots bargroups with details 
    % similar to plot_per_chromosome
   

    %   Returns:
    %       f,chromosomeConsensus
    %
    if nargin <11
    horizontalgap=200;
    end
    if nargin <10
    unmask=0;
    end
    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=2;
    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

f=figure;nexttile([1,2]);hold on
chromosome_offset=0;
layers = {};
if chromosome==0
    chromosomes_to_search=1:width(overlapStruct);
else
    chromosomes_to_search=chromosome;
end
g=0;
legendEntries={};
legendhandles = [];
for chr=chromosomes_to_search
g=g+1;
% get experiments that had chromosome chr as best
exps=find(best_chromosomes==chr);

theoryBar = barStruct(height(overlapStruct)+chr).rawBarcode(barStruct(height(overlapStruct)+chr).rawBitmask);
% we plot chromosome once
h_main=plot(chromosome_offset+1:chromosome_offset+length(theoryBar),zscore(theoryBar),'Color',[0.5 0.5 0.5])  ;  

if (~isempty(exps))
colors = lines(length(exps)); % colors for lines or parula(n), hsv(n), turbo(n), etc.



legendhandles(end+1)=h_main;
legendEntries{end+1} = ['chr = ' num2str(barcodeGen{height(overlapStruct)+chr}.name)];

c=0;
pA=[];
pB=[];
pAl=[];
norm_expBar=[];
local_expBar=[];
keep=[];
k=0;
  for bar=exps
c=c+1;


% somewhere here we check and kill what we dont want or we do that on
  % "best_chromosome" gen
        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;
        sF=overlapStruct(bar,chr).bestBarStretch;
        % p-value for full
        import Zeromodel.beta_ev_cdf;
       pvalfun = @(x,l1,l2,nuF,h) 1-beta_ev_cdf(x,nuF*h,1,max(alphaN1*2*(max(l1,l2)-h),alphaN2*2*(l1-h+1)*(l2-h+1)),0);

        minL = 50;
        pval = pvalfun(score,lenA,lenB,alphaNu2,h); 
        %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,alphaNu1);
            end
        pvalCombined = (norminv(1-pval)+norminv(1-pvalLeftOver))/sqrt(2);
        pvalCombined(isnan(pvalCombined)) = (norminv(1-pval(isnan(pvalCombined))));
        orr = overlapStruct(bar,chr).or ;
        bS =  overlapStruct(bar,chr).bestBarStretch;
        fullscore = overlapStruct(bar,chr).fullscore;        

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

    



  
        if unmask==1 % COORDINATES MUST BE FIXED IN ORDER FOR THIS TO WORK!!!
        barStruct(bar).rawBitmask=ones(size(barStruct(bar).rawBitmask));
        barStruct(bar).rawBitmask(1:6)=0;
        barStruct(bar).rawBitmask(end-5:end)=0;
        barStruct(bar).rawBitmask=logical(barStruct(bar).rawBitmask);
        end
        expBar = imresize(barStruct(bar).rawBarcode(logical(barStruct(bar).rawBitmask)),'Scale' ,[1 bS]); 
        expBlock = imresize(barcodeGen{bar}.outConsensus(:,logical(barStruct(bar).rawBitmask)),'Scale' ,[1 bS]);
    if orr~=1
        expBar = fliplr(expBar);
        expBlock = fliplr(expBlock);
    end

    
   



      norm_expBar{c}=(expBar-mean(expBar,'omitnan' ))./std(expBar,1,'omitnan' );
    
      ampcorrected=norm_expBar{c}/range(norm_expBar{c})*layerwidth*1;
      for j =1:height(expBlock)
      expBlock(j,:)= expBlock(j,:)/range(expBlock(j,:))*layerwidth*1;
      end
         % layers implementation 
    % we get xstart and end first
    xStart = chromosome_offset + 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-1) * layerwidth+3.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)-1) * layerwidth+3.5;
        end
     
     
      hold on
      if highlight_overlap==1
          h_main=plot(xStart:xEnd,ampcorrected+yOffset,'Color', colors(1, :));
            
   
          hold on
          for p=1:height(expBlock) 
          plot(xStart:xEnd,expBlock(p,:)+yOffset+(layerwidth-1)*(p-1),'Color', colors(1, :));
          end

          plot(chromosome_offset+pB{c}:chromosome_offset+pB{c}+h-1,ampcorrected(pA{c}:pA{c}+h-1)+yOffset,'Color','black')
       
        else
         if  highlight_overlap==2
           h_main=plot(chromosome_offset+pB{c}:chromosome_offset+pB{c}+h-1,ampcorrected(pA{c}:pA{c}+h-1)+yOffset,'Color','black');
          hold on
          for p=1:height(expBlock) 
          plot(xStart:xEnd,expBlock(p,:)+yOffset+(layerwidth-1)*(p-1),'Color', colors(1, :));
          end
         else
          %h_main=plot(xStart:xEnd,ampcorrected+yOffset,'Color', colors(k, :));
          hold on
          for p=1:height(expBlock) 
          plot(xStart:xEnd,expBlock(p,:)+yOffset+(layerwidth*.8)*(p-1),'Color', colors(1, :));
          end
         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);

    try
    entryStr = strcat(['bgroup ' num2str(barcodeGen{bar}.bargroupid) ' local=', num2str(score, '%.2f'), ' global=', num2str(fullscore, '%.2f'),' sF=',num2str(sF,'%.2f')]);
    catch
    try
    entryStr = strcat(['bgroup ' num2str(barcodeGen{bar}.idx) ' local=', num2str(score, '%.2f'), ' global=', num2str(fullscore, '%.2f'),' sF=',num2str(sF,'%.2f')]);
    
    catch
    try
    entryStr = strcat(['bcode ' num2str(barcodeGen{bar}.index) ' local=', num2str(score, '%.2f'), ' global=', num2str(fullscore, '%.2f'),' sF=',num2str(sF,'%.2f')]);
    catch
    entryStr = strcat(['bcode ' num2str(bar) ' local=', num2str(score, '%.2f'), ' global=', num2str(fullscore, '%.2f'),' sF=',num2str(sF,'%.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);
  chromosomeConsensus{g}.theory=num2str(barcodeGen{height(overlapStruct)+chr}.name);
  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
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;
plot(chromosome_offset+1-left_extension:chromosome_offset+length(chrC{g}.forcedconsensus)-left_extension,chrC{g}.forcedconsensus-consensus_offset,'Color','black','LineWidth',2) % Whole forced consensus

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(chromosome_offset+1-left_extension:chromosome_offset+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?
xline(chromosome_offset+length(theoryBar), '--', 'Color', [0.5 0.5 0.5],'LineWidth',2);
chromosome_offset=length(theoryBar)+chromosome_offset+horizontalgap;
end %end of which chromosomes to search


end

