clear; pack;

%batch mode
loc = 'C:\Users\Lab_2\Desktop\mingfaifong\20100629\';
cd(loc);
dirdata = dir('*.mat');
datfiles = {dirdata.name};

for j = 1:numel(datfiles)
clearvars -except loc datfiles j;
pack;
fid = datfiles{j};

% load data   
%fid = '20100629_3-11.mat';
%loc = 'C:\Users\Lab_2\Desktop\mingfaifong\20100629\';

data = load(strcat([loc fid]));
datid = fieldnames(data);
if length(datid) == 1
    dat = data.(datid{1});
end
time = dat(:,1);
ord = 10e11*dat(:,2);
clear dat data datid

% reshape data into manageable chunks
segTime = 300; %in seconds (600s = 10min)
segLen = segTime*10000; %samples every 0.1ms
nChunks = ceil(length(time)/segLen);
padTime = padarray(time,nChunks*segLen - length(time),NaN,'post');
padOrd =  padarray(ord,nChunks*segLen - length(ord),NaN,'post');
newTime = reshape(padTime,segLen,nChunks);
newOrd =  reshape(padOrd,segLen,nChunks);
remTime = 5:5:segTime-5; %removing the weird thing every 5sec
newOrd(remTime*10000+1,:) = NaN;
newOrd(remTime*10000+2,:) = NaN;
newOrd(remTime*10000+3,:) = NaN;
newOrd(remTime*10000+4,:) = NaN;
newOrd(remTime*10000+5,:) = NaN;

% save chunks as separate files
for i = 1:nChunks
    clear time ord;
    time = newTime(:,i);
    ord = newOrd(:,i);
    fname_prefix = fid(1:length(fid)-4);
    fname_suffix = [num2str((i-1)*segTime),'to',num2str(i*segTime),'s'];
    save([loc '5min chunks\' fname_prefix '_' fname_suffix],'time','ord');
end


end



%     figure;
% for i = 1:nChunks
%     subplot(nChunks,1,i);
%     plot(newTime(:,i),newOrd(:,i));
% end