function compare_tsplot_original(cruiseid)
% COMPARE_TSPLOT_ORIGINAL - makes ts-plots 
%
% CTD Calibration toolbox.
%
% USAGE:
%  compare_tsplot(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_cond
% _sumfile from the cruise database and plot the ts plots using primary and
% secondary sensor for conductivity and temperature.  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:Carlos Fonseca 
%         UM/CIMAS
%         Derrick Snowden
%         NOAA/AOML/PhOD
%         Tue May 11 11:23:37 EDT 2004
%
% 
% VERSION: 
%	$Revision: 1.8 $
%	$Date: 2008/01/19 19:46:35 $
%	$Id: compare_tsplot_original.m,v 1.8 2008/01/19 19:46:35 duncombe Exp duncombe $
%
% CHANGELOG: 
%   
%   24-Mar-2006 - Molly Baringer
%       * Included comments, better error messages
%       * Cleaned up and streamlined the plotting
%       * Will process raw cnv files if no delooped files are present
%	2007/12/17 - CMDR
%	* read cruise id from the file in the current directory
%	
%	
%		

% DEPENDENCIES: SW package (Version 3 using ITS-90 Temperature Scale)
%               load_salts
%               load_btl
%               load_bl
%               load_cnv
%

%%%%%%%%%%% CMDR read cruiseid if we can
if nargin==0, cruiseid=getcruiseid; end;
if isempty(cruiseid), cruiseid=getcruiseid; end;
%%%%%%%%%%%
% 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 = 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
        

aux_stations=vertcat(cnv_compare.station);
disp('****************************************** ')
disp('SENSORS COMPARISONS')
disp('****************************************** ')
disp('The data found in cnv goes from') 
disp(['the station ',num2str(min(aux_stations)),' to the station ', ...
	num2str(max(aux_stations)),'.'] ) 
disp('****************************************** ')
%
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);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
 
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

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 included ' ...
	'because cond_match was not found.']])
fprintf(1,[['Run make_cond_sum. The program will continue anyway']])
bottle_samples=0;
return;
 end
end

 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
 
% 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 TS plot
    disp(['Station ',num2str(cnv_compare(i).station), ...
	'  Temperature        Salinity        Pressure  ']) 
    if plot_type==0;
     disp(['        ' num2str(min(cnv_compare(i).thetapri)) ' - ' ...
	num2str(max(cnv_compare(i).thetapri)) '  ' ...
	num2str(min(cnv_compare(i).salpri)) ' - ' ...
	num2str(max(cnv_compare(i).salpri)) '   ' ...
	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.         
  
 %%%% plotting 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

% plotting 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

    if plot_type==0;
    plot(cnv_compare(i).salpri,cnv_compare(i).thetapri,'color', ...
		profile_color(sta_counter,:),'linewidth',2)
    hold on;
    plot(cnv_compare(i).salsec,cnv_compare(i).thetasec,':','color', ...
		profile_color(sta_counter,:))
    axis([min(cnv_compare(i).salpri)-0.5 ...
	max(cnv_compare(i).salpri)+0.5 ...
	min(cnv_compare(i).thetapri)-1 ...
	max(cnv_compare(i).thetapri)+1 ])
    else
     plot(cnv_compare(i).salt,cnv_compare(i).pottemp,'color', ...
	profile_color(sta_counter,:),'linewidth',2)    
      axis([min(cnv_compare(i).salt)-0.5  ...
	max(cnv_compare(i).salt)+0.5  ...
	min(cnv_compare(i).pottemp)-1  ...
	max(cnv_compare(i).pottemp)+1 ])  
        
        
    end
    
    % adding bottle sample data
    if bottle_samples==1
        aux_sta_idx=find(cond_match.stnnbr==cnv_compare(i).station);
        plot(cond_match.btlsal(aux_sta_idx),...
        	sw_ptmp(cond_match.btlsal(aux_sta_idx), ...
		cond_match.ctdtmp1(aux_sta_idx), ...
		cond_match.ctdprs(aux_sta_idx),0), ...
		'*','color',profile_color(sta_counter,:))
    end
%%%%%%%%%%%%%%%%%%%%%%
    xlabel('salinity [ psu ]')
    ylabel('potential temperature [ ^{o}C ]')
    if plot_type == 1
      title(['TS-PLOT Calibrated - Cruise ',cruiseid])
    else
      title(['TS-PLOT Raw - Cruise ',cruiseid, ...
		'   Primary-solid     Secondary-dotted '])
    end
    
    if (sta_counter==10 | i==sta_end_idx)
        counter=1;
    %%%%%%%%%%%%%%%%%
        change_axis =input('Do you want to define the axis? (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')
            change_axis=input('Do you want to define the axis? (0=no 1=yes) ');
        end
        if change_axis==1
            new_axis=input('Enter the new axis limits. (Ex. [ 34.8 35 1 5])');
            axis(new_axis);
        end
 %%%%%%%%%%%%%%%%%
        for j=legend_ini_idx:i
            aux_legend=legend_ini_idx:i;
            legend_string2{counter}=['Station ',num2str(cnv_compare(j).station)];
            c=axis;
            diff_temp=(c(4)+(c(4)*0.01))-((c(3))-(c(3)*0.01));
            potemp_sample=((c(4)*0.01)+c(4))-((diff_temp/length(aux_legend)*(counter-1)));
            text((0.00001*c(2))+c(2),potemp_sample,legend_string2(counter),'color',profile_color(counter,:))
            counter=counter+1;
        end
    %replotting the isopycnal contours    
        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 45.85 45.9 45.95 46 46.05 46.2 46.4 46.6] ,'k');
            end
            clabel(c,h)
        end
end
 

