%% Load image;
function [Sx,Sy,V]=genSpaceTimeVid(foldMain,vidName,startTime,numFrames,maxXpix,foldSave,saveXtime,saveYtime,saveXY)

%%% INPUTS %%%
% filename - number of frames to load from video

%% Load video
filename = [foldMain,vidName];
v = VideoReader(filename); % create video object
v.CurrentTime = startTime; % time to start video
maxFrames = floor((v.Duration-startTime)*v.FrameRate)-2;
p = 2; % initialize p

if numFrames>maxFrames
    
    disp('Not enough time for input total number of frames');
    disp(['Setting number of frames to: ',num2str(maxFrames)]);
    
    numFrames = maxFrames;
    
end

disp('... LOADING  VIDEO ...')
clear V

testFrame = readFrame(v);
% maxXpix = 800;
nPxTest = size(testFrame,2);

if size(testFrame,2) > maxXpix
    
    reScale = maxXpix/nPxTest;
    V(:,:,:,1) = imresize(testFrame,reScale);
    while p<=numFrames
        temp = imresize(readFrame(v),reScale);
        V(:,:,:,p) = temp; % Matrix containing all images of video
        p=p+1;
    end
    
else
    
    V(:,:,:,1) = testFrame;
    while p<=numFrames
        
        V(:,:,:,p) = readFrame(v); % Matrix containing all images of video
        p=p+1;
        
    end
    
end

[nPy,nPx,~,N]=size(V); % size of video matrix

disp(' ');
%% Create X - time images

disp('... CREATING X-time images ...')
clear Sx
for d=1:nPy
    
    temp = squeeze(V(d,:,:,:));
    
    for p =1:N
        Sx(:,p,:,d)=temp(:,:,p);
    end
    
end
disp(' ');

%% Create Y - time images

disp('... CREATING Y-time images ...')

clear Sy
for d=1:nPx
    
    temp = squeeze(V(:,d,:,:));
    
    for p =1:N
        Sy(:,p,:,d)=temp(:,:,p);
    end
    
end

disp(' ');

%% Save space-time videos

disp('... SAVING Space-Time videos ...')


if saveXtime ==1
    % save([foldSave,'Sx.mat'],'Sx');
    v = VideoWriter([foldSave,vidName,'_Sx']);
    open(v);
    writeVideo(v,Sx);
    close(v);
end

if saveYtime ==1
    % save([foldSave,'Sy.mat'],'Sy');
    v = VideoWriter([foldSave,vidName,'_Sy']);
    open(v);
    writeVideo(v,Sy);
    close(v);
end

if saveXY ==1
    % save([foldSave,'Sy.mat'],'Sy');
    v = VideoWriter([foldSave,vidName,'_V']);
    open(v);
    writeVideo(v,V);
    close(v);
end

clc
