%clear all

%%% Read RD/NAP drifter text files into Matlab structure.

list=dir('*RD*txt');

if length(list)==0
    error('no .txt files found with RD in the filename')
else
    disp(['processing ' num2str(length(list)) ' textfiles' ])
end

for j=1:length(list)
    
    filenameRAW.name=list(j).name;
    fid = fopen(filenameRAW.name);
    
    disp(['opening ' filenameRAW.name])
    
    GPSdata=[]; GPStime=[]; X=[]; Y=[]; Z=[]; %% clear matrices
    
    for i=1:20      % skip header lines
        tline = fgetl(fid);
    end

    gi=0;
    for i=1:200000                % Arbitrary high number
        tline = fgetl(fid);
        if length(tline) >= 50
            gi=gi+1;
            tline = strrep(tline, ',', '.');  % replace the old decimal seperator (comma's) into points
            %%% tline info: GPSTime Date Easting Northing
            [ time date c d e] = strread(tline, '%s %s %f %f %f ', 'delimiter',' ');

            %%% GPS TIME in UTC hh:mm:ss.decss
            [ hh mm ss ] = strread(cell2mat(time), '%f %f %f  ', 'delimiter',':');
            GPStime(gi,1)=hh*3600+mm*60+ss; %%GPS time in sec after midnight

            X(gi,1)=c; %% east

            Y(gi,1)=d; %% north
            
            Z(gi,1)=e; %% elevation 

        else
            break
        end

    end


    fclose(fid);

    %%%% STORE DATA in single Matrix
    
   
        
    GPSdata(:,1)=X;
    GPSdata(:,2)=Y;
    GPSdata(:,3)=GPStime;   %in sec after midnight
    eval([filenameRAW.name(1:end-4) '=GPSdata;' ]); % rewrite to bluelogger unique name

   % eval(['save(''' filenameRAW.name(1:end-4) '.mat'', ''' filenameRAW.name(1:end-4) ''',''date'')'])

end