/***************************************************************************
 *   Copyright (C) 2004 by Christoph Thielecke                             *
 *   crissi99@gmx.de                                                       *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

//BEGIN INCLUDES
#include "kvpncconfig.h"
#include "utils.h"
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <iostream>
#include <kstandarddirs.h>
#include <qdom.h>
#include "kvpncimportprofileselectiondialogbase.h"
#include <qlistview.h>
#include <qcheckbox.h>
#include <qcursor.h>
#include <qregexp.h>
#include <kpushbutton.h>
//END INCLUDES

KVpncConfig::KVpncConfig(QWidget *parent,KStatusBar *statusbar)
{
	this->parent = parent;
	this->statusbar = statusbar;

	pathToVpnc = "";
	pathToCiscoVpnc = "";
	pathToRacoon = "";
	pathToSetkey = "";
	pathToFreeswan = "";
	pathToPppd="";
	pathToPptp="";
	pathToL2tpd="";
	pathToXl2tpd="";
	pathToKill="";
	pathToKillall="";
	pathToPing="";
	pathToOpenvpn="";
	pathToIp="/sbin/ip";
	pathToIfconfig="/sbin/ifconfig";
	pathToRoute="/sbin/route";
	pathToNetstat="/bin/netstat";
	pathToL2tpd="/usr/sbin/l2tpd";
	pathToPkcs11Tool="/usr/bin/pkcs11-tool";
	pathToVtund="/usr/sbin/vtund";
	pathToCiscoCertMgr="/usr/local/bin/cisco_cert_mgr";
	AutoConnectProfile="";
	Vpnc_pid_file = "";
	Pppd_pid_file = "";
	lastProfile = "";
	logfileName = "";
	InterpreterShell="/bin/bash";

	TmpPassword="";
	TmpGroupPassword="";
	TmpUsername="";
	TmpPrivKeyPassStr="";
	TmpGatewayIP="";
	TmpXauthInterPasscode="";
	TmpPrivateKeyPass="";
	TmpHttpProxyPassword="";

	connectSleepDelay = 15;
	connectSleepRetry = 0;
	tryConnectTimeout = 10;
	runningCheckCounter = 0;
	runningCheckTimeout = 60;
	mainwindow_pos_x=0;
	mainwindow_pos_y=0;
	mainwindow_height=200;
	mainwindow_width=400;
	AuthRetryCount=0;

	OpenvpnManagementPort=2222;

	minimizeAfterConnect = true;
	//showDebugConsole = false;
	useDefaultPaths = false;
	writeLogFile = true;
	useSilentQuit = false;
	holdGeneratedScripts = true;
	enableDebugPppd=false;
	enableDebugPptpd=false;
	enableDebugL2tpd=false;
	enableDebugXl2tpd=false;
	enableDebugOpenvpn=false;
	useColorizedLogOutput=true;
	showInterfaceIPinTooltip=true;
	dontQuitOnCloseEvent=true;
	PppdDebugLevel = false;
	doAutoConnectAtStartup=false;
	useKwallet=true;
	showStatusBar=true;
	showToolBar=true;
	firstUseOfKwallet=true;
	shutdownIsCalled=false;
	skipKwalletStoring = false;
	hideOnCloseInfo = false;
	enableFreeswanVerbose=false;
	doKillL2tpdIfStillRunning=true;
	doKillRacoonIfStillRunning=true;
	hideMainWindow=false;
	showInterfaceIPinTooltip = true;
	showConnectionTimeInTooltip = true;

	VpncDebugLevel = 0;
	RacoonDebugLevel = "info";
	KvpncDebugLevel = 0;
	OpenvpnDebugLevel =0;
	LogViewerFontSize=0; // can be from -3 up to +3

	DebugBackgroundcolor=black;

	ToolList = new QPtrList<ToolInfo>();
	ToolList->setAutoDelete( TRUE );

	AccountList = new QPtrList<VpnAccountData>();
	AccountList->setAutoDelete( TRUE ); // the list owns the objects

	InfoLogColor=Qt::black;
	ErrorLogColor=Qt::red;
	SuccessLogColor=Qt::darkGreen;
	DebugLogColor=Qt::yellow;

	KStandardDirs *dirs = KGlobal::dirs();
	logfileName = QString(dirs->saveLocation( "data" ));
	QString logfilePath = QString(logfileName + "/kvpnc/kvpnc.log");
	logfile.setName( logfilePath );
	logFileStream.setDevice( &logfile );

	currentProfile=0L;
}

KVpncConfig::~KVpncConfig()
{
	delete AccountList;
	delete ToolList;
}

void KVpncConfig::setLogOutput(QTextEdit *LogOutput)
{
	this->LogOutput = LogOutput;
}

void KVpncConfig::appendLogEntry( QString msg, LogType type )
{

	// write to logfile
	if ( writeLogFile )
	{
		if ( !logfile.isOpen() )
		{
			KStandardDirs * dirs = KGlobal::dirs();
			QString logfileName = dirs->saveLocation( "data" );
			logfileName += "/kvpnc/kvpnc.log"; // /root.kde/share/apps/kvpnc.log
			//    KMessageBox::information( this, logfileName, "info" );
			logfile.setName( logfileName );
			if ( !logfile.open( IO_WriteOnly | IO_Append ) )
				KMessageBox::error( 0, i18n( "Log file can not be opened!" ) );
			else
			{
				//				QTextStream s( &logfile );
				logFileStream << i18n( "Log session started at: " );
				logFileStream << QDateTime::currentDateTime().toString( Qt::TextDate );
				logFileStream << "\n";
				logfile.flush();
			}
		}
		else
		{
			QString date = QDate().currentDate().toString(Qt::ISODate)+ " ";
			QString time = QTime().currentTime().toString(Qt::ISODate)+ " ";
			QString prefix="";
			switch ( type )
			{
					case info:
					prefix=i18n("info")+": ";
					break;
					case remote:
					prefix=i18n("remote")+": ";
					break;
					case error:
					prefix=i18n("error")+": ";
					break;
					case success:
					prefix=i18n("success")+": ";
					break;
					case debug:
					prefix=i18n("debug")+": ";
					break;
			}
// 			appPointer->processEvents();
			logFileStream << date << time << prefix << msg << "\n";
			logfile.flush();
// 			appPointer->processEvents();
		}


		// write into debug console
		QString prefix="";
		QString postfix="";

		// font size
		prefix+="<font size=\""+QString().setNum(LogViewerFontSize)+"\">";
		postfix+="<\\font>";

		if (useColorizedLogOutput)
			prefix+="<font color=\"";

		switch ( type )
		{
				case info:
				if (useColorizedLogOutput)
				{
					prefix+=InfoLogColor.name();
					prefix+="\">";
				}
				prefix+=i18n("info")+": ";
				break;
				case remote:
				if (useColorizedLogOutput)
				{
					prefix+=RemoteLogColor.name();
					prefix+="\">";
				}
				prefix+=i18n("remote")+": ";

				break;
				case error:
				if (useColorizedLogOutput)
				{
					prefix+=ErrorLogColor.name();
					prefix+="\">";
				}
				prefix+=i18n("error")+": ";

				break;
				case success:
				if (useColorizedLogOutput)
				{
					prefix+=SuccessLogColor.name();
					prefix+="\">";
				}
				prefix+=i18n("success")+": ";
				break;
				case debug:
				if (useColorizedLogOutput)
				{
					prefix+=DebugLogColor.name();
					prefix+="\">";
				}
				prefix+=i18n("debug")+": ";
				break;
		}

		if (useColorizedLogOutput)
			postfix+="</font>";

		LogOutput->append( prefix+msg+postfix );
// 		appPointer->processEvents();
	}
}

void KVpncConfig::slotStatusMsg( const QString &text, int id )
{
	if ( id != ID_FLASH_MSG )
	{
		statusbar ->clear();
		statusbar ->changeItem( text, id );
	}
	else
	{
		statusbar->message( text, 2000 );
	}

}

void KVpncConfig::saveOptions()
{
	KStandardDirs * dirs = KGlobal::dirs();
	QString filePath = dirs->findResource ( "config", "kvpncrc" );
	QFile::remove
		( filePath );
	config->setGroup( "General Options" );

	config->writeEntry( "Minimize after connect", minimizeAfterConnect );
	config->writeEntry("Hide on startup", hideMainWindow );
	config->writeEntry( "Use silent quit", useSilentQuit );
	config->writeEntry( "Dont quit on CloseEvent", dontQuitOnCloseEvent );
	config->writeEntry( "Enable pppd debug", enableDebugPppd );
	config->writeEntry( "Enable pptpd debug", enableDebugPptpd );
	config->writeEntry( "Enable l2tpd debug", enableDebugL2tpd );
	config->writeEntry( "Enable xl2tpd debug", enableDebugXl2tpd );
	config->writeEntry( "Enable FreeSWAN verbose", enableFreeswanVerbose );
	config->writeEntry( "Show debugconsole", showDebugConsole );
	config->writeEntry( "Pid file for vpnc ", Vpnc_pid_file );
	config->writeEntry( "Vpnc debuglevel", VpncDebugLevel );
	config->writeEntry( "Racoon debuglevel", RacoonDebugLevel );
	config->writeEntry( "Kvpnc debuglevel", KvpncDebugLevel );
	config->writeEntry( "Pppd debuglevel", PppdDebugLevel );
	config->writeEntry( "Openvpn debuglevel", OpenvpnDebugLevel );
	config->writeEntry( "Pptp debuglevel", PptpLogLevel );
	config->writeEntry( "Path to vpnc-bin", pathToVpnc );
	config->writeEntry( "Path to vpnclient", pathToCiscoVpnc );
	config->writeEntry( "Path to racoon", pathToRacoon );
	config->writeEntry( "Path to setkey", pathToSetkey );
	config->writeEntry( "Path to iptables", pathToIptables );
	config->writeEntry( "Path to openssl", pathToOpenssl );
	config->writeEntry( "Path to freeswan", pathToFreeswan );
	config->writeEntry( "Path to pppd", pathToPppd );
	config->writeEntry( "Path to pptp", pathToPptp );
	config->writeEntry( "Path to l2tpd", pathToL2tpd );
	config->writeEntry( "Path to xl2tpd", pathToXl2tpd );
	config->writeEntry( "Path to kill", pathToKill );
	config->writeEntry( "Path to kill-all", pathToKillall );
	config->writeEntry( "Path to ping", pathToPing );
	config->writeEntry( "Path to openvpn", pathToOpenvpn );
	config->writeEntry( "Path to iputility", pathToIp );
	config->writeEntry( "Path to ifconfig", pathToIfconfig );
	config->writeEntry( "Path to route", pathToRoute );
	config->writeEntry( "Path to netstat", pathToNetstat );
	config->writeEntry( "Path to pkcs11-tool", pathToPkcs11Tool );
	config->writeEntry( "Path to vtund", pathToVtund );
	config->writeEntry( "Path to cisco_cert_mgr",pathToCiscoCertMgr);
	config->writeEntry( "Show Statusbar", showStatusBar );
	config->writeEntry( "Try connect timeout", tryConnectTimeout );
	config->writeEntry( "Last Profile", lastProfile );
	config->writeEntry( "Write log file", writeLogFile );
	config->writeEntry( "Hold generated scripts", holdGeneratedScripts );
	config->writeEntry( "Programs in path", programsInPath );
	config->writeEntry( "Info logwindow color", InfoLogColor );
	config->writeEntry( "Remote logwindow color", RemoteLogColor );
	config->writeEntry( "Error logwindow color", ErrorLogColor );
	config->writeEntry( "Success  logwindow color", SuccessLogColor );
	config->writeEntry( "Debug logwindow color", DebugLogColor );
	config->writeEntry("Debug background color", DebugBackgroundcolor );
	config->writeEntry( "Use colorized log output", useColorizedLogOutput );
	config->writeEntry( "Show interface IP in tooltip", showInterfaceIPinTooltip );
	config->writeEntry( "Auto connect profile", AutoConnectProfile );
	config->writeEntry( "Do auto connect at startup", doAutoConnectAtStartup );
	config->writeEntry( "Log viewer font size", LogViewerFontSize );
	config->writeEntry( "Mainwindow width", parent->width() );
	config->writeEntry( "Mainwindow height", parent->height() );
	config->writeEntry( "Mainwindow position x", parent->x() );
	config->writeEntry( "Mainwindow position y", parent->y() );
	config->writeEntry("Openvpn management port", OpenvpnManagementPort );
	config->writeEntry( "hideOnCloseInfo" ,hideOnCloseInfo);
//   config->writeEntry( "ToolBar Settings" ,parent->toolBar( "mainToolBar" ));
	config->writeEntry("Use KWallet",useKwallet);
	config->writeEntry("FeedbackMailSent",feedbackMailSent);
	config->writeEntry("Do kill l2tpd if still running",doKillL2tpdIfStillRunning);
	config->writeEntry("Do kill racoon if still running",doKillRacoonIfStillRunning);
	config->writeEntry("Do kill xl2tpd if still running",doKillXl2tpdIfStillRunning);
	config->writeEntry("Show connection time in Tooltip",showConnectionTimeInTooltip);
	config->writeEntry("Enable debug Openvpn",enableDebugOpenvpn);
// 	appPointer->processEvents();

	if (useKwallet && KWallet::Wallet::isEnabled())
		config->writeEntry( "First use of Kwallet", false );
	/* = user data = */
	VpnAccountData *it;
	if ( !AccountList->isEmpty() )
	{
		/* passwords with kwallet */
		if ( useKwallet && KWallet::Wallet::isEnabled())
		{
			if (!skipKwalletStoring )
			{
				if (KvpncDebugLevel > 2)
					appendLogEntry(i18n( "Wallet enabled and available, writing to wallet." ),debug);
				// Open local wallet
				wallet = KWallet::Wallet::openWallet(KWallet::Wallet::LocalWallet());
				//appPointer->processEvents();
				if (wallet != 0)
				{
				}
			}
		}
		else
		{
			if (KvpncDebugLevel > 2)
				appendLogEntry(i18n( "Wallet disabled or not available, writing to config file." ),debug);
		}

		for ( it = AccountList->first(); it; it = AccountList->next() )
		{
// 			appPointer->processEvents();
// 			std::cout << "Save profile: " << it->getName().ascii() << std::endl;
			if ( !it->getName().isEmpty() )
			{
				QString name = it->getName();
				QString ProfileName = "Profile_";
				ProfileName += name;
				config->setGroup( ProfileName );

				config->writeEntry("Description",it->getDescription());

				/* passwords with kwallet */
				if ( useKwallet && KWallet::Wallet::isEnabled())
				{
					if (!skipKwalletStoring )
					{
						if (KvpncDebugLevel > 2)
							appendLogEntry(i18n( "Wallet enabled and available, writing to wallet." ),debug);
						if (wallet != 0)
						{
							QString walletname="kvpnc";
							// Check if folder exists, otherwise create it
							bool walletOK=true;
							if (!wallet->hasFolder(walletname))
							{
								walletOK = wallet->createFolder(walletname);
// 								wallet->sync();
// 								appPointer->processEvents();
							}
							if (walletOK)
							{
								wallet->setFolder(walletname);
// 								appPointer->processEvents();
								//std::cout << "[set] account: " << ProfileName << ", loginname: " << loginname << ", password: " << pwd << std::endl;
								bool UserPasswordOK=true;
								if ( it->getSaveUserPassword() )
									UserPasswordOK = (wallet->writePassword (QString(name+"__user_pw"), it->getUserPassword()) == 0);
								else
									UserPasswordOK = (wallet->writePassword (QString(name+"__user_pw"), "") == 0);
// 								wallet->sync();
// 								appPointer->processEvents();

								bool PskOK=true;
								if ( it->getSavePsk() )
									PskOK = (wallet->writePassword (QString(name+"__psk"), it->getPreSharedKey()) == 0);
								else
									PskOK = (wallet->writePassword (QString(name+"__psk"), "") == 0);
// 								wallet->sync();

// 								appPointer->processEvents();

								bool PskKeyPassOK = (wallet->writePassword (QString(name+"__priv_key_pwd"), it->getPrivateKeyPass()) == 0);
// // 								wallet->sync();

// 								appPointer->processEvents();

								if (KvpncDebugLevel > 2)
								{
									if (UserPasswordOK)
										if (KvpncDebugLevel > 2)
											appendLogEntry(i18n( "write of %1 was ok." ).arg(i18n("user password")), debug);
									else
									{
										// 									if ( KMessageBox::warningContinueCancel( 0,
										// 									        i18n( "KVpnc is unable to save %1 password securely in your wallet.<br>"
										// 									              "Do you want to save the password in the <b>unsafe</b> configuration file instead?" ).arg(i18n("user password")),
										// 									        i18n( "Unable to store secure %1" ).arg(i18n("user password")),
										// 									        KGuiItem( i18n( "Store &Unsafe" ), QString::fromLatin1( "unlock" ),QString::fromLatin1( "KWalletFallbackToKConfig" ) ) ) == KMessageBox::Continue )
										// 									{
										// 										config->writeEntry( "User password", it->getUserPassword() );
										// 									}

										appendLogEntry(i18n( "write of %1 has failed." ).arg(i18n("user password")), error);
									}

									if (PskOK)
										if (KvpncDebugLevel > 2)
											appendLogEntry(i18n( "write of %1 was successful." ).arg(i18n("preshared key")), debug);
									else
									{
										// 									if ( KMessageBox::warningContinueCancel( 0,
										// 									        i18n( "KVpnc is unable to save %1 password securely in your wallet.<br>"
										// 									              "Do you want to save the password in the <b>unsafe</b> configuration file instead?" ).arg(i18n("pre shared key")),
										// 									        i18n( "Unable to store secure %1" ).arg(i18n("pre shared key")),
										// 									        KGuiItem( i18n( "Store &Unsafe" ), QString::fromLatin1( "unlock" ),QString::fromLatin1( "KWalletFallbackToKConfig" ) ) ) == KMessageBox::Continue )
										// 									{
										// 										config->writeEntry( "Pre shared key", it->getPreSharedKey() );
										// 									}
										appendLogEntry(i18n( "write of %1 has failed." ).arg(i18n("preshared key")),error);
									}

									if (PskOK)
										if (KvpncDebugLevel > 2)
											appendLogEntry(i18n( "write of %1 was successful." ).arg(i18n("preshared key")), debug);
									else
									{
										// 									if ( KMessageBox::warningContinueCancel( 0,
										// 									        i18n( "KVpnc is unable to save %1 password securely in your wallet.<br>"
										// 									              "Do you want to save the password in the <b>unsafe</b> configuration file instead?" ).arg(i18n("preshared key password")),
										// 									        i18n( "Unable to store secure %1" ).arg(i18n("reshared key password")),
										// 									        KGuiItem( i18n( "Store &Unsafe" ), QString::fromLatin1( "unlock" ),QString::fromLatin1( "KWalletFallbackToKConfig" ) ) ) == KMessageBox::Continue )
										// 									{
										// 										config->writeEntry( "Pre shared key", it->getPreSharedKey() );
										// 									}
										appendLogEntry(i18n( "write of %1 has failed." ).arg(i18n("preshared key")),error);
									}
									if (PskKeyPassOK)
										if (KvpncDebugLevel > 2)
											appendLogEntry(i18n( "write of %1 was successful." ).arg(i18n("preshared key password")), debug);
									else
									{
										// 									if ( KMessageBox::warningContinueCancel( 0,
										// 									        i18n( "KVpnc is unable to save %1 password securely in your wallet.<br>"
										// 									              "Do you want to save the password in the <b>unsafe</b> configuration file instead?" ).arg(i18n("preshared key password")),
										// 									        i18n( "Unable to store secure %1" ).arg(i18n("reshared key password")),
										// 									        KGuiItem( i18n( "Store &Unsafe" ), QString::fromLatin1( "unlock" ),QString::fromLatin1( "KWalletFallbackToKConfig" ) ) ) == KMessageBox::Continue )
										// 									{
										// 										config->writeEntry( "Pre shared key", it->getPreSharedKey() );
										// 									}
										appendLogEntry(i18n( "write of %1 has failed." ).arg(i18n("preshared key password")),error);
									}
									//std::cout << "success: " << pwdOK << std::endl;
								}
// 								appPointer->processEvents();
// 								wallet->sync();
							}
							else
							{
								KMessageBox::error( 0, i18n( "Unable to create wallet folder for kvpnc!" ) );
								appendLogEntry(i18n( "Unable to create wallet folder for kvpnc!" ), error);
							}
						}
					}
					else //sessionSaving neither writing to wallet nor to config-file
					{
					if (KvpncDebugLevel > 2)
							appendLogEntry(i18n( "Writing into Wallet is not possible at shutdown, skipping." ),debug);
					}
				}
				else//Wallet not available
				{
					//if (!useKwallet)
					{
						if (KvpncDebugLevel > 2)
							appendLogEntry(i18n( "Wallet disabled or not available, writing to config file." ),debug);
						// write passwords to config file :|
						if ( it->getSaveUserPassword() )
						{
							config->writeEntry( "User password", it->getUserPassword() );
						}
						if ( it->getSavePsk() )
						{
							config->writeEntry( "Pre shared key", it->getPreSharedKey() );
						}
						config->writeEntry( "PrivateKey password", it->getPrivateKeyPass() );
					}
				}

// 				appPointer->processEvents();

// 				KMessageBox::information(0,"connection type changed: "+QString().setNum(it->getConnectionType())+QString(" ")+it->getName(),QString("type set"));

				// normal config
				if ( it->getConnectionType() == VpnAccountData::cisco )
					config->writeEntry( "Connection type", "cisco" );
				else if ( it->getConnectionType() == VpnAccountData::ciscoorig )
					config->writeEntry( "Connection type", "ciscoorig" );
				else if ( it->getConnectionType() == VpnAccountData::racoon )
					config->writeEntry( "Connection type", "racoon" );
				else if ( it->getConnectionType() == VpnAccountData::l2tpd_racoon )
					config->writeEntry( "Connection type", "l2tpd (racoon)" );
				else if ( it->getConnectionType() == VpnAccountData::freeswan )
					config->writeEntry( "Connection type", "freeswan" );
				else if ( it->getConnectionType() == VpnAccountData::l2tpd_freeswan )
					config->writeEntry( "Connection type", "l2tpd (openswan)" );
				else if ( it->getConnectionType() == VpnAccountData::pptp )
					config->writeEntry( "Connection type", "pptp" );
				else if ( it->getConnectionType() == VpnAccountData::openvpn )
					config->writeEntry( "Connection type", "openvpn" );
				else if ( it->getConnectionType() == VpnAccountData::vtun )
					config->writeEntry( "Connection type", "vtun" );
				else
					config->writeEntry( "Connection type", "other" );
				config->writeEntry( "VPN Gateway", it->getGateway() );
				config->writeEntry( "VPN ID", it->getID() );
				config->writeEntry( "Username", it->getUserName() );

				config->writeEntry( "Save user password", it->getSaveUserPassword() );
				config->writeEntry( "Save PSK", it->getSavePsk() );
				config->writeEntry( "Save private key password", it->getSavePrivateKeyPassword() );
				config->writeEntry( "Private key", it->getPrivateKey() );
				config->writeEntry( "Use advanced settings", it->getUseAdvancedSettings() );
				config->writeEntry( "Application version", it->getApplicationVersion() );
				config->writeEntry( "Local port", it->getLocalPort() );
				config->writeEntry( "Remote port", it->getRemotePort() );
				config->writeEntry( "NT domain name", it->getNtDomainName() );
				config->writeEntry( "Perfect forward secrety", it->getPerfectForwardSecrety() );
				config->writeEntry( "IKE group", it->getIkeGroup() );
				
				config->writeEntry( "Use application version", it->getUseApplicationVersion() );
				config->writeEntry( "Use global IPSec secret", it->getUseGlobalIpsecSecret() );
				config->writeEntry( "Use IKE group", it->getUseIkeGroup() );
				config->writeEntry( "Use local port", it->getUseLocalPort() );
				config->writeEntry( "Use remote port", it->getUseRemotePort() );
				config->writeEntry( "Use NT domain name", it->getUseNtDomainName() );
				config->writeEntry( "Use single DES", it->getUseSingleDes() );
				config->writeEntry( "Use perfect Forward Secrety", it->getUsePerfectForwardSecrety() );
				config->writeEntry( "Remote net address", it->getRemoteNetAddr() );
				config->writeEntry( "Remote net mask", it->getRemoteNetMask() );

				config->writeEntry( "x509 certificate", it->getX509Certificate() );
				config->writeEntry( "Ca certificate", it->getCaCertificate() );
				config->writeEntry( "Network device", it->getNetworkDevice() );
				config->writeEntry( "Cert path", it->getCertPath() );
				if ( it->getAuthType() == VpnAccountData::cert )
					config->writeEntry( "Auth type", "cert" );
				else
					config->writeEntry( "Auth type", "psk" );
				config->writeEntry( "do ping ip", it->getDoPingIP() );
				config->writeEntry( "Ping host IP", it->getPingHostIP() );

// 				appPointer->processEvents();

				config->writeEntry( "Use special remote ID", it->getUseSpecialRemoteID() );
				config->writeEntry( "Use special local ID", it->getUseSpecialLocalID() );
				config->writeEntry( "Special server certificate", it->getSpecialServerCertificate() );
				config->writeEntry( "Use special server certificate", it->getUseSpecialServerCertificate() );
				config->writeEntry( "Special remote ID", it->getSpecialRemoteID() );
				config->writeEntry( "Special local ID", it->getSpecialLocalID() );
				config->writeEntry( "Local ID type", it->getLocalIDType() );
				config->writeEntry( "Use UDP-protocol", it->getUseUdp() );
				config->writeEntry( "Use UDP-port", it->getUseUdpPort() );
				config->writeEntry( "local UDP port", it->getUdpPort() );
				config->writeEntry( "use DNS_UPDATE", it->getUseDnsUpdate() );
				config->writeEntry( "use DNS-server", it->getUseDnsServer() );
				config->writeEntry( "DNS server", it->getDnsServer() );
				config->writeEntry( "get dns server from peer", it->getUseGetDnsFromPeer() );
				config->writeEntry( "refuse 40 bit encryption", it->getRefuse40BitEncryption() );
				config->writeEntry( "refuse 128 bit encryption", it->getRefuse128BitEncryption() );
				config->writeEntry( "require stateless encryption", it->getAllowStatefulMode() );
				config->writeEntry( "require mppe", it->getRequireMppe() );
				config->writeEntry( "refuse EAP", it->getRefuseEap() );
				config->writeEntry( "Disable MPPE compression", it->getDisableMPPEComp() );
				config->writeEntry( "Local virtual IP", it->getLocalVirtualIP() );
				config->writeEntry( "Remote virtual IP", it->getRemoteVirtualIP() );
				config->writeEntry( "Pre shared key file", it->getPreSharedKeyFile() );
				config->writeEntry( "Execute command before connect", it->getExecuteCmdBeforeConnect() );
				config->writeEntry( "Execute command after connect", it->getExecuteCmdAfterConnect() );
				config->writeEntry( "Execute command before disconnect", it->getExecuteCmdBeforeDisconnect() );
				config->writeEntry( "Execute command after disconnect", it->getExecuteCmdAfterDisconnect() );
				config->writeEntry( "Command before connect", it->getCommandBeforeConnect() );
				config->writeEntry( "Command after connect", it->getCommandAfterConnect() );
				config->writeEntry( "Command before disconnect", it->getCommandBeforeDisconnect() );
				config->writeEntry( "Command after disconnect", it->getCommandAfterDisconnect() );
				config->writeEntry( "Use no BSD compression", it->getUseNoBsdComp() );
				config->writeEntry( "Do not use no IP by default", it->getUseNoIpDefault());
				config->writeEntry( "Use no deflate", it->getUseNoDeflate() );
				config->writeEntry( "Set default route", it->getSetDefaultRoute() );
				config->writeEntry( "Replace default route", it->getReplaceDefaultRoute() );
				config->writeEntry( "Use own MTU", it->getUseMtu() );
				config->writeEntry( "Use own MRU", it->getUseMru() );
				config->writeEntry( "MTU for pppd", it->getMtu() );
				config->writeEntry( "MRU for pppd", it->getMru() );
				config->writeEntry( "Use Virtual IP", it->getUseVirtualIP() );
				config->writeEntry( "Virtual IP", it->getVirtualIP() );
				config->writeEntry( "PSK is in file", it->getPskIsInFile() );
				config->writeEntry( "Use additional network routes", it->getUseAdditionalNetworkRoutes() );
				config->writeEntry( "Hash algorithm", it->getHashAlgo() );
				config->writeEntry( "Encryption algorithm", it->getEncryptionAlgorithm() );
				config->writeEntry( "Authentication algorithm", it->getAuthenticationAlgorithm() );
				config->writeEntry( "Tunnel device type", it->getTunnelDeviceType() );
				config->writeEntry( "Use userdefined port", it->getUseUserdefinedPort() );
				config->writeEntry( "Userdefined port", it->getUserdefinedPort() );
				config->writeEntry( "Keep default route", it->getKeepDefaultRoute() );
				config->writeEntry( "NS cert type", it->getNsCertType() );
				config->writeEntry( "Use NS cert type", it->getUseNsCertType() );
				config->writeEntry( "Use connection status check", it->getUseConnectionStatusCheck() );
				config->writeEntry( "Connection check success count", it->getConnectionStatusCheckSuccessCount() );
				config->writeEntry( "Connection check status interval", it->getConnectionStatusInterval() );
				config->writeEntry( "Do reconnect after connection lost", it->getDoReconnectAfterConnectionLost());
				config->writeEntry( "Disable LZO compression", it->getDisableLzoCompression());
				config->writeEntry( "AuthWithUsernameAndPassword", it->getAuthWithUsernameAndPassword() );
				config->writeEntry( "AllowEmptyGroupPassword", it->getAllowEmptyGroupPassword() );
				config->writeEntry( "Use userdefinied cipher", it->getUseUserdefiniedCipher() );
				config->writeEntry( "Userdefinied cipher", it->getUserdefiniedCipher() );
				config->writeEntry( "Use redirect gateway", it->getUseRedirectGateway() );
// 				appPointer->processEvents();
				config->writeEntry( "Use TLS auth", it->getUseTlsAuth() );
				config->writeEntry( "TLS auth file", it->getTlsAuthFile() );
				config->writeEntry( "Use HTTP proxy", it->getUseHttpProxy() );
				config->writeEntry( "HTTP proxy host", it->getHttpProxy() );
				config->writeEntry( "HTTP proxy port", it->getHttpProxyPort() );
				config->writeEntry( "HTTP proxy timeout", it->getHttpProxyTimeout() );
				config->writeEntry( "Dont save username", it->getDontSaveUsername() );
				config->writeEntry( "Use mode config", it->getUseModeConfig() );
				config->writeEntry( "Exchange mode", it->getExchangeMode() );
				config->writeEntry( "Use delay at reconnect", it->getUseReconnectDelay() );
				config->writeEntry( "Reconnect delay", it->getReconnectDelay() );
				config->writeEntry( "Use TLS host", it->getUseTlsRemoteHost() );
				config->writeEntry( "TLS remote host", it->getTlsRemoteHost() );
				config->writeEntry( "Disable opportunistic encryption", it->getDisableOpportunisticEncryption() );
				config->writeEntry( "Right next hop", it->getRightNextHop() );
				config->writeEntry( "Left next hop", it->getLeftNextHop() );
				config->writeEntry( "Use userdefinied packet size for fragmentation", it->getUseFragment() );
				config->writeEntry( "Use userdef packet size", it->getUseMssfix()  );
				config->writeEntry( "Fragment", it->getFragment() );
				config->writeEntry( "PeerTimeout", it->getPeerTimeout() );
				config->writeEntry("Disable CCP", it->getDisableCcp() );
				config->writeEntry("Use smartcard", it->getUseSmartcard() );
				config->writeEntry("Use Xauth interactive", it->getUseXauthInteractive() );
				config->writeEntry("Use HTTP Proxy Authentication", it->getUseHttpProxyAuth() );
				config->writeEntry("Use HTTP Proxy Authtype", it->getHttpProxyAuthType() );
				config->writeEntry("Use HTTP Proxy Auth user", it->getHttpProxyUser() );
				config->writeEntry("Use HTTP Proxy Auth pass", it->getHttpProxyPass() );
				config->writeEntry("Use only CA cert and user auth", it->getUseOnlyCaCertAndUserAuth() );
				config->writeEntry("Use mail address as identifier", it->getUseMailAddressAsIdentifier() );
				config->writeEntry("Use right next hop", it->getUseRightNextHop() );
				config->writeEntry("Use left next hop", it->getUseLeftNextHop() );
				config->writeEntry("Pkcs11 providers", it->getPkcs11Providers() );
				config->writeEntry("Pkcs11 slot type", it->getPkcs11SlotType() );
				config->writeEntry("Pkcs11 slot", it->getPkcs11Slot() );
				config->writeEntry("Pkcs11 id type", it->getPkcs11IdType() );
				config->writeEntry("Pkcs11 id", it->getPkcs11Id() );
				config->writeEntry("Pkcs11 sign mode", it->getPkcs11SignMode() );
				config->writeEntry("Use Pkcs11 providers", it->getUsePkcs11Providers() );
				config->writeEntry("Allow empty private key password", it->getAllowEmptyPrivateKeyPassword());
				config->writeEntry("Allow ip address change of peer", it->getAllowIpAddressChangeOfPeer());
				config->writeEntry("Auth method", it->getAuthMethod());
				config->writeEntry("Command after connect delay time", it->getCommandAfterConnectDelayTime());
				config->writeEntry("Use search domain in resolv conf",it->getUseSearchDomainInResolvConf());
				config->writeEntry("Search domain in resolv conf",it->getSearchDomainInResolvConf());
				config->writeEntry("Authentication direction",it->getAuthenticationDirection());
				config->writeEntry("IPSec ESP",it->getIpsecEsp());
				config->writeEntry("IPSec IKE",it->getIpsecIke());
				config->writeEntry("Vtun profile",it->getVtunProfile());
				config->writeEntry("Disable data encryption", it->getDisableDataEncryption());
				config->writeEntry("Use authentication algorithm", it->getUseAuthenticationAlgorithm());
				config->writeEntry("Fix path mtu discovery problem" , it ->getFixPathMtuDiscoveryProblem());

// 				appPointer->processEvents();

				QString AdditionalNetworkRoutesString;
				QStringList AdditionalNetworkRoutes = it->getAdditionalNetworkRoutes();

				// Networks delimited by a ','
				for ( QStringList::Iterator it2 = AdditionalNetworkRoutes.begin(); it2 != 	AdditionalNetworkRoutes.end(); ++it2 )
				{
					AdditionalNetworkRoutesString+=*it2;
					AdditionalNetworkRoutesString+=",";
				}
				AdditionalNetworkRoutesString=AdditionalNetworkRoutesString.left(AdditionalNetworkRoutesString.length()-1);
				config->writeEntry( "Additional network routes", AdditionalNetworkRoutesString );

// 				wallet->sync();
				/* give info */
// 				slotStatusMsg ( i18n( "Profile \"%1\" saved." ).arg( ProfileName.remove("Profile_") ), ID_FLASH_MSG );

				appendLogEntry ( i18n( "Profile \"%1\" saved." ).arg( ProfileName.remove("Profile_") ) , info);
// 				appPointer->processEvents();
			}
			appPointer->processEvents();
		}
	}


// 	if ( !skipKwalletStoring && wallet != 0)
// 		if (useKwallet && KWallet::Wallet::isEnabled())
// 			if (wallet->isOpen())
// 				wallet->sync();
	config->sync();
	doBackupConfig();

	slotStatusMsg ( i18n( "Profiles saved." ) , ID_FLASH_MSG );
	appPointer->processEvents();
}

void KVpncConfig::loadOptions()
{
	config->setGroup( "Notification Messages" );
	hideOnCloseInfo = config->readBoolEntry( "hideOnCloseInfo" ,false);

	config->setGroup( "General Options" );
	minimizeAfterConnect = config->readBoolEntry( "Minimize after connect", true );
	hideMainWindow = config->readBoolEntry("Hide on startup", false );
	useSilentQuit = config->readBoolEntry( "Use silent quit", false );
	dontQuitOnCloseEvent = config->readBoolEntry( "Dont quit on CloseEvent", true );
	showDebugConsole = config->readBoolEntry( "Show debugconsole", true );
	enableDebugPppd = config->readBoolEntry( "Enable pppd debug", false );
	enableDebugPptpd = config->readBoolEntry( "Enable pptpd debug", false );
	enableFreeswanVerbose = config->readBoolEntry( "Enable FreeSWAN verbose", false );
	Vpnc_pid_file = config->readEntry( "Pid file for vpnc ", "/var/run/vpnc/pid" );
	RacoonDebugLevel = config->readEntry( "Racoon debuglevel", "info" );
	// we need to correct old int value
	if (RacoonDebugLevel == "0")
		RacoonDebugLevel="info";

	VpncDebugLevel = config->readNumEntry( "Vpnc debuglevel", 0 );
	KvpncDebugLevel = config->readNumEntry( "Kvpnc debuglevel", 0 );
	PppdDebugLevel = config->readBoolEntry( "Pppd debuglevel", false );
	OpenvpnDebugLevel = config->readNumEntry( "Openvpn debuglevel", 0 );
	PptpLogLevel = config->readNumEntry( "Pptp debuglevel", 1 );
	enableDebugL2tpd = config->readBoolEntry( "enable l2tpd debug", false );
	enableDebugXl2tpd = config->readBoolEntry( "Enable xl2tpd debug", false );
	pathToVpnc = config->readEntry( "Path to vpnc-bin", "/usr/sbin/vpnc" );
	pathToCiscoVpnc = config->readEntry( "Path to vpnclient", "/usr/local/bin/vpnclient" );
	pathToSetkey = config->readEntry( "Path to setkey", "/usr/sbin/setkey" );
	pathToRacoon = config->readEntry( "Path to racoon", "/usr/sbin/racoon" );
	pathToIptables = config->readEntry( "Path to iptables", "/sbin/iptables" );
	pathToOpenssl = config->readEntry( "Path to openssl", "/usr/bin/openssl" );
	pathToFreeswan = config->readEntry( "Path to freeswan", "/usr/sbin/ipsec" );
	pathToIp = config->readEntry( "Path to iputility", "/sbin/ip" );
	pathToIfconfig = config->readEntry( "Path to ifconfig", "/sbin/ifconfig" );
	pathToRoute = config->readEntry( "Path to route", "/sbin/route" );
	pathToNetstat = config->readEntry( "Path to netstat", "/bin/netstat" );
	pathToPppd = config->readEntry ("Path to pppd","/usr/sbin/pppd");
	pathToPptp = config->readEntry ("Path to pptp","/usr/sbin/pptp");
	pathToL2tpd = config->readEntry ("Path to l2tpd","/usr/sbin/l2tpd");
	pathToXl2tpd = config->readEntry ("Path to xl2tpd","/usr/sbin/xl2tpd");
	pathToKill = config->readEntry ("Path to kill","/bin/kill");
	pathToKillall = config->readEntry ("Path to kill-all","/usr/bin/killall");
	pathToPing = config->readEntry ("Path to ping","/bin/ping");
	pathToOpenvpn = config->readEntry ("Path to openvpn","/usr/sbin/openvpn");
	pathToPkcs11Tool = config->readEntry( "Path to pkcs11-tool", "/usr/bin/pkcs11-tool" );
	pathToVtund = config->readEntry( "Path to vtund", "/usr/sbin/vtund" );
	pathToCiscoCertMgr = config->readEntry( "Path to cisco_cert_mgr","/usr/local/bin/cisco_cert_mgr");

	tryConnectTimeout = QString( config->readEntry( "Try connect timeout", "10" ) ).toInt();
	lastProfile = config->readEntry( "Last Profile", "" );
	writeLogFile = config->readBoolEntry( "Write log file", true );
	holdGeneratedScripts = config->readBoolEntry( "Hold generated scripts", true );
	showStatusBar = config->readBoolEntry( "Show Statusbar", true );
	programsInPath = config->readBoolEntry( "Programs in path", true );

	if (programsInPath)
		useDefaultPaths=true;

	InfoLogColor = config->readColorEntry ( "Info logwindow color", new QColor(Qt::black) );
	RemoteLogColor = config->readColorEntry ( "Remote logwindow color", new QColor(Qt::blue) );
	ErrorLogColor = config->readColorEntry( "Error logwindow color", new QColor(Qt::red ));
	SuccessLogColor = config->readColorEntry( "Success  logwindow color", new QColor(Qt::darkGreen) );
	DebugLogColor = config->readColorEntry( "Debug logwindow color", new QColor(255,175,0 ));
	DebugBackgroundcolor = config->readColorEntry("Debug background color", new QColor (Qt::white) );
	useColorizedLogOutput = config->readBoolEntry("Use colorized log output", true);
	showInterfaceIPinTooltip = config->readBoolEntry( "Show interface IP in tooltip", true );
	AutoConnectProfile= config->readEntry( "Auto connect profile", "" );
	doAutoConnectAtStartup = config->readBoolEntry( "Do auto connect at startup", false );
	LogViewerFontSize = config->readNumEntry( "Log viewer font size", 2 );

	WindowSize = QSize( config->readNumEntry( "Mainwindow width", 50 ), this->config->readNumEntry( "Mainwindow height", 50 ) );
	WindowPos = QPoint ( config->readNumEntry( "Mainwindow position x", 10 ), this->config->readNumEntry( "Mainwindow position y", 50 ) );

	OpenvpnManagementPort = config->readNumEntry("Openvpn management port", 2222 );

	appPointer->processEvents();

	if ( writeLogFile )
		if ( !logfile.isOpen() )
		{
			KStandardDirs *dirs = KGlobal::dirs();

			QDir AppFolder (QString(dirs->saveLocation( "data" )+"/kvpnc"));
			if (!AppFolder.exists())
			{
				// 		KMessageBox::error( this, i18n( "creating dir: %1" ).arg(dirs->saveLocation( "data" )+"/kvpnc" ));
				QDir AppFolder2(dirs->saveLocation( "data" ));
				if(!AppFolder2.mkdir("kvpnc",true))
				{
					KMessageBox::error( 0, i18n( "The appdir for kvpnc could not be created. Be sure that you have write permission of \"%1\"." ).arg(dirs->saveLocation( "data" )) );
					appendLogEntry( i18n( "The appdir for kvpnc could not be created. Be sure that you have write permission of \"%1\"." ).arg(dirs->saveLocation( "data" )),error);
				}
			}

			logfileName = dirs->saveLocation( "data" );
			logfileName += "/kvpnc/kvpnc.log";
			//KMessageBox::information( this, logfileName, "info" );
			logfile.setName( logfileName );
			if ( !logfile.open( IO_WriteOnly | IO_Append ) )
			{
				KMessageBox::error( 0, i18n( "Log file cant be opened!" ) );
				appendLogEntry(i18n( "Unable to find \"%1\"!" ).arg("pppd"),error);
			}
			else
			{
				QTextStream s( &logfile );
				s << i18n( "Log session started at: " ) << QDateTime::currentDateTime().toString( Qt::TextDate ) << endl;
			}
		}

	useKwallet = config->readBoolEntry("Use KWallet", true);
	firstUseOfKwallet = config->readBoolEntry( "First use of Kwallet", true );
	feedbackMailSent = config->readBoolEntry("FeedbackMailSent",false);
	doKillL2tpdIfStillRunning = config->readBoolEntry("Do kill l2tpd if still running",true);
	doKillXl2tpdIfStillRunning = config->readBoolEntry("Do kill xl2tpd if still running",true);
	doKillRacoonIfStillRunning = config->readBoolEntry("Do kill racoon if still running",true);
	showConnectionTimeInTooltip = config->readBoolEntry("Show connection time in Tooltip",true);
	enableDebugOpenvpn  = config->readBoolEntry("Enable debug Openvpn",false);



	if ( KvpncDebugLevel > 2 )
		appendLogEntry( i18n( "Global configuration loaded." ) ,info);


	/* = user data = */
	/* old style: one profile: will be removed in future */
	/*
	config->setGroup( "Client Options" );
	this->mw->gatewayLineEdit->setText( config->readEntry( "VPN Gateway", "" ) );
	this->mw->IDLineEdit->setText( config->readEntry( "VPN ID", "" ) );
	this->mw->PSKLineEdit->setText( config->readEntry( "Group password", "" ) );
	this->mw->UsernameLineEdit->setText( config->readEntry( "Username", "" ) );
	this->mw->PasswordEdit->setText( config->readEntry( "Password", "" ) );

	this->mw->CheckUserPass->setChecked( config->readBoolEntry( "Save user password", false ) );
	this->mw->CheckGroupPass->setChecked( config->readBoolEntry( "Save group password", false ) );
	*/

	/* profiles are stored in a group which is named to the following scheme:
	 Profile_XXXXX
	 XXXXX is the account name (important: unique!)
	*/
	QStringList configGroups = config->groupList();
	bool oldConfigurationFound = false;

	bool sessionFound = false;

	for ( QStringList::Iterator it = configGroups.begin(); it != configGroups.end(); ++it )
	{
		QString name = *it;
		name.stripWhiteSpace();
		if ( name.left( 7 ) == "Profile" && name.length() > 8 )
		{
			// Profile found

			sessionFound = true;

			if ( KvpncDebugLevel > 2 )
			{
				QString tmp = i18n( "Profile found: " );
				tmp += name.right( ( name.length() ) - 8 );
				appendLogEntry ( tmp, debug );
			}
			config->setGroup( name );
			QString UserPassword="";
			QString PrivateKeyPass="";
			QString PreSharedKey ="";

			/* passwords with kwallet */
			if (useKwallet && KWallet::Wallet::isEnabled() && !firstUseOfKwallet)
			{
				if (KvpncDebugLevel > 2)
					appendLogEntry(i18n( "Wallet enabled and available, reading passwords from wallet." ),debug);
				// Open local wallet
				wallet = KWallet::Wallet::openWallet(KWallet::Wallet::LocalWallet());
				if (wallet != 0)
				{
					QString walletname="kvpnc";

					if (!wallet->hasFolder(walletname))
					{
						wallet->createFolder(walletname);
						wallet->sync();
					}

					if (wallet->setFolder(walletname))
					{
						if (KvpncDebugLevel > 2)
							appendLogEntry(i18n( "Folder for kvpnc has been set." ),debug);

						QString profilename = name.right( ( name.length() ) - 8 );

						if (wallet->readPassword(QString(profilename+"__user_pw"), UserPassword) != 0)
							appendLogEntry(i18n( "read of %1 has failed." ).arg(i18n("user password")),error);
						else
							if (KvpncDebugLevel > 2)
								appendLogEntry(i18n( "read of %1 was successful." ).arg(i18n("user password")),debug);

						if (wallet->readPassword(QString(profilename+"__psk"), PreSharedKey) != 0)
							appendLogEntry(i18n( "read of %1 has failed." ).arg(i18n("preshared key")),error);
						else
							if (KvpncDebugLevel > 2)
								appendLogEntry(i18n( "read of %1 was successful." ).arg(i18n("preshared key")),debug);

						if (wallet->readPassword(QString(profilename+"__priv_key_pwd"), PrivateKeyPass) != 0)
							appendLogEntry(i18n( "read of %1 has failed." ).arg(i18n("preshared key password")),error);
						else
							if (KvpncDebugLevel > 2)
								appendLogEntry(i18n( "read of %1 was successful." ).arg(i18n("preshared key password")),debug);
					}
					else
					{
						KMessageBox::error( 0, i18n( "Unable to set wallet folder for kvpnc!" ) );
						appendLogEntry(i18n( "Unable to set wallet folder for kvpnc!" ), error);
					}
					appPointer->processEvents();
				}
				else
				{
					KMessageBox::error( 0, i18n( "Unable to open wallet folder for kvpnc!" ) );
					appendLogEntry(i18n( "Unable to open wallet folder for kvpnc!" ), error);
				}


			}
			else
			{
				if (KvpncDebugLevel > 2)
				{
					if (useKwallet && KWallet::Wallet::isEnabled() && firstUseOfKwallet)
						appendLogEntry(i18n( "Wallet enabled, available but first time, reading passwords from config file." ),debug);
					else
						appendLogEntry(i18n( "Wallet disabled or not available, reading passwords from config file." ),debug);
				}
				// read from config file
				UserPassword = config->readEntry( "User password", "" );
				PrivateKeyPass = config->readEntry( "PrivateKey password", "" );
				PreSharedKey = config->readEntry( "Pre shared key", "" );
			}

			VpnAccountData::ConnectionType ConnType = VpnAccountData::ConnectionType( VpnAccountData::cisco );
			QString type_string = config->readEntry( "Connection type", "cisco" );

			if ( type_string == "cisco" )
				ConnType = VpnAccountData::cisco;
			else if ( type_string == "ciscoorig" )
				ConnType = VpnAccountData::ciscoorig;
			else if ( type_string == "racoon" )
				ConnType = VpnAccountData::racoon;
			else if ( type_string == "l2tpd (racoon)" )
				ConnType = VpnAccountData::l2tpd_racoon;
			else if ( type_string == "freeswan" )
				ConnType = VpnAccountData::freeswan;
			else if ( type_string == "l2tpd (openswan)" )
				ConnType = VpnAccountData::l2tpd_freeswan;
			else if ( type_string == "pptp" )
				ConnType = VpnAccountData::pptp;
			else if ( type_string == "openvpn" )
				ConnType = VpnAccountData::openvpn;
			else if ( type_string == "vtun" )
				ConnType = VpnAccountData::vtun;
			else
				ConnType = VpnAccountData::other;

			QString Name = name.right( name.length() - 8 );
			VpnAccountData *data = new VpnAccountData( ConnType, Name );
			data->setGateway( config->readEntry( "VPN Gateway", "" ));
			data->setID( config->readEntry( "VPN ID", "" ) );
			data->setDescription( config->readEntry("Description",""));
			data->setUserName( config->readEntry( "Username", "" ));
			data->setSaveUserPassword( config->readBoolEntry( "Save user password", false ));
			data->setSavePsk( config->readBoolEntry( "Save PSK", false ));
			data->setSavePrivateKeyPassword( config->readBoolEntry( "Save private key password", true ) );
			data->setUseAdvancedSettings( config->readBoolEntry( "Use advanced settings", false ));
			data->setApplicationVersion( config->readEntry( "Application version", "Cisco Systems VPN Client 0.3-rm+zomb.1:Linux" ));
			data->setLocalPort( config->readNumEntry( "Local port", 500 ));
			data->setRemotePort( config->readNumEntry( "Remote port", 500 ));
			data->setNtDomainName( config->readEntry( "NT domain name", "" ));
			data->setPerfectForwardSecrety( config->readEntry( "Perfect forward secrety", "server" ));
			data->setIkeGroup( config->readEntry( "IKE group", "dh1" ));
			data->setUseApplicationVersion( config->readBoolEntry( "Use application version", false ));
			data->setUseGlobalIpsecSecret( config->readBoolEntry( "Use global IPSec secret", false ));
			data->setUseIkeGroup( config->readBoolEntry( "Use IKE group", false ));
			data->setUseLocalPort( config->readBoolEntry( "Use local port", false ));
			data->setUseRemotePort( config->readBoolEntry( "Use remote port", false ));
			data->setUseNtDomainName( config->readBoolEntry( "Use NT domain name", false ));
			data->setUseSingleDes( config->readBoolEntry( "Use single DES", false ));
			data->setUsePerfectForwardSecrety( config->readBoolEntry( "Use perfect Forward Secrety", false ));
			data->setX509Certificate( config->readEntry( "x509 certificate", "" ));
			data->setCaCertificate( config->readEntry( "Ca certificate", "" ));
			data->setNetworkDevice( config->readEntry( "Network device", "default" ));
			data->setCertPath( config->readEntry( "Cert path", "/etc/racoon/certs" ));
			data->setPrivateKey( config->readEntry( "Private key", "" ));
			VpnAccountData::AuthenticationType authtype;
			if ( config->readEntry( "Auth type", "cert" ) == "cert" )
				authtype = VpnAccountData::cert;
			else
				authtype = VpnAccountData::psk;
			data->setAuthType(authtype);

			appPointer->processEvents();

			data->setDoPingIP( config->readBoolEntry( "do ping ip", false ));
			data->setPingHostIP( config->readEntry( "Ping host IP", "" ));
			data->setUseSpecialRemoteID( config->readBoolEntry( "Use special remote ID", false ));
			data->setUseSpecialLocalID( config->readBoolEntry( "Use special local ID", false ));
			data->setSpecialRemoteID( config->readEntry( "Special remote ID", "" ));
			data->setSpecialLocalID( config->readEntry( "Special local ID", "" ));
			data->setLocalIDType(config->readEntry( "Local ID type", "asn1dn") );
			data->setUseSpecialServerCertificate( config->readBoolEntry( "Use special server certificate", false ));
			data->setSpecialServerCertificate( config->readEntry( "Special server certificate", "" ));
			data->setUseUdp( config->readBoolEntry( "Use UDP-protocol", false ));
			data->setUseUdpPort( config->readBoolEntry( "Use UDP-port", false ));
			data->setUdpPort( config->readNumEntry( "local UDP port", 4500 ));
			data->setUseDnsUpdate( config->readBoolEntry( "use DNS_UPDATE", true));
			data->setUseDnsServer( config->readBoolEntry( "use DNS-server", false));
			data->setDnsServer( config->readEntry( "DNS server", "" ));
			data->setUseGetDnsFromPeer( config->readBoolEntry( "get dns server from peer", true ));
			data->setRefuse40BitEncryption( config->readBoolEntry( "refuse 40 bit encryption", true ));
			data->setRefuse128BitEncryption( config->readBoolEntry( "refuse 128 bit encryption", false ));
			data->setAllowStatefulMode( config->readBoolEntry( "require stateless encryption",false ));
			data->setRequireMppe( config->readBoolEntry( "require mppe", true ));
			data->setRefuseEap( config->readBoolEntry( "refuse EAP", false ));
			data->setUseNoBsdComp( config->readBoolEntry( "Use no BSD compression", true ));
			data->setUseNoIpDefault(config->readBoolEntry( "Do not use no IP by default", false));
			data->setUseNoDeflate( config->readBoolEntry( "Use no deflate", true ));
			data->setDisableMPPEComp( config->readBoolEntry( "Disable MPPE compression", false ));
			data->setLocalVirtualIP( config->readEntry( "Local virtual IP", "" ));
			data->setRemoteVirtualIP( config->readEntry( "Remote virtual IP", "" ));
			data->setPreSharedKeyFile( config->readEntry( "Pre shared key file", "" ));
			data->setExecuteCmdBeforeConnect( config->readBoolEntry( "Execute command before connect",false));
			data->setExecuteCmdAfterConnect( config->readBoolEntry( "Execute command after connect",false));
			data->setExecuteCmdBeforeDisconnect( config->readBoolEntry( "Execute command before disconnect", false));
			data->setExecuteCmdAfterDisconnect( config->readBoolEntry( "Execute command after disconnect", false));
			data->setCommandBeforeConnect( config->readEntry( "Command before connect", "" ));
			data->setCommandAfterConnect( config->readEntry( "Command after connect", "" ));
			data->setCommandBeforeDisconnect( config->readEntry( "Command before disconnect", "" ));
			data->setCommandAfterDisconnect( config->readEntry( "Command after disconnect", "" ));
			data->setSetDefaultRoute( config->readBoolEntry( "Set default route", true ));
			data->setReplaceDefaultRoute( config->readBoolEntry( "Replace default route", false ));
			data->setUseMtu( config->readBoolEntry( "Use own MTU", false ));
			data->setUseMru( config->readBoolEntry( "Use own MRU", false ));
			data->setMtu( config->readNumEntry( "MTU for pppd", 1492 ));
			data->setMru( config->readNumEntry( "MRU for pppd", 1492 ));
			data->setUseVirtualIP( config->readBoolEntry( "Use Virtual IP", false ));
			data->setVirtualIP( config->readEntry( "Virtual IP", "" ));
			data->setPskIsInFile( config->readBoolEntry( "PSK is in file", false ));
			data->setUseAdditionalNetworkRoutes(	config->readBoolEntry( "Use additional network routes", false ));
			appPointer->processEvents();
			QString AdditionalNetworkRoutesString = config->readEntry( "Additional network routes", "" );
			// Networks delimited by a ','
			QStringList AdditionalNetworkRoutes(QStringList::split( ",", AdditionalNetworkRoutesString ));
			data->setAdditionalNetworkRoutes(AdditionalNetworkRoutes);
			data->setHashAlgo( config->readEntry( "Hash algorithm", "md5" ));
			data->setEncryptionAlgorithm( config->readEntry( "Encryption algorithm", "3des" ));
			data->setAuthenticationAlgorithm( config->readEntry( "Authentication algorithm", "hmac_sha1" ));
			data->setTunnelDeviceType( config->readEntry( "Tunnel device type", "tun" ));
			data->setUseUserdefinedPort( config->readBoolEntry( "Use userdefined port", false ));
			data->setUserdefinedPort( config->readNumEntry( "Userdefined port", 1194 ));
			data->setKeepDefaultRoute( config->readBoolEntry ("Keep default route", false ));
			data->setNsCertType( config->readEntry( "NS cert type", "client" ));
			data->setUseNsCertType( config->readBoolEntry( "Use NS cert type", false ));
			data->setUseConnectionStatusCheck ( config->readBoolEntry( "Use connection status check", true ));
			data->setConnectionStatusCheckSuccessCount ( config->readNumEntry( "Connection check success count", 4 ));
			data->setConnectionStatusInterval ( config->readNumEntry( "Connection check status interval", 1 ));
			data->setDoReconnectAfterConnectionLost(config->readBoolEntry("Do reconnect after connection lost", false));
			data->setDisableLzoCompression(config->readBoolEntry("Disable LZO compression", false));
			data->setUserPassword( UserPassword );
			data->setRemoteNetAddr( config->readEntry("Remote net address","") );
			data->setRemoteNetMask( QString().setNum(config->readNumEntry("Remote net mask",24 )));
			data->setPreSharedKey( PreSharedKey );
			data->setPrivateKeyPass( PrivateKeyPass );
			data->setAuthWithUsernameAndPassword( config->readBoolEntry( "AuthWithUsernameAndPassword",false ) );
			data->setAllowEmptyGroupPassword( config->readBoolEntry( "AllowEmptyGroupPassword", false ) );
			data->setUseUserdefiniedCipher( config->readBoolEntry( "Use userdefinied cipher", false ) );
			data->setUserdefiniedCipher( config->readEntry( "Userdefinied cipher", "" ) );
			appPointer->processEvents();
			data->setUseRedirectGateway( config->readBoolEntry( "Use redirect gateway", false ) );
			data->setUseTlsAuth( config->readBoolEntry( "Use TLS auth", false ) );
			data->setTlsAuthFile( config->readEntry( "TLS auth file", "" ) );
			data->setUseHttpProxy( config->readBoolEntry( "Use HTTP proxy", false ) );
			data->setHttpProxy( config->readEntry( "HTTP proxy host", "" ) );
			data->setHttpProxyPort( config->readNumEntry( "HTTP proxy port", 8080 ) );
			data->setHttpProxyTimeout( config->readNumEntry( "HTTP proxy timeout", 5 ) );
			data->setDontSaveUsername( config->readBoolEntry( "Dont save username", false ) );
			data->setUseModeConfig( config->readBoolEntry( "Use mode config", false ) );
			data->setExchangeMode( config->readEntry( "Exchange mode", "main" ) );
			data->setUseReconnectDelay( config->readBoolEntry( "Use delay at reconnect", false ) );
			data->setReconnectDelay( config->readNumEntry( "Reconnect delay", 5 ) );
			data->setUseTlsRemoteHost( config->readBoolEntry( "Use TLS host", false) );
			data->setTlsRemoteHost( config->readEntry( "TLS remote host", "") );
			data->setDisableOpportunisticEncryption( config->readBoolEntry( "Disable opportunistic encryption", false  ) );
			data->setRightNextHop( config->readEntry( "Right next hop", "" ) );
			data->setLeftNextHop( config->readEntry( "Left next hop", "" ) );
			data->setUseMssfix(config->readBoolEntry( "Use userdef packet size", false) );
			data->setUseFragment(config->readBoolEntry( "Use userdefinied packet size for fragmentation" , false) );
			data->setMssfix(config->readNumEntry( "Mssfix", 1300) );
			data->setFragment( config->readNumEntry( "Fragment", 1300) );
			data->setPeerTimeout( config->readNumEntry( "PeerTimeout",0) );
			data->setDisableCcp( config->readBoolEntry("Disable CCP",false) );
			data->setUseSmartcard( config->readBoolEntry("Use smartcard", false) );
			data->setUseXauthInteractive(config->readBoolEntry("Use Xauth interactive", false) );
			data->setUseHttpProxyAuth( config->readBoolEntry("Use HTTP Proxy Authentication", false ) );
			data->setHttpProxyAuthType( config->readEntry("Use HTTP Proxy Authtype", "basic") );
			data->setHttpProxyUser( config->readEntry("Use HTTP Proxy Auth user", "") );
			data->setHttpProxyPass( config->readEntry("Use HTTP Proxy Auth pass", "") );
			data->setUseOnlyCaCertAndUserAuth(config->readBoolEntry("Use only CA cert and user auth", false) );
			data->setUseMailAddressAsIdentifier(config->readBoolEntry("Use mail address as identifier", false) );
			data->setUseRightNextHop(config->readBoolEntry("Use right next hop", false) );
			data->setUseLeftNextHop(config->readBoolEntry("Use left next hop", false) );
			data->setPkcs11Providers(config->readEntry("Pkcs11 providers", "/usr/local/lib/libetpkcs11.so" ) );
			data->setPkcs11SlotType(config->readEntry("Pkcs11 slot type", "id") );
			data->setPkcs11Slot(config->readEntry("Pkcs11 slot", "0") );
			data->setPkcs11IdType(config->readEntry("Pkcs11 id type", "id") );
			data->setPkcs11Id(config->readEntry("Pkcs11 id","" ) );
			data->setPkcs11SignMode(config->readEntry("Pkcs11 sign mode", "auto") );
			data->setUsePkcs11Providers(config->readBoolEntry("Use Pkcs11 providers", false) );
			data->setAllowEmptyPrivateKeyPassword( config->readBoolEntry("Allow empty private key password", false ));
			data->setAllowIpAddressChangeOfPeer(config->readBoolEntry("Allow ip address change of peer", false));
			data->setAuthMethod(config->readEntry("Auth method", "chap"));
			data->setCommandAfterConnectDelayTime(config->readNumEntry("Command after connect delay time", 5));
			data->setUseSearchDomainInResolvConf(config->readBoolEntry("Use search domain in resolv conf",false));
			data->setSearchDomainInResolvConf(config->readEntry("Search domain in resolv conf",""));
			data->setAuthenticationDirection(config->readEntry("Authentication direction","none"));
			data->setIpsecEsp(config->readEntry("IPSec ESP","3des-md5-96"));
			data->setIpsecIke(config->readEntry("IPSec IKE","3des-sha-modp2048"));
			data->setVtunProfile(config->readEntry("Vtun profile",""));
			data->setDisableDataEncryption(config->readBoolEntry("Disable data encryption", false));
			data->setUseAuthenticationAlgorithm(config->readBoolEntry("Use authentication algorithm", false));
			data->setFixPathMtuDiscoveryProblem(config->readBoolEntry("Fix path mtu discovery problem" , false));
			appPointer->processEvents();
			AccountList->append( data );
		}

		if ( name == "Client Options" )
		{
			// old style configuration found
			config->setGroup( "Client Options" );
			QString Name = "Default";
			VpnAccountData::ConnectionType ConnType = VpnAccountData::cisco;
			QString Gateway = config->readEntry( "VPN Gateway", "" );
			QString ID = config->readEntry( "VPN ID", "" );
			QString Psk = config->readEntry( "Group password", "" );
			QString Username = config->readEntry( "Username", "" );
			QString UserPassword = config->readEntry( "Password", "" );
			bool saveUserPassword = config->readBoolEntry( "Save user password", false );
			bool savePsk = config->readBoolEntry( "Save group password", false );

			VpnAccountData *AccData = new VpnAccountData( ConnType, Name);
			AccData->setGateway ( Gateway );
			AccData->setID( ID );
			AccData->setPreSharedKey( Psk);
			AccData->setUserName( Username );
			AccData->setUserPassword( UserPassword );
			AccData->setSaveUserPassword( saveUserPassword );
			AccData->setSavePsk( savePsk );
			AccData->setLocalPort( 500 );
			AccData->setPerfectForwardSecrety ( "server" );
			AccData->setIkeGroup( "dh1" );
			AccountList->append( AccData );

			lastProfile = "Default";

			// now mark for deleting old configuration
			oldConfigurationFound = true;
			if ( KvpncDebugLevel > 2 )
				appendLogEntry ( i18n( "Old configuration found, converted." ),info );

			if ( KvpncDebugLevel > 2 )
				appendLogEntry( i18n( "Configuration for profile \"%1\" loaded." ).arg( Name ),info );

			appPointer->processEvents();
		}


	}
	if ( oldConfigurationFound )
	{
		// delete configuration file
		KStandardDirs * dirs = KGlobal::dirs();
		QString filePath = dirs->findResource ( "config", "kvpncrc" );
		QFile::remove
			( filePath );
		if ( KvpncDebugLevel > 2 )
			appendLogEntry ( i18n( "Old configuration deleted." ), debug );
	}
}

bool KVpncConfig::exportKvpncConfig(QString filename)
{
	bool ok=true;
	int exportCount=0;
	bool exportGlobal=false;
	QFile exportfile (filename);
	if (exportfile.exists())
	{
		int res = KMessageBox::questionYesNo ( 0, i18n ( "\"%1\" still exists. Do you really want to overwrite it?" ).arg ( filename ), i18n ( "Overwrite?" ), i18n("&Overwrite") , KStdGuiItem::cancel() );

		if (res == 4)
			ok=false;
	}
	if (ok==true)
	{
		if( exportfile.open(IO_WriteOnly))
		{
				QPtrList<VpnAccountData> *exportAccountList = new QPtrList<VpnAccountData>();
				exportAccountList->setAutoDelete( TRUE ); // the list owns the objects
				KvpncImportProfileSelectionBase selectdlg;
				VpnAccountData *it=NULL;

				selectdlg.textLabel->setText(i18n("Select profiles for export:"));
				selectdlg.ImportPushButton->setText(i18n("&Export selected profiles..."));
				selectdlg.ImportGlobalSettingsCheckBox->setText(i18n("export &global settings"));

				if ( !AccountList->isEmpty() )
				{
					selectdlg.ImportProfileListView->takeItem(selectdlg.ImportProfileListView->currentItem());
					selectdlg.ImportProfileListView->addColumn(i18n("Name"));
					selectdlg.ImportProfileListView->addColumn(i18n("Type"));
					selectdlg.ImportProfileListView->addColumn(i18n("Gateway"));
					QCheckListItem *item;
					for ( it = AccountList->first(); it; it = AccountList->next() )
					{
							QString name = it->getName();
							QString type;
							if ( it->getConnectionType() == VpnAccountData::cisco )
								type = "cisco" ;
							else if ( it->getConnectionType() == VpnAccountData::ciscoorig )
								type = "ciscoorig" ;
							else if ( it->getConnectionType() == VpnAccountData::racoon )
								type = "racoon" ;
							else if ( it->getConnectionType() == VpnAccountData::l2tpd_racoon )
								type = "l2tpd (racoon)" ;
							else if ( it->getConnectionType() == VpnAccountData::freeswan )
								type = "freeswan" ;
							else if ( it->getConnectionType() == VpnAccountData::l2tpd_freeswan )
								type = "l2tpd (openswan)" ;
							else if ( it->getConnectionType() == VpnAccountData::pptp )
								type = "pptp" ;
							else if ( it->getConnectionType() == VpnAccountData::openvpn )
								type = "openvpn" ;
							else
								type =  i18n("other");


// 						litem->setSelectable(true);
						item = new QCheckListItem(selectdlg.ImportProfileListView,it->getName(),QCheckListItem::CheckBox);
						item->setText(1,type);
						item->setText(2,it->getGateway());
						selectdlg.ImportProfileListView->insertItem(item);

// 						std::cout << "insert profile into listview: " << name << std::endl;
					}
				}
				bool ret = selectdlg.exec();
				if (ret == true)
				{
					QListViewItemIterator it2( selectdlg.ImportProfileListView );
					for ( ; it2.current(); ++it2 )
					{
						if (  ( (QCheckListItem*)it2.current() )->isOn() )
						{
							VpnAccountData *data=NULL;
							it = 0;
							for ( it = AccountList->first(); it; it = AccountList->next() )
								if ( it->getName() == ( (QCheckListItem*)it2.current() )->text() && ( (QCheckListItem*)it2.current() )->isOn()  )
									data = it;
							exportAccountList->append(data);
						}
					}
					exportGlobal = selectdlg.ImportGlobalSettingsCheckBox->isChecked();
					if (exportAccountList->count() == 0 && exportGlobal==false)
					{
						KMessageBox::sorry ( 0, i18n ( "No profiles for export, export canceled." ) );
						exportfile.close();
						exportfile.remove();
						return false;
					}
				}
				else
				{
					KMessageBox::sorry ( 0, i18n ( "Export canceled." ) );
					exportfile.close();
					exportfile.remove();
					return false;
				}



			QString date (__DATE__);
			QString day= date.section(' ',0,0);
			QString month= QString().setNum(QDate::fromString(date.section(' ',0,0),Qt::ISODate).month());
			QString year= date.section(' ',2,2);
			
			QString currentdate ( date+" "+ QTime().fromString(QString (__TIME__)).toString( "hh:mm" ) );
	
			QTextStream ExportStream ( &exportfile );
			ExportStream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << "\n";
			ExportStream << "<!-- generated by kvpnc at " << currentdate<< ". Do not edit it. -->" << "\n";
			ExportStream << "<kvpnc>" << "\n";
			ExportStream << "\t<version>" << "\n";
			ExportStream << "\t\t<app>" << "0.8.9" << "</app>" << "\n";
			ExportStream << "\t\t<exportversion>" << "1" << "</exportversion>" << "\n";
			ExportStream << "\t</version>" << "\n";
	
			if (exportGlobal == true)
			{
				ExportStream << "\t<global>" << "\n";
				ExportStream << "\t\t<option name=\"Minimize after connect\"" << " type=\"bool\"" << ">" << minimizeAfterConnect<< "</option>\n";
				ExportStream << "\t\t<option name=\"Hide on startup\"" << " type=\"bool\"" << ">" << hideMainWindow<< "</option>\n";
				ExportStream << "\t\t<option name=\"Use silent quit\"" << " type=\"bool\"" << ">" << useSilentQuit<< "</option>\n";
				ExportStream << "\t\t<option name=\"Dont quit on CloseEvent\"" << " type=\"bool\"" << ">" << dontQuitOnCloseEvent<< "</option>\n";
				ExportStream << "\t\t<option name=\"Enable pppd debug\"" << " type=\"bool\"" << ">" << enableDebugPppd<< "</option>\n";
				ExportStream << "\t\t<option name=\"Enable pptpd debug\"" << " type=\"bool\"" << ">" << enableDebugPptpd<< "</option>\n";
				ExportStream << "\t\t<option name=\"Enable l2tpd debug\"" << " type=\"bool\"" << ">" << enableDebugL2tpd<< "</option>\n";
				ExportStream << "\t\t<option name=\"Enable xl2tpd debug\"" << " type=\"bool\"" << ">" << enableDebugXl2tpd<< "</option>\n";
				ExportStream << "\t\t<option name=\"Enable FreeSWAN verbose\"" << " type=\"bool\"" << ">" << enableFreeswanVerbose<< "</option>\n";
				ExportStream << "\t\t<option name=\"Show debugconsole\"" << " type=\"bool\"" << ">" << showDebugConsole<< "</option>\n";
				ExportStream << "\t\t<option name=\"Pid file for vpnc \"" << " type=\"string\"" << ">" << Vpnc_pid_file<< "</option>\n";
				ExportStream << "\t\t<option name=\"Vpnc debuglevel\"" << " type=\"int\"" << ">" << VpncDebugLevel<< "</option>\n";
				ExportStream << "\t\t<option name=\"Racoon debuglevel\"" << " type=\"string\"" << ">" << RacoonDebugLevel<< "</option>\n";
				ExportStream << "\t\t<option name=\"Kvpnc debuglevel\"" << " type=\"int\"" << ">" << KvpncDebugLevel<< "</option>\n";
				ExportStream << "\t\t<option name=\"Pppd debuglevel\"" << " type=\"bool\"" << ">" << PppdDebugLevel<< "</option>\n";
				ExportStream << "\t\t<option name=\"Openvpn debuglevel\"" << " type=\"int\"" << ">" << OpenvpnDebugLevel<< "</option>\n";
				ExportStream << "\t\t<option name=\"Pptp debuglevel\"" << " type=\"string\"" << ">" << PptpLogLevel<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to vpnc-bin\"" << " type=\"string\"" << ">" << pathToVpnc<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to vpnclient\"" << " type=\"string\"" << ">" << pathToCiscoVpnc<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to racoon\"" << " type=\"string\"" << ">" << pathToRacoon<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to setkey\"" << " type=\"string\"" << ">" << pathToSetkey<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to iptables\"" << " type=\"string\"" << ">" << pathToIptables<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to openssl\"" << " type=\"string\"" << ">" << pathToOpenssl<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to freeswan\"" << " type=\"string\"" << ">" << pathToFreeswan<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to pppd\"" << " type=\"string\"" << ">" << pathToPppd<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to pptp\"" << " type=\"string\"" << ">" << pathToPptp<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to l2tpd\"" << " type=\"string\"" << ">" << pathToL2tpd<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to xl2tpd\"" << " type=\"string\"" << ">" << pathToXl2tpd<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to kill\"" << " type=\"string\"" << ">" << pathToKill<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to kill-all\"" << " type=\"string\"" << ">" << pathToKillall<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to ping\"" << " type=\"string\"" << ">" << pathToPing<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to openvpn\"" << " type=\"string\"" << ">" << pathToOpenvpn<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to iputility\"" << " type=\"string\"" << ">" << pathToIp<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to ifconfig\"" << " type=\"string\"" << ">" << pathToIfconfig<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to route\"" << " type=\"string\"" << ">" << pathToRoute<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to netstat\"" << " type=\"string\"" << ">" << pathToNetstat<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to pkcs11-tool\"" << " type=\"string\"" << ">" << pathToPkcs11Tool<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to vtund\"" << " type=\"string\"" << ">" << pathToVtund<< "</option>\n";
				ExportStream << "\t\t<option name=\"Path to cisco_cert_mgr\"" << " type=\"string\"" << ">" << pathToCiscoCertMgr<< "</option>\n";
				ExportStream << "\t\t<option name=\"Show Statusbar\"" << " type=\"bool\"" << ">" << showStatusBar<< "</option>\n";
				ExportStream << "\t\t<option name=\"Try connect timeout\"" << " type=\"int\"" << ">" << tryConnectTimeout<< "</option>\n";
				ExportStream << "\t\t<option name=\"Last Profile\"" << " type=\"string\"" << ">" << lastProfile<< "</option>\n";
				ExportStream << "\t\t<option name=\"Write log file\"" << " type=\"bool\"" << ">" << writeLogFile<< "</option>\n";
				ExportStream << "\t\t<option name=\"Hold generated scripts\"" << " type=\"bool\"" << ">" << holdGeneratedScripts<< "</option>\n";
				ExportStream << "\t\t<option name=\"Programs in path\"" << " type=\"bool\"" << ">" << programsInPath<< "</option>\n";
				ExportStream << "\t\t<option name=\"Info logwindow color\"" << " type=\"string\"" << ">" << InfoLogColor.name() << "</option>\n";
				ExportStream << "\t\t<option name=\"Remote logwindow color\"" << " type=\"string\"" << ">" << RemoteLogColor.name() << "</option>\n";
				ExportStream << "\t\t<option name=\"Error logwindow color\"" << " type=\"string\"" << ">" << ErrorLogColor.name() << "</option>\n";
				ExportStream << "\t\t<option name=\"Success  logwindow color\"" << " type=\"string\"" << ">" << SuccessLogColor.name() << "</option>\n";
				ExportStream << "\t\t<option name=\"Debug logwindow color\"" << " type=\"string\"" << ">" << DebugLogColor.name() << "</option>\n";
				ExportStream << "\t\t<option name=\"Debug background color\"" << " type=\"string\"" << ">" << DebugBackgroundcolor.name() << "</option>\n";
				ExportStream << "\t\t<option name=\"Use colorized log output\"" << " type=\"bool\"" << ">" << useColorizedLogOutput<< "</option>\n";
				ExportStream << "\t\t<option name=\"Show interface IP in tooltip\"" << " type=\"bool\"" << ">" << showInterfaceIPinTooltip<< "</option>\n";
				ExportStream << "\t\t<option name=\"Auto connect profile\"" << " type=\"string\"" << ">" << AutoConnectProfile<< "</option>\n";
				ExportStream << "\t\t<option name=\"Do auto connect at startup\"" << " type=\"bool\"" << ">" << doAutoConnectAtStartup<< "</option>\n";
				ExportStream << "\t\t<option name=\"Log viewer font size\"" << " type=\"int\"" << ">" << LogViewerFontSize<< "</option>\n";
				ExportStream << "\t\t<option name=\"Mainwindow width\"" << " type=\"int\"" << ">" << parent->width()<< "</option>\n";
				ExportStream << "\t\t<option name=\"Mainwindow height\"" << " type=\"int\"" << ">" << parent->height()<< "</option>\n";
				ExportStream << "\t\t<option name=\"Mainwindow position x\"" << " type=\"int\"" << ">" << parent->x()<< "</option>\n";
				ExportStream << "\t\t<option name=\"Mainwindow position y\"" << " type=\"int\"" << ">" << parent->y()<< "</option>\n";
				ExportStream << "\t\t<option name=\"Openvpn management port\"" << " type=\"bool\"" << ">" << OpenvpnManagementPort<< "</option>\n";
				ExportStream << "\t\t<option name=\"hideOnCloseInfo\"" << " type=\"bool\"" << ">" << hideOnCloseInfo<< "</option>\n";
			//   ExportStream << "\t\t<option name=\"ToolBar Settings\"" << " type=\"bool\"" << ">" << parent->toolBar( "mainToolBar" )<< "</option>\n";
				ExportStream << "\t\t<option name=\"Use KWallet\"" << " type=\"bool\"" << ">" << useKwallet<< "</option>\n";
				ExportStream << "\t\t<option name=\"FeedbackMailSent\"" << " type=\"bool\"" << ">" << feedbackMailSent<< "</option>\n";
				ExportStream << "\t\t<option name=\"Do kill l2tpd if still running\"" << " type=\"bool\"" << ">" << doKillL2tpdIfStillRunning<< "</option>\n";
				ExportStream << "\t\t<option name=\"Do kill xl2tpd if still running\"" << " type=\"bool\"" << ">" << doKillXl2tpdIfStillRunning<< "</option>\n";
				ExportStream << "\t\t<option name=\"Do kill racoon if still running\"" << " type=\"bool\"" << ">" << doKillRacoonIfStillRunning<< "</option>\n";
				ExportStream << "\t\t<option name=\"Show connection time in Tooltip\"" << " type=\"bool\"" << ">" << showConnectionTimeInTooltip<< "</option>\n";
				ExportStream << "\t\t<option name=\"Enable debug Openvpn\"" << " type=\"bool\"" << ">" << enableDebugOpenvpn<< "</option>\n";
		
				ExportStream << "\t</global>" << "\n";
			}


			ExportStream << "\t<profiles>" << "\n";
// 			VpnAccountData *it;
			if ( !exportAccountList->isEmpty() )
			{
				for ( it = exportAccountList->first(); it; it = exportAccountList->next() )
				{
	// 			std::cout << "export profile: " << it->getName().ascii() << std::endl;
					ExportStream << "\t\t<profile name=\"" << it->getName() << "\">" << "\n";
	
					// normal config
					if ( it->getConnectionType() == VpnAccountData::cisco )
						ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "cisco" << "</option>" << "\n";
					else if ( it->getConnectionType() == VpnAccountData::ciscoorig )
						ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "ciscoorig" << "</option>" << "\n";
					else if ( it->getConnectionType() == VpnAccountData::racoon )
						ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "racoon" << "</option>" << "\n";
					else if ( it->getConnectionType() == VpnAccountData::l2tpd_racoon )
						ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "l2tpd (racoon)" << "</option>" << "\n";
					else if ( it->getConnectionType() == VpnAccountData::freeswan )
						ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "freeswan" << "</option>" << "\n";
					else if ( it->getConnectionType() == VpnAccountData::l2tpd_freeswan )
						ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "l2tpd (openswan)" << "</option>" << "\n";
					else if ( it->getConnectionType() == VpnAccountData::pptp )
						ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "pptp" << "</option>" << "\n";
					else if ( it->getConnectionType() == VpnAccountData::openvpn )
						ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "openvpn" << "</option>" << "\n";
					else
						ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "other" << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"VPN Gateway\"" << " type=\"string\"" << ">" <<  it->getGateway() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"VPN ID\"" << " type=\"string\"" << ">" <<  it->getID() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Username\"" << " type=\"string\"" << ">" <<  it->getUserName() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Save user password\"" << " type=\"bool\"" << ">" <<  it->getSaveUserPassword() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Save PSK\"" << " type=\"bool\"" << ">" <<  it->getSavePsk() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Save private key password\"" << " type=\"bool\"" << ">" <<  it->getSavePrivateKeyPassword() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Private key\"" << " type=\"string\"" << ">" <<  it->getPrivateKey() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use advanced settings\"" << " type=\"bool\"" << ">" <<  it->getUseAdvancedSettings() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Application version\"" << " type=\"string\"" << ">" <<  it->getApplicationVersion() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Local port\"" << " type=\"int\"" << ">" <<  it->getLocalPort() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Remote port\"" << " type=\"int\"" << ">" <<  it->getRemotePort() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"NT domain name\"" << " type=\"string\"" << ">" <<  it->getNtDomainName() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Perfect forward secrety\"" << " type=\"string\"" << ">" <<  it->getPerfectForwardSecrety() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"IKE group\"" << " type=\"string\"" << ">" <<  it->getIkeGroup() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use application version\"" << " type=\"bool\"" << ">" <<  it->getUseApplicationVersion() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use global IPSec secret\"" << " type=\"bool\"" << ">" <<  it->getUseGlobalIpsecSecret() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use IKE group\"" << " type=\"bool\"" << ">" <<  it->getUseIkeGroup() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use local port\"" << " type=\"bool\"" << ">" <<  it->getUseLocalPort() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use remote port\"" << " type=\"bool\"" << ">" <<  it->getUseRemotePort() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use NT domain name\"" << " type=\"bool\"" << ">" <<  it->getUseNtDomainName() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use single DES\"" << " type=\"bool\"" << ">" <<  it->getUseSingleDes() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use perfect Forward Secrety\"" << " type=\"bool\"" << ">" <<  it->getUsePerfectForwardSecrety() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Remote net address\"" << " type=\"string\"" << ">" <<  it->getRemoteNetAddr() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Remote net mask\"" << " type=\"string\"" << ">" <<  it->getRemoteNetMask() << "</option>" << "\n";
	
					ExportStream << "\t\t\t<option name=\"x509 certificate\"" << " type=\"string\"" << ">" <<  it->getX509Certificate() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Ca certificate\"" << " type=\"string\"" << ">" <<  it->getCaCertificate() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Network device\"" << " type=\"string\"" << ">" <<  it->getNetworkDevice() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Cert path\"" << " type=\"string\"" << ">" <<  it->getCertPath() << "</option>" << "\n";
					if ( it->getAuthType() == VpnAccountData::cert )
						ExportStream << "\t\t\t<option name=\"Auth type\"" << " type=\"string\"" << ">" <<  "cert" << "</option>" << "\n";
					else
						ExportStream << "\t\t\t<option name=\"Auth type\"" << " type=\"string\"" << ">" <<  "psk" << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"do ping ip\"" << " type=\"bool\"" << ">" <<  it->getDoPingIP() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Ping host IP\"" << " type=\"string\"" << ">" <<  it->getPingHostIP() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use special remote ID\"" << " type=\"bool\"" << ">" <<  it->getUseSpecialRemoteID() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use special local ID\"" << " type=\"bool\"" << ">" <<  it->getUseSpecialLocalID() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Special server certificate\"" << " type=\"string\"" << ">" <<  it->getSpecialServerCertificate() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use special server certificate\"" << " type=\"bool\"" << ">" <<  it->getUseSpecialServerCertificate() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Special remote ID\"" << " type=\"string\"" << ">" <<  it->getSpecialRemoteID() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Special local ID\"" << " type=\"string\"" << ">" <<  it->getSpecialLocalID() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Local ID type\"" << " type=\"string\"" << ">" <<  it->getLocalIDType() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use UDP-protocol\"" << " type=\"bool\"" << ">" <<  it->getUseUdp() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use UDP-port\"" << " type=\"bool\"" << ">" <<  it->getUseUdpPort() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"local UDP port\"" << " type=\"int\"" << ">" <<  it->getUdpPort() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"use DNS_UPDATE\"" << " type=\"bool\"" << ">" <<  it->getUseDnsUpdate() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"use DNS-server\"" << " type=\"bool\"" << ">" <<  it->getUseDnsServer() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"DNS server\"" << " type=\"string\"" << ">" <<  it->getDnsServer() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"get dns server from peer\"" << " type=\"bool\"" << ">" <<  it->getUseGetDnsFromPeer() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"refuse 40 bit encryption\"" << " type=\"bool\"" << ">" <<  it->getRefuse40BitEncryption() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"refuse 128 bit encryption\"" << " type=\"bool\"" << ">" <<  it->getRefuse128BitEncryption() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"require stateless encryption\"" << " type=\"bool\"" << ">" <<  it->getAllowStatefulMode() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"require mppe\"" << " type=\"bool\"" << ">" <<  it->getRequireMppe() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"refuse EAP\"" << " type=\"bool\"" << ">" <<  it->getRefuseEap() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Disable MPPE compression\"" << " type=\"bool\"" << ">" <<  it->getDisableMPPEComp() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Local virtual IP\"" << " type=\"string\"" << ">" <<  it->getLocalVirtualIP() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Remote virtual IP\"" << " type=\"string\"" << ">" <<  it->getRemoteVirtualIP() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Pre shared key file\"" << " type=\"string\"" << ">" <<  it->getPreSharedKeyFile() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Execute command before connect\"" << " type=\"string\"" << ">" <<  it->getExecuteCmdBeforeConnect() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Execute command after connect\"" << " type=\"string\"" << ">" <<  it->getExecuteCmdAfterConnect() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Execute command before disconnect\"" << " type=\"string\"" << ">" <<  it->getExecuteCmdBeforeDisconnect() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Execute command after disconnect\"" << " type=\"string\"" << ">" <<  it->getExecuteCmdAfterDisconnect() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Command before connect\"" << " type=\"string\"" << ">" <<  it->getCommandBeforeConnect() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Command after connect\"" << " type=\"string\"" << ">" <<  it->getCommandAfterConnect() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Command before disconnect\"" << " type=\"string\"" << ">" <<  it->getCommandBeforeDisconnect() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Command after disconnect\"" << " type=\"string\"" << ">" <<  it->getCommandAfterDisconnect() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use no BSD compression\"" << " type=\"bool\"" << ">" <<  it->getUseNoBsdComp() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Do not use no IP by default\"" << " type=\"bool\"" << ">" <<  it->getUseNoIpDefault()<< "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use no deflate\"" << " type=\"bool\"" << ">" <<  it->getUseNoDeflate() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Set default route\"" << " type=\"bool\"" << ">" <<  it->getSetDefaultRoute() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Replace default route\"" << " type=\"bool\"" << ">" <<  it->getReplaceDefaultRoute() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use own MTU\"" << " type=\"bool\"" << ">" <<  it->getUseMtu() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use own MRU\"" << " type=\"bool\"" << ">" <<  it->getUseMru() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"MTU for pppd\"" << " type=\"int\"" << ">" <<  it->getMtu() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"MRU for pppd\"" << " type=\"int\"" << ">" <<  it->getMru() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use Virtual IP\"" << " type=\"bool\"" << ">" <<  it->getUseVirtualIP() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Virtual IP\"" << " type=\"string\"" << ">" <<  it->getVirtualIP() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"PSK is in file\"" << " type=\"bool\"" << ">" <<  it->getPskIsInFile() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use additional network routes\"" << " type=\"bool\"" << ">" <<  it->getUseAdditionalNetworkRoutes() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Hash algorithm\"" << " type=\"string\"" << ">" <<  it->getHashAlgo() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Encryption algorithm\"" << " type=\"string\"" << ">" <<  it->getEncryptionAlgorithm() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Authentication algorithm\"" << " type=\"string\"" << ">" <<  it->getAuthenticationAlgorithm() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Tunnel device type\"" << " type=\"string\"" << ">" <<  it->getTunnelDeviceType() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use userdefined port\"" << " type=\"bool\"" << ">" <<  it->getUseUserdefinedPort() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Userdefined port\"" << " type=\"int\"" << ">" <<  it->getUserdefinedPort() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Keep default route\"" << " type=\"bool\"" << ">" <<  it->getKeepDefaultRoute() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"NS cert type\"" << " type=\"string\"" << ">" <<  it->getNsCertType() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use NS cert type\"" << " type=\"bool\"" << ">" <<  it->getUseNsCertType() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use connection status check\"" << " type=\"bool\"" << ">" <<  it->getUseConnectionStatusCheck() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Connection check success count\"" << " type=\"int\"" << ">" <<  it->getConnectionStatusCheckSuccessCount() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Connection check status interval\"" << " type=\"int\"" << ">" <<  it->getConnectionStatusInterval() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Do reconnect after connection lost\"" << " type=\"bool\"" << ">" <<  it->getDoReconnectAfterConnectionLost()<< "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Disable LZO compression\"" << " type=\"bool\"" << ">" <<  it->getDisableLzoCompression()<< "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"AuthWithUsernameAndPassword\"" << " type=\"bool\"" << ">" <<  it->getAuthWithUsernameAndPassword() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"AllowEmptyGroupPassword\"" << " type=\"bool\"" << ">" <<  it->getAllowEmptyGroupPassword() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use userdefinied cipher\"" << " type=\"bool\"" << ">" <<  it->getUseUserdefiniedCipher() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Userdefinied cipher\"" << " type=\"string\"" << ">" <<  it->getUserdefiniedCipher() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use redirect gateway\"" << " type=\"bool\"" << ">" <<  it->getUseRedirectGateway() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use TLS auth\"" << " type=\"bool\"" << ">" <<  it->getUseTlsAuth() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"TLS auth file\"" << " type=\"string\"" << ">" <<  it->getTlsAuthFile() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use HTTP proxy\"" << " type=\"bool\"" << ">" <<  it->getUseHttpProxy() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"HTTP proxy host\"" << " type=\"string\"" << ">" <<  it->getHttpProxy() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"HTTP proxy port\"" << " type=\"int\"" << ">" <<  it->getHttpProxyPort() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"HTTP proxy timeout\"" << " type=\"int\"" << ">" <<  it->getHttpProxyTimeout() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Dont save username\"" << " type=\"bool\"" << ">" <<  it->getDontSaveUsername() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use mode config\"" << " type=\"bool\"" << ">" <<  it->getUseModeConfig() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Exchange mode\"" << " type=\"string\"" << ">" <<  it->getExchangeMode() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use delay at reconnect\"" << " type=\"bool\"" << ">" <<  it->getUseReconnectDelay() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Reconnect delay\"" << " type=\"int\"" << ">" <<  it->getReconnectDelay() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use TLS host\"" << " type=\"bool\"" << ">" <<  it->getUseTlsRemoteHost() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"TLS remote host\"" << " type=\"string\"" << ">" <<  it->getTlsRemoteHost() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Disable opportunistic encryption\"" << " type=\"bool\"" << ">" <<  it->getDisableOpportunisticEncryption() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Right next hop\"" << " type=\"string\"" << ">" <<  it->getRightNextHop() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Left next hop\"" << " type=\"string\"" << ">" <<  it->getLeftNextHop() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use userdefinied packet size for fragmentation\"" << " type=\"bool\"" << ">" <<  it->getUseFragment() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use userdef packet size\"" << " type=\"bool\"" << ">" <<  it->getUseMssfix() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Fragment\"" << " type=\"int\"" << ">" <<  it->getFragment() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"PeerTimeout\"" << " type=\"int\"" << ">" <<  it->getPeerTimeout() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Disable CCP\"" << " type=\"bool\"" << ">" <<  it->getDisableCcp() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use smartcard\"" << " type=\"bool\"" << ">" <<  it->getUseSmartcard() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use Xauth interactive\"" << " type=\"bool\"" << ">" <<  it->getUseXauthInteractive() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use HTTP Proxy Authentication\"" << " type=\"bool\"" << ">" <<  it->getUseHttpProxyAuth() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use HTTP Proxy Authtype\"" << " type=\"bool\"" << ">" <<  it->getHttpProxyAuthType() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use HTTP Proxy Auth user\"" << " type=\"bool\"" << ">" <<  it->getHttpProxyUser() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use HTTP Proxy Auth pass\"" << " type=\"bool\"" << ">" <<  it->getHttpProxyPass() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use only CA cert and user auth\"" << " type=\"bool\"" << ">" <<  it->getUseOnlyCaCertAndUserAuth() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use mail address as identifier\"" << " type=\"bool\"" << ">" <<  it->getUseMailAddressAsIdentifier() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use right next hop\"" << " type=\"bool\"" << ">" <<  it->getUseRightNextHop() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use left next hop\"" << " type=\"bool\"" << ">" <<  it->getUseLeftNextHop() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Pkcs11 providers\"" << " type=\"string\"" << ">" <<  it->getPkcs11Providers() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Pkcs11 slot type\"" << " type=\"string\"" << ">" <<  it->getPkcs11SlotType() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Pkcs11 slot\"" << " type=\"string\"" << ">" <<  it->getPkcs11Slot() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Pkcs11 id type\"" << " type=\"string\"" << ">" <<  it->getPkcs11IdType() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Pkcs11 id\"" << " type=\"string\"" << ">" <<  it->getPkcs11Id() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Pkcs11 sign mode\"" << " type=\"string\"" << ">" <<  it->getPkcs11SignMode() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use Pkcs11 providers\"" << " type=\"bool\"" << ">" <<  it->getUsePkcs11Providers() << "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Allow empty private key password\"" << " type=\"bool\"" << ">" <<  it->getAllowEmptyPrivateKeyPassword()<< "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Allow ip address change of peer\"" << " type=\"bool\"" << ">" <<  it->getAllowIpAddressChangeOfPeer()<< "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Auth method\"" << " type=\"string\"" << ">" <<  it->getAuthMethod()<< "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Command after connect delay time\"" << " type=\"string\"" << ">" <<  it->getCommandAfterConnectDelayTime()<< "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use search domain in resolv conf\"" << " type=\"bool\"" << ">" << it->getUseSearchDomainInResolvConf()<< "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Search domain in resolv conf\"" << " type=\"bool\"" << ">" << it->getSearchDomainInResolvConf()<< "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Authentication direction\"" << " type=\"string\"" << ">" << it->getAuthenticationDirection()<< "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"IPSec ESP\"" << " type=\"string\"" << ">" << it->getIpsecEsp()<< "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"IPSec IKE\"" << " type=\"string\"" << ">" << it->getIpsecIke()<< "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Vtun profile\"" << " type=\"string\"" << ">" << it->getVtunProfile()<< "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Disable data encryption\"" << " type=\"bool\"" << ">" << it->getDisableDataEncryption()<< "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Use authentication algorithm\"" << " type=\"bool\"" << ">" << it->getUseAuthenticationAlgorithm()<< "</option>" << "\n";
					ExportStream << "\t\t\t<option name=\"Fix path mtu discovery problem\"" << " type=\"bool\"" << ">" << it->getFixPathMtuDiscoveryProblem() <<  "</option>" << "\n";

					ExportStream << "\t\t</profile>" << "\n";
					exportCount++;
				}
	
			}
			ExportStream << "\t</profiles>" << "\n";
			ExportStream << "</kvpnc>" << "\n";
			exportfile.close();
		}
		else
		{
			KMessageBox::error ( 0, i18n ( "Creating of \"%1\" has been failed!" ).arg ( filename ) );
			return false;
		}
	}
	else
	{
		KMessageBox::information ( 0, i18n ( "Export canceled." ) );
		return false;
	}
	QString msg="";
	if (exportCount > 0 && exportGlobal==true)
		msg = i18n("Export was successful. %1 profiles and global settings are exported.").arg(QString::number(exportCount));
	if (exportCount > 0 && exportGlobal==false)
		msg = i18n("Export was successful. %1 profiles are exported.").arg(QString::number(exportCount));
	if (exportCount < 1 && exportGlobal==true)
		msg = i18n("Export was successful. Global settings are exported.");
	KMessageBox::information ( 0, msg,i18n("Export success") );
	return true;
}

bool KVpncConfig::importKvpncConfig(QString filename)
{
	QFile importfile (filename);
	if (!importfile.exists())
	{
		KMessageBox::error ( 0, i18n ( "Reading of \"%1\" has been failed!" ).arg ( filename ) );
		return false;
	}
	QString kvpncexportversion="";

	QString pathToVpnc;
	QString pathToCiscoVpnc;
	QString pathToRacoon;
	QString pathToSetkey;
	QString pathToIptables;
	QString pathToOpenssl;
	QString pathToFreeswan;
	QString pathToPppd;
	QString pathToPptp;
	QString pathToL2tpd;
	QString pathToXl2tpd;
	QString pathToKill;
	QString pathToKillall;
	QString pathToPing;
	QString pathToOpenvpn;
	QString pathToIp;
	QString pathToIfconfig;
	QString pathToRoute;
	QString pathToNetstat;
	QString pathToPkcs11Tool;
	QString pathToVtund;
	QString AutoConnectProfile;
	QString RacoonDebugLevel;
	QString Vpnc_pid_file;
	QString Pppd_pid_file;
	QString lastProfile;
	QString logfileName;

	QString TmpPassword; //< from enter password dialog
	QString TmpGroupPassword; //< from enter password dialog
	QString TmpUsername; //< from enter password dialog
	QString TmpPrivKeyPassStr;
	QString TmpGatewayIP;
	QString TmpXauthInterPasscode; //< from Xauth interactive passcode dialog
	QString TmpPrivateKeyPass;
	QString TmpHttpProxyPassword;

	bool minimizeAfterConnect=true;
	bool showDebugConsole=true;
	bool writeLogFile=true;
	bool useDefaultPaths=true;
	bool useSilentQuit=false;
	bool holdGeneratedScripts=true;
	bool programsInPath=true;
	bool enableDebugPppd=false;
	bool enableDebugPptpd=false;
	bool enableDebugL2tpd=false;
	bool enableDebugXl2tpd=false;
	bool enableFreeswanVerbose=false;
	bool enableDebugOpenvpn=false;
	bool useColorizedLogOutput=true;
	bool showInterfaceIPinTooltip=true;
	bool dontQuitOnCloseEvent=true;
	bool doAutoConnectAtStartup=false;
	bool useKwallet=true;
	bool showStatusBar=true;
	bool showToolBar=true;
	bool hideMainWindow=false;
	bool PppdDebugLevel=false;
	bool firstUseOfKwallet=false;
	bool shutdownIsCalled=false;
	bool skipKwalletStoring=false;
	bool hideOnCloseInfo=false;
	bool feedbackMailSent=false;
	bool doKillL2tpdIfStillRunning=false;
	bool doKillXl2tpdIfStillRunning=false;
	bool doKillRacoonIfStillRunning=false;
	bool showConnectionTimeInTooltip=false;

	int VpncDebugLevel=0;
	int KvpncDebugLevel=1;
	int OpenvpnDebugLevel=0;
	int PptpLogLevel=0;
	int LogViewerFontSize=10;
	int mainwindow_pos_x=10;
	int mainwindow_pos_y=10;
	int mainwindow_height=600;
	int mainwindow_width=800;
	int connectSleepDelay=10;
	int connectSleepRetry=3;
	int tryConnectTimeout=30;
	int connectionStartTime=0;
	int runningCheckCounter=0;
	int runningCheckTimeout=0;
	int OpenvpnManagementPort=2222;
	QPtrList<VpnAccountData> *ImportedAccountList;

	QColor InfoLogColor;
	QColor RemoteLogColor;
	QColor ErrorLogColor;
	QColor SuccessLogColor;
	QColor DebugLogColor;
	QColor DebugBackgroundcolor;

	QPoint pos;
	QPoint WindowPos;
	QSize WindowSize;

	bool importGlobal=false;
	int importCount=0;
	
	QDomDocument doc( "kvpncsettingsdoc" );
	if( importfile.open(IO_ReadOnly))
	{
		QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) );
	
		if ( !doc.setContent( &importfile ) ) {
			importfile.close();
			return false;
		}
		importfile.close();
	
		// print out the element names of all elements that are direct children
		// of the outermost element.
		QDomElement docElem = doc.documentElement();
	
		QDomNode n = docElem.firstChild();
		if (KvpncDebugLevel > 5)
			std::cout << "dom doc:" << std::endl;
		while( !n.isNull() ) 
		{
			if (n.toElement().tagName()  == "version")
			{
				if (KvpncDebugLevel > 5)
					std::cout << "version tag found." << std::endl;
				QDomNodeList vsubnodes = n.toElement().childNodes();
				for (int i=0;i<=(int)vsubnodes.count();i++)
				{
					QDomNode n1 = vsubnodes.item(i);
					if (n1.toElement().tagName() == "app")
					{
						if (KvpncDebugLevel > 5)
							std::cout << " doc was created from kvpnc ver " << n1.toElement().text() << std::endl;
					}
					if (n1.toElement().tagName() == "exportversion")
					{
						kvpncexportversion = n1.toElement().text();
						if (KvpncDebugLevel > 5)
							std::cout << " doc was created from kvpnc with exportver " << n1.toElement().text() << std::endl;
					}
				}
			}

			if (n.toElement().tagName()  == "global")
			{
				if (KvpncDebugLevel > 5)
					std::cout << "gobal tag found." << std::endl;
				QDomNodeList vsubnodes = n.toElement().childNodes();
				for (int i=0;i<=(int)vsubnodes.count();i++)
				{
					QDomNode n1 = vsubnodes.item(i);
					if (n1.toElement().tagName() != "")
					{
						if (KvpncDebugLevel > 5)
							std::cout << "	=> option: " << ", value: " << n1.toElement().text() <<  std::endl;
					}
					if ( n1.toElement().tagName() == "Minimize after connect" ) { minimizeAfterConnect = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Hide on startup" ) { hideMainWindow = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Use silent quit" ) { useSilentQuit = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Dont quit on CloseEvent" ) { dontQuitOnCloseEvent = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Enable pppd debug" ) { enableDebugPppd = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Enable pptpd debug" ) { enableDebugPptpd = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Enable l2tpd debug" ) { enableDebugL2tpd = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Enable xl2tpd debug" ) { enableDebugXl2tpd = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Enable FreeSWAN verbose" ) { enableFreeswanVerbose = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Show debugconsole" ) { showDebugConsole = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Pid file for vpnc " ) { Vpnc_pid_file = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Vpnc debuglevel" ) { VpncDebugLevel = n1.toElement().text().toInt(); }
					if ( n1.toElement().tagName() == "Racoon debuglevel" ) { RacoonDebugLevel = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Kvpnc debuglevel" ) { KvpncDebugLevel = n1.toElement().text().toInt(); }
					if ( n1.toElement().tagName() == "Pppd debuglevel" ) { PppdDebugLevel = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Openvpn debuglevel" ) { OpenvpnDebugLevel = n1.toElement().text().toInt(); }
					if ( n1.toElement().tagName() == "Pptp debuglevel" ) { PptpLogLevel = n1.toElement().text().toInt(); }
					if ( n1.toElement().tagName() == "Path to vpnc-bin" ) { pathToVpnc = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to vpnclient" ) { pathToCiscoVpnc = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to racoon" ) { pathToRacoon = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to setkey" ) { pathToSetkey = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to iptables" ) { pathToIptables = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to openssl" ) { pathToOpenssl = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to freeswan" ) { pathToFreeswan = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to pppd" ) { pathToPppd = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to pptp" ) { pathToPptp = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to l2tpd" ) { pathToL2tpd = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to xl2tpd" ) { pathToXl2tpd = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to kill" ) { pathToKill = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to kill-all" ) { pathToKillall = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to ping" ) { pathToPing = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to openvpn" ) { pathToOpenvpn = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to iputility" ) { pathToIp = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to ifconfig" ) { pathToIfconfig = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to route" ) { pathToRoute = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to netstat" ) { pathToNetstat = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to pkcs11-tool" ) { pathToPkcs11Tool = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to vtund" ) { pathToVtund = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Path to cisco_cert_mgr" ) { pathToCiscoCertMgr = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Show Statusbar" ) { showStatusBar = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Try connect timeout" ) { tryConnectTimeout = n1.toElement().text().toInt(); }
					if ( n1.toElement().tagName() == "Last Profile" ) { lastProfile = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Write log file" ) { writeLogFile = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Hold generated scripts" ) { holdGeneratedScripts = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Programs in path" ) { programsInPath = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Info logwindow color" ) { InfoLogColor.name()  = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Remote logwindow color" ) { RemoteLogColor.name()  = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Error logwindow color" ) { ErrorLogColor.name()  = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Success  logwindow color" ) { SuccessLogColor.name()  = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Debug logwindow color" ) { DebugLogColor.name()  = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Debug background color" ) { DebugBackgroundcolor.name()  = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Use colorized log output" ) { useColorizedLogOutput = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Show interface IP in tooltip" ) { showInterfaceIPinTooltip = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Auto connect profile" ) { AutoConnectProfile = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Do auto connect at startup" ) { doAutoConnectAtStartup = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Log viewer font size" ) { LogViewerFontSize = n1.toElement().text().toInt(); }
					if ( n1.toElement().tagName() == "Mainwindow width" ) { mainwindow_width = n1.toElement().text().toInt(); }
					if ( n1.toElement().tagName() == "Mainwindow height" ) { mainwindow_height = n1.toElement().text().toInt(); }
					if ( n1.toElement().tagName() == "Mainwindow position x" ) { mainwindow_pos_x = n1.toElement().text().toInt(); }
					if ( n1.toElement().tagName() == "Mainwindow position y" ) { mainwindow_pos_y = n1.toElement().text().toInt(); }
					if ( n1.toElement().tagName() == "Openvpn management port" ) { OpenvpnManagementPort = n1.toElement().text().toInt(); }
					if ( n1.toElement().tagName() == "hideOnCloseInfo" ) { hideOnCloseInfo = n1.toElement().text(); }
					//   if (n1.toElement().tagName() == "ToolBar Settings") { parent->toolBar( "mainToolBar" ) = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Use KWallet" ) { useKwallet = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "FeedbackMailSent" ) { feedbackMailSent = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Do kill l2tpd if still running" ) { doKillL2tpdIfStillRunning = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Do kill xl2tpd if still running" ) { doKillXl2tpdIfStillRunning = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Do kill racoon if still running" ) { doKillRacoonIfStillRunning = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Show connection time in Tooltip" ) { showConnectionTimeInTooltip = n1.toElement().text(); }
					if ( n1.toElement().tagName() == "Enable debug Openvpn" ) { enableDebugOpenvpn = n1.toElement().text(); }
				}
			}

			if (n.toElement().tagName()  == "profiles")
			{
				if (KvpncDebugLevel > 5)
					std::cout << "profiles tag found." << std::endl;

				ImportedAccountList = new QPtrList<VpnAccountData>();
				ImportedAccountList->setAutoDelete( TRUE ); // the list owns the objects

				QDomNodeList profiles_subnodes = n.toElement().childNodes();
				for (int i=0;i<=(int)profiles_subnodes.count();i++)
				{
					QDomNode n1 = profiles_subnodes.item(i);
					if (n1.toElement().attribute("name") != "")
					{
						if (KvpncDebugLevel > 5)
							std::cout << "profile: " << n1.toElement().attribute("name") << std::endl;
						QString name =  "kvpnc_import_" +n1.toElement().attribute("name");
						VpnAccountData *data = new VpnAccountData( VpnAccountData::cisco, name); // cisco is a dummy here, it will be set later
						data->setDescription(i18n("import from ")+filename);

						QDomNodeList profile_subnodes = n1.toElement().childNodes();
						for (int j=0;j<=(int)profile_subnodes.count();j++)
						{
							QDomNode n2 = profile_subnodes.item(j);
							if (n2.toElement().attribute("name") != "")
							{
								QString elementname= n2.toElement().attribute("name");
								QString elementvalue = n2.toElement().text();
								if (KvpncDebugLevel > 5)
									std::cout << "	=> option: " << elementname << ", value: " << elementvalue <<  std::endl;
								// normal config
								if (elementname == "Connection type")
								{  
									QString type = elementvalue;
									VpnAccountData::ConnectionType ConnType = VpnAccountData::ConnectionType( VpnAccountData::cisco );
									if ( type == "cisco" )
										ConnType = VpnAccountData::cisco;
									else if ( type == "ciscoorig" )
										ConnType = VpnAccountData::ciscoorig;
									else if ( type == "racoon" )
										ConnType = VpnAccountData::racoon;
									else if ( type == "l2tpd (racoon)" )
										ConnType = VpnAccountData::l2tpd_racoon;
									else if ( type == "freeswan" )
										ConnType = VpnAccountData::freeswan;
									else if ( type == "l2tpd (openswan)" )
										ConnType = VpnAccountData::l2tpd_freeswan;
									else if ( type == "pptp" )
										ConnType = VpnAccountData::pptp;
									else if ( type == "openvpn" )
										ConnType = VpnAccountData::openvpn;
									else
										ConnType = VpnAccountData::other;
									data->setConnectionType(ConnType);
// 									std::cout << " ==> type: " << type << std::endl;
								}
			
			
								if (elementname == "VPN Gateway") {  data->setGateway(elementvalue); }
								if (elementname == "VPN ID") {  data->setID(elementvalue); }
								if (elementname == "Username") {  data->setUserName(elementvalue); }
				
								if (elementname == "Save user password") {  data->setSaveUserPassword(elementvalue); }
								if (elementname == "Save PSK") {  data->setSavePsk(elementvalue); }
								if (elementname == "Save private key password") {  data->setSavePrivateKeyPassword(elementvalue); }
								if (elementname == "Private key") {  data->setPrivateKey(elementvalue); }
								if (elementname == "Use advanced settings") {  data->setUseAdvancedSettings(elementvalue); }
								if (elementname == "Application version") {  data->setApplicationVersion(elementvalue); }
								if (elementname == "Local port") {  data->setLocalPort(elementvalue.toInt()); }
								if (elementname == "Remote port") {  data->setRemotePort(elementvalue.toInt()); }
								if (elementname == "NT domain name") {  data->setNtDomainName(elementvalue); }
								if (elementname == "Perfect forward secrety") {  data->setPerfectForwardSecrety(elementvalue); }
								if (elementname == "IKE group") {  data->setIkeGroup(elementvalue); }
								
								if (elementname == "Use application version") {  data->setUseApplicationVersion(elementvalue); }
								if (elementname == "Use global IPSec secret") {  data->setUseGlobalIpsecSecret(elementvalue); }
								if (elementname == "Use IKE group") {  data->setUseIkeGroup(elementvalue); }
								if (elementname == "Use local port") {  data->setUseLocalPort(elementvalue); }
								if (elementname == "Use remote port") {  data->setUseRemotePort(elementvalue); }
								if (elementname == "Use NT domain name") {  data->setUseNtDomainName(elementvalue); }
								if (elementname == "Use single DES") {  data->setUseSingleDes(elementvalue); }
								if (elementname == "Use perfect Forward Secrety") {  data->setUsePerfectForwardSecrety(elementvalue); }
								if (elementname == "Remote net address") {  data->setRemoteNetAddr(elementvalue); }
								if (elementname == "Remote net mask") {  data->setRemoteNetMask(elementvalue); }
				
								if (elementname == "x509 certificate") {  data->setX509Certificate(elementvalue); }
								if (elementname == "Ca certificate") {  data->setCaCertificate(elementvalue); }
								if (elementname == "Network device") {  data->setNetworkDevice(elementvalue); }
								if (elementname == "Cert path") {  data->setCertPath(elementvalue); }
								
								if (elementname == "Auth type")
								{
									QString Authtype = elementvalue;
									if (Authtype == "cert")
										data->setAuthType(VpnAccountData::cert)	;
									else
										data->setAuthType( VpnAccountData::psk);
								}
								if (elementname == "do ping ip") {  data->setDoPingIP(elementvalue); }
								if (elementname == "Ping host IP") {  data->setPingHostIP(elementvalue); }
				


								if (elementname == "Special server certificate") {  data->setSpecialServerCertificate(elementvalue); }
								if (elementname == "Use special server certificate") {  data->setUseSpecialServerCertificate(elementvalue); }
								if (elementname == "Special remote ID") {  data->setSpecialRemoteID(elementvalue); }
								if (elementname == "Special local ID") {  data->setSpecialLocalID(elementvalue); }
								if (elementname == "Local ID type") {  data->setLocalIDType(elementvalue); }
								if (elementname == "Use UDP-protocol") {  data->setUseUdp(elementvalue); }
								if (elementname == "Use UDP-port") {  data->setUseUdpPort(elementvalue); }
								if (elementname == "local UDP port") {  data->setUdpPort(elementvalue.toInt()); }
								if (elementname == "use DNS_UPDATE") {  data->setUseDnsUpdate(elementvalue); }
								if (elementname == "use DNS-server") {  data->setUseDnsServer(elementvalue); }
								if (elementname == "DNS server") {  data->setDnsServer(elementvalue); }
								if (elementname == "get dns server from peer") {  data->setUseGetDnsFromPeer(elementvalue); }
								if (elementname == "refuse 40 bit encryption") {  data->setRefuse40BitEncryption(elementvalue); }
								if (elementname == "refuse 128 bit encryption") {  data->setRefuse128BitEncryption(elementvalue); }
								if (elementname == "require stateless encryption") {  data->setAllowStatefulMode(elementvalue); }
								if (elementname == "require mppe") {  data->setRequireMppe(elementvalue); }
								if (elementname == "refuse EAP") {  data->setRefuseEap(elementvalue); }
								if (elementname == "Disable MPPE compression") {  data->setDisableMPPEComp(elementvalue); }
								if (elementname == "Local virtual IP") {  data->setLocalVirtualIP(elementvalue); }
								if (elementname == "Remote virtual IP") {  data->setRemoteVirtualIP(elementvalue); }
								if (elementname == "Pre shared key file") {  data->setPreSharedKeyFile(elementvalue); }
								if (elementname == "Execute command before connect") {  data->setExecuteCmdBeforeConnect(elementvalue); }
								if (elementname == "Execute command after connect") {  data->setExecuteCmdAfterConnect(elementvalue); }
								if (elementname == "Execute command before disconnect") {  data->setExecuteCmdBeforeDisconnect(elementvalue); }
								if (elementname == "Execute command after disconnect") {  data->setExecuteCmdAfterDisconnect(elementvalue); }
								if (elementname == "Command before connect") {  data->setCommandBeforeConnect(elementvalue); }
								if (elementname == "Command after connect") {  data->setCommandAfterConnect(elementvalue); }
								if (elementname == "Command before disconnect") {  data->setCommandBeforeDisconnect(elementvalue); }
								if (elementname == "Command after disconnect") {  data->setCommandAfterDisconnect(elementvalue); }
								if (elementname == "Use no BSD compression") {  data->setUseNoBsdComp(elementvalue); }
								if (elementname == "Do not use no IP by default") {  data->setUseNoIpDefault(elementvalue); }
								if (elementname == "Use no deflate") {  data->setUseNoDeflate(elementvalue); }
								if (elementname == "Set default route") {  data->setSetDefaultRoute(elementvalue); }
								if (elementname == "Replace default route") {  data->setReplaceDefaultRoute(elementvalue); }
								if (elementname == "Use own MTU") {  data->setUseMtu(elementvalue); }
								if (elementname == "Use own MRU") {  data->setUseMru(elementvalue); }
								if (elementname == "MTU for pppd") {  data->setMtu(elementvalue.toInt()); }
								if (elementname == "MRU for pppd") {  data->setMru(elementvalue.toInt()); }
								if (elementname == "Use Virtual IP") {  data->setUseVirtualIP(elementvalue); }
								if (elementname == "Virtual IP") {  data->setVirtualIP(elementvalue); }
								if (elementname == "PSK is in file") {  data->setPskIsInFile(elementvalue); }
								if (elementname == "Use additional network routes") {  data->setUseAdditionalNetworkRoutes(elementvalue); }
								if (elementname == "Hash algorithm") {  data->setHashAlgo(elementvalue); }
								if (elementname == "Encryption algorithm") {  data->setEncryptionAlgorithm(elementvalue); }
								if (elementname == "Authentication algorithm") {  data->setAuthenticationAlgorithm(elementvalue); }
								if (elementname == "Tunnel device type") {  data->setTunnelDeviceType(elementvalue); }
								if (elementname == "Use userdefined port") {  data->setUseUserdefinedPort(elementvalue); }
								if (elementname == "Userdefined port") {  data->setUserdefinedPort(elementvalue.toInt()); }
								if (elementname == "Keep default route") {  data->setKeepDefaultRoute(elementvalue); }
								if (elementname == "NS cert type") {  data->setNsCertType(elementvalue); }
								if (elementname == "Use NS cert type") {  data->setUseNsCertType(elementvalue); }
								if (elementname == "Use connection status check") {  data->setUseConnectionStatusCheck(elementvalue); }
								if (elementname == "Connection check success count") {  data->setConnectionStatusCheckSuccessCount(elementvalue.toInt()); }
								if (elementname == "Connection check status interval") {  data->setConnectionStatusInterval(elementvalue.toInt()); }
								if (elementname == "Do reconnect after connection lost") {  data->setDoReconnectAfterConnectionLost(elementvalue); }
								if (elementname == "Disable LZO compression") {  data->setDisableLzoCompression(elementvalue); }
								if (elementname == "AuthWithUsernameAndPassword") {  data->setAuthWithUsernameAndPassword(elementvalue); }
								if (elementname == "AllowEmptyGroupPassword") {  data->setAllowEmptyGroupPassword(elementvalue); }
								if (elementname == "Use userdefinied cipher") {  data->setUseUserdefiniedCipher(elementvalue); }
								if (elementname == "Userdefinied cipher") {  data->setUserdefiniedCipher(elementvalue); }
								if (elementname == "Use redirect gateway") {  data->setUseRedirectGateway(elementvalue); }
				// 				appPointer->processEvents(<< "</option>") { "\n";
								if (elementname == "Use TLS auth") {  data->setUseTlsAuth(elementvalue); }
								if (elementname == "TLS auth file") {  data->setTlsAuthFile(elementvalue); }
								if (elementname == "Use HTTP proxy") {  data->setUseHttpProxy(elementvalue); }
								if (elementname == "HTTP proxy host") {  data->setHttpProxy(elementvalue); }
								if (elementname == "HTTP proxy port") {  data->setHttpProxyPort(elementvalue.toInt()); }
								if (elementname == "HTTP proxy timeout") {  data->setHttpProxyTimeout(elementvalue.toInt()); }
								if (elementname == "Dont save username") {  data->setDontSaveUsername(elementvalue); }
								if (elementname == "Use mode config") {  data->setUseModeConfig(elementvalue); }
								if (elementname == "Exchange mode") {  data->setExchangeMode(elementvalue); }
								if (elementname == "Use delay at reconnect") {  data->setUseReconnectDelay(elementvalue); }
								if (elementname == "Reconnect delay") {  data->setReconnectDelay(elementvalue.toInt()); }
								if (elementname == "Use TLS host") {  data->setUseTlsRemoteHost(elementvalue); }
								if (elementname == "TLS remote host") {  data->setTlsRemoteHost(elementvalue); }
								if (elementname == "Disable opportunistic encryption") {  data->setDisableOpportunisticEncryption(elementvalue); }
								if (elementname == "Right next hop") {  data->setRightNextHop(elementvalue); }
								if (elementname == "Left next hop") {  data->setLeftNextHop(elementvalue); }
								if (elementname == "Use userdefinied packet size for fragmentation") {  data->setUseFragment(elementvalue); }
								if (elementname == "Use userdef packet size") {  data->setUseMssfix(elementvalue); }
								if (elementname == "Fragment") {  data->setFragment(elementvalue.toInt()); }
								if (elementname == "PeerTimeout") {  data->setPeerTimeout(elementvalue.toInt()); }
								if (elementname == "Disable CCP") {  data->setDisableCcp(elementvalue); }
								if (elementname == "Use smartcard") {  data->setUseSmartcard(elementvalue); }
								if (elementname == "Use Xauth interactive") {  data->setUseXauthInteractive(elementvalue); }
								if (elementname == "Use HTTP Proxy Authentication") {  data->setUseHttpProxyAuth(elementvalue); }
								if (elementname == "Use HTTP Proxy Authtype") {  data->setHttpProxyAuthType(elementvalue); }
								if (elementname == "Use HTTP Proxy Auth user") {  data->setHttpProxyUser(elementvalue); }
								if (elementname == "Use HTTP Proxy Auth pass") {  data->setHttpProxyPass(elementvalue); }
								if (elementname == "Use only CA cert and user auth") {  data->setUseOnlyCaCertAndUserAuth(elementvalue); }
								if (elementname == "Use mail address as identifier") {  data->setUseMailAddressAsIdentifier(elementvalue); }
								if (elementname == "Use right next hop") {  data->setUseRightNextHop(elementvalue); }
								if (elementname == "Use left next hop") {  data->setUseLeftNextHop(elementvalue); }
								if (elementname == "Pkcs11 providers") {  data->setPkcs11Providers(elementvalue); }
								if (elementname == "Pkcs11 slot type") {  data->setPkcs11SlotType(elementvalue); }
								if (elementname == "Pkcs11 slot") {  data->setPkcs11Slot(elementvalue); }
								if (elementname == "Pkcs11 id type") {  data->setPkcs11IdType(elementvalue); }
								if (elementname == "Pkcs11 id") {  data->setPkcs11Id(elementvalue); }
								if (elementname == "Pkcs11 sign mode") {  data->setPkcs11SignMode(elementvalue); }
								if (elementname == "Use Pkcs11 providers") {  data->setUsePkcs11Providers(elementvalue); }
								if (elementname == "Allow empty private key password") {  data->setAllowEmptyPrivateKeyPassword(elementvalue); }
								if (elementname == "Allow ip address change of peer") {  data->setAllowIpAddressChangeOfPeer(elementvalue); }
								if (elementname == "Auth method") {  data->setAuthMethod(elementvalue); }
								if (elementname == "Command after connect delay time") {  data->setCommandAfterConnectDelayTime(elementvalue.toInt()); }
								if (elementname == "Use search domain in resolv conf") { data->setUseSearchDomainInResolvConf(elementvalue); }
								if (elementname == "Search domain in resolv conf") { data->setSearchDomainInResolvConf(elementvalue); }
								if (elementname == "Authentication direction") { data->setAuthenticationDirection(elementvalue); }
								if (elementname == "IPSec ESP") { data->setIpsecEsp(elementvalue); }
								if (elementname == "IPSec IKE") { data->setIpsecIke(elementvalue); }
								if (elementname == "Vtun profile") { data->setVtunProfile(elementvalue); }
								if (elementname == "Disable data encryption") { data->setDisableDataEncryption(elementvalue); }
								if (elementname == "Use authentication algorithm") { data->setUseAuthenticationAlgorithm(elementvalue); }
								if (elementname == "Fix path mtu discovery problem") { data->setFixPathMtuDiscoveryProblem(elementvalue); }
								
							}
						}
						if (KvpncDebugLevel > 5)
							std::cout << "profile end " << std::endl;
						ImportedAccountList->append(data);
					}
					appPointer->processEvents();
				}
				QApplication::restoreOverrideCursor();
				KvpncImportProfileSelectionBase selectdlg;
				VpnAccountData *it=NULL;
				
				if ( !ImportedAccountList->isEmpty() )
				{
					selectdlg.ImportProfileListView->takeItem(selectdlg.ImportProfileListView->currentItem());
					selectdlg.ImportProfileListView->addColumn(i18n("Name"));
					selectdlg.ImportProfileListView->addColumn(i18n("Type"));
					selectdlg.ImportProfileListView->addColumn(i18n("Gateway"));
					QCheckListItem *item;
					for ( it = ImportedAccountList->first(); it; it = ImportedAccountList->next() )
					{
							QString name = it->getName();
							QString type;
							if ( it->getConnectionType() == VpnAccountData::cisco )
								type = "cisco" ;
							else if ( it->getConnectionType() == VpnAccountData::ciscoorig )
								type = "ciscoorig" ;
							else if ( it->getConnectionType() == VpnAccountData::racoon )
								type = "racoon" ;
							else if ( it->getConnectionType() == VpnAccountData::l2tpd_racoon )
								type = "l2tpd (racoon)" ;
							else if ( it->getConnectionType() == VpnAccountData::freeswan )
								type = "freeswan" ;
							else if ( it->getConnectionType() == VpnAccountData::l2tpd_freeswan )
								type = "l2tpd (openswan)" ;
							else if ( it->getConnectionType() == VpnAccountData::pptp )
								type = "pptp" ;
							else if ( it->getConnectionType() == VpnAccountData::openvpn )
								type = "openvpn" ;
							else
								type =  i18n("other");


// 						litem->setSelectable(true);
						item = new QCheckListItem(selectdlg.ImportProfileListView,it->getName(),QCheckListItem::CheckBox);
						item->setText(1,type);
						item->setText(2,it->getGateway());
						selectdlg.ImportProfileListView->insertItem(item);

// 						std::cout << "insert profile into listview: " << name << std::endl;
					}
				}
				bool ret = selectdlg.exec();
				
				if (ret == true)
				{
					importGlobal=selectdlg.ImportGlobalSettingsCheckBox->isChecked();
					QListViewItemIterator it2( selectdlg.ImportProfileListView );
					for ( ; it2.current(); ++it2 )
					{
						if (  ( (QCheckListItem*)it2.current() )->isOn() )
						{
							VpnAccountData *data=NULL;
							it = 0;
							for ( it = ImportedAccountList->first(); it; it = ImportedAccountList->next() )
								if ( it->getName() == ( (QCheckListItem*)it2.current() )->text() && ( (QCheckListItem*)it2.current() )->isOn()  )
								{
									data = it;
									importCount++;
								}
							AccountList->append(data);
						}
					}
					
				}
				else
				{
					KMessageBox::sorry ( 0, i18n ( "Import canceled." ) );
					return false;
				}
			}

			QDomElement e = n.toElement(); // try to convert the node to an element.
			if( !e.isNull() ) {
				std::cout << e.tagName() << std::endl; // the node really is an element.
			}
			n = n.nextSibling();
		}
		if (KvpncDebugLevel > 5)
			std::cout << "dom doc end" << std::endl;

		if (importGlobal == true)
		{
			this-> pathToVpnc= pathToVpnc;
			this-> pathToCiscoVpnc= pathToCiscoVpnc;
			this-> pathToRacoon= pathToRacoon;
			this-> pathToSetkey= pathToSetkey;
			this-> pathToIptables= pathToIptables;
			this-> pathToIptables= pathToIptables;
			this-> pathToFreeswan= pathToFreeswan;
			this-> pathToPppd= pathToPppd;
			this-> pathToPptp= pathToPptp;
			this-> pathToL2tpd= pathToL2tpd;
			this-> pathToXl2tpd= pathToXl2tpd;
			this-> pathToKill= pathToKill;
			this-> pathToKillall= pathToKillall;
			this-> pathToPing= pathToPing;
			this-> pathToOpenvpn= pathToOpenvpn;
			this-> pathToIp= pathToIp;
			this-> pathToIfconfig= pathToIfconfig;
			this-> pathToRoute= pathToRoute;
			this-> pathToNetstat= pathToNetstat;
			this-> pathToPkcs11Tool= pathToPkcs11Tool;
			this-> AutoConnectProfile= AutoConnectProfile;
			this-> RacoonDebugLevel= RacoonDebugLevel;
			this-> Vpnc_pid_file= Vpnc_pid_file;
			this-> Pppd_pid_file= Pppd_pid_file;
			this-> lastProfile= lastProfile;
			this-> logfileName= logfileName;		
			this->minimizeAfterConnect= minimizeAfterConnect;
			this->showDebugConsole= showDebugConsole;
			this-> writeLogFile= writeLogFile;
			this-> useDefaultPaths= useDefaultPaths;
			this-> useSilentQuit= useSilentQuit;
			this-> holdGeneratedScripts= holdGeneratedScripts;
			this-> programsInPath= programsInPath;
			this-> enableDebugPppd= enableDebugPppd;
			this-> enableDebugPptpd= enableDebugPptpd;
			this-> enableDebugL2tpd= enableDebugL2tpd;
			this-> enableDebugXl2tpd= enableDebugXl2tpd;
			this-> enableFreeswanVerbose= enableFreeswanVerbose;
			this-> enableDebugOpenvpn= enableDebugOpenvpn;
			this-> useColorizedLogOutput= useColorizedLogOutput;
			this-> showInterfaceIPinTooltip= showInterfaceIPinTooltip;
			this-> dontQuitOnCloseEvent= dontQuitOnCloseEvent;
			this-> doAutoConnectAtStartup= doAutoConnectAtStartup;
			this-> useKwallet= useKwallet;
			this-> showStatusBar= showStatusBar;
			this-> showToolBar= showToolBar;
			this-> hideMainWindow= hideMainWindow;
			this-> PppdDebugLevel= PppdDebugLevel;
			this-> firstUseOfKwallet= firstUseOfKwallet;
			this-> shutdownIsCalled= shutdownIsCalled;
			this-> skipKwalletStoring= skipKwalletStoring;
			this-> hideOnCloseInfo= hideOnCloseInfo;
			this-> feedbackMailSent= feedbackMailSent;
			this-> doKillL2tpdIfStillRunning= doKillL2tpdIfStillRunning;
			this-> doKillXl2tpdIfStillRunning= doKillXl2tpdIfStillRunning;
			this-> doKillRacoonIfStillRunning= doKillRacoonIfStillRunning;
			this-> showConnectionTimeInTooltip= showConnectionTimeInTooltip;
			this-> VpncDebugLevel= VpncDebugLevel;
			this-> KvpncDebugLevel= KvpncDebugLevel;
			this-> OpenvpnDebugLevel= OpenvpnDebugLevel;
			this-> PptpLogLevel= PptpLogLevel;
			this-> LogViewerFontSize= LogViewerFontSize;
			this-> mainwindow_pos_x= mainwindow_pos_x;
			this-> mainwindow_pos_y= mainwindow_pos_y;
			this-> mainwindow_height= mainwindow_height;
			this-> mainwindow_width= mainwindow_width;
			this-> connectSleepDelay= connectSleepDelay;
			this-> connectSleepRetry= connectSleepRetry;
			this-> tryConnectTimeout= tryConnectTimeout;
			this-> connectionStartTime= connectionStartTime;
			this-> runningCheckCounter= runningCheckCounter;
			this-> runningCheckTimeout= runningCheckTimeout;
			this-> OpenvpnManagementPort= OpenvpnManagementPort;
			this->InfoLogColor= InfoLogColor;
			this->RemoteLogColor= RemoteLogColor;
			this->ErrorLogColor= ErrorLogColor;
			this->SuccessLogColor= SuccessLogColor;
			this->DebugLogColor= DebugLogColor;
			this->DebugBackgroundcolor= DebugBackgroundcolor;
			this->pos= pos;
			this->WindowPos= WindowPos;
			this->WindowSize= WindowSize;

		}
		saveOptions();

		QString msg="";
		if (importCount > 0 && importGlobal==true)
			msg = i18n("Import was successful. %1 profiles and global settings are imported.").arg(QString::number(importCount));
		if (importCount > 0 && importGlobal==false)
			msg = i18n("Import was successful. %1 profiles are imported.").arg(QString::number(importCount));
		if (importCount < 1 && importGlobal==false)
			msg = i18n("Import was successful. Global settings are imported.");
		KMessageBox::information ( 0, msg,i18n("Import success") );
	}
	else
	{
		KMessageBox::error ( 0, i18n ( "Reading of \"%1\" has been failed!" ).arg ( filename ) );
		return false;
	}
	return true;
}

bool KVpncConfig::importIpsecConfig(QString filename )
{
	QFile importfile (filename);
	if (!importfile.exists())
	{
		KMessageBox::error ( 0, i18n ( "Reading of \"%1\" has been failed!" ).arg ( filename ) );
		return false;
	}
	QPtrList<VpnAccountData> *ImportedAccountList = new QPtrList<VpnAccountData>();
	ImportedAccountList->setAutoDelete( TRUE ); // the list owns the objects
	QPtrList<IpsecImportSection> *IpsecImportSectionList = new QPtrList<IpsecImportSection>();
	
	bool isIpsecGlobalSection=false;
	bool firstSectionFound=false;
	bool useUdp=false;
	bool disableOpportunisticEncryption=true;
	int IpsecVersion=1;
	
	QString IpsecConfigSection="";
	bool validLineFound=false;
	if ( importfile.open(IO_ReadOnly))
	{
		QString line = NULL;
		QString IpsecConfigSectionName="";
		QString IpsecConfigData="";
		bool sectionEndFound=false;

// 		std::cout << "pass1: collecting sections" << std::endl;
		if (KvpncDebugLevel > 2)
			appendLogEntry("import freeswan config: pass1: collecting sections",debug);
		QTextStream stream(&importfile);
		while ( !stream.atEnd() )
		{
			line = stream.readLine();

// 			std::cout << "line: \"" << line << "\"" << std::endl;

			if ( IpsecConfigSectionName!="" && (  line=="\n" || removeWhiteSpaceAtBegin(line) =="\n" ||  line == NULL || line.startsWith("include") || line.startsWith("conn") ))
			{
				// end of section found
// 				std::cout << "end of section " << IpsecConfigSectionName << " found." << std::endl;
				if (KvpncDebugLevel > 2)
					appendLogEntry("import freeswan config: end of section " + IpsecConfigSectionName + " found.", debug);
				sectionEndFound=true;

				IpsecImportSection *section = new IpsecImportSection();
				section->SectionName = IpsecConfigSectionName;
				section->SectionData = IpsecConfigData;
				IpsecImportSectionList->append(section);
				IpsecConfigData="";
				IpsecConfigSectionName="";

// 				std::cout << "Section:"<< std::endl;
// 				std::cout << section->SectionName << std::endl;
// 				std::cout << section->SectionData.join("\n");
// 				std::cout << "-------------------"<< std::endl;

				if (KvpncDebugLevel > 2)
				{
					appendLogEntry( "import freeswan config: Section:", debug);
					appendLogEntry( section->SectionName , debug);
					appendLogEntry( section->SectionData.join("\n"), debug);
					appendLogEntry( "-------------------", debug);
				}
			}

			if (line.startsWith("conn"))
			{
				// section found
				IpsecConfigSectionName=line.simplifyWhiteSpace().section('#',0,0).section(" ",1,1);
// 				std::cout << "normal section found: " << IpsecConfigSectionName << std::endl;

				if (KvpncDebugLevel > 2)
					appendLogEntry( "import freeswan config: normal section found: " + IpsecConfigSectionName , debug);
				sectionEndFound=false;
				firstSectionFound=true;
			}
			if (line.startsWith("version"))
			{
				IpsecVersion=line.simplifyWhiteSpace().section('#',0,0).section(" ",1,1).toInt();
				validLineFound=true;
// 				std::cout << "ipsec version found: " << IpsecVersion << std::endl;
				if (KvpncDebugLevel > 2)
					appendLogEntry("import freeswan config: ipsec version found: "+ IpsecVersion ,debug);
			}
			if (line.startsWith("config"))
			{
				// config section found
				QString section =line.simplifyWhiteSpace().section('#',0,0).section(" ",1,1);
	
				if (section == "setup")
				{
					isIpsecGlobalSection=true;
					validLineFound=true;
// 					std::cout << "global section found." << std::endl;
				if (KvpncDebugLevel > 2)
					appendLogEntry("import freeswan config: global section found.",debug);
				}
			}
			if (line.startsWith("plutodebug"))
			{
				validLineFound=true;
				// FIXME not implemented yet
			}
			if (line.startsWith("nat_traversal="))
			{
				validLineFound=true;
				bool useUdp=false;
				if (line.section('=',1,1) == "yes")
				{
					useUdp=true;
					if (KvpncDebugLevel > 2)
						appendLogEntry("import freeswan config: use UDP (NAT).",debug);
				}
				else
				{
					useUdp=false;
					if (KvpncDebugLevel > 2)
						appendLogEntry("import freeswan config: use no UDP (no NAT).",debug);
				}
			}
			if (line.startsWith("include /etc/ipsec.d/examples/no_oe.conf"))
			{
				validLineFound=true;
// 				std::cout << "opportunistic enncrytion disabled found." << std::endl;
				if (KvpncDebugLevel > 2)
					appendLogEntry("import freeswan config: opportunistic enncrytion disabled found",debug);

				disableOpportunisticEncryption=true;
			}

			if (!sectionEndFound && firstSectionFound==true)
			{
				// collecting data
				QString cleanLine = removeWhiteSpaceAtBegin(line)+"\n";
// 				std:: cout << "clean line: \"" << cleanLine << "\"" << std::endl;
				if (!cleanLine.startsWith("#") && !cleanLine.startsWith("include")  && cleanLine != ""  && !line.startsWith("conn") && cleanLine != "\n")
				{
// 					std:: cout << "appending line: \"" << line << "\"" << std::endl;
					IpsecConfigData.append(line+"\n");
				}
				else
				{
// 					std:: cout << "skipping line: \"" << line << "\"" << std::endl;
				}
			}
		}
		if (IpsecConfigSectionName!="")
		{
			// end of section found
// 			std::cout << "end of section " << IpsecConfigSectionName << " found." << std::endl;
			if (KvpncDebugLevel > 2)
				appendLogEntry("end of section " + IpsecConfigSectionName +" found.",debug);
			sectionEndFound=true;

			IpsecImportSection *section = new IpsecImportSection();
			section->SectionName = IpsecConfigSectionName;
			section->SectionData = IpsecConfigData;
			IpsecImportSectionList->append(section);
			IpsecConfigData="";
			IpsecConfigSectionName="";
		}
		
		importfile.close();
	

// 		std::cout << "pass2: modifiy sections" << std::endl;
		if (KvpncDebugLevel > 2)
			appendLogEntry("import freeswan config: pass2: modifiy sections",debug);

// 		std::cout << "sections: IpsecImportSectionList: " << IpsecImportSectionList->count() << std::endl;
		if (KvpncDebugLevel > 2)
			appendLogEntry("import freeswan config: sections: IpsecImportSectionList: " + QString().setNum(IpsecImportSectionList->count()),debug);

		if (!IpsecImportSectionList->isEmpty())
		{
			for ( int i=0; i< (int)IpsecImportSectionList->count();i++ )
			{
				IpsecImportSection *section = IpsecImportSectionList->at(i);
				QString Name= section->SectionName;
				QStringList data = QStringList::split('\n',section->SectionData.join("\n"));

// 				std::cout << "	 => processing section: \"" << Name << "\"" << std::endl;
				if (KvpncDebugLevel > 2)
					appendLogEntry("import freeswan config: => processing section: \"" + Name + "\"",debug);

				for ( QStringList::Iterator it2 = data.begin(); it2 != data.end(); ++it2 )
				{
					QString dataline = *it2;
// 					std::cout << "dataline found: \"" << dataline.remove("\n") << "\"" << std::endl;
					if (removeWhiteSpaceAtBegin( dataline).startsWith("also="))
					{
// 						std::cout << "also= found, looking for other section..." << std::endl;
						if (KvpncDebugLevel > 2)
							appendLogEntry("import freeswan config: also= found, looking for other section...",debug);
						
						QString newdata = QString(section->SectionData.join("\n"));
						newdata.replace(QRegExp("^.*also=.*$"),"");
						section->SectionData= newdata;

						QString OtherSection=dataline.simplifyWhiteSpace().section('#',0,0).section("=",1,1);
						// we have to find the other section and replace this line by the config data of the other section (after the =)
						bool section_found=false;
						for (IpsecImportSection * it3 = IpsecImportSectionList->first(); it3; it3 = IpsecImportSectionList->next() )
						{
							if (it3->SectionName == OtherSection)
							{
// 								std::cout << "section " << OtherSection << " found, appending:" << std::endl;
								if (KvpncDebugLevel > 2)
									appendLogEntry("import freeswan config: section " + OtherSection + " found, appending:",debug);
// 								std::cout << "other data:" << std::endl << it3->SectionData.join("\n")  << "--------" << std::endl;
// 								std::cout << "section data:" << std::endl << section->SectionData.join("\n")  << "--------" << std::endl;
								section_found=true;
// 								data.remove(dataline);
								dataline="";
// 								QStringList otherdata = QStringList::split("\n",QString(it3->SectionData.join("\n")));
								QString OtherData = QString(it3->SectionData.join("\n"));
								
								QStringList newdata;
								
								for ( QStringList::Iterator it6 = data.begin(); it6 != data.end(); ++it6 )
								{
// 									std::cout << " also line: " << *it6 << std::endl;
									if (KvpncDebugLevel > 2)
										appendLogEntry("import freeswan config: also line: " + QString(*it6),debug);

									if (QString(*it6).find("also=") < 0)
									{
// 										std::cout << " also= found." << std::endl;
										if (KvpncDebugLevel > 2)
											appendLogEntry("import freeswan config: also= found.",debug);
										newdata.append(QString(*it6));
									}
									else
									{
// 										std::cout << " also= not found." << std::cout;
									if (KvpncDebugLevel > 2)
										appendLogEntry("import freeswan config: also= not found." ,debug);
									}
								}
// 								newdata.append(data.join("\n"));
								newdata.append(OtherData);
								section->SectionData= newdata;
								
							}
						}
						if (!section_found)
						{
// 							std::cout << "section " << OtherSection << " not found, skipping" << std::endl;
							if (KvpncDebugLevel > 2)
								appendLogEntry("import freeswan config: section " + OtherSection + " not found, skipping" ,debug);
						}
						
					}
    			}
			
			}
		}

// 		std::cout << "modified config" << std::endl << "---------------------" << std::endl;
// 		IpsecImportSection *it5=NULL;
// 		for ( it5 = IpsecImportSectionList->first(); it5; it5 = IpsecImportSectionList->next() )
// 		{
// 			QString SectionName= it5->SectionName;
// 			QStringList data = it5->SectionData;
// 
// 			std::cout << SectionName << std::endl;
// 			std::cout << data.join("\n") << std::endl;
// 		}
		if (KvpncDebugLevel > 2)
		{
			appendLogEntry("modified config" ,debug);
			appendLogEntry( "---------------------" ,debug);
			IpsecImportSection *it5=NULL;
			for ( it5 = IpsecImportSectionList->first(); it5; it5 = IpsecImportSectionList->next() )
			{
				QString SectionName= it5->SectionName;
				QStringList data = it5->SectionData;
	
				appendLogEntry(SectionName  ,debug);
				appendLogEntry(data.join("\n")  ,debug);
			}
		}



// 		std::cout << "pass3: parse sections" << std::endl;
		if (KvpncDebugLevel > 2)
			appendLogEntry("import freeswan config: pass3: parse sections" ,debug);


		if (!IpsecImportSectionList->isEmpty())
		{
			for ( int i=0; i< (int)IpsecImportSectionList->count();i++ )
			{
				IpsecImportSection *section = IpsecImportSectionList->at(i);

				QStringList sectiondata = QStringList::split('\n',section->SectionData.join("\n"));

// 				std::cout << "	 => processing section: \"" << section->SectionName << "\"" << std::endl;
// 				std::cout << "	 => data: \"" << section->SectionData.join("\n") << "\"" << std::endl;
		if (KvpncDebugLevel > 2)
			appendLogEntry("import freeswan config: 	 => processing section: \"" + section->SectionName + "\"" ,debug);

				VpnAccountData *profiledata = new VpnAccountData(VpnAccountData::freeswan,QString(section->SectionName)) ;
				

				for ( QStringList::Iterator it2 = sectiondata.begin(); it2!= sectiondata.end() ; it2++ )
				{
					QString dataline = *it2;
					

					QString line2 = removeWhiteSpaceAtBegin( dataline); // line of text excluding '\n' and replace all white chars with one blank
// 					std::cout << "dataline: \"" << line2 << "\"";
					if (line2.startsWith("rightsubnet="))
					{
						validLineFound=true;
						QString RightSubnet=line2.simplifyWhiteSpace().section("=",1,1).section('#',0,0);
// 						std::cout << "right subnet (remote) found: " << RightSubnet << std::endl;
						if (KvpncDebugLevel > 2)
							appendLogEntry("import freeswan config: right subnet (remote) found: " + RightSubnet ,debug);
						profiledata->setRemoteNetAddr(RightSubnet.section('/',0,0));
						profiledata->setRemoteNetMask(RightSubnet.section('/',1,1));
// 						std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." ,debug);
					}
					if (line2.startsWith("leftsubnet="))
					{
						validLineFound=true;
						QString LeftSubnet=line2.simplifyWhiteSpace().section('#',0,0).section("=",1,1);
// 						std::cout << "left subnet (local) found: " << LeftSubnet << std::endl;
						if (KvpncDebugLevel > 2)
							appendLogEntry("import freeswan config: left subnet (local) found: " + LeftSubnet ,debug);
	//						local subnet cant be set yet.
	// 					profiledata->setLocalNetAddr(RightSubnet.section('/',0,0));
	// 					profiledata->setLocalNetMask(RightSubnet.section('/',1,1));
	// 					std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;

					}
					if (line2.startsWith("rightnexthop="))
					{
						validLineFound=true;
						QString RightNextHop=line2.simplifyWhiteSpace().section('#',0,0);
// 						std::cout << "right next hop (remote) found: " << RightNextHop << std::endl;
						if (KvpncDebugLevel > 2)
							appendLogEntry("import freeswan config: right next hop (remote) found: " +RightNextHop ,debug);
						profiledata->setRightNextHop(RightNextHop);
// 						std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." ,debug);
					}
					if (line2.startsWith("leftnexthop="))
					{
						validLineFound=true;
						QString LeftNextHop=line2.simplifyWhiteSpace().section('#',0,0);
	//						local next hop cant be set yet.
	// 					std::cout << "left next hop (local) found: " << LeftNextHop << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: left next hop (local) found: " +LeftNextHop ,debug);
	// 					profiledata->setLeftNextHop(LeftNextHop);
	// 					std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." ,debug);
					}
					if (line2.startsWith("left="))
					{
						validLineFound=true;
						QString left=line2.simplifyWhiteSpace().section("=",1,1).section('#',0,0);
	//						local ip cant be set yet.
	// 					std::cout << "left found: " << left << std::endl;
// 							if (KvpncDebugLevel > 2)
// 								appendLogEntry("import freeswan config: left found: " + left ,debug);
	// 					profiledata->setLocal (left);
	// 					std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." ,debug);
					}
					if (line2.startsWith("right="))
					{
						validLineFound=true;
						QString right=line2.simplifyWhiteSpace().section("=",1,1).section('#',0,0);
// 						std::cout << "right (remote gateway) found: " << right << std::endl;
						if (KvpncDebugLevel > 2)
							appendLogEntry("import freeswan config: right (remote gateway) found: " + right ,debug);
						profiledata->setGateway(right);
// 						std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." ,debug);
					}
					if (line2.startsWith("leftcert="))
					{
						validLineFound=true;
						QString LeftCert=line2.simplifyWhiteSpace().section("=",1,1).section('#',0,0);
// 						std::cout << "left cert (local) found: " << LeftCert << std::endl;
						if (KvpncDebugLevel > 2)
							appendLogEntry("import freeswan config: left cert (local) found: " + LeftCert ,debug);
						profiledata->setX509Certificate(LeftCert);
// 						std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." ,debug);
					}
					if (line2.startsWith("rightca="))
					{
						validLineFound=true;
						QString RightCA=line2.simplifyWhiteSpace().section("=",1,1).section('#',0,0);
// 						std::cout << "right CA (remote) found: " << RightCA << std::endl;
						if (KvpncDebugLevel > 2)
							appendLogEntry("import freeswan config: right CA (remote) found: " +RightCA ,debug);
						profiledata->setCaCertificate( RightCA );
// 						std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." ,debug);
					}
					if (line2.startsWith("rightid="))
					{
						validLineFound=true;
						QString RightID=line2.simplifyWhiteSpace().remove("rightid=").section('#',0,0).remove('"');
// 						std::cout << "right ID (remote) found: " << RightID << std::endl;
						if (KvpncDebugLevel > 2)
							appendLogEntry("import freeswan config: right ID (remote) found: " + RightID ,debug);
						profiledata->setUseSpecialRemoteID(true);
						profiledata->setSpecialRemoteID ( RightID );
// 						std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." ,debug);
					}
					if (line2.startsWith("leftid="))
					{
						validLineFound=true;
						QString LeftID=line2.simplifyWhiteSpace().remove("lefttid=").section('#',0,0).remove('"');
// 						std::cout << "local ID (local) found: " << LeftID << std::endl;
						if (KvpncDebugLevel > 2)
							appendLogEntry("import freeswan config: local ID (local) found: " + LeftID ,debug);
						profiledata->setUseSpecialLocalID(true);
						profiledata->setSpecialLocalID ( LeftID );
// 						std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." ,debug);
					}

					if (line2.startsWith("rightrsasigkey="))
					{
						validLineFound=true;
						QString RightRsaSigKey=line2.simplifyWhiteSpace().section("=",1,1).section('#',0,0);
// 						std::cout << "right uses (remote) " << RightRsaSigKey << std::endl;
						if (KvpncDebugLevel > 2)
							appendLogEntry("import freeswan config: right uses (remote) " + RightRsaSigKey ,debug);
						profiledata->setAuthType(VpnAccountData::cert);
// 						std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." ,debug);
					}
					if (line2.startsWith("leftrsasigkey="))
					{
						validLineFound=true;
						QString LeftRsaSigKey=line2.simplifyWhiteSpace().section("=",1,1).section('#',0,0);
// 						std::cout << "left uses (remote) " << LeftRsaSigKey << std::endl;
						if (KvpncDebugLevel > 2)
							appendLogEntry("import freeswan config: left uses (remote) " + LeftRsaSigKey ,debug);
						profiledata->setAuthType(VpnAccountData::cert);
// 						std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." ,debug);
					}
					if (line2.startsWith("authby="))
					{
						validLineFound=true;
						QString Authby=line2.simplifyWhiteSpace().section("=",1,1).section('#',0,0);
// 						std::cout << "left and right use certs " << std::endl;
						if (KvpncDebugLevel > 2)
							appendLogEntry("import freeswan config: left and right use certs." ,debug);
						profiledata->setAuthType(VpnAccountData::cert);
// 						std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." ,debug);
					}
					if (line2.startsWith("auto=start"))
					{
	// 					validLineFound=true;
	// 					QString Authby=line2.simplifyWhiteSpace().section("=",1,1).section('#',0,0);
	// 					std::cout << "profile should be started" << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: profile should be started" ,debug);
	// 					profiledata->setAuthType(VpnAccountData::cert);
	// 					std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." ,debug);
					}
					if (line2.startsWith("leftsourceip="))
					{
						validLineFound=true;
						QString leftsourceip=line2.simplifyWhiteSpace().section("=",1,1).section('#',0,0);
	// 					//FIXME virtual ip addess not supported yet
	// 					std::cout << "left (local) have to use IP address " << leftsourceip << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: left (local) have to use IP address " + leftsourceip ,debug);
	// 					profiledata->setLocalVirtualIP(leftsourceip);
	// 					std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." ,debug);
					}
					if (line2.startsWith("esp="))
					{
						validLineFound=true;
						QString IpsecEsp=line2.simplifyWhiteSpace().remove("esp=").section('#',0,0);
// 						std::cout << "esp settings found: " << IpsecEsp << std::endl;
						if (KvpncDebugLevel > 2)
							appendLogEntry("import freeswan config: esp settings found: " + IpsecEsp ,debug);
						profiledata->setIpsecEsp(IpsecEsp);
// 						std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." ,debug);
					}
					if (line2.startsWith("ike="))
					{
						validLineFound=true;
						QString IpsecIke=line2.simplifyWhiteSpace().remove("ike=").section('#',0,0);
// 						std::cout << "ike settings found: " << IpsecIke << std::endl;
						if (KvpncDebugLevel > 2)
							appendLogEntry("import freeswan config: ike settings found: " + IpsecIke ,debug);
						profiledata->setIpsecIke(IpsecIke);
// 						std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
// 						if (KvpncDebugLevel > 2)
// 							appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." ,debug);
					}
					else
					{
	// 				std::cout << "comment found." << std::endl;
					}
				}

				if (useUdp)
				{
					profiledata->setUseUdp(true);
// 					std::cout << "nat_traversal=yes found, enabling udp." << std::endl;
						if (KvpncDebugLevel > 2)
							appendLogEntry("import freeswan config: nat_traversal=yes found, enabling udp." ,debug);
				}
				else
				{
					profiledata->setUseUdp(false);
// 					std::cout << "nat_traversal=no found, disabling udp." << std::endl;
						if (KvpncDebugLevel > 2)
							appendLogEntry("import freeswan config: nat_traversal=no found, disabling udp." ,debug);
				}
				if (disableOpportunisticEncryption==  true)
				{
					profiledata->setDisableOpportunisticEncryption(true);
				}
				else
				{
					profiledata->setDisableOpportunisticEncryption(false);
				}

				profiledata->setName("kvpnc_import_"+profiledata->getName());
				profiledata->setDescription(QString(i18n("import from ")+filename));
				ImportedAccountList->append(profiledata);
			}
		 }


		KvpncImportProfileSelectionBase selectdlg;
		selectdlg.ImportGlobalSettingsCheckBox->hide();
		VpnAccountData *it=NULL;
		int importCount=0;

		if ( !ImportedAccountList->isEmpty() )
		{
			selectdlg.ImportProfileListView->takeItem(selectdlg.ImportProfileListView->currentItem());
			selectdlg.ImportProfileListView->addColumn(i18n("Name"));
			selectdlg.ImportProfileListView->addColumn(i18n("Type"));
			selectdlg.ImportProfileListView->addColumn(i18n("Gateway"));
			selectdlg.ImportProfileListView->addColumn(i18n("Authentication"));
			selectdlg.ImportProfileListView->addColumn(i18n("Remote network"));
			QCheckListItem *item;
			for ( it = ImportedAccountList->first(); it; it = ImportedAccountList->next() )
			{
				QString name = it->getName();
				QString type="";
				if ( it->getConnectionType() == VpnAccountData::cisco )
					type = "cisco" ;
				else if ( it->getConnectionType() == VpnAccountData::ciscoorig )
					type = "ciscoorig" ;
				else if ( it->getConnectionType() == VpnAccountData::racoon )
					type = "racoon" ;
				else if ( it->getConnectionType() == VpnAccountData::l2tpd_racoon )
					type = "l2tpd (racoon)" ;
				else if ( it->getConnectionType() == VpnAccountData::freeswan )
					type = "freeswan" ;
				else if ( it->getConnectionType() == VpnAccountData::l2tpd_freeswan )
					type = "l2tpd (openswan)" ;
				else if ( it->getConnectionType() == VpnAccountData::pptp )
					type = "pptp" ;
				else if ( it->getConnectionType() == VpnAccountData::openvpn )
					type = "openvpn" ;
				else
					type =  i18n("other");
				
// 				litem->setSelectable(true);
				item = new QCheckListItem(selectdlg.ImportProfileListView,it->getName(),QCheckListItem::CheckBox);
				item->setText(1,type);
				item->setText(2,it->getGateway());
				if (it->getAuthType() == VpnAccountData::cert)
					item->setText(3,i18n("certificate"));
				else if (it->getAuthType() == VpnAccountData::cert)
					item->setText(3,i18n("preshared key"));
				else
					item->setText(3,i18n("unknown"));
				selectdlg.ImportProfileListView->insertItem(item);
				QString RemoteNetDiv="/";
				if (it->getRemoteNetAddr() == "")
				{
					it->setRemoteNetMask("");
					RemoteNetDiv="";
				}
				item->setText(4,QString(it->getRemoteNetAddr()+RemoteNetDiv+it->getRemoteNetMask()));

// 			std::cout << "insert profile into listview: " << name << std::endl;
			}
		}
		bool ret = selectdlg.exec();
		
		if (ret == true)
		{
			QListViewItemIterator it2( selectdlg.ImportProfileListView );
			for ( ; it2.current(); ++it2 )
			{
				if (  ( (QCheckListItem*)it2.current() )->isOn() )
				{
					VpnAccountData *data=NULL;
					it = 0;
					for ( it = ImportedAccountList->first(); it; it = ImportedAccountList->next() )
						if ( it->getName() == ( (QCheckListItem*)it2.current() )->text() && ( (QCheckListItem*)it2.current() )->isOn()  )
						{
							data = it;
							importCount++;
						}
					AccountList->append(data);
				}
			}
			
		}
		else
		{
			KMessageBox::sorry ( 0, i18n ( "Import canceled." ) );
			return false;
		}

		saveOptions();

		QString msg="";
		if (importCount > 0 )
			msg = i18n("Import was successful. %1 profiles are imported.").arg(QString::number(importCount));
		else
			msg = i18n("Import was canceled because no profiles are selected.").arg(QString::number(importCount));

		KMessageBox::information ( 0, msg,i18n("Import success") );
	
	}
	else
	{
		KMessageBox::error ( 0, i18n ( "Reading of \"%1\" has been failed!" ).arg ( filename ) );
		return false;
	}
	

	return true;

}

VpnAccountData* KVpncConfig::findProfile(QPtrList<VpnAccountData> *list,const QString& Name)
{
	VpnAccountData *it=NULL;
	bool found=false;
	if ( !list->isEmpty() )
	{
		for ( it = list->first(); it; it = list->next() )
		{
// 			std::cout << "findProfile(): it: " << it->getName() << " Name: " << Name << std::endl;
			if (Name == it->getName())
			{
				found=true;
// 				std::cout << "findProfile(): profile found." << std::endl;
				break;
			}
		}
	}
	if (found)
		return it;
	else
	{
// 		std::cout << "findProfile(): profile not found." << std::endl;
		return NULL;
	}
}

QString KVpncConfig::removeWhiteSpaceAtBegin(const QString str)
{
	QString newstr="";
	int i=0;
	for (i=0;i<(int)str.length();i++)
	{
		if (!QChar(str.at(i)).isSpace())
			break;
	}
	newstr = str.right(str.length()-i);
	return newstr;
}

void KVpncConfig::doBackupConfig()
{
	KStandardDirs * dirs = KGlobal::dirs();
	QString  config = QString(dirs->saveLocation( "config" )+"/kvpncrc");
	QFile OriginalConfFile( config );
	QFile backupOriginalConfFile( config+".backup" );
	QTextStream writestream( &backupOriginalConfFile );
	QTextStream readstream( &OriginalConfFile );
	if ( OriginalConfFile.open( IO_ReadOnly ) )
	{
		if (backupOriginalConfFile.open(IO_WriteOnly))
		{
			QString OriginalConfFileContent = QString( OriginalConfFile.readAll() )	;
			writestream << OriginalConfFileContent;
			OriginalConfFile.close();
			backupOriginalConfFile.close();
		}
	}
}

void KVpncConfig::restoreBackupConfig()
{
	KStandardDirs * dirs = KGlobal::dirs();
	QString  config = QString(dirs->saveLocation( "config" )+"/kvpncrc");
	QFile OriginalConfFile( config+".backup" );
	QFile backupOriginalConfFile( config );
	QTextStream writestream( &backupOriginalConfFile );
	QTextStream readstream( &OriginalConfFile );
	if ( OriginalConfFile.open( IO_ReadOnly ) )
	{
		if (backupOriginalConfFile.open(IO_WriteOnly))
		{
			QString OriginalConfFileContent = QString( OriginalConfFile.readAll() )	;
			writestream << OriginalConfFileContent;
			OriginalConfFile.close();
			backupOriginalConfFile.close();
		}
	}
}

void KVpncConfig::getToolsInfo()
{
	ToolInfo *it;
	//std::cout << "Tool (bin): " << bin << std::endl;
	if (!ToolList->isEmpty())
	{
		for ( it = ToolList->first(); it; it = ToolList->next() )
		{

				

				if(programsInPath)
				{
					it->addSearchPath("/sbin");
					it->addSearchPath("/usr/local/sbin");
					it->addSearchPath("/usr/sbin");
					it->addSearchPath("/bin");
					it->addSearchPath("/usr/local/bin");
					it->addSearchPath("/usr/bin");
				}
				it->collectToolInfo();
		}
	}
}

void KVpncConfig::removeEntry(QString Name)
{
	KStandardDirs * dirs = KGlobal::dirs();
	QString filePath = dirs->findResource ( "config", "kvpncrc" );

	appPointer->processEvents();

	if (useKwallet && KWallet::Wallet::isEnabled())
		config->deleteEntry( "First use of Kwallet", false );
	/* = user data = */
	VpnAccountData *it;
	if ( !AccountList->isEmpty() )
	{
		for ( it = AccountList->first(); it; it = AccountList->next() )
		{
			if ( !it->getName().isEmpty() )
			{
				QString name = it->getName();
				if (it->getName() == Name)
				{
					//std::cout << "Remove profile: " << it->getName() << std::endl;
					QString ProfileName = "Profile_";
					ProfileName += name;
					config->setGroup( ProfileName );

					/* passwords with kwallet */
					if ( useKwallet && KWallet::Wallet::isEnabled())
					{
	// 					if (KvpncDebugLevel > 0)
	// 						appendLogEntry(i18n( "Wallet enabled and available, writing to wallet." ),debug);
	// 					// Open local wallet
						wallet = KWallet::Wallet::openWallet(KWallet::Wallet::LocalWallet());
						if (wallet != 0)
						{
							QString walletname="kvpnc";
							// Check if folder exists, otherwise create it
							bool walletOK=true;
							if (!wallet->hasFolder(walletname))
							{
								walletOK = wallet->createFolder(walletname);
								wallet->sync();
							}
							if (walletOK)
							{
								wallet->setFolder(walletname);
								//std::cout << "[set] account: " << ProfileName << ", loginname: " << loginname << ", password: " << pwd << std::endl;
								bool UserPasswordOK = (wallet->removeEntry (QString(name+"__user_pw")) == 0);
								bool PskOK= (wallet->removeEntry (QString(name+"__psk")) == 0);
								bool PskKeyPassOK = (wallet->removeEntry (QString(name+"__priv_key_pwd")) == 0);
// 								wallet->sync();

								if (KvpncDebugLevel > 2)
								{
									if (UserPasswordOK)
										appendLogEntry(i18n( "delete of %1 was ok." ).arg(i18n("user password")), debug);
									else
										appendLogEntry(i18n( "delete of %1 has failed." ).arg(i18n("user password")), debug);
	//
									if (PskOK)
										appendLogEntry(i18n( "delete of %1 was successful." ).arg(i18n("preshared key")), debug);
									else
										appendLogEntry(i18n( "delete of %1 has failed." ).arg(i18n("preshared key")),debug);

									if (PskKeyPassOK)
										appendLogEntry(i18n( "delete of %1 was successful." ).arg(i18n("private key password")), debug);
									else
										appendLogEntry(i18n( "delete of %1 has failed." ).arg(i18n("private key password")),debug);


	// 								//std::cout << "success: " << pwdOK << std::endl;
								}
							}
							else
							{
								KMessageBox::error( 0, i18n( "Unable to create wallet folder for kvpnc!" ) );
								appendLogEntry(i18n( "Unable to create wallet folder for kvpnc!" ), error);
						}
					}
				}
					if (KvpncDebugLevel > 0)
						appendLogEntry(i18n( "Wallet disabled or not available, writing to config file." ),debug);
					// write passwords to config file :|
					config->deleteEntry( "User password" );
					config->deleteEntry( "Pre shared key" );
					config->deleteEntry( "PrivateKey password" );
					// 			}

					config->deleteEntry( "Connection type" );
					config->deleteEntry( "VPN Gateway" );
					config->deleteEntry( "VPN ID" );
					config->deleteEntry( "Username" );
					config->deleteEntry( "Save user password" );
					config->deleteEntry( "Save PSK" );
					config->deleteEntry( "Private key" );
					config->deleteEntry( "Use advanced settings" );
					config->deleteEntry( "Application version" );
					config->deleteEntry( "Local port" );
					config->deleteEntry( "NT domain name" );
					config->deleteEntry( "Perfect forward secrety" );
					config->deleteEntry( "IKE group" );
					config->deleteEntry( "Use application version" );
					config->deleteEntry( "Use global IPSec secret" );
					config->deleteEntry( "Use IKE group" );
					config->deleteEntry( "Use local port" );
					config->deleteEntry( "Use NT domain name" );
					config->deleteEntry( "Use single DES" );
					config->deleteEntry( "Use perfect Forward Secrety" );
					config->deleteEntry( "Remote net address" );
					config->deleteEntry( "Remote net mask" );
					config->deleteEntry( "x509 certificate" );
					config->deleteEntry( "Ca certificate" );
					config->deleteEntry( "Network device" );
					config->deleteEntry( "Cert path" );
					config->deleteEntry( "Auth type");
					config->deleteEntry( "do ping ip" );
					config->deleteEntry( "Ping host IP" );
					config->deleteEntry( "Use special remote ID" );
					config->deleteEntry( "Special server certificate" );
					config->deleteEntry( "Use special server certificate" );
					config->deleteEntry( "Special remote ID" );
					config->deleteEntry( "Use UDP-protocol" );
					config->deleteEntry( "Use UDP-port" );
					config->deleteEntry( "local UDP port" );
					config->deleteEntry( "use DNS_UPDATE" );
					config->deleteEntry( "use DNS-server" );
					config->deleteEntry( "DNS server" );
					config->deleteEntry( "get dns server from peer" );
					config->deleteEntry( "refuse 40 bit encryption" );

					appPointer->processEvents();

					config->deleteEntry( "refuse 128 bit encryption" );
					config->deleteEntry( "require stateless encryption" );
					config->deleteEntry( "require mppe" );
					config->deleteEntry( "refuse EAP" );
					config->deleteEntry( "Disable MPPE compression" );
					config->deleteEntry( "Local virtual IP" );
					config->deleteEntry( "Remote virtual IP" );
					config->deleteEntry( "Pre shared key file" );
					config->deleteEntry( "Execute command before connect" );
					config->deleteEntry( "Execute command after connect" );
					config->deleteEntry( "Execute command before disconnect" );
					config->deleteEntry( "Execute command after disconnect" );
					config->deleteEntry( "Command before connect" );
					config->deleteEntry( "Command after connect" );
					config->deleteEntry( "Command before disconnect" );
					config->deleteEntry( "Command after disconnect" );
					config->deleteEntry( "Use no BSD compression" );
					config->deleteEntry( "Use no deflate" );
					config->deleteEntry( "Set default route" );
					config->deleteEntry( "Replace default route" );
					config->deleteEntry( "Use own MTU" );
					config->deleteEntry( "Use own MRU" );
					config->deleteEntry( "MTU for pppd" );
					config->deleteEntry( "MRU for pppd" );
					config->deleteEntry( "Use Virtual IP" );
					config->deleteEntry( "Virtual IP" );
					config->deleteEntry( "PSK is in file" );
					config->deleteEntry( "Use additional network routes" );
					config->deleteEntry( "Hash algorithm" );
					config->deleteEntry( "Tunnel device type" );
					config->deleteEntry( "Use userdefined port" );
					config->deleteEntry( "Userdefined port" );
					config->deleteEntry( "Keep default route" );
					config->deleteEntry( "Additional network routes" );
					config->deleteEntry("AuthWithUsernameAndPassword" );
					config->deleteEntry("AllowEmptyGroupPassword" );
					config->deleteEntry("Encryption algorithm");
					config->deleteEntry("Authentication algorithm");

					config->deleteGroup( ProfileName );

					/* give info */
					//slotStatusMsg ( i18n( "Profile \"%1\" removed." ).arg( Name ), ID_FLASH_MSG );
					appendLogEntry ( i18n( "Profile \"%1\" removed." ).arg( Name ) , info);
					AccountList->remove(it);
					break;
				}
			}
		}
		appPointer->processEvents();
	}
	config->sync();
	appPointer->processEvents();
}


#include "kvpncconfig.moc"
