clear
addpath(genpath('../cellLib/Scripts/'))
%% Build new components from the .csv
csvFile=[pwd filesep 'Vars.csv'];
libPath="C:/Users/wai484/Documents/SinglePASMC/cellLib";
%% Reuse existing cellml components
cellmlFiles=[libPath+ "/Protocols/X_clamp_protocol.cellml",libPath+ "/Components/time.cellml",libPath+ "/Components/E_Nernst.cellml",];
whichComp={["X_clamp_protocol"],["time_s"],["E_K"]};
% Specify the inputs of the existing components, otherwise the variable would
% be categorized as input if pub:in
labelRead={};
nm=1;
labelRead(nm).comp="E_K";
labelRead(nm).vars=["Ko"];
%% Encapsuate new components
encap={};
m=1;
encap(m).name="PASMC";
encap(m).chd.name=["JVOCCi","JNCXi","JSERCAi","JCICRi","JPMCAi","Jleaki","JNKAi","JCli","JKi","Casr","Cai","Vm"];
encap(m).chd.def=["JVOCCi","JNCXi","JSERCAi","JCICRi","JPMCAi","Jleaki","JNKAi","JCli","JKi","Casr","Cai","Vm"];
encap(m).chd.label=[];
m=m+1;
encap(m).name="JKi";
encap(m).chd.name=["E_K",];
encap(m).chd.def=["E_K"];
% Label some vars for mapping
label={};
nm=1;
label(nm).comp="E_K";
label(nm).vars=["Ko","K_out";"E_K","v_K";];
encap(m).chd.label=label;
%% Add equations to components
Eqs={};
m=1;
Eqs(m).comp="JVOCCi";
Eqs(m).listEqs=["J_VOCCi=G_Ca*((v_Ca1-v_i)/(1{dimensionless}+exp((v_Ca2-v_i)/R_Ca)));"];
m=m+1;
Eqs(m).comp="JNCXi";
Eqs(m).listEqs=["J_NCXi=G_NCX*(c_i/(c_i+c_NCX))*(v_NCX-v_i);"];
m=m+1;
Eqs(m).comp="JSERCAi";
Eqs(m).listEqs=["J_SERCAi=B*(pow(c_i,2{dimensionless})/(pow(c_i,2{dimensionless})+pow(c_b,2{dimensionless})));"];
m=m+1;
Eqs(m).comp="JCICRi";
Eqs(m).listEqs=["J_CICRi=C*(pow(s_i,2{dimensionless})/(pow(s_i,2{dimensionless})+pow(s_c,2{dimensionless})))*(pow(c_i,4{dimensionless})/(pow(c_i,4{dimensionless})+pow(c_c,4{dimensionless})));"];
m=m+1;
Eqs(m).comp="JPMCAi";
Eqs(m).listEqs=["J_PMCAi=D*c_i*(1{dimensionless}+(v_i-v_d)/(R_d));"];
m=m+1;
Eqs(m).comp="Jleaki";
Eqs(m).listEqs=["J_leaki=L*s_i;"];
m=m+1;
Eqs(m).comp="JNKAi";
Eqs(m).listEqs=["J_NKAi=C_NKA*(K_out/(K_mK+K_out));"];
m=m+1;
Eqs(m).comp="JCli";
Eqs(m).listEqs=["J_Cli=G_Cl*(v_i-v_Cl);"];
m=m+1;
Eqs(m).comp="JKi";
Eqs(m).listEqs=["J_Ki=G_Ki*w_i*(v_i-v_K);",...
    "ode(w_i,t)=lambda*(K_activationi-w_i);",...
    "K_activationi = sqr(c_i+c_w)/(sqr(c_i+c_w)+beta*exp(-(v_i-v_Ca3)/R_K));"];
m=m+1;
Eqs(m).comp="Casr";
Eqs(m).listEqs=["ode(s_i,t)=J_SERCAi-J_CICRi-J_leaki;"];
m=m+1;
Eqs(m).comp="Cai";
Eqs(m).listEqs=["ode(c_i,t)=J_VOCCi-J_NCXi-J_SERCAi+J_CICRi-J_PMCAi+J_leaki;"];
m=m+1;
Eqs(m).comp="Vm";
Eqs(m).listEqs=["ode(v_i,t)=gamma*(-J_NKAi-J_Cli+2{dimensionless}*J_VOCCi+J_NCXi-J_Ki);"];
m=m+1;
%%
[comp,idx]=buildComponents(csvFile,cellmlFiles,whichComp,labelRead,encap,Eqs);
save("comp.mat","comp","idx")