clear all
close all
truncResults_path = 'X:\707976 EPBuoyPrototypeAndTesting\Deployments\June2012 Deployment\MeasuredResults\';

j = 0;

dpath = '134.89.12.189/data/';
dataDirs = dir([dpath 'R*']);
  
for i = 1:length(dataDirs)
  if(dataDirs(i).isdir == 1)
     ppath = [dpath dataDirs(i).name '/'];
      
     matfiles = dir([ppath 'D*.mat']);

     K = length(matfiles);
 
     for k = 1:K
         j = j+1;
         results_filename{j} = [dpath dataDirs(i).name '/' matfiles(k).name]
     end
  end
end

wavedata_path = 'X:\707976 EPBuoyPrototypeAndTesting\Deployments\June2012 Deployment\CDIPWaveRiderData\';

files = dir([wavedata_path 'WaveData*.mat']);
%Put in chronological order
%Put in chronological order.
for i = 1:length(files)
    WaveData = load([wavedata_path files(i).name]);
    SerialDate(i) = WaveData.sdate;
end
[Dates IX] = sort(SerialDate);
files = files(IX);
clear WaveData SerialDate Dates IX i;

i = 1;
for j = 1:length(results_filename)-1
   MeasData{1} = load(results_filename{j});
   
   WaveData = load([wavedata_path files(i).name]);
   start_sdate = WaveData.sdate;
   end_sdate = start_sdate+1/(2*24);  %30 minutes
   while(start_sdate < MeasData{1}.serialdate(1))
      i = i+1
      WaveData = load([wavedata_path files(i).name]);
      start_sdate = WaveData.sdate;
      end_sdate = start_sdate+1/(2*24);  %30 minutes
   end
   
   datestr(MeasData{1}.serialdate(end))
   datestr(end_sdate)
   if(MeasData{1}.serialdate(end) > end_sdate)  %Entire wave file is in this buoy data file.
      idx = find((MeasData{1}.serialdate < end_sdate) & (MeasData{1}.serialdate >= start_sdate)); 
      MeasuredData = TruncateMeasuredData(MeasData{1},idx);
      store_results_filename = ['Results_' files(i).name]
      save([truncResults_path store_results_filename],'MeasuredData');

   else  %Data for this wave data file is spread over more than one buoy measurement file.
      disp('Split Files');
      idx = find((MeasData{1}.serialdate < end_sdate) & (MeasData{1}.serialdate >= start_sdate)); 
      MeasuredData_CellArray{1} = TruncateMeasuredData(MeasData{1},idx);
      k = 1;
      while( MeasData{k}.serialdate(end) < end_sdate)
         k = k+1;
         MeasData{k} = load(results_filename{j+k-1}); 
         idx = find((MeasData{k}.serialdate < end_sdate) & (MeasData{k}.serialdate >= start_sdate)); 
         MeasuredData_CellArray{k} = TruncateMeasuredData(MeasData{k},idx);
      end
      disp(['Concatenate and save ' num2str(k)]);
       
   end
   clear MeasuredData;
   
end

