function mat2bugs(varargin)
%MAT2BUGS - save matlab variables in S-PLUS format for BUGS
%
%mat2bugs(name1,value1,name2,value2,...)
%  Writes S-PLUS data specification to the standard output
%  for given variable names and values. 
%  Any number of name,value pairs can be given.
%
%mat2bugs(filename,name1,value1,name2,value2,...)
%  Writes S-PLUS data specification to the given file
%  for given variable names and values. 
%  Any number of name,value pairs can be given.
%
%mat2bugs(filename,name1,value1,dim1,name2,value2,...)
%  Writes S-PLUS data specification to the given file for
%  given variable names and values. Dim argument can be used
%  to force use of 1D or 2D tables (value 1 or 2 respectively)
%  Any number of name,value pairs can be given.
%
%Examples: 
%  mat2bugs('x',x,'y',y); 
%  mat2bugs('bugs_data.dat','x',x,'y',y); 
%  mat2bugs('bugs_inits.dat','mu',zeros(size(y)),'tau',1);
%  mat2bugs('bugs_inits.dat','Y',itr{i1},'Y2',itst{i1},1);
%
%BUGS: (no pun intended)
%  Supports only scalars and 1D and 2D tables. 3D tables would be
%  trivial to add.
%

% (c) jouko.lampinen@hut.fi, 1998-1999
% 2002-11-01 Aki.Vehtari@hut.fi - Added handling for NaN 
% 2003-01-14 Aki.Vehtari@hut.fi - Option to force use of 1D and 2D tables

if ischar(varargin{1}) & ischar(varargin{2})
  ofile=fopen(varargin{1},'w');
  if ofile<1, error(['Cannot open ' varargin{1}]); end
  i=2;
else
  ofile=1;
  i=1;
end

fprintf(ofile,'list(');
while i<nargin
  name=varargin{i};
  val=varargin{i+1};
  if i+2<=nargin & isnumeric(varargin{i+2})
    dim=varargin{i+2};
    i=i+3;
  else
    dim=0;
    i=i+2;
  end
  [r,c]=size(val);
  
  if r==1 & c==1 & dim==0
    fprintf(ofile,'%s=',name);
    fprintval(ofile,val);
  elseif c==1 & dim<2
    fprintf(ofile,'%s=c(',name);
    for k=1:(r-1), 
      fprintval(ofile,val(k));
      fprintf(ofile,', '); 
    end
    fprintval(ofile,val(r));
    fprintf(ofile,')');
  else
    fprintf(ofile,'%s=structure(\n  .Data=c(\n',name);
    for k=1:r,
      fprintf(ofile,'\t');
      for l=1:(c-1)
        fprintval(ofile,val(k,l));
        fprintf(ofile,', ');
      end
      if k<r,
        fprintval(ofile,val(k,c));
        fprintf(ofile,',\n');
      else
        fprintval(ofile,val(k,c));
        fprintf(ofile,'),\n');
      end
    end
    fprintf(ofile,'  .Dim=c(%G,%G))',r,c);
  end
  if i<nargin
    fprintf(ofile,',\n');
  end
end
fprintf(ofile,')\n');
if ofile>2, fclose(ofile); end

function fprintval(ofile, val)
if isnan(val)
  fprintf(ofile,'NA');
else
  fprintf(ofile,'%G',val);
end
