function write_s87(cruiseid,cnv_cal)
%WRITE_S87 - 	write calibrated ctd data to s87 file
% 
%USAGE -	write_s87(cruiseid,cnv_cal)
%
%EXPLANATION -	to write calibrated ctd data to a file in a standard 
%		data format
%
%SEE ALSO -	
%

%PROGRAM - 	MATLAB code by c.m.duncombe rae
%
%CREATED -	2008/01/31
%
%VERSION - 
%	$Revision: 1.5 $
%	$Date: 2008/03/11 00:39:41 $
%	$Id: write_s87.m,v 1.5 2008/03/11 00:39:41 duncombe Exp duncombe $
%	$Name: v200804301619 $
%
%CHANGE_LOG
%  2008/03/10 CMDR
%	* put the results files in calibrated/ subdirectory if it exists
%
%DISCLAIMER -	No responsibility can be accepted for failure or 
%		incorrect operation of this code. No guarantee, express 
%		or implied, is given. 
%

% use a bunch of standard stuff for the ctdcal package
if nargin==0, cruiseid=getcruiseid; end;
if isempty(cruiseid), cruiseid=getcruiseid; end;
group = group_name(cruiseid);
% if we are given a cnv_cal on the command line, we don't need to fiddle with
% the database file
if ~exist('cnv_cal'),
   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;
   db_file = fullfile(cruise_dir,[cruiseid '_db.mat']);
   if exist(db_file)==2,
   disp(['loading ' db_file]);
      load(db_file);
   else
      error(['The cruise data base file was not found on the path.  ' ...
      db_file '.  Check path']);
   end;
end;

% loop through stations
n_stns=size({cnv_cal.station},2);
for i_stn=1:n_stns,
% create a file for each station
   % get the largest station number we are going to use
   % and find out how many characters we need for the filename.
   numer=sprintf(['%0'  ...
	num2str(fix(log10(max([cnv_cal.station]))+1))  ...
	'd'],cnv_cal(i_stn).station);
   % this needs to be made robust with tests and all
   subdir='calibrated';
   file_name=[subdir '/' cruiseid '_' numer '.s87'];
   % We might want to test if the file already exists and determine if it is
   % okay to overwrite it. For now we just overwrite it and tough luck if you 
   % messed up...
   fid=fopen(file_name,'w');
   % write out the header
   % TPPCC SSSS CC SDD.DDDD SDDD.DDDD YY/MM/DD YDA HH:MM  CRUISE_ID
   %	FG Walton Smith
   % C33WA stn cast lat long yyyy/mm/dd yda hh:mm cruiseid]);
   % cast does not appear to be present in the data
   cast=1;
   headerstr=[ ...
	'C33WA ' ...
   	num2str(cnv_cal(i_stn).station)  ' ' ...
   	num2str(cast) ' ' ...
   	num2str(cnv_cal(i_stn).latitude) ' ' ...
   	num2str(cnv_cal(i_stn).longitude) ...
   	sprintf(' %04d/%02d/%02d ',cnv_cal(i_stn).gtime(1:3)) ...
   	num2str(yeardays(cnv_cal(i_stn).gtime(1:3))) ...
   	sprintf(' %02d:%02d ',cnv_cal(i_stn).gtime(4:5)) ...
   	cruiseid ];
   fprintf(fid, '%s\n', headerstr);
   % write out the id line
   fprintf(fid,'%s\n', '@PR DE TE PT CO SA OX');
   % write out the data
   fields={ 'pressure' 'depth' 'temp' 'pottemp' 'cond' 'salt' 'oxymll' };
   formspec=[];
	DATA=[];
   for j=1:length(fields),
	% disp(fields(j))
% disp([i_stn,j])
	DATA(:,j)=[cnv_cal(i_stn).(fields{j})];
	formspec=[formspec '%g\t'];
	
   end;
   formspec(length(formspec)-1:length(formspec))='\n';
   fprintf(fid,formspec,DATA.');
   % close the file
   fclose(fid);
   disp([file_name ' written']);
   
end;

return;

