load protosessions
sesid=10
x=session(sesid).sitabs;%this gets spectra for pams session on 7-7
g=session(sesid).glu;%this has the refmeter glucose values
session(sesid).refmeteruse %this shows which ref meters are used [cgm, ultra, lite, oxi, verio]
st=session(sesid).spectimes;%these are the time staps for each spectrum
t=avp(st,6);%this averages the time stamps in chunks of 6

refmetercount=length(session(sesid).refmeteruse);
refmeterids=1:refmetercount;

for k=refmeterids(session(sesid).refmeteruse)
sg=g(:,k);%start with reference values from the CGM
ax=x;
ax(:,69)=sg;%make the last col of the spectral array the glucose values
clear loop
loop=[];

for i=1:size(ax,1)/6
    % cid=logical(ones(size(ax,1),1));
    % cid(i)=0;
    cid=logical(ones(6,1)*ones(1,size(ax,1)/6));%make a set of logicals for all entries in the array
    cid(:,i)=0;%set the ones corresponding to sitting i to zero so they're left out of the calibration
    ccid=cid;
    % ccid(:,[9,23,29,33,34])=0;
    cid=cid(:);
    ccid=ccid(:);
    
    %the code below can be used for the rectangular distribution of the
    %glucose information
    % [hr,rcal]=rba(ax(cid,1:64),ax(cid,end),500,50);
    % [hr,rcal]=rba(ax(ccid,1:64),ax(ccid,end),1000,500);
    % [hr,rcal]=rba(ax(ccid,1:64),ax(ccid,end),1000,50);

    %the code below performs a partial least squares regression and slope
    %intercept corrects the bvector using the orthogonal regression slope
    %of the self predicted results
    [mbr2bbcr,ysipreds,bvects]=jpredosic(ax(ccid,[1:28,35:64]),ax(ccid,69),1,ax(:,[1:28,35:64]),ax(:,69),1);
    % [mbr2bbcr,ysipreds,bvects]=jpredosic(ax(ccid,[1:64]),ax(ccid,66),1,ax(:,[1:64]),ax(:,66),1);
    % [mbr2bbcr,ysipreds,bvects]=jpredosic(rcal(:,[1:28,35:64]),hr,1,ax(:,[1:28,35:64]),ax(:,66),1);
%    loop(i,:)=ysipreds(i,:);
    loop=[loop;ysipreds(~cid,:)];%all of the spectra hag glucose values predicted, but save only the ones left out
end

figure
plot((t-t(1))*24*60,(avp([loop(:,end),loop(:,end-2)],6)),'o:');grid
xlabel('Time')
ylabel('Blood Glucose Concentration (mg/dL)')
legend('Ref Meter Spline','ProtoData')
title(['Proto Measurements: ',session(sesid).user,', ',char(session(sesid).date),', ',char(session(sesid).refmeternames{k}),' as Reference Values'])
% ylim([50 300]);
end
