function [fid]=write_gdf(fn, data)
%  NAME:
% 		write_gdf
%  PURPOSE:
% 		write data files in gdf format.
%  CATEGORY:
% 		General Purpose Utility
%  CALLING SEQUENCE:
% 		fid = write_gdf(filename,data)
%  INPUTS:
% 		file:	Complete pathname of the file to be written.
%  OUTPUTS:
% 		data:	Data structure.  For example, if the original
% 			data was stored as an array of bytes, then
% 			DATA will be returned as an array of bytes also.
%  RESTRICTIONS:
% 		Current implementation does not support structures or
% 		arrays of structures.
%  PROCEDURE:
% 		Reasonably straightforward.
% 		Determines if the file is ASCII or binary, reads the size
% 		and dimension info from the header, and reads in the data
%  MODIFICATION HISTORY:
% 		Written by David G. Grier, AT&T Bell Laboratories, 9/91
% 	12/95 Figures out how to deal with data from different-endian
% 		machines DGG.
%   converted to matlab 04/29/04, MDS NB: endian not implemented
%   converted to matlab 01/21/09, MDS write_gdf ascii not implemented
% -

MAGIC = 082991;
HEADER = 'GDF v. 1.0';

typelist={'Undefined',...
          'char',...
          'int32',...
          'int64',...
          'float',...
          'double',...
          'complex float',...
          'string',...
          'structure',...
          'complex double'...
          'pointer',...
          'object'};

%file = findfile(filespec, count=nfiles)
% MDS no error checking at this time
%if nfiles eq 0 then message,'No files matched specification '+filespec

ascii=false;

fid=fopen(fn,'w');

fwrite(fid,MAGIC,'int32');

% if(mgc~=MAGIC)
%   fseek(fid,0,'bof');
%   hdr=fscanf(fid,'%s');
%   if (hdr==HEADER) 
%     disp('-ascii may not work right');
%     ascii=true;
%   else
%     error([fn ' is not a GDF file']);
%   end
% end

sz=size(data);
ndim=sum(sz>0);
ne=numel(data);
tp=find(strcmpi(class(data),typelist))-1;
if(isempty(tp))
  fprintf('Data type %s not supported\n',class(data));
end

if ascii  % not working
%  ndim=fscanf(fid,'%d');
%  sz=fscanf(fid,'%d',ndim+2);
%  data=fscanf(fid,'%f',sz(end));
%  data=reshape(data,sz(1:end-1));
else
  fwrite(fid,ndim,'int32');
  fwrite(fid,sz(sz>1),'int32');
  fwrite(fid,tp,'int32');
  fwrite(fid,ne,'int32');
  fwrite(fid,data,class(data));
end
fclose(fid);

end

