% pioneer_ar29_read_ctd_headers.m

clear;

% ---- Save Option.
%saveOption='yes';
saveOption='no';
%

%************************
% CTD data PATH, file names.
%************************
%!!!!!!!!!!!!!!!!!!!!!!!!!!
% Change to your CTD data - stations ## and path
last_st=66;
no_sts_list=[12 18 20:28 45:55];
path_name='~/OOI_pioneer/p_11/leg_1/';
%!!!!!!!!!!!!!!!!!!!!!!!!!!
path_name_out=path_name;
fname_part_1='ar29';
fname_part_2='';
fname_ext='btl';
fname_pre='';
cr_id=[fname_part_1 fname_part_2];

%************************
% CTD list.
%************************
ctdList=1:last_st;
for st=no_sts_list
    rr=find(ctdList(:)==st);
    if ~isempty(rr)
        ctdList(rr)=[];
    end
end

%************************
% CTD info lines and characters from CTD Headers.
%************************
% Station #.
line_stNum=2;
        stationNumberCharacters = 26:28;
% Station date.
    line_date=10;
    stationDateCharacters = 24:43;
    % Latitude.
    line_lat=11;
    stationLatCharacters = 19:26;
    % Longitude.
    line_lon=12;
    stationLonCharacters = 20:28;
% Line to terminate reading headers.
headerLastLineNum=20;

% OUTPUT file name.
fname=['p_11_' cr_id '_ctd_list'];
ctd_list_ext_1='mat';
ctd_list_ext_2='txt';
% OUTPUT file variables.
variables_out='% Station#, year, month, day, hour, minute, second, latitude (degN), longitude (degW)';

%************************
% For each station.
%************************
ctdInfo=[];
for stNum = ctdList
    % Write input file names to string.
    if stNum < 10
        stNum_str=['00' num2str(stNum)];
    else
        stNum_str=['0' num2str(stNum)];
    end
    j = [fname_pre cr_id stNum_str '.' fname_ext];
    % Open file for reading.
    pfid = fopen([path_name j]);
    if pfid<0
        disp(['Station# ' stNum_str ' not found']);
        return;
    end
%************************
% For each line from the headers.
%************************
    for lineNum=1:headerLastLineNum
        % Read line from file header, keep new line character (fgets).
        line=fgets(pfid);
        if lineNum==line_stNum
            % (1) Station name.
            lineInfo = line(stationNumberCharacters);
            ctdNum = str2num(lineInfo);
            if isempty(ctdNum) | ctdNum~=stNum
                %if crNum==6 & leg==3 & stNum==6
                %    % do nothing, I know this exception
                %    ctdNum=stNum;
                %else
                    disp(['Station #' num2str(stNum) ': WRONG Station# in the Headers, line #' num2str(lineNum)]);
                    return;
                %end
            end
        elseif lineNum==line_date
            % (2) Date.
            lineInfo = line(stationDateCharacters);
            ctdMonName = lineInfo(1:3);
            ctdDay = lineInfo(5:6);
            ctdYear = lineInfo(8:11);
            if strcmp(ctdMonName,'Jan')
                ctdMon='1';
            elseif strcmp(ctdMonName,'Feb')
                ctdMon='2';
            elseif strcmp(ctdMonName,'Mar')
                ctdMon='3';
            elseif strcmp(ctdMonName,'Apr')
                ctdMon='4';
            elseif strcmp(ctdMonName,'May')
                ctdMon='5';
            elseif strcmp(ctdMonName,'Jun')
                ctdMon='6';
            elseif strcmp(ctdMonName,'Jul')
                ctdMon='7';
            elseif strcmp(ctdMonName,'Aug')
                ctdMon='8';
            elseif strcmp(ctdMonName,'Sep')
                ctdMon='9';
            elseif strcmp(ctdMonName,'Oct')
                ctdMon='10';
            elseif strcmp(ctdMonName,'Nov')
                ctdMon='11';
            elseif strcmp(ctdMonName,'Dec')
                ctdMon='12';
            else
                disp([ctdMonName ' ?']);
                return;
            end
            ctdDate = strcat(ctdMon,ctdDay,ctdYear);
            ctdDate = str2num(ctdDate);
            ctdYear_num=str2num(ctdYear);
            ctdMon_num=str2num(ctdMon);
            ctdDay_num=str2num(ctdDay);
            % (3) Time.
            ctdTime = lineInfo(13:20);
            ctdTime_num = str2num(strrep(ctdTime,':',char(9)));
        elseif lineNum==line_lat
            % (4) Latitude.
            lineInfo=line(stationLatCharacters);
            ctdLat_num = str2num(lineInfo);
            lat_deg = ctdLat_num(1);
            lat_min = ctdLat_num(2);
            ctdLat = lat_deg + lat_min/60;
        elseif lineNum==line_lon
            % (5) Longitude.
            lineInfo=line(stationLonCharacters);
            ctdLon_num = str2num(lineInfo);
            lon_deg = ctdLon_num(1);
            lon_min = ctdLon_num(2);
            ctdLon = lon_deg + lon_min/60;
        end
    end % For for lineNum=1:
    % Close open file.
    fclose(pfid);
    % Make a matrix with CTD Info.
    ctdInfo = [ctdInfo;ctdNum ctdYear_num ctdMon_num ctdDay_num ...
        ctdTime_num ctdLat ctdLon];
end % for i = 1:lastStation
%*******************
% Save a file.
%*******************
if strcmp(saveOption,'yes')
    %--------- (1) Save data matrix as ASCII tab delimited file with the first
    % commented line - headers.
    dlmwrite('TEMP.txt',ctdInfo,'delimiter','\t','precision',6);
    % Make text file - headers.
    pfid=fopen('headers.txt','w');
    fprintf(pfid,'%s\n',variables_out);
    fclose(pfid);
    % Concatenate 'Headers' file and 'Matrix' file.
    p=['! cat headers.txt TEMP.txt > ' fname '.' ctd_list_ext_2];
    eval(p);
    % Remove text files - headers and TEMP.
    ! rm headers.txt  TEMP.txt
    %--------- (2) Save as MATfile.
    p=[fname '=ctdInfo;'];
    eval(p);
    p=['save ' fname ' ' fname ';'];
    eval(p);
    %--------- (3) MOVE OUTPUT files to the CTD data location.
    %p=['! mv ' fname '.* ' path_name_out];
    %eval(p);
    %--------- (4) Display info:
    disp(strvcat(blanks(1),['OUTPUT FILE SAVED, filename: ' fname '.mat and .txt, size ' num2str(size(ctdInfo))],...
        'Variables name:',...
        variables_out,...
        ['Total stations: ' num2str(size(ctdInfo,1)) '; first station listed: ' num2str(min(ctdInfo(:,1))) ', last station listed: ' num2str(max(ctdInfo(:,1)))],...
        ['File location: ' path_name_out],...
        blanks(1)));
else
    %*******************
    % Display.
    %*******************
    disp(strvcat(blanks(1),'Output matrix - CTD stations list (FILE NOT SAVED).','OUTPUT matrix:',['name = ctdInfo, size = ' num2str(size(ctdInfo))],...
        'Variables name:',...
        variables_out,...
        ['Total stations: ' num2str(size(ctdInfo,1)) '; first station listed: ' num2str(min(ctdInfo(:,1))) ', last station listed: ' num2str(max(ctdInfo(:,1)))],...
        blanks(1)));
end % For if strcmp(saveOption,'yes')

