% acquisition tsg45 - sbe38 - gps
% decodage et enregistrement dans un fichier horaire

disp('---------- start ---------------------');
warning off matlab:serial:fscanf:unsuccessfulread;
close all;
clear all;

%% cartes
scrsz = get(0,'ScreenSize');

x = [7 9];
y = [-32 -31];
xcor=input('longitudes xmin, xmax [0 15] ');
ycor=input('latitudes ymin, ymax [-35 -20] ');
if isfinite(xcor)
    x=xcor;
    %disp(['limite ouest en longitude : ', num2str(x(1)),'   limite est en longitude : ', num2str(x(2))])
    xcor=[];
end
if isfinite(ycor)
    y=ycor;
    %disp(['limite sud en latitude    : ', num2str(y(1)),'   limite nord en latitude : ', num2str(y(2))])
    ycor=[];
end

sondes = input('isobathes [-5000 -4000 -3000 -2500 -2000 -1500 -1000 -500 -250 -125] par défaut ?');
if isempty(sondes)
    sondes=[-5000 -4000 -3000 -2500 -2000 -1500 -1000 -500 -250 -125];
end
salinity = input('salinity range [34 36] ?');
if isempty(salinity)
    salinity = [34 39];
end
temperature = input('temperature range [15 20] ? ');
if isempty(temperature)
    temperature = [15 20];
end

%% recuperation donnees
recovery = input('recovery of previous data ? (y/n) ','s');
if isempty(recovery)
    recovery = 'y';
end
% duration = input('number of days to include (2 is default) ? ',);
% if isempty(recovery)
%     recovery = 2;
% end

realtime = input('add real time recording and display ? (y/n) ','s');
if isempty(realtime)
    realtime = 'y';
end
m_proj('mercator','longitudes',x,'latitudes',y);
[x,y]=m_ll2xy(x,y);
% Fermeture Figure 1
%close all;

%% trace de la carte salinity
s=figure('numbertitle','off','name','salinity','position',[10 20 scrsz(3)/4 scrsz(3)/4]);
set(gcf,'color','white');
ax=axes('NextPlot','add');
m_gshhs_f('patch',[.7 .7 .7],'edgecolor','k','parent',ax);
set(gca,'color','none')
m_grid('box','fancy','parent',ax)
set(gca,'color','white')
m_tbase_cor('contour',sondes);
xlabel(['SALINITY [range: ' num2str(salinity(1)) '-'  num2str(salinity(2))   ' PSU]'],'fontsize',13);
% ylabel('latitude','fontsize',13);
colormap('jet')
colorbar;

%% trace de la carte temperature
t=figure('numbertitle','off','name','temperature','position',[10 50+(scrsz(3)/4) scrsz(3)/4 scrsz(3)/4]);
ax=axes('nextplot','add');
set(gcf,'color','white');
m_gshhs_f('patch',[.7 .7 .7],'edgecolor','k','parent',ax);
set(gca,'color','none')
m_grid('box','fancy','parent',ax)
set(gca,'color','white')
m_tbase_cor('contour',sondes);
xlabel(['TEMPERATURE [range: ' num2str(temperature(1)) '-'  num2str(temperature(2))   ' °C]'],'fontsize',13);
%ylabel('latitude','fontsize',13);
colormap('jet')
colorbar;
disp('--------- end map preparation ---------------');

%% affichage donnees precedentes
if strcmp(recovery,'y');
    listf = dir('c:/tsg');
    for k = 3 :size(listf,1);
        if strcmp(listf(k).name(1:10),'tara_tsg_2');
            filename = ['c:/tsg/' listf(k).name];
            fid = fopen(filename);
            disp(['Processing ' filename]);
            a=1;
            rawc = [];
            while ~feof(fid)
                tline = fgetl(fid);
                rawc = [rawc; tline];
                a=a+1;
            end
            %% SALINITY
            for h=1:50:a-1;
                text = rawc(h,1:end);
                %% affichage sur la carte
                % conversion des positions pour tracé sur la carte
                latt = [];
                longg = [];
                %        text = 't1= 13.5307, c1= 4.13996, s= 34.9243, t2= 13.3240, lat=32 10.0412, s, lon=017 42.5347, e, hms=190256, dmy=070910';
                %                text = 't1= 15.8191, c1= 4.36371, s= 34.9209, t2= 15.7208, lat=31 09.4872 S, lon=007 48.0208 E, hms=000206, dmy=120910';
                latitude = [str2num(text(56:57))+ str2num(text(59:65))/60];
                nscardinal = text(67);
                if strcmp(nscardinal,'S')
                    latitude = latitude*-1;
                end
                longitude = [str2num(text(74:76))+ str2num(text(78:85))/60];
                ewcardinal = text(86);
                if strcmp(ewcardinal,'W')
                    longitude = longitude*-1;
                end
                % disp([num2str(latitude) '   ' num2str(longitude)]);
                % disp([num2str(latt(1,1)) '  ' num2str(longg(1,1))]);
                latt = [single(nearest(latitude*1000)/1000) single(nearest(latitude*1000)/1000)];
                longg =[single(nearest(longitude*1000)/1000) single(nearest(longitude*1000)/1000)];
                [lonr,latr]=m_ll2xy(longg,latt);
                figure(s);
                %   sal = abs(random('normal',35,1));
                sal = str2num(text(29:36));
                scatter(lonr(1,1),latr(1,1),30,(sal-salinity(1))*abs(sondes(1))/(salinity(2)-salinity(1)),'filled');
                hold on;
                
                %% temperature
                figure(t);
                %   temp = abs(random('normal',15,1));
                temp = str2num(text(42:49));
                scatter(lonr(1,1),latr(1,1),30,(temp-temperature(1))*abs(sondes(1))/(temperature(2)-temperature(1)),'filled');
                hold on;
                % disp([text '----' num2str(lonr(1)) '   ' num2str(latr(1))]);
                % disp([num2str(latitude) '  ' num2str(longitude) '   ' num2str(sal) '    ' num2str((sal-salinity(1))*abs(sondes(1))/(salinity(2)-salinity(1))) '      ' num2str(temp) '   ' num2str((temp-temperature(1))*abs(sondes(1))/(temperature(2)-temperature(1)))]);
            end
            
        end
    end
end
disp('-------------- End of recovery -------------');
%% TEMPS REEL
if strcmp(realtime,'y');
    
    %% create a serial port object for gps.
    disp('opening gps port. wait !');
    obj1 = instrfind('type', 'serial', 'port', 'com6', 'tag', '');
    % create the serial port object if it does not exist
    % otherwise use the object that was found.
    if isempty(obj1)
        obj1 = serial('com6');
    else
        fclose(obj1);
        obj1 = obj1(1);
    end
    % set the baudrate
    obj1.baudrate = 4800;
    % connect to instrument object, obj1.
    fopen(obj1);
    % jour du premier fichier
    jour0 = 0;
    time0 = 0;
    
    sal = 34;
    temp = 17;
    
    
    disp('gps port open');
    
    
    %% boucle infinie !
    for i=1:10000000
        
        %% lecture gps
        % we only want the strings with $gprmc…
        datagps = '';
        while isempty(strmatch('$gprmc',datagps))
            datagps = fscanf(obj1);
        end
        % si jour change, nouveau fichier
        [frame,data] = strtok(datagps,',');
        [time,data] = strtok(data,',');
        [letter,data] = strtok(data,',');
        [lat,data] = strtok(data,',');
        [nscardinal,data] = strtok(data,',');
        [long,data] = strtok(data,',');
        [ewcardinal,data] = strtok(data,',');
        [letter,data] = strtok(data,',');
        [letter,data] = strtok(data,',');
        [date,data] = strtok(data,',');
        
        %if str2num(date) ~= jour0;
        if str2num(time) > time0+1000
            % fermeture du fichier si ouvert
            fclose('all');
            % creation du fichier a partir de cette date et de l'heure courante
            filename = ['tsg_' time(1:6) '.txt'];
            fid=fopen(filename,'w');
            disp(filename);
            time0 = str2num(time);
            jour0 = str2num(date);
        end
        
        % acquisition interface box
        %   dataint = fscanf(obj2);
        dataint = datagps(1:10);
        
        % concatenation de date, time, latitude, longitude, t(38), t(45), c(45)
        text = ['lat=' num2str(lat(1:2)) ' ' num2str(lat(3:end)) ' ' nscardinal ', lon=',num2str(long(1:3)) ' ' num2str(long(4:end)) ', ' ewcardinal ', hms=' num2str(time(1:6)) ', dmy=' num2str(date) ];
        
        if str2num(time)/5 == ceil(str2num(time)/5)
            disp(text);
            % ecriture dans fichier
            fprintf(fid,'%s\n',text);
            
            
            %% affichage sur la carte
            % conversion des positions pour tracé sur la carte
            latt = [];
            longg = [];
            
            latitude = [str2num(lat(1:2))+ str2num(lat(3:end))/60];
            if strcmp(nscardinal,'s')
                latitude = latitude*-1;
            end
            longitude = [str2num(long(1:3))+ str2num(long(4:end))/60];
            if strcmp(ewcardinal,'w')
                longitude = longitude*-1;
            end
            % disp([num2str(latitude) '   ' num2str(longitude)]);
            latt = [single(nearest(latitude*1000)/1000) single(nearest(latitude*1000)/1000)];
            longg =[single(nearest(longitude*1000)/1000) single(nearest(longitude*1000)/1000)];
            % disp([num2str(latt(1,1)) '  ' num2str(longg(1,1))]);
            [lonr,latr]=m_ll2xy(longg,latt);
            %% salinity
            figure(s);
            %   sal = abs(random('normal',35,1));
            sal = sal+0.01;
            scatter(lonr(1,1),latr(1,1),50,(sal-salinity(1))*abs(sondes(1))/(salinity(2)-salinity(1)),'filled');
            hold on;
            
            %% temperature
            figure(t);
            %   temp = abs(random('normal',15,1));
            temp = temp+0.01;
            scatter(lonr(1,1),latr(1,1),50,(temp-temperature(1))*abs(sondes(1))/(temperature(2)-temperature(1)),'filled');
            hold on;
            disp(['sal= ',num2str((sal-salinity(1))*abs(sondes(1))/(salinity(2)-salinity(1))),'  temp= ',num2str((temp-temperature(1))*abs(sondes(1))/(temperature(2)-temperature(1)))]);
            
        end
    end
    
    
    %% free the serial ports
    
    close('all');
end
