
close all
clear all


outDir = 'SeaHorseFiles';
files = dir([outDir '/*.cnv']);

n = 0;
for n = 1:length(files)
  fid = fopen([outDir '/' files(n).name]);
  
  %Determine appropriate info from text of each file.
  first_sample_time{n,1} = [];
  while(isempty(first_sample_time{n,1}))
     tline = fgets(fid);
     k = strfind(tline,'First Sample Time:');
     if(k>0)
         first_sample_time{n,1} = tline(k+19:k+39);
     end
  end
 
  %Read Data
  C{n,1} = textscan(fid, '%f %f %f %f %f %f','commentStyle','*');
  fclose(fid);
end


%Create timestamp estimate of each measurement, based on sample rate and
%start time.  Place result in last C field, it's unused anyway.
freq = 4;  %hz
for n = 1:length(files)
nn = datenum(first_sample_time{n,1});  %,'dd mmm yyyy HH:MM:SS');
for m = 1:length(C{n,1}{1})
C{n,1}{6}(m) = nn+m/(freq*60*60*24);
end
end


%Put data into arrays for plotting, etc.
data.time = []; data.press = []; data.temp = []; data.sal=[];
data.depth = []; data.pottemp = [];
for n = 1:length(files)
 data.press = [data.press; cell2mat(C{n,1}(1))];
 data.temp = [data.temp; cell2mat(C{n,1}(2))];
 data.sal = [data.sal; cell2mat(C{n,1}(3))];
 data.depth = [data.depth; cell2mat(C{n,1}(4))];
 data.pottemp = [data.pottemp; cell2mat(C{n,1}(5))];
 data.time = [data.time; cell2mat(C{n,1}(6))];
end


%Sort all into order of increasing time, in case file's were read in out of
%order.
[data.time,IX] = sort(data.time);
data.press = data.press(IX);
data.temp = data.temp(IX);
data.sal = data.sal(IX);
data.depth = data.depth(IX);
data.pottemp = data.pottemp(IX);
clear IX;


%Grid and Plot
dt = 10;  %minutes
t0 = data.time(1);
tf = data.time(end);
depthMin = min(data.depth);
depthMax = max(data.depth);
dh = 0.1;  %meters

[XI,YI] = meshgrid(t0:(tf-t0)/(60*24/dt):tf,depthMin:(depthMax-depthMin)/10:depthMax);

TempI = griddata(data.time,data.depth,data.temp,XI,YI);
SalI = griddata(data.time,data.depth,data.sal,XI,YI);
PotTempI = griddata(data.time,data.depth,data.pottemp,XI,YI);

figure
contourf(XI,YI,TempI,20);
datetick('x');
set(gca,'YDir','reverse') ;
print -dpng Temp
print -depsc2 Temp

figure
contourf(XI,YI,SalI,20);
datetick('x');
set(gca,'YDir','reverse') ;

figure
contourf(XI,YI,PotTempI,20);
datetick('x');
set(gca,'YDir','reverse') ;



