function split_ctf_recording(origDS, newDSpath, sampRate, totalTrials)
% splits CTF .ds recordings into chunks according to the head
% movement.  Run the Brainstorm process 'process_detect_movement.m' first to get the
% headpositions.txt file
% 
% Inputs: 	origDS		- file to split
%		newDSpath	- directory where the new file will be written
%		sampRate	- sampling rate of the data set
%		totalTrial	- total trials in the file
%
% Elizabeth Bock 2013-2015 

%% Info
info = load(fullfile(origDS, 'headpositions.txt'));
[p,n] = fileparts(origDS);

posFile = dir([origDS '/*.pos']);
posFile = fullfile(origDS, posFile.name);

% find files that are > 5 secs
len = diff(info(:,1));
ind = find(len > sampRate*5);
disp(['Files ' num2str(ind') ' are greater than 5 seconds']);

%% split first chunk
if info(1,1) == 1
    disp('first chunk has a new head position also')
    % go directly to the 'N-1 chunks' to get the new head position
else
    st = 1;
    en = round(info(1,1)/sampRate) - 1;
    newDS = [newDSpath '/' n '_s1.ds'];
    command = ['ctf newDs -includeTrialRange ' num2str(st) ' ' num2str(en) ' ' origDS ' ' newDS];
    system(command)
    try
        copyfile(posFile,newDS)
    catch
        disp (['cannot copy pos file to ' newDS])
    end
end


%% next N-1 chunks
for ii = 1:size(info,1) - 1
    % split next chunk
    st = max(1,round(info(ii,1)/sampRate));
    en = round(info(ii+1,1)/sampRate) - 1;
    newDS = [newDSpath '/' n '_s' num2str(ii+1) '.ds'];
    command = ['ctf newDs -includeTrialRange ' num2str(st) ' ' num2str(en) ' ' origDS ' ' newDS];
    system(command) 

    % update head position (need mm for input to this function)
    na = info(ii,3:5).*1000;
    le = info(ii,6:8).*1000;
    re = info(ii,9:11).*1000;
    command = ['ctf changeHeadPos -na ' num2str(na) ' -le ' num2str(le) ' -re ' num2str(re) ' ' newDS];
    system(command)

    try
        copyfile(posFile,newDS)
    catch
        disp (['cannot copy pos file to ' newDS])
    end
end

%% last chunk
ind = size(info,1);
st = round(info(ind,1)/sampRate);
en = totalTrials;
newDS = [newDSpath '/' n '_s' num2str(ind+1) '.ds'];
command = ['ctf newDs -includeTrialRange ' num2str(st) ' ' num2str(en) ' ' origDS ' ' newDS];
system(command) 

% update head position
na = info(ind,3:5).*1000;
le = info(ind,6:8).*1000;
re = info(ind,9:11).*1000;
command = ['ctf changeHeadPos -na ' num2str(na) ' -le ' num2str(le) ' -re ' num2str(re) ' ' newDS];
system(command)

try
    copyfile(posFile,newDS)
catch
    disp (['cannot copy pos file to ' newDS])
end
