function [date dateb stat lat lon dat]=rd_msg(fnam)
%
%  Program to read ARGOS message data files
%
%  INPUTS
%    FNAM = file name to read in.
%
%  OUTPUTS
%    
%   dat-data(p, F_ref, F_sig, LSS_ref LSS_Sig)
%
%  Written by Emmanuel Boss, UMaine, 2005.
%   
fid=fopen(fnam,'r')
%
%fid=fopen('0015.001.msg-all','r')
%read lines until the second byte is '02'-the message containing surface
%data
%
ii=1;
junk=fscanf(fid,'%x',[2]);
while(feof(fid)==0) 
     if(junk(2)~= 2)
        junk=fgetl(fid);
        junk=fscanf(fid,'%x',[2]);
    elseif(junk(2)==2)
       fseek(fid,-5,0);
    %for i=1:32
        junk2(:,:)=fscanf(fid,'%s',[32]);
    %end
        date1=fscanf(fid,'%s',[1]);
        time1=fscanf(fid,'%s',[1]);
        for i=1:7
           garb=fscanf(fid,'%s',[1]);
        end
        junk3=fscanf(fid,'%s',[1]);
        nn=length(junk3); %added 05/11/06
        if (nn==1) & (str2num(junk3) == 1 |str2num(junk3) == 2 |str2num(junk3) == 3) %if we have position information
           dat(ii,1)=hex2dec(junk2(5))*16^3+hex2dec(junk2(6))*16^2+hex2dec(junk2(7))*16+hex2dec(junk2(8));%pressure
           dat(ii,2)=hex2dec(junk2(9))*16^2+hex2dec(junk2(10))*16+hex2dec(junk2(11));%F_Ref
           dat(ii,3)=hex2dec(junk2(12))*16^2+hex2dec(junk2(13))*16+hex2dec(junk2(14));%F_Sig
           dat(ii,4)=hex2dec(junk2(15))*16^2+hex2dec(junk2(16))*16+hex2dec(junk2(17));%LSS_Ref
           dat(ii,5)=hex2dec(junk2(18))*16^2+hex2dec(junk2(19))*16+hex2dec(junk2(20));%LSS_Sig  
           dat(ii,6)=hex2dec(junk2(21))*16^3+hex2dec(junk2(22))*16^2+hex2dec(junk2(23))*16+hex2dec(junk2(24));%T_sensor
           stat(ii,:)=junk3;
           yr=str2num(date1(1,1:4));
           mo=str2num(date1(1,6:7));
           da=str2num(date1(1,9:10));
           hr=str2num(time1(1,1:2));
           min=str2num(time1(1,4:5));
           sec=str2num(time1(1,7:8));
           date(ii,:)=datenum(yr,mo,da,hr,min,sec);
           date2=fscanf(fid,'%s',[1]);
           time2=fscanf(fid,'%s',[1]);
           yr=str2num(date2(1,1:4));
           mo=str2num(date2(1,6:7));
           da=str2num(date2(1,9:10));
           hr=str2num(time2(1,1:2));
           min=str2num(time2(1,4:5));
           sec=str2num(time2(1,7:8));
           dateb(ii,:)=datenum(yr,mo,da,hr,min,sec);
           lat(ii,:)=fscanf(fid,'%s',[1]);
           lon(ii,:)=fscanf(fid,'%s',[1]);
           garb=fgetl(fid);
           junk=fscanf(fid,'%x',[2]);
           ii=ii+1;
        else
           fseek(fid,-2,0);
           junk=fscanf(fid,'%x',[2]);
        end
     end
end
fclose(fid);