// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//

#include <BALL/FORMAT/MOPACInputFile.h>

#include <BALL/KERNEL/system.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/PDBAtom.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/PTE.h>

namespace BALL
{
	MOPACInputFile::MOPACInputFile()
		: GenericMolFile(),
			default_mopac_keywords_("AM1 MMOK GEO-OK BONDS PRECISE")
	{
	}

	MOPACInputFile::MOPACInputFile(const String& name, File::OpenMode open_mode)
		: GenericMolFile(),
			default_mopac_keywords_("AM1 MMOK GEO-OK BONDS PRECISE")
	{
		open(name, open_mode);
	}

	MOPACInputFile::~MOPACInputFile()
	{
	}

	void MOPACInputFile::writeHeader_(AtomContainer const& ac)
	{
		String mopac_keywords = default_mopac_keywords_;
		if (ac.hasProperty("MOPAC-Keywords"))
			mopac_keywords = ac.getProperty("MOPAC-Keywords").toString();

		// TODO: take the correct charge
		String charge = "CHARGE=0";

		String multiplicity = "SINGLET";
		if (ac.hasProperty("SpinMultiplicity"))
			multiplicity = ac.getProperty("SpinMultiplicity").toString();

		mopac_keywords += " " + charge + " " + multiplicity;

		String comment = "Generated by BALL for " + ac.getName() + "\n";

		File& f = static_cast<File&>(*this);

		f << mopac_keywords << std::endl;
		f << comment << std::endl;
	}

	// TODO: warn if odd number of electrons and charge / multiplicity not set
	void MOPACInputFile::writeAtoms_(const AtomContainer& ac)
	{
		File& f = static_cast<File&>(*this);

		Size number_of_electrons = 0;
		for (AtomConstIterator at_it = ac.beginAtom(); +at_it; ++at_it)
		{
			String line(256, "%5s%12.4lf  1  %12.4lf  1  %12.4lf  1   \n", 
					at_it->getElement().getSymbol().c_str(), at_it->getPosition().x,
					at_it->getPosition().y, at_it->getPosition().z);

			f << line;

			number_of_electrons += at_it->getElement().getAtomicNumber();
		}

		f << std::endl;
	}

	bool MOPACInputFile::write(const System& system)
	{
		if (!isOpen() || getOpenMode() != std::ios::out)
		{
			throw(File::CannotWrite(__FILE__, __LINE__, name_));
		}

		writeHeader_(system);
		writeAtoms_(system);

		return true;
	}

	bool MOPACInputFile::write(const Molecule& molecule)
	{
		if (!isOpen() || getOpenMode() != std::ios::out)
		{
			throw(File::CannotWrite(__FILE__, __LINE__, name_));
		}

		writeHeader_(molecule);
		writeAtoms_(molecule);

		return true;
	}
}
