function savevrml(node, face, elem, fname)
%
% savevrml(node,face,elem,fname)
%
% save a surface mesh to VRML 1.0 format
%
% author: Qianqian Fang, <q.fang at neu.edu>
% date: 2010/04/25
%
% input:
%      node: input, surface node list, dimension (nn,3)
%      face: input, surface face element list, dimension (be,3)
%      elem: input, tetrahedral element list, dimension (ne,4)
%      fname: output file name
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

if (nargin == 2)
    fname = face;
    face = [];
    elem = [];
end

if (nargin == 3)
    fname = elem;
    elem = [];
end

fid = fopen(fname, 'wt');
if (fid == -1)
    error('You do not have permission to save mesh files.');
end

fprintf(fid, '#VRML V1.0 ascii\n#Generated by iso2mesh (http://iso2mesh.sf.net)\n');
fprintf(fid, 'Separator {\nSwitch {\n\tDEF %s\n\tSeparator {\n', fname);

if (~isempty(node))
    node = node(:, 1:3);
    fprintf(fid, '\t\tCoordinate3 {\n\t\t\tpoint [\n');
    fprintf(fid, '%.16f %.16f %.16f,\n', node');
    fprintf(fid, '\t\t\t]\n\t\t}\n');
end

if (~isempty(face))
    face = face(:, 1:3);
    fprintf(fid, '\t\tIndexedFaceSet {\n\t\t\tcoordIndex [\n');
    fprintf(fid, '%d %d %d -1\n', (face - 1)');
    fprintf(fid, '\t\t\t]\n\t\t}\n');
end

fprintf(fid, '\t} # Separator\n}\n}\n');

fclose(fid);
