%% LOAD AND PREPROCESS CALCIUM IMAGING DATA FROM BASELINE AND DRUG SESSIONS

% Load preprocessed ΔF/F calcium imaging data (Inscopix) from baseline and drug/lesion sessions
ld=load('C:\Users\marce\Google Drive\Shared_data_MM_CA\Imaging_D1D2\mousevideo_inscopix_aligned\24309_d1les\LD\recording_20170830_161508_mosaic_pp_dff_LD.mat');
bs=load('C:\Users\marce\Google Drive\Shared_data_MM_CA\Imaging_D1D2\mousevideo_inscopix_aligned\24309_d1les\Bs\recording_20170830_161508_mosaic_pp_dff_BS.mat');

% Extract imaging matrices
baselineinsco=bs.Y; % Baseline session
druginsco=ld.Y;     % Drug or lesion session

% Concatenate and normalize both imaging datasets for consistent visualization
newvid=cat(3, baselineinsco, druginsco);
newvidedited=mat2gray(newvid);

% Split the normalized video back into baseline and drug sessions, adding a constant offset to enhance visibility
baselineinsco=newvidedited(:,:,1:601)+0.1;
druginsco=newvidedited(:,:,602:end)+0.1;

%% ALIGN BEHAVIORAL VIDEO TO IMAGING SESSION (BASELINE)
% Load accelerometer + timestamp metadata recorded during the imaging session
accelbaseline='C:\Users\marce\Google Drive\Shared_data_MM_CA\Imaging_D1D2\mousevideo_inscopix_aligned\24309_d1les\Bs\Accel2017-08-30T16_14_40.5825280+01_00.csv';
matrxbl= csvread(accelbaseline,1,0);

% Extract relevant timestamps from behavioral and Inscopix camera streams
camerats=matrxbl((matrxbl(:,2)==37),3); % Camera timestamps
inscots=matrxbl((matrxbl(:,2)==35)&(matrxbl(:,4)>10000),3); % Inscopix frame timestamps

% Define temporal window of interest based on imaging frames
mininsco=inscots(3400);
maxinsco=inscots(4000);

% Find corresponding camera timestamps that best match the selected Inscopix frame interval
pointmin=find((abs(camerats-mininsco))==min(abs(camerats-mininsco)));
pointmax=find((abs(camerats-maxinsco))==min(abs(camerats-maxinsco)));

% Load TOP camera timestamps and convert selected points to seconds
topcam_computs='C:\Users\marce\Google Drive\Shared_data_MM_CA\Imaging_D1D2\mousevideo_inscopix_aligned\24309_d1les\Bs\Centroid_Timestamped_Top2017-08-30T16_14_43.csv';
topcamread=readtable(topcam_computs, 'Delimiter', ' ');
timemin=cell2mat(table2array(topcamread(pointmin,3)));
timeminh=str2num(timemin(12:13))*60*60;
timeminm=str2num(timemin(15:16))*60;
timemins=str2num(timemin(18:27));
finaltimemin=timeminh+timeminm+timemins;

timemax=cell2mat(table2array(topcamread(pointmax,3)));
timemaxh=str2num(timemax(12:13))*60*60;
timemaxm=str2num(timemax(15:16))*60;
timemaxs=str2num(timemax(18:27));
finaltimemax=timemaxh+timemaxm+timemaxs;

% Load SIDE camera timestamps and convert all entries to seconds
sidecam_computs='C:\Users\marce\Google Drive\Shared_data_MM_CA\Imaging_D1D2\mousevideo_inscopix_aligned\24309_d1les\Bs\Centroid_Timestamped_Side2017-08-30T16_14_43.csv';
sidecamread=readtable(sidecam_computs, 'Delimiter', ' ');
for a=1:size(sidecamread,1);
    timeminside=cell2mat(table2array(sidecamread(a,3)));
    timeminsideh=str2num(timeminside(12:13))*60*60;
    timeminsidem=str2num(timeminside(15:16))*60;
    timeminsides=str2num(timeminside(18:27));
    finaltimeminside(a)=timeminsideh+timeminsidem+timeminsides;
end

% Find side video frames corresponding to the selected time window
point_sidemin=find((abs(finaltimeminside-finaltimemin))==min(abs(finaltimeminside-finaltimemin)));
point_sidemax=find((abs(finaltimeminside-finaltimemax))==min(abs(finaltimeminside-finaltimemax)));

% Read grayscale side camera video
v=VideoReader('C:\Users\marce\Google Drive\Shared_data_MM_CA\Imaging_D1D2\mousevideo_inscopix_aligned\24309_d1les\Bs\VideosideFile2017-08-30T16_14_43.avi')
i=1;
while hasFrame(v)
    video = readFrame(v);
    matrix_video(:,:,i)=video(:,:,1);
    i=i+1
end

video2use=matrix_video(:,:,point_sidemin:point_sidemax);

% Upsample calcium video by 3× to match behavioral video frame rate
for a=1:size(baselineinsco,3)*3
    frame=fix(a/3)+1;
    baselinevideo_times3(:,:,a)=imresize(baselineinsco(:,:,frame), [NaN 544]);
end

% Upsample behavioral video by 2× for temporal alignment
for a=1:size(video2use,3)*2
    frame=fix(a/2)+1;
    video2use_times2(:,:,a)=imresize(video2use(:,:,frame), [NaN 544]);
end

% Trim edge frames and format for concatenation
video2use_final = video2use_times2(:,:,9:end-9);
insco2use = uint8(255 * baselinevideo_times3);  % Convert to 8-bit grayscale
empty = 255 * ones(20,544,1802);                % White spacer between top and bottom videos

% Combine behavioral (top), spacer, and imaging (bottom) video streams
concatvid = cat(1, video2use_final, empty, insco2use);

% Export final composite video (baseline session)
vid = VideoWriter('C:\Users\marce\Google Drive\Shared_data_MM_CA\Imaging_D1D2\mousevideo_inscopix_aligned\24309_d1les\Bs\BS_Newbg.avi','Motion JPEG AVI');
vid.FrameRate=60;
open(vid)
for k = 1:1802 
   imshow(concatvid(:,:,k));
   frame = getframe(gcf);
   writeVideo(vid,frame);
   close
end

close(vid)

%% REPEAT SAME PROCEDURE FOR DRUG/LESION SESSION (LD)

accelbaseline='C:\Users\marce\Google Drive\Shared_data_MM_CA\Imaging_D1D2\mousevideo_inscopix_aligned\24309_d1les\LD\Accel2017-08-30T16_52_02.4756224+01_00.csv';
matrxbl= csvread(accelbaseline,1,0);

camerats=matrxbl((matrxbl(:,2)==37),3);
inscots=matrxbl((matrxbl(:,2)==35)&(matrxbl(:,4)>10000),3);

mininsco=inscots(14615-12064-0);
maxinsco=inscots(14615-12064+600);

pointmin=find((abs(camerats-mininsco))==min(abs(camerats-mininsco)))
pointmax=find((abs(camerats-maxinsco))==min(abs(camerats-maxinsco)))

topcam_computs='C:\Users\marce\Google Drive\Shared_data_MM_CA\Imaging_D1D2\mousevideo_inscopix_aligned\24309_d1les\LD\Centroid_Timestamped_Top2017-08-30T16_52_39.csv';
topcamread=readtable(topcam_computs, 'Delimiter', ' ');
timemin=cell2mat(table2array(topcamread(pointmin,3)));
timeminh=str2num(timemin(12:13))*60*60;
timeminm=str2num(timemin(15:16))*60;
timemins=str2num(timemin(18:27));
finaltimemin=timeminh+timeminm+timemins;

timemax=cell2mat(table2array(topcamread(pointmax,3)));
timemaxh=str2num(timemax(12:13))*60*60;
timemaxm=str2num(timemax(15:16))*60;
timemaxs=str2num(timemax(18:27));
finaltimemax=timemaxh+timemaxm+timemaxs;

sidecam_computs='C:\Users\marce\Google Drive\Shared_data_MM_CA\Imaging_D1D2\mousevideo_inscopix_aligned\24309_d1les\LD\Centroid_Timestamped_Side2017-08-30T16_52_39.csv';
sidecamread=readtable(sidecam_computs, 'Delimiter', ' ');
for a=1:size(sidecamread,1);
    timeminside=cell2mat(table2array(sidecamread(a,3)));
    timeminsideh=str2num(timeminside(12:13))*60*60;
    timeminsidem=str2num(timeminside(15:16))*60;
    timeminsides=str2num(timeminside(18:27));
    finaltimeminside(a)=timeminsideh+timeminsidem+timeminsides;
end

point_sidemin=find((abs(finaltimeminside-finaltimemin))==min(abs(finaltimeminside-finaltimemin)));
point_sidemax=find((abs(finaltimeminside-finaltimemax))==min(abs(finaltimeminside-finaltimemax)));

v=VideoReader('C:\Users\marce\Google Drive\Shared_data_MM_CA\Imaging_D1D2\mousevideo_inscopix_aligned\24309_d1les\LD\VideosideFile2017-08-30T16_52_39.avi')
i=1
while hasFrame(v)
    video = readFrame(v);
    matrix_video(:,:,i)=video(:,:,1);
    i=i+1
end

video2use=matrix_video(:,:,point_sidemin:point_sidemax);

for a=1:size(druginsco,3)*3
    frame=fix(a/3)+1;
    baselinevideo_times3(:,:,a)=imresize(druginsco(:,:,frame), [NaN 544]);
end

for a=1:size(video2use,3)*2
    frame=fix(a/2)+1;
    video2use_times2(:,:,a)=imresize(video2use(:,:,frame), [NaN 544]) ;
end

video2use_final=video2use_times2(:,:,9:end-9);
insco2use=uint8(255*baselinevideo_times3);
empty=255*ones(20,544,1802);

concatvid=cat(1,video2use_final, empty, insco2use);

vid = VideoWriter('C:\Users\marce\Google Drive\Shared_data_MM_CA\Imaging_D1D2\mousevideo_inscopix_aligned\24309_d1les\LD\Dysk_OptimalBG.avi','Motion JPEG AVI');
vid.FrameRate=60;
open(vid)
for k = 1:1799 
   imshow(concatvid(:,:,k));
   frame = getframe(gcf);
   writeVideo(vid,frame);
   close
end

close(vid)

