function xcircuit(file, x, y, xyratio) 
% XCIRCUIT (FILE, X, Y, XYRATIO)
%      generate a xcircuit library file that has one object: the line 
%               with the given x and y coordinates
%      inputs: 
%	     FILE - the name of output xcircuit library file 
%		X - the vector of x co-ordinates
%		Y - the vector of y co-ordinates of same length as X
%	  XYRATIO - the ratio between x and y axis, similar to MATLAB 
%                    Axes option PlotBoxAspectRatio
%      output:  the file with name FILE

% Author: Zhengdao Wang, Ph.D student, ECE dept. UMN
% Date: Sept. 21 1999
% Email: zhengdao@ece.umn.edu

M=1000;  % points per polygon. Change this to a smaller value 
	 % if you have printer memory overflow problem
P=300;   % polygons per object

if exist('xyratio')~=1
	xyratio=1;
end
MAX=500; MIN=-200;
N=length(x);
K=ceil(N/M);  % total number of polygons
K1=ceil(K/P); % total number of first level objects

if (xyratio > 1) 
	MAXX=MAX; 
	MAXY=floor((MAX-MIN)/xyratio)+MIN;
else
	MAXY=MAX; 
	MAXX=floor((MAX-MIN)*xyratio)+MIN;
end
	
allminx=min(x);
allmaxx=max(x);
allminy=min(y);
allmaxy=max(y);
x=round(MIN+(MAXX-MIN)/(allmaxx-allminx)*(x-allminx));
y=round(MIN+(MAXY-MIN)/(allmaxy-allminy)*(y-allminy));


a='a'+1-1';
z='z'+1-1;
name=char(randint(1,4,[a z]));
fid=fopen(file, 'w');
if (fid==-1)
	error('file ''%s'' cannot be opened', file);
end
fprintf(fid, '%%! PostScript set of library objects for XCircuit\n');
fprintf(fid, '%%  Library name is: 11\n');
fprintf(fid, '%%  Version: 2.0\n');
fprintf(fid, '%%\n');
fprintf(fid, '%%\n\n');
fprintf(fid, '%% XCircuitLib library built-in objects\n');

% first level objects (each contains <= P polygons)
for k1=1:K1 
	fprintf(fid, '/%s%d {\n', name, k1);
	s1=max(M*P*(k1-1), 1);
	s2=min(s1+M*P, N);
	minx=min(x(s1:s2));
	maxx=max(x(s1:s2));
	miny=min(y(s1:s2));
	maxy=max(y(s1:s2));
	fprintf(fid, '%% %d %d %d %d bbox\n', minx, miny, ...
		maxx-minx, maxy-miny);
	fprintf(fid, 'begingate\n');
	if (K1>1)
		fprintf(fid, '%% hidden\n');
	end
	for p=1:min(K-P*(k1-1), P)  % polygons
		pstart=max(M*P*(k1-1)+M*(p-1), 1);    
		pend=min(pstart+M, N);
		polysegs=pend-pstart;
		fprintf(fid, '1  1.00');
		for m=0:polysegs
			n=pstart+m;
			if rem(m, 7)==0
				fprintf(fid, '\n');
			end
			fprintf(fid, ' %d %d', x(n), y(n));
		end
		fprintf(fid, ' %d polygon\n', polysegs+1);
	end
	fprintf(fid, 'endgate\n');
	fprintf(fid, '} def\n\n');
end

% the second level object (in case there are more than one first-level objects)
if (K1>1)
	fprintf(fid, '/%s_ {\n', name);
	fprintf(fid, '%% %d %d %d %d bbox\n', MIN, MIN, MAXX-MIN, MAXY-MIN);
	fprintf(fid, 'begingate\n');
	for m=1:K1
		fprintf(fid, '1.00 0 0 0 %s%d\n', name, m);
	end
	fprintf(fid, 'endgate\n');
	fprintf(fid, '} def\n\n\n');
end

fprintf(fid, '%% EndLib');
fclose(fid);
