function [pos, dat, date]=rd_apex(fnam)
%
%  program to read apex profile data files
%  called from gen_apex_data 
%
%  INPUTS
%    FNAM = file name to read in
%
%  OUTPUTS
%  	pos-position data
%   dat-data(p, T, S, O, BlueRef, FSig, NtuReg, Tsig, theta, sigma, O2sat, O2, chl, B_LSS)
%
%   written by Emmanuel Boss, UMaine, 2004
%   
fid=fopen(fnam,'r')
%
%   skip nondata lines
junk=fscanf(fid,'%c',[6]); %reads first 6 elements and stores as characters in array junk 
while(strcmp(junk,'$  Fix')==0) %compares the contents of array junk to the string $  Fix - if equal to 0 (line is empty),
    line=fgetl(fid); %gets next line
    junk=fscanf(fid,'%c',[6]); %reads first 6 characters and stores as characters in array junk
end
%
i=1;
while(junk=='$  Fix') %while the first six characters match $  Fix
     junk=fscanf(fid,'%c',[9]); %reads the next 9 elements and stores as characters in array junk 
     junk=fscanf(fid,'%e',[3]); %reads the next 3 elements (lat, lon, and minutes) and stores as exponential notation in array junk
     pos(i,1:3)=junk(1:3)'; %assigns elements in array junk to array pos at row i
     date1=fscanf(fid,'%s',[1]);
     mo=str2num(date1(1,1:2));
     da=str2num(date1(1,4:5));
     yr=str2num(date1(1,7:10));
     %
     time1a=fscanf(fid,'%f',[1]); % need to break into hours and minutes
     time1b=time1a*3600; % convert hrs/min to seconds
     hr=fix(time1b/3600); % get number of hours
     time1b=time1b-(3600*hr); % remove the hours
     min=fix(time1b/60); % get number of minutes
     time1b=time1b-(60*min); % remove the minutes
     sec=time1b; % get seconds
     %
     date(i,:)=datenum(yr,mo,da,hr,min,sec);
     i=i+1; 
     line=fgetl(fid); %gets next line
     junk=fscanf(fid,'%c',[6]); %%reads first 6 elements and stores as characters in array junk
end %ends when there are no more lines beginning with $  Fix
%
%   skip the format and data header lines
line=fgetl(fid); %gets next line
line=fgetl(fid); %gets next line
%
%   gets the next 14 fields of data and assigns -999 to *
i=1;
clear junk
while(feof(fid)==0); %while not at end of file
    for j=1:15 
        junk2=fscanf(fid,'%s',[1]); %reads next element and stores as character in junk2
        if junk2=='*' %if junk2 equals * (no data recorded)
             junk(j)=-999; %sets j to -999 and stores in array junk
        else
             junk(j)=str2num(junk2); %converts the string in junk2 to a number and stores in array junk 
        end %repeats for 15 fields
    end
    dat(i,:)=junk; %assigns 15 fields in junk to array dat at row i 
    i=i+1; %increments i 
    line=fgetl(fid); %gets next line
end %ends when feof is reached
%passes arrays pos and dat to gen_apex_data.m
dat(:,16)=date(1,1);
fclose(fid);
