clearvars -except norm_ccf_live norm_ccf_fixed

frame_time = 0.2; % in seconds

randomise = 0; % off = 0; on = 1

%Filenames for DnaX and DnaQ foci
DnaX_file = 'Find_spots_DnaQ_DnaXdata.xls';
DnaQ_file = 'Find_spots_DnaQ_DnaQdata.xls';

%Load the files
DnaX_traj = dlmread(DnaX_file,'\t',1,1);
DnaQ_traj = dlmread(DnaQ_file,'\t',1,1);

%Define a new storage matrix
[frames,replisomes] = size(DnaQ_traj);

%Define the number of lags for the correlation fuctions
Maxlags=599;

% Peaks that resulted from noise (eg very high intensities) need to be
% filtered out.
% Find the maximum intensity per trajectory
Max_DnaQ=[];
Max_DnaX=[];
for i=1:replisomes
    Max_DnaQ(i,1)=max(DnaQ_traj(:,i));
    Max_DnaX(i,1)=max(DnaX_traj(:,i));
end
% Filter out any trajectories that have to high intensities
real=find(Max_DnaQ<400 & Max_DnaX<500);
DnaX_traj=DnaX_traj(:,real);
DnaQ_traj=DnaQ_traj(:,real);

%Re-define a new storage matrix
[frames,replisomes] = size(DnaX_traj);

% If randomizing, this will randomize the DnaQ trajectories.
if randomise ==1
    DnaQ_traj = DnaQ_traj(:,randperm(size(DnaQ_traj,2)));
else
end

% Calculate cross-correlation functions
for i = 1:replisomes
    acf_DnaX(:,i) = xcorr(DnaX_traj(:,i),Maxlags);
    acf_DnaQ(:,i) = xcorr(DnaQ_traj(:,i),Maxlags);
    ccf(:,i) = xcorr(DnaX_traj(:,i),DnaQ_traj(:,i),Maxlags);
end

acf_DnaX = acf_DnaX(Maxlags:end,:);
acf_DnaQ = acf_DnaQ(Maxlags:end,:);

mean_acf_DnaX = mean(acf_DnaX,2);
mean_acf_DnaQ = mean(acf_DnaQ,2);
mean_ccf = mean(ccf,2);
flip_ccf = flipud(mean_ccf);

%Find the photobleaching trajectories
photobleach_DnaX = mean(DnaX_traj,2);
photobleach_DnaQ = mean(DnaQ_traj,2);

%Find the photobleaching correlations
acf_photobleach_DnaX = xcorr(photobleach_DnaX,Maxlags);
acf_photobleach_DnaQ = xcorr(photobleach_DnaQ,Maxlags);

acf_photobleach_DnaX = acf_photobleach_DnaX(Maxlags:end,:);
acf_photobleach_DnaQ = acf_photobleach_DnaQ(Maxlags:end,:);

ccf_photobleach = xcorr(photobleach_DnaX,photobleach_DnaQ,Maxlags);
flip_ccf_photobleach = flipud(ccf_photobleach);
norm_ccf_photobleach = (ccf_photobleach + flip_ccf_photobleach)./2;

% Normalize the average cross-correlation functions to the 
% cross-correlation function of the photo-bleaching
norm_mean_acf_DnaX = mean_acf_DnaX./acf_photobleach_DnaX;
norm_mean_acf_DnaQ = mean_acf_DnaQ./acf_photobleach_DnaQ;
norm_mean_ccf = mean_ccf./ccf_photobleach;
flip_norm_ccf = flipud(norm_mean_ccf);
norm_ccf = (norm_mean_ccf + flip_norm_ccf)./2;
