function [cGenAll] = plot_island_cGen(barcodeGen, cGenAll, unmask,outConsensus,numStds)
%   Plots bargroups given they have been previously calculated, needs at least barcodeGen and cGenAll Creates islands
% might be even enough with cGenAll
% Main feature is that it unmasks bargroups after being previously created after masked
% So can be used to see repetitive stuff in a bagroupo created after
% repmasking
       
    if nargin < 3
       unmask =0; % 
    end
    if nargin < 5
        numStds =10; % this can get rid of some peaks, so keep high (previous default 2)
    end
    if nargin < 4
        outConsensus =0; % 
    end
newstart=8; % bitmasking hardcoded default when unmasking
newstop=7; % bitmasking hardcoded default when unmasking

        %   TODO: plot in the tabbedscreen
          % create tabbed figure
        hFig = figure('Name', 'Barcode Islands', ...
            'Units', 'normalized', ...
            'OuterPosition', [0 0 0.9,0.9], ...
            'NumberTitle', 'off', ...
            'MenuBar', 'none', ...
            'ToolBar', 'figure' ...
        );
        hPanel = uipanel('Parent', hFig);
        h = uitabgroup('Parent',hPanel);
        t1 = uitab(h, 'title', 'islands');
       
        tsHCC = uitabgroup('Parent',t1);
    
   
if ~(~iscell(barcodeGen) && ~iscell(outConsensus))

    outC = cell(1,numel(cGenAll));
    outC_unmasked = cell(1,numel(cGenAll));
    t =[];

   

    for  i=1:numel(cGenAll)
        all_pos = cellfun(@(x) x.pos, cGenAll{i}.comparisonStruct);
        all_or = cellfun(@(x) x.or, cGenAll{i}.comparisonStruct);
        all_sF = cellfun(@(x) x.bestBarStretch, cGenAll{i}.comparisonStruct);
        all_len = cellfun(@(x) x.lengthMatch, cGenAll{i}.comparisonStruct);
        all_barids = cellfun(@(x) x.barid, cGenAll{i}.comparisonStruct);
        % rezero and offsetzero pos
        all_pos = all_pos-min(all_pos)+1;
        POS_OFFSET = 5000;                      % safety padding to avoid negative indices
        all_pos = all_pos + POS_OFFSET;
        all_pos_unmasked=all_pos;
        
        % allocating space for the consensus
        maxLen = max(all_pos+round(all_len.*all_sF))+1000;
        if ~iscell(outConsensus)
            try % now we inherit outConsensus in cGenall, so take it from there if else didnt work 
        outConsensus = nan(length(all_len),maxLen);
        outConsensus_unmasked = nan(length(all_len),maxLen);

            for k=1:length(all_len)
                if iscell(barcodeGen)
                expBar = barcodeGen{all_barids(k)}.rawBarcode;
                expBit = barcodeGen{all_barids(k)}.rawBitmask;
             
                    if unmask==1      
                    unmasked_expBar= expBar;
                    unmasked_expBit= ones(size(unmasked_expBar));
                    unmasked_expBit(1:newstart)=0;
                    unmasked_expBit(end-newstop:end)=0;
                    newstartbit= find(unmasked_expBit == 1, 1, 'first');
                    newstopbit = find(unmasked_expBit == 1, 1, 'last');
                    unmasked_expBar=unmasked_expBar(newstartbit:newstopbit);
                    end

                 % Luis: This was here to use the bitmask, the problem is that this
                 % is not enough, pairwise comparisons from the oS ignore the first
                 % many 0's in the bitmask instead of just make it invisible
                 expBar(~expBit)= nan;
                 % I first added these, but they cut out internal parts of barcode
                 % if internal 0's exist in bitmask
                 %expBar=expBar(expBit);
                 %expBit = ones(size(expBar));
                  startbit= find(expBit == 1, 1, 'first');
                  stopbit = find(expBit == 1, 1, 'last');
                  expBar=expBar(startbit:stopbit);

                % interpolate to the length which gave best CC value
                expBar = imresize(expBar,'Scale' ,[1 all_sF(k)]);
                if unmask==1
                unmasked_expBar=imresize(unmasked_expBar,'Scale' ,[1 all_sF(k)]);
                end

                if all_or(k)==2
                  expBar = fliplr(expBar);
                  if unmask==1
                   unmasked_expBar=fliplr(unmasked_expBar);
                   all_pos_unmasked(k)=all_pos(k)-ceil((newstopbit-stopbit)*all_sF(k));
                  end
                else
                if unmask==1
                 all_pos_unmasked(k)=all_pos(k)-ceil((startbit-newstartbit)*all_sF(k));
                end
                end

                   insertion_start = all_pos(k);
                   insertion_end   = all_pos(k) + length(expBar) - 1;
    
                   % enforce bounds (shouldn't be necessary with offset, but better have bulletproof)
                   if insertion_start < 1 || insertion_end > size(outConsensus,2)
                   warning("Index out of bounds for barcode %d, skipping placement, code larger outConsensus matrix next time", k);
                   continue;
                   end
                   outConsensus(k, insertion_start:insertion_end) =  (expBar-nanmean(expBar))/nanstd(expBar,1);

                   if unmask==1
                   insertion_start_unmasked = all_pos_unmasked(k);
                   insertion_end_unmasked   = all_pos_unmasked(k) + length(unmasked_expBar) - 1;
    
                   % enforce bounds (shouldn't be necessary with offset, but better have bulletproof)
                   if insertion_start_unmasked < 1 || insertion_end_unmasked > size(outConsensus_unmasked,2)
                   warning("Index out of bounds for barcode %d, skipping placement, code larger outConsensus matrix next time", k);
                   continue;
                   end
                   outConsensus_unmasked(k, insertion_start_unmasked:insertion_end_unmasked) =  (unmasked_expBar-nanmean(unmasked_expBar))/nanstd(unmasked_expBar,1);
                   end
                end
            end
    % trim out unused NaN columns 
    firstCol = find(any(~isnan(outConsensus),1),1,'first');
    lastCol  = find(any(~isnan(outConsensus),1),1,'last');
    outConsensus = outConsensus(:, firstCol:lastCol);

   
    % test: remove pixels which are outliers
    lowerBound = nanmean(outConsensus)-numStds*nanmean(nanstd(outConsensus));
    higherBound = nanmean(outConsensus)+numStds*nanmean(nanstd(outConsensus));

    outConsensus(outConsensus<lowerBound) = nan;
    outConsensus(outConsensus>higherBound) = nan;
    
    %lets kill all 0's created after the last NaN
    [m, ~] = size(outConsensus);   %

    for r = 1:m
    row = outConsensus(r,:);
    nanIdx = find(isnan(row), 1, 'last'); % index of last NaN in this row
    
    if ~isempty(nanIdx)   % only process if there's at least one NaN
        % find all 0's after the last NaN
        zeroIdx = find(row(nanIdx+1:end) == 0) + nanIdx;
        % replace them with NaN
        outConsensus(r, zeroIdx) = NaN;
    end
    end

    

    outC{i} = outConsensus;
    if unmask==1
        % trim out unused columns 
    firstCol = find(any(~isnan(outConsensus_unmasked),1),1,'first');
    lastCol  = find(any(~isnan(outConsensus_unmasked),1),1,'last');
    outConsensus_unmasked = outConsensus_unmasked(:, firstCol:lastCol);

   
    % test: remove pixels which are outliers
    lowerBound = nanmean(outConsensus_unmasked)-numStds*nanmean(nanstd(outConsensus_unmasked));
    higherBound = nanmean(outConsensus_unmasked)+numStds*nanmean(nanstd(outConsensus_unmasked));

    outConsensus_unmasked(outConsensus_unmasked<lowerBound) = nan;
    outConsensus_unmasked(outConsensus_unmasked>higherBound) = nan;
    
    %lets kill all 0's created after the last NaN
    [m, ~] = size(outConsensus_unmasked);  

    for r = 1:m
    row = outConsensus_unmasked(r,:);
    nanIdx = find(isnan(row), 1, 'last'); % index of last NaN in this row
    
    if ~isempty(nanIdx)   % only process if there's at least one NaN
        % find all 0's after the last NaN
        zeroIdx = find(row(nanIdx+1:end) == 0) + nanIdx;
        % replace them with NaN
        outConsensus_unmasked(r, zeroIdx) = NaN;
    end
    end

    

    outC_unmasked{i} = outConsensus_unmasked;
    end
      
        catch % now we inherit outConsensus in cGenall, so take it from there if else didnt work 
        outC{i}= cGenAll{i}.outConsensus; 
      
            end 
        else
      
        outC{i} = outConsensus{i};
        end



        hPanelPlot = uitab(tsHCC, 'title', strcat(['Bar Island_' num2str(i)]));
if unmask == 0
        t{i} = tiledlayout(hPanelPlot,2,1,'TileSpacing','tight','Padding','tight');
else
        t{i} = tiledlayout(hPanelPlot,4,1,'TileSpacing','tight','Padding','tight');
end
ax = [];   % store axes handles

%  normal consensus 
ax(1) = nexttile(t{i});
plot(outC{i}')
hold on
plot(nanmean(outC{i}),'Color','black','LineWidth',2)

%  offset barcodes
ax(2) = nexttile(t{i});
plot(outC{i}' + (1:size(outC{i},1)) * 3)
legend({num2str(cGenAll{i}.idx)})

% unmasked consensus (if enabled) ----
if unmask == 1
    ax(3) = nexttile(t{i});
    cGenAll{i}.outConsensus_unmasked = outC_unmasked{i};
    plot(outC_unmasked{i}')
    hold on
    plot(nanmean(outC_unmasked{i}),'Color','black','LineWidth',2)

    ax(4) = nexttile(t{i});
    cGenAll{i}.outConsensus_unmasked = outC_unmasked{i};
    plot(outC_unmasked{i}'+ (1:size(outC_unmasked{i},1)) * 3)
    hold on
end

% Determine the global x-limit
if unmask == 1
    maxLen = max([ ...
        size(outC{i},2), ...
        size(outC_unmasked{i},2) ...
    ]);
else
    maxLen = size(outC{i},2);
end

% Apply the same xlim to all tiles
set(ax, 'XLim', [1 maxLen]);
    
    
    end

else 
    for i=1:numel(cGenAll)
        hPanelPlot = uitab(tsHCC, 'title', strcat(['Bar Island_' num2str(i)]));
        t{i} = tiledlayout(hPanelPlot,1,1,'TileSpacing','tight','Padding','tight');
      
        nexttile(t{i})        
        plot(cGenAll{i}.rawBarcode,'Color','black','LineWidth',2)
        legend({num2str(cGenAll{i}.idx)})
    end 
end
end
  


