% Traitement données CTD de OUTPACE
% Chargement fichiers btl et creation collection ODV
% Picheral 2015/03

clear all
close all
process_odv = 'y';

warning off MATLAB:divideByZero
groupe = 1;

disp('------------------- CTD data BOTTLE process tools ------------------------');
%% Choix du projet
btl_ok = 0;
disp('---------------------------------------------------------------------');
disp('Select CTD ROOT directory');
disp('---------------------------------------------------------------------');
while btl_ok == 0;
    btl_dir = uigetdir('Select CTD ROOT directory');
    % Existence de fichiers btl
    btl_dir = [btl_dir,'\final_cnv'];
    btl_list = dir([btl_dir, '\*.btl']);
    if isempty(btl_list)
        disp(['No btl file in ',btl_dir]);
    else
        btl_ok = 1;
    end
end
disp([btl_dir, ' contains ' num2str(size(btl_list,1)),' btl files.']);
disp(['Folder ',btl_dir,' accepted.']);
% Nom fichier
filename = [btl_dir,'\OUTPACE_ctd_classik_bottle_odv.txt'];
maj = 'l';
% if exist(filename) == 2;
%     disp([filename ' exists in ' btl_dir]);
%     maj = input('Add new bottle file only or load all files ? (a/l) ','s');
%     if isempty(maj); maj = 'a';end
% end

disp('---------------------------------------------------------------------');
% Creation de la base
base = [];
% Boucle sur les fichiers btl
for fichier = 1:size(btl_list,1);
    btl_file = btl_list(fichier).name;
    base(fichier).ctdrosette = btl_file(1:end-4);
    disp(['Loading ',btl_file]);
    [data] = btl2mat_outpace_nmea(btl_dir,btl_file);
    
    base(fichier).ctdrosettedata.names = data.names;
    base(fichier).ctdrosettedata.ctdrosette= data.filename;
    base(fichier).ctdrosettedata.data= data.data;
    base(fichier).ctdrosettedata.datenum = data.datenum;  
    base(fichier).ctdrosettedata.time = data.time;  
    base(fichier).ctdrosettedata.latitude = data.latitude;
    base(fichier).ctdrosettedata.longitude = data.longitude;
    disp('----------------------------------------------------------------------')
    % -------------- Correction cast 163 (sans PAR ni UVP) ---------------------------
    if strncmp(base(fichier).ctdrosette , 'out_c_163',9);
        % ----- Liste des noms ------------------
        base(fichier).ctdrosettedata.names = base(fichier-1).ctdrosettedata.names;
        % ----- Ajout de colonnes NaN pour PAR et CPAR ----------------
        aa = ones(size(data.data,1),1)*NaN;
        base(fichier).ctdrosettedata.data= [data.data(:,1:15) aa aa aa data.data(:,17:end)];
        disp('out_c_163 corrected');
    end   
end

% ----------- "Retournement" N° bouteilles TMC ----------------------------
if strncmp(btl_dir,'D:\grougier\OutPace\Traitement_CTD\Batch_Marc_Picheral\CTD_TMR\',28);
    for i = 2:7 %   numel(base);
        aa = find(strcmp(base(i).ctdrosettedata.names,'Bottle'));
        base(i).ctdrosettedata.data(:,aa) = 25-base(i).ctdrosettedata.data(:,aa);
    end
end
    
%% Paramètres "fixes"
cruise = 'OUTPACE';

disp('-------------- Data processed and loaded into base -------------------');
disp('----------------------------------------------------------------------')

%% Création archive ODV
if (strcmp(process_odv,'y'));
    disp('-------------------- START ODV PROCESS ---------------------');
        
    %% CTD
    % Test existence fichier
    
    
    if strcmp(maj,'l');      
        fid=fopen(filename,'w');
        %+++++++++++++++++++++++ ENTETE +++++++++++++++++++++++++++++++++++++++++++++++
        fprintf(fid,'%s\n','//<Creator>marc.picheral@obs-vlfr.fr</Creator>');
        s = datestr(now,31);
        s(11) = 'T';
        fprintf(fid,'%s\n',strcat('//<CreateTime>',s,'</CreateTime>'));
        fprintf(fid,'%s\n',strcat('//<Source>',filename(1:end-4),'</Source>'));
        liste=(dir(filename));
        s = datestr(liste(1).date,31);
        s(11) = 'T';
        fprintf(fid,'%s\n',strcat('//<SourceLastModified>',s,'</SourceLastModified>'));
        fprintf(fid,'%s\n','//<DataField>Ocean</DataField>');
        fprintf(fid,'%s\n','//<DataType>Profiles</DataType>');
        data1='CTD data from OUTPACE project.';
        fprintf(fid,'%s\n',strcat('//<Method>',data1,'</Method>'));
        name3 = 'Marc.picheral[at]obs-vlfr.fr http://www.obs-vlfr.fr/LOV/ZooPart/Portal/ Laboratoire d''Oceanographie de Villefranche  B.P. 28 Villefranche-Sur-Mer France +33 (0)4 93 76 38 08 +33 (0)4 93 76 38 34 http://www.obs-vlfr.fr/LOV/ZooPart/UVP/';
        fprintf(fid,'%s\n',strcat('//<Owner1>',name3,'</Owner1>'));
        
        %+++++++++++++++++++++++ Column Labels ++++++++++++++++++++++++++++++++++++++++++++++++++
        fprintf(fid,'%s','Cruise:METAVAR:TEXT:20;Station:METAVAR:TEXT:20;yyyy-mm-dd hh:mm;Latitude [degrees_north]:METAVAR:DOUBLE;Longitude [degrees_east]:METAVAR:DOUBLE;Zm [m]:DOUBLE;');
        
        %% CTD data
        
        aa = find(strcmp(base(1).ctdrosettedata.names,'PrDM'));
        ctdnb = size(base(1).ctdrosettedata.names,1);
        for k=1:size(base(1).ctdrosettedata.names,1)-1;
            if k ~= aa 
                name = base(1).ctdrosettedata.names(k,:);
                fprintf(fid,'%s',strcat(char(name),';'));
            end
        end
        k = size(base(1).ctdrosettedata.names,1);
        name = base(1).ctdrosettedata.names(k,:);
        fprintf(fid,'%s\n',char(name));
        fclose(fid);
    end
    
    %% ++++++++++++++++++ METADATA et DATA ++++++++++++++++
    for i=1:size(base,2);
        fid=fopen(filename,'a');
        [a,b]=size(base(i).ctdrosettedata.data);
        % -------- METADATA ------------
        for h=1:a
            % Cruise; Station name ; Histfile;UVPtype;CTDrosette;
            %   disp(char(base(i).ctdrosettedata.station));
            fprintf(fid,'%s',strcat(cruise,';',char(base(i).ctdrosette),';'));
            % Date ISO8601
            s = base(i).ctdrosettedata.datenum;
%           s = datestr(data.datenum,31); 
            s = datestr(s,31);  %% correction 28/07/2015 Gilles 
            sd = s(1:end-3);
            fprintf(fid,'%s',strcat(sd,';'));
            disp([char(base(i).ctdrosette),' ',sd])
            % Latitude
            fprintf(fid,'%s',strcat(num2str(base(i).ctdrosettedata.latitude)),';');
            % Longitude
            fprintf(fid,'%s',strcat(num2str(base(i).ctdrosettedata.longitude)),';');
            
            % --------- Pression pour ODV ----------------
            fprintf(fid,'%f',base(i).ctdrosettedata.data(h,aa));
            fprintf(fid,'%s',';');
            
            %% CTD data
            for k=1:size(base(1).ctdrosettedata.names,1)-1;
                if k ~= aa 
                    fprintf(fid,'%f',base(i).ctdrosettedata.data(h,k));
                    fprintf(fid,'%s',';');
                end
            end
            k = size(base(1).ctdrosettedata.names,1);
            fprintf(fid,'%f',base(i).ctdrosettedata.data(h,k));
            fprintf(fid,'%s\n','');
        end
        fclose(fid);
        disp([char(base(i).ctdrosette), ' processed']);
    end
    disp('-------------------- END CTD ---------------------');
end



