function [SDw,stat]=hdfsd_write_open(hdf_root,SDw,jset,dlab,dims, ...
	scales,labels);
%
% Call [SDw,stat]=hdfsd_write_open(hdf_root,SDw,jset,dlab,dims, ...
%	scales,labels);
%
% hdf_root	= Output root of HDF file (suffix = '.hdf');
% SDw.SD_id	= 0 to open new HDF file, SDw.SD_id for subsequent dataset writes;
%             Set SDw=[] on initial hdfsd_open call;
% jset		= Set number;
% dlab		= Label for data;
% dims		= Vector of dimensions;
% scales	= Cell array of axis scales;
% labels	= Cell array of axis labels;
%
% Use: 	hdfsd_write_open 	to open HDF file
% Use: 	hdfsd_write 		to write data sets to SDw.
% Use: 	hdfsd_write_close 	to close SDw finally.
%
%
% COPYRIGHT (c) 2008
% 
% Applied Research Laboratories, The University of Texas at Austin
% (ARL:UT)
% All rights reserved.
% 
% This material may be reproduced by or for the U.S. Government
% only. This notice must appear in all copies of this file and its
% derivatives. Further distribution outside the U.S. Government is
% prohibited without the explicit written authorization from the
% Director of the Environmental Sciences Laboratory, ARL:UT.
% 
% THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
% EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE
% IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
% PURPOSE, OR NONINFRINGEMENT.
% 
% IN NO EVENT WILL ARL:UT BE LIABLE FOR ANY DAMAGES WHATSOEVER ARISING
% OUT OF THE USE OR INABILITY TO USE THIS SOFTWARE, EVEN IF ARL:UT HAS
% BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
stat=-1; ndim=length(dims);
if isempty(SDw) | ~isfield(SDw,'SD_id') | SDw.SD_id==0,
    SDw.hdf_file=[hdf_root,'.hdf'];
	SDw.SD_id=hdfsd('start',SDw.hdf_file,'create');
	SDw.nset=jset;
	if SDw.SD_id<0, 
		disp('Error opening HDF file.  Check file is not open already.'); 
		return; 
	end
else
    SDw.SD_id = hdfsd('start',SDw.hdf_file,'write');
end
%
data_type='float32';
sds_id=hdfsd('create',SDw.SD_id,dlab,data_type,ndim,dims([ndim:-1:1]));
if sds_id<0, disp('Error creating data set '); return; end
%
status=hdfsd('setdatastrs',sds_id,dlab,' ','f9.4','cartesian');
if status<0, disp('Error setting dlab.'); return; end
%
for jdim=1:ndim,
	jd=ndim-jdim+1;
	dim_id(jdim)=hdfsd('getdimid',sds_id,jd-1);
	stat1=hdfsd('setdimname',dim_id(jdim),[labels{jdim},int2str(jset)]);
	stat2=hdfsd('setdimstrs',dim_id(jdim),labels{jdim},' ','f9.4');
	stat3=hdfsd('setdimscale',dim_id(jdim),single(scales{jdim}));
	if length(scales{jdim})~=dims(jdim),
		disp(['Bad length for scales of dim ',int2str(jdim)]);
		return
	end
	if any([stat1,stat2,stat3]<0), 
		disp(['Error setting dimension: ',int2str(jd)]); 
		disp([stat1,stat2,stat3]);
		return; 
	end
end
%
stat=0;
SDw.nset=max(SDw.nset,jset);
SDw.ndim(jset)=ndim;
SDw.dlab{jset}=dlab;
SDw.dims{jset}=dims;
SDw.scales{jset}=scales;
SDw.labels{jset}=labels;
SDw.dim_id{jset}=dim_id;
SDw.sds_id(jset)=sds_id;
%
% TEMP: see if closing after each write is OK:
status=hdfsd_write_close(SDw);
