/* ****************************************************************************
  This file is part of KBabel

  Copyright (C) 1999-2000 by Matthias Kiefer
                            <matthias.kiefer@gmx.de>
		2001-2002 by Stanislav Visnovsky
			    <visnovsky@kde.org>

  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., 675 Mass Ave, Cambridge, MA 02139, USA.

**************************************************************************** */
#include <qtextstream.h>
#include <qfile.h>
#include <qdir.h>
#include <qfileinfo.h>
#include <qregexp.h>
#include <qstring.h>
#include <qtextcodec.h>
#include <qdatetime.h>

#include <kconfig.h>
#include <kglobal.h>
#include <klocale.h>
#include <kapplication.h>
#include <kio/netaccess.h>
#include <krfcdate.h>
#include <kurl.h>

#include "catalog.h"
#include "catalogitem.h"
#include "diff.h"
#include "findoptions.h"
#include "catalogview.h"
#include "editcmd.h"

#include "resources.h"
#include "version.h"

// from libgettext
extern "C"
{
#include "libgettext/fstrcmp.h"
}

#include "libgettext/pofiles.h"
#include <FlexLexer.h>

#include <fstream>

// set to 0 for unlimited undo
#define UNDODEPTH 0

bool Catalog::stopStaticRead = 0;

Catalog::Catalog(QObject* parent, const char* name) 
        : QObject(parent,name)
        , diffCache(30,73)
{
   _modified=false;
   _readOnly=false;
   fileCodec=0;
   numberOfPluralForms=-1;

   readPreferences();

   _views.setAutoDelete(false);

   _undoList.setAutoDelete(true);
   _redoList.setAutoDelete(true);

   diffCache.setAutoDelete(true);
}


Catalog::~Catalog()
{
}

QString Catalog::msgid(uint index) const
{
   uint max=_entries.count()-1;
   if(index > max)
      index=max;

   return _entries[index].msgid();
}

QString Catalog::msgstr(uint index) const
{
   uint max=_entries.count()-1;
   if(index > max)
      index=max;

   return _entries[index].msgstr();
}

QString Catalog::comment(uint index) const
{
   uint max=_entries.count()-1;
   if(index > max)
      index=max;

   return _entries[index].comment();
}

CatalogItem Catalog::header() const
{
   return _header;
}


int Catalog::indexForMsgid(const QString& id) const
{
    int i=0;
	QValueList<CatalogItem>::ConstIterator it = _entries.begin(); 

    while(it != _entries.end() && (*it).msgid() != id)
    {
        ++it; 
        i++;
    }

    if(it == _entries.end())
        i=-1;

    return i;
}

QStringList Catalog::tagList(uint index)
{
   uint max=_entries.count()-1;
   if(index > max)
      index=max;

   return _entries[index].tagList();
}


/*
bool Catalog::setMsgstr(uint index,QString msgstr)
{
    kdWarning() << "Catalog::setMsgstr()" << endl;

   bool untranslatedChanged=false;

   if(_entries[index].isUntranslated() && !msgstr.isEmpty())
   {
      _untransIndex.remove(index);
      untranslatedChanged=true;
   }
   else if(msgstr.isEmpty())
   {
      QValueList<uint>::Iterator it;

      // insert index in the right place in the list
      it = _untransIndex.begin();
      while(it != _untransIndex.end() && index > (*it))
      {
         ++it;
      }
      _untransIndex.insert(it,index);

      untranslatedChanged=true;
   }

   _entries[index].setMsgstr(msgstr);

   setModified(true);

   if(untranslatedChanged)
      emit signalNumberOfUntranslatedChanged(numberOfUntranslated());

   return untranslatedChanged;
}
*/

/*
bool Catalog::setComment(uint index,QString comment)
{
    kdWarning() << "Catalog::setComment()" << endl;
   bool fuzziesChanged=false;


   bool wasFuzzy=_entries[index].isFuzzy();

   _entries[index].setComment(comment);

   bool isFuzzy=_entries[index].isFuzzy();

   if(wasFuzzy && !isFuzzy)
   {
      _fuzzyIndex.remove(index);
      fuzziesChanged=true;
   }
   else if(isFuzzy)
   {
      QValueList<uint>::Iterator it;

      // insert index in the right place in the list
      it = _fuzzyIndex.begin();
      while(it != _fuzzyIndex.end() && index > (*it))
      {
         ++it;
      }
      _fuzzyIndex.insert(it,index);

      fuzziesChanged=true;
   }

   setModified(true);

   if(fuzziesChanged)
      emit signalNumberOfFuzziesChanged(numberOfFuzzies());


   return fuzziesChanged;
}
*/

bool Catalog::setHeader(CatalogItem newHeader)
{
   if(newHeader.isValid())
   {
      _header=newHeader;
      setModified(true);

      emit signalHeaderChanged();
      
      return true;
   }

   return false;
}

KURL Catalog::currentURL() const
{
   return _url;
}

void Catalog::setCurrentURL(const KURL& url)
{
   _url=url;
}


CatalogItem Catalog::updatedHeader(CatalogItem oldHeader, bool usePrefs) const
{
   QStringList headerList=oldHeader.msgstrAsList();

   QStringList::Iterator it;
   QString temp;
   bool found;
   if(!usePrefs || _saveSettings.updateLastTranslator)
   {
      found=false;

      temp="Last-Translator: "+_identitySettings.authorName;
      if(!_identitySettings.authorEmail.isEmpty())
      {
         temp+=(" <"+_identitySettings.authorEmail+">");
      }
      temp+="\\n";
      for( it = headerList.begin(); it != headerList.end(); ++it )
      {
         if((*it).contains(QRegExp("^ *Last-Translator:.*")))
         {
            (*it).replace(QRegExp("^ *Last-Translator:.*"),temp);
            found=true;
         }
       }
       if(!found)
       {
          headerList.append(temp);
       }
   }
   if(!usePrefs || _saveSettings.updateRevisionDate)
   {
      found=false;

      temp="PO-Revision-Date: "+dateTime()+"\\n";

      for( it = headerList.begin(); it != headerList.end(); ++it )
      {
         if((*it).contains(QRegExp("^ *PO-Revision-Date:.*")))
         {
            (*it).replace(QRegExp("^ *PO-Revision-Date:.*"),temp);
            found=true;
         }
       }
       if(!found)
       {
          headerList.append(temp);
       }
   }
   if(!usePrefs || _saveSettings.updateLanguageTeam)
   {
      found=false;

      temp="Language-Team: "+_identitySettings.languageName;
      if(!_identitySettings.mailingList.isEmpty())
      {
         temp+=(" <"+_identitySettings.mailingList+">");
      }
      temp+="\\n";
      for( it = headerList.begin(); it != headerList.end(); ++it )
      {
         if((*it).contains(QRegExp("^ *Language-Team:.*")))
         {
            (*it).replace(QRegExp("^ *Language-Team:.*"),temp);
            found=true;
         }
       }
       if(!found)
       {
          headerList.append(temp);
       }
   }
   if(!usePrefs || _saveSettings.updateCharset)
   {
      found=false;

	  QString encodingStr;
      if(_saveSettings.useOldEncoding && fileCodec)
      {
		  encodingStr = charsetString(fileCodec);
      }
      else
      {
          encodingStr=charsetString(_saveSettings.encoding);
      }
      temp="Content-Type: text/plain; charset="+encodingStr+"\\n";
      QString charsettemp="; charset="+encodingStr+"\\n";

      for( it = headerList.begin(); it != headerList.end(); ++it )
      {
         if((*it).contains(QRegExp("^ *Content-Type:.*;\\s*charset=")))
         {
            (*it).replace(QRegExp(";\\s*charset\\s*=\\s*[^\\\"\\n]+"),charsettemp);
            found=true;
         }
       }
       if(!found)
       {
          headerList.append(temp);
       }
   }
   if(!usePrefs || _saveSettings.updateEncoding)
   {
      found=false;

      temp="Content-Transfer-Encoding: 8bit\\n";

      for( it = headerList.begin(); it != headerList.end(); ++it )
      {
         if((*it).contains(QRegExp("^ *Content-Transfer-Encoding:.*")))
         {
            (*it).replace(QRegExp("^ *Content-Transfer-Encoding:.*"),temp);
            found=true;
         }
       }
       if(!found)
       {
          headerList.append(temp);
       }
   }

   temp="X-Generator: KBabel %1\\n";
   temp=temp.arg(VERSION);
   found=false;

   for( it = headerList.begin(); it != headerList.end(); ++it )
   {
      if((*it).contains(QRegExp("^ *X-Generator:.*")))
      {
         (*it).replace(QRegExp("^ *X-Generator:.*"),temp);
         found=true;
      }
    }
    if(!found)
    {
       headerList.append(temp);
    }

   QString msgstr;
   for( it = headerList.begin(); it != headerList.end(); ++it )
   {
      msgstr+=("\n"+(*it));
   }

   msgstr.remove(0,1);// remove first newline

   oldHeader.setMsgstr(msgstr);
   return oldHeader;
}

void Catalog::setFuzzy(uint index, bool on)
{
   uint max=_entries.count()-1;
   if(index > max)
       return;

   if(_entries[index].isFuzzy() != on)
   {
      EditCommand *cmd;
      cmd=new BeginCommand();
      cmd->setPart(EditCommand::Comment);
      cmd->setIndex(index);
      applyEditCommand( cmd, 0 );
      
      QPtrList<EditCommand> editList;
      if(on)
      {
          editList=_entries[index].addFuzzy(false);
      }
      else
      {
          editList=_entries[index].removeFuzzy(false);
          _fuzzyIndex.remove(index);
      }

      for ( cmd=editList.first(); cmd != 0; cmd=editList.next() )
      {
         cmd->setIndex(index);
         applyEditCommand(cmd,0);
      }

      setModified(true);

      cmd=new EndCommand();
      cmd->setPart(EditCommand::Comment);
      cmd->setIndex(index);
      applyEditCommand( cmd ,0);

      emit signalNumberOfFuzziesChanged(numberOfFuzzies());
   }

}

void Catalog::removeFuzzyStatus(uint index)
{
    setFuzzy(index,false);
}


void Catalog::setModified(bool flag)
{
    bool old=_modified;
    _modified=flag;

    if(old!=_modified);
       emit signalModified(flag);
}


QString Catalog::packageName() const
{
    QString package=_url.fileName();

    int index=package.findRev(QRegExp(".pot?"));

    if(index>0)
      package=package.left(index);

    return package;
}

QString Catalog::packageDir() const
{
    QString dir=_url.directory();

    return dir;
}

QString Catalog::encoding() const
{
    QString encodingStr;
    if(_saveSettings.useOldEncoding && fileCodec)
    {
	    encodingStr = charsetString(fileCodec);
    }
    else
    {
        encodingStr= charsetString(_saveSettings.encoding);
    }

    return encodingStr;
}

Catalog::IOStatus Catalog::openURL(const KURL& url, bool& errorInHeader)
{
   QString target;

   if(KIO::NetAccess::download(url, target))
   {
        // load in the file (target is always local)
        IOStatus success=openFile(target,errorInHeader);

        // and remove the temp file
        KIO::NetAccess::removeTempFile(target);

        // store current url
        if(success==OK || success==RECOVERED_PARSE_ERROR)
        {
           setModified(false);
           _url=url;

           emit signalFileOpened(_readOnly);
           emit signalNumberOfFuzziesChanged(numberOfFuzzies());
           emit signalNumberOfUntranslatedChanged(numberOfUntranslated());
           emit signalTotalNumberChanged(numberOfEntries());
        }

        return success;
   }
   else
   {
      return OS_ERROR;
   }
}

Catalog::IOStatus Catalog::openURL(const KURL& openUrl, const KURL& saveURL, bool& errorInHeader)
{
   QString target;

   if(KIO::NetAccess::download(openUrl, target))
   {
        // load in the file (target is always local)
        IOStatus success=openFile(target,errorInHeader);

        // and remove the temp file
        KIO::NetAccess::removeTempFile(target);

        // store current url
        if(success==OK || success==RECOVERED_PARSE_ERROR)
        {
           setModified(false);
           _url = saveURL;

           emit signalFileOpened(_readOnly);
           emit signalNumberOfFuzziesChanged(numberOfFuzzies());
           emit signalNumberOfUntranslatedChanged(numberOfUntranslated());
           emit signalTotalNumberChanged(numberOfEntries());
        }

        return success;
   }
   else
   {
      return OS_ERROR;
   }
}

Msgfmt::Status Catalog::checkSyntax(QString& output)
{
   QString filename;
   bool tempFileUsed=false;

   if(_url.isLocalFile() && !isModified())
   {
      filename=_url.path(0);
   }
   else
   {
      tempFileUsed=true;
      filename=saveTempFile();
   }

   Msgfmt msgfmt;
   Msgfmt::Status result = msgfmt.checkSyntax( filename , output );

   clearErrorList();

   if( result==Msgfmt::SyntaxError )
   {
      int currentIndex=-1;
      int currentLine=0;

      if( !_header.msgstr().isEmpty() )
         currentLine=_header.totalLines()+1;

      QStringList lines = QStringList::split("\n",output);
      for ( QStringList::Iterator it = lines.begin(); it != lines.end(); ++it )
      {
         if( (*it).contains(QRegExp("^.+:\\d+:")) )
         {
            int begin=(*it).find(":",0)+1;
            int end=(*it).find(":",begin);

            QString line=(*it).mid(begin,end-begin);

            while( line.toInt() > currentLine )
            {
               currentIndex++;
               currentLine += ( _entries[currentIndex].totalLines() + 1 );
            }

            if( !_errorIndex.contains(currentIndex) )
            {
               _errorIndex.append(currentIndex);
			   _entries[currentIndex].setSyntaxError(true);
            }
         }
      }
   }

   if(tempFileUsed)
      QFile::remove(filename);

   return result;
}

void Catalog::clearErrorList()
{
	QValueList<uint>::Iterator it;
	for(it = _errorIndex.begin(); it != _errorIndex.end(); ++it)
	{
		_entries[(*it)].setSyntaxError(false);
	}

	_errorIndex.clear();
}

void Catalog::removeFromErrorList(uint index)
{
	if(_errorIndex.contains(index))
	{
		_errorIndex.remove(index);
		_entries[index].setSyntaxError(false);
	}
}

int Catalog::itemStatus(uint index, bool recheck, int whatToCheck)
{
	uint max=_entries.count()-1;
	if(index > max)
		index=max;

	CatalogItem& item = _entries[index]; 

	if(recheck)
	{
		if(whatToCheck & CatalogItem::Args)
			item.checkArgs(_miscSettings.contextInfo);

		if(whatToCheck & CatalogItem::Accel)
			item.checkAccelerator(_miscSettings.accelMarker,_miscSettings.contextInfo);

		if(whatToCheck & CatalogItem::Equation)
			item.checkEquation();

		if(whatToCheck & CatalogItem::Context)
			item.checkForContext(_miscSettings.contextInfo);
        
		if((whatToCheck & CatalogItem::SingularPlural))
        {
			item.checkSingularPlural(_miscSettings.singularPlural
                    ,numberOfPluralForms);
        }
	}

	return item.errors();
}

bool Catalog::checkArgs(bool clearErrors)
{
	if(clearErrors)
		clearErrorList();

	int index = 0;
	bool hasErrors=false;
	for ( QValueList<CatalogItem>::Iterator it = _entries.begin(); 
					it != _entries.end(); ++it, index++ )
	{
		if(!(*it).checkArgs(_miscSettings.contextInfo))
		{
			if( !_errorIndex.contains(index) )
			{
				_errorIndex.append(index);
				hasErrors=true;
			}
		}
	}

	return !hasErrors;
}


bool Catalog::checkAccelerators(bool clearErrors)
{
	if(clearErrors)
		clearErrorList();

	int index = 0;
	bool hasErrors=false;
	for ( QValueList<CatalogItem>::Iterator it = _entries.begin(); 
					it != _entries.end(); ++it , index++)
	{
		if(!(*it).checkAccelerator(_miscSettings.accelMarker,_miscSettings.contextInfo))
		{
			if( !_errorIndex.contains(index) )
			{
				_errorIndex.append(index);
				hasErrors=true;
			}
		}
	}

	return !hasErrors;
}

bool Catalog::checkEquations(bool clearErrors)
{
	if(clearErrors)
		clearErrorList();

	int index = 0;
	bool hasErrors=false;
	for ( QValueList<CatalogItem>::Iterator it = _entries.begin(); 
					it != _entries.end(); ++it , index++)
	{
		if(!(*it).checkEquation())
		{
			if( !_errorIndex.contains(index) )
			{
				_errorIndex.append(index);
				hasErrors=true;
			}
		}
	}

	return !hasErrors;
}


bool Catalog::checkForContext(bool clearErrors)
{
	if(clearErrors)
		clearErrorList();

	int index = 0;
	bool hasErrors=false;
	for ( QValueList<CatalogItem>::Iterator it = _entries.begin(); 
					it != _entries.end(); ++it , index++)
	{
		if(!(*it).checkForContext(_miscSettings.contextInfo))
		{
			if( !_errorIndex.contains(index) )
			{
				_errorIndex.append(index);
				hasErrors=true;
			}
		}
	}

	return !hasErrors;
}

bool Catalog::checkSingularPlural(bool clearErrors)
{
    if(clearErrors)
		clearErrorList();
    
	int index = 0;
	bool hasErrors=false;
	for ( QValueList<CatalogItem>::Iterator it = _entries.begin(); 
					it != _entries.end(); ++it , index++)
	{
		if(!(*it).checkSingularPlural(_miscSettings.singularPlural
                    ,numberOfPluralForms))
		{
			if( !_errorIndex.contains(index) )
			{
				_errorIndex.append(index);
				hasErrors=true;
			}
		}
	}

	return !hasErrors;
}


void Catalog::clear()
{
    _entries.clear();
    _url=KURL();
    _obsolete.clear();

    if(_undoList.count() > 0)
       emit signalUndoAvailable(false);
    if(_redoList.count() > 0)
       emit signalRedoAvailable(false);

    _undoList.clear();
    _redoList.clear();

    msgidDiffList.clear();
    msgstr2MsgidDiffList.clear();
    diffCache.clear();
}


uint Catalog::numberOfEntries() const
{
   return _entries.count();
}

uint Catalog::numberOfFuzzies() const
{
   return _fuzzyIndex.count();
}

uint Catalog::numberOfUntranslated() const
{
   return _untransIndex.count();
}


bool Catalog::hasFuzzyInFront(uint index)  const
{
   if(findPrevInList(_fuzzyIndex,index)>=0)
   {
      return true;
   }

   return false;
}

bool Catalog::hasFuzzyAfterwards(uint index) const
{
   if(findNextInList(_fuzzyIndex,index)>=0)
   {
      return true;
   }

   return false;
}

bool Catalog::hasUntranslatedInFront(uint index) const
{
   if(findPrevInList(_untransIndex,index)>=0)
   {
      return true;
   }

   return false;
}

bool Catalog::hasUntranslatedAfterwards(uint index) const
{
   if(findNextInList(_untransIndex,index)>=0)
   {
      return true;
   }

   return false;
}

bool Catalog::hasErrorInFront(uint index)  const
{
   if(findPrevInList(_errorIndex,index)>=0)
   {
      return true;
   }

   return false;
}

bool Catalog::hasErrorAfterwards(uint index) const
{
   if(findNextInList(_errorIndex,index)>=0)
   {
      return true;
   }

   return false;
}

bool Catalog::isFuzzy(uint index) const
{
   if(index > numberOfEntries())
      return false;

   return _entries[index].isFuzzy();
}


bool Catalog::isUntranslated(uint index) const
{
   if(index > numberOfEntries())
      return false;

   return _entries[index].isUntranslated();
}

bool Catalog::hasError(uint index) const
{
   return _errorIndex.contains(index);
}

bool Catalog::isPluralForm(uint index) const
{
    if(index > numberOfEntries())
        return false;

    return _entries[index].isPluralForm();
}

int Catalog::nextFuzzy(uint startIndex) const
{
   return findNextInList(_fuzzyIndex,startIndex);
}

int Catalog::prevFuzzy(uint startIndex) const
{
   return findPrevInList(_fuzzyIndex,startIndex);
}

int Catalog::nextUntranslated(uint startIndex) const
{
   return findNextInList(_untransIndex,startIndex);
}

int Catalog::prevUntranslated(uint startIndex) const
{
   return findPrevInList(_untransIndex,startIndex);
}


int Catalog::nextError(uint startIndex) const
{
   return findNextInList(_errorIndex,startIndex);
}

int Catalog::prevError(uint startIndex) const
{
   return findPrevInList(_errorIndex,startIndex);
}


void Catalog::registerView(CatalogView* view)
{
   if(_views.containsRef(view)==0)
   {
      _views.append(view);
   }
}


void Catalog::removeView(CatalogView* view)
{
   _views.removeRef(view);
}


void Catalog::updateViews(EditCommand* cmd,CatalogView* view2exclude)
{
    CatalogView* view;
    for ( view=_views.first(); view != 0; view=_views.next())
    {
       if(view!=view2exclude)
       {
          view->update(cmd);
       }
    }
}



bool Catalog::hasView() const
{
    if(_views.count()==0)
           return false;

    return true;
}

bool Catalog::isLastView() const
{
    if(_views.count()<=1)
           return true;

    return false;
}


void Catalog::readPreferences()
{
   //KConfigBase* config=KGlobal::config();
   KConfig* config=KGlobal::config();

   KConfigGroupSaver groupSaver(config,"Header");

   _saveSettings.autoUpdate=config->readBoolEntry("AutoUpdate"
				   ,Defaults::Save::autoUpdate);
   _saveSettings.updateLastTranslator=config->readBoolEntry("Update-Last-Translator"
                       ,Defaults::Save::updateLastTranslator);
   _saveSettings.updateRevisionDate=config->readBoolEntry("Update-Revision-Date"
                       ,Defaults::Save::updateRevisionDate);
   _saveSettings.updateLanguageTeam=config->readBoolEntry("Update-Language-Team"
                       ,Defaults::Save::updateLanguageTeam);
   _saveSettings.updateCharset=config->readBoolEntry("Update-Charset"
                       ,Defaults::Save::updateCharset);
   _saveSettings.updateEncoding=config->readBoolEntry("Update-Encoding"
                       ,Defaults::Save::updateEncoding);
   _saveSettings.encoding=(FileEncoding)(config->readNumEntry("Encoding"
						   ,(int)Defaults::Save::encoding));
   _saveSettings.useOldEncoding=config->readBoolEntry("UseOldEncoding"
                           ,Defaults::Save::useOldEncoding);

   _saveSettings.autoSyntaxCheck = config->readBoolEntry("AutoSyntaxCheck"
                 ,Defaults::Save::autoSyntaxCheck);
   _saveSettings.customDateFormat = config->readEntry("CustomDateFormat"
                 ,Defaults::Save::customDateFormat());
   _saveSettings.dateFormat = (Qt::DateFormat)( config->readNumEntry("DateFormat"
                 ,(int)Defaults::Save::dateFormat) );

    Defaults::Identity defaultIdentity;
   _identitySettings.authorName=config->readEntry("Author-Name"
				   ,defaultIdentity.authorName());
   _identitySettings.authorEmail=config->readEntry("Author-Email"
				   ,defaultIdentity.authorEmail());
   _identitySettings.languageName=config->readEntry("Language"
				   ,defaultIdentity.languageName());
   _identitySettings.languageCode=config->readEntry("LanguageCode"
				   ,defaultIdentity.languageCode());
   _identitySettings.mailingList=config->readEntry("Mailinglist"
				   ,defaultIdentity.mailingList());
   _identitySettings.timeZone=config->readEntry("Timezone"
				   ,defaultIdentity.timezone());

   config->setGroup("Misc");
   
   Defaults::Misc defaultMisc;
   QString temp=config->readEntry("AccelMarker"
				   ,defaultMisc.accelMarker());
   if(temp.length() > 0)
		   _miscSettings.accelMarker=temp[0];

   temp = config->readEntry("ContextInfo"
				   ,defaultMisc.contextInfo().pattern());
   _miscSettings.contextInfo.setPattern(temp);
   
   temp = config->readEntry("SingularPlural"
				   ,defaultMisc.singularPlural().pattern());
   _miscSettings.singularPlural.setPattern(temp);

   _identitySettings.numberOfPluralForms=config->readNumEntry("PluralForms"
           , defaultIdentity.numberOfPluralForms);

   getNumberOfPluralForms();
}

void Catalog::savePreferences()
{
   //KConfigBase* config=KGlobal::config();
   KConfig* config=KGlobal::config();

   KConfigGroupSaver groupSaver(config,"Header");

   config->writeEntry("AutoUpdate",_saveSettings.autoUpdate);
   config->writeEntry("Update-Last-Translator",_saveSettings.updateLastTranslator);
   config->writeEntry("Update-Revision-Date",_saveSettings.updateRevisionDate);
   config->writeEntry("Update-Language-Team",_saveSettings.updateLanguageTeam);
   config->writeEntry("Update-Charset",_saveSettings.updateCharset);
   config->writeEntry("Update-Encoding",_saveSettings.updateEncoding);
   config->writeEntry("Encoding",(int)_saveSettings.encoding);
   config->writeEntry("UseOldEncoding",_saveSettings.useOldEncoding);

   config->writeEntry("AutoSyntaxCheck",_saveSettings.autoSyntaxCheck);
   config->writeEntry("CustomDateFormat",_saveSettings.customDateFormat);
   config->writeEntry("DateFormat",(int)_saveSettings.dateFormat);

   config->writeEntry("Author-Name",_identitySettings.authorName);
   config->writeEntry("Author-Email",_identitySettings.authorEmail);
   config->writeEntry("Language",_identitySettings.languageName);
   config->writeEntry("LanguageCode",_identitySettings.languageCode);
   config->writeEntry("Mailinglist",_identitySettings.mailingList);
   config->writeEntry("Timezone",_identitySettings.timeZone);


   config->setGroup("Misc");
   QString temp(_miscSettings.accelMarker);
   config->writeEntry("AccelMarker",temp);
   config->writeEntry("ContextInfo",_miscSettings.contextInfo.pattern());
   config->writeEntry("SingularPlural",_miscSettings.singularPlural.pattern());
   config->writeEntry("PluralForms",_identitySettings.numberOfPluralForms);
   
   config->sync();
}


void Catalog::setSettings(SaveSettings settings)
{
   _saveSettings=settings;

   emit signalSettingsChanged(settings);
}

void Catalog::setSettings(IdentitySettings settings)
{
   QString oldLanguageCode = _identitySettings.languageCode;
   int oldForms =_identitySettings.numberOfPluralForms;
    
   
   _identitySettings=settings;

   if(oldLanguageCode != _identitySettings.languageCode)
   {
       getNumberOfPluralForms();
   }

    if(oldForms != _identitySettings.numberOfPluralForms)
    {
        getNumberOfPluralForms();
    }

   emit signalSettingsChanged(settings);
}

void Catalog::setSettings(MiscSettings settings)
{
	_miscSettings=settings;

	emit signalSettingsChanged(settings);
}

void Catalog::generateIndexLists()
{
   _fuzzyIndex.clear();
   _untransIndex.clear();
   clearErrorList();

   uint counter=0;
   for ( QValueList<CatalogItem>::Iterator it = _entries.begin(); it != _entries.end(); ++it )
   {
       if((*it).isUntranslated())
       {
          _untransIndex.append(counter);
       }
       else if((*it).isFuzzy())
       {
          _fuzzyIndex.append(counter);
       }

       counter++;
   }

}

int Catalog::findNextInList(const QValueList<uint>& list,uint index) const
{
    QValueList<uint>::ConstIterator it;

    int nextIndex=-1;

    // find index in List
    it=list.find(index);

    // if the given index is found in the list and not the last entry
    // in the list, return the next listentry
    if(it!=list.end() && it!=list.fromLast())
    {
       ++it;
       return (*it);
    }

    // if the index is not in the list, search the index in the list, that
    // is the nearest to the given index
    for( it = list.begin(); it != list.end(); ++it )
    {
       if((*it) > index)
       {
          nextIndex=(*it);
          break;
       }
    }


    return nextIndex;
}

int Catalog::findPrevInList(const QValueList<uint>& list,uint index) const
{
    QValueList<uint>::ConstIterator it;

    int prevIndex=-1;

    it=list.find(index);

    // if the given index is found in the list and not the last entry
    // in the list, return the next listentry
    if(it!=list.end() && it!=list.begin())
    {
       --it;
       return (*it);
    }


    // if the index is not in the list, search the index in the list, that
    // is the nearest to the given index
    for( it = list.fromLast(); it != list.end(); --it )
    {
       if((*it) < index)
       {
          prevIndex=(*it);
          break;
       }
    }


    return prevIndex;
}


QString Catalog::dateTime() const
{
    QString dateTimeString;
    QDate date=QDate::currentDate();
    QTime time=QTime::currentTime();

    switch(_saveSettings.dateFormat)
    {
       case Qt::LocalDate:
       {
          return KGlobal::locale()->formatDateTime(QDateTime::currentDateTime());
       }
       case Qt::ISODate:
          dateTimeString = Defaults::Save::customDateFormat();
          break;
       case Qt::TextDate:
          dateTimeString = _saveSettings.customDateFormat;
          break;
    }

    // the year
    dateTimeString.replace( QRegExp("%Y"), QString::number( date.year() ) );
    dateTimeString.replace( QRegExp("%y"), QString::number( date.year() ).right(2) );

    // the month
    if(date.month()<10)
    {
       dateTimeString.replace( QRegExp("%m"), "0"+QString::number( date.month() ) );
    }
    else
    {
       dateTimeString.replace( QRegExp("%m"), QString::number( date.month() ) );
    }

    dateTimeString.replace( QRegExp("%f"), QString::number( date.month() ) );

    dateTimeString.replace( QRegExp("%b"), date.longMonthName(date.month()) );
    dateTimeString.replace( QRegExp("%h"), date.longMonthName(date.month()) );

    // the day
    dateTimeString.replace( QRegExp("%j"), QString::number( date.dayOfYear() ) );
    dateTimeString.replace( QRegExp("%e"), QString::number( date.day() ) );
    if(date.day() < 10)
    {
       dateTimeString.replace( QRegExp("%d"), "0"+QString::number( date.day() ) );
    }
    else
    {
       dateTimeString.replace( QRegExp("%d"), QString::number( date.day() ) );
    }

    dateTimeString.replace( QRegExp("%a"), date.longDayName( date.dayOfWeek() ) );


    // hour
    dateTimeString.replace( QRegExp("%k"), QString::number( time.hour() ) );

    if(time.hour() < 10)
    {
       dateTimeString.replace( QRegExp("%H"), "0"+QString::number( time.hour() ) );
    }
    else
    {
       dateTimeString.replace( QRegExp("%H"), QString::number( time.hour() ) );
    }

    QString zone;
    int hour;
    if( time.hour() > 12 )
    {
       zone="PM";
       hour=time.hour()-12;
    }
    else
    {
       zone="AM";
       hour=time.hour();
    }

    dateTimeString.replace( QRegExp("%I"), QString::number( hour ) );

    if(hour < 10)
    {
       dateTimeString.replace( QRegExp("%i"), "0"+QString::number( hour ) );
    }
    else
    {
       dateTimeString.replace( QRegExp("%i"), QString::number( hour ) );
    }

    dateTimeString.replace( QRegExp("%p"), zone );

    // minutes
    if(time.minute() < 10)
    {
       dateTimeString.replace( QRegExp("%M"), "0"+QString::number( time.minute() ) );
    }
    else
    {
       dateTimeString.replace( QRegExp("%M"), QString::number( time.minute() ) );
    }

    // seconds
    if(time.second() < 10)
    {
       dateTimeString.replace( QRegExp("%S"), "0"+QString::number( time.second() ) );
    }
    else
    {
       dateTimeString.replace( QRegExp("%S"), QString::number( time.second() ) );
    }

    // timezone
    dateTimeString.replace( QRegExp("%Z"), _identitySettings.timeZone );
    QTime t;
    int sgn = KRFCDate::localUTCOffset() < 0 ? -1 : 1 ; 
    t = t.addSecs( sgn*KRFCDate::localUTCOffset()*60 );
    dateTimeString.replace( QRegExp("%z"), (sgn<0 ? "-" : "+") +t.toString("hhmm"));

    return dateTimeString;
}


Catalog::IOStatus Catalog::readHeader(QTextStream& stream, CatalogItem& header)
{
   CatalogItem temp;
   int filePos=stream.device()->at();
   CatalogItem::IOStatus status=temp.read(stream);

   if(status==CatalogItem::Ok || status==CatalogItem::RecoveredParseError)
   {
      // test if this is the header
      if(temp.msgid().isEmpty())
      {
          header=temp;
          if(header.isFuzzy())
          {
             header.removeFuzzy();
          }
      }
      else
      {
         stream.device()->at(filePos);
      }

      if(status==CatalogItem::RecoveredParseError)
      	return RECOVERED_PARSE_ERROR;
      else
	      return OK;
   }

   return PARSE_ERROR;

}

Catalog::IOStatus Catalog::openFile(QString filename, bool& errorInHeader)
{
	errorInHeader=false;

   if ( filename.isEmpty() )
    kdDebug() << "fatal error: empty filename to open" << endl;

   QFileInfo info(filename);

   if(!info.exists() || info.isDir())
      return NO_FILE;

   if(!info.isReadable())
      return NO_PERMISSIONS;

   QFile file(filename);


   bool recoveredError=false;
   	
   if(file.open(IO_ReadOnly))
   {
	  uint oldPercent = 0;
      emit signalResetProgressBar(i18n("loading file"),100);
      
      QByteArray ba = file.readAll();
      
      // find codec for file
	  bool hadCodec;
      QTextCodec* codec=codecForFile(file,&hadCodec);

      file.close();

      QTextStream stream(ba,IO_ReadOnly);
      if(codec)
          stream.setCodec(codec);
      QIODevice *dev = stream.device();
	  int fileSize = dev->size();

      // if somethings goes wrong with the parsing, we don't have deleted the old contents
      QValueList<CatalogItem> tempEntries;
      CatalogItem tempHeader;
      QValueList<QString> tempObsolete;


      kdDebug(KBABEL) << "start parsing..." << endl;

      // first read header
      IOStatus status = readHeader(stream,tempHeader);
      if(status == RECOVERED_PARSE_ERROR) {
      	errorInHeader=true;
      }
      else if(status!=OK)
      {
          emit signalClearProgressBar();

          return status;
      }

      // now parse the rest of the file
      CatalogItem tempCatItem;
      CatalogItem::IOStatus success=CatalogItem::Ok;
      uint counter=0;
      QValueList<uint> errorIndex;

      while(!stream.eof() && success==CatalogItem::Ok )
      {
         kapp->processEvents(10);

         success=tempCatItem.read(stream);

         if(success==CatalogItem::Ok)
         {
            // add new entry to the list of entries
            tempEntries.append(tempCatItem);
            tempCatItem.clear();
         }
         else if(success==CatalogItem::RecoveredParseError)
         {
         	success=CatalogItem::Ok;
         	recoveredError=true;
         	errorIndex.append(counter);
         	
            // add new entry to the list of entries
            tempEntries.append(tempCatItem);
            tempCatItem.clear();
         }
	 
	 if( success==CatalogItem::Obsolete )
	 {
	    success=CatalogItem::Ok;
	    kdDebug() << "Obsolete added: " << tempCatItem.comment() << endl;
	    tempObsolete.append(tempCatItem.comment());
	 }
	 else counter++;

         if((100*dev->at())/fileSize > oldPercent)
		 {
			oldPercent = (100*dev->at())/fileSize;
            emit signalProgress(oldPercent);
		 }
      }


      // to be sure it is set to 100, if someone don't connect to
      // signalClearProgressBar()
      emit signalProgress(100);

      emit signalClearProgressBar();

      kdDebug(KBABEL) << "ready." << endl;


      if(success!=CatalogItem::ParseError)
      {
         clear();

         // check if file is readOnly
         QFileInfo fi(file);
         _readOnly=!fi.isWritable();

         _entries=tempEntries;
         _header=tempHeader;
         emit signalHeaderChanged();
	 
	 _obsolete=tempObsolete;

         generateIndexLists();
         _errorIndex=errorIndex;

         if(hadCodec)
            fileCodec=codec;
         else
            fileCodec=0;
      }
      else
      {
         return PARSE_ERROR;
      }
   }
   else
   {
      return NO_PERMISSIONS;
   }

   if(recoveredError)
   	return RECOVERED_PARSE_ERROR;

   return OK;
}

Catalog::IOStatus Catalog::saveFile()
{
   if(_url.isEmpty())
   {
      kdFatal(KBABEL) << "fatal error: empty filename" << endl;
      return NO_FILE;
   }

   return saveFileAs(_url,true);
}

Catalog::IOStatus Catalog::saveFileAs(const KURL &url, bool overwrite)
{
   IOStatus status=OK;

   bool newName=false;
   KURL targetURL=_url;

   if(url != _url)
   {
      newName = true;
      targetURL=url;
   }


   if(_saveSettings.autoUpdate)
   {
      _header=updatedHeader(_header);
      emit signalHeaderChanged();
   }


   if(targetURL.isLocalFile())
   {
      // test if the directory exists. If not, create it.
      QDir dir( targetURL.directory());
      
      QStringList dirList;
      while(!dir.exists() && !dir.dirName().isEmpty())
      {
         dirList.prepend(dir.dirName());
         dir.setPath(dir.path()+"/..");
      }
      for ( QStringList::Iterator it = dirList.begin(); it != dirList.end(); ++it )
      {
         if(!dir.mkdir(*it))
         {
            status=OS_ERROR;
            break;
         }
         dir.cd(*it);
      }
      
      if(status==OK)
      {
         status=writeFile(targetURL.path(0),overwrite);
      }
   }
   else
   {
      QString tempFile=kapp->tempSaveName(targetURL.path(0));

      status = writeFile(tempFile,overwrite);

      if(status == OK)
      {
         KURL temp(tempFile);
         if( !KIO::NetAccess::upload( temp.url(), targetURL.url() ) )
         {
            status = OS_ERROR;
         }
      }

      QFile::remove(tempFile);
   }

   if(status == OK)
   {
      setModified(false);

      if(newName)
      {
         // if we saved a file, the catalog can not be any longer readOnly;
         _readOnly=false;

         _url=targetURL;

         emit signalFileOpened(_readOnly);
      }
   }

   return status;
}

QString Catalog::saveTempFile()
{
   QString filename = kapp->tempSaveName("/temp/kbabel_temp.po");
   if( writeFile(filename) != OK )
   {
      filename = QString::null;
   }

   return filename;
}


Catalog::IOStatus Catalog::writeFile(QString localFile , bool overwrite)
{
   QFileInfo info(localFile);

   if(info.isDir())
      return NO_FILE;

   if(info.exists())
   {
      if(!overwrite || !info.isWritable())
      {
         return NO_PERMISSIONS;
      }
   }
   else // check if the directory is writable
   {
      QFileInfo dir(info.dirPath());
      if(!dir.isWritable())
      {
         return NO_PERMISSIONS;
      }
   }

   QFile file(localFile);

   if(file.open(IO_WriteOnly))
   {
      int progressRatio = QMAX(100/numberOfEntries(), 1);
      emit signalResetProgressBar(i18n("saving file"),100);

      QTextStream stream(&file);
	  if(_saveSettings.useOldEncoding && fileCodec)
	  {
		   stream.setCodec(fileCodec);
	  }
      else
      {
         switch(_saveSettings.encoding)
         {
            case UTF8:
	       fileCodec = QTextCodec::codecForName("utf-8");
               stream.setCodec(fileCodec);
               break;
            case UTF16:
	       fileCodec = QTextCodec::codecForName("utf-16");
               stream.setEncoding(QTextStream::Unicode);
               break;
            default:
	       fileCodec = QTextCodec::codecForLocale();
               break;
         }
      }

      // only save header if it is not empty
      if(!_header.comment().isEmpty() || !_header.msgstr().isEmpty())
      {
         _header.write(stream);
         stream << "\n";
      }

      QValueList<CatalogItem>::ConstIterator it;

      int counter=1;
      QStringList list;
      for( it = _entries.begin(); it != _entries.end(); ++it )
      {
          if(counter%10==0) {
             emit signalProgress(counter/progressRatio);
	  }
	  
          counter++;

          (*it).write(stream);
          stream << "\n";

	 kapp->processEvents(10);
      }

      QValueList<QString>::ConstIterator oit;

      for( oit = _obsolete.begin(); oit != _obsolete.end(); ++oit )
      {
          stream << (*oit) << "\n\n";

	 kapp->processEvents(10);
      }
      emit signalProgress(100);
      file.close();

      emit signalClearProgressBar();
   }
   else
   {
      //emit signalError(i18n("Wasn't able to open file %1").arg(filename.ascii()));
      return OS_ERROR;
   }

   return OK;
}

QTextCodec* Catalog::codecForFile(QFile& file, bool* hadCodec)
{
   bool wasOpen=true;
   int fileIndex=0;
   
   if(hadCodec)
   {
      *hadCodec=false;
   }

   if(!file.isOpen())
   {
      wasOpen=false;

      if(!file.open(IO_ReadOnly))
      {
         kdDebug(KBABEL) << "wasn't able to open file" << endl;
         return 0;
      }
   }
   else
   {
      fileIndex=file.at();
		file.at(0);
   }

   QTextStream stream(&file);
   CatalogItem tempHeader;

   // first read header
   IOStatus status = readHeader(stream,tempHeader);
   if(status!=OK && status != RECOVERED_PARSE_ERROR)
   {
       kdDebug(KBABEL) << "wasn't able to read header" << endl;
       if(!wasOpen)
          file.close();
       return 0;
   }

   QString charset;

   QString head = tempHeader.msgstr();

   QRegExp r("Content-Type:\\s*\\w+/[-\\w]+;\\s*charset\\s*=\\s*[^\\\"\\n]+");
   int begin=r.search(head);
   int len=r.matchedLength();
   if(begin<0) {
   	kdDebug() << "no charset entry found" << endl;
   	return 0;
   }	
   	
   head = head.mid(begin,len);

   QRegExp regexp("charset *= *([^\\\\\\\"]+)");
   if( regexp.search( head ) > -1 )
   {
       charset = regexp.cap(1);
       kdDebug(KBABEL) << QString("charset: ")+charset << " for " << file.name() << endl;
   }

   QTextCodec* codec=0;

   if(!charset.isEmpty())
   {
      // "CHARSET" is the default charset entry in a template (pot).
      // characters in a template should be either pure ascii or 
      // at least utf8, so utf8-codec can be used for both.
      if( charset == "CHARSET")
      {
          if(hadCodec)
             *hadCodec=false;

          codec=QTextCodec::codecForName("utf8");
          kdDebug(KBABEL) 
              << QString("file seems to be a template: using utf8 encoding.")
              << endl;
      }
      else
      {
         codec=QTextCodec::codecForName(charset.latin1());
         if(hadCodec)
            *hadCodec=true;
      }

      if(!codec)
      {
         kdWarning() << "charset found, but no codec available, using UTF8 instead" << endl;
	 codec=QTextCodec::codecForName("utf8");
      }
   }

   if(!wasOpen)
   {
       file.close();
   }
   else
   {
       file.at(fileIndex);
   }

   return codec;
}

PoInfo Catalog::headerInfo(const CatalogItem headerItem)
{
   QStringList header=headerItem.msgstrAsList();

   QStringList::Iterator it;

   PoInfo info;

   // extract information from the header
   for(it=header.begin();it!=header.end();++it)
   {
      if((*it).contains(QRegExp("^\\s*Project-Id-Version\\s*:\\s*.+\\s*$")))
      {
         info.project=(*it).replace(QRegExp("^\\s*Project-Id-Version\\s*:\\s*"),"");

         if(info.project.right(2)=="\\n")
            info.project.remove(info.project.length()-2,2);
         
         info.project=info.project.simplifyWhiteSpace();
      }
      else if((*it).contains(QRegExp("^\\s*POT-Creation-Date\\s*:\\s*.+\\s*$")))
      {
         info.creation=(*it).replace(QRegExp("^\\s*POT-Creation-Date\\s*:\\s*"),"");

         if(info.creation.right(2)=="\\n")
            info.creation.remove(info.creation.length()-2,2);

         info.creation=info.creation.simplifyWhiteSpace();
      }
      else if((*it).contains(QRegExp("^\\s*PO-Revision-Date\\s*:\\s*.+\\s*$")))
      {
         info.revision=(*it).replace(QRegExp("^\\s*PO-Revision-Date\\s*:\\s*"),"");

         if(info.revision.right(2)=="\\n")
            info.revision.remove(info.revision.length()-2,2);

         info.revision=info.revision.simplifyWhiteSpace();
      }
      else if((*it).contains(QRegExp("^\\s*Last-Translator\\s*:\\s*.+\\s*$")))
      {
         info.lastTranslator=(*it).replace(QRegExp("^\\s*Last-Translator\\s*:\\s*"),"");

         if(info.lastTranslator.right(2)=="\\n")
            info.lastTranslator.remove(info.lastTranslator.length()-2,2);

         info.lastTranslator=info.lastTranslator.simplifyWhiteSpace();
      }
      else if((*it).contains(QRegExp("^\\s*Language-Team\\s*:\\s*.+\\s*")))
      {
         info.languageTeam=(*it).replace(QRegExp("^\\s*Language-Team\\s*:\\s*"),"");

         if(info.languageTeam.right(2)=="\\n")
            info.languageTeam.remove(info.languageTeam.length()-2,2);

         info.languageTeam=info.languageTeam.simplifyWhiteSpace();
      }
      else if((*it).contains(QRegExp("^\\s*MIME-Version\\s*:\\s*.+\\s*")))
      {
         info.mimeVersion=(*it).replace(QRegExp("^\\s*MIME-Version\\s*:\\s*"),"");

         if(info.mimeVersion.right(2)=="\\n")
            info.mimeVersion.remove(info.mimeVersion.length()-2,2);

         info.mimeVersion=info.mimeVersion.simplifyWhiteSpace();
      }
      else if((*it).contains(QRegExp("^\\s*Content-Type\\s*:\\s*.+\\s*")))
      {
         info.contentType=(*it).replace(QRegExp("^\\s*Content-Type\\s*:\\s*"),"");

         if(info.contentType.right(2)=="\\n")
            info.contentType.remove(info.contentType.length()-2,2);

         info.contentType=info.contentType.simplifyWhiteSpace();
      }
      else if((*it).contains(QRegExp("^\\s*Content-Transfer-Encoding\\s*:\\s*.+\\s*")))
      {
         info.encoding=(*it).replace(QRegExp("^\\s*Content-Transfer-Encoding\\s*:\\s*"),"");

         if(info.encoding.right(2)=="\\n")
            info.encoding.remove(info.encoding.length()-2,2);

         info.encoding=info.encoding.simplifyWhiteSpace();
      }
      else
      {
          QString line=(*it);

         if(line.right(2)=="\\n")
            line.remove(line.length()-2,2);

         line=line.simplifyWhiteSpace();
         if(!info.others.isEmpty())
             info.others+='\n';

         info.others+=line;
      }


   }

   info.headerComment=headerItem.comment();

   return info;
}


Catalog::IOStatus Catalog::info(const QString url, PoInfo& info, QStringList &wordList, bool updateWordList)
{
   stopStaticRead = false;
   QString target;
   if(KIO::NetAccess::download(url, target))
   {
       QFile file(target);

	   // first check file with msgfmt to be sure, it is 
	   // syntactically correct
	   Msgfmt msgfmt;
	   QString output;
	   Msgfmt::Status stat = msgfmt.checkSyntax( target , output );
	   if(stat == Msgfmt::SyntaxError)
	   {
          KIO::NetAccess::removeTempFile(target);
		  return PARSE_ERROR;
	   }


       if(file.open(IO_ReadOnly))
       {
           CatalogItem temp;

           QTextCodec *codec = codecForFile(file);

           file.close();
	   
           info.total=0;
           info.fuzzy=0;
           info.untranslated=0;
	   
	   if( !codec ) return PARSE_ERROR;
	   
	   std::ifstream* stream = new std::ifstream( file.name().local8Bit());
	   FlexLexer* lexer = new yyFlexLexer( stream  );

	   lexer->yylex();
	   
           // now parse the rest of the file
           CatalogItem::IOStatus success=CatalogItem::Ok;
	   
           while( lastToken != T_EOF && success==CatalogItem::Ok)
           {
	       int save = lastToken;
               kapp->processEvents(10);
	       lastToken = save;
	       
	       if( stopStaticRead )
	       {
	    	    delete lexer;
		    delete stream;
		    return OK;
		}
	       
	       success=temp.fastRead(lexer, codec, updateWordList );
	       
               if(success==CatalogItem::Ok || success==CatalogItem::RecoveredParseError)
               {
		  success=CatalogItem::Ok;

                  if( temp.msgid().isEmpty() ) //header
		  {
		      if( temp.isFuzzy() )  temp.removeFuzzy();
		      
		      PoInfo infoCounts = info;
		      info=Catalog::headerInfo(temp);
		      info.total = infoCounts.total;
		      info.fuzzy = infoCounts.fuzzy;
		      info.untranslated = infoCounts.untranslated;
		      continue; // do not update counters and word list for header
		  }
		  		  
                  info.total++;

                  if(temp.isFuzzy())
                     info.fuzzy++;
                  else if(temp.isUntranslated())
                     info.untranslated++;
		     
		  if( updateWordList )
		  {
		    QString st = temp.msgid().simplifyWhiteSpace().lower();
		    QStringList sl = QStringList::split( ' ', st );
		    while(!sl.isEmpty())
		    {
			QString w = sl.first();
			sl.pop_front();
			if( !wordList.contains(w) ) wordList.append( w );
		    }
		    st = temp.msgstr().simplifyWhiteSpace().lower();
		    sl = QStringList::split( ' ', st );
		    while(!sl.isEmpty())
		    {
			QString w = sl.first();
			sl.pop_front();
			if( !wordList.contains(w) ) wordList.append( w );
		    }
		    st = temp.comment().simplifyWhiteSpace().lower();
		    sl = QStringList::split( ' ', st );
		    while(!sl.isEmpty())
		    {
			QString w = sl.first();
			sl.pop_front();
			if( !wordList.contains(w) ) wordList.append( w );
		    }
                }
	      }
           }

	   delete lexer;
	   delete stream;

           if(success==CatalogItem::ParseError)
           {
	       KIO::NetAccess::removeTempFile(target);
               return PARSE_ERROR;
           }
       }
       else
       {
          KIO::NetAccess::removeTempFile(target);
          return NO_PERMISSIONS;
       }

	KIO::NetAccess::removeTempFile(target);
        return OK;
   }
   else
   {
      return OS_ERROR;
   }

   return OK;
}

bool Catalog::findInFile( const QString url, FindOptions options )
{
   enum {Begin, Comment, Msgid, Msgstr} part = Begin;
   
   stopStaticRead = false;
   QString target;
   if(KIO::NetAccess::download(url, target))
   {
       QFile file(target);

       if(file.open(IO_ReadOnly))
       {
           QTextCodec *codec = codecForFile(file);

           file.close();
           KIO::NetAccess::removeTempFile(target);
	   
	   if( !codec ) return false;
	   
	   std::ifstream* stream = new std::ifstream( file.name().local8Bit()); 
	   FlexLexer* lexer = new yyFlexLexer( stream );

	   lexer->yylex();

           // prepare the search
	   
	   QString searchStr = options.findStr;
	   QRegExp regexp( searchStr );
	   
	   if( options.isRegExp ) 
		regexp.setCaseSensitive( options.caseSensitive );

           // first read header
	   CatalogItem temp;
	   
	   CatalogItem::IOStatus status = temp.fastRead( lexer, codec );
	   if( status != CatalogItem::Ok || !temp.msgid().isEmpty() ) 
	   {
		delete lexer;
		delete stream;
		return false; // header is not at the beginning, broken file
	   }
	   
	   // now parse the rest of the file
	   QString text;
	   int pos,len;
	   
           while(lastToken != T_EOF)
           {
	       switch( lastToken ) {
	           case T_COMMENT: {
			part = Comment;
			if( !options.inComment ) break;
			text = codec->toUnicode(lexer->YYText()); 
			if( options.isRegExp )
			    pos=regexp.search(text, 0 );
			else 
			    pos=text.find(searchStr,0,options.caseSensitive);
			if( pos >= 0)
			{
			    if( options.wholeWords) {
				len = searchStr.length();
				QString pre = text.mid(pos-1,1);
				QString post = text.mid(pos+len,1);
				if( !pre.contains( QRegExp("[a-zA-Z0-9]")) &&
				    !post.contains( QRegExp("[a-zA-Z0-9]") )
				) {
				    delete lexer;
				    delete stream;
				    return true;
				}
			    }
			    else {
				delete lexer;
				delete stream;
				return true;
			    };
			}
			break;
		   }
		   case T_STRING: {
			if( part == Msgid && !options.inMsgid ) break;
			if( part == Msgstr && !options.inMsgstr ) break;
			
			text = codec->toUnicode(lexer->YYText()); 
			if( options.ignoreContextInfo )
			{
			    pos = options.contextInfo.search(text);
			    len = options.contextInfo.matchedLength();
			    if( pos >= 0 )
		    		text.remove( pos, len );
			}
		    
			if( options.ignoreAccelMarker )
			{
			    pos = text.find( options.accelMarker );
			    if( pos >= 0 )
				text.remove( pos, 1 );
			}
			
			if( options.isRegExp )
			    pos=regexp.search(text, 0 );
			else 
			    pos=text.find(searchStr,0,options.caseSensitive);

			if( pos >= 0)
			{
			    if( options.wholeWords) {
				len = searchStr.length();
				QString pre = text.mid(pos-1,1);
				QString post = text.mid(pos+len,1);
				if( !pre.contains( QRegExp("[a-zA-Z0-9]")) &&
				    !post.contains( QRegExp("[a-zA-Z0-9]") )
				) {
				    delete lexer;
				    delete stream;
				    return true;
				}
			    }
			    else {
				delete lexer;
				delete stream;
				return true;
			    };
			}
			break;
		   }
		   case T_MSGSTR: {
			part = Msgstr;
			break;
		   }
		   case T_MSGID: 
		   case T_MSGIDPLURAL: {
	    		kapp->processEvents(10);
			
			// if stopped, return not found
			if( stopStaticRead ) 
			{
			    delete lexer;
			    delete stream;
			    return false;
			}
			part = Msgid;
			break;
		   }
	       }
	       lexer->yylex();
           }
	   delete lexer;
	   delete stream;
       }
    }
    return false;
}

bool Catalog::isUndoAvailable()
{
   return !_undoList.isEmpty();
}

bool Catalog::isRedoAvailable()
{
   return !_redoList.isEmpty();
}

int Catalog::undo()
{
   if(!isUndoAvailable())
      return -1;

   int macroLevel = 0;

   EditCommand *command=0;
   do
   {
      command = _undoList.take();
      if ( !command )
      {
         kdError() << "undo command is NULL?" << endl;
         return -1;
      }

      processCommand( command, 0, true );

      macroLevel += command->terminator();

      if ( _undoList.isEmpty() )
      {
         emit signalUndoAvailable( false );
      }
      if(_redoList.isEmpty())
      {
         emit signalRedoAvailable(true);
      }
      _redoList.append(command);

    }
    while(macroLevel != 0);

    return command->index();
}

int Catalog::redo()
{
   if(!isRedoAvailable())
      return -1;

   int macroLevel = 0;
   EditCommand *command=0;

   do
   {
      command = _redoList.take();
      if ( !command )
      {
         kdError() << "undo command is NULL?" << endl;
         return -1;
      }

      processCommand( command, 0,false );

      macroLevel += command->terminator();
      if ( _redoList.isEmpty() )
      {
         emit signalRedoAvailable( false );
      }
      if ( _undoList.isEmpty() )
      {
         emit signalUndoAvailable( true );
      }

      _undoList.append( command );
    }
    while (macroLevel != 0);

    return command->index();
}

void Catalog::applyEditCommand(EditCommand* cmd, CatalogView* view)
{

    processCommand(cmd,view);
    setModified(true);

    if ( _undoList.isEmpty() )
    {
       emit signalUndoAvailable(true);	
    }
    else if ( cmd->merge( _undoList.last() ) )
    {
       delete cmd;
       return;
    }


    if ( UNDODEPTH > 0 && _undoList.count() >= UNDODEPTH )
    {
       _undoList.removeFirst();
    }

    _undoList.append(cmd);


    if ( !_redoList.isEmpty() )
    {
       _redoList.clear();
       emit signalRedoAvailable( false );
    }

}

void Catalog::processCommand(EditCommand* cmd,CatalogView* view, bool undo)
{
    if(cmd->terminator()==0)
    {
       bool checkUntranslated=false;
       bool checkFuzzy=false;
       bool wasFuzzy=false;
       
       CatalogItem &item=_entries[cmd->index()];

       if(cmd->part() == EditCommand::Msgstr)
       {
          if( item.isUntranslated() )
          {
             _untransIndex.remove(cmd->index());

             emit signalNumberOfUntranslatedChanged(numberOfUntranslated());
          }
          else
          {
             checkUntranslated=true;
          }
       }
       else if(cmd->part() == EditCommand::Comment)
       {
          checkFuzzy=true;
          wasFuzzy=item.isFuzzy();
       }



       item.processCommand(cmd,undo);

       if(undo)
       {
          EditCommand* tmpCmd=0;
          DelTextCmd* delcmd = (DelTextCmd*) cmd;
          if (delcmd->type() == EditCommand::Delete )
          {
             tmpCmd = new InsTextCmd(delcmd->offset,delcmd->str);
          }
          else
          {
             tmpCmd = new DelTextCmd(delcmd->offset,delcmd->str);
          }

          tmpCmd->setIndex(cmd->index());
          tmpCmd->setPart(cmd->part());

          updateViews(tmpCmd,view);

          delete tmpCmd;
       }
       else
       {
          updateViews(cmd,view);
       }
       
       if(checkUntranslated && item.isUntranslated())
       {
          QValueList<uint>::Iterator it;

          // insert index in the right place in the list
          it = _untransIndex.begin();
          while(it != _untransIndex.end() && cmd->index() > (int)(*it))
          {
             ++it;
          }
          _untransIndex.insert( it,(uint)(cmd->index()) );
	  
          emit signalNumberOfUntranslatedChanged(numberOfUntranslated());
       }
       else if(checkFuzzy)
       {
          if(wasFuzzy != item.isFuzzy())
          {
             if(wasFuzzy)
             {
                _fuzzyIndex.remove(cmd->index());
                emit signalNumberOfFuzziesChanged(numberOfFuzzies());
             }
             else
             {
                QValueList<uint>::Iterator it;

                // insert index in the right place in the list
                it = _fuzzyIndex.begin();
                while(it != _fuzzyIndex.end() && cmd->index() > (int)(*it))
                {
                   ++it;
                }
                _fuzzyIndex.insert( it,(uint)(cmd->index()) );

                emit signalNumberOfFuzziesChanged(numberOfFuzzies());
             }
          }
       }

    }
}

bool Catalog::findNext(const FindOptions* findOpts, DocPosition& docPos, int& len)
{
	bool success = false; // true, when string found
	bool endReached=false;
	
	len=0;
	int pos=0;
		
	QString searchStr = findOpts->findStr;	
	QRegExp regexp(searchStr);
	
	if( findOpts->isRegExp ) {
		regexp.setCaseSensitive(findOpts->caseSensitive);
	}
		
	if( docPos.item == numberOfEntries()-1) {
		switch(docPos.part) {
			case Msgid:
				if(!findOpts->inMsgstr && !findOpts->inComment
					&& docPos.offset >= msgid(docPos.item).length() ) {
					endReached=true;
				}
				break;
			case Msgstr:
				if(!findOpts->inComment && docPos.offset >= msgstr(docPos.item).length() ) {
					endReached=true;
				}
				break;
			case Comment:
				if(docPos.offset >= comment(docPos.item).length() ) {
					endReached=true;
				}
				break;
		}
	}
	
	while(!success) {
        int accelMarkerPos = -1;
        int contextInfoLength = 0;
        int contextInfoPos = -1;
		QString targetStr;
		
		kapp->processEvents(10);
		
		if(endReached) {
			return false;
		}
		
		switch(docPos.part) {
			case Msgid:
				targetStr = msgid(docPos.item);
				break;
			case Msgstr:
				targetStr = msgstr(docPos.item);
				break;
			case Comment:
				targetStr = comment(docPos.item);
				break;
		}

        if(findOpts->ignoreContextInfo)
        {
            contextInfoPos = _miscSettings.contextInfo.search(targetStr);
	    contextInfoLength = _miscSettings.contextInfo.matchedLength();
            if(contextInfoPos >= 0)
            {
                targetStr.remove(contextInfoPos,contextInfoLength);
                
                if(docPos.offset > (uint)contextInfoPos)
                    docPos.offset -= contextInfoLength;
            }
        }

        if(findOpts->ignoreAccelMarker 
                && targetStr.contains(_miscSettings.accelMarker))
        {
            accelMarkerPos = targetStr.find(_miscSettings.accelMarker);
            targetStr.remove(accelMarkerPos,1);

            if(docPos.offset > (uint)accelMarkerPos)
                docPos.offset--;
        }
		
		if( findOpts->isRegExp ) {
			if ((pos=regexp.search(targetStr,docPos.offset)) >= 0 ) {
			    len = regexp.matchedLength();
				if(findOpts->wholeWords) {
					QString pre=targetStr.mid(pos-1,1);
					QString post=targetStr.mid(pos+len,1);
					if(!pre.contains(QRegExp("[a-zA-Z0-9]")) && !post.contains(QRegExp("[a-zA-Z0-9]")) ){
						success=true;
						docPos.offset=pos;
					}
				}
				else {	
					success=true;
					docPos.offset=pos;
				}
			}
		}
		else {
			if( (pos=targetStr.find(searchStr,docPos.offset,findOpts->caseSensitive)) >= 0 ) {
				len=searchStr.length();
				
				if(findOpts->wholeWords) {
					QString pre=targetStr.mid(pos-1,1);
					QString post=targetStr.mid(pos+len,1);
					if(!pre.contains(QRegExp("[a-zA-Z0-9]")) && !post.contains(QRegExp("[a-zA-Z0-9]")) ){
						success=true;
						docPos.offset=pos;
					}
				}
				else {	
					success=true;
					docPos.offset=pos;
				}
			}
		}
		
		
		if(!success) {					
			docPos.offset=0;
			switch(docPos.part) {
				case Msgid:
				{
					if(findOpts->inMsgstr) {
						docPos.part = Msgstr;
					}
					else if(findOpts->inComment) {
						docPos.part = Comment;
					}
					else
					{
						if(docPos.item >= numberOfEntries()-1)
						{
							endReached=true;
						}
						else
						{
							docPos.item++;
						}
					}
					break;
				}
				case Msgstr:
					if(findOpts->inComment) {
						docPos.part = Comment;
					}
					else if(findOpts->inMsgid) {
						if(docPos.item >= numberOfEntries()-1)
						{
							endReached=true;
						}
						else
						{
							docPos.part = Msgid;
							docPos.item++;
						}
					}
					else {
						if(docPos.item >= numberOfEntries()-1)
						{
							endReached=true;
						}
						else
						{
							docPos.item++;
						}
					}
					break;
				case Comment:
					if(findOpts->inMsgid) {
						if(docPos.item >= numberOfEntries()-1)
						{
							endReached=true;
						}
						else
						{
							docPos.part = Msgid;
							docPos.item++;
						}
					}
					else if(findOpts->inMsgstr){
						if(docPos.item >= numberOfEntries()-1)
						{
							endReached=true;
						}
						else
						{
							docPos.part = Msgstr;
							docPos.item++;
						}
					}
					else {
						if(docPos.item >= numberOfEntries()-1)
						{
							endReached=true;
						}
						else
						{
							docPos.item++;
						}
					}
					break;
			}
		}
        else
        {
            if(accelMarkerPos >= 0)
            {
                if(docPos.offset >= (uint)accelMarkerPos)
                {
                    docPos.offset++;
                }
                else if(docPos.offset+len > (uint)accelMarkerPos)
                {
                    len++;
                }
            }

            if(contextInfoPos >= 0)
            {
                if(docPos.offset >= (uint)contextInfoPos)
                {
                    docPos.offset+=contextInfoLength;
                }
                else if(docPos.offset+len > (uint)contextInfoPos)
                {
                    len+=contextInfoLength;
                }

            }
        }
	}	
	
	
	return true;
}

bool Catalog::findPrev(const FindOptions* findOpts, DocPosition& docPos, int& len)
{
	bool success = false;  // true, when found
	bool beginReached = false;
	
	len=0;
	int pos=0;
	
	QString searchStr = findOpts->findStr;	
	QRegExp regexp(searchStr);
	
	if( findOpts->isRegExp ) {
		regexp.setCaseSensitive(findOpts->caseSensitive);
	}
	while(!success) {
        int accelMarkerPos = -1;
        int contextInfoLength = 0;
        int contextInfoPos = -1;
		QString targetStr;
		
		kapp->processEvents(10);
		
		if(beginReached) {
			return false;				
		}
		
		switch(docPos.part) {
			case Msgid:
				targetStr = msgid(docPos.item);
				break;
			case Msgstr:
				targetStr = msgstr(docPos.item);
				break;
			case Comment:
				targetStr = comment(docPos.item);
				break;
		}
		
        if(findOpts->ignoreContextInfo)
        {
            contextInfoPos = _miscSettings.contextInfo.search(targetStr);
	    contextInfoLength = _miscSettings.contextInfo.matchedLength();
            if(contextInfoPos >= 0)
            {
                targetStr.remove(contextInfoPos,contextInfoLength);

                if(docPos.offset > (uint)contextInfoPos)
                    docPos.offset -= contextInfoLength;
            }
        }

        if(findOpts->ignoreAccelMarker 
                && targetStr.contains(_miscSettings.accelMarker))
        {
            accelMarkerPos = targetStr.find(_miscSettings.accelMarker);
            targetStr.remove(accelMarkerPos,1);

            if(docPos.offset > (uint)accelMarkerPos)
                docPos.offset--;
        }

		if(docPos.offset <= 0) {
			success=false;
		}	
		else if( findOpts->isRegExp ) {
			/*
			don't work!?
			if((pos=targetStr.findRev(regexp,docPos.offset)) >= 0 ) {
				regexp.match(targetStr,pos,&len); // to get the length of the string
			*/
			bool found=false;
			int tmpPos=docPos.offset;
			while(!found && tmpPos>=0)
			{
				if( (pos=regexp.search(targetStr,tmpPos)) >= 0 && (uint)pos < docPos.offset)
					found=true;
				else
					tmpPos--;
				len = regexp.matchedLength();
			}		
			if(found) {
				if(findOpts->wholeWords) {
					QString pre=targetStr.mid(pos-1,1);
					QString post=targetStr.mid(pos+len,1);
					if(!pre.contains(QRegExp("[a-zA-Z0-9]")) && !post.contains(QRegExp("[a-zA-Z0-9]")) ){
						success=true;
						docPos.offset=pos;
					}
				}
				else {	
					success=true;
					docPos.offset=pos;
				}
			}
		}
		else if( (pos=targetStr.findRev(searchStr,docPos.offset-1,findOpts->caseSensitive)) >= 0
		          && (uint)pos < docPos.offset) {
			len=searchStr.length();
			if(findOpts->wholeWords) {
				QString pre=targetStr.mid(pos-1,1);
				QString post=targetStr.mid(pos+len,1);
				if(!pre.contains(QRegExp("[a-zA-Z0-9]")) && !post.contains(QRegExp("[a-zA-Z0-9]")) ){
					success=true;
					docPos.offset=pos;
				}
			}
			else {	
				success=true;
				docPos.offset=pos;
			}			
		}
			
		if(!success) {	
			switch(docPos.part) {
				case Comment:
				{
					if(findOpts->inMsgstr) {
						docPos.part = Msgstr;
						docPos.offset = msgstr(docPos.item).length();
					}
					else if(findOpts->inMsgid) {
						docPos.part = Msgid;
						docPos.offset = msgid(docPos.item).length();
					}
					else
					{
						if(docPos.item <= 0)
						{
							beginReached=true;
						}
						else
						{
							docPos.item--;
							docPos.offset = comment(docPos.item).length();
						}
					}
					break;
				}
				case Msgstr:
					if(findOpts->inMsgid) {
						docPos.part = Msgid;
						docPos.offset = msgid(docPos.item).length();
					}
					else if(findOpts->inComment) {
						if(docPos.item <= 0)
						{
							beginReached=true;
						}
						else
						{
							docPos.part = Comment;
							docPos.item--;
							docPos.offset = comment(docPos.item).length();
						}
					}
					else {
						if(docPos.item <= 0)
						{
							beginReached=true;
						}
						else
						{
							docPos.item--;
							docPos.offset = msgstr(docPos.item).length();
						}
					}
					break;
				case Msgid:
					if(findOpts->inComment) {
						if(docPos.item <= 0 )
						{
							beginReached=true;
						}
						else
						{
							docPos.part = Comment;
							docPos.item--;
							docPos.offset = comment(docPos.item).length();
						}
					}
					else if(findOpts->inMsgstr){
						if(docPos.item <= 0)
						{
							beginReached=true;
						}
						else
						{
							docPos.part = Msgstr;
							docPos.item--;
							docPos.offset = msgstr(docPos.item).length();
						}
					}
					else {
						if(docPos.item <= 0)
						{
							beginReached=true;
						}
						else
						{
							docPos.item--;
							docPos.offset = msgid(docPos.item).length();
						}
					}
					break;
			}
		}
        else
        {
            if(accelMarkerPos >= 0)
            {
                if(docPos.offset >= (uint)accelMarkerPos)
                {
                    docPos.offset++;
                }
                else if(docPos.offset+len > (uint)accelMarkerPos)
                {
                    len++;
                }
            }

            if(contextInfoPos >= 0)
            {
                if(docPos.offset >= (uint)contextInfoPos)
                {
                    docPos.offset+=contextInfoLength;
                }
                else if(docPos.offset+len > (uint)contextInfoPos)
                {
                    len+=contextInfoLength;
                }

            }
        }
	}	
	
	return true;
}


Catalog::DiffResult Catalog::diff(uint entry, QString *result)
{
    if(!result)
    {
        kdWarning() << "0 pointer for result" << endl;
        return DiffNotFound;
    }

    if( msgidDiffList.isEmpty() )
    {
        return DiffNeedList;
    }

    // first look if the diff for this entry is in the cache
    QString *s = diffCache[entry];
    if(s)
    {
        if(s->isEmpty())
            return DiffNotFound;

        
        *result = *s;
        return DiffOk;
    }
    
    // then look if the same msgid is contained in the diff file
    QRegExp nlReg("\\n");
    QString id = msgid(entry);
    id.replace(nlReg,"");
    if(msgidDiffList.contains(id))
    {
        *result = msgid(entry);

        return DiffOk;
    }
    
    QString idForDiff;
    
    // then look if there are entries with the same translation
    QString str = msgstr(entry);
    str.replace(nlReg,"");
    if(msgstr2MsgidDiffList.contains(str))
    {
        QStringList list = msgstr2MsgidDiffList[str];
        
        if(list.count() == 1)
        {
            idForDiff = list.first();
        }
        else
        {
            // find the best matching id
            double bestWeight = 0.6;
            QString bestId;

            QStringList::ConstIterator it;
            for(it = list.begin(); it != list.end(); ++it)
            {
                double weight = fstrcmp( id.utf8(), (*it).utf8() );
                if(weight > bestWeight)
                {
                    bestWeight = weight;
                    bestId = (*it);
                }
            }

            if( !bestId.isEmpty() )
            {
                idForDiff = bestId;
            }
        }
    }
    else
    {
        emit signalResetProgressBar(i18n("searching matching message")
                ,100);
            
        // find the best matching id
        double bestWeight = 0.6;
        QString bestId;

        int counter=0;
        int oldPercent=0;
        int max = QMAX( msgidDiffList.count()-1, 1);
        
        QStringList::ConstIterator it;
        for(it = msgidDiffList.begin();
                it != msgidDiffList.end(); ++it)
        {
            counter++;
            int  percent = 100*counter/max;
            if(percent > oldPercent)
            {
                oldPercent = percent;
                emit signalProgress(percent);
            }
            
            double weight = fstrcmp( id.utf8(), (*it).utf8() );
            if(weight > bestWeight)
            {
                bestWeight = weight;
                bestId = (*it);
            }

            kapp->processEvents(10);
        }

        if( !bestId.isEmpty() )
        {
            idForDiff = bestId;
        }

        emit signalClearProgressBar();

    }

    if( idForDiff.isEmpty() )
    {
        s = new QString(*result);
        if( !diffCache.insert(entry,s) )
            delete s;

        return DiffNotFound;
    }

    QString r = Diff::charDiff(idForDiff,id);

    
    // restore the newlines
    QString orig = msgid(entry);
    if(orig.contains('\n'))
    {
        int pos=orig.find('\n');
        int oldPos=0;
        int rPos=0;
        int max = r.length();
        while(pos > 0)
        {
            int len = pos - oldPos;
            oldPos = pos+1;
            
            int p = 0;
            while(p < len && rPos < max)
            {
                QString m = r.mid(rPos,11);
                if(r[rPos]=='<' && m == "<KBABELDEL>")
                {
                    int endPos = r.find("</KBABELDEL>",rPos+11);
                    if(endPos > rPos)
                    {
                        rPos = endPos+12;
                    }
                    else
                    {
                        kdWarning(KBABEL) << "no closing diff remove tag found" 
                                          << endl;
                        rPos+=11;
                    }
                }
                else if(r[rPos] == '<' && m == "<KBABELADD>")
                {
                    rPos+=11;
                }
                else if(r[rPos] == '<' && m == "</KBABELADD")
                {
                    rPos+=12;
                }
                else
                {
                    rPos++;
                    p++;
                }
            }

            if(rPos < max)
            {
                r.insert(rPos,'\n');
                max++;
                rPos++;
            }

            
            pos = orig.find('\n',pos+1);
        }
    }

    
    int pos = r.find("\\n");
    while(pos >= 0 )
    {
        int slash=1;
        while(pos-slash >= 0 && r[pos-slash]=='\\')
        {
            slash++;
        }
        if(slash%2 == 1 && r[pos+2]!='\n')
        {
            r.insert(pos+2,'\n');
            pos+=3;
        }
        else
        {
            pos+=2;
        }

        pos = r.find("\\n",pos);
    }

    // add newlines if line has gotten to long;
    pos = r.find('\n');
    int oldPos=0;
    const int maxLength = 60;
    while(pos >= 0)
    {
        int length=pos-oldPos;
        QString tmp = r.mid(oldPos, pos-oldPos);
        if(!tmp.contains("KBABELDEL>") )
        {
            oldPos = pos;
            pos = r.find('\n',pos+1);
            continue;
        }
                
        int n = tmp.contains("<KBABELADD>");
        length -= n*11;
        n = tmp.contains("<KBABELDEL>");
        length -= n*11;
        n = tmp.contains("</KBABELADD>");
        length -= n*12;
        n = tmp.contains("</KBABELDEL>");
        length -= n*12;
        while(length > maxLength)
        {
            int counter=0;
            while(counter < maxLength-10 && oldPos < pos)
            {
                if(r[oldPos]=='<' && r.mid(oldPos,11)=="<KBABELADD>")
                {
                    oldPos+=11;
                }
                else if(r[oldPos]=='<' && r.mid(oldPos,11)=="<KBABELDEL>")
                {
                    oldPos+=11;
                }
                else if(r[oldPos]=='<' && r.mid(oldPos,12)=="</KBABELADD>")
                {
                    oldPos+=12;
                }
                else if(r[oldPos]=='<' && r.mid(oldPos,12)=="</KBABELDEL>")
                {
                    oldPos+=12;
                }
                else
                {
                    counter++;
                    oldPos++;
                }
            }
                
            while(oldPos < pos-5 && !r[oldPos].isSpace() )
            {
                oldPos++;
            }
            oldPos++;
            if(oldPos < pos-5)
            {
                r.insert(oldPos,'\n');
                pos++;
            }
            else
            {
                break;
            }
            
            length=pos-oldPos;
            QString tmp = r.mid(oldPos, pos-oldPos);
            n = tmp.contains("<KBABELADD>");
            length -= n*11;
            n = tmp.contains("<KBABELDEL>");
            length -= n*11;
            n = tmp.contains("</KBABELADD>");
            length -= n*12;
            n = tmp.contains("</KBABELDEL>");
            length -= n*12;
        }
            
        oldPos=pos;
        pos = r.find('\n',pos+1);
    }
    
    // now the last line
    pos = r.length();
    
    int length=pos-oldPos;
    QString tmp = r.mid(oldPos, pos-oldPos);
    int n = tmp.contains("<KBABELADD>");
    length -= n*11;
    n = tmp.contains("<KBABELDEL>");
    length -= n*11;
    n = tmp.contains("</KBABELADD>");
    length -= n*12;
    n = tmp.contains("</KBABELDEL>");
    length -= n*12;
    while(length > maxLength)
    {
        int counter=0;
        while(counter < maxLength-10 && oldPos < pos)
        {
            if(r[oldPos]=='<' && r.mid(oldPos,11)=="<KBABELADD>")
            {
                oldPos+=11;
            }
            else if(r[oldPos]=='<' && r.mid(oldPos,11)=="<KBABELDEL>")
            {
                oldPos+=11;
            }
            else if(r[oldPos]=='<' && r.mid(oldPos,12)=="</KBABELADD>")
            {
                oldPos+=12;
            }
            else if(r[oldPos]=='<' && r.mid(oldPos,12)=="</KBABELDEL>")
            {
                oldPos+=12;
            }
            else
            {
                counter++;
                oldPos++;
            }
        }
        
        while(oldPos < pos-5 && !r[oldPos].isSpace() )
        {
            oldPos++;
        }
        oldPos++;
        if(oldPos < pos-5)
        {
            r.insert(oldPos,'\n');
            pos++;
        }
        else
        {
            break;
        }
        
        length=pos-oldPos;
        QString tmp = r.mid(oldPos, pos-oldPos);
        n = tmp.contains("<KBABELADD>");
        length -= n*11;
        n = tmp.contains("<KBABELDEL>");
        length -= n*11;
        n = tmp.contains("</KBABELADD>");
        length -= n*12;
        n = tmp.contains("</KBABELDEL>");
        length -= n*12;
    }
    
    *result = r;
    
    s = new QString(*result);
    if( !diffCache.insert(entry,s) )
        delete s;
    
    return DiffOk;
}

void Catalog::setDiffList( const QValueList<DiffEntry>& list)
{
    emit signalResetProgressBar(i18n("preparing messages for diff"),100);

    msgidDiffList.clear();
    msgstr2MsgidDiffList.clear();
    diffCache.clear();

    uint max = QMAX(list.count()-1,1);
    int oldPercent=0;
    uint counter=0;
    QRegExp nlReg("\\n");
    QValueList<DiffEntry>::ConstIterator it;
    for(it = list.begin(); it != list.end(); ++it)
    {
        int percent = (100*counter)/max;
        counter++;
        if(percent > oldPercent)
        {
            oldPercent = percent;
            emit signalProgress(percent);
            kapp->processEvents(10);
        }

        QString id = (*it).msgid;
        id.replace(nlReg,"");
        QString str = (*it).msgstr;
        str.replace(nlReg,"");
        msgidDiffList.append(id);
        
        if(!str.isEmpty())
        {
            if(msgstr2MsgidDiffList.contains(str))
            {           
                QStringList sl = msgstr2MsgidDiffList[str];
                sl.append(id);
            }
            else
            {
                QStringList sl;
                sl.append(id);
                msgstr2MsgidDiffList.insert(str,sl);
            }
        }
    }

    emit signalClearProgressBar();
}

QValueList<DiffEntry> Catalog::asDiffList()
{
    QValueList<DiffEntry> list;	
    
    for ( QValueList<CatalogItem>::Iterator it = _entries.begin(); 
					it != _entries.end(); ++it)
	{
        DiffEntry e;
        e.msgid = (*it).msgid();
        e.msgstr = (*it).msgstr();

        list.append(e);
    }

    return list;

}

void Catalog::getNumberOfPluralForms()
{
    if(_identitySettings.numberOfPluralForms > 0)
    {
        numberOfPluralForms = _identitySettings.numberOfPluralForms;
        return;
    }
    
    QString lang=_identitySettings.languageCode;
    if(lang.isEmpty())
    {
        numberOfPluralForms=-1;
        return;
    }

    numberOfPluralForms = getNumberOfPluralForms(lang);
}

int Catalog::getNumberOfPluralForms(const QString& lang)
{
    int nr=-1;

    KLocale locale("kdelibs");
    locale.setLanguage(lang);

    const char* formsString =
        "_: Dear translator, please do not translate this string in any form, but pick the _right_ value out of NoPlural/TwoForms/French.... If not sure what to do mail thd@kde.org and coolo@kde.org, they will tell you. Better leave that out if unsure, the programs will crash!!\nDefinition of PluralForm - to be set by the translator of kdelibs.po";
    
    QString formsTranslation = locale.translate(formsString);

    // no translation found
    if(formsTranslation == formsString || formsTranslation.isEmpty())
    {
        kdDebug(KBABEL) << "no translation of PluralForms found" << endl;
        return -1;
    }
    if ( formsTranslation == "NoPlural" )
      nr = 0;
    else if ( formsTranslation == "TwoForms" )
      nr = 1;
    else if ( formsTranslation == "French" )
      nr = 2;
    else if ( formsTranslation == "Gaeilge" || formsTranslation == "OneTwoRest" )
      nr = 3;
    else if ( formsTranslation == "Russian" )
      nr = 4;
    else if ( formsTranslation == "Polish" )
      nr = 5;
    else if ( formsTranslation == "Slovenian" )
      nr = 6;
    else if ( formsTranslation == "Lithuanian" )
      nr = 7;
    else if ( formsTranslation == "Czech" )
      nr = 8;
    else if ( formsTranslation == "Slovak" )
      nr = 9;
    else if ( formsTranslation == "Maltese" )
      nr = 10;
    else
    {
        kdDebug(KBABEL) << "unknown translation of PluralForms: " 
            << formsTranslation << endl;
        nr=-1;
    }

    return nr;
}

bool Catalog::hasPluralForms() const
{
    bool have=false;
    for ( QValueList<CatalogItem>::ConstIterator it = _entries.begin(); 
					it != _entries.end(); ++it)
	{
		if((*it).isPluralForm())
		{
            have=true;
            break;
		}
	}

    return have;
}

#include "catalog.moc"
