clear all
close all
SelectedResults_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];
         load(results_filename{j},'serialdate');
         Results_sdate(j) = serialdate(1);
         Results_edate(j) = serialdate(end);
     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]);
    Wave_sdate(i) = WaveData.sdate;
    Wave_edate(i) = Wave_sdate(i)+1/(2*24);  %30 minutes
end
[Dates IX] = sort(Wave_sdate);
Wave_sdate = Wave_sdate(IX);
Wave_edate = Wave_edate(IX);
Wave_files = files(IX);
clear WaveData Dates IX i files;



for i = 1:length(Wave_sdate)
  %Find all data files that have data for this range.
  PertinantFiles{i} = [];
  for k = 1:length(results_filename)
    if((Results_sdate(k) < Wave_edate(i)) && (Results_edate(k) > Wave_sdate(i)))
       PertinantFiles{i} = [PertinantFiles{i} k];
    end
  end
end

MeasData = cell(length(results_filename),1);
for i = 1:length(Wave_sdate)  %For each wave_data file...
    
  for j = PertinantFiles{i}  %Load buoy data file that has something to contribute.
     disp([num2str(i) '  ' num2str(j)]);
     if(isempty(MeasData{j}))
         MeasData{j} = load(results_filename{j});
     end
  end
 
  
  idx = {};
  for k = 1:length(PertinantFiles{i})  %For each pertinant buoy data file, find the data in the right time-frame. 
     j = PertinantFiles{i}(k)
     idx{k} = find((MeasData{j}.serialdate < Wave_edate(i)) & (MeasData{j}.serialdate >= Wave_sdate(i))); 
  end
  
  %Combine data into one structure and save with filename cooresponding to wave-data filename.
  if (~isempty(PertinantFiles{i}))
    SelectedData = SelectData(PertinantFiles{i},MeasData,idx);
    save([SelectedResults_path 'MeasuredResults_for' Wave_files(i).name],'SelectedData');
    clear SelectedData;
  end
  
  
  if(~isempty(PertinantFiles{i}))  %Free up memory, this isn't super efficient since it causes some re-loading...
    MeasData{PertinantFiles{i}(1)} = [];
  end
    
end
  