%-----------PRE-PROCESSING / DEMODULATION---------


%INPUT
directory = ''; %directory where files are stored 
filename = ''; %fill in a full name of the file


%______input ends here__________
  filename_r = strcat(directory,'/',filename);
  filename_w = strcat(directory,'/','DEMOD_', filename);
  %S = csvread(filename_r,1,0); % 1: skip first line (header)
  S = dlmread(filename_r,'\t', 10,0); % 1: skip first 6 lines (header)

  %Extracting data
  mytime1 = S(:,1);
 
  N = length(mytime1); % Number of datapoints
  tmin = mytime1(1); % First Time value
  tmax = mytime1(N); % Time at the end of data
  t = linspace(tmin, tmax, N); % Equi-distant time vector (for FFT)
  dt = (t(2)-t(1)); % Time intervals 
  Fs = 1/dt; %Sampling rate
  df = Fs/N; %Freqency intervals
  frq = linspace(0,(N-1)*df,N)'; % Frequency vector, maximum value = Fs-df
  cmg = S(:,2); % cmg data
  AIN01 = S(:,3); % Data Analog IN 1
  AIN01S = interp1(mytime1,AIN01,t,'spline'); % Data Analog IN 1 resampled with equidistant time vector
  %AIN02 = S(:,4); % Data Analog IN 2
  %AIN02S = interp1(mytime1,AIN02,t,'spline'); % Data Analog IN 2 resampled with equidistant time vector
  %AIN03 = S(:,4); % Data Analog IN 3
  %AIN03S = interp1(mytime1,AIN03,t,'spline'); % Data Analog IN 3 resampled with equidistant time vector
  %AIN04 = S(:,5); % Data Analog IN 4
  %AIN04S = interp1(mytime1,AIN04,t,'spline'); % Data Analog IN 4 resampled with equidistant time vector

  Fref1 = 211; % First signal Reference frequency from console Analog output;
  Fref2 = 515; % Second signal Reference frequency from console Analog output;

  % LPF for demodulation.
  LPF_Fc1 = 30;   % Cutting frequency for LPF in Hz for first signal
  LPF_Fc2 = 30;  % Cutting frequency for LPF in Hz for second signal
   mag1 = [1, 0]; 
   mag2 = [1, 0]; 
   dev1=[0.005, 0.001]; %a reverifier 
   dev2=[0.005, 0.001]; %a reverifier 
   band1=[LPF_Fc1, 1.5*LPF_Fc1]; 
   band2=[LPF_Fc2, 1.5*LPF_Fc2]; 
   [n1, w1, beta1, ftype1] = kaiserord(band1, mag1, dev1, Fs);
   [n2, w2, beta2, ftype2] = kaiserord(band2, mag2, dev2, Fs);
   d1=max(1,fix(n1/10));
   d2=max(1,fix(n2/10));
  b1 = fir1(n1,w1,ftype1,kaiser(n1+1,beta1),'noscale');
  b2 = fir1(n2,w2,ftype2,kaiser(n2+1,beta2),'noscale');
  a1 = 1; % FIR filter (if 'a' is different = IIR filter.
  a2 = 1; % FIR filter (if 'a' is different = IIR filter.
  [h1, f1] = freqz(b1,a1,N,Fs);
  [h2, f2] = freqz(b2,a2,N,Fs);
  tf1 = t - t(round(n1/2)); % time shift because of FIR filter
  tf2 = t - t(round(n2/2)); % time shift because of FIR filter



  % LPF on raw data of Analog input channel 1
  AIN01SF1=filter(b1, a1, AIN01S);
  AIN01SF2=filter(b2, a2, AIN01S);

  % Compute reference Sine
  REF_SIN1 = sin(2*pi*Fref1 * t);
  REF_COS1 = cos(2*pi*Fref1 * t);
  REF_SIN2 = sin(2*pi*Fref2 * t);
  REF_COS2 = cos(2*pi*Fref2 * t);


  % Multiply lock-in sine with signal
  Q1 = AIN01S .* REF_SIN1;
  I1 = AIN01S .* REF_COS1;
  Q2 = AIN01S .* REF_SIN2;
  I2 = AIN01S .* REF_COS2;

  % LPF after multiplication
  Q1F1=filter(b1, a1, Q1);
  I1F1=filter(b1, a1, I1);
  Q1F2=filter(b2, a2, Q2);
  I1F2=filter(b2, a2, I2);

  % Demodulation of signal : Amplitude and Phase
  SIG1A1 = 2*sqrt(Q1F1.^2 + I1F1.^2); 
  SIG1A2 = 2*sqrt(Q1F2.^2 + I1F2.^2); 
  % NOTE double-check if we really need to multiply amplitude by 2

  %SIG1P = atan(I1F1./Q1F1);  % phase not used
  %SIG1 = SIG1A .* sin(SIG1P); 
  %SIG2P = atan(I1F2./Q1F2); % phase not used
  %SIG2 = SIG2A .* sin(SIG2P); 

  if displayGraphs == true
    % plot filter response
    figure(1)
    plot(f1, 10*log10(abs(h1)), '-b', f2, 10*log10(abs(h2)), '-r')
    xlim ([0 600]); 
    title('LP Filter Response')
    xlabel('frequency')
    ylabel('dB')
    legend ('Filter 1', 'Filter 2', 'Location','south')
    
    % plot signal frequency response
    figure(2)
    plot(frq, abs(fft(AIN01S)), 'k', frq, abs(fft(SIG1A1)), 'b', frq, abs(fft(SIG1A2)), 'r');
    xlim([0 600]);  
    title('Fourier transform')
    xlabel('frequency')
    legend ('FFT raw', 'FFT demod signal 1', 'FFT demod signal 2', 'Location','south')

    % plot signal and demodulation
    figure(3)
    plot(t, AIN01S, '-k', tf1, SIG1A1, 'b', tf2, SIG1A2, 'r')
    xlim([0 tmax-t(round(n2/2))]);  
    title('Signal')
    xlabel('Time in seconds')
    ylabel('Volt')
    legend ('Raw signal', 'Demod signal 1', 'Demod signal 2', 'Location','south')
  end
  
  data = [t', SIG1A1', SIG1A2', cmg];
  cHeader = {'Time' 'Reference' 'Ca2+ Signal' 'cmg'};
  %commaHeader = [cHeader;repmat({','},1,numel(cHeader))];
  %commaHeader = commaHeader(:)';
  %textHeader = cell2mat(commaHeader);
  %textHeader = textHeader(1:end-1);
  %fid = fopen(filename_w,'w'); 
  %fprintf(fid,'%s\n',textHeader);
  %fclose(fid);
  dlmwrite(filename_w, data, 'delimiter', ',', '-append', 'precision', 8);   

%----------END OF PRE-PROCESSING / DEMODULATION---------------



%----------- PROCESSING / EVENT SELECTION ---------

directory = ''; 
sub_directory = '/'; 
mouse_name = ''; 
recording_date = '';
demod_file = ''; % file name of demodulated, downsized file


event_time = []; % micturition event times in seconds


fit_curve = 6 %best fit line (use values between 2 and 6)



%______INPUT ends here__________

raw_data = importdata(strcat(directory, sub_directory, '/', demod_file)); 


time = round(raw_data(1:end, 1), 1);

cmg = raw_data(1:end, 4) - min(raw_data(1:end, 4));

figure(1)
plot(time, cmg, 'r');
title('Re-scaled CMG trace', 'FontSize',14);  

figure(2)
plot(time, raw_data(1:end, 2), 'k', time, raw_data(1:end, 3), 'g');


signal = raw_data(1:end, [1 2 3]);
 
%Calculates dF/F0 for gCAMP and background signal
signal_df_f0 = time;
  
  for i = 2:size(signal, 2)
    data = signal(:, i);
    fit = polyfit(time, data, fit_curve);
    f0 = polyval(fit, time);
    df_f0_tmp = (data - f0)./f0 * 100;
    signal_df_f0 = horzcat(signal_df_f0, df_f0_tmp);
    
  end
  
  
    figure(3)
    plot(time, signal(:, 3), 'g', time, f0);
    
    
    figure(4)
    
    yyaxis left
    plot(time, signal_df_f0(:, 2), 'k');
    title('\Deltaf / f0 background - black, gCAMP - green', 'FontSize',14);  
    
    yyaxis right
    plot(time, signal_df_f0(:, 3), 'g');
    
%Calculates final dF/F0    
dF_F0 = signal_df_f0(:, 3) - signal_df_f0(:, 2);


    figure(5)
    plot(time, dF_F0)
    title('\DeltaF / F0 final', 'FontSize',14);  
    

%Creates a CSV containing time, dF/F0, cmg

FP_CMG_data = horzcat(time, dF_F0, cmg);

filename_w = strcat('Source/Resulting files/', mouse_name, '_', recording_date, '_time_dF_F0_CMG_', date, '.csv');

dlmwrite(filename_w, FP_CMG_data, 'delimiter', ',', '-append'); 


%Filters separate events
time_scale = (-60:0.1:60)';

FP_event = zeros(size(time_scale, 1), size(event_time, 2));  
CMG_event = FP_event;
deltaF_F0 = FP_event;
FP_baseline = event_time;
m = round(size(event_time, 2)/4, 0)+1;
n = 4;


for i = 1:size(event_time, 2)
     index = (FP_CMG_data(:, 1) >= (event_time(i)+time_scale(1)) & FP_CMG_data(:, 1) <= (event_time(i)+time_scale(end)));
     FP_event(:, i) = FP_CMG_data(index, 2); %filters stim period+60s before and 60s after
        
     CMG_event(:, i) = FP_CMG_data(index, 3); %filters stim period+60s before and 60s after
     
     FP_baseline(i) = mean(FP_event(1:601, i));
     deltaF_F0 (:, i) = ((FP_event(:, i) - FP_baseline(i)) ./ FP_baseline(i)) * 100; 
     
     
     figure(6)
     yyaxis left
     subplot(m,n,i)
     plot(time_scale, FP_event(:, i), 'g', 'LineWidth', 2);
     
     yyaxis right
     subplot(m,n,i)
     plot(time_scale, CMG_event(:, i), 'r', 'LineWidth', 1.5);
     
     title(strcat(mouse_name,'-', recording_date, ' void #', num2str(i), ' @ ', num2str(event_time(i)))) %title
     
end


%Creates a CSV containing individual FP events data - time, FP
 filename_FP = strcat(directory,'/','Resulting files/', mouse_name, '_', recording_date, '_FP_', num2str(i), '_events_', date, '.csv');
 dlmwrite(filename_FP, FP_event, 'delimiter', ',', '-append'); 
 
 

%Creates a CSV containing individual CMG events data - time, CMG
 filename_CMG = strcat(directory,'/', 'Resulting files/', mouse_name, '_', recording_date, '_CMG_', num2str(i), '_voids_', date, '.csv');
 %dlmwrite(filename_CMG, CMG_event, 'delimiter', ',', '-append'); 

%----------END PROCESSING / EVENT SELECTION ---------------



%---------- VISUALISATION ---------------

directory = ''; %directory where the files stored 
mouse_name = ''; 

filename_FP = '.csv'. %CSV file containing individual FP events data 
filename_CMG = '.csv' %CSV file containing individual CMG events data 


FP_event = importdata(strcat(directory, '/', filename_FP));
CMG_event = importdata(strcat(directory, '/', filename_CMG));
 

allFP = FP_event; %creates FP matrix - use for the 1st recording
allCMG = CMG_event; %creates CMG matrix  - use for the 1st recording

%allFP = horzcat(allFP, FP_event); %adds extra data to FP matrix - use for all subseq. recordings
%allCMG = horzcat(allCMG, CMG_event); %adds extra ata to CMG matrix - use for all subseq. recordings


 all_Zscore = zeros(size(allFP));
 mean_FP = zeros(size(allFP(2,:)));
 SD_FP = mean_FP;
 
 CMG_Zscore = all_Zscore;
 mean_CMG = mean_FP;
 SD_CMG = mean_CMG;
 
for i = 1:size(mean_FP, 2)
    mean_FP(i) = mean(allFP(:, i));
    SD_FP(:, i) = std(allFP(:, i));
    
    all_Zscore(:, i) = (allFP(:, i) - mean_FP(i)) / SD_FP(i); 
    
    mean_CMG(i) = mean(allCMG(:, i));
    SD_CMG(:, i) = std(allCMG(:, i));
    
    CMG_Zscore(:, i) = (allCMG(:, i) - mean_CMG(i)) / SD_CMG(i);     
end


y1 = allFP';
y2 = allCMG';

x = [-60:0.1:60]';


%Creates a heatmap of all events using Zscored FP values
figure(1)
imagesc(all_Zscore');  


 % Creates average FP-CMG graph with SEM error shade
figure(2) 
yyaxis left
shadedErrorBar(x, y1, {@mean, @(y1) 1*std(y1)/ sqrt(size(y1,1))}, 'lineprops', 'b', 'patchSaturation',0.33 );

% Create ylabel
ylabel('\DeltaF / F0 (%)');

% Create xlabel
xlabel('Time (s)');

yyaxis right
shadedErrorBar(x, y2, {@mean, @(y2) 1*std(y2)/ sqrt(size(y2,1))}, 'lineprops', 'r', 'patchSaturation',0.33 );

%---------- END OF VISUALISATION ---------------


% Shaded error bar function by Rob Campbell availible here https://github.com/raacampbell/shadedErrorBar