%incoming.m

clear;
float = 'FAUCON';
%path =    sprintf('/u/bogcpf/data');
path =    sprintf('');
infile = sprintf('%s/%s.raw',path,float);
outfile = sprintf('%s/%s_sbd.mat',path,float);
outfig = sprintf('%s.T.png',float);


numfiles=0;
inFID = fopen(infile);
while ~feof(inFID)
  inString = fgets(inFID);
  if(inString(1)=='!')
      numfiles=numfiles+1;
  end
end
fclose(inFID);


MAXi=125;
P = NaN(numfiles,MAXi);
T = NaN(numfiles,MAXi);
S = NaN(numfiles,MAXi);
CPtime = NaN(numfiles,MAXi);
maxP = NaN(numfiles);
maxI = NaN(numfiles);
vac = NaN(numfiles);
battV = NaN(numfiles);
relh = NaN(numfiles);
lat = NaN(numfiles);
lon = NaN(numfiles);
gps_t = cell(numfiles);



 ii=1;
 inFID = fopen(infile);
 while ~feof(inFID)
  inString = fgets(inFID);
  if(inString(1)=='!')
   inFields = strsplit(inString, ',', 'CollapseDelimiters', false);

   %date and time
   A = sscanf(inFields{1},'!!!%d-%d-%dT%d:%d:%dZ');
   format long;
   prof_time = datenum(A(1),A(2),A(3),A(4),A(5),A(6));
   gps_t{ii}=sprintf('%02d%02d',A(4),A(5));

   %lat lon
   latmin=str2double(inFields{2})-3600;
   lonmin=str2double(inFields{4})-12100;
   lat(ii) = 36 + latmin/60;
   lon(ii) = -1*(121 + lonmin/60);

   maxP(ii) = -str2double(inFields{10});
   maxI(ii) = str2double(inFields{11});
   battV(ii) = str2double(inFields{14})/100;
   vac(ii) = str2double(inFields{15});
   relh(ii) = str2double(inFields{13})/100;


   begin = 16;

   for UBX = begin:1:size(inFields,2)
       if (strfind(inFields{UBX}, 'UBX') > 0)
           ubx = UBX;
       end
   end

   dat=1;
   for UBX = begin:3:ubx-1
       P(ii,dat)= -str2double(inFields{UBX});
       T(ii,dat)= str2double(inFields{UBX+1});
       S(ii,dat)= str2double(inFields{UBX+2});
       CPtime(ii,dat)=prof_time;
       dat=dat+1;
   end

   ii=ii+1;
  end
end
fclose(inFID);

numfiles = ii-1;

figure(1);hold on;
for prof=1:numfiles
    scatter(CPtime(prof,:),P(prof,:),350,T(prof,:),'filled','s');
end
colorbar;datetick;grid on
title('Temp');
xlabel('time');
ylim([min(min(P))-5 0]);
print(outfig,'-dpng');

figure(2);hold on;
for prof=1:numfiles
    scatter(CPtime(prof,:),P(prof,:),350,S(prof,:),'filled','s');
end
colorbar;datetick;grid on;
title('Sal');
xlabel('time');
ylim([min(min(P))-5 0]);
outfig = sprintf('%s.S.png',float);
print(outfig,'-dpng');

figure(3);

subplot(5,1,1);
plot(battV);
ylabel('battv');
grid on;
subplot(5,1,2);
plot(maxI);
ylabel('max amp');
grid on;
subplot(5,1,3);
plot(relh);
ylabel('relh');
grid on;
subplot(5,1,4);
plot(vac);
ylabel('int vac');
grid on;
subplot(5,1,5);
plot(maxP);
ylabel('max dBar');
grid on;
xlabel('prof');

outfig = sprintf('%s.ENG.png',float);
print(outfig,'-dpng');

bdjkmlwrite(float,lat,lon,gps_t);
