function [atoms,specs,bonds]=loadmolecule(f)
%LOADMOLECULE Load molecule specification from a .bs file.
%
%[atoms,spec,bonds]=loadmolecule(f)
%f
%atoms - struct with fields type and pos.
%        atoms.type - cell array containing the type of each atom in
%                     the molecule.
%        atoms.pos  - nx3 matrix with the 3d position of each atom
%                     within the molecule.
%spec  - struct with fields radius and color.
%        spec.radius - vector with radii of the spheres to plot for each
%                      atom type.
%        spec.color  - nx3 matrix with the color for each atom type.
%bonds - struct with fields type, range, radius, and color.
%        bonds.type   - cell array with the atom types for this bond as
%                       'type1;type2', where type1<type2.
%        bonds.range  - the range in which the bond is active, i.e.
%                       should be plotted.
%        bonds.radius - the radius of the plotting cylinder.
%        bonds.color  - the color of the plotting cylinder.

% v1.0  2000-10-27. Niclas Borlin, niclas@cs.umu.se.

fid=fopen(f,'rt');

if (fid<0)
	error('Couldn''t open file.');
end

atoms.type={};
atoms.pos=[];
specs.type={};
specs.radius=[];
specs.color=[];
bonds.type={};
bonds.range=[];
bonds.radius=[];
bonds.color=[];

while (~feof(fid))
	% Get each line.
	l=fgetl(fid);
	% Get first word.
	[id,rest]=strtok(l);
	% What type?
	if (~isempty(id))
		switch (id)
		case 'atom'
			% Atom format is 'atom type x y z'
			[type,rest]=strtok(rest);
			atoms.type{end+1}=type;
			atoms.pos(end+1,:)=sscanf(rest,'%f %f %f');
		case 'spec'
			% Spec format is 'spec type radius color'
			[type,rest]=strtok(rest);
			specs.type{end+1}=type;
			s=sscanf(rest,'%f ');
			specs.radius(end+1)=s(1);
			color=s(2:end);
			% This will allow both 1-value colors and 3-value colors.
			if (length(color)==1)
				color=color*[1,1,1];
			end
			specs.color(end+1,:)=color;
		case 'bonds'
			% Spec format is 'spec type radius color'
			[type1,rest]=strtok(rest);
			[type2,rest]=strtok(rest);
			% Construct sorted lookup string.
			sorted=cellstr(sort(strvcat(upper(type1),upper(type2),';')));
			lookup=strcat(sorted{[2,1,3]});
			bonds.type(end+1)={lookup};
			s=sscanf(rest,'%f ');
			bonds.range(end+1,:)=s(1:2);
			bonds.radius(end+1)=s(3);
			color=s(4:end);
			if (length(color)==1)
				color=color*[1,1,1];
			end
			bonds.color(end+1,:)=color;
		otherwise
			% Ignore all other rows.
		end
	end
end

fclose(fid);
