# DL_POLY Configuration Import / Export (for v1.2+)
# Created:	 25/03/2009
# Last modified: 17/03/2011
# ChangeLog:
# 	17/03/2011 - Added custom dialog options to control level or written data and half-cell shift in CONFIG files.
# 	16/09/2009 - Expression export filter now uses atom type names rathern than ffbound type names. FF term loop styles updated.
#	11/06/2009 - Fixed counting and output of constraint terms in FIELD export. 'nvdw' section corrected to 'vdw'.

filter(type="importmodel", name="DL_POLY Configuration", extension="CONFIG,REVCON,config,revcon", glob="*CON*",exact="CONFIG,REVCON,config,revcon",nickname="dlpoly",id=2)
{
	# Variable Declaration
	string e, title;
	int n,keytrj,imcon;
	double ax,ay,az,bx,by,bz,cx,cy,cz;
	double rx,ry,rz,vx,vy,vz,fx,fy,fz;

	option("DL_POLY uses fractional cell coordinates ranging from -0.5 to +0.5", "label", "centre");
	option("while Aten uses 0 to 1.0. The option below, if checked, will convert", "label", "newline", "centre");
	option("DL_POLY to Aten coordinates by shifting all atoms by one half of the unit cell.", "label", "newline", "centre");
	int cellshift = option("Shift input coordinates by half cell", "check", 1, "newline");

	#aten.prefs.zmap = "ff";

	# Title section
	getline(title);
	newmodel(title);
	readline(keytrj,imcon);

	# Cell (if present)
	if (imcon != 0)
	{
		readline(ax,ay,az);
		readline(bx,by,bz);
		readline(cx,cy,cz);
		cellaxes(ax,ay,az,bx,by,bz,cx,cy,cz);
	}

	# Atoms
	while (!eof())
	{
		readline(e);
		readline(rx,ry,rz);
		newatom(e,rx,ry,rz);
		if (keytrj > 0)
		{
			readline(vx,vy,vz);
			setvelocities(vx,vy,vz);
		}
		if (keytrj > 1)
		{
			readline(fx,fy,fz);
			setforces(fx,fy,fz);
		}
	}
	
	# Shift atoms if requested
	if (cellshift)
	{
		selectall();
		translatecell(0.5,0.5,0.5);
		selectnone();
	}

	rebond();
	fold();
	finalisemodel();
}

filter(type="exportmodel", name="DL_POLY Configuration", extension="CONFIG,REVCON,config,revcon", glob="*CON*", exact="CONFIG,REVCON,config,revcon", nickname="dlpoly", id=2)
{
	# Variable Declaration
	int n,imcon;
	atom i;

	int keytrj = option("keytrj", "radiogroup");
	option("Coordinates", "radio", "keytrj", 1, "group=Atom Data Export", "newline");
	option("Coordinates and velocties", "radio", "keytrj", 0, "group=Atom Data Export", "newline");
	option("Coordinates, velocties and forces", "radio", "keytrj", 0, "group=Atom Data Export", "newline");
	option("DL_POLY uses fractional cell coordinates ranging from -0.5 to +0.5", "label", "newline", "centre");
	option("while Aten uses 0 to 1.0. The option below, if checked, will convert", "label", "newline", "centre");
	option("Aten to DL_POLY coordinates by shifting all atoms by one half of the unit cell.", "label", "newline", "centre");
	int cellshift = option("Shift input coordinates by half cell", "check", 1, "newline");

	# Get current model
	model m = aten.frame;

	# Title section
	writeline(m.name);

	# Convert celltype string to DL_POLY-style integer
	if (m.cell.type == "none") imcon = 0;
	else if (m.cell.type == "cubic") imcon = 1;
	else if (m.cell.type == "orthorhombic") imcon = 2;
	else if (m.cell.type == "parallelepiped") imcon = 3;
	writelinef("%10i%10i\n",keytrj-1,imcon);

	# Cell (if present) 
	if (imcon <> 0)
	{
		writelinef("%20.12f%20.12f%20.12f\n",m.cell.ax, m.cell.ay, m.cell.az);
		writelinef("%20.12f%20.12f%20.12f\n",m.cell.bx, m.cell.by, m.cell.bz);
		writelinef("%20.12f%20.12f%20.12f\n",m.cell.cx, m.cell.cy, m.cell.cz);
	}

	# Atoms
	vector v;
	for (n = 1; n <= m.natoms; ++n)
	{
		# Get variable pointer to make manipulation a little less cluttered
		i = m.atoms[n];
		if (i.type == 0) writelinef("%-8s%10i%20f\n",i.symbol,i.id,i.mass);
		else writelinef("%-8s%10i%20f\n",i.type.name,i.id,i.type.mass);
		if (cellshift) v = m.cell.translateatom(i,-0.5,-0.5,-0.5);
		else v = i.r;
		writelinef("%20.14f%20.14f%20.14f\n", v.x, v.y, v.z);
		if (keytrj > 1) writelinef("%20.14f%20.14f%20.14f\n",i.vx,i.vy,i.vz);
		if (keytrj > 2) writelinef("%20.14f%20.14f%20.14f\n",i.fx,i.fy,i.fz);
	}
}


filter(type="importtrajectory", name="DL_POLY Unformatted History", extension="HISu", glob="*HISu", exact="HISTORY", nickname="dlpolyu")
{
	# Since its a Fortran code, each record in the file is preceded and followed by an integer specifying
	# the record size in characters.

	int readheader()
	{
		int intsize=4, realsize=8, recsize;

		# First line is 80-character header.
		recsize = readint(intsize);
		if (recsize == 40)
		{
			printf("No header found in unformatted DL_POLY trajectory file. Assuming a restarted trajectory...\n");
			rewind();
			return TRUE;
		}
		else if (recsize != 80)
		{
			printf("File '%s' doesn't appear to be a DL_POLY Unformatted trajectory.\n", filterfilename());
			return FALSE;
		}
		string title = readchars(recsize);
		recsize = readint(intsize);

		# Next, number of atoms in the system (as a double)
		recsize = readint(intsize);
		int natoms = nint(readdouble());
		recsize = readint(intsize);

		# Atom names
		recsize = readint(intsize);
		skipchars(recsize);
		recsize = readint(intsize);

		# Atomic masses
		recsize = readint(intsize);
		skipchars(recsize);
		recsize = readint(intsize);

		# Atom charges
		recsize = readint(intsize);
		skipchars(recsize);
		recsize = readint(intsize);
		
		return TRUE;
	}

	int readframe()
	{
		int intsize=4, realsize=8, recsize;

		# Variables
		double mass,q,tstep;
		double axes[9];
		string title;
		int natoms, nstep, keytrj, imcon, n;

		# First data for frame is : nstep, $natoms, keytrj, imcon, tstep, all as doubles 
		recsize = readint(intsize);
		if (recsize != 5*realsize) { printf("Error reading start of trajectory frame.\n"); return FALSE; }
		nstep = nint(readdouble(realsize));
		natoms = nint(readdouble(realsize));
		keytrj = nint(readdouble(realsize));
		imcon = nint(readdouble(realsize));
		tstep = readdouble(realsize);
		recsize = readint(intsize);
		verbose("nstep = %i, natoms = %i, keytrj = %i, imcon = %i, tstep = %f\n", nstep, natoms, keytrj, imcon, tstep);
		title = "t = " + ftoa(tstep) + ", n = " + itoa(nstep);
		setname(title);

		# Create temporary data arrays for reading
		double x[natoms], y[natoms], z[natoms];

		# Unit cell
		if (imcon != 0)
		{
			recsize = readint(intsize);
			if (recsize != 9*realsize) { printf("Error reading cell info from trajectory frame.\n"); return FALSE; }
			readdoublearray(axes,9);
			recsize = readint(intsize);
			cellaxes(axes[1],axes[2],axes[3],axes[4],axes[5],axes[6],axes[7],axes[8],axes[9]);
		}

		# Template atoms in parent model
		modeltemplate();
		if (aten.model.natoms != natoms) { printf("Parent model contains different number of atoms to trajectory - aborting.\n"); return FALSE; }

		# Coordinates
		recsize = readint(intsize);
		if (recsize != natoms*realsize) { printf("Error reading coordinate info from trajectory frame.\n"); return FALSE; }
		if (!readdoublearray(x,natoms)) { printf("Error reading x-coordinates from trajectory frame.\n"); return FALSE; }
		recsize = readint(intsize);
		recsize = readint(intsize);
		if (!readdoublearray(y,natoms)) { printf("Error reading y-coordinates from trajectory frame.\n"); return FALSE; }
		recsize = readint(intsize);
		recsize = readint(intsize);
		if (!readdoublearray(z,natoms)) { printf("Error reading z-coordinates from trajectory frame.\n"); return FALSE; }
		recsize = readint(intsize);
		for (n = 1; n<= natoms; ++n) setcoords(x[n], y[n], z[n], n);

		# Velocities
		if (keytrj > 0)
		{
			recsize = readint(intsize);
			if (recsize != natoms*realsize) { printf("Error reading velocity info from trajectory frame.\n"); return FALSE; }
			if (!readdoublearray(x,natoms)) { printf("Error reading x-velocities from trajectory frame.\n"); return FALSE; }
			recsize = readint(intsize);
			recsize = readint(intsize);
			if (!readdoublearray(y,natoms)) { printf("Error reading y-velocities from trajectory frame.\n"); return FALSE; }
			recsize = readint(intsize);
			recsize = readint(intsize);
			if (!readdoublearray(z,natoms)) { printf("Error reading z-velocities from trajectory frame.\n"); return FALSE; }
			recsize = readint(intsize);
			for (n = 1; n<= natoms; ++n) setvelocities(x[n], y[n], z[n], n);
		}

		# Forces
		if (keytrj > 1)
		{
			recsize = readint(intsize);
			if (recsize != natoms*realsize) { printf("Error reading force info from trajectory frame.\n"); return FALSE; }
			if (!readdoublearray(x,natoms)) { printf("Error reading x-forces from trajectory frame.\n"); return FALSE; }
			recsize = readint(intsize);
			recsize = readint(intsize);
			if (!readdoublearray(y,natoms)) { printf("Error reading y-forces from trajectory frame.\n"); return FALSE; }
			recsize = readint(intsize);
			recsize = readint(intsize);
			if (!readdoublearray(z,natoms)) { printf("Error reading z-forces from trajectory frame.\n"); return FALSE; }
			recsize = readint(intsize);
			for (n = 1; n<= natoms; ++n) setforces(x[n], y[n], z[n], n);
		}

		rebond();
		return TRUE;
	}
}

filter(type="importtrajectory", name="DL_POLY Formatted History", extension="HISf", glob="*HISf", exact="HISTORY", nickname="dlpolyf")
{
	int readheader()
	{
		string title;
		# DL_POLY formatted history files may contain a header.
		# Check first 8 characters of first line - if it reads 'timestep' then this trajectory doesn't have a header
		readlinef("%8s",title);
		if (title == "timestep")
		{
			printf("No header found in DL_POLY formatted trajectory. Assuming a restarted trajectory...\n");
			rewind();
		}
		else
		{
			# Next line contains keytrj, imcon, and natoms
			skipline();
		}
		return TRUE;
	}

	int readframe()
	{
		string title, e;
		int nstep, natoms, keytrj, imcon, n, id;
		vector x,y,z;
		double tstep, mass, q;

		# Frame header - '"timestep"	nstep	natms	keytrj	imcon	tstep'
		readlinef("%8s%10i%10i%10i%10i%12.6f", title, nstep, natoms, keytrj, imcon, tstep);
		title = "t = " + ftoa(tstep) + ", n = " + itoa(nstep);
		setname(title);

		# Check number of atoms in trajectory frame
		if (aten.model.natoms != natoms) { printf("Parent model contains different number of atoms to trajectory - aborting.\n"); return FALSE; }
		modeltemplate();

		# Read cell if its present
		if (imcon > 0)
		{
			readlinef("%12.4f%12.4f%12.4f",x.x, x.y, x.z);
			readlinef("%12.4f%12.4f%12.4f",y.x, y.y, y.z);
			readlinef("%12.4f%12.4f%12.4f",z.x, z.y, z.z);
			cellaxes(x.x, x.y, x.z, y.x, y.y, y.z, z.x, z.y, z.z);
		}

		# Now the atoms, velocities, and forces
		for (n=1; n<=natoms; ++n)
		{
			readlinef("%8s%10i%12.6f%12.6f", e, id, mass, q);
			readlinef("%12.4e%12.4e%f12.4e", x.x, x.y, x.z);
			setcoords(x.x, x.y, x.z, n);
			if (keytrj > 0)
			{
				readlinef("%12.4e%12.4e%f12.4e", x.x, x.y, x.z);
				setvelocities(x.x, x.y, x.z, n);
			}
			if (keytrj > 1)
			{
				readlinef("%12.4e%12.4e%f12.4e", x.x, x.y, x.z);
				setforces(x.x, x.y, x.z, n);
			}
		}
		rebond();
		return TRUE;
	}
}

filter(type="exportexpression",name="DL_POLY Forcefield Specification", extension="FIELD", glob="*FIELD",exact="FIELD",nickname="dlpoly")
{
	# Variable declaration
	pattern p;
	atom i;
	bound b;
	ffatom at1, at2;
	int nvdw, n, nc, n2, nconstraints;
	model m = aten.model;

	# First, write header consisting of title, energy units, and number of molecule types
	writeline(m.name);
	if (aten.prefs.energyunit == "kj") writeline("units kj");
	else if (aten.prefs.energyunit == "kcal") writeline("units kcal");
	else if (aten.prefs.energyunit == "ev") writeline("units ev");
	else error("Current energy unit (%s) is not compatible with DL_POLY FIELD output.\n", aten.prefs.energyunit);

	writeline("molecules",m.npatterns);

	# Loop over patterns (molecule types)
	for (p = m.patterns; p; ++p)
	{
		nconstraints = 0;

		# Write pattern name and number of molecules
		writeline(p.name);
		writeline("nummols",p.nmols);

		# Write atoms - just loop over those in the first molecule of the pattern
		writeline("atoms",p.nmolatoms);
		i = p.firstatom;
		for (n=0; n<p.nmolatoms; ++n)
		{
			writelinef("%-8s   %10.5f  %9.6f   1   0   1\n",i.type.name,i.type.mass,i.q);
			++i;
		}

		# Bonds in pattern
		nc = 0;
		for (b=p.bonds; b; ++b) if (b.form == "constraint") ++nc;
		writeline("bonds",p.nbonds-nc);
		for (b=p.bonds; b; ++b)
		{
			# Convert functional form to be recognised by DL_POLY
			# Note: DL_POLY constraint terms are written in their own section
			if (b.form == "harmonic") writelinef("harm     %5i %5i %10.4f %10.4f\n",b.id[1],b.id[2],b.parameter("k"),b.parameter("eq"));
			else if (b.form == "morse") writelinef("morse    %5i %5i %10.4f %10.4f %10.4f\n",b.id[1],b.id[2],b.parameter("d"),b.parameter("eq"),b.parameter("k"));
			else if (b.form == "constraint") nconstraints++;
			else
			{
				printf("Functional form of bond term (%s) not accounted for in export filter.\n",b.form);
				writelinef("X%s  %5i %5i %10.4f %10.4f %10.4f %10.4f\n",b.form,b.id[1],b.id[2],b.data[1],b.data[2],b.data[3],b.data[4]);
			}
		}

		# Angles in pattern
		nc = 0;
		for (b=p.angles; b; ++b) if (b.form == "bondconstraint") ++nc;
		writeline("angles",p.nangles-nc);
		for (b=p.angles; b; ++b)
		{
			# Convert functional form to be recognised by DL_POLY
			if (b.form == "harmonic") writelinef("harm     %5i %5i %5i %10.4f %10.4f\n",b.id[1],b.id[2],b.id[3],b.parameter("k"),b.parameter("eq"));
			else if (b.form == "cos") writelinef("cos      %5i %5i %5i %10.4f %10.4f %10.4f\n",b.id[1],b.id[2],b.id[3],b.parameter("k"),b.parameter("eq"),b.parameter("n"));
			else if (b.form == "harmcos") writelinef("hcos     %5i %5i %5i %10.4f %10.4f\n",b.id[1],b.id[2],b.id[3],b.parameter("k"),b.parameter("eq"));
			else if (b.form == "bondconstraint") nconstraints++;
			else
			{
				printf("Functional form of angle term (%s) not accounted for in export filter.\n",b.form);
				writelinef("X%s  %5i %5i %5i %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f\n",b.form,b.id[1],b.id[2],b.id[3],b.data[1],b.data[2],b.data[3],b.data[4],b.data[5],b.data[6]);
			}
		}

		# Torsions in pattern
		writeline("dihedrals",p.ntorsions);
		for (b=p.torsions; b; ++b)
		{
			# Convert functional form to be recognised by DL_POLY
			if (b.form == "cos") writelinef("cos      %5i %5i %5i %5i %10.4f %10.4f %10.4f %10.4f %10.4f\n",b.id[1],b.id[2],b.id[3],b.id[4],b.parameter("k"),b.parameter("eq"),b.parameter("n"),b.escale,b.vscale);
			else if (b.form == "cos3") writelinef("cos3     %5i %5i %5i %5i %10.4f %10.4f %10.4f %10.4f %10.4f\n",b.id[1],b.id[2],b.id[3],b.id[4],b.parameter("k1"),b.parameter("k2"),b.parameter("k3"),b.escale,b.vscale);
			else if (b.form == "cos3c") writelinef("opls     %5i %5i %5i %5i %10.4f %10.4f %10.4f %10.4f %10.4f\n",b.id[1],b.id[2],b.id[3],b.id[4],b.parameter("k0"),b.parameter("k1"),b.parameter("k2"),b.parameter("k3"),b.escale);
			else
			{
				printf("Functional form of torsion term (%s) not accounted for in export filter.\n",b.form);
				writelinef("X%s     %5i %5i %5i %5i %10.4f %10.4f %10.4f %10.4f %10.4f\n",b.form,b.id[1],b.id[2],b.id[3],b.id[4],b.data[1],b.data[2],b.data[3],b.escale,b.vscale);
			}
		}
		# Constraint terms
		if (nconstraints > 0)
		{
			writeline("constraints",nconstraints);
			# ...proper bond constraints first
			for (b=p.bonds; b; ++b)
			{
				if (b.form == "constraint") writelinef("    %5i %5i  %10.4f\n",b.id[1],b.id[2],b.data[2]);
			}
			# ...and now angles that are of type 'bondconstraint'
			for (b=p.angles; b; ++b)
			{
				if (b.form == "bondconstraint") writelinef("    %5i %5i  %10.4f\n",b.id[1],b.id[3],b.data[2]);
			}
		}

		# Terminating line
		writeline("finish");
	}

	# VDW Specification
	# Get total number of pair terms to write
	nvdw = 0;
	for (n=1; n<=m.nfftypes; ++n) nvdw += n;
	writeline("vdw",nvdw);
	for (n=1; n<=m.nfftypes; ++n)
	{
		at1 = m.fftypes[n];
		for (n2=1; n2<=n; ++n2)
		{
			at2 = m.fftypes[n2];
			# Check functional forms of each atomtype
			if (at1.form != at2.form)
			{
				printf("Functional forms of fftypes '%s' and '%s' differ - raw data written to output...",at1.name,at2.name); 
				writelinef("%-8s  %-8s   %12.6f  %12.6f  %12.6f  %12.6f  %12.6f %12.6f\n",at1.name,at2.name,at1.data[1],at1.data[2],at1.data[3],at1.data[4],at1.data[5],at1.data[6]);
			}
			else if (at1.form == "lj") writelinef("%-8s %-8s  lj  %12.6f  %12.6f\n",at1.name,at2.name,at1.combine(at2,1),at1.combine(at2,2));
			else if (at1.form == "ljgeom") writelinef("%-8s %-8s  lj  %12.6f  %12.6f\n",at1.name,at2.name,at1.combine(at2,1),at1.combine(at2,2));
			else if (at1.form == "buck") error("Buckingham potential not included in FIELD file export yet.\n");
			else printf("Functional form of VDW term (%s) not accounted for in export filter.\n",at1.form);
		}
	}
	writeline("close");
}

# Function definitions
int elementbymass(double mass, double masstol)
{
	for (int n=1; 1<=aten.nelements; ++n) if (abs(mass-aten.elements[n].mass) < masstol) return n;
	return 0;
}

filter(type="importexpression",name="DL_POLY Forcefield Specification", extension="FIELD", glob="*FIELD",exact="FIELD",nickname="dlpoly")
{
	# Variable declaration
	forcefield ff;
	ffbound ffb;
	ffatom at1, at2;
	int i, j, k, l, m, n, natoms, nmols, mol, nrepeat, nbound, nvdw;
	double mass, charge, qdiff, data[10];
	string discard, s, keyword, form, name, names[100];

	# Filter options
	int assumeua = option("Assume United Atom", "check", 0, "disabled", "group=Options");
	int reducetypes = option("Reduce Types", "check", 1, "group=Options");
	double masstol = option("Mass", "doublespin", 0.0, 1.0, 0.01, 0.01, "group=Tolerances for Real Values");
	double qtol = option("Charge", "doublespin", 0.0, 1.0, 0.01, 0.01, "group=Tolerances for Real Values");

	# First line is header information - use as FF name
	getline(s);
	ff = newff(s);

	# Next line is energy unit
	readline(discard, s);
	if ((lowercase(s) != "kj") && (lowercase(s) != "kcal") && (lowercase(s) != "ev")) error("FIELD file energy unit (%s) is not compatible with Aten.\n", s);
	units(s);

	# Next is number of molecules specified in the 
	readline(s, nmols);
	if (lowercase(s) != "molecules") error("Didn't find 'molecules' directive where expected.");
	else printf("Number of molecule types specified in FIELD file : %i\n", nmols);

	# Loop over molecule types
	for (mol=1; mol<=nmols; ++mol)
	{
		# First line is pattern name, next is number of molecules (neither of which we care about)
		getline(s);
		skipline();

		# Number of atoms per molecule of this type we need...
		readline(keyword,natoms);
		printf(" -- %i atoms in molecule '%s'\n", natoms, s);
		n = 0;
		do
		{
			readline(name, mass, charge, nrepeat);
			if (nrepeat == 0) nrepeat = 1;
			# if 'reducetypes == TRUE' check previous atomtype definitions for ones with same name and charge (within tolerance)
			if (reducetypes)
			{
				for (at1 in ff.atomtypes)
				{
					qdiff = abs(charge - at1.charge);
					if ((at1.name == name) && (qdiff < qtol)) break;
				}
			}
			else null(at1);
			# if 'at1 != NULL' this type already exists and we should move on....Otherwise, create a new type
			if (at1 == NULL)
			{
				at1 = typedef(ff.natomtypes,name,name,elementbymass(mass, masstol),"");
				at1.charge = charge;
			}
			# Increase atom counter and store names for upcoming bound definitions
			for (m=0; m<nrepeat; ++m) names[++n] = name;
		} while (n < natoms);

		# Next sections are optional, and terminated by 'end' keyword
		while (1)
		{
			readline(keyword, nbound);
			keyword = lowercase(keyword);
			if (keyword == "bonds")
			{
				printf("Found 'bonds' block...\n");
				for (n=1; n<=nbound; ++n)
				{
					readline(form, i, j, data[1], data[2], data[3], data[4]);
					form = lowercase(form);
					# Does a bond definition between atom names i and j already exist?
					if (ff.findbond(names[i], names[j]))
					{
						printf("Bond %s-%s has already been created in the forcefield. Skipped...\n", names[i], names[j]);
						continue;
					}
					// Create new definition
					if (form == "harm") bonddef("harmonic", names[i], names[j], data[1], data[2]);
					else if (form == "morse") bonddef("morse", names[i], names[j], data[1], data[3], data[2]);
					else printf("Functional form of bond term (%s) is not present in Aten.\n", form);
				}
			}
			else if (keyword == "constraints")
			{
				printf("Found 'constraints' block...\n");
				for (n=1; n<=nbound; ++n)
				{
					readline(i, j, data[1]);
					# Does a constraint bond definition between atom names i, and j already exist?
					if (ff.findbond(names[i], names[j]))
					{
						printf("Constraint bond %s-%s has already been created in the forcefield. Skipped...\n", names[i], names[j]);
						continue;
					}
					// Create new definition
					bonddef("constraint", names[i], names[j], 1000.0, data[1]);
				}
			}
			else if (keyword == "angles")
			{
				printf("Found 'angles' block...\n");
				for (n=1; n<=nbound; ++n)
				{
					readline(form, i, j, k, data[1], data[2], data[3], data[4]);
					form = lowercase(form);
					# Does an angle definition between atom names i, j, and k already exist?
					if (ff.findangle(names[i], names[j], names[k]))
					{
						printf("Angle %s-%s-%s has already been created in the forcefield. Skipped...\n", names[i], names[j], names[k]);
						continue;
					}
					// Create new definition
					if (form == "harm") angledef("harmonic", names[i], names[j], names[k], data[1], data[2]);
					else if (form == "cos") angledef("cos", names[i], names[j], names[k], data[1], data[3], data[2]);
					else if (form == "hcos") angledef("harmcos", names[i], names[j], names[k], data[1], data[2]);
					else printf("Functional form of angle term (%s) is not present in Aten.\n", form);
				}
			}
			else if (keyword == "dihedrals")
			{
				printf("Found 'dihedrals' block...\n");
				for (n=1; n<=nbound; ++n)
				{
					readline(form, i, j, k, l, data[1], data[2], data[3], data[4], data[5]);
					form = lowercase(form);
					# Does a torsion definition between atom names i, j, k, and l already exist?
					if (ff.findtorsion(names[i], names[j], names[k], names[l]))
					{
						printf("Torsion %s-%s-%s-%s has already been created in the forcefield. Skipped...\n", names[i], names[j], names[k], names[l]);
						continue;
					}
					// Create new definition
					null(ffb);
					if (form == "cos") ffb = torsiondef("cos", names[i], names[j], names[k], names[l], data[1], data[3], data[2]);
					else if (form == "cos3") ffb = torsiondef("cos", names[i], names[j], names[k], names[l], data[1], data[3], data[2]);
					else if (form == "opls") ffb = torsiondef("cos3c", names[i], names[j], names[k], names[l], data[1], data[2], data[3], data[4]);
					else printf("Functional form of torsion term (%s) is not present in Aten.\n", form);
					if (ffb != NULL) { ffb.escale = data[4]; ffb.vscale = data[5]; }
				}
			}
			else if (keyword == "finish") break;
			else printf("Unrecognised keyword in FIELD file - '%s'\n", keyword);
		}
	}

	# VDW Specification
	readline(keyword, nvdw);
	if (lowercase(keyword) != "vdw") printf("Didn't find 'vdw' section where expected. VDW information not converted.");
	else
	{
		printf("Found 'vdw' block...\n");
		for (n=0; n<nvdw; ++n)
		{
			# Read in each line of data, searching for those where the first atomtype is equal to the second
			readline(names[1], names[2], form, data[1], data[2], data[3], data[4], data[5]);
			if (names[1] != names[2]) continue;
			# We may have added multiple types of the same name earlier, so search the whole list explicitly
			for (at1 in ff.atomtypes)
			{
				if (at1.name != names[1]) continue;
				# Check form
				if (form == "lj") interdef("lj", at1.id, at1.charge, data[1], data[2]);
#				else if (form == "buck") error("Buckingham potential not included in FIELD file export yet.\n");
				else printf("Functional form of VDW term (%s) is not present in Aten.\n",form);
			}
		}
	}

	# Perform necessary tasks
	finaliseff();
}
