function model=buildModel(modelname,comp,listComp,listMap,idx)
model.name=modelname;
nComp=length(listComp(:,1));
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,1);
    model.comps(i).name=listComp(i,2);
    model.comps(i).from=listComp(i,3);
    model.comps(i).impComp=listComp(i,4);
    model.comps(i).defaultVars=listComp(i,5);
    icomp=comp(cmnames==model.comps(i).def);
    model.comps(i).vars(:,1)=icomp.vars(:,idx.var);
    model.comps(i).vars(:,2)=icomp.vars(:,idx.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.alias);
            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
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

