function [comp,idx]=buildComponents(csvFile,cellmlFiles,whichComp,labelRead,encap,Eqs)
% Build new components from the .csv
[comp,idx]=newComp(csvFile);
% Build the para component
comp=getPara(comp,idx);
[filepath,~,~] = fileparts(csvFile);
paraCsv=[filepath filesep 'Para.csv'];
writePara(comp,idx,paraCsv)
% Reuse existing cellml models
existComp=[];
for i=1:length(cellmlFiles)
    existComp=[existComp,readComp(cellmlFiles(i),whichComp(i))];      
end
% Merge
comp=mergeComp(comp,existComp,idx);
cmnames=string(extractfield(comp,'name'));%unique
% Specify the inputs for the existing components
if ~isempty(labelRead)
labelComps=string(extractfield(labelRead,'comp'));%unique
for i=1:length(labelComps)
   icomp=comp(cmnames==labelComps(i)); 
   [~,idxVar,~]=intersect(icomp.vars(:,idx.var),labelRead(i).vars,'stable');
   icomp.vars(idxVar,idx.vctg)="in";
   comp(cmnames==labelComps(i)).vars=icomp.vars;
end
end
% Encapsuate new components
for i=1:length(encap)
    chdname=cellstr(encap(i).chd.name);
    chddef=cellstr(encap(i).chd.def);
    labels=cell(length(chdname),1);
    chd={};
    [chd(1:length(chdname)).name]=deal(chdname{:});
    [chd(1:length(chdname)).def]=deal(chddef{:});
    [chd(1:length(chdname)).label]=deal(labels{:});    
    in_labels=encap(i).chd.label;
    if ~isempty(in_labels)
        label_comps=string(extractfield(in_labels,'comp'));%unique
        label_vars=extractfield(in_labels,'vars');
        [~,idxa,idxb]=intersect(chdname,label_comps);
        [chd(idxa).label]=deal(label_vars{idxb});        
    end
    comp=encapNew(comp,encap(i).name,chd,idx);
end
% Update variable io description
comp=updateVIO(comp,idx);
% Check the uniqueness of the components
cmnames=string(extractfield(comp,'name'));%unique
if length(cmnames)>length(unique(cmnames))
    disp('There are duplicate component names')
    return
end
% Link the equations to the components
for i=1:length(Eqs)
    comp(cmnames==Eqs(i).comp).Eqs=Eqs(i).listEqs;
end

end