% nbp1201_read_merge_UW_navigation.m
%
% Read original UW data files under format control;
% load Navigation mat files;
% merge UW and navigation;
% save as mat files.
%
%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
%@@@@@@@@@@@@@   DATA SOURCE  @@@@@@@@@@@@@@@@@@
%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
% (1) UNDERWAY data
% Original rvdas underway data:
% http://science.whoi.edu/users/mcgillic/nbp1201/rvdas/uw/
% File names:
% 1201eng1.tar
% 1201gen1.tar
% 1201hdas.tar
% 1201knud.tar
% 1201mtsg.tar
% 1201mwx1.tar
% 1201oxyg.tar
% 1201pco2.tar
% 1201pguv.tar
% 1201rtmp.tar
% 1201svp1.tar
% Also in the directory and not merged: 
% 1201bwnc.tar (no name and description)
% 1201ctdd.tar (no name and description)
% 1201cwnc.tar (no name and description)
% 1201grv1.tar Gravimeter raw data
% 1201mbdp.tar Multibeam depth data (no description)
% 1201twnc.tar Winch data
%
% (2) NAVIGATION data
% rvdas navigation mat files (OUTPUT from: nbp1201_read_navigation.m),
% seap/GGA as PRIMARY navigation source and PCOD/GGA as SECONDARY source
% (for points not available in PRIMARY).
%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

clear;

t0 = clock;
%operation
%etime(clock,t0)

% Option: Save data as mat file:
%optionSave='yes';
optionSave='no';
% Days list.
day_list=[361:365 1:36];
%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
%@@@@@@@@  SEARCH in Navigation: @@@@@@@@@@@@
%@@@@@@@@@@@@  Time INTERVAL  @@@@@@@@@@@@@@@
%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
%------------------
d_search_sec=0.6;      % unless assigned further
d_search_sec_add=0.6;  % unless assigned further
%------------------
%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
%@@@@@@@@@  OUTPUT matrix columns:  @@@@@@@@@
%@@@@ Date/Time/Location - same for all @@@@@
%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
colYear_M=1;
colDay_M=2;
colHour_M=3;
colMin_M=4;
colSec_M=5;
colLat_M=6;
colLon_M=7;
%$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
%$$$$$$$$$$$$$  N A V I G A T I O N   DATA  $$$$$$$$$$$$$$
%$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
colLat_N_2=7;  % ddmm.mmmmmm
colLon_N_2=8;  % ddmm.mmmmmm
path_part_1_nav='/data2/antarctic_data2/nbp1201/underway/rvdas/nav/';
%------------------------------------------------
% -------- MENU (1): Navigation channel ---------
%------------------------------------------------
%%%channel_name_list_nav=strvcat('PCOD GLL: Trimble (PCOD) GPS','PCOD GGA: Trimble (PCOD) GPS','seap GGA: seapath GPS - GGA');
%%%channel_name_nav=f_menu_of_strings('NAVIGATION channel',channel_name_list_nav);
%%%if isempty(channel_name_nav), return; end
%%%pause(0.001);
%channel_name_nav='PCOD GLL: Trimble (PCOD) GPS';
channel_name_nav='seap GGA: seapath GPS - GGA';
% NOTE:
% seap/GGA is chosen as PRIMARY navigation source.
% The missing points are taken from the SECONDARY source - PCOD/GGA
% (if available).
%--------------------------------------------
channel_id_nav=channel_name_nav(1:4);
sub_channel_id_nav=channel_name_nav(6:8);
%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
%@@@@@@@ N A V I G A T I O N  columns @@@@@@@
%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
colYear_N=1;
colDay_N=2;
colHour_N=3;
colMin_N=4;
colSec_N=5;
if strcmp(channel_id_nav,'PCOD') & strcmp(sub_channel_id_nav,'GLL')
    % (1) PCOD GLL (day #1 size: 86400x9):
    colLat_N=6;  % degrees
    colLon_N=7;  % degrees
elseif  strcmp(channel_id_nav,'PCOD') & strcmp(sub_channel_id_nav,'GGA')
    % (2) PCOD GGA (day #1 size: 86400x16).
    colTime_N=6; % hhmmss.ss
    colLat_N=7;  % ddmm.mmmmmm
    colLon_N=8;  % ddmm.mmmmmm
elseif strcmp(channel_id_nav,'seap') & strcmp(sub_channel_id_nav,'GGA')
    %@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    %@@@@@@@  INPUT Navigation columns   @@@@@@@@
    %@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    % (3) seap GGA (day #1 size: 86411x15).
    % NOTE: variable "Empty field" excluded;
    %the name of the last variable is not clear - the guide shows 2 variables after
    % the last "M" (put to"1" in my mat files):
    % "age of DGPS corrections in seconds (s.s)" and "DGPS reference station ID
    % (0000-1023)" and only one of them is available in the data.
    %par_list=strvcat('GPS quality indicator, 0=invalid, 1=GPS SPS, 2=DGPS, 3=PPS, 4=RTK, 5=float RTK, 6=dead reckoning',...
    %    'number of satellites in use (00-99)',...
    %    'HDOP x.x',...
    %    'height above ellipsoid in meters m.mm',...
    %    'M',...
    %    'M',...
    %    'age of DGPS corrections in seconds s.s ');
    % ??? 'DGPS reference station ID (0000-1023)',... in the descriptin
    % is the last variables before Check Sum which I do not use. In the
    % data seems it is lost.
    colTime_N=6; % hhmmss.ss
    colLat_N=7;  % ddmm.mmmmmm
    colLon_N=8;  % ddmm.mmmmmm
else
    return;
end
sub_channel_id_nav_str=['_' sub_channel_id_nav];
path_name_nav=[path_part_1_nav channel_id_nav '/process/'];
path_name_nav_2=[path_part_1_nav 'PCOD/process/'];
fname_ext_nav='mat';
%$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
%$$$$$$$$$$$$$$$  U N D E R W A Y   DATA  $$$$$$$$$$$$$$$$
%$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
path_part_1='/data2/antarctic_data2/nbp1201/underway/rvdas/uw/';
time_tag_chars=1:19;   %12+001:00:00:00.086
channel_list=strvcat('eng1','gen1','hdas','knud','mtsg','mwx1','oxyg','pco2','pguv','rtmp','svp1');
channel_name_list=strvcat('eng1: Engineering','gen1: Micro-TSG #2','hdas: Hydro-DAS','knud: Knudsen','mtsg: Micro-TSG',...
    'mwx1: Meteorology','oxyg: Oxygen data','pco2: PCO2','pguv: GUV data','rtmp: Remote Temperature','svp1: Sound Velosity Probe');
% ----- MENU: Underway channel -----
channel_name=f_menu_of_strings('Channel',channel_name_list);
if isempty(channel_name), return; end
channel_id=channel_name(1:4);
%channel_id='oxyg';
pause(0.01);
text_tag_list='';
comma_delimeter='no';
if strcmp(channel_id,'eng1')
    % The number of columns to read data.
    n_par=17;
    % !!! In the document there are total 16 values (5 of them are time tag values)
    % but data files have total 17 values. What is this ????
    %------------------
    d_search_sec=0.5;
    %------------------
elseif strcmp(channel_id,'gen1')
    comma_delimeter='yes';
    % The number of columns to read data.
    n_par=9;
    % Day #22 is not available - exclude from the list.
    no_day=22;
    r_no_day=find(day_list(:)==no_day);
    day_list(r_no_day)=[];
elseif strcmp(channel_id,'hdas')
    % The number of columns to read data.
    n_par=14;
elseif strcmp(channel_id,'knud')
    comma_delimeter='yes';
    % The number of columns to read data. 
    n_par=7;
    text_tag_list=strvcat(' HF',...
        ',LF',...
       ',------');
elseif strcmp(channel_id,'mtsg')
    comma_delimeter='yes';
    % The number of columns to read data.
    n_par=9;
elseif strcmp(channel_id,'mwx1')
    comma_delimeter='yes';
    mwx1_channels=strvcat('MET','SUS','PUS');
    % ----- MENU: Meteorology channel part -----
    %mwx1_channel_id=f_menu_of_strings('Meteorology mwx1 data',strvcat('MET','PUS','SUS'));
    %if isempty(mwx1_channel_id), return; end
    %mwx1_channel_id=deblank(mwx1_channel_id);
    %------------------
    d_search_sec=0.5;
    %d_search_sec_add=0.6;
    %------------------
elseif strcmp(channel_id,'oxyg')
    % The number of columns to read data.
    n_par=17;
    text_tag_list=strvcat('MEASUREMENT',...
        'Oxygen:',...
        'Saturation:',...
        'Temperature:',...
        'DPhase:',...
        'BPhase:',...
        'RPhase:',...
        'BAmp:',...
        'BPot:',...
        'RAmp:',...
        'RawTem.:');
elseif strcmp(channel_id,'pco2')
    % The number of columns to read data.
    n_par=16;
    text_tag_list=strvcat('01 Equil',...
        '02 Atmos',...
        '03 Nitrogen',...
        '04 CA06630',...
        '05 CA06632',...
        '06 CA06636',...
        '07 CA06661',...
        '08 CA07206');
elseif strcmp(channel_id,'pguv')
    % The number of columns to read data.
    n_par=17;
elseif strcmp(channel_id,'rtmp')
    % The number of columns to read data.
    n_par=6;
elseif strcmp(channel_id,'svp1')
    % The number of columns to read data. 
    n_par=6;
else
    return
end
% Path, name.
path_name=[path_part_1 channel_id '/'];
fname=['NBP1201' channel_id];
path_name_out=[path_name 'process/'];
fname_out_part=['NBP1201_uw_' channel_id];
fname_out_ext='mat';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%  For EACH DAY %%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%------------------
d_search=d_search_sec/3600;
d_search_add=d_search_sec_add/3600;
%------------------
data=ones(100000,20);
time_notFound_final_all=[]; % after additional search interval added and some points found
time_notFound_final_all_2=[]; % after additional search interval added and some points found
time_points_moreThanTwo=[];
LOCATION_from_secondary_NAVIGATION_all=[];
TIME_diff_UW_NAV_max_in_seconds=[];
%DDD=[];
not_idential=[];
%d_uw_merged=[];
%%%day_list=[361:365 1:36];
%%%day_list=[361 4 5 12]% days for recalculation with secondary Navigation used instead of partly missed primary navigation  
for day=1%[361:365 2:36]%day_list
%for day=1%[8:36]%:2%day_list
    if day>=361
        year=11;
    else
        year=12;
    end
    % one day info - initial matricies.
    points_moreThanOne=[];
    time_notFound=[];
    time_notFound_2=[];
    time_notFound_final=[];   % after additional search interval added and some points found
    time_notFound_final_2=[]; % after additional search interval added and some points found
    notFound_count=0;
    notFound_count_2=0;
    moreThanOne_count=0;
    time_diff_day=[];
    if day<10
        fname_ext=['d00' num2str(day)];
    elseif day>=10 &  day<100
        fname_ext=['d0' num2str(day)];
    else
        fname_ext=['d' num2str(day)];
    end
    day_str=fname_ext;
    %*************************************************
    %************    NAVIGATION   ********************
    %************   LOAD  mat file   *****************
    %*************************************************
    fname_nav=['NBP1201_nav_' channel_id_nav '_' sub_channel_id_nav '_'  day_str];
    p=['load ' path_name_nav fname_nav '.' fname_ext_nav ';'];
    eval(p);
    p=['d_nav=' fname_nav ';'];
    eval(p);
    %size(d_nav)
    if  ( strcmp(channel_id_nav,'PCOD') & strcmp(sub_channel_id_nav,'GGA') ) | ...
            ( strcmp(channel_id_nav,'seap') & strcmp(sub_channel_id_nav,'GGA') )
        % Lat, Lon - Get decimal degree from ddmm.mmmmmm.
        lat=abs(d_nav(:,colLat_N));
        lon=abs(d_nav(:,colLon_N));
        lat_dec=floor(lat/100) + ( (floor(lat)/100-floor(lat/100))*100 + ( lat-floor(lat) ) )/60;
        lon_dec=floor(lon/100) + ( (floor(lon)/100-floor(lon/100))*100 + ( lon-floor(lon) ) )/60;
        r_minus_lat=find(d_nav(:,colLat_N)<0);
        r_minus_lon=find(d_nav(:,colLon_N)<0);
        lat_dec(r_minus_lat,1)=lat_dec(r_minus_lat,1)*(-1);
        lon_dec(r_minus_lon,1)=lon_dec(r_minus_lon,1)*(-1);
        d_nav(:,colLat_N)=lat_dec;
        d_nav(:,colLon_N)=lon_dec;
        %--------- E.g. --------------------
        %lat=6421.630563;
        %lon=09907.079075;
        %lat_dec=floor(lat/100) + ( (floor(lat)/100-floor(lat/100))*100 + ( lat-floor(lat) ) )/60;
        %--------- E.g. END --------------------
        clear lat lon lat_dec lon_dec r_minus_lat r_minus_lon
    end
    % Decimal hour from Navigation.
    h_dec_N=d_nav(:,colHour_N) + ( d_nav(:,colMin_N) + d_nav(:,colSec_N)/60 )/60;
    %**************************************************************
    %*********  LOAD another NAVIGATION SOURCE - PCOD/GGA *********
    %************   Search for the data not available in  *********
    %************  PRIMARY Navigation source  - seap/GGA  *********
    %**************************************************************
    if day==361 | day==4 |  day==5 | day==12
        fname_nav_2=['NBP1201_nav_PCOD_GGA_'  day_str];
        p=['load ' path_name_nav_2 fname_nav_2 '.' fname_ext_nav ';'];
        eval(p);
        p=['d_nav_2=' fname_nav_2 ';'];
        eval(p);
        % Lat, Lon - Get decimal degree from ddmm.mmmmmm.
        lat=abs(d_nav_2(:,colLat_N_2));
        lon=abs(d_nav_2(:,colLon_N_2));
        lat_dec=floor(lat/100) + ( (floor(lat)/100-floor(lat/100))*100 + ( lat-floor(lat) ) )/60;
        lon_dec=floor(lon/100) + ( (floor(lon)/100-floor(lon/100))*100 + ( lon-floor(lon) ) )/60;
        r_minus_lat=find(d_nav_2(:,colLat_N_2)<0);
        r_minus_lon=find(d_nav_2(:,colLon_N_2)<0);
        lat_dec(r_minus_lat,1)=lat_dec(r_minus_lat,1)*(-1);
        lon_dec(r_minus_lon,1)=lon_dec(r_minus_lon,1)*(-1);
        d_nav_2(:,colLat_N_2)=lat_dec;
        d_nav_2(:,colLon_N_2)=lon_dec;
        %--------- E.g. --------------------
        %lat=6421.630563;
        %lon=09907.079075;
        %lat_dec=floor(lat/100) + ( (floor(lat)/100-floor(lat/100))*100 + ( lat-floor(lat) ) )/60;
        %--------- E.g. END --------------------
        clear lat lon lat_dec lon_dec r_minus_lat r_minus_lon
        % Decimal hour from Navigation.
        h_dec_N_2=d_nav_2(:,colHour_N) + ( d_nav_2(:,colMin_N) + d_nav_2(:,colSec_N)/60 )/60;
    end
    %*************************************************
    %****************** UNDERWAY *********************
    %***********    Open file for reading   **********
    %*************************************************
    pfid = fopen([path_name fname '.' fname_ext]);
    if pfid<0
        fclose(pfid);
        disp(['File not found: ' fname '.' fname_ext ]);
        return;
    end
    count_line=0;
    data=[];
    data_MET=[];
    data_SUS=[];
    data_PUS=[];
    while 1
        count_line=count_line+1;
        line = fgetl(pfid);
         if ( strcmp(channel_id,'hdas') & day==8 & count_line==1 ) | ...
            ( strcmp(channel_id,'pguv') & day==361 & count_line==1 )   
            % 1st line is "bad", miss it.
            line = fgetl(pfid);
         end   
       %%%%line='12+001:03:50:21.895 SUS,A,,,M,,,04,24';%%%41463
        %if ~isstr(line), break, end
        if ~ischar(line), break, end
        % C O R R E C T I O N  - Oxygen: 4 unknown characters after RVDAS time
        % tag - delete them.
        if strcmp(channel_id,'oxyg')
            if (day==5 & count_line==1034) | (day==361 & count_line==1) | ...
               (day==365 & count_line==7135)     
                line(21:23)='';
            else
                line(21:24)='';
            end
        elseif strcmp(channel_id,'mwx1'),
            mwx1_channel_id=line(21:23);
        end
        %if ~isempty(line)
        % C O R R E C T I O N  - DATE,TIME.
        line_cor_date=line(time_tag_chars);
        line_cor_date = strrep(line_cor_date,'+',char(9));
        line_cor_date = strrep(line_cor_date,':',char(9));
        % Concatenate corrected date/time with the string remaining
        % characters; do not use line ID characters.
        line_cor1=[line_cor_date line(length(time_tag_chars)+1:end)];
        if strcmp(channel_id,'pco2')
            % Find text tag and replace it with the tag code.
            if ~isempty(text_tag_list)
                for tn=1:size(text_tag_list,1)
                    text_tag=deblank(text_tag_list(tn,4:end));
                    text_tag_code=text_tag_list(tn,1:2);
                    ss=strfind(line_cor1,text_tag);
                    if ~isempty(ss)
                        line_cor1=strrep(line_cor1,text_tag,text_tag_code);
                        break;
                    end
                end
            end
        elseif strcmp(channel_id,'oxyg') | strcmp(channel_id,'knud')
        %elseif strcmp(channel_id,'oxyg')
            % Find text tag and replace it with the tag code.
            if ~isempty(text_tag_list)
                for tn=1:size(text_tag_list,1)
                    text_tag=deblank(text_tag_list(tn,:));
                    text_tag_code='';
                    ss=strfind(line_cor1,text_tag);
                    if ~isempty(ss)
                        line_cor1=strrep(line_cor1,text_tag,text_tag_code);
                    end
                end
            end
        elseif strcmp(channel_id,'mwx1')
            % Three string for mats in Meteorogy mwx1 data: the flags MET,
            % PUS and SUS in strings indicate the type.
            % I'll make 3 separate files - one for each channel.
            % C O R R E C T I O N S:
            % (1) All three Meteo channels:
            % - delete channel name from the strinng;
            % (2) SUS and PUS:
            % - delete the first character of the next quantity after
            % channel name - units identification (there is some code preceding "A" character
            % in the units identification - Matlab reads it as one
            % character);
            % - delete the last quantity - Check Sum
            % (I don't know how to recognaze all values, they include letters along
            % the numbers, for now I don't need this code);
            % - replace units character "M" with 1;
            % - replace units identification character A with 1.
            ss=strfind(line_cor1,mwx1_channel_id);
            if strcmp(mwx1_channel_id,'MET')
                % The number of columns to read data.
                n_par=15;
                line_cor1(ss:ss+3)='';
            elseif strcmp(mwx1_channel_id,'SUS') | strcmp(mwx1_channel_id,'PUS')
                % The number of columns to read data.
                n_par=12;
                %line_cor1=strrep(line_cor1,'\u0002A','1'); %!!! does not work
                % delete channel flag and the first character of the next
                % quantity - units identification.
                line_cor1(ss:ss+4)='';
                % Replace units identification character A with 1
                % (A becomes ss' character after channel flag removing).
                if strcmp(line_cor1(ss),'A'), line_cor1(ss)='1'; end
                % Remove last value - "Check Sum" (for now - do not know
                % how to recognaze all values, they include letters along
                % the numbers).
                ss_comma=strfind(line_cor1,',');
                line_cor1(ss_comma(end):end)='';
                % Replace units character "M" with 1.
                su=strfind(line_cor1,'M');% units
                if ~isempty(su)
                    line_cor1(su)='1';
                else
                    disp(['Line ' num2str(count_line)]);
                    return;
                end
            else
                return;
            end
        end % For if strcmp(channel_id,'pco2')
        if strcmp(comma_delimeter,'yes')
            % C O R R E C T I O N  - comma delimeter: NOT available data.
            line_cor2=line_cor1;
            rr_3c=strfind(line_cor2,',,,');
            if ~isempty(rr_3c)
                line_cor2=strrep(line_cor2,',,,',',nan,nan,');
            end
            rr_2c=strfind(line_cor2,',,');
            if ~isempty(rr_2c)
                line_cor2=strrep(line_cor2,',,',',nan,');
            end
            % C O R R E C T I O N  - ',' to TAB.
            line_cor2=strrep(line_cor2,',',char(9));
            line_cor1=line_cor2;
        end % For if strcmp(comma_delimeter,'yes')
        % Read line under format control.
        line_data = (sscanf(line_cor1,'%f'))';
        % CHECK for vectors length. If 'good' - MAKE MATRIX, if 'bad' display a message:
        if length(line_data)==n_par
            %@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
            %@@@@@@@@@ MERGE with NAVIGATION  @@@@@@@@@@@@@@@
            %@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
            % UW Point Decimal hour.
            h_dec_i=line_data(1,colHour_M) + ( line_data(1,colMin_M) + line_data(1,colSec_M)/60 )/60;
            % For the current UW point find corresponding time in
            % NAVIGATION - using UW Point Decimal hour and +-time interval.
            rr_nav=find(h_dec_N(:,1)>=h_dec_i-d_search & h_dec_N(:,1)<h_dec_i+d_search); 
            if isempty(rr_nav)
                % not found in primary.
                notFound_count=notFound_count+1;
                time_notFound=[time_notFound;line_data(1,[colHour_M colMin_M colSec_M])];
                % if not found: (1) increase time search interval.
                rr_nav_add=find(h_dec_N(:,1)>=h_dec_i-(d_search+d_search_add) & h_dec_N(:,1)<h_dec_i+(d_search+d_search_add) );
                if isempty(rr_nav_add)
                    % not found in primary using increased search interval
                    % - try to find in secondary source.
                    %$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
                    %---- C O R R E C T I O N - find from another NAVIGATION source-------
                    %$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
                    %$$$$$$ Try to find unavailable location $$$$$$$$
                    %$$$$$$  from other NAVIGATION source  $$$$$$$$$$
                    %$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
                    if day==361 | day==4 |  day==5 | day==12 % known days with missed data in primary.
                        % For the current UW point find corresponding time in
                        % NAVIGATION secondary - using UW Point Decimal hour and +-time interval.
                        rr_nav_2=find(h_dec_N_2(:,1)>=h_dec_i-d_search & h_dec_N_2(:,1)<h_dec_i+d_search);
                        if isempty(rr_nav_2)
                            notFound_count_2=notFound_count_2+1;
                            time_notFound_2=[time_notFound_2;line_data(1,[colHour_M colMin_M colSec_M])];
                            % if not found, increase time search interval.
                            rr_nav_add_2=find(h_dec_N_2(:,1)>=h_dec_i-(d_search+d_search_add) & h_dec_N_2(:,1)<h_dec_i+(d_search+d_search_add) );
                            if isempty(rr_nav_add_2)
                                % Not found in secondary Navigation source:
                                time_notFound_final_2=[time_notFound_final_2;line_data(1,[colHour_M colMin_M colSec_M])];
                                time_notFound_final_all_2=[time_notFound_final_all_2;line_data(1,[colDay_M colHour_M colMin_M colSec_M])];
                                time_notFound_final_all=[time_notFound_final_all;line_data(1,[colDay_M colHour_M colMin_M colSec_M])];
                                time_notFound_final=[time_notFound_final;line_data(1,[colHour_M colMin_M colSec_M])];
                                % use NaNs for location.
                                lat=NaN;
                                lon=NaN;
                            else
                                % use  secondary Navigation point with min time differece.
                                [mi,rmi_add_2]=min(abs(h_dec_N_2(rr_nav_add_2,1)-h_dec_i));
                                lat=d_nav_2(rr_nav_add_2(rmi_add_2),colLat_N_2);
                                lon=d_nav_2(rr_nav_add_2(rmi_add_2),colLon_N_2);
                                time_diff_day=[time_diff_day;mi];
                                clear mi rmi_add_2
                                LOCATION_from_secondary_NAVIGATION_all=[LOCATION_from_secondary_NAVIGATION_all;line_data(1,[colDay_M colHour_M colMin_M colSec_M])];
                            end
                        else
                            % use secondary Navigation point with min time differece.
                            [mi,rmi_2]=min(abs(h_dec_N_2(rr_nav_2,1)-h_dec_i));
                            lat=d_nav_2(rr_nav_2(rmi_2),colLat_N_2);
                            lon=d_nav_2(rr_nav_2(rmi_2),colLon_N_2);
                            time_diff_day=[time_diff_day;mi];
                            clear mi rmi_2;
                            LOCATION_from_secondary_NAVIGATION_all=[LOCATION_from_secondary_NAVIGATION_all;line_data(1,[colDay_M colHour_M colMin_M colSec_M])];
                        end
                        %$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
                        %---- C O R R E C T I O N - find from another NAVIGATION source END -------
                        %$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
                    else  % For if day==361 | day==4 |  day==5 | day==12
                        % Not found in primary and without search in secondary Navigation source:
                        time_notFound_final=[time_notFound_final;line_data(1,[colHour_M colMin_M colSec_M])];
                        time_notFound_final_all=[time_notFound_final_all;line_data(1,[colDay_M colHour_M colMin_M colSec_M])];
                        % use NaNs for location.
                        lat=NaN;
                        lon=NaN;
                    end % For if day==361 | day==4 |  day==5 | day==12
                else % For if isempty(rr_nav_add)
                    % use Navigation point with min time differece.
                    [mi,rmi_add]=min(abs(h_dec_N(rr_nav_add,1)-h_dec_i));
                    lat=d_nav(rr_nav_add(rmi_add),colLat_N);
                    lon=d_nav(rr_nav_add(rmi_add),colLon_N);
                    time_diff_day=[time_diff_day;mi];
                    clear mi rmi_add
                end % For if ~isempty(rr_nav_add)
            elseif length(rr_nav)>1 % For if isempty(rr_nav)
                % found in primary - more than one. I
                moreThanOne_count=moreThanOne_count+1;
                points_moreThanOne=[points_moreThanOne;length(rr_nav)];
                % use Navigation point with min time differece.
                [mi,rmi]=min(abs(h_dec_N(rr_nav,1)-h_dec_i));
                lat=d_nav(rr_nav(rmi),colLat_N);
                lon=d_nav(rr_nav(rmi),colLon_N);
                time_diff_day=[time_diff_day;mi];
                clear mi rmi
                %%%DDD=[DDD;line_data(1,[colHour_M colMin_M colSec_M]) lat lon d_nav(rr_nav(rmi),[colDay_N colHour_N colMin_M colSec_N]) ];
                if length(rr_nav)>2
                    time_points_moreThanTwo=[time_points_moreThanTwo;line_data(1,[colDay_M colHour_M colMin_M colSec_M])];
                end
            else % For if isempty(rr_nav)
                % found in primary - one point.
                lat=d_nav(rr_nav,colLat_N);
                lon=d_nav(rr_nav,colLon_N);
                time_diff_day=[time_diff_day;abs(h_dec_N(rr_nav,1)-h_dec_i)];
            end
            line_data =[line_data(1,1:5) lat lon line_data(1,6:end)];
            %d_uw_merged=[d_uw_merged;d_uw(ii,1:5) lat lon d_uw(ii,6:end)];
            %end % For for ii=1:size(d_uw,1)
            %@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
            %@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
            if strcmp(channel_id,'mwx1')
                p=['data_' mwx1_channel_id '=[data_' mwx1_channel_id ';line_data];'];
                eval(p);
            else
                data = [data;line_data];
            end
        else % For if length(line_data)==n_par
            disp(['Character (not number) is found in a line ' num2str(count_line) ':']);
            disp(line);
            disp('This part of line is read sucessfully:');
            disp(line_data);
            bad_line=count_line
            return;
        end  % For if length(line_data)==n_par
        clear line line_cor1 line_cor2 line_data lat lon rr_nav rr_nav_add h_dec_i rr_nav_2 rr_nav_add_2
    end  % For while 1
    % Close file.
    fclose(pfid);
    % !!!!
    %@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    % CHECK time difference between UW and Navigation.
    %@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    TIME_diff_UW_NAV_max_in_seconds=[TIME_diff_UW_NAV_max_in_seconds;day size(time_diff_day,1) max(time_diff_day)*3600];
    clear time_diff_day
    %@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    % DISPLAY values CHECKED earlier.
    %@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    disp(['Day # ' num2str(day) ':']);
    notFound_notFoundFinal_moreThanOne=[ notFound_count size(time_notFound_final,1) moreThanOne_count];
    disp(['notFound_notFoundFinal_moreThanOne = [' num2str(notFound_notFoundFinal_moreThanOne)  ']']);
    %total_uwMerged_notFound_notFoundFinal_moreThanOne=[size(d_uw,1) size(d_uw_merged,1) notFound_count size(time_notFound_final,1) moreThanOne_count]
    if ~isempty(points_moreThanOne)
        points_moreThanOne_2=length(find(points_moreThanOne(:,1)==2));
        points_moreThanOne_3_or_more=length(find(points_moreThanOne(:,1)>=3));
        disp(strvcat(['points_moreThanOne_2 = ' num2str(points_moreThanOne_2)],['points_moreThanOne_3_or_more = ' num2str(points_moreThanOne_3_or_more)]))
    end
    %*******************
    % Save data as a matfile.
    %*******************
    if strcmp(optionSave,'yes')
        if strcmp(channel_id,'mwx1')
            for nn=1:3
                fname_out_part_2=mwx1_channels(nn,:);
                fname_out=[fname_out_part '_' fname_out_part_2 '_' fname_ext];
                p=[fname_out '= data_' fname_out_part_2 ';'];
                eval(p);
                p=['f_size=size(data_' fname_out_part_2 ');'];
                eval(p);
                p=['save ' fname_out ' ' fname_out ';'];
                eval(p);
                p=['! mv ' fname_out '.' fname_out_ext ' ' path_name_out ';'];
                eval(p);
                %disp( strvcat(['File has been SAVED, filename: ' fname_out '.mat, size ' num2str(size(fname_out))],...
                disp( strvcat(blanks(1),['File has been SAVED, filename: ' fname_out '.mat, size ' num2str(f_size)],...
                    ['Location: ' path_name_out]) );
                p=['dd=data_' fname_out_part_2 ';'];
                eval(p);
                % CHECK are Year/day the same for both UW and Navigation.
                if mean(dd(:,colYear_M))==mean(d_nav(:,colYear_N)) & mean(dd(:,colYear_M))==year & ...
                        mean(dd(:,colDay_M))==mean(d_nav(:,colDay_N)) & mean(dd(:,colDay_M))==day
                    %%%disp(['Day # ' num2str(day) ' UW and Navigation Year/Day check for identity - identical']);
                else
                    not_idential=[not_idential; year day];
                    disp(['Data from the Day # ' num2str(day) ': UW and Navigation Year/Day are different']);
                    return;
                end
            end
        else
            fname_out=[fname_out_part '_' fname_ext];
            p=[fname_out '= data;'];
            eval(p);
            p=['save ' fname_out ' ' fname_out ';'];
            eval(p);
            p=['! mv ' fname_out '.' fname_out_ext ' ' path_name_out ';'];
            eval(p);
            disp( strvcat(blanks(1),['File has been SAVED, filename: ' fname_out '.mat, size ' num2str(size(data))],...
                ['Location: ' path_name_out]) );
            % Check the year.
            if mean(data(:,colYear_M))==mean(d_nav(:,colYear_N)) & mean(data(:,colYear_M))==year & ...
                    mean(data(:,colDay_M))==mean(d_nav(:,colDay_N)) & mean(data(:,colDay_M))==day
                %%%disp(['Day # ' num2str(day) ' UW and Navigation Year/Day check for identity - identical']);
            else
                not_idential=[not_idential; year day];
                disp(['Data from the Day # ' num2str(day) ': UW and Navigation Year/Day are different']);
                return;
            end
        end
    else
        if strcmp(channel_id,'mwx1')
            for nn=1:2
                fname_out_part_2=mwx1_channels(nn,:);
                p=['f_size=size(data_' fname_out_part_2 ');'];
                eval(p);
                disp( ['OUTPUT File NOT SAVED, OUTPUT matrix: data_' fname_out_part_2 ', size ' num2str(f_size)] );
                p=['dd=data_' fname_out_part_2 ';'];
                eval(p);
                if mean(dd(:,colYear_M))==mean(d_nav(:,colYear_N)) & mean(dd(:,colYear_M))==year & ...
                        mean(dd(:,colDay_M))==mean(d_nav(:,colDay_N)) & mean(dd(:,colDay_M))==day
                    %%%disp(['Day # ' num2str(day) ' UW and Navigation Year/Day check for identity - identical']);
                else
                    not_idential=[not_idential; year day];
                    disp(['Data from the Day # ' num2str(day) ': UW and Navigation Year/Day are different']);
                    return;
                end
            end
        else
            %   disp([monName ' ' num2str(dayNum) ', filename: ' fname]);
            disp( ['OUTPUT File NOT SAVED, OUTPUT matrix: data, size ' num2str(size(data))] );
            if mean(data(:,colYear_M))==mean(d_nav(:,colYear_N)) & mean(data(:,colYear_M))==year & ...
                    mean(data(:,colDay_M))==mean(d_nav(:,colDay_N)) & mean(data(:,colDay_M))==day
                %%%disp(['Day # ' num2str(day) ' UW and Navigation Year/Day check for identity - identical']);
            else
                not_idential=[not_idential; year day];
                disp(['Data from the Day # ' num2str(day) ': UW and Navigation Year/Day are different']);
                return;
            end
        end
    end
    %clear data;
    clear d_nav d_nav_2  data_MET data_SUS data_PUS h_dec_N h_dec_N_2;
end % for day=day_list
%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
% DISPLAY values CHECKED earlier.
%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
% (1) not found in PRIMARY and SECONDARY NAVIGATION.
if ~isempty(time_notFound_final_all)
    disp(strvcat(['W A R N I N G: there are ' num2str(size(time_notFound_final_all,1)) ' points not found in NAVIGATION'],...
        'NaNs used for location, see variable "time_notFound_final_all"'));
end
% (2) not found in PRIMARY but found in SECONDARY NAVIGATION.
if ~isempty(LOCATION_from_secondary_NAVIGATION_all)
    disp(strvcat(blanks(1),['NOTE: ' num2str(size(LOCATION_from_secondary_NAVIGATION_all,1)) ' points have been taken from SECONDARY NAVIGATION source (PCOD/GGA),'],...
        'they are not available in PRIMARY NAVIGATION (seap/GGA); see:  LOCATION_from_secondary_NAVIGATION_all'));
end
% (3) max difference between each point time in UW and time found in
% NAVIGATION.
disp(strvcat(blanks(1),['Max difference in seconds abs(Time_UW-Time_Nav) = ' num2str(max(TIME_diff_UW_NAV_max_in_seconds(:,3))) ', variable: TIME_diff_UW_NAV_max_in_seconds']));
% (4) day, year are not identical in UW and NAVIGATION files
% (not used; now I use return if not identical).
if ~isempty(not_idential)
    disp(strvcat(['W A R N I N G: there are ' num2str(size(not_idential,1)) ' points (variable "not_idential") - not identical Year/Day in UW/NAVIGATION']));
end
% (4) Estimated time of computing.
estimated_time_minutes=etime(clock,t0)/60

