function write_surf(fname, vertex_coords, faces)

%
% write_surf(fname, vertex_coords, faces)
% Writes vertex coordinates and triangle faces to a FreeSurfer surface file
%
% write_surf.m
%
% Original Author: Jay Dubb
%
% Copyright (C) 2012,
% The General Hospital Corporation (Boston, MA). 
% All rights reserved.
%
faces = faces-1;

TRIANGLE_FILE_MAGIC_NUMBER =  16777214 ;

nv = size(vertex_coords,1);
nf = size(faces,1);

fid = fopen(fname, 'wb', 'b') ;
fwrite3(fid, TRIANGLE_FILE_MAGIC_NUMBER) ;
fprintf(fid, 'Generated by Freesurfer matlab toolbox function write_surf.m\n\n');
fwrite(fid, nv, 'int32');
fwrite(fid, nf, 'int32');
fwrite(fid, vertex_coords(:,1:3)', 'float32'); 
fwrite(fid, faces(:,1:3)', 'int32'); 
fclose(fid);


    
    
