function [P,E] = MshToMatlab2D(filename)

% parser to generate matrices containing information about mesh from gmsh output (*.msh)

% filename...path to the *.msh file

% P...matrix of coordinates of nodes in the mesh
% E...elements of the grid = triangles

fileID = fopen(filename,'r');

fileline = fgetl(fileID);
% nalezeni radku, ve kterem je "$Nodes"
while ~strcmp('$Nodes',fileline)
	fileline = fgetl(fileID);
end    
% pocet Nodes
n_p = fscanf(fileID,'%d',1);            
P = fscanf(fileID,'%d %f %f %f',[4, n_p]);
P([1, 4],:) = [];

% nalezeni radku, ve kterem je "$Elements"
while ~strcmp('$Elements',fileline)
	fileline = fgetl(fileID);
end  
% pocet Elements          
n_e = fscanf(fileID,'%d',1); 
E = zeros(3,n_e); 
elements = 1;
for i = 1:n_e
	% nacteni prvnich 2 cisel v radku, druhe znaci druh elementu
	data = fscanf(fileID,'%d %d',2);
   	if data(2) == 2
   		% nacteni zbytku radku - info o trojuhelniku
    	data = fscanf(fileID,'%d %d %d %d %d %d',6);
   		E(:,elements) = data((end - 2):end);
   		elements = elements + 1;
	else
		% posunuti na dalsi radek  
		fgetl(fileID);
	end                
end
E(:,elements:end) = [];       

fclose(fileID);

end
