function [data2aoml]=save_final_results(cruiseid,staa,stab)
% SAVE_FINAL_RESULTS - apply oxygen and conductivity calibration and save data
%
% CTD Calibration toolbox.
%
% USAGE:
% [data2aoml]=save_final_results(cruiseid,staa,stab);
%	staa, stab are optional. 
%
% INPUT: cruiseid: Cruise identification name.
% 
% OUTPUT: creates ctd.csv and aoml.cal files with WOCE and AOML style data
%	formats resp.
%          
% DESCRIPTION
%	Apply oxygen and conductivity calibration to
%	the cond_match and oxy_match files and save the calibrated data
%	in the AOML and WOCE format.
% 

% AUTHORS:
%	  Carlos Fonseca 
%         UM/CIMAS
%         Derrick Snowden
%         NOAA/AOML/PhOD
%         Tue May 11 11:23:37 EDT 2004
%
% VERSION: 
%	$Revision: 1.11 $
%	$Date: 2008/03/12 16:13:05 $
%	$Id: save_final_results.m,v 1.11 2008/03/12 16:13:05 duncombe Exp duncombe $
%
% CHANGELOG: 
%  07-Oct-2004, Version 1.0
%	* Initial version. 
%  2007/12/17 - CMDR
%	* read cruise id from the file in the current directory
%  2008/01/16 CMDR
%	* comments
%  2008/03/05 CMDR
% 	* change carriage returns (\r) to newlines (\n) in the output
% 	* vectorise some loops
%	* introduce staa and stab as optional arguments, and give defaults
%	* put results files in calibrated/ subdirectory
%	* tidying up and comments
%
% BUGS
%	* still much tidying up to do with the header information in the 
%	files.
% 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% 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;
n=who('cnv_cal');

if isempty(n)==1
	error('cnv_cal not found. Run apply_calibration.m ');
	return;
end
disp(['***********************************************************' ...
	'*****************']);
disp(['***********************************************************' ...
	'*****************']);
disp(['This is the program that saves the calibrated data in AOML ' ...
	'and WOCE formats.']);
disp(['Stations range: ',num2str(min(vertcat(cnv_cal.station))),' to ',...
    num2str(max(vertcat(cnv_cal.station)))]);
disp(['***********************************************************' ...
	'*****************']);
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([cnv_cal.station]); end;
if isempty(stab), stab=max([cnv_cal.station]); end;
%%%%%%%%%%%%

%% whut???
%% for j=1:1:length(cnv_cal)
%%       if staa==cnv_cal(j).station
%%       	   sta_min_idx=j;
%%       end;
%%       if stab==cnv_cal(j).station
%%       	   sta_max_idx=j;
%%       end;
%% end;
%% how about:
sta_min_idx=find(staa==[cnv_cal.station]);
sta_max_idx=find(stab==[cnv_cal.station]);

% Saving the data in the AOML format  
%open the cnv_cal file
%station=station_number
form=['%0' num2str(fix(log10(max([cnv_cal.station])))+2) 'i'];
for i=sta_min_idx:1:sta_max_idx
	sta=cnv_cal(i).station;   
	outfile=['calibrated/' cruiseid(1:6), sprintf(form,sta),'_aoml.cal'];
	outfile_woce=['calibrated/' cruiseid(1:6), sprintf(form,sta),'_ctd.csv'];
% calculating the julian day
jday=datenum(cnv_cal(i).gtime(1:3))-datenum(2001,12,31);
%index for the parameters that we want to save in the aoml format;
%pres_idx=1;
%temp_idx=3;
%cond_idx=9;
%sal_idx=4;
%ox_c_idx=10;
%ox_t_idx=11;
%ox_idx=8;
%max_val=find(out(i).data(:,1)==max(out(i).data(:,1)));
GMT=cnv_cal(i).gtime(4)*100+cnv_cal(i).gtime(5);
%preparing the matrix to save the data in aoml format
data2aoml=[	cnv_cal(i).pressure cnv_cal(i).temp cnv_cal(i).pottemp  ...
		cnv_cal(i).salt cnv_cal(i).dynheight cnv_cal(i).depth  ...
		cnv_cal(i).oxyumol];
%% 
%% CMDR: Do we really want to return the data in rows not columns?
data2aoml=data2aoml.'; 
fid=fopen(outfile,'w');
fprintf(fid,' cast   lat    long    jday   mo/da/yr   gmt\n');
fprintf(fid,'%4i%8.3f%8.3f%6i%6i/%2i/%2i%6i \n \n',sta, ...
	abs(cnv_cal(i).latitude), cnv_cal(i).longitude  ...
         ,jday,cnv_cal(i).gtime(2),cnv_cal(i).gtime(3), ...
	cnv_cal(i).gtime(1)-2000,GMT);
crdate=datestr(cnv(1).gtime);
fprintf(fid,['    File created by Jay Hooper - ',num2str(date), ...
	'   \n']); % Cambiar para cada crucero RG 7/2/2007
fprintf(fid,['                  ABACO Cruise ',crdate(4:6),' ',crdate(8:12), '\n ']);
fprintf(fid,'                 \n \n');
fprintf(fid,['     Secondary sensors (T,S,O) - ' ...
	'Calibrated data   \n \n']);
fprintf(fid,'\n');
fprintf(fid,'   pr       te       th       sa       ht       ga       ox\n');
fprintf(fid,'dbars    deg c    deg c      psu  dyn. cm    gamma  umol/kg\n');
fprintf(fid,'%5.3f   %2.3f   %2.3f   %2.3f    %2.3f    %5.3f   %2.3f\n', ...
		data2aoml);
fclose(fid);
%%%Saving in the WOCE Exchange Format
% 31-USA; WBTS-Nombre del projecto; OCEANUS-Nombre del Barco.
% 	REVISAR BIEN QUE COSA ES EXPOCODE
expocode='02WBTSRHB';  
sect_id='AB1202';
cast=1;
depth=max(cnv_cal(i).depth+20);
fid1=fopen(outfile_woce,'w');
%

fprintf(fid1,'CTD,%4i%02i%02iPHODAOMLRG \n',cnv_cal(i).gtime(1), ...
		cnv_cal(i).gtime(2),cnv_cal(i).gtime(3));
fprintf(fid1,'#code: save_final_results.m \n');
fprintf(fid1,['#original CTD file: cnv_cal in ab1202_db.mat - created' ...
	' 5/4/12  \n']); % Informacion extra. RG 7/2/2007
fprintf(fid1,'#depth estimated from CTD depth + 20 meters \n');
fprintf(fid1,'NUMBER_HEADERS = 10 \n');
fprintf(fid1,'EXPOCODE = %16s  \n',expocode);
fprintf(fid1,'SECT_ID = %6s \n',sect_id);
fprintf(fid1,'STNNBR = %6s \n',num2str(cnv_cal(i).station));
fprintf(fid1,'CASTNO = %3i \n',cast);
fprintf(fid1,'DATE = %4i%02i%02i \n',cnv_cal(i).gtime(1), ...
		cnv_cal(i).gtime(2),cnv_cal(i).gtime(3));
fprintf(fid1,'TIME = %04i \n',GMT);
fprintf(fid1,'LATITUDE = %8.4f \n',cnv_cal(i).latitude);
fprintf(fid1,'LONGITUDE = %9.4f \n',cnv_cal(i).longitude);
fprintf(fid1,'DEPTH = %5i \n',round(depth));
fprintf(fid1,['CTDPRS,CTDPRS_FLAG_W,CTDTMP,CTDTMP_FLAG_W,CTDSAL,' ...
		'CTDSAL_FLAG_W,CTDOXY,CTDOXY_FLAG_W \n']);
fprintf(fid1,'DBAR,,ITS-90,,PSS-78,,UMOL/KG \n');
data2woce=[	cnv_cal(i).pressure repmat(2,length(cnv_cal(i).pressure),1) ...
		cnv_cal(i).temp repmat(2,length(cnv_cal(i).pressure),1) ...
           	cnv_cal(i).salt repmat(2,length(cnv_cal(i).pressure),1) ...
		cnv_cal(i).oxyumol repmat(2,length(cnv_cal(i).pressure),1)];

fprintf(fid1,'%9.1f,%1i,%9.4f,%1i,%9.4f,%1i,%9.1f,%1i \n',data2woce.');
fprintf(fid1,'END_DATA \n');
fclose(fid1);

end;
return;

