% 
% %% Loading analogin data (3sec pulses)
% nAnalogin=2;
% SampleRate=20000;
% dataAnalogIn=LoadBinary('analogin.dat','nchannels',nAnalogin,'precision','uint16');
% dataAnalogIn=double(dataAnalogIn)*0.000050354;   % 0.000050354 to convert to Volt
% 
% StimTrigger=dataAnalogIn(:,1);
% StimTrigger=smoothdata(StimTrigger,'gaussian',500);
% 
% %% Conversion to degC
% temp_OpSens=dataAnalogIn(:,2)*20;   %conversion to C
% %filtering
% temp_OpSens=sgolayfilt(temp_OpSens,3,SampleRate+1);
xx=dir('P*.mat');
yy=(xx.name);
yy=yy(1:end-4);
load(xx.name);
SampleRate=eval([yy '.SampleRate']);
temp_OpSens=eval([yy '.temp_OpSens']);
StimTrigger=eval([yy '.StimTrigger']);

%% Downsample
NewSampleRate=SampleRate/1000;
temp_OpSens=downsample(temp_OpSens,SampleRate/NewSampleRate);
StimTrigger=downsample(StimTrigger,SampleRate/NewSampleRate);

%% finding the edges of the 3sec pulses from AnalogIn
LShiftStimTrigger=[StimTrigger(2:end);0];
stdv=std(StimTrigger);

StartStim=find(StimTrigger<2*stdv & LShiftStimTrigger>2*stdv);   %finds RisingEdge of Pulses
EndStim=find(StimTrigger>2*stdv & LShiftStimTrigger<2*stdv);   %finds RisingEdge of Pulses
%% Creat traces
time_On=50;  %in sec
time_Off=200; %in sec
time_prestim=50;
load('goodstims.mat');
StimTraces=[];
for i=goodstims
    StimTraces(:,i)=temp_OpSens(StartStim(i)-time_prestim*NewSampleRate:StartStim(i)+(time_On+time_Off)*NewSampleRate)-temp_OpSens(StartStim(i)-5);
end

%mean T rise
ss1=0;
ss2=0;
for i=goodstims
ss1=ss1+temp_OpSens(EndStim(i))-temp_OpSens(StartStim(i));
ss2=ss2+temp_OpSens(StartStim(i))-temp_OpSens(StartStim(i)-time_prestim*NewSampleRate);
end

mean_T_rise_1=ss1/length(goodstims);
mean_T_rise_2=ss2/length(goodstims);
mean_T_rise=mean_T_rise_1-mean_T_rise_2;


%% plot

time=(0:length(temp_OpSens)-1)/NewSampleRate;
figure();
subplot(211);hold on;
yyaxis left
plot(time,temp_OpSens,'color',[0 0 204]/255,'LineWidth',2);
ylabel('Temp (C)')
yyaxis right
plot(time,StimTrigger,':','color',[151 15 15]/255,'LineWidth',1.5);
ylabel('Voltage (V)')
xlabel('time (s)')
legend({'Optic Sensor','Stim Trigger'})
set(gca,'fontweight','bold','fontsize',11,'linewidth',1)

subplot(212);hold on;
stdshade(StimTraces','sem',0.3,'b',(0:size(StimTraces',2)-1)/NewSampleRate-time_prestim,1);
v = [0 min(ylim);time_On min(ylim);time_On max(ylim); 0 max(ylim)];
f = [1 2 3 4];
patch('Faces',f,'Vertices',v,'FaceColor',[150 50 50]/255)
alpha(0.3)
ylabel('Temperature (C)')
xlabel('time (s)')
title(['Temp response to RF-5trialMeanTRise=' num2str(mean_T_rise)])
set(gca,'fontweight','bold','fontsize',11,'linewidth',1)

saveas(gca,fullfile(cd,['TempResponse.fig']))
saveas(gca,fullfile(cd,['TempResponse.pdf']))


save(['VariablesAt' datestr(now,'mmddyyHHMMSS') '.mat'],'-v7.3')

close all