function savexdr(file,varargin)

% SAVEXDR   Save data in an XDR file
%   SAVEXDR('FILE',P1,P2,...) saves P1,P2,... in FILE with the machine
%   independant format XDR.
%
% [+GenLib General Purpose Library+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

xdrid = fopen(file,'w','ieee-be');
if xdrid < 0, error(['"' file '" cannot be created.']), end

for k = 1:nargin-1

 name = [inputname(k+1) 0];
 name = [name zeros(1,ceil(length(name)/4)*4-length(name))];

 % variable header
 if ndims(varargin{k}) > 2, error(['"' inputname(k+1) '" is not a matrix.']), end
 switch class(varargin{k})
  case 'double', header = 0;
  case 'char', header = 21;
  otherwise, error(['"' inputname(k+1) '" class is neither "double" nor "char".'])
 end 
 header = [header size(varargin{k}) ~isreal(varargin{k}) length(name)];
 cnt = fwrite(xdrid,header,'int32');
 if cnt ~= 5, error('cannot write file.'), end

 % variable name
 cnt = fwrite(xdrid,name,'char');
 if cnt ~= header(5), error('cannot write file.'), end

 % data
 for kri = 0:header(4)
  if kri
   x = imag(varargin{k});
  else
   x = real(varargin{k});
  end
  switch header(1)
   case 0,  cnt = fwrite(xdrid,x,'float64');
   case 21, cnt = fwrite(xdrid,x,'int32');
  end
  if cnt ~= prod(header(2:3)), error('cannot write file.'), end
 end
 
end
fclose(xdrid);
