function compare_ctd_sensors(cruiseid)
% COMPARE_CTD_SENSORS -  Diagnostics plots to compare the sensors (conductivity, dissolved oxygen
%                        and temperature) of the CTD.
%
% CTD Calibration toolbox.
%
% USAGE:
% compare_ctd_sensors(cruiseid);
%
%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
% 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
%   Fall-2006 - Carlos Fonseca
%       * Added delooped and calibrated data options for plot
%   1-April-2007 - Molly Baringer
%       * Changed to plot most recent files as available (fixed bug that
%       program dies if Station requested does not exist).
%

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

% cruise_dir is the main calibration data directory 
% it should contain the subdirectories proc_data, raw_data etc.
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
    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

%type_plot = input('Compare_ctd_sensors: select datatype\n    raw data = 0\n    delooped data = 1\n    calibrated data = 2\n');    

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

if type_plot == 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;
        disp('Delooped data loaded')
    end
elseif type_plot == 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


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: ');

disp(' Choose the parameter that you want to evaluate')
disp('  0 = Temperature  ')
disp('  1 = Conductivity ')
disp('  2 = Dissolved Oxygen ')
ctd_var=input('What parameter you want to evaluate: ');
    
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;

% New figure index, we are only allowing 10 stations per plot
new_fig_idx=0;
% station counter
sta_counter=0;
% Initialization of the plots
sta_ini_idx=find(aux_stations==staa);
sta_end_idx=find(aux_stations==stab);

% Program could fail here is the specific station numbers are not found.
if isempty(sta_ini_idx)
% default to the smallest station number
  sta_ini_idx=find(aux_stations==min(aux_stations));
end
if isempty(sta_end_idx)
% default to the largest station number
  sta_end_idx=find(aux_stations==max(aux_stations));
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
% finding the index for the variables
% Indexes for variables
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Starting the plots
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;
        clear legend_string;
        clear legend_string2;
    end
 if type_plot==2,%JH edit
     %if ctd_var==2,
         y=cnv_compare(i).pressure;
        x1=cnv_compare(i).oxyumol;
        x2=cnv_compare(i).oxyumol;
        xaxis_label ='Dissolved Oxygen (umol/kg)';
        ylabel('Pressure (dbar)');
        title(['CTD Profiles']) 
        xaxis_label_diff ='Dissolved Oxygen Differences [Pri-Sec] (umol/kg)';
        yaxis_label = 'Pressure (dbar)';
     else
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    if (ctd_var==0)
        y=cnv_compare(i).pressure;
        x1=cnv_compare(i).temppri;
        x2=cnv_compare(i).tempsec;
        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;
        x1=cnv_compare(i).condpri;
        x2=cnv_compare(i).condsec;
        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;
        x1=cnv_compare(i).oxmmpri;
        x2=cnv_compare(i).oxmmsec;
        xaxis_label ='Dissolved Oxygen (umol/kg)';
        ylabel('Pressure (dbar)');
        title(['CTD Profiles']) 
        xaxis_label_diff ='Dissolved Oxygen Differences [Pri-Sec] (umol/kg)';
        yaxis_label = 'Pressure (dbar)';
    end
 end;

% Ploting the profile
    subplot(1,2,1)
    plot(x1,y,'color',profile_color(sta_counter,:))
    %wysiwyg;
    hold on
    plot(x2,y,'--','color',profile_color(sta_counter,:))
    ax1=gca;
    grid on; 
    set(ax1,'XMinorTick','on','ydir','reverse', 'box','on')
    xlabel(xaxis_label);
    ylabel(yaxis_label);
    title(['CTD Profiles: Station ' int2str(cnv_compare(i).station)]) 
    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)];
            counter=counter+2;
        end
        legend(legend_string,0)
    end
% ploting the difference between sensors
    subplot(1,2,2)
    plot(x1-x2,y,'color',profile_color(sta_counter,:))
    ax1=gca;
    grid on;
    set(ax1,'XMinorTick','on','ydir','reverse', 'box','on')
    xlabel(xaxis_label_diff);
    ylabel(yaxis_label);
    title('Primary-Secondary Sensors ')
    hold on
    if (sta_counter==10 | i==sta_end_idx)
        counter=1;
        for j=legend_ini_idx:i
            legend_string2{counter}=['Station ',num2str(cnv_compare(j).station)];
            counter=counter+1;
        end
        legend(legend_string2,0)
    end
end

clear cnv_compare;
return;