function [cellid1,seq1,seqC1,sig1,score1,seq2,seqC2,sig2,score2]=mmbasecallcells_xt(filename,maski)
%using segmented images, call barcodes from cells. 
dic='GTACN';
  
cellid1=unique(maski(:));
cellid1=cellid1(cellid1~=0);
  
if ~isempty(cellid1)
    files=dir(['*',filename,'*.tif']);
    files=sort_nat({files.name});
    info=imfinfo(files{1});
    
    im=zeros(info(1).Height,info(1).Width,4);
    for i=1:length(files)
        for n=1:4
            im(:,:,n,i)=imread(files{i},n);
        end
    end
    im1=reshape(im,size(im,1)*size(im,2),4,[]);
    
    maski1=reshape(maski,[],1);
    
    %read signal
    
    sig1=zeros(size(cellid1,1),size(im1,2),size(im1,3));
    for i=1:size(sig1,1)
        sig1(i,:,:)=mean(im1(maski1==cellid1(i),:,:));
    end
        
    %call sequences
    [score1,seq1]=max(sig1,[],2);
    seq1=reshape(seq1,size(seq1,1),[]);
    seqC1=dic(seq1);
    % seqC1=char(seq1);
    % seqC1(seq1==1)='G';
    % seqC1(seq1==2)='T';
    % seqC1(seq1==3)='A';
    % seqC1(seq1==4)='C';

    score1=score1./sqrt(sum(sig1.^2,2));
    score1=reshape(score1,size(score1,1),[]);
    score1(isnan(score1))=0.5;


    score_im_whole=reshape(max(im1,[],2)./sqrt(sum(im1.^2,2)),size(im,1),size(im,2),size(im,4));
    score_im_whole_s=sort(score_im_whole,3,'ascend');

    hd_thresh=0.85;%high quality pixel threshold
    hd_count_thresh=50;
    
    base_num=size(score_im_whole_s,3);
    hd_pixels=score_im_whole_s(:,:,min(3,base_num))>hd_thresh;


    seq2=ones(max(cellid1),size(im,4))*5;
    sig2=zeros(max(cellid1),4,size(im,4));
    score2=seq2;
    %
    for roi=1:max(cellid1)
        % basecall by pooling high-quality pixels and calling those
        valid_pixels=hd_pixels&maski==roi;
        im_f=reshape(im,[],size(im,3),size(im,4));
        sig2(roi,:,:)=(mean(im_f(valid_pixels(:),:,:),1));
        if sum(valid_pixels,'all')>hd_count_thresh
            [maxsig,seq2(roi,:)]=max(reshape(sig2(roi,:,:),size(sig2,2),size(sig2,3)),[],1);
            score2(roi,:)=maxsig./sqrt(sum(reshape(sig2(roi,:,:),size(sig2,2),size(sig2,3)).^2));
        else
            sig2(roi,:,:)=zeros(1,4, size(im,4));
            seq2(roi,:)=ones(1, size(im,4))*5;
            score2(roi,:)=zeros(1, size(im,4));
        end
    end

    seqC2=dic(seq2);
else
    sig1=[];
    seq1=[];
    seqC1=char([]);
    cellid1=[];
    score1=[];
    sig2=[];
    seq2=[];
    seqC2=char([]);
    score2=[];
end
end


