% TRACE GPS issu de SeaClear
% Récupération des données des jours précédents dont les fichiers sont dans les répertoires
% Calcul automatique des échelles des cartes
% Picheral 2010/02

disp('---------------- START ---------------------');
close all;
clear all;
%% Repertoires
track_ok = 0;
while track_ok == 0;
    track_dir = uigetdir('Select Track file directory');
    % Existence de fichiers track
    track_list = dir([track_dir, '\*.txt']);
    if isempty(track_list)
        disp(['No track file in ',track_dir]);
    else
        track_ok = 1;
    end
end
disp([track_dir, ' contains ' num2str(size(track_list,1)),' track files.']);
disp(['Folder ',track_dir,' accepted.']);
% Nom fichier
filename = [track_dir,'\tara_track_odv.txt'];
folder = track_dir;

%% OPTIONS
recoverydata = 'y';
recoveryaxes = 'n';
if strcmp(recoverydata,'y');
    recoveryaxes = input('Use auto axis ? (y/n) ','s');
    if isempty(recoveryaxes);        recoveryaxes = 'y';    end
end
map = input('Draw map ? (y/n) ','s');
if isempty(map);        map = 'y';    end



datestart = input('Enter starting date YYYYMMDD. Press Enter for all dates. ');
dateend = input('Enter ending date YYYYMMDD. Press Enter for today. ');
if isempty(datestart);        datestart = 19000101;     end
if isempty(dateend);        dateend = 25000101;         end


colortype = input('Change color scale to grey ? (n/y) ','s');
if isempty(colortype);        colortype = 'n';    end
colorrange = 'Jet';
if strcmp(colortype,'y'); colorrange = 'Gray';  end
coastline = input('Include coastline in map ? (y/n) ','s');
if isempty(coastline);    coastline = 'y';    end
bathym = input('Include bathymetry in map ? (y/n) ','s');
if isempty(bathym);    bathym = 'y';    end

disp('---------------------------------------------------');
if strcmp(recoveryaxes,'n');
    disp('Keep waiting to fill information after recovery! ');
    disp('---------------------------------------------------');
end
%% FICHIER pour ODV
fid_track=fopen(filename,'w');
%+++++++++++++++++++++++ ENTETE +++++++++++++++++++++++++++++++++++++++++++++++
fprintf(fid_track,'%s\n','//<Creator>marc.picheral@obs-vlfr.fr</Creator>');
s = datestr(now,31);
s(11) = 'T';
fprintf(fid_track,'%s\n',strcat('//<CreateTime>',s,'</CreateTime>'));
fprintf(fid_track,'%s\n',strcat('//<Source>',filename(1:end-4),'</Source>'));
liste=(dir(filename));
s = datestr(liste(1).date,31);
s(11) = 'T';
fprintf(fid_track,'%s\n',strcat('//<SourceLastModified>',s,'</SourceLastModified>'));
fprintf(fid_track,'%s\n','//<DataField>Ocean</DataField>');
fprintf(fid_track,'%s\n','//<DataType>Profiles</DataType>');
data1='CTD data from Tara Oceans project.';
fprintf(fid_track,'%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_track,'%s\n',strcat('//<Owner1>',name3,'</Owner1>'));

%+++++++++++++++++++++++ Column Labels ++++++++++++++++++++++++++++++++++++++++++++++++++
fprintf(fid_track,'%s','Cruise:METAVAR:TEXT:20;Station:METAVAR:TEXT:20;yyyy-mm-ddThh:mm:METAVAR:TEXT:40;Latitude [degrees_north]:METAVAR:DOUBLE;Longitude [degrees_east]:METAVAR:DOUBLE;scan');



%% affichage donnees precedentes
datalist = [];
dataindex = [];
station = 1;
if strcmp(recoverydata,'y');
    deb = 3;
    listf = dir([folder,'\20*.txt']);
    for k = deb :size(listf,1);
        if isempty(findstr(listf(k).name,'.txt'))==0 &&  listf(k).bytes >100 ;
            % ------ Dans l'intervale de dates -----------------------
            if str2num(listf(k).name(1:8)) >= datestart && str2num(listf(k).name(1:8)) <= dateend;
                filenametext = [folder '\' listf(k).name];
                fid = fopen(filenametext,'r');
                disp(['Processing ' filenametext]);
                aa=1;
                rawc = [];
                while ~feof(fid)
                    tline = fgetl(fid);
                    rawc = [rawc; {tline}];
                    aa=aa+1;
                end
                for h=2:10:aa-1;
                    textdata = char(rawc(h,1:end));
                    % conversion des positions pour tracé sur la carte
                    latt = [];
                    longg = [];
                    %   textdata = '30/11/2009,00:31:46, 34.89707,28.70645, 8.1,0.5';
                    [date,data] = strtok(textdata,',');
                    [time,data] = strtok(data,',');
                    [latitude,data] = strtok(data,',');
                    [longitude,data] = strtok(data,',');
                    latitudetxt = str2num(latitude);
                    longitudetxt = str2num(longitude);
                    dataindex = [latitudetxt longitudetxt];
                    datalist = [datalist;dataindex];
                    % Ecriture dans fichier global
                    % Cruise
                    fprintf(fid_track,'%s','tara_oceans;');
                    % Station index
                    station = station+1;
                    fprintf(fid_track,'%s',strcat(num2str(station),';'));
                    % Date heure
                    sd = [date(7:10),'-',date(4:5),'-',date(1:2),'T',time];
                    fprintf(fid_track,'%s',strcat(sd,';'));
                    % Latitude
                    latitude = str2num(latitude);
                    latitude = num2str(latitude);
                    fprintf(fid_track,'%s',strcat(latitude),';');
                    % Longitude
                    longitude = str2num(longitude);
                    longitude = num2str(longitude);
                    fprintf(fid_track,'%s',strcat(longitude,';'));
                    % scan
                    fprintf(fid_track,'%s\n','1');
                 end
                fclose(fid);
            end
        end
    end
end



% Fermeture fichier global
fclose(fid_track);

%% CARTE
if strcmp(map,'y');
    % Echelles automatiques
    if strcmp(recoverydata,'y');
        latmini = floor(min(datalist(:,1)))-1;
        latmaxi = ceil(max(datalist(:,1)))+1;
        LATi = [latmini latmaxi];
        longmini = floor(min(datalist(:,2)))-1;
        longmaxi = ceil(max(datalist(:,2)))+1;
        LONg = [longmini longmaxi];
    else
        LATi = [0 2];
        LONg = [0 2];
    end
    y = double(LATi);
    x = double(LONg);
    sondes=[-5000 -4000 -3000 -2500 -2000 -1500 -1000 -500 -250 -125];
    disp('---------------------------------------------------');
    if strcmp(recoverydata,'y');
        %disp('ALL suggested ranges computed from recovered data.');
        disp(['Last position = ',num2str(dataindex(1)), '   ', num2str(dataindex(2))]);
    end
    if strcmp(recoveryaxes , 'n');
        y=input(['LATITUDE range  [' num2str(LONg(1)) ' ' num2str(LONg(2)) '] ']);
        x=input(['LONGITUDE range [' num2str(LATi(1)) ' ' num2str(LATi(2)) '] ']);
        if isempty(y);    y = double(LATi);end
        if isempty(x);    x = double(LONg);end
        sondes = input('Depth scale [-5000 -4000 -3000 -2500 -2000 -1500 -1000 -500] ?');
        if isempty(sondes);    sondes=[-5000 -4000 -3000 -2500 -2000 -1500 -1000 -500];end
    end
    %% Re lecture
    m_proj('Mercator','longitudes',x,'latitudes',y);
    for h=1:size(datalist,1);
        % conversion des positions pour tracé sur la carte
        latt = datalist(h,1);
        longg = datalist(h,2);
        %% Conversion des positions
        [xx yy] = m_ll2xy(longg,latt);
        datalist(h,3) = xx(1);
        datalist(h,4) = yy(1);
        %   disp([num2str(Temp),'  ',num2str(Sal),'  ',num2str(latt(1)),'  ',num2str(longg(1)),'  ',num2str(xx(1)),'  ',num2str(yy(1))]);
    end
    close
    
    
    disp('MAP being processed  : wait !');
    disp('---------------------------------------------------');
    %% trace de la carte
    scrsz = get(0,'ScreenSize');
    S=figure('numbertitle','off','name','TARA TRACK','Position',[10 110+(scrsz(4)/4) scrsz(3)/2.2 scrsz(4)/2]);
    ax=axes('NextPlot','add');
    set(gcf,'color','white');
    m_proj('Mercator','longitudes',x,'latitudes',y);
    if strcmp(coastline,'y');     m_gshhs_l('patch',[.7 .7 .7],'edgecolor','k','parent',ax); end
    set(gca,'color','none');
    m_grid('box','fancy','parent',ax);
    set(gca,'color','white');
    if strcmp(bathym,'y');      m_tbase_cor('contour',sondes);    end
    xlabel(['GPS Seaclear track'],'fontsize',13);
    % ylabel('latitude','fontsize',13);
    colormap(colorrange)
    %   colorbar;
    figure(S);
    if strcmp(recoverydata,'y');
        scatter(datalist(:,3) ,datalist(:,4),15,'r','filled');
    end
end
%% ---------- Calcul distance parcourue -------------------
disp('---------------------------------------------------');
dist = 0;
for s = 1:size(datalist,1)-1;
    d = m_lldist(datalist(s:s+1,2),datalist(s:s+1,1))/1852;
    dist = dist+d;
end
dist = floor(dist);
disp(['Total distance = ',num2str(dist),' nautical miles.']);
disp('---------------------------------------------------');
disp('Normal end !');
disp('---------------------------------------------------');
