function [f,chromosomeConsensus,b,y] = whole_genome_coverage(barcodeGen, comparisonStruct, best_chromosomes, theoryStruct,layerwidth, chromosome,cross_hca,font_size,threshold,makethemlines,unmask,coverageline)
    %   Args:
    %      barcodeGen, overlapStruct,best_chromosomes,offset, chromosome,highlight_overlap,gen_consensus
    %
    %  barcodeGen - all original barcodes/bargroups+theories *typically cGen used here
    %  comparisonStruct - can come from hca (global alignment) (rezMax) or be an overlapStruct
    %  overlapStruct - oS generated by an overlap struct of all in barcodeGen (size barcodes x theories)    
    %  best_chromosomes - list of best theories per experiment/bargroup
    %  theory struct - theory bcodes
    %  layerWidth -  vertical offset for plotting
    %  chromosome - which chromosome to focus in (0 = all)
    %  cross_hca - is this cross species? 0/1 (single specie vs or not)
    %  threshold - ccdif to use as threshold, can be changed to pval
    %  threshold
    %  makethemlines - makes (experimental) barcodes into flat lines to
    %  visualize easier
    %  coverageline - adds a count-line on the background for coverage
    %  depth

    %   Returns:
    %       f,chromosomeConsensus,b,y
    %       chromosomeConsensus - a matrix with all the aligned barcodes
    %       b/y - vectors for right and wrong placement (blue/yellow) for
    %       crosshca

    if nargin <11
    unmask=0;
    end


    if nargin <10
    makethemlines=0;
    end
    if nargin <9
    threshold=0.7;
    end
    if nargin <8
    font_size=12;
    end

    if nargin <7
    highlight_overlap=0;
    end

    if nargin <6
          chromosome=0;
    end
    if nargin <5
          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

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

try
theoryBar = theoryStruct(chr).rawBarcode(7:end);
catch
theoryBar = barStruct(height(comparisonStruct)+chr).rawBarcode(barStruct(height(comparisonStruct)+chr).rawBitmask);
end
xTheoryStart = chromosome_offset + 1;
xTheoryEnd   = chromosome_offset + length(theoryBar);

% we plot theory chromosome once
h_main=plot(xTheoryStart:xTheoryEnd,zscore(theoryBar)*3-10,'Color',[0.5 0.5 0.5])  ;  

if (~isempty(exps))
colors = lines(length(exps)); 



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

c=0;
pos=[];
norm_expBar=[];
keep=[];
len=[];
k=0;
pA=[];
pB=[];
pAl=[];
norm_expBar=[];
local_expBar=[];
if chr>16
    exps=flip(exps);
end

  for bar=exps
c=c+1;


        try
        len(c)=comparisonStruct{bar}.lengthMatch;
        score=comparisonStruct{bar}.maxcoef(1);
        ccdif=score-comparisonStruct{bar}.maxcoef(2); 
        sF=comparisonStruct{bar}.bestBarStretch;
        orr = comparisonStruct{bar}.or(1) ;
        catch
        lenA=comparisonStruct(bar,chr).lenA;
        lenB=comparisonStruct(bar,chr).lenB;
        score=comparisonStruct(bar,chr).score;
        score_vector=sort(reshape([comparisonStruct(bar,:).score],[1,19]),'descend');
        score_vector=score_vector(~isnan(score_vector));
        ccdif=score-score_vector(2);
        partialScore=comparisonStruct(bar,chr).partialScore;
        partialLength=comparisonStruct(bar,chr).partialLength;
        h = comparisonStruct(bar,chr).h;
        sF=comparisonStruct(bar,chr).bestBarStretch;
        orr = comparisonStruct(bar,chr).or ;
        bS =  comparisonStruct(bar,chr).bestBarStretch;
        fullscore = comparisonStruct(bar,chr).fullscore;  
        end

        if ccdif >= threshold 
%        if pval <= threshold 
%        if pvalCombined >= 0 
        k=k+1;
        keep(k)=c;
        try
        pos{c} = comparisonStruct{bar}.pos(1) ;
        catch
        pA{c} = comparisonStruct(bar,chr).pA ;
        pB{c} = comparisonStruct(bar,chr).pB ;
        end



       % resizing depends on how barcodes were defined. For PCC, we resize
        % first, and then apply bitmask. 
        % I must fix this, it really doesnt unmask as it should.... I mean
        % it does, but then startpos gets messed up....
        if unmask==1
        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
   if isstruct(theoryStruct)
        newLen = floor(length(barStruct(bar).rawBarcode) * sF);
        xq = linspace(1, length(barStruct(bar).rawBarcode), newLen);
        expBar = interp1(barStruct(bar).rawBarcode, xq, 'linear');
        expBit = barStruct(bar).rawBitmask(round(xq));
 
        expBar(~expBit)= nan;
    if orr~=1
        expBar = fliplr(expBar);
    end
        expBar=expBar(~isnan(expBar));
      
        

         % layers implementation 
    % we get xstart and end first
    xStart = chromosome_offset + pos{c};
 
% Trim LEFT side if starting before theory
    if xStart < xTheoryStart
    
    shift = xTheoryStart - xStart;   % how many pixels to remove
    
    if shift < length(expBar)
        expBar = expBar(shift+1:end);
        xStart = xTheoryStart;
    end
    end
    % HCA is doing something weird with linear chromosomes... so let's do
    % this, trim right:
    lastValidIdx = xTheoryEnd - xStart + 1;
    lastValidIdx = min(lastValidIdx, length(expBar));
    expBar = expBar(1:lastValidIdx);
    xEnd   = xStart + length(expBar)-1;  
    norm_expBar{c}=(expBar-mean(expBar,'omitnan' ))./std(expBar,1,'omitnan' );
    
    ampcorrected=norm_expBar{c}/range(norm_expBar{c})*layerwidth*1.5;
    % 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; % keep your amplitude-safe offset deleted an +5
            placed = true;
            break;
        end
    end
    % ifno free layer, make a newone
        if ~placed
        layers{end+1} = [xStart, xEnd];
        yOffset = (numel(layers)-1) * layerwidth;
        end
   else 
        expBar = imresize(barStruct(bar).rawBarcode(logical(barStruct(bar).rawBitmask)),'Scale' ,[1 bS]);   
        if orr~=1
        expBar = fliplr(expBar);
        end

        xStart = chromosome_offset + pB{c} - pA{c} + 1;
% Trim LEFT
    if xStart < xTheoryStart
    pA{c} = pB{c};
    shift = xTheoryStart - xStart;   % how many pixels to remove
    
    if shift < length(expBar)
        expBar = expBar(shift+1:end);
        xStart = xTheoryStart;
    end
    end
    % Trim right
    lastValidIdx = xTheoryEnd - xStart + 1;
    lastValidIdx = min(lastValidIdx, length(expBar));
    expBar = expBar(1:lastValidIdx);
    xEnd   = xStart + length(expBar)-1;  

        norm_expBar{c}=(expBar-mean(expBar,'omitnan' ))./std(expBar,1,'omitnan' );
    
        ampcorrected=norm_expBar{c}/range(norm_expBar{c})*layerwidth*1.5;
         
   
    % 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;
            placed = true;
            break;
        end
    end
    % ifno free layer, make a newone
        if ~placed
        layers{end+1} = [xStart, xEnd];
        yOffset = (numel(layers)-1) * layerwidth;
        end
     
   end
    if cross_hca==1
        if or(strcmp(barcodeGen{bar}.original,'scer') && best_chromosomes(bar)<=16,strcmp(barcodeGen{bar}.original , 'pombe') && best_chromosomes(bar)>16)
        actual_color='#0072B2';
        b(chr)=b(chr)+1;
        else
        actual_color='#E69F00';
        y(chr)=y(chr)+1;
        end
    else
        actual_color=colors(k, :);
    
    end
      hold on
   %figure
         if makethemlines==0
             plot(xStart:xEnd,ampcorrected+yOffset,'Color', actual_color);
         else
            plot(xStart:xEnd,repelem(yOffset,xEnd-xStart+1),'Color', actual_color);
         end

        end % threshold end
  end
 

 % Place consensus gen here
 try 
 norm_expBar=norm_expBar(keep);
  pos=pos(keep);
  len=len(keep);
  exps=exps(keep);
  global_hca=1;
  chromosomeConsensus{g}.consensusMatrix=consensusMatrix(norm_expBar,pos,len,zscore(theoryBar),global_hca);
  chromosomeConsensus{g}.forcedconsensus=nanmean(chromosomeConsensus{g}.consensusMatrix(1:end-1,:),1);
  chromosomeConsensus{g}.theory=num2str(theoryStruct(chr).name);
  chromosomeConsensus{g}.expbars=exps;
 catch
  pA=pA(keep);
  pB=pB(keep);
  exps=exps(keep);
    global_hca=0;
  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(comparisonStruct)+chr}.name);
  chromosomeConsensus{g}.expbars=exps;
 end
% Plot add coverage line!
if coverageline==1
if height(chromosomeConsensus{g}.consensusMatrix) <3
  plot(chromosome_offset+1:chromosome_offset+length(chromosomeConsensus{g}.consensusMatrix), chromosomeConsensus{g}.consensusMatrix(1,:)>-Inf,'k','LineWidth',2)
else
    plot(chromosome_offset+1:chromosome_offset+length(chromosomeConsensus{g}.consensusMatrix), sum(chromosomeConsensus{g}.consensusMatrix(1:end-1,:)>-Inf),'k','LineWidth',2)
end
end
  %this is consensus here
%  plot(chromosome_offset+1:chromosome_offset+length(chromosomeConsensus{g}.consensusMatrix),chromosomeConsensus{g}.forcedconsensus*3-10,'k','LineWidth',2)
  legend(legendhandles, legendEntries, 'Location', 'southeastoutside', 'Interpreter', 'latex','FontSize', font_size);


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+0;
end %end of which chromosomes to search


end


