## function count=edfwrite(filename,matrix,datatype,head)
## writes an image in esrf data format
## 
## datatype can be
##	uint8	= 8 bits	= UnsignedByte
##	uint16	= 16 bits	= UnsignedShort
##	uint32	= 32 bits	= UnsignedLong = UnsignedInteger
##	float32	= 		= Float = Real
##	float64 =		= DoubleValue = Double
## writes bigendian files
##
## head (optional) is a structure whose fields are written to the file
##
## 30.09.2009 (HSu): Modified to write header structures 
function count=edfwrite(filename,matrix,datatype,varargin)

  switch nargin
    case 3
      head=[];
    case 4
      head=varargin{1};
  end

  switch datatype
    case 'uint8',
      esrfdatatype='UnsignedByte';
      nbytes=1;
    case 'uint16',
      esrfdatatype='UnsignedShort';
      nbytes=2;
    case 'uint32',
      esrfdatatype='UnsignedLong';
      nbytes=4;
    case 'float32',
      esrfdatatype='Float';
      nbytes=4;
    case 'float64',
      esrfdatatype='DoubleValue';
      nbytes=8;
  end

  if isempty(head) || isstruct(head)
    head=writeheader(size(matrix),esrfdatatype,nbytes,1,head);
  end

  fid=fopen(filename,'w','b');
  fwrite(fid,head);
  fwrite(fid,matrix,datatype);
  fclose(fid);
endfunction
