function xvsout(fname, t, x, u)
% xvs Writes output from 1+1 FD code in asctoxvs format [PHYS210-xvs]
%
% Input arguments
%
%     fname (character string): Name of output file.
%
%     t (real 1D array, length nt): Contains output times. 
%
%     x (real 1D array, length nx): Contains output x coordinates.
%
%     u (real 2D array, dimensions nx x nt): contains function values.
%
% Input arguments
%
%     NONE
% 
% Once a datafile has been created via a call to this function, send 
% the data in it to xvs using asctoxvs (invoked from the bash/terminal
% command line, NOT within Matlab
%
%     asctoxvs <fname>
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
   R = 'xvsout';

   % BEGIN argument processing / checking ...
   err = 0;
   nt = 0;
   nx = 0;

   % Need exactly 4 arguments ...
   if nargin ~= 4
      fprintf('%s: Must be called with at exactly 4 arguments.\n', R);
      return;
   end
 
   % Check that fname is a string ...
   if ~ ischar(fname)
      fprintf('%s: 1st argument [fname] must be a string.\n', R);
      err = 1;
   end

   % Check that t is a vector; if it is, set nt to its length ...
   if ~ isvector(t) 
      fprintf('$s: 2nd argument [t] must be a vector.\n', R);
      err = 1;
   else
      nt = length(t);
   end

   % Check that x is a vector; if it is, set nt to its length ...
   if ~ isvector(x) 
      fprintf('%s: 3rd argument [x] must be a vector.\n', R);
      err = 1;
   else
      nx = length(x);
   end

   % Check rank and dimensions of u ...
   szu = size(u);
   ranku = length(szu);
   if ranku ~= 2
      fprintf('%s: 4th argument [u] must be a 2D array.\n', R);
      err = 1;
   else
      if szu(1) ~= nx || szu(2) ~= nt
         fprintf('%s: 4th argument should be %d x %d but is %d x %d\n', ...
            R, nx, nt, szu(1), szu(2));
         err = 1;
      end
   end

   if err 
      fprintf('%s: One or more errors detected in input arguments.\n', R);
      fprintf('%s: Aborting without writing to file.\n', R);
      return
   end
   % ... END argument processing / checking

   % Open file for write ...
   fid = fopen(fname, 'w');
   if fid < 0  
      fprintf('nbodyout: Error opening ''%s'' for write.\n', R, fname);
      return;
   end

   for n = 1 : nt
      % Write time ...
      fprintf(fid, '%24.16e\n', t(n));
      fprintf(fid, '%d\n', nx);
      % Write x(:), u(n,:) ...
      fprintf(fid, '%24.16e %24.16e\n', reshape([x; u(:,n)'], 1, 2*length(x)));
   end

   % Close file and return ...
   fclose(fid);
end
