function [P,E,E_partitions,E_partitions_neighbours] = MshToMatlab2D_with_partitions(filename)

% format converter to convert gmsh output (*.msh) to matrices containing information about the mesh

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

% P...matrix of coordinates of nodes in the mesh
% E...elements of the mesh = 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);
E_partitions = zeros(1,n_e);
E_partitions_neighbours = cell(1,n_e);
elements = 1;
for i = 1:n_e
	% nacteni prvnich 3 cisel v radku, druhe znaci druh elementu
	element_type = fscanf(fileID,'%d %d %d',3);
   	if element_type(2) == 2
   		n_tags = element_type(3);
        dummy = fscanf(fileID,'%d %d %d',3);
        E_partitions(elements) = fscanf(fileID,'%d',1);
        n_neighbours = n_tags - 4;
        if n_neighbours > 0
            neighbours = zeros(n_neighbours,1);
            for j = 1:n_neighbours
                neighbours(j) = fscanf(fileID,'%d',1);
            end
            E_partitions_neighbours{elements} = abs(neighbours);
        end
        vertices = fscanf(fileID,'%d %d %d',3);
   		E(:,elements) = vertices;
   		
        if n_neighbours > 0
            clear neighbours;
        end
   		elements = elements + 1;
	else
		% posunuti na dalsi radek  
		fgetl(fileID);
	end                
end
E(:,elements:end) = [];
E_partitions(:,elements:end) = [];
E_partitions_neighbours(:,elements:end) = [];

fclose(fileID);

end