function b = bytesof(a,varargin);

% BYTESOF(A) returns a UINT8 array with the bytes of A.
% BYTESOF(A,OPT,...) controls
% endianness: 'l'ittle 'b'ig 'n'ative (default)
% out shape : 'a'rray  [ELEMENTSIZE(A),SIZE(A)] (default)
% 	      'm'atrix [ELEMENTSIZE(A),PROD(SIZE(A))]
%             'v'ector [ELEMENTSIZE(A)*PROD(SIZE(A)),1] (only option for struct)
% If A is a structure, returns bytes of all fields in a vector.
%
% [+GenLib General Purpose Library+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

if nargin == 0, error('Missing input argument'), end

% options
endian = 'n'; vector = 'a';
for k = 1:nargin-1
 opt = lower(varargin{k}); opt(2:end) = '';
 switch opt
  case {'l','n','b'}, endian = opt;
  case {'v','a','m'}, vector = opt;
  otherwise, error('Invalid option')
 end
end

% native endianness
persistent native
if isempty(native)
 b = bytesofmex(uint32(1));
 if isequal(b,uint8([0;0;0;1]))
  native = 'l';
 elseif isequal(b,uint8([1;0;0;0]))
  native = 'b';
 else
  native = 'n';
 end
end
  
if isnumeric(a)
 b = bytesofmex(a);
 switch [native endian]
  case {'lb','bl'}, b = flipud(b);
  case {'nb','nl'}, error('Unknown native endianness')
 end
 switch vector
  case 'v', b = b(:);
  case 'a', b = reshape(b,[size(b,1),size(a)]);
 end
elseif isstruct(a)
 b = [];
 fields = fieldnames(a);
 for k = 1:length(fields)
  b = [b;bytesof(getfield(a,fields{k}),endian,'vector')];
 end
end
 
