function r=mat2vpt(m, fn, objname, res)
% usage: mat2vpt(m, fn, objname, res)
% Writes the matrix "m" out in CSIM's VPT format.
%   input: m       The input matrix
%   input: fn      The output file name (default=geom.dat)
%   input: objname The name of the object (default=TestObj)
%   input: res     The grid resolution of the matrix

if (~exist('fn') | isempty(fn)) fn = 'geom.dat'; end;
if (~exist('objname') | isempty(objname)) objname = 'TestObj'; end;
if (~exist('res') | isempty(res)) res = 100; end;

f = fopen(fn,'w');
if (~f) fprintf('Could not open output file: %s\n',fn); return; end;
[r,c]=size(m);

fprintf(f,'<set_camera>\n');
fprintf(f,'  <frustum fov="45.0" near_field="100.0" far_field="10000.0"/>\n');
fprintf(f,'  <position x="0.0" y="%f" z="0.0"/>\n', max(max(m)) );
fprintf(f,'  <pointat x="%f" y="0" z="%f"/>\n', res*(c-1),res*(r-1) );
fprintf(f,'</set_camera>\n');

fprintf(f,'<def_obj> %s\n', objname );

fprintf(f,'<col 1 0 0 0.5/>\n');
for ii=1:r-1,
  for jj=1:c-1,
    fprintf(f,'  <quad2> <vrt x="%f" y="%f" z="%f" /> <vrt x="%f" y="%f" z="%f" /> <vrt x="%f" y="%f" z="%f" /> <vrt x="%f" y="%f" z="%f" /> </quad2>\n', ...
            res*(jj-1),m(ii,jj),res*(ii-1), res*(jj-1),m(ii+1,jj),res*ii , ...
            res*jj,m(ii+1,jj+1),res*ii, res*jj,m(ii,jj+1),res*(ii-1) );
  end;
end;

fprintf(f,'</def_obj>\n');
fprintf(f,'<inst_obj name="%s" x="0" y="0" z="0" xang="0" yang="0" zang="0" </inst_obj>\n', objname,objname );
fclose(f);
