function A2P( A , filename , start_pajek , Ess)
%A2P  exports an adjacency matrix into Pajek file
%  Usage: A2P( A , filename , start_pajek , Ess)
%  where:   A is a square adjacency matrix
%           FILENAME is a string containing the desired filename
%           START_PAJEK is a flag whether to start Pajek with the new file
%           ESS is a vector with important vertices (colored different)
%
%  Example: A2P(G3,'test.net',1) would create the file pajek/test.net and
%           open it in Pajek
%
%  Note:    A folder with the name 'pajek' should exist !
%
%  Last change:  10/2/2005 - Florian Knorn

if ~exist('A')
	error('Please input adjacency matrix !');
else
	if size(A,1) ~= size(A,2)
		error('Please input SQUARE matrix !');
	end
end

if nargin == 1
	filename = 'temp.net';
	start_pajek = 1;
end

if nargin < 4
	Ess = [];
end

if ~exist('filename')
	error('Please input filename (as a string) !');
else
	if ~ischar(filename)
		error('Filename must be a string !');
	end
end

if ~strmatch(filename,'.net')
	strcat(filename,'.net');
end

if ~exist('start_pajek')
	start_pajek = 0;
end

if (~isempty(find(A~=0 & A~=1)) & ~any(isnan(A)))
	A = logical(A);
end

n = size(A,1);
nans = findnans(A);

% open / create file and store handle
FID = fopen(strcat([pwd '\pajek\' filename]),'wt');

% print vertices
fprintf(FID,'*Vertices %i\n',n);

for i = 1:n
	if nans(i)
		fprintf(FID,'%i "%i" ic Black bc Black shape empty\n',i,i);
	else
		if isempty(Ess)
			fprintf(FID,'%i "%i" ic Red bc Black\n',i,i);
		else
			if ismember(i,Ess)
				fprintf(FID,'%i "%i" ic Red bc Black\n',i,i);
			else
				fprintf(FID,'%i "%i" ic LightGreen bc Black\n',i,i);
			end
		end
	end
end

% print edges or arcs, depending on whether A is symmetric or not
if ~length(find(A-A'>0))
	A = triu(A,1);
	fprintf(FID,'*Edges\n',n);
	for i = 1:n
		if nans(i) % deleted-row -> skip
			continue;
		else
			for j = 1:n
				if A(i,j) == 1
					fprintf(FID,'%i %i 1\n',i,j);
				end
			end
		end
	end
	disp('A is symmetric --> undirected graph exported to pajek');

else
	fprintf(FID,'*Arcs\n',n);
	for i = 1:n
		for j = 1:n
			if A(i,j) == 1 && ~isnan(A(i,j))
				fprintf(FID,'%i %i\n',i,j);
			end
		end
	end
	disp('A is not symmetric --> directed graph exported to pajek');

end

% close file
fclose(FID);

if start_pajek
	cd pajek % pajek creates some files; we don't want them in our working dir...
	pcmd = ['C:\Programme\Pajek\Pajek\PAJEK.exe ' pwd '\' filename '&'];
	system(pcmd);
	cd ..
end