function [mesh_file, meshstruct] = CSGMethod(mainguifighandle,varargin);
% [FILE, MESH] = CSGMethod(FIGHANDLE) 
% This function accepts the handle to the main GUI figure FIGHANDLE and returns
% the string FILE with the name of the mesh file and the struct MESH. It
% loads the variables p, e, and t which are the results of running the  
% CSG Toolbox. The struct MESH has the following fields:
%     MESH.size     = [number of elements , 
%                      number of global nodes , 
%                      number of nodes per element , 
%                      global number of degrees of freedom , 
%                      number of degrees of freedom per element] 
%     MESH.xcoords  = [1 x (number of nodes)] X coordinate of each node
%     MESH.ycoords  = [1 x (number of nodes)] Y coordinate of each node
%     MESH.connect  = [(number of elements) x 3] connectivity array
%     MESH.edges    = [7 x (number of edge elements)] : information about mesh boundaries
%                                 row 1: first node number
%                                 row 2: second node number
%                                 row 3: first node parameter (not used)
%                                 row 4: second node parameter (not used)
%                                 row 5: boundary number
%                                 row 6: first subdomain number 
%                                 row 7: second subdomain number 

% prompt for mesh file name if need be
if nargin>1
    mesh_file = varargin{1}; fn=mesh_file;
else
    filterspec = '*.mat';
    title = 'Choose mesh file';
    [mesh_file,mesh_path] = uigetfile(filterspec, title);
    fn=fullfile(mesh_path,mesh_file);
end

% load the mesh file
ToggleStatus(1,mainguifighandle);
eval(['load(''',fn,''');']);%p e t

%initialize important mesh variables
numels = size(t,2); % # of elements
numnp = size(p,2);  % # of nodal points
numeq = 2*numnp;    % # of global equations
nnpe = 3;           % # of nodes per element
ndof = nnpe*2;      % # of degrees of freedom in each element
x = p(1,:);         % x coordinates of all nodal points
y = p(2,:);         % y coordinates of all nodal points
np = t(1:3,:)';     % connectivity array

%remove any internal edges
edges=e(:,find(~min(e(6:7,:))));
curnums=edges(5,:);
[junk1,junk2,newnums]=unique(curnums);
edges(5,:)=newnums;

% output the structure and indicate WAITING in main GUI figure
meshdata(1) = numels;
meshdata(2) = numnp;
meshdata(3) = nnpe;
meshdata(4) = numeq;
meshdata(5) = ndof;

meshstruct = struct('size',meshdata,...
    'xcoords', x,...
    'ycoords', y,...
    'connect', np,...
    'edges', edges);

ToggleStatus(0,mainguifighandle);



