function RemoveBeginningFramesByTimeFunction(movName,numSecondsToLeave)
% RemoveBeginningFramesByTimeFunction_v4_flycap crops movie to keep only a user-defined number of seconds
% at the end. The rest of the movie is deleted. The movie can then be further cropped on a
% frame-based basis using the RemoveFramesFunction.
%
% WARNING: the original movie is overwritten! Please keep all originals in a separate place.
%
%%%%%%% Arguments:
% movName [string]: name of movie to crop
% numSecondsToLeave [double]: number of seconds to pause between frames. Does not have to be
% integer: corresponding frame numbers will be rounded.
%
% WARNING: AGAIN, IT IS IMPOTANT TO HAVE THE ORIGINAL MOVIE BACKED UP IN A DIFFERENT FOLDER!


workingDir = tempname;
mkdir(workingDir);
mkdir(workingDir,'images');

close

% Load Original Movie And Create Sorted Images From Frames
movOriginal = VideoReader(movName);
numFrames = movOriginal.NumberOfFrames;
frameRate = movOriginal.framerate;

for i = 1:numFrames
    img = read(movOriginal,i);
    img = img(:,:,2); % take only green channel (camera is set to green-scale)
    imwrite(img,fullfile(workingDir,'images',sprintf('img%d.jpg',i)));
end

imageNames = dir(fullfile(workingDir,'images','*.jpg'));
imageNames = {imageNames.name}';

imageStrings = regexp([imageNames{:}],'(\d*)','match');
imageNumbers = str2double(imageStrings);

[~,sortedIndices] = sort(imageNumbers);
sortedImageNames = imageNames(sortedIndices);

% Cut out all but requested number of seconds from movie
framesToKeep = round(max(numFrames-numSecondsToLeave*frameRate,1)):numFrames; % keep either the user specified number of seconds or 1 (if there are fewer seconds in the movie)
framesToRemove = setdiff(1:numFrames,framesToKeep);

% Crop Movie

for i = framesToRemove
    delete(fullfile(workingDir,'images',sortedImageNames{i})) % BE CAREFUL, AS DELETE DOES NOT GIVE ANY WARNINGS WHEN REMOVING FILES
end

imageNames = dir(fullfile(workingDir,'images','*.jpg'));
imageNames = {imageNames.name}';

imageStrings = regexp([imageNames{:}],'(\d*)','match');
imageNumbers = str2double(imageStrings);

[~,sortedIndices] = sort(imageNumbers);
sortedImageNames = imageNames(sortedIndices);

numFrames = length(sortedImageNames);
outputCroppedMovie = VideoWriter(movName);
outputCroppedMovie.FrameRate = movOriginal.FrameRate;
open(outputCroppedMovie);
for i = 1:numFrames
    img = imread(fullfile(workingDir,'images',sortedImageNames{i}));
    writeVideo(outputCroppedMovie,img);
end
close(outputCroppedMovie);
close


end
    

