# GAMESS-US Input / Outputi, Logfile and Trajectory Filters (for v1.2+)
# Created:	 14/04/2009
# Last modified: 29/01/2011
# ChangeLog:
#	29/01/2011 - Added COORD option to specify CART or ZMT
#	28/01/2011 - Updated trajectory reader to handle IRC trajectory data
#	15/12/2010 - Added basic trajectory reader
#	09/12/2010 - Updated reading of vibration data from logfile to cope with presence of symmetry line
#	29/10/2010 - Major update to log file filter - ability to read in basis set, MOs, and vibrations added
#	02/10/2010 - Logfile import filter now names models after filenames.
#	14/09/2010 - Tweaks to options output in GUI filter. Standard DFTTYPs added.
#	25/08/2010 - Added GUI options to output filter
#	12/05/2010 - Changed id of log file filter to 11 (was 10, which conflicted with MDL Molfile in 'mol')
#	13/10/2009 - Last frame and parent frame from logfile are now deselected.
# Notes:
#	Output model filter sets symmetry to C1, regardless of the actual symmetry.

filter(type="importtrajectory", name="GAMESS-US Trj File", nickname="gamustrj", extension="trj", glob="*.trj", zmap="name", search="GAMESS VERSION", id=11)
{
        int readheader()
        {
                return TRUE;
        }

        int readframe()
        {
		int n, natm, nfrag, nqmmm, packettype, skip = 0;
		string discard, symbol, line;
		double ano, x, y, z;
		model m = aten.frame;

		# MD data packets have three skippable lines at the start
		# IRC data packets have 
		if (find("DATA PACKET",line))
		{
			# Found a data packet - determine which type it is...
			if (contains(line, "===== MD")) { packettype = 1; skip = 3; }
			else if (contains(line, "===== IRC")) { packettype = 2; skip = 1; }
			else
			{
				printf("Unrecognised DATA PACKET type encountered in trj file.\n");
				return FALSE;
			}
		}
		else packettype = 0;

		# Did we find some data?
		if (packettype != 0)
		{
			# Read in number of atoms
			readline(discard, natm, discard, nfrag, discard, nqmmm);
			skipline(skip);
			# Read QM atom data (if present)
			if (natm > 0)
			{
				skipline();
				for (n=0; n<natm; ++n)
				{
					readline(symbol,ano,x,y,z);
					newatom(symbol,x,y,z);
				}
			}
			# Read fragment data (if present)
			if (nfrag > 0)
			{
				error("Reading of fragment data from trajectory not implemented yet.");
				skipline();
				for (n=0; n<nfrag; ++n)
				{
				}
			}
			# Read QMMM data (if present)
			if (nqmmm > 0)
			{
				error("Reading of QMMM data form trajectory not implemented yet.");
				skipline();
				for (n=0; n<nqmmm; ++n)
				{
				}
			}
			# Specific reads for DATA PACKET types
			if (packettype == 1)
			{
				# Read in velocities for atoms
				if (find("TVELQM(1)"))
				{
					for (n=1; n<=natm; ++n)
					{
						readline(x, y, z);
						m.atoms[n].v = { x, y, z};
					}
				}
			}
			else if (packettype == 2)
			{
				# Discard mass-weighted gradient
				skipline(natm+1);
			}
			rebond();
			finalisemodel();
		}
		else return FALSE;
		return TRUE;
	}
}

filter(type="importmodel", name="GAMESS-US Log File", nickname="gamuslog", extension="log", glob="*.log", zmap="name", search="GAMESS VERSION", id=11)
{
	# Variable declaration
	int result,nstructures,natoms,n,l,lastshell,shell,count,orb_no[5];
	atom i;
	basisshell bas;
	basisprimitive prim;
	eigenvector orbs[5];
	vibration vibs[5];
	string line,e,name,discard,orb_symm[5],type, vib_imag[5], vib_symm[5];
	double rx,ry,rz, exponent,coeff,orb_nrg[5], orb_coeff[5];
	double vib_freq[5], vib_dx[5], vib_dy[5], vib_dz[5], vib_rmass[5], vib_ir[5];

	# Create a new model, and store its pointer for use later
	model m = newmodel(filterfilename());

	# Find initial coordinates (in Bohr)
	if (find("ATOM      ATOMIC                      COORDINATES (BOHR)"))
	{
		skipline();
		while (readline(e,discard,rx,ry,rz) != 0) newatom(e,rx,ry,rz);
		bohr(aten.model);
		rebond();
	}
	else error("No coordinates in file?");

	# Read in basis set information
	if (find("ATOMIC BASIS SET"))
	{
		skipline(6);
		# Loop over basis shell definitions, stopping when we find the text 'TOTAL'
		readlinef("%s %s %i %f %r", e, name, n, exponent, line);
		#printf("%s %s %i %f [%s]\n", e, name, n, exponent, line);
		lastshell = -1;
		count = 0;
		while (e != "TOTAL")
		{
			# Start of a new atom?
			if (n == 0)
			{
				count ++;
				lastshell = 0;
				#printf("Found start of atom %i, which is element %s\n", count, e);
			}
			else
			{
				# Create new basis shell?
				shell = atoi(e);
				#if (lastshell != shell) printf("Lastn (%i) is != shell (%i), so creating a new shell...\n", lastshell, shell);
				if (lastshell != shell) bas = m.newbasisshell(count, name);
				lastshell = shell;
			}

			# Store primitive's exponent and coefficient(s)
			if (lastshell != 0)
			{
				prim = bas.addprimitive(exponent);
				# Cycle over provided coefficients
				while (nextvararg(line,coeff)) prim.addcoefficient(coeff);
			}

			# Get next line, ignoring blanks
			do
			{
				readlinef("%s %s %i %f %r", e, name, n, exponent, line);
			} while (e == "");
			#printf("%s %s %i %f [%s]\n", e, name, n, exponent, line);
		}
		# We end up with the 'TOTAL NUMBER OF BASIS SET SHELLS' line (beginning at 'SET...'), so we can do a check
		readvar(line, discard, discard, discard, n);
		printf("         Number of basis set shells read in : %i\n", m.nbasisshells());
		printf("            --> number specified in logfile : %i\n", n);
		if (n != m.nbasisshells()) error("Failed to read in basis set information.");
		# Also, check the total number of cartesian basis functions
		readlinef("%r", line);
		n = atoi( afterstr(line,"=") );
		printf("Number of implied cartesian basis functions : %i\n", m.nbasiscartesians());
		printf("            --> number specified in logfile : %i\n", n);
		if (n != m.nbasiscartesians()) error("Failed to read in basis set information.");
	}

	# Determine number of atoms - search for line containing 'TOTAL NUMBER OF ATOMS'
	if (!find("TOTAL NUMBER OF ATOMS",line)) error("Couldn't determine number of atoms from GAMESS-US output.");

	# Get number of atoms from line
	readvarf(line, "%48*%i",natoms);

	# Now search for sets of coordinate
	nstructures = 0;
	# Lines containing 'COORDINATES OF ALL ATOMS ARE' are the beginning of coordinate sections
	while (find("COORDINATES OF ALL ATOMS ARE"))
	{
		# Found a set of coordinates. Skip 2 lines and then read coordinates
		nstructures++;
		skipline(2);
		writevarf(name, "Frame %i", nstructures);
		m = addframe(name);
		for (n=1; n<=natoms; ++n)
		{
			readline(e,discard,rx,ry,rz);
			newatom(e,rx,ry,rz);
		}
		# Recalculate bonding
		rebond();
		finaliseframe();
	}

	# Molecular orbitals?
	if (find("MOLECULAR ORBITALS"))
	{
		skipline(2);
		# MO information is provided 5 orbs per line, in the format:
		#                     1          2          3          4
		#                   -0.5942     0.2657     0.9175     1.5319
		#                     A          A          A          A
		#    1  H  1  S   -0.290651  -0.111641  -0.783160   1.077794
		#    .  .  .  .
		#    NC .  .  .   
		# ...where NC is the number of cartesian basis functions.
		for (n=1; n<m.nbasisshells(); n +=5)
		{
			# Read in orbital numbers as a sanity check
			readline(discard);
			# End of orbital specification?
			if (atoi(discard) == 0) break;
			else if (n != atoi(discard))
			{
				printf("Failed to read in MO information at orbital number %i (read [%s] from file)\n", n, discard);
				break;
			}
			# Read in eigenvalues and symmetry type
			readline(orb_nrg[1], orb_nrg[2], orb_nrg[3], orb_nrg[4], orb_nrg[5]);
			readline(orb_symm[1], orb_symm[2], orb_symm[3], orb_symm[4], orb_symm[5]);
			# Create eigenvectors
			for (l=1; l<6; ++l)
			{
				if ((l+n-1) > m.nbasisshells()) break;
				verbose(" -- Created MO number %i with eigenvalue %f\n", l+n-1, orb_nrg[l]);
				orbs[l] = m.neweigenvector();
				orbs[l].eigenvalue = orb_nrg[l];
				orbs[l].name = orb_symm[l];
			}
			# Next lines contain coefficients...
			for (count=1; count<=m.nbasiscartesians(); ++count)
			{
				readline(discard,e,shell,type,orb_coeff[1], orb_coeff[2], orb_coeff[3], orb_coeff[4], orb_coeff[5]);
				for (l=1; l<6; ++l)
				{
					if ((l+n-1) > m.nbasisshells()) break;
					orbs[l].vector[count] = orb_coeff[l];
				}
			}
		}
	}

	# Frequencies?
	rewind();
	if (find("FREQUENCIES IN CM**-1"))
	{
		# Skip warning of non-stationary point if present...
		if (find("THIS IS NOT A STATIONARY POINT"))
		{
			skipline(3);
			printf(" *** The frequencies correspond to a non-stationary point.\n");
		}
		else skipline(2);
		# Vibration information is provided 5 vibrations per line, in the format:
		#                       1          2          3          4            5
		#    FREQUENCY:      39.84 I     19.94       19.03       15.12       11.87
		#     SYMMETRY:         A          A           A           A           A       (optional)
		# REDUCED MASS:      2.15985     3.96061     4.04986     3.97821     5.98898
		# IR INTENSITY:      0.00121     0.00399     0.00426     0.00020     0.00070
		#  <blank line>
		#    1  HYDROGEN  X  0.05470495  0.01254668 -0.05069468  0.01778118 -0.01077563
		#    .  .  .  .
		#    3N .  .  .   
		# ...where N is the number of atoms in the model
		for (n=1; n<3*m.natoms(); n +=5)
		{
			# Read in vibration numbers as a sanity check
			readline(discard);
			if (n != atoi(discard))
			{
				printf("Failed to read in vibration information at vibration number %i (read [%s] from file)\n", n, discard);
				break;
			}
			# Read in frequencies and imaginary flags
			readlinef("%* %f%2s%f%2s%f%2s%f%2s%f%2s", vib_freq[1], vib_imag[1], vib_freq[2], vib_imag[2], vib_freq[3], vib_imag[3], vib_freq[4], vib_imag[4], vib_freq[5], vib_imag[5]);
			readlinef("%18s %r", discard, line);
			if (stripchars(discard," ") == "REDUCEDMASS:") readvar(line, vib_rmass[1], vib_rmass[2], vib_rmass[3], vib_rmass[4], vib_rmass[5]);
			else
			{
				readvar(line, vib_symm[1], vib_symm[2], vib_symm[3], vib_symm[4], vib_symm[5]);
				readline(discard, vib_rmass[1], vib_rmass[2], vib_rmass[3], vib_rmass[4], vib_rmass[5]);
			}
			readline(discard, vib_ir[1], vib_ir[2], vib_ir[3], vib_ir[4], vib_ir[5]);
			# Create vibrations
			for (l=1; l<6; ++l)
			{
				if ((l+n-1) > 3*m.natoms()) break;
				if (contains(vib_imag[l],"I")) vib_freq[l] = -vib_freq[l];
				verbose("Created vibration number %i with frequency %f\n", l+n-1, vib_freq[l]);
				vibs[l] = m.newvibration();
				vibs[l].frequency = vib_freq[l];
			}
			skipline(1);
			# Next lines contain atomic displacements
			for (count=1; count<=m.natoms(); ++count)
			{
				readline(discard,e,type,vib_dx[1], vib_dx[2], vib_dx[3], vib_dx[4], vib_dx[5]);
				readline(type,vib_dy[1], vib_dy[2], vib_dy[3], vib_dy[4], vib_dy[5]);
				readline(type,vib_dz[1], vib_dz[2], vib_dz[3], vib_dz[4], vib_dz[5]);
				for (l=1; l<6; ++l)
				{
					if ((l+n-1) > 3*m.natoms()) break;
				#	vibs[l].displacements[count] = { vib_dx[l], vib_dy[l], vib_dz[l] };
					vibs[l].displacements[count].x = vib_dx[l] ;
					vibs[l].displacements[count].y = vib_dy[l] ;
					vibs[l].displacements[count].z = vib_dz[l] ;
				}
			}
			# Skip over Sayvetz information
			skipline(11);
		}
		printf("Read in data for %i vibrations.\n", m.nvibrations());
	}

	# Atomic Charges
	rewind();
	if (find("ELECTROSTATIC POTENTIAL"))
	{
		# Skip to last section
		do { }
		while (find("ELECTROSTATIC POTENTIAL"));
		# Now search for "NET CHARGES"
		if (find("NET CHARGES"))
		{
			skipline(3);
			for (i = m.atoms; i; ++i) readline(discard, i.q);
			printf("Found and read in ESP charges.\n");
		}
	}

	finalisemodel();
}

filter(type="importmodel", name="GAMESS-US Cartesian Input", nickname="gamusinp", extension="inp", glob="*.inp", zmap="name", id=5)
{
	# Variables
	string symm,symbol,title;
	int n,z;
	double rx,ry,rz;

	# Search for $DATA section
	if (!find("DATA")) error("Couldn't find 'DATA' section in input file.");

	# Read in title card
	getline(title);
	newmodel(title);

	# Skip over symmetry specification
	readline(symm);
	if (symm <> "C1")
	{
		# Single blank line means the master frame is in use, and only this line to skip
		readline(symm);
		if (symm != "") skipline();
	}
	
	# Coordinates follow, terminated by $END
	readline(symbol,z,rx,ry,rz);
	while (symbol != "$END")
	{
		newatom(symbol,rx,ry,rz);
		readline(symbol,z,rx,ry,rz);
	}

	# Done
	rebond();
	finalisemodel();
}

filter(type="exportmodel", name="GAMESS-US Input", nickname="gamusinp", extension="inp", glob="*.inp", id=5)
{
	#
	# GUI Control Definitions
	#

	# General control options ($CONTRL)
	string contrl_runtyp = option("Run Type", "combo", "ENERGY,GRADIENT,HESSIAN,GAMMA,OPTIMIZE,TRUDGE,SADPOINT,MEX,IRC,VSCF,DRC,MD,GLOBOP,OPTFMO,GRADEXTR,SURFACE,G3MP2,PROP,RAMAN,NACME,NMR,EDA,TRANSITN,FFIELD,TDHF,TDHFX,MAKEFP,FMO0", 5, "group=Job Control ($CONTRL)");
	string contrl_scftyp = option("SCF Type", "combo", "RHF,UHF,ROHF,GVB,MCSCF,NONE", 1, "group=Job Control ($CONTRL)");
	int contrl_mult = option("Multiplicity", "intspin", 1, 8, 1, 1, "group=Job Control ($CONTRL)");
	int contrl_charge = option("Charge", "intspin", -1000, 1000, 1, 0, "group=Job Control ($CONTRL)");
	string contrl_dfttyp = option("DFT Type", "combo", "NONE,SVWN,BLYP,PW91,B97-D,PBE,PBEsol,B3LYP,X3LYP,PBE0,TPSS,TPSSm,TPSSh,M06,SLATER,BECKE,GILL,OPTX,PW91X,PBEX,VWN,VWN1,PZ81,P86,LYP,PW91C,PBEc,OP,SVWN,BLYP,BOP,BP86,GVWN,GPW91,PBEVWN,PBEOP,OLYP,PW91,PBE", 1, "group=Job Control ($CONTRL)", "newline");
	string contrl_tddft = option("TDDFT Type", "combo", "NONE,EXCITE", 1, "group=Job Control ($CONTRL)");
	string contrl_mplevl = option("MP Level", "combo", "0,2", 1, "group=Job Control ($CONTRL)");
	string contrl_cityp = option("CI Type", "combo", "NONE,CIS,ALDET,ORMAS,FSOCI,GENCI,GUGA", 1, "group=Job Control ($CONTRL)");
	string contrl_cctyp = option("CC Type", "combo", "NONE,LCCD,CCD,CCSD,CCSD(T),R-CC,CR-CC,CR-CCL,CCSD(TQ),CR-CC(Q),EOM-CCSD,CR-EOM,CR-EOML,IP-EOM2,EA-EOM2,EA-EOM3A", 1, "group=Job Control ($CONTRL)", "newline");
	string contrl_relwfn = option("Rel. Wfn.", "combo", "NONE,DK,RESC,NESC", 1, "group=Job Control ($CONTRL)");
	string contrl_exetyp = option("Exe Type", "combo", "RUN,CHECK,DEBUG", 1, "group=Job Control ($CONTRL)");
	string contrl_pp = option("Pseudo", "combo", "NONE,READ,SBKJC,HW,MCP", 1, "group=Job Control ($CONTRL)");
	string contrl_coord = option("Coord Type", "combo", "CART,ZMT", 1, "group=Job Control ($CONTRL)", "newline");
	int cart_symbols = option("Use Symbols", "check", 1, "group=Job Control ($CONTRL)", "span=2");
	int contrl_maxit = option("Max SCF It.", "intspin", 1,1000,10,30, "group=Job Control ($CONTRL)");

	# Basis set specification ($BASIS)
	string basis_gbasis = option("Basis", "combo", "MINI,MIDI,STO,N21,N31,N311,DZV,DH,TZV,MC,CCD,CCT,CCQ,CC5,CC6,ACCD,ACCT,ACCQ,ACC5,ACC6,CCDC,CCTC,CCQC,CC5C,CC6C,ACCDC,ACCTC,ACCQC,ACC5C,ACC6C,PC0,PC1,PC2,PC3,PC4,APC0,APC1,APC2,APC3,APC4,SBKJC,HW,MCP-DZP,MCP-TZP,MCP-QZP,IMCP-SR1,IMCP-SR2,IMCP-NR1,IMCP-NR2,MNDO,AM1,PM3", 5, "group=Basis Set ($BASIS)", "newline");
	int basis_ngauss = option("NGAUSS", "intspin", 3,8,1,6, "group=Basis Set ($BASIS)");
	int basis_ndfunc = option("NDFUNC", "intspin", 0,3,1,0, "group=Basis Set ($BASIS)");
	int basis_npfunc = option("NPFUNC", "intspin", 0,3,1,0, "group=Basis Set ($BASIS)");
	int basis_nffunc = option("NFFUNC", "intspin", 0,1,1,0, "group=Basis Set ($BASIS)");
	string basis_diffsp = option("DIFFSP", "combo", ".TRUE.,.FALSE.", 2, "group=Basis Set ($BASIS)");
	string basis_diffs = option("DIFFS", "combo", ".TRUE.,.FALSE.", 2, "group=Basis Set ($BASIS)");

	# DFT options ($DFT), placed in 'opts' tab
	string dftgrid = option("DFT Method", "combo", "GRID,GRIDFREE", 1, "state=GRID@DFT Type?originalitems", "state=GRIDFREE@DFT Type?items=NONE,XALPHA,SLATER,BECKE,DEPRISTO,CAMA,HALF,VWN,PWLOC,LYP,BVWN,BLYP,BPWLOC,B3LYP,CAMB,XVWN,XPWLOC,SVWN,SPWLOC,WIGNER,WS,WIGEXP", "tab=$DFT@opts", "newline");

	# Stationary point location options ($STATPT), placed in 'opts' tabs
	string statpt_method = option("Method", "combo", "NR,RFO,QA,SCHLEGEL,CONOPT", 3, "tab=$STATPT@opts", "newline");
	double statpt_opttol = option("Tolerance", "doublespin", 0.0, 1.0, 0.0001, 0.0001, "tab=$STATPT@opts");
	int statpt_nstep = option("NStep", "intspin", 1, 1000000, 5, 20, "tab=$STATPT@opts");
	int statpt_ifolow = option("IFOLOW", "intspin", 1, 100000, 1, 1, "tab=$STATPT@opts", "newline");
	string statpt_stpt = option("STPT", "combo", ".TRUE.,.FALSE.", 2, "tab=$STATPT@opts");
	double statpt_ststep = option("STSTEP", "doublespin", 0.0, 1.0, 0.005, 0.01, "tab=$STATPT@opts");
	string statpt_ifreez = option("IFREEZ", "edit", "", "tab=$STATPT@opts", "newline", "span=5");
	string statpt_hess = option("HESS", "combo", "GUESS,READ,RDAB,RDALL,CALC", 1, "tab=$STATPT@opts", "newline");
	int statpt_ihrep = option("IHREP", "intspin", 0, 1000, 1, 0, "tab=$STATPT@opts");
	string statpt_hssend = option("HSSEND", "combo", ".TRUE.,.FALSE.", 2, "tab=$STATPT@opts");

	# Intrinsic reaction coordinate run ($IRC), place in 'opts' tabs
	string irc_forwrd = option("Forward", "combo", ".TRUE.,.FALSE.", 1, "tab=$IRC@opts"); 
	string irc_saddle = option("Saddle", "combo", ".TRUE.,.FALSE.", 1, "tab=$IRC@opts"); 
	double irc_stride = option("Stride", "doublespin", 0.001, 1.0, 0.05, 0.3, "tab=$IRC@opts");
	int irc_npoint = option("NPoint", "intspin", 1, 1000, 5, 1, "tab=$IRC@opts");
	string irc_pace = option("Pace", "combo", "GS2,LINEAR,QUAD,AMPC4,RK4", 1, "tab=$IRC@opts", "newline");

	# Electron density calculation ($ELDENS), placed in 'opts' tabs
	int eldens_ieden = option("Calculate", "check", 0, "tab=$ELDENS@opts", "newline");
	int eldens_morb = option("MORB", "intspin", 0, 10000, 1, 0, "tab=$ELDENS@opts");
	string eldens_where = option("WHERE", "combo", "COMASS,NUCLEI,POINTS,GRID", 2, "tab=$ELDENS@opts");
	string eldens_output = option("OUTPUT", "combo", "PUNCH,PAPER,BOTH", 3, "tab=$ELDENS@opts");

	# Electrostatic potential calculation ($ELPOT), placed in 'opts' tabs
	int elpot_iepot = option("Calculate", "check", 0, "tab=$ELPOT@opts", "newline");
	string elpot_where = option("WHERE", "combo", "COMASS,NUCLEI,POINTS,GRID,PDC", 2, "tab=$ELPOT@opts");
	string elpot_output = option("OUTPUT", "combo", "PUNCH,PAPER,BOTH,NONE", 3, "tab=$ELPOT@opts");

	# Point selection ($PDC), placed in 'opts' tabs
	string pdc_ptsel = option("PTSEL", "combo", "GEODESIC,CONNOLLY,CHELPG", 1, "tab=$PDC@opts");
	string pdc_constr = option("CONSTR", "combo", "NONE,CHARGE,DIPOLE,QUPOLE", 2, "tab=$PDC@opts");

	# Grid specification ($GRID), placed in 'opts' tabs
	int grid_modgrd = option("3D Grid", "check", 0, "tab=$GRID@opts", "newline");
	double grid_size = option("Grid Increment", "doublespin", 0.00001, 2.0, 0.1, 0.25, "tab=$GRID@opts");
	option("ORIGIN", "label", "newline", "tab=$GRID@opts");
	double grid_originx = option("X", "doublespin", -1000.0, 1000, 1, -10.0, "tab=$GRID@opts");
	double grid_originy = option("Y", "doublespin", -1000.0, 1000, 1, -10.0, "tab=$GRID@opts");
	double grid_originz = option("Z", "doublespin", -1000.0, 1000, 1, -10.0, "tab=$GRID@opts");
	option("XVEC", "label", "newline", "tab=$GRID@opts");
	double grid_xvecx = option("X", "doublespin", -1000.0, 1000, 1,  10.0, "tab=$GRID@opts");
	double grid_xvecy = option("Y", "doublespin", -1000.0, 1000, 1, -10.0, "tab=$GRID@opts");
	double grid_xvecz = option("Z", "doublespin", -1000.0, 1000, 1, -10.0, "tab=$GRID@opts");
	option("YVEC", "label", "newline", "tab=$GRID@opts");
	double grid_yvecx = option("X", "doublespin", -1000.0, 1000, 1, -10.0, "tab=$GRID@opts");
	double grid_yvecy = option("Y", "doublespin", -1000.0, 1000, 1,  10.0, "tab=$GRID@opts");
	double grid_yvecz = option("Z", "doublespin", -1000.0, 1000, 1, -10.0, "tab=$GRID@opts");
	option("ZVEC", "label", "newline", "tab=$GRID@opts");
	double grid_zvecx = option("X", "doublespin", -1000.0, 1000, 1, -10.0, "tab=$GRID@opts");
	double grid_zvecy = option("Y", "doublespin", -1000.0, 1000, 1, -10.0, "tab=$GRID@opts");
	double grid_zvecz = option("Z", "doublespin", -1000.0, 1000, 1,  10.0, "tab=$GRID@opts");

	# PCM options ($PCM), placed in 'opts' tab
	string pcm_solvnt = option("Solvent", "combo", "NONE,WATER,CH3OH,CLFORM,METHYCL,BENZENE,CLBENZ,NEPTANE,ANILINE,C2H5OH,CTCL,12DCLET,TOLUENE,NITMET,CYCHEX,ACETONE", 1, "tab=$PCM@opts", "newline");


	#
	# Write Data
	#
	string line;
	# Write $CONTRL line(s)
	writelinef(" $CONTRL SCFTYP=%s RUNTYP=%s COORD=%s ICHARG=%i MULT=%i $END\n", contrl_scftyp, contrl_runtyp, contrl_coord, contrl_charge, contrl_mult);
	line = "";
	if (contrl_dfttyp != "NONE") line += " DFTTYP=" + contrl_dfttyp;
	if (contrl_tddft != "NONE") line += " TDDFT=" + contrl_tddft;
	if (contrl_mplevl != "0") line += " MPLEVL=" + contrl_mplevl;
	if (contrl_cityp != "NONE") line += " CITYP=" + contrl_cityp;
	if (contrl_cctyp != "NONE") line += " CCTYP=" + contrl_cctyp;
	if (contrl_pp != "NONE") line += " ECPTYP=" + contrl_pp;
	if (contrl_maxit != 30) line += " MAXIT=" + itoa(contrl_maxit);
	if (line != "") writelinef(" $CONTRL%s $END\n", line);

	# Write $BASIS line(s)
	if ((basis_gbasis == "STO") || (basis_gbasis == "N21") || (basis_gbasis == "N31") || (basis_gbasis == "N311"))
	{
		sprintf(line, "GBASIS=%s NGAUSS=%i", basis_gbasis, basis_ngauss);
		if (basis_ndfunc != 0) line += " NDFUNC=" + itoa(basis_ndfunc);
		if (basis_npfunc != 0) line += " NPFUNC=" + itoa(basis_npfunc);
		if (basis_nffunc != 0) line += " NFFUNC=" + itoa(basis_nffunc);
		writelinef(" $BASIS %s $END\n", line);
		if (basis_diffsp == ".TRUE." || basis_diffs == ".TRUE.") writelinef(" $BASIS DIFFSP=%s DIFFS=%s $END\n", basis_diffsp, basis_diffs);
	}
	else writelinef(" $BASIS GBASIS=%s $END\n", basis_gbasis);

	# Write additional groups, depending on job type
	if ((contrl_runtyp == "OPTIMIZE") || (contrl_runtyp == "SADPOINT"))
	{
		writevarf(line, " $STATPT METHOD=%s NSTEP=%i OPTTOL=%f HESS=%s", statpt_method, statpt_nstep, statpt_opttol, statpt_hess);
		if (statpt_ihrep != 0) line += " IHREP=" + itoa(statpt_ihrep);
		if (statpt_hssend == ".TRUE.") line += " HSSEND=.TRUE.";
		writelinef("%s $END\n", line);
		if (contrl_runtyp == "SADPOINT") writelinef(" $STATPT IFOLOW=%i STPT=%s STSTEP=%f $END\n", statpt_ifolow, statpt_stpt, statpt_ststep);
		if (statpt_ifreez != "") writelinef(" $STATPT IFREEZ(1)=%s $END\n", statpt_ifreez);
	}
	else if (contrl_runtyp == "IRC") writelinef(" $IRC PACE=%s FORWRD=%s SADDLE=%s STRIDE=%f NPOINT=%i $END\n", irc_pace, irc_forwrd, irc_saddle, irc_stride, irc_npoint);

	# Write $ELDENS if required
	if (eldens_ieden == 1) writelinef(" $ELDEN IEDEN=1 MORB=%i WHERE=%s OUTPUT=%s $END\n", eldens_morb, eldens_where, eldens_output);

	# Write $ELPOT if required
	if (elpot_iepot == 1)
	{
		writelinef(" $ELPOT IEPOT=1 WHERE=%s OUTPUT=%s $END\n", elpot_where, elpot_output);
		if (elpot_where == "PDC") writelinef(" $PDC PTSEL=%s CONSTR=%s $END\n", pdc_ptsel, pdc_constr);
	}

	# Write $GRID if required
	if ((eldens_where == "GRID") || (elpot_where == "GRID"))
	{
		writelinef(" $GRID MODGRD=%i UNITS=ANGS SIZE=%f $END\n", grid_modgrd, grid_size);
		writelinef(" $GRID ORIGIN(1)=%f ORIGIN(2)=%f ORIGIN(3)=%f $END\n", grid_originx, grid_originy, grid_originz);
		writelinef(" $GRID XVEC(1)=%f XVEC(2)=%f XVEC(3)=%f $END\n", grid_xvecx, grid_xvecy, grid_xvecz);
		writelinef(" $GRID YVEC(1)=%f YVEC(2)=%f YVEC(3)=%f $END\n", grid_yvecx, grid_yvecy, grid_yvecz);
		if (grid_modgrd == 1) writelinef(" $GRID ZVEC(1)=%f ZVEC(2)=%f ZVEC(3)=%f $END\n", grid_zvecx, grid_zvecy, grid_zvecz);
	}

	# Write $PCM if required
	if (pcm_solvnt != "NONE")
	{
		writelinef(" $PCM SOLVNT=%s $END\n", pcm_solvnt);
	}

	# Write $SYSTEM, $GUESS, and $SCF groups
	writeline(" $SYSTEM MEMDDI=16 TIMLIM=2400 MWORDS=96 $END");
	writeline(" $GUESS GUESS=HUCKEL $END");
	writeline(" $SCF DIRSCF=.TRUE. $END");

	# Now for the DATA section
	writeline(" $DATA");
	writeline(aten.frame.name);
	writeline("C1");
	if (contrl_coord == "CART")
	{
		if (cart_symbols) for (atom i = aten.frame.atoms; i != 0; ++i) writelinef("%-15s  %4.1f  %12.6f %12.6f %12.6f\n", i.symbol,i.z*1.0,i.rx,i.ry,i.rz);
		else for (atom i = aten.frame.atoms; i != 0; ++i) writelinef("%-15s  %4.1f  %12.6f %12.6f %12.6f\n", i.name,i.z*1.0,i.rx,i.ry,i.rz);
	}
	else writezmatrix(aten.frame);
	writeline(" $END");
}
