function model=buildModel(modelname,comp,listComp,listMap,idx)
model.name=modelname;
nComp=length(listComp);
cmnames=string(extractfield(comp,'name'));%unique
if length(cmnames)>length(unique(cmnames))
    disp('There are repetitions of component names')
    return
end
for i=1:nComp
    % default
    model.comps(i).def=listComp(i).def;
    model.comps(i).name=listComp(i).name;
    model.comps(i).from=listComp(i).from;
    model.comps(i).impComp=listComp(i).impComp;
    model.comps(i).defaultVars=listComp(i).defaultVars;
    icomp=comp(cmnames==model.comps(i).def);
    model.comps(i).vars(:,1)=icomp.vars(:,idx.var); % original name
    if ~isempty(listComp(i).label)  % Label alias for some vars
    [~,idxLabel,~]=intersect(icomp.vars(:,idx.var),listComp(i).label(1));
    icomp.vars(idxLabel,idx.var)=listComp(i).label(2);
    end
    model.comps(i).vars(:,2)=icomp.vars(:,idx.var);% alias
    if model.comps(i).defaultVars=="N"
        % rename some of the aliases for mapping
        nvar=length(icomp.vars(:,idx.var));
        for n=1:nvar
            var= icomp.vars(n,idx.var);
            alias=icomp.vars(n,idx.var);
            prompt = sprintf('%s-->:%s?',var,alias);
            str = input(prompt,"s");
            if ~isempty(str)
                model.comps(i).vars(n,2)=str;
            end
        end
    end
end
%% Mapping based on aliases
if ~isempty(listMap)
    nmap=length(listMap(:,1));
    icmnames=string(extractfield(model.comps,'name'));%unique
    for i=1:nmap
        model.vmaps(i)=struct('name',"",'vpairs',["",""]);
        model.vmaps(i).name=listMap(i,:);
        comp1=model.comps(icmnames==listMap(i,1));
        comp2=model.comps(icmnames==listMap(i,2)); 
        alias1=comp1.vars(:,2);
        alisa2=comp2.vars(:,2);
        % Map vars
        [~,ivars1,ivars2]=intersect(alias1,alisa2);
        model.vmaps(i).vpairs=[comp1.vars(ivars1,1),comp2.vars(ivars2,1)];
    end
else
    model.vmaps=[];
end

end

