function showcgts(fname)
%SHOWCGTS Plot a gts file.
%   SHOWCGTS(fname) plots the contents of a GTS file, taking
%   into account colorization.  GTS is the GNU Triangulated
%   Surface Library.
%
%   SHOWCGTS(fname) will plot all triangles contained in fname.
%   If fname contains no triangles, all edges will be plotted.
%   If fname contains no edges, all points will be plotted.
%
%   At this time, SHOWGTS requires Matlab R12 because of it use
%   of the UNION command.

fid = fopen (fname, 'r');
A = fscanf (fid, '%i %i %i');
fclose (fid);

np = A(1); 
ne = A(2); 
nf = A(3); 
clear A;
% figure;
X = dlmread (fname, ' ', [1 0 np 2]);

if (ne == 0)
   plot3 (X(:,1), X(:,2), X(:,3), 'ko');
   axis equal;
   axis off;
else
   edg = dlmread (fname, ' ', [np+1 0 np+ne 1]);
   if (nf == 0)
      for (ii = 1:ne)
         linX(:, ii) = X(edg(ii, :), 1);
         linY(:, ii) = X(edg(ii, :), 2);
         linZ(:, ii) = X(edg(ii, :), 3);
      end
      line (linX, linY, linZ, 'Color', [0 0 0])
      axis equal
      axis off
   else
      fac = dlmread (fname, ' ', [np+ne+1 0 np+ne+nf 3]);

      facX = zeros (3, nf);
      facY = zeros (3, nf);
      facZ = zeros (3, nf);

      for (ii = 1:nf)
         V = union (edg(fac(ii, 1:3), 1), edg(fac(ii, 1:3), 2)); 
         facX(:, ii) = X(V, 1);
         facY(:, ii) = X(V, 2);
         facZ(:, ii) = X(V, 3);
      end

      colorflag = fac(:, 4);
      cref = unique (colorflag);
      cmap = colormap (hsv (length (cref)));
      colormap (cmap);
      for (i = 1:length (colorflag))
         color(i) = find (cref == colorflag(i));
      end
      
      fill3 (facX, facY, facZ, color)
      axis equal
      axis off
   end
end