function fh=compare_ctd_sensors(cruiseid,staa,stab)
% COMPARE_CTD_SENSORS - plots to compare the primary and secondary sensors
%	(temperature, conductivity and dissolved oxygen) of the CTD.
%
% CTD Calibration toolbox.
%
% USAGE:
% 	fh=compare_ctd_sensors(cruiseid,staa,stab)
%	fh is figure handles of figures created
%
% INPUT: cruiseid: Cruise identification name.
%   
% OUTPUT: A series of plots to comparing the primary and the secondary
% sensors of the CTD.  
%          
% DESCRIPTION: This function uses the cnv files from the cruise database and
% plot the profiles as well the differences between primary and secondary
% sensor for conductivity or temperature or dissolved oxygen to have a better
% visualization of the data this function only allows up to 10 different
% stations for a single plot.
%

% AUTHORS:Carlos Fonseca 
%         UM/CIMAS
%         Fri Dec 2 09:19:37 EDT 2005
% 
% VERSION: 
%	$Revision: 1.17 $
%	$Date: 2008/04/17 15:23:10 $
%	$Id: compare_ctd_sensors.m,v 1.17 2008/04/17 15:23:10 duncombe Exp duncombe $
%
% CHANGELOG: 
%   23-Jul-2004, Version 1.0
%		* Initial version.
%   22-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/10 - CMDR
%	* Use getcruiseid to read the cruise id from a file in the
%	cruise directory.
%  2007/12/11 - CMDR
%	* check for empty data sets (eg no secondary sensor)
%  2008/01/02 - CMDR
%	* return figure handles
%	* create a new figure on the first pass, stop overwriting existing  
%	figure
%  2008/01/17 CMDR
% 	* put staa and stab in the input variables so that it
%	doesn't keep asking for stations when you're doing testing.
%	* used the wrong test for bad data or no secondary sensor - fixed
%	* It doesnt make sense to have a random station number in the 
%	figure title - fixed.
%	* change oxygen x-axis label to reflect what is actually plotted.
%	* legend construction did not take into account missing sensors - fixed
%  2008/01/26 CMDR
%	* loop through the parameters we are comparing, instead of running the 
%	function repeatedly
%	* I learn more about preferences and discover that I detest them.
%	* Put titles in a variable so that they can be used to display an alert
%  2008/03/11 CMDR
%	* provide default staa and stab if empty
%  2008/03/12 CMDR
%	* improve readability
%  2008/03/18 CMDR 
%	* place legend better, reduce need to edit each figure before printing 
%  2008/03/27 CMDR
%	* fixed the assumption that the dir command would provide a nicely
%	sorted array of station numbers. Now sort station numbers and loop 
%	through the station number index.
%  2008/04/17 CMDR
% 	* accomodate beckman oxygen sensors
%

% BUGS
%
%  2008/01/02 CMDR
%	* warning message in this function refers to make_.m. What 
%	is that about? Which function is that?
%	* When plotting calibrated data primary and secondary sensors
%	appear not to be distinguishable. What should we be plotting here? 
%

%%%%%%%%%%% CMDR read cruiseid if we can
if nargin==0, cruiseid=getcruiseid; end;
if isempty(cruiseid), cruiseid=getcruiseid; end;
%%%%%%%%%%%

%%% CMDR prepare for file handles
fcnt=0;

% 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
%%%%%%%%% CMDR why dont you do this?
disp(['loading ' db_file]);
	load(db_file);
%    ld_file=(['load ',db_file]);
%    eval(ld_file)
%%%%%%%%%
else
	error(['The cruise data base file was not found on the path.  ' ...
		db_file '.  Check path']);
end

plot_type = input(['Compare_ctd_sensors: \n' ...
		'    raw data = 0\n' ...
		'    delooped data = 1\n' ...
		'    calibrated data = 2\n' ...
		'Select datatype: ']);    

if plot_type == 1
    n=who('cnv_dlp');
    if isempty(n)==1
        fprintf (1,[ ...
	['WARNING COMPARE_CTD_SENSOR: Selected delooped cnv files.  \n'] ...
        ['    Variable cnv_dlp not found. \n'] ...
        ['    Proceeding with raw CNV files.    \n'] ...
        ['    If delooped data desired hit CTRL-C '], ...
	['and run despike.m and deloop.m before proceeding.\n'] ...
        ['    Hit <RETURN> to continue with raw CNV files.\n']]);
        pause
        cnv_compare = cnv_load;
    else
        cnv_compare = cnv_dlp;
    end;
elseif plot_type == 2
    n=who('cnv_cal');
    if isempty(n)==1
        fprintf (1,[ ...
	['WARNING COMPARE_CTD_SENSOR: Selected calibrated files.  \n'] ...
        ['    Variable cnv_cal not found. \n'] ...
        ['    Proceeding with raw CNV files.    \n'] ...
        ['    If calibrated data desired hit CTRL-C '], ...
	['and run make_.m before proceeding.\n'] ...
        ['    Hit <RETURN> to continue with raw CNV files.\n']]);
        pause
        cnv_compare = cnv_load;
    else
        cnv_compare = cnv_cal;
    end
else
    cnv_compare = cnv_load;
end;

seabird=false;
beckman=false;
if isfield(cnv_compare,'oxvpri'),
	seabird=true; 
elseif isfield(cnv_compare,'oxcpri'),
	beckman=true;
end;
% we need to be very sure which order the stations are being accessed, so 
% set up aux_stations so that we do not need to rely on any arbitrary order
% that the variable structure might have been created in.
[aux_stations,ind_stns]=sort(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('****************************************** ')

%%%%%%%%%%%% CMDR
% staa=input('Input first station: ');
% stab=input('Input last station: ');
if ~exist('staa'), staa=input('Input first station: '); end;
if ~exist('stab'), stab=input('Input last station: '); end;
if isempty(staa), staa=min(aux_stations); end;
if isempty(stab), stab=max(aux_stations); end;
%%%%%%%%%%%%

%%%%%%%%%%%% CMDR offer the option to loop through all the sensors
disp(' Choose the parameter that you want to evaluate')
disp('  0 = Temperature  ')
disp('  1 = Conductivity ')
disp('  2 = Dissolved Oxygen ')
disp('  9 = All the above ')
ctd_var_choice=input('What parameter do you want to evaluate: ');

while (isempty(ctd_var_choice)==1 | ~any(ctd_var_choice==[0 1 2 9]) )
   disp('Invalid Option, please choose one of the options above')
   ctd_var_choice=input('What parameter do you want to evaluate: ');
end

if ctd_var_choice==9, ctd_var_choice=[0,1,2]; end;
%%%%%%%%% CMDR end of mods to choosing variables

% while (isempty(ctd_var)==1 | ctd_var<0 | ctd_var>2)
%    disp('Invalid Option, please choose one of the options above')
%    ctd_var=input('What parameter you want to evaluate: ');
% end

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

%%%%%%% CMDR we loop through our chosen ctdvar's
for ctd_var=ctd_var_choice,

% New figure index, we are only allowing 10 stations per plot
%%%%%%%%% CMDR: And the first figure should be created before we plot 
%%%%%%%%% all over something else.
% new_fig_idx=0;
new_fig_idx=1;
%%%%%%%%%
% station counter
sta_counter=0;
% Initialization of the plots

% Assumes stations are in "order" in cnv data array (which they should be
% since they were loaded with a "dir" command that puts things in order.
% And it turns out they may not be in the expected order. So aux_stations 
% has been rearranged (sorted) above so that we know the order.
sta_ini_idx = find(aux_stations==staa);
sta_end_idx = find(aux_stations==stab);       

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
% finding the index for the variables
% Indexes for variables
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Starting the plots
legend_ini_idx=sta_ini_idx;

% and loop through the known order of ind_stns
for i = ind_stns(sta_ini_idx: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)
%%%%%%%% CMDR new figure
	fcnt=fcnt+1;
        fh(fcnt)=figure;
%%%%%%%%
        sta_counter=1;
        legend_ini_idx=i;
        new_fig_idx=0;
from_stnno=int2str(cnv_compare(i).station);
        % clear legend_string;
        % clear legend_string2;
         legend_string=[];
         legend_string2=[];
    end
 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    if (ctd_var==0)
        y=cnv_compare(i).pressure;
%%%%%%% CMDR pri and sec sensors are not distinguished in the cal data.
if isfield(cnv_compare(i),'temppri'),
        x1=cnv_compare(i).temppri;
        x2=cnv_compare(i).tempsec;
else,
        x1=[];
        x2=[];
end;
%%%%%%%
        xaxis_label = 'Temperature (Deg. C)';
        xaxis_label_diff = 'Temperature Differences [Pri-Sec] (Deg. C)';
        yaxis_label = 'Pressure (dbar)';
    elseif (ctd_var==1)
        y=cnv_compare(i).pressure;
%%%%%%% CMDR pri and sec sensors are not distinguished in the calibrated data.
if isfield(cnv_compare(i),'condpri'),
        x1=cnv_compare(i).condpri;
        x2=cnv_compare(i).condsec;
else,
        x1=[];
        x2=[];
end;
%%%%%%%
        xaxis_label = 'Conductivity (S/m)';
        title(['CTD Profiles']) ;
        xaxis_label_diff = 'Conductivity Differences [Pri-Sec] (S/m)';
        yaxis_label = 'Pressure (dbar)';
    elseif (ctd_var==2)
        y=cnv_compare(i).pressure;
%%%%%%% CMDR - it seems you are going to plot oxygen voltage. The label says 
%%%%%%% oxygen in mL/L. Wassup with that?  Primary and secondary data are not 
%%%%%%% distinguished in the cal data.
if seabird,
        x1=cnv_compare(i).oxvpri;
        x2=cnv_compare(i).oxvsec;
 	x_oxy_label='Oxygen sensor voltage (V)';
	x_oxydiff_label='Oxygen voltage differences [Pri-Sec] (V)';
elseif beckman,
        x1=cnv_compare(i).oxcpri;
        x2=cnv_compare(i).oxcsec;
 	x_oxy_label='Oxygen sensor current (uA)';
	x_oxydiff_label='Oxygen current differences [Pri-Sec] (uA)';
else,
        x1=[];
        x2=[];
end;
%%%%%%%
%        xaxis_label ='Dissolved Oxygen (ml/l)';
        xaxis_label = x_oxy_label;
        ylabel('Pressure (dbar)');
        title(['CTD Profiles']) 
%        xaxis_label_diff ='Dissolved Oxygen Differences [Pri-Sec] (ml/l)';
        xaxis_label_diff = x_oxydiff_label;
        yaxis_label = 'Pressure (dbar)';
    end

% plotting the profile
    subplot(1,2,1)
%%%%%%%%%% CMDR
    if ~isempty(x1), plot(x1,y,'color',profile_color(sta_counter,:)); end;
%%%%%%%%%%
    %wysiwyg;
    hold on
%%%%%%%%%% CMDR
    if ~isempty(x2),
		plot(x2,y,'--','color',profile_color(sta_counter,:));
	end;
%%%%%%%%%%
    ax1=gca;
    grid on; 
    set(ax1,'XMinorTick','on','ydir','reverse', 'box','on')
    xlabel(xaxis_label);
    ylabel(yaxis_label);
    if (sta_counter==10 | i==sta_end_idx)
        counter=1;
        for j=legend_ini_idx:i
%%%%%%%%% CMDR
if ~isempty(x1),
            legend_string{counter}=['Pri - Sta ', ...
		num2str(cnv_compare(j).station)];
            counter=counter+1;
%%%%%%%%% CMDR
end;
if ~isempty(x2),
            legend_string{counter}=['Sec - Sta ', ...
		num2str(cnv_compare(j).station)];
            counter=counter+1;
end;
        end;
    to_stnno=int2str(cnv_compare(i).station);
	titlestr=['CTD Profiles: Station ' from_stnno ' to ' to_stnno ];
    title(titlestr) ;
%%%%%%%%% CMDR testing for empty plot
if isempty(get(gca,'children')),
	disp(['empty plot: ' titlestr]);
else
        legend(legend_string,0);
end;
    end
% plotting the difference between sensors
    subplot(1,2,2)
%%%%%%%%%% CMDR
    if ~isempty(x1) & ~isempty(x2),
	plot(x1-x2,y,'color',profile_color(sta_counter,:));
	end;
%%%%%%%%%% 
    ax1=gca;
    grid on;
    set(ax1,'XMinorTick','on','ydir','reverse', 'box','on')
    xlabel(xaxis_label_diff);
    ylabel(yaxis_label);
% title(['Primary-Secondary Sensors: Station ' int2str(cnv_compare(i).station)])
    hold on
    if (sta_counter==10 | i==sta_end_idx)
        counter1=1;
        for j=legend_ini_idx:i
            legend_string2{counter1}=['Station ', ...
		num2str(cnv_compare(j).station)];
            counter1=counter1+1;
        end
    % to_stnno=int2str(cnv_compare(i).station);
    titlestr=['Primary-Secondary Sensors: Station ' from_stnno ' to ' to_stnno ];
    title(titlestr) ;
%%%%%%%%% CMDR testing for empty plot
if isempty(get(gca,'children')),
	disp(['empty plot: ' titlestr]);
else
        %legend(legend_string2,0,'location','southeast')
        legend(legend_string2,0);
    end;
%%%%%%%%% CMDR end
    end
end;

%%%%%%%% CMDR end of looping through ctd_var 
end; % for ctd_var=ctd_var_choice,

clear cnv_compare;
return;


