% Read_SOCATv2019_v2022()
%-------------------------------------------------------------------------%
% This is the routine to get the SOCAT v2019                              %
% to v2023  data into matlab.                                             %
% The data files are the SOCAT V2019 to V2023 global and regional zip or tsv %
% files which can be downloaded from the SOCAT Data Download              %
% page on www.socat.info.  It can also read the individual cruise files   %
% from Pangaea (http://doi.pangaea.de) as well as the ascii or csv        %
% files downloaded from the cruise viewer on the SOCAT website.           %
% Several files can be selected, all with the same extension.             %
% For allowed extensions, see the 'exts' variable.                        %
% It reads the file(s) until the column headers are found.                %
% Determines # of columns from # of headers.                              %
% Creates GUI to ask user which columns to import                         %
% If Lat or Lon are selected for import, it creates another GUI           %
%      to ask the user which geographical region to import                %      
% If cruise flags are present and selected for import,                    %
%          the GUI to select which flags to import will have that option. %      
% Likewise with data flags.                                               %
% Data is stored in variables named after (sometimes modified)            %
% column headers                                                          %
% For questions, contact:                                                 %
%       Denis Pierrot (Denis.Pierrot@noaa.gov)                            %
%   or  Peter Landschutzer (p.landschutzer@uea.ac.uk)                     %
%-------------------------------------------------------------------------%
clear all;close all;clearvars;
%dbstop at 135;
%--------------------------------------------------------------------------%
%  TO USER:                                                                % 
%  Data file(s) should prefarably be in same directory as this .m file     % 
%  but doesn't have to.                                                    %
%  User Input:                                                             %
%   (~line 40)    readnumlines = number of lines to read to find data header  %
%                                                                          %
%   (~line 100)   dflt(_info)    = column number initially selected        % 
%                           to be imported when interface is created       %     
%--------------------------------------------------------------------------%

global readnumlines ftype delim cruiseflags data_in data_info_in data_in_clean ;
global hdrs rcol hdrs0 rcol0 fstr_data fstr_info;
global bv ind2 ind3 ind4 ind5;
global statb plb cfb dfb gb hsc divb statcb
global hcoast hcb argout
global coastlon coastlat

plb=gobjects(4,1);cfb=gobjects(5,1);dfb=gobjects(3,1);

readnumlines=10000;
exts={'.txt';'.tab.tsv';'.tsv';'.csv';'.rtf'};
ftypestr={'data report';'Data Collection'};%1=regional files, 2=from LAS server
allexts='.txt; .tab.tsv; .tsv; .csv; .rtf';
cruiseflags={'A','B','C','D','E'};
axts='';for i=1 : size(exts,1),axts=[axts '*' exts{i} ';'];end

%----Gets mfile directory ----------------------------------------------------
if exist(mfilename,'file')==2
    projDir = strrep([mfilename('fullpath') '.m'],[filesep mfilename '.m'],'');
else
    projDir =pwd;
end
%--------------------------------------------------------------------------
mess=sprintf('%s:\n\n\t1) %s\n\n\t2) %s\n\n\t3) %s\n    %s\n\n\t4) %s\n%s','Data Users are requested:',...
    'To report problems by emailing ''submit@socat.info''...',...
    'To generously acknowledge the contribution of SOCAT investigators...',...
    'To inform  ''submit@socat.info''',' of publications in which SOCAT is used...',...
    'To cite SOCAT as detailed in its ''FAIR DATA USE STATEMENT''','     found at ''www.socat.info''');
mmm=msgbox(mess,'WARNING: Data Use Policy','Warn','modal');

th = findall(mmm, 'Type', 'Text');                   %get handle to text within msgbox
th.FontSize = 14;                                   %Change the font size
mmm.Position([3]) = mmm.Position([3]) *1.5;
mmm.Position([4]) = mmm.Position([4]) *1.1;

mmm.Resize = 'on';
uiwait(mmm);

%----Select files to be imported (only 1 kind at a time)-------------------
[fname,fpath] = uigetfile(axts,'Select Data File(s)',[projDir filesep],'MultiSelect','on');
if (fpath==0),return;end
if strcmp(fpath(end),filesep)>0,fpath=fpath(1:end-1);end

%--------------- Detects file type in files selected  -------------------
% 1 or more files selected
if ischar(fname), lname=1;fnamel{1}=fname; else, fnamel=fname;lname=length(fnamel);  fnamel=sort(fnamel);end
cond=0;

for fnum=1:lname
    ff(fnum)= fopen([fpath filesep fnamel{fnum}],'r');
    line1=textscan(ff(fnum),'%s',1,'delimiter','\n');
    if fnum==1%gets file type of 1st file
        for i=1:size(ftypestr,1)
            if ~isempty(regexpi(char(line1{1}),char(ftypestr{i}),'ONCE')), ftype=i;end
        end
    else
        for i=1:size(ftypestr,1)%checks file type is same as 1st file
            if (~isempty(regexpi(char(line1{1}),char(ftypestr{i}),'ONCE')) && ftype~= i)
                mmm=msgbox(sprintf('You have selected different types of files which cannot be processed together.\n Program terminated'),'Loading Error','modal');
                uiwait(mmm);
                return;
            end
        end
    end
end

% ************************************** txt or tsv files*****************************************************************
switch ftype
    case 1 %synthesis files (data reports)
        mots={'Expocode','fCO2rec_flag';'Expocode','Platform Name'};
        dflt_info=[1 2 3 4 14];
        dflt=[1 2 4 5 6 7 8 9 10 11 12 14 15 23 30 32];% Expocode QC_Flag version yr mon day hh mm ss lon lat sal SST GVCO2 fCO2rec fCO2rec_flag
        tcol=[1 2 3 4];%text columns for data part  (expocode, version, doi, QC_Flag)
        clean_with={'longitude','latitude','QC_flag','fCO2rec_flag'};
        fco2_hdr='fCO2rec';
    case 2 %Data Collection downloaded from LAS server on SOCAT.info
        dflt=[1 3 4 6 10 11 12 13 14 15 16 17 18 21 23 24 27 28 30];% EXPOCODE LATITUDE LONGITUDE QC_FLAG YEAR MONTH DAY HOUR MINUTE SECOND SAL TEMP TEMPERATURE_EQUI PRESSURE_ATM WOA_SSS PRESSURE_NCEP_SLP GVCO2 FCO2_RECOMMENDED WOCE_CO2_WATER
        tcol=[1 2 3 4];%text columns  (expocode, version, doi, QC_Flag)
        mots={'EXPOCODE','FCO2_RECOMMENDED'};
        clean_with={'longitude','latitude','qc_flag', 'woce_co2_water'};
        fco2_hdr='fco2_recommended';
end


for fnum=1:lname
    fs=dir([fpath filesep fnamel{fnum}]);
    fseek(ff(fnum),0,'bof');
    %--------------------------------------------------------------------------
    % get location of header line(s) and create format strings fstr_data and fstr_info
    %--------------------------------------------------------------------------
    
    if size(mots,1)>1
        isdata=0;
        get_header_col(ff,fnum,mots{2,1},mots{2,2},dflt_info,isdata);
        hdrline_info=argout{1};hdrline_info_end=argout{2};
        if size(argout,2)==3,fstr_info=argout{3};end
        if isempty(fstr_info), return;end
    end % end getting fmt string for dataset info
    
    isdata=1;
    get_header_col(ff,fnum,mots{1,1},mots{1,2},dflt,isdata);
    hdrline_data=argout{1};
    if size(argout,2)==2,fstr_data=argout{2};end
    

    if ~isempty(fstr_info)
        fseek(ff(fnum),0,'bof');
        %--------------------------------------------------------------------------
        % start reading the data info according to the format string 'fstr_info'
        %--------------------------------------------------------------------------
        %tic;

        data_info_in1=textscan(ff(fnum),fstr_info,hdrline_info,'delimiter',delim);
        data_info_in1=textscan(ff(fnum),fstr_info,hdrline_info_end-hdrline_info-2,'delimiter',delim);
        if fnum==1 , data_info_in=data_info_in1;ncol=size(data_info_in1,2);
        else, for j=1:size(data_info_in1,2),data_info_in{1,j}=cat(1,data_info_in{1,j},data_info_in1{1,j});end; end

        %toc

    end
    
    %--------------------------------------------------------------------------
    % start reading the data according to the format string 'fstr_data'
    %--------------------------------------------------------------------------
    %tic;
    
    fseek(ff(fnum),0,'bof');
    data_in1=textscan(ff(fnum),fstr_data,hdrline_data, 'delimiter',delim);
    data_in1=textscan(ff(fnum),fstr_data,'delimiter',delim);
    if ftype==1,ind=find(~cellfun('isempty',strfind((hdrs),'longitude')));
        if ~isempty(ind)
            A=str2num(char(data_in1{1,sum(bv(1:ind))})); A(A>180)=A(A>180)-360;
            data_in1{1,sum(bv(1:ind))}=cellstr(num2str(A));
        end
    end
    if fnum==1 , data_in=data_in1;ncol=size(data_in1,2);
    else, for j=1:size(data_in1,2),data_in{1,j}=cat(1,data_in{1,j},data_in1{1,j});end; end    
    
    fclose(ff(fnum));
    
    %toc
end
            
%--------------------------------------------------------------------------
% Puts each column read in a variable named after column header.
%--------------------------------------------------------------------------
%Cleans hdrs for use as variable name
hdrs=lower(hdrs);
hdrs=regexprep(hdrs,'\s\[\S*\]','');%gets rid of units
hdrs=regexprep(hdrs,'\s(\S*)','');%gets rid of what is in parentheses
hdrs=regexprep(hdrs,'[\s/\\]','_');%replace (spaces, / or \) by underscore
for i = rcol
    eval([hdrs{i} '=data_in{1,find(rcol==i)};']);
end

if ~isempty(fstr_info)
    hdrs0=regexprep(hdrs0,'\[(.*\]','_$1_'); %replaces brackets by underscore
    hdrs0=regexprep(hdrs0,'\((.*)\)','_$1_');%replaces parentheses by underscore
    hdrs0=regexprep(hdrs0,'[ /\\]+','_');%replace (spaces, / or \) by underscore
    for i = rcol0
        eval([hdrs0{i} '_info=data_info_in{1,find(rcol0==i)};']);
    end
end


%select_data_limits;
%--------------------------------------------------------------------------
% Create Interface to select data
%--------------------------------------------------------------------------


ind2=find(ismember(hdrs,lower(clean_with{1})));
ind3=find(ismember(hdrs,lower(clean_with{2})));
ind4=find(ismember(hdrs,lower(clean_with{3})));
ind5=find(ismember(hdrs,lower(clean_with{4})));
if isempty(ind5),ind5=find(~cellfun(@isempty,(regexp(hdrs,lower('Flag \[\#\]')))));end

%--------------------------------------------------------------------------
% plot data
%--------------------------------------------------------------------------
n=10;  %will plot 1/10th of the data (user can cange on UI)
for i=1:size(data_in,2)
   data_plot{i}=data_in{1,i}(1:n:end);
end
fig=figure('NumberTitle', 'off', 'Name', 'DATA SELECTION');dotsize=3;
if ~isempty(find(ismember(hdrs,lower(fco2_hdr))))
    ind=find(ismember(hdrs,lower(fco2_hdr)));
    plotv=str2num(char(data_plot{1,sum(bv(1:ind))}));  %replace fCO2rec by variable name to be plotted.
end
ind=find(ismember(hdrs,clean_with{1})); xv=str2num(char(data_plot{1,sum(bv(1:ind))}));
ind=find(ismember(hdrs,clean_with{2}));yv=str2num(char(data_plot{1,sum(bv(1:ind))}));
mx=max(plotv);    plotvc=plotv/mx;
hsc=scatter3(xv,yv,plotv,4,plotvc);
x1lim=get(gca,'XLim');
y1lim=get(gca,'YLim');
hold (gca,'on');

%Color Bar
colormap jet; hcb=colorbar; set(hcb,'location','eastoutside','yaxislocation','right');
yt=get(hcb,'YTick');ytl='';
for i=1:length(yt)
    ytl=strvcat(ytl,int2str(yt(i)*mx));
    set(hcb,'YTickLabel',ytl);
end

if isMATLABReleaseOlderThan('R2020a')
    load coast;coastlon=long;coastlat=lat;
else
    load coastlines;
end
map_height=mean(plotv); % average of plotted data
hcoast=plot3(coastlon,coastlat,zeros(size(coastlon,1),1)+map_height,'Parent',gca, 'Marker','none', 'MarkerSize',dotsize, 'MarkerEdgeColor','b', 'MarkerFaceColor','none','LineStyle','-');
set(gca,'XLim',x1lim,'YLim',y1lim);

%increase canvas
gcfpos0=get(gcf,'position');gcfpos1=gcfpos0;gcfpos1(4)=gcfpos0(4)*2;
set(gcf,'position',gcfpos1);
gcapos0=get(gca,'position');gcapos1=gcapos0;
gcapos1(4)=gcapos0(4)/2;set(gca,'position',gcapos1);
gcapos1(2)=gcapos0(2)+gcapos1(4);set(gca,'position',gcapos1);

statb=uicontrol ('Style','text','units','Normalized','position', [0.05 0.01 0.4 0.05],'String','Status','Tag','stat','backgroundcolor',get(gcf,'color'),'foregroundcolor','r');
okb=uicontrol ('Style','togglebutton','units','Normalized','position', [0.5 0.01 0.2 0.05],'String','DONE','Tag','ok','backgroundcolor',get(gcf,'color'));
ccb=uicontrol ('Style','togglebutton','units','Normalized','position', [0.75 0.01 0.2 0.05],'String','Cancel','Tag','cancel','backgroundcolor',get(gcf,'color'));
ind=find(ismember(hdrs,'Expocode'));
if ~isempty(ind)
    msg=sprintf('# Data Points: %i\n# cruises: %i',size(data_in{1,1},1),numel(unique(data_in{1,sum(bv(1:ind))})));
else
    msg=sprintf('# Data Points: %i',size(data_in{1,1},1));
end
statb.String = msg;
statb.FontSize=14;

height=0.42;
gb = uicontrol('Style','checkbox','FontSize', 14,'units','Normalized','Position',[0.72 height 0.2 0.03],'Tag','graph');
gb.String='Plot Data';
gb.Value=1;
gb.Callback={@graph_vis};
divb = uicontrol('Style','edit','FontSize', 14,'units','Normalized','Position',[0.6 height 0.1 0.03],'Tag','div');
divb.String='10';
divbl = uicontrol('Style','text','FontSize', 14,'units','Normalized','Position',[0.6 height+0.03 0.2 0.03],'Tag','divl');
divbl.String='Plot 1 point out of';
statcb=uicontrol ('Style','text','units','Normalized','position', [0.05 height 0.4 0.05],'String','Status','Tag','statc','backgroundcolor',get(gcf,'color'),'foregroundcolor','r');
ind=find(ismember(hdrs,'Expocode'));
if ~isempty(ind)
    msg=sprintf('# Points disp.: %i\n# cruises disp.: %i',size(data_plot{1,1},1),numel(unique(data_plot{1,sum(bv(1:ind))})));
else
    msg=sprintf('# Points disp: %i',size(data_plot{1,1},1));
end
statcb.String = msg;
statcb.FontSize=14;

height=0.3;
pbg = uibuttongroup(gcf,'units','Normalized','Position',[0.1 height 0.8 0.1],'Tag','pos_limits');
ctrln=4;bdv=[-180 180 -90 90];bdl=['Min Lon'; 'Max Lon'; 'Min Lat'; 'Max Lon'];
for i=1:ctrln
    plb(i)=uicontrol (pbg,'Style','edit','FontSize', 14,'units','Normalized','position', [0.05+(i-1)*0.21 0.1 0.2 0.6],'String',num2str(bdv(i)));
    pll(i)=uicontrol (pbg,'Style','text','FontSize', 14,'units','Normalized','position', [0.05+(i-1)*0.21,0.8,0.2,0.2],'String',bdl(i,:));
end

if exist('ind4','var')
    if bv(ind4)~=0  %if ind4 exists and has been selected
        height=0.2;
        fbg = uibuttongroup(gcf,'units','Normalized','Position',[0.1 height 0.8 0.1],'Tag','cruise_flags');
        ctrln=5;bdl=['A'; 'B'; 'C'; 'D'; 'E'];
        for i=1:ctrln
            cfb(i)=uicontrol (fbg,'Style','checkbox','FontSize', 14,'units','Normalized','position', [0.05+(i-1)*0.19 0.1 0.18 0.6],'String',bdl(i,:));
        end
        msg=sprintf('%s \n[%s @ %s]','Select Cruise Flags to Import','see the QC Cookbook', 'www.SOCAT.info - ''About SOCAT'' - ''Publications''');
        uicontrol (fbg,'Style','text','FontSize', 12,'units','Normalized','position', [0.0,0.6,1,0.4],'String',msg);
    end
end

if exist('ind5','var')
    if bv(ind5)~=0  %if ind5 exists and has been selected
        height=0.1;
        fbg = uibuttongroup(gcf,'units','Normalized','Position',[0.1 height 0.8 0.1],'Tag','data_flags');
        ctrln=3;bdl=['2'; '3'; '4'];
        for i=1:ctrln
            dfb(i)=uicontrol (fbg,'Style','checkbox','FontSize', 14,'units','Normalized','position', [0.05+(i-1)*0.31 0.1 0.3 0.6],'String',bdl(i,:));
        end
        uicontrol (fbg,'Style','text','FontSize', 14,'units','Normalized','position', [0.05,0.8,0.8,0.2],'String','Select Data WOCE Flags to Import');
    end 
end


for i=1:4
    plb(i).Callback={@plot_data};
end
if exist('ind4','var')
    if bv(ind4)~=0  %if ind4 exists and has been selected
        for i=1:5
            cfb(i).Value=1;
            cfb(i).Callback={@plot_data};
        end
    end 
end
if exist('ind5','var')
    if bv(ind5)~=0  %if ind5 exists and has been selected
        for i=1:3
            dfb(i).Value=1;
            dfb(i).Callback={@plot_data};
        end
    end
end
okb.Callback={@plot_data};
ccb.Callback={@plot_data};

uiwait(fig);


%--------------------------------------------------------------------------
% Finalize Data
%--------------------------------------------------------------------------

if isempty(data_in_clean),data_in_clean=data_in;end

if size(data_in_clean{1},1)==0
    mmm=msgbox(sprintf('No data within the criteria specified.\n\nTry again with different selections\n\n'),'modal');
    uiwait(mmm);

else
    for i = rcol
        eval([hdrs{i} '=data_in_clean{1,find(rcol==i)};']);
    end
    %--------------------------------------------------------------------------
    % Clean _info data in case selection above eliminated a cruise.
    %--------------------------------------------------------------------------
    if (exist('Expocode_info','Var') && exist('Expocode','Var'))
        for i=1:size(data_info_in,2)
            data_info_in{1,i}(~ismember(Expocode_info,Expocode))=[];
        end
        for i = rcol0
            eval([hdrs0{i} '_info=data_info_in{1,find(rcol0==i)};']);
        end
    end
end
%--------------------------------------------------------------------------
% clears unnecessary variables
%--------------------------------------------------------------------------



clear bdl bdv coastlat coastlon dotsize fbg fCO2rec fCO2rec_flag gcapos0 gcapos1 gcfpos0 gcfpos1
clear allexts  ans  axts  bv  ccb  cfb  cond  cruiseflags  ctrln    data_in1  
clear data_info_in1  delim  dfb  dflt  dflt_info  exts  ff  fig  fname  fnamel  
clear fnum  fpath  fs  fstr_data  fstr_info  ftype  ftypestr  gb  hcb  hcoast  hdrline  
clear hdrline0  hdrline1  hdrs  hdrs0  height  hsc  i  ind  ind2  ind3  ind4  ind5  i
clear sdata  line1  lname  map_height  mess  mmm   mots  msg  mx  ncol  okb  pbg  
clear plb  pll  plotv  plotvc  projDir  rcol  rcol0  readnumlines statb  tcol  th  
clear x1lim  xv yv  y1lim  yt  ytl isdata
clear fstr_data fstr_info hlin0 hline A argout data_plot divb divbl statcb
clear hdrline_info_end hdrline_data hdrline_info j n fco2_hdr fs





function  get_header_col(ff, fnum,mot1,mot2,dflt,isdata)
global readnumlines ftype delim colmax ;
global hdrs rcol hdrs0 rcol0;
global bv argout;

        argout=[];varg=1;
        fseek(ff(fnum),0,'bof');
        %--------------------------------------------------------------------------
        % searches for info header line
        %--------------------------------------------------------------------------

        hdrline=[];
        hdr_in=textscan(ff(fnum),'%s',readnumlines,'delimiter','\n');
        %hdr_in=readlines([fpath filesep fname]);
        hdr_in1 = strfind(hdr_in{1}, mot1); hdr_in2=strfind(hdr_in{1}, mot2);
        hdr_in1=~cellfun('isempty', hdr_in1);hdr_in2=~cellfun('isempty', hdr_in2);
        hdrline1=intersect(find(hdr_in1), find(hdr_in2));
        argout{varg}=hdrline1;varg=varg+1;

        if(isempty(hdrline1) | feof(ff(fnum))), h=msgbox(sprintf('%s%d%s\n\n%s\n\n%s','Could not find header line in the first ',readnumlines,' lines.','Increase the value of the ''readnumlines'' variable','at the beginning of the code and restart.'),'Error','Error','modal');uiwait(h);return;end

        if length(hdrline1)>1, h=msgbox(sprintf('%s\n%s\n','Found several possible header lines...','Check words to look for.'),'Error','Error');return;end
        if (hdrline1>0),fseek(ff(fnum),0,'bof');StartText=textscan(ff(fnum),'%s',hdrline1-1,'delimiter','\n');end
        if isdata==0
            if ftype==1
                hdrline2 = find(~cellfun('isempty',strfind(hdr_in{1},'Explanation of data columns:')));
                argout{varg}=hdrline2;varg=varg+1;
            end
        end
        tline = fgets(ff(fnum));
        %gets rid of ending characters [\]
        tline=regexprep(tline,'[\\$]','');
        %--------------------------------------------------------------------------
        % Reads headers and number of columns
        %--------------------------------------------------------------------------
        %get delimiter
        delim='\t';
        if length(strfind(tline,','))> length(strfind(tline,delim)), delim=',';end
        hdr2=textscan(tline,'%s','delimiter',delim);
        

        if fnum==1

            hdrs=hdr2{1,1};
            colmax=length(hdrs);

            %--------------------------------------------------------------------------
            % Creates interface
            %--------------------------------------------------------------------------
            [scrsz]=get(0,'ScreenSize');   ht=700;spc=50;ctrln=13;ncolmax=ceil(colmax/ctrln);wd=300*ncolmax;
            fs=14;
            if isdata==0,msg='Select INFORMATION Variables to import';,else msg='Select DATA Variables to import';end
            fig = figure('NumberTitle', 'off', 'Name', msg,'position', [(scrsz(3)-wd)/2 (scrsz(4)-ht)/2 wd ht]);
            %set(fig,'Color',get(fig,'Color'));
            cols=[];
            for i=1:ncolmax
                cols=[cols 300*(i-1)+50];
            end
           
            %uicontrol ('Style','text','Fontsize',fs,'position', [(wd-200)/2 ht-20 200 20],'String',msg,'backgroundcolor',get(fig,'color'));

            for i=1:colmax
                ncol=ceil(i/ctrln);
                b(i) = uicontrol ('Style','radiobutton','Fontsize',fs,'position', [cols(ncol) ht-50-spc*i+(ctrln*spc*(ncol-1)) 50+length(hdrs{i})*10 50],'String',hdrs{i},'backgroundcolor',get(fig,'color'));
                set(b(i),'Value',ismember(i,dflt));
            end
            ccb=uicontrol ('Style','togglebutton','position', [(wd-100) 20 40 20],'String','Cancel','Callback','uiresume(gcbf)');
            okb=uicontrol ('Style','togglebutton','position', [(wd-50) 20 30 20],'String','OK','Callback','uiresume(gcbf)');
            uicontrol(okb);
            uiwait(fig);

            set(fig,'visible','off');drawnow;
            if ~get(okb,'value'), fstr=[];return;end
            for i=1:colmax,bv(i)=get(b(i),'Value');end
            rcol=find(bv);% columns to read

            if isdata==0,hdrs0=hdrs;colmax0=colmax;rcol0=rcol;end

            fstr='';% Creates the format string to read data
            for i=1:colmax
                if ~ismember(i,rcol)
                    fstr=[fstr '%*s '];
                else
                    fstr=[fstr '%s '];
                end
            end
            fstr=[fstr '\n'];
            argout{varg}=fstr;

        end

end    






function plot_data(src,event)
global hdrs ind2 ind3 ind4 ind5 bv cf df hsc hcoast rcol rcol0
global statb plb cfb dfb gb divb statcb data_in data_info_in data_in_clean
global coastlon coastlat

switch src.Tag
    case 'ok'
        
        close all;

    case 'cancel'

        close all;   

    otherwise
        statb.String='Working on it...';
        
        data_in_clean=data_in;

        %
        for i=1:5
            cfb(i).Enable='off';
            if i<=4,plb(i).Enable='off';end
            if i<=3,dfb(i).Enable='off';end
        end
        drawnow;
        lonmin = str2double(plb(1).String);%convert string to number
        lonmax = str2double(plb(2).String);
        latmin = str2double(plb(3).String);
        latmax = str2double(plb(4).String);
        %--------------------------------------------------------------------------
        % remove lines outside lat and lon border (PL 17102011)
        %--------------------------------------------------------------------------
        ind=str2num(char(data_in_clean{1,sum(bv(1:ind2))}))<lonmin | str2num(char(data_in_clean{1,sum(bv(1:ind2))}))>lonmax;
        if sum(ind)>0
            for i=1:size(data_in_clean,2)
                data_in_clean{1,i}(ind)=[];
            end
        end

        statb.String='Working on it...selecting positions...';drawnow;
        ind=str2num(char(data_in_clean{1,sum(bv(1:ind3))}))<latmin | str2num(char(data_in_clean{1,sum(bv(1:ind3))}))>latmax;
        if sum(ind)>0
            for i=1:size(data_in_clean,2)
                data_in_clean{1,i}(ind)=[];
            end
        end

        %case 'cruise_flags'
        cf=[cfb(find([cfb.Value])).String];% cruise flags to read
        statb.String='Working on it...selecting data flags...';drawnow;
        ind=~ismember(char(data_in_clean{1,sum(bv(1:ind4))}),cf);
        if sum(ind)>0
            for i=1:size(data_in_clean,2)
                data_in_clean{1,i}(ind)=[];
            end
        end

        %case 'data_flags'
        df=[dfb(find([dfb.Value])).String];% cruise flags to read
        statb.String='Working on it...selecting cruise flags...';drawnow;
        ind=~ismember(char(data_in_clean{1,sum(bv(1:ind5))}),df);
        if sum(ind)>0
            for i=1:size(data_in_clean,2)
                data_in_clean{1,i}(ind)=[];
            end
        end

        %end

        for i=1:5
            cfb(i).Enable='on';
            if i<=4,plb(i).Enable='on';end
            if i<=3,dfb(i).Enable='on';end
        end
        drawnow;

        if gb.Value
            n=str2num(divb.String);
            for i=1:size(data_in,2)
                data_plot{i}=data_in_clean{1,i}(1:n:end);
            end
            dotsize=3;
            if ~isempty(find(ismember(hdrs,'fCO2rec')))
                ind=find(ismember(hdrs,'fCO2rec'));
                plotv=str2num(char(data_plot{1,sum(bv(1:ind))}));  %replace fCO2rec by variable name to be plotted.
            end

            ind=find(ismember(hdrs,'longitude')); xv=str2num(char(data_plot{1,sum(bv(1:ind))}));
            ind=find(ismember(hdrs,'latitude'));yv=str2num(char(data_plot{1,sum(bv(1:ind))}));
            mx=max(plotv);    plotvc=plotv/mx;
            delete(hsc);delete(hcoast);
            hsc=scatter3(xv,yv,plotv,4,plotvc);
            x1lim=get(gca,'XLim');
            y1lim=get(gca,'YLim');
            map_height=mean(plotv); % average of plotted data
            hcoast=plot3(coastlon,coastlat,zeros(size(coastlon,1),1)+map_height,'Parent',gca, 'Marker','none', 'MarkerSize',dotsize, 'MarkerEdgeColor','b', 'MarkerFaceColor','none','LineStyle','-');
            set(gca,'XLim',x1lim,'YLim',y1lim);

            ind=find(ismember(hdrs,'Expocode'));
            if ~isempty(ind)
                msg=sprintf('# Data Points: %i\n# cruises: %i',size(data_plot{1,1},1),numel(unique(data_plot{1,sum(bv(1:ind))})));
            else
                msg=sprintf('# Data Points: %i',size(data_plot{1,1},1));
            end
            statcb.String = msg;
            statcb.FontSize=14;
        end

        ind=find(ismember(hdrs,'Expocode'));
        if ~isempty(ind)
            msg=sprintf('# Data Points: %i\n# cruises: %i',size(data_in_clean{1,1},1),numel(unique(data_in_clean{1,sum(bv(1:ind))})));
        else
            msg=sprintf('# Data Points: %i',size(data_in_clean{1,1},1));
        end
        statb.String = msg;
        statb.FontSize=14;
        
end


end 

function graph_vis(src,event)
global hsc hcb hcoast gb 

  ha=[gca hsc hcb hcoast];
  if gb.Value, set(ha,'Visible','on');else set(ha,'Visible','off');end

end
