function varargout = loadxdr(file,form)

% LOADXDR   Load an XDR data file
%   [P1,P2,...] = LOADXDR(FILE) loads data from a file written in the machine
%   independant format XDR. Variables are returned in the order they were saved.
%   [VALUES,NAMES] = LOADXDR(FILE,1) returns the variable contents in the cell
%   array VALUES and their names in NAMES. STRUC = LOADXDR(FILE,2) returns
%   a structure.
%
% [+GenLib General Purpose Library+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

xdrid = fopen(file,'r','ieee-be');
if xdrid < 0, error(['"' file '" not found.']), end

names = {}; k = 0;
while 1
 k = k + 1;
 
 % variable header
 [header,cnt] = fread(xdrid,5,'int32');
 if cnt == 0, break, end
 if cnt ~= 5, error('cannot read file.'), end
 if header(1) > 99, error('bad XDR format (bad variable type).'), end

 % variable name
 header(5) = ceil(header(5)/4)*4;
 [name,cnt] = fread(xdrid,header(5),'char');
 if cnt ~= header(5), error('cannot read file.'), end
 names{k} = char(name(name>0)');

 % data
 for kri = 0:header(4)
  if kri, y = x; end
  switch floor(header(1)/10)
   case 0, [x,cnt] = fread(xdrid,header(2:3)','float64');
   case 1, [x,cnt] = fread(xdrid,header(2:3)','float32');
   case 2, [x,cnt] = fread(xdrid,header(2:3)','int32');
   case 3, [x,cnt] = fread(xdrid,header(2:3)','int16');
   case 4, [x,cnt] = fread(xdrid,header(2:3)','uint16');
   otherwise, error('bad XDR format (bad variable type).')
  end
  if cnt ~= prod(header(2:3)), error('cannot read file.'), end
  if kri, x = y + sqrt(-1)*x; end
 end
 
 % text variable
 if rem(header(1),2), x = char(x); end
 
 if form == 2
  varargout{1}.(names{k}) = x;
 else
  varargout{k} = x;
 end
end
fclose(xdrid);

if nargin > 1 && form == 1
 varargout = {varargout,names};
end
