
function filt_neurons_comb=combine_allneurons(varargin)
% combine multiple filt_neurons. add a new field uid, which is a unique
% cell id in the format of batch_num-slice-id

% must have the same number of fields as the first dataset. Additional
% fields are lost.

filt_neurons=varargin;
% check if uid is present. If not, generate uid
for n=1:numel(filt_neurons)
    if ~isfield(filt_neurons,'uid')
        filt_neurons{n}=add_uid(filt_neurons{n});
    end
end




filt_neurons_comb=filt_neurons{1};
% for all fields that are not rows = neurons, put them in cells and combine them across datasets. 
fnames=fieldnames(filt_neurons_comb);
cellnum=numel(filt_neurons_comb.id);
is_cell_based=zeros(numel(fnames),1,'logical');

for n=1:numel(fnames)
    v=filt_neurons_comb.(fnames{n});
    s=size(v,1);
    if s==cellnum
        is_cell_based(n)=1;
    else
        filt_neurons_comb.(fnames{n})={filt_neurons_comb.(fnames{n})};
    end
end

for m=2:numel(filt_neurons)
    for n=1:numel(fnames)
        if is_cell_based(n)
            filt_neurons_comb.(fnames{n})=[filt_neurons_comb.(fnames{n});filt_neurons{m}.(fnames{n})];
        else
            filt_neurons_comb.(fnames{n})=[filt_neurons_comb.(fnames{n});{filt_neurons{m}.(fnames{n})}];
        end
    end
end
%check if neuron ids are unique. If not, throw a warning, but continue
uniq_uid=unique(filt_neurons_comb.uid);
if numel(unique(filt_neurons_comb.uid))<numel(filt_neurons_comb.uid)
    warning('Some neurons are repeated in the two. Adding unique tag to distinguish repeated uids.\n');
    [~,I]=ismember(filt_neurons_comb.uid, uniq_uid);
    c=histcounts(I,0.5:numel(uniq_uid)+0.5);
    rep_idx=find(c>1);
    for ii=1:numel(rep_idx)
        rep_cells=find(I==rep_idx(ii));
        filt_neurons_comb.uid(rep_cells)=filt_neurons_comb.uid(rep_cells)+"r"+string(1:numel(rep_cells))';
    end
end


end