function compare_toplot(cruiseid)
%  compare_tsplot -  Makes to-plots .
%
% CTD Calibration toolbox.
%
% USAGE:
%  compare_toplot(cruiseid);
%
% INPUT: cruiseid: Cruise identification name. 
%   
% OUTPUT:  A series of  ts plots to compare the primary and the secondary
% sensors of the CTD with historical data and/or bottle samples.
%         
%               
%
% DESCRIPTION:   This function uses the summary file created by make_oxy _sumfile from the cruise database 
%               and plot the ts plots using primary and secondary sensor for conductivity and oxygen. 
%               In order to have a better visualization of the data this function only allows up to 10 different
%               stations for a single plot. Bottle samples data and historical data can be added to the plots
% 
%  
%  
%  
%
% AUTHORS:Jay Hooper
%         UM/CIMAS   
%         3/21/2012
%
% CHANGELOG: 
%  
% DEPENDENCIES: SW package (Version 3 using ITS-90 Temperature Scale)
%               load_salts
%               load_btl
%               load_bl
%               load_cnv

%%%%%%%%%%%%%%%%%%%%%%%%%%% Begin Function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Retrieve the necessary preferences for this cruise
group = group_name(cruiseid);

% cruise_dir is the main calibration data directory 
if ispref(group,'cal_data_dir')
	cruise_dir=getpref(group,'cal_data_dir');
else
	error(['The cal_data_dir preference was not set for cruise: ' cruiseid '.  Run register_cruise.m']);
end

% Load data from the cruise database
db_file = fullfile(cruise_dir,[cruiseid '_db.mat']);
if exist(db_file)==2
	load(db_file);
else
	error(['The cruise data base file was not found on the path.  ' db_file]);
end

% Check for the necessary variables in the cruise database.
n=who('cnv');
if isempty(n)==1
	error(['cnv variable not found in the cruise database. Run load_cnv.m ']);
	return;
end

plot_type = 1;
plot_type = input('Compare_ctd_sensors: select datatype\n    raw data = 0\n    calibrated data = 1\n');    

if plot_type == 1
    n=who('cnv_cal');
    if isempty(n)==1
        fprintf (1,[['WARNING COMPARE_TSPLOT: Selected calibrated files.  \n'] ...
        ['    Variable cnv_cal not found. \n']])
        cnv_compare = cnv_load;
        plot_type = 0;
    else
        cnv_compare = cnv_cal;
    end
else
    if (isempty(who('cnv_dlp')) == 0)     % not empty = 0
        cnv_compare = cnv_dlp;
    else
        fprintf (1,[['WARNING COMPARE_TSPLOT: Variable cnv_dlp not found.  \n'] ])
        if (isempty(who('cnv_fill')) == 0)        % not empty = 0
            fprintf (1,[['   Continuing with cnv_fill.  \n']]) 
            cnv_compare = cnv_fill;
        else
            fprintf (1,[['WARNING COMPARE_TSPLOT: Variable cnv_fill not found.  \n']]) 
            fprintf (1,[['   Continuing with cnv_load.  \n'] ])
            cnv_compare = cnv_load;
        end
    end
end

%Display stations eligible to work with
aux_stations=vertcat(cnv_compare.station);
disp('****************************************** ')
disp('SENSORS COMPARISONS')
disp('****************************************** ')
disp(['The CTD data goes from station ',num2str(min(vertcat(cnv_load.station))),...
    ' to station ',num2str(max(vertcat(cnv_load.station))),'.'] ) 
disp(['The Bottle data goes from station ',num2str(min(oxy_match.stnnbr)),...
    ' to station ',num2str(max(oxy_match.stnnbr)),'.'] )
disp('****************************************** ')
%Allow input for station interval to plot
staa=input('Input first station: ');
stab=input('Input last station: ');

% Creating a color table for the plots
profile_color= [    255   117     0
                    255     0   255
                    128     0   186
                    255     0     0
                      0   117     0
                      0     0   255
                    136    92    29
                      0     0     0
                    255   255     0
                      0   255   255];
 profile_color=profile_color./255;

 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% New figure index, we are only allowing 10 stations per plot
new_fig_idx=0;
% station counter (set up provided on first station of each plot)
sta_counter=0;

% Initialization of the plots
sta_ini_idx=find(aux_stations==staa);
sta_end_idx=find(aux_stations==stab);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
if 0,
disp(' Setup sigma contours for plot ' )
disp('    0 = use the sigma 0 ' )
disp('    1 = use the sigma 2' )
disp('    2 = use the sigma 4' )
sig_con=input('Enter type sigma for isopycnal contours: ');
while (isempty(sig_con)==1 | sig_con<0 | sig_con>2)
    sig_con=input(['Invalid entry = ' num2str(sig_con) '.  Please try again: ']);
end
end;
bottle_samples=input('Do you want include the bottle samples? (0=no 1=yes)');
while (isempty(bottle_samples)==1 | bottle_samples<0 | bottle_samples>1)
    disp('Please answer 0 (zero) for no or  1(one) for yes')
    bottle_samples=input('Do you want include the bottle samples? (0=no 1=yes)');
end
if bottle_samples==1
n=who('cond_match');
 if isempty(n)==1
fprintf(1,[['Bottle samples cannot be include because cond_match was not found.']])
fprintf(1,[['Run make_cond_sum. The program will continue anyway']])
bottle_samples=0;
return;
 end
end

%%%%%%%%%%%%% Don't have a historical data base for oxygen yet %%%%%%%%%%%%
if 0,
    historical=input('Do you want include the historical data ? (0=no 1=yes)');
    while (isempty(historical)==1 | historical<0 | historical>1)
	disp('Please answer 0 (zero) for no or  1(one) for yes')
    historical=input('Do you want include the historical data ? (0=no 1=yes)');
    end


    if historical==1
    disp('Enter the name of the file with the historical data.')
    hist_file=input('Ex. abaco_historical.dat: ');
    hist=load(hist_file);
    end
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%% no historical O2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 


% finding the station
legend_ini_idx=sta_ini_idx;
for i=sta_ini_idx:1:sta_end_idx
    sta_counter=sta_counter+1;
    % starting or not another figure 
      if (sta_counter>10)
         new_fig_idx=1;
      end
      if (new_fig_idx == 1)
         figure;
         sta_counter=1;
         legend_ini_idx=i;
         new_fig_idx=0;
      end
      
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Parameters for the TO plot
    disp(['Station ',num2str(cnv_compare(i).station),'  Temperature        Oxygen        Pressure  ']) 
    if plot_type==0;
     disp(['        ' num2str(min(cnv_compare(i).thetapri)) ' - ' num2str(max(cnv_compare(i).thetapri)) '  ' num2str(min(cnv_compare(i).oxmmpri)) ' - ' num2str(max(cnv_compare(i).oxmmpri)) '   ' num2str(min(cnv_compare(i).pressure)) ' - ' num2str(max(cnv_compare(i).pressure))] )
    %else
     %disp(['        ' num2str(min(cnv_compare(i).pottemp)) ' - ' num2str(max(cnv_compare(i).pottemp)) '  ' num2str(min(cnv_compare(i).salt)) ' - ' num2str(max(cnv_compare(i).salt)) '   ' num2str(min(cnv_compare(i).pressure)) ' - ' num2str(max(cnv_compare(i).pressure))] )
    end

% Creating TS-plot
% Creating a matrix to calculate sigma 
% Choose the sigma to make the isopycnal contours

   % if sta_counter==1       % first station of each plot.         

   plot(cnv_compare(i).oxmmpri,cnv_compare(i).thetapri,'color',profile_color(sta_counter,:),'linewidth',2)
    hold on;
    plot(cnv_compare(i).oxmmsec,cnv_compare(i).thetasec,':','color',profile_color(sta_counter,:))
    
    if bottle_samples==1
        aux_sta_idx=find(oxy_match.stnnbr==cnv_compare(i).station & oxy_match.quality1 == 2);
        plot(oxy_match.btloxy(aux_sta_idx),...
        sw_ptmp(oxy_match.ctdsal1(aux_sta_idx),oxy_match.ctdtmp1(aux_sta_idx),oxy_match.ctdprs(aux_sta_idx),0),'r*','color',profile_color(sta_counter,:))
    end
    
     xlabel('Oxygen [ umol/kg ]')
     ylabel('potential temperature [ ^{o}C ]')
     title(['TO-PLOT Raw - Cruise ',cruiseid,'   Primary-solid     Secondary-dotted '])
     
   if (sta_counter==10 | i==sta_end_idx)
        counter=1;
        for j=legend_ini_idx:i
            legend_string{counter}=['Pri - Sta ',num2str(cnv_compare(j).station)];
            legend_string{counter+1}=['Sec - Sta ',num2str(cnv_compare(j).station)];
            legend_string{counter+2}=['Btl - Sta ',num2str(cnv_compare(j).station)];
            counter=counter+3;
        end
        legend(legend_string,0)
    end
     
end 
    


    if 0,
%%%%Ploting the sigma contours 
        if (sta_counter==1)
             if plot_type ==0
             diff_temp=max(cnv_compare(i).thetapri)-min(cnv_compare(i).thetapri);
             else
             diff_temp=max(cnv_compare(i).pottemp)-min(cnv_compare(i).pottemp);    
             end
             if diff_temp>10
                t_sigma=0:0.5:30;
             else
                t_sigma=0:0.1:30;
             end
             sal_sigma=33:0.1:38;
             [temp,sal]=meshgrid(t_sigma,sal_sigma);
             if sig_con==0
                sigma=sw_pden(sal,temp,0,0)-1000;
             elseif sig_con==1
                sigma=sw_pden(sal,temp,2000,2000)-1000;
             elseif sig_con==2
                sigma=sw_pden(sal,temp,4000,4000)-1000;
             end
             
% ploting the TS
%figure
            if sig_con==0
                [c,h]=contour(sal,temp,sigma,[21 22 23 24 25 26 27 28 29],'k');
            elseif sig_con==1
                [c,h]=contour(sal,temp,sigma,[35 35.5 36 36.5 37 37.5 38],'k');
            elseif sig_con==2
                [c,h]=contour(sal,temp,sigma,[45.2 45.4 45.6 45.8 46 46.2 46.4 46.6] ,'k');
            end
            clabel(c,h)
            hold on
      

% adding historical data as a background
        if historical==1
            salts_hist=hist(:,3);
            temp_hist=hist(:,2);
            press_hist=hist(:,1);
            potemp_hist=sw_ptmp(salts_hist,temp_hist,press_hist,0);
            h1=plot(salts_hist,potemp_hist,'k.');
            set(h1,'color',[0.8,0.8,0.8])
            hold on
        end
    end % END of first station of each plot set up
    end;