Index: sievejob.cpp
===================================================================
--- sievejob.cpp	(wersja 809596)
+++ sievejob.cpp	(kopia robocza)
@@ -198,7 +198,7 @@
 	emit gotScript( this, false, mScript, mUrl.fileName() == mActiveScriptName );
 
       mJob = 0;
-      delete this;
+      deleteLater();
       return;
     }
 
@@ -220,7 +220,7 @@
 	emit gotScript( this, true, mScript, mUrl.fileName() == mActiveScriptName );
 
       mJob = 0; // deletes itself on returning from this slot
-      delete this;
+      deleteLater();
       return;
     } else {
       // schedule the next command:
Index: kmfolderindex_sqlite.cpp
===================================================================
--- kmfolderindex_sqlite.cpp	(wersja 809596)
+++ kmfolderindex_sqlite.cpp	(kopia robocza)
@@ -206,10 +206,12 @@
   const char selectSql[] = "SELECT id, data FROM messages";
   int result = sqlite3_prepare_v2( mIndexDb, selectSql, -1, &pStmt, 0 );
   bool ok = true;
+  QList<sqlite3_int64> rowsToDelete; // rows with 0 serial number to delete later
   if( result != SQLITE_OK ) {
     ok = false;
     kWarning() << "sqlite3_prepare_v2() error: sql=" << selectSql << errorMessage( result, mIndexDb );
   }
+  kDebug( Test1Area ) << fileName();
   while ( ok ) {
     result = sqlite3_step( pStmt );
     if ( result == SQLITE_DONE )
@@ -239,6 +241,12 @@
         ++mUnreadMsgs;
     }
     mMsgList.append(mi, false);
+    kDebug( Test1Area ) << "getMsgSerNum:" << mi->getMsgSerNum();
+    if ( mi->getMsgSerNum() == 0 ) {
+      kDebug() << "mi->getMsgSerNum() == 0: let's rebuild the index";
+      rowsToDelete.append( dbId );
+      break;
+    }
   } // while
 
   if ( pStmt ) {
@@ -248,71 +256,73 @@
       kWarning() << "sqlite3_reset() error " << errorMessage( result, mIndexDb );
     }
     result = sqlite3_finalize( pStmt );
-    if( result == SQLITE_OK && prevResult != SQLITE_OK )
+    if ( result == SQLITE_OK && prevResult != SQLITE_OK )
       result = prevResult; // rollback if sqlite3_finalize() or prev. command failed
   }
-/*  if ( result != SQLITE_OK ) {
-    executeQuery( mIndexDb, "ROLLBACK" );
-    return false;
-  }*/
 
-/*old impl:
-  while (!feof(mIndexStream))
-  {
-    mi = 0;
-    if(version >= 1505) {
-      if(!fread(&len, sizeof(len), 1, mIndexStream))
-        break;
+  mTotalMsgs = mMsgList.count();
+  if ( ok )
+    ok = deleteIndexRows( rowsToDelete );
 
-      if (mIndexSwapByteOrder)
-        len = kmail_swap_32(len);
+  return ok;
+}
 
-      off_t offs = KDE_ftell(mIndexStream);
-      if(KDE_fseek(mIndexStream, len, SEEK_CUR))
+bool KMFolderIndex::deleteIndexRows( const QList<sqlite3_int64>& rowsToDelete )
+{
+  if ( rowsToDelete.isEmpty() )
+    return true;
+
+  if ( !executeQuery( mIndexDb, "BEGIN" ) )
+    return false;
+  // We're preparing both versions of statements because regardless of the mode
+  // both could be used.
+  const char sqlDelete[] = "DELETE FROM messages WHERE id=?";
+  sqlite3_stmt *pDeleteStmt = 0;
+  int result = sqlite3_prepare_v2( mIndexDb, sqlDelete, -1, &pDeleteStmt, 0 );
+  if( result != SQLITE_OK ) {
+    kWarning() << "sqlite3_prepare_v2() error: sql=" << sqlDelete << errorMessage( result, mIndexDb );
+  }
+  if( result == SQLITE_OK ) {
+    result = sqlite3_prepare_v2( mIndexDb, sqlDelete, -1, &pDeleteStmt, 0 );
+    if( result != SQLITE_OK ) {
+      kWarning() << "sqlite3_prepare_v2() error: sql=" << sqlDelete << errorMessage( result, mIndexDb );
+    }
+  }
+  if( result == SQLITE_OK ) {
+    QList<sqlite3_int64>::ConstIterator constEnd( rowsToDelete.constEnd() );
+    for ( QList<sqlite3_int64>::ConstIterator it( rowsToDelete.constBegin() ); it != constEnd; ++it ) {
+      result = sqlite3_bind_int64( pDeleteStmt, 1, *it ); // bind existing id value
+      if ( result != SQLITE_OK ) {
+        kWarning() << "sqlite3_bind_int64() error " << errorMessage( result, mIndexDb );
         break;
-      mi = new KMMsgInfo(folder(), offs, len);
-    }
-    else
-    {
-      QByteArray line( MAX_LINE, '\0' );
-      fgets(line.data(), MAX_LINE, mIndexStream);
-      if (feof(mIndexStream)) break;
-      if (*line.data() == '\0') {
-        fclose(mIndexStream);
-        KMailStorageInternalsDebug << "fclose(mIndexStream = " << mIndexStream << ")";
-        mIndexStream = 0;
-        clearIndex();
-        return false;
       }
-      mi = new KMMsgInfo(folder());
-      mi->compat_fromOldIndexString(line, mConvertToUtf8);
+      result = sqlite3_step(pDeleteStmt);
+      if ( result != SQLITE_DONE ) {
+        kWarning() << "sqlite3_step() error " << errorMessage( result, mIndexDb );
+        break;
+      }
+      result = sqlite3_reset(pDeleteStmt);
+      if ( result != SQLITE_OK ) {
+        kWarning() << "sqlite3_reset() error " << errorMessage( result, mIndexDb );
+        break;
+      }
     }
-    if(!mi)
-      break;
+  }
+  // free the resources
+  if ( pDeleteStmt ) {
+    int prevResult = result;
+    result = sqlite3_finalize( pDeleteStmt );
+    if( result == SQLITE_OK && prevResult != SQLITE_OK )
+      result = prevResult; // rollback if sqlite3_finalize() or prev. command failed
+  }
 
-    if (mi->status().isDeleted())
-    {
-      delete mi;  // skip messages that are marked as deleted
-      setDirty( true );
-      needsCompact = true;  //We have deleted messages - needs to be compacted
-      continue;
-    }
-    if ((mi->status().isNew()) || (mi->status().isUnread()) ||
-        (folder() == kmkernel->outboxFolder()))
-    {
-      ++mUnreadMsgs;
-      if (mUnreadMsgs == 0) ++mUnreadMsgs;
-    }
-    mMsgList.append(mi, false);
-  }*/
-
-/*  if( version < 1505)
-  {
-    mConvertToUtf8 = false;
-    setDirty( true );
-    writeIndex();
-  }*/
-  mTotalMsgs = mMsgList.count();
+  // commit or rollback
+  if ( result != SQLITE_OK ) {
+    executeQuery( mIndexDb, "ROLLBACK" );
+    return false;
+  }
+  if ( !executeQuery( mIndexDb, "COMMIT" ) )
+    return false;
   return true;
 }
 
Index: kmmessage.h
===================================================================
--- kmmessage.h	(wersja 809596)
+++ kmmessage.h	(kopia robocza)
@@ -872,8 +872,6 @@
   bool mReadyToShow :1;
   bool mComplete :1;
   bool mIsParsed :1;
-  static const KMail::HeaderStrategy * sHeaderStrategy;
-  static QString sForwardStr;
   const QTextCodec * mOverrideCodec;
 
   QString mFileName;
@@ -886,7 +884,6 @@
   KMMessage* mUnencryptedMsg;
   DwBodyPart* mLastUpdated;
   int mCursorPos;
-  static QList<KMMessage*> sPendingDeletes;
 };
 
 
Index: kmfoldermaildir.cpp
===================================================================
--- kmfoldermaildir.cpp	(wersja 809596)
+++ kmfoldermaildir.cpp	(kopia robocza)
@@ -503,10 +503,12 @@
   aMsg->setParent(folder());
   aMsg->setMsgSize( msgText.length() );
   idx = mMsgList.append( &aMsg->toMsgBase(), mExportsSernums );
-  if (aMsg->getMsgSerNum() <= 0)
+  const unsigned long msgSerNum = aMsg->getMsgSerNum();
+  kDebug( Test1Area ) << "getMsgSerNum:" << msgSerNum;
+  if ( msgSerNum <= 0 )
     aMsg->setMsgSerNum();
   else
-    replaceMsgSerNum( aMsg->getMsgSerNum(), &aMsg->toMsgBase(), idx );
+    replaceMsgSerNum( msgSerNum, &aMsg->toMsgBase(), idx );
 
   // write index entry if desired
   if (mAutoCreateIndex)
Index: jobscheduler.cpp
===================================================================
--- jobscheduler.cpp	(wersja 809596)
+++ jobscheduler.cpp	(kopia robocza)
@@ -35,6 +35,17 @@
 
 using namespace KMail;
 
+ScheduledTask::ScheduledTask( KMFolder* folder, bool immediate )
+  : mCurrentFolder( folder ), mImmediate( immediate )
+{
+  kDebug( Test1Area ) << this << "idString=" << (mCurrentFolder ? mCurrentFolder->idString() : QString()) << "immediate=" << mImmediate;
+}
+
+ScheduledTask::~ScheduledTask()
+{
+  kDebug( Test1Area ) << this << "idString=" << (mCurrentFolder ? mCurrentFolder->idString() : QString()) << "immediate=" << mImmediate;
+}
+
 JobScheduler::JobScheduler( QObject* parent, const char* name )
   : QObject( parent ), mTimer( this ),
     mPendingImmediateTasks( 0 ),
@@ -49,9 +60,8 @@
 JobScheduler::~JobScheduler()
 {
   // delete tasks in tasklist (no autodelete for QValueList)
-  for( TaskList::Iterator it = mTaskList.begin(); it != mTaskList.end(); ++it ) {
-    delete (*it);
-  }
+  qDeleteAll( mTaskList );
+  mTaskList.clear();
   delete mCurrentTask;
   delete mCurrentJob;
 }
@@ -247,12 +257,18 @@
 
 ////
 
-KMail::ScheduledJob::ScheduledJob( KMFolder* folder, bool immediate )
+ScheduledJob::ScheduledJob( KMFolder* folder, bool immediate )
   : FolderJob( 0, tOther, folder ), mImmediate( immediate ),
     mOpeningFolder( false )
 {
   mCancellable = true;
   mSrcFolder = folder;
+  kDebug( Test1Area ) << this << "mDestFolder->idString=" << (mDestFolder ? mDestFolder->idString() : QString()) << "immediate=" << mImmediate;
 }
 
+ScheduledJob::~ScheduledJob()
+{
+  kDebug( Test1Area ) << this << "mDestFolder->idString=" << (mDestFolder ? mDestFolder->idString() : QString()) << "immediate=" << mImmediate;
+}
+
 #include "jobscheduler.moc"
Index: networkaccount.cpp
===================================================================
--- networkaccount.cpp	(wersja 809596)
+++ networkaccount.cpp	(kopia robocza)
@@ -45,11 +45,11 @@
 
 
  // for restricting number of concurrent connections to the same server
-  static QMap<QString, int> s_serverConnections;
+  typedef QHash<QString, int> ServerConnectionsHash;
+  K_GLOBAL_STATIC( ServerConnectionsHash, s_serverConnections )
 
   NetworkAccount::NetworkAccount( AccountManager * parent, const QString & name, uint id )
     : KMAccount( parent, name, id ),
-      mSlave( 0 ),
       mAuth( "*" ),
       mPort( 0 ),
       mStorePasswd( false ),
@@ -348,20 +348,21 @@
       mCheckingMail = checking;
       if ( host().isEmpty() )
           return;
+    ServerConnectionsHash::Iterator serverConnectionsIt( s_serverConnections->find( host() ) );
     if ( checking ) {
-        if ( s_serverConnections.find( host() ) != s_serverConnections.end() )
-            s_serverConnections[host()] += 1;
+        if ( serverConnectionsIt != s_serverConnections->end() )
+            *serverConnectionsIt += 1;
         else
-            s_serverConnections[host()] = 1;
+            s_serverConnections->insert( host(), 1 );
         kDebug(5006) <<"check mail started - connections for host"
                 << host() << "now is"
-                << s_serverConnections[host()];
+                << s_serverConnections->value( host() );
     } else {
-            if ( s_serverConnections.find( host() ) != s_serverConnections.end() &&
-                s_serverConnections[host()] > 0 ) {
-                s_serverConnections[host()] -= 1;
+            if ( serverConnectionsIt != s_serverConnections->end() &&
+                *serverConnectionsIt > 0 ) {
+                *serverConnectionsIt -= 1;
                 kDebug(5006) <<"connections to server" << host()
-                        << "now" << s_serverConnections[host()];
+                        << "now" << *serverConnectionsIt;
             }
     }
 }
@@ -370,14 +371,15 @@
   {
       bool offlineMode = KMKernel::isOffline();
 
+      ServerConnectionsHash::Iterator serverConnectionsIt( s_serverConnections->find( host() ) );
       kDebug(5006) <<"for host" << host()
               << "current connections="
-              << (s_serverConnections.find(host())==s_serverConnections.end() ? 0 : s_serverConnections[host()])
+              << (serverConnectionsIt==s_serverConnections->end() ? 0 : *serverConnectionsIt)
               << "and limit is" << GlobalSettings::self()->maxConnectionsPerHost();
       bool connectionLimitForHostReached = !host().isEmpty()
               && GlobalSettings::self()->maxConnectionsPerHost() > 0
-              && s_serverConnections.find( host() ) != s_serverConnections.end()
-              && s_serverConnections[host()] >= GlobalSettings::self()->maxConnectionsPerHost();
+              && serverConnectionsIt!=s_serverConnections->end()
+              && *serverConnectionsIt >= GlobalSettings::self()->maxConnectionsPerHost();
       kDebug(5006) <<"connection limit reached:"
               << connectionLimitForHostReached;
 
@@ -386,7 +388,7 @@
 
   void NetworkAccount::resetConnectionList( NetworkAccount* acct )
   {
-    s_serverConnections[ acct->host() ] = 0;
+    s_serverConnections->remove( acct->host() );
   }
 
 } // namespace KMail
Index: kmmessage.cpp
===================================================================
--- kmmessage.cpp	(wersja 809596)
+++ kmmessage.cpp	(kopia robocza)
@@ -75,22 +75,29 @@
 
 using namespace KMime;
 
-static DwString emptyString("");
+struct KMMessageStaticData
+{
+  KMMessageStaticData()
+    : emptyString(""), headerStrategy( HeaderStrategy::rich() )
+  {
+  }
 
-// Values that are set from the config file with KMMessage::readConfig()
-static QString sReplyLanguage, sReplyStr, sReplyAllStr, sIndentPrefixStr;
-static bool sSmartQuote,
-  sWordWrap;
-static int sWrapCol;
-static QStringList sPrefCharsets;
+  DwString emptyString;
 
-QString KMMessage::sForwardStr;
-const HeaderStrategy * KMMessage::sHeaderStrategy = HeaderStrategy::rich();
+  // Values that are set from the config file with KMMessage::readConfig()
+  QString replyLanguage, replyStr, replyAllStr, forwardStr, indentPrefixStr;
+  bool smartQuote : 1, wordWrap : 1;
+  int wrapCol;
+  QStringList prefCharsets;
+  const HeaderStrategy* headerStrategy;
+  QList<KMMessage*> pendingDeletes;
+};
+
+K_GLOBAL_STATIC( KMMessageStaticData, s )
+
 //helper
 static void applyHeadersToMessagePart( DwHeaders& headers, KMMessagePart* aPart );
 
-QList<KMMessage*> KMMessage::sPendingDeletes;
-
 //-----------------------------------------------------------------------------
 KMMessage::KMMessage(DwMessage* aMsg)
   : KMMsgBase()
@@ -266,8 +273,8 @@
 void KMMessage::setTransferInProgress(bool value, bool force)
 {
   MessageProperty::setTransferInProgress( getMsgSerNum(), value, force );
-  if ( !transferInProgress() && sPendingDeletes.contains( this ) ) {
-    sPendingDeletes.removeAll( this );
+  if ( !transferInProgress() && s->pendingDeletes.contains( this ) ) {
+    s->pendingDeletes.removeAll( this );
     if ( parent() ) {
       int idx = parent()->find( this );
       if ( idx > 0 ) {
@@ -444,7 +451,7 @@
            like this change to a short XX/XX/YY date format.
            At least not for the default. -sanders */
         result += KMime::DateFormatter::formatDate( KMime::DateFormatter::Localized,
-            date(), sReplyLanguage, false );
+            date(), s->replyLanguage, false );
         break;
       case 'e':
         result += from();
@@ -843,8 +850,8 @@
   content += '\n';
 
   const QString headerStr = formatString( aHeaderStr );
-  if ( sSmartQuote && sWordWrap )
-    return headerStr + smartQuote( content, sWrapCol );
+  if ( s->smartQuote && s->wordWrap )
+    return headerStr + smartQuote( content, s->wrapCol );
   return headerStr + content;
 }
 
@@ -882,7 +889,7 @@
   }
 
   // use the "On ... Joe User wrote:" header by default
-  replyStr = sReplyAllStr;
+  replyStr = s->replyAllStr;
 
   switch( replyStrategy ) {
   case KMail::ReplySmart : {
@@ -899,7 +906,7 @@
     else {
       // doesn't seem to be a mailing list, reply to From: address
       toStr = from();
-      replyStr = sReplyStr; // reply to author, so use "On ... you wrote:"
+      replyStr = s->replyStr; // reply to author, so use "On ... you wrote:"
       replyAll = false;
     }
     // strip all my addresses from the list of recipients
@@ -1026,7 +1033,7 @@
     else if ( !from().isEmpty() ) {
       toStr = from();
     }
-    replyStr = sReplyStr; // reply to author, so use "On ... you wrote:"
+    replyStr = s->replyStr; // reply to author, so use "On ... you wrote:"
     replyAll = false;
     break;
   }
@@ -1048,8 +1055,8 @@
 //      QByteArray cStr = selection.toLatin1();
 //      msg->setBody( cStr );
 //    }else{
-//      msg->setBody(asQuotedString(replyStr + '\n', sIndentPrefixStr, selection,
-//                                  sSmartQuote, allowDecryption).toUtf8());
+//      msg->setBody(asQuotedString(replyStr + '\n', s->indentPrefixStr, selection,
+//                                  s->smartQuote, allowDecryption).toUtf8());
 //    }
 //  }
 
@@ -1058,7 +1065,7 @@
   // If the reply shouldn't be blank, apply the template to the message
   if ( !noQuote ) {
     TemplateParser parser( msg, (replyAll ? TemplateParser::ReplyAll : TemplateParser::Reply),
-                           selection, sSmartQuote, allowDecryption, selectionIsBody );
+                           selection, s->smartQuote, allowDecryption, selectionIsBody );
     if ( !tmpl.isEmpty() )
       parser.process( tmpl, this );
     else
@@ -1162,30 +1169,24 @@
 //-----------------------------------------------------------------------------
 QByteArray KMMessage::createForwardBody()
 {
-  QString s;
-  QByteArray str;
-
-  if (sHeaderStrategy == HeaderStrategy::all()) {
-    s = "\n\n----------  " + sForwardStr + "  ----------\n\n";
-    s += headerAsString();
-    str = asQuotedString(s, "", QString(), false, false).toUtf8();
-    str += "\n-------------------------------------------------------\n";
+  QString tmp;
+  if (s->headerStrategy == HeaderStrategy::all()) {
+    tmp = "\n\n----------  " + s->forwardStr + "  ----------\n\n"
+      + headerAsString();
   } else {
-    s = "\n\n----------  " + sForwardStr + "  ----------\n\n";
-    s += "Subject: " + subject() + '\n';
-    s += "Date: "
+    tmp = "\n\n----------  " + s->forwardStr + "  ----------\n\n"
+      + "Subject: " + subject() + '\n'
+      + "Date: "
          + KMime::DateFormatter::formatDate( KMime::DateFormatter::Localized,
-                                             date(), sReplyLanguage, false )
-         + '\n';
-    s += "From: " + from() + '\n';
-    s += "To: " + to() + '\n';
-    if (!cc().isEmpty()) s += "Cc: " + cc() + '\n';
-    s += '\n';
-    str = asQuotedString(s, "", QString(), false, false).toUtf8();
-    str += "\n-------------------------------------------------------\n";
+                                             date(), s->replyLanguage, false )
+         + '\n'
+      + "From: " + from() + '\n'
+      + "To: " + to() + '\n'
+      + ( cc().isEmpty() ? QString() : ("Cc: " + cc() + '\n') )
+      + '\n';
   }
-
-  return str;
+  return asQuotedString(tmp, "", QString(), false, false).toUtf8()
+    + "\n-------------------------------------------------------\n";
 }
 
 void KMMessage::sanitizeHeaders( const QStringList& whiteList )
@@ -1294,7 +1295,7 @@
   else
     parser.process( this );
 
-  // QByteArray encoding = autoDetectCharset(charset(), sPrefCharsets, msg->body());
+  // QByteArray encoding = autoDetectCharset(charset(), s->prefCharsets, msg->body());
   // if (encoding.isEmpty()) encoding = "utf-8";
   // msg->setCharset(encoding);
   // force utf-8
@@ -2372,7 +2373,7 @@
     if ( type != Unstructured )
       kDebug(5006) <<"value: \"" << value <<"\"";
 #endif
-    QByteArray encoding = autoDetectCharset( charset(), sPrefCharsets, value );
+    QByteArray encoding = autoDetectCharset( charset(), s->prefCharsets, value );
     if (encoding.isEmpty())
        encoding = "utf-8";
     aValue = encodeRFC2047String( value, encoding );
@@ -3109,7 +3110,7 @@
 //-----------------------------------------------------------------------------
 DwBodyPart* KMMessage::createDWBodyPart(const KMMessagePart* aPart)
 {
-  DwBodyPart* part = DwBodyPart::NewBodyPart(emptyString, 0);
+  DwBodyPart* part = DwBodyPart::NewBodyPart(s->emptyString, 0);
 
   if ( !aPart )
     return part;
@@ -3120,7 +3121,7 @@
   QByteArray cte      = aPart->cteStr();
   QByteArray contDesc = aPart->contentDescriptionEncoded();
   QByteArray contDisp = aPart->contentDisposition();
-  QByteArray encoding = autoDetectCharset(charset, sPrefCharsets, aPart->name());
+  QByteArray encoding = autoDetectCharset(charset, s->prefCharsets, aPart->name());
   if (encoding.isEmpty()) encoding = "utf-8";
   QByteArray name     = KMMsgBase::encodeRFC2231String(aPart->name(), encoding);
   bool RFC2231encoded = aPart->name() != QString(name);
@@ -3199,7 +3200,7 @@
 
   if (!paramAttr.isEmpty())
   {
-    QByteArray encoding = autoDetectCharset(charset, sPrefCharsets,
+    QByteArray encoding = autoDetectCharset(charset, s->prefCharsets,
                                             aPart->parameterValue());
     if (encoding.isEmpty()) encoding = "utf-8";
     QByteArray paramValue;
@@ -3905,32 +3906,32 @@
 
   { // area for config group "KMMessage #n"
     KConfigGroup config( KMKernel::config(), QString("KMMessage #%1").arg(languageNr) );
-    sReplyLanguage = config.readEntry("language",KGlobal::locale()->language());
-    sReplyStr = config.readEntry("phrase-reply",
+    s->replyLanguage = config.readEntry("language",KGlobal::locale()->language());
+    s->replyStr = config.readEntry("phrase-reply",
       i18n("On %D, you wrote:"));
-    sReplyAllStr = config.readEntry("phrase-reply-all",
+    s->replyAllStr = config.readEntry("phrase-reply-all",
       i18n("On %D, %F wrote:"));
-    sForwardStr = config.readEntry("phrase-forward",
+    s->forwardStr = config.readEntry("phrase-forward",
       i18n("Forwarded Message"));
-    sIndentPrefixStr = config.readEntry("indent-prefix",">%_");
+    s->indentPrefixStr = config.readEntry("indent-prefix",">%_");
   }
 
   { // area for config group "Composer"
     KConfigGroup config( KMKernel::config(), "Composer" );
-    sSmartQuote = GlobalSettings::self()->smartQuote();
-    sWordWrap = GlobalSettings::self()->wordWrap();
-    sWrapCol = GlobalSettings::self()->lineWrapWidth();
-    if ((sWrapCol == 0) || (sWrapCol > 78))
-      sWrapCol = 78;
-    if (sWrapCol < 30)
-      sWrapCol = 30;
+    s->smartQuote = GlobalSettings::self()->smartQuote();
+    s->wordWrap = GlobalSettings::self()->wordWrap();
+    s->wrapCol = GlobalSettings::self()->lineWrapWidth();
+    if ((s->wrapCol == 0) || (s->wrapCol > 78))
+      s->wrapCol = 78;
+    if (s->wrapCol < 30)
+      s->wrapCol = 30;
 
-    sPrefCharsets = config.readEntry("pref-charsets", QStringList() );
+    s->prefCharsets = config.readEntry("pref-charsets", QStringList() );
   }
 
   { // area for config group "Reader"
     KConfigGroup config( KMKernel::config(), "Reader" );
-    sHeaderStrategy = HeaderStrategy::create( config.readEntry( "header-set-displayed", "rich" ) );
+    s->headerStrategy = HeaderStrategy::create( config.readEntry( "header-set-displayed", "rich" ) );
   }
 }
 
@@ -3938,8 +3939,8 @@
 {
   QByteArray retval;
 
-  if (!sPrefCharsets.isEmpty())
-    retval = sPrefCharsets[0].toLatin1();
+  if (!s->prefCharsets.isEmpty())
+    retval = s->prefCharsets[0].toLatin1();
 
   if (retval.isEmpty()  || (retval == "locale")) {
     retval = QByteArray(kmkernel->networkCodec()->name());
@@ -3953,7 +3954,7 @@
 
 const QStringList &KMMessage::preferredCharsets()
 {
-  return sPrefCharsets;
+  return s->prefCharsets;
 }
 
 //-----------------------------------------------------------------------------
@@ -4323,5 +4324,5 @@
 
 void KMMessage::deleteWhenUnused()
 {
-  sPendingDeletes << this;
+  s->pendingDeletes << this;
 }
Index: jobscheduler.h
===================================================================
--- jobscheduler.h	(wersja 809596)
+++ jobscheduler.h	(kopia robocza)
@@ -56,9 +56,8 @@
   /// Create a scheduled task for a given folder
   /// If @p immediate is true, the scheduler will run this task as soon
   /// as possible (but won't interrupt a currently running job for it)
-  ScheduledTask( KMFolder* folder, bool immediate )
-    : mCurrentFolder( folder ), mImmediate( immediate ) {}
-  virtual ~ScheduledTask() {}
+  ScheduledTask( KMFolder* folder, bool immediate );
+  virtual ~ScheduledTask();
 
   /// Run this task, i.e. create a job for it.
   /// Important: the job's execute() method must either call open() on the
@@ -143,6 +142,7 @@
 {
 public:
   ScheduledJob( KMFolder* folder, bool immediate );
+  ~ScheduledJob();
 
   bool isOpeningFolder() const { return mOpeningFolder; }
 
Index: kmcommands.cpp
===================================================================
--- kmcommands.cpp	(wersja 809596)
+++ kmcommands.cpp	(kopia robocza)
@@ -2059,6 +2059,10 @@
   mProgressItem->setTotalItems( mSerNumList.count() );
 
   for ( QList<quint32>::ConstIterator it = mSerNumList.constBegin(); it != mSerNumList.constEnd(); ++it ) {
+    if ( *it == 0 ) {
+      kDebug(5006) << "serial number == 0!";
+      continue; // invalid message
+    }
     KMFolder *srcFolder;
     int idx = -1;
     KMMsgDict::instance()->getLocation( *it, &srcFolder, &idx );
Index: kmmsgbase.cpp
===================================================================
--- kmmsgbase.cpp	(wersja 809596)
+++ kmmsgbase.cpp	(kopia robocza)
@@ -802,12 +802,12 @@
 {
   QString ret;
 retry:
-  bool using_mmap = false;
 #ifdef KMAIL_SQLITE_INDEX
   bool swapByteOrder = false;
   g_chunk = (uchar*)mData;
   g_chunk_length = mIndexLength;
 #else
+  bool using_mmap = false;
   bool swapByteOrder = storage()->indexSwapByteOrder();
   if (storage()->indexStreamBasePtr()) {
     if (g_chunk)
@@ -846,10 +846,12 @@
     type = (MsgPartType) tmp;
     if( g_chunk_offset + len > mIndexLength ) {
       kDebug() << "This should never happen..";
+#ifndef KMAIL_SQLITE_INDEX
       if( using_mmap ) {
         g_chunk_length = 0;
         g_chunk = 0;
       }
+#endif
       if ( !storage()->recreateIndex() )
         return QString();
       goto retry;
@@ -862,10 +864,12 @@
       break;
     }
   } //for
+#ifndef KMAIL_SQLITE_INDEX
   if(using_mmap) {
       g_chunk_length = 0;
       g_chunk = 0;
   }
+#endif
   // Normally we need to swap the byte order because the QStrings are written
   // in the style of Qt2 (MSB -> network ordered).
   // QStrings in Qt3 expect host ordering.
@@ -886,7 +890,6 @@
 {
 retry:
   off_t ret = 0;
-  bool using_mmap = false;
 
 #ifdef KMAIL_SQLITE_INDEX
   //todo reenable
@@ -895,6 +898,7 @@
   g_chunk = (uchar*)mData;
   g_chunk_length = mIndexLength;
 #else
+  bool using_mmap = false;
   bool swapByteOrder = storage()->indexSwapByteOrder();
   int sizeOfLong = storage()->indexSizeOfLong();
   if (storage()->indexStreamBasePtr()) {
@@ -930,10 +934,12 @@
 
     if (g_chunk_offset + len > mIndexLength) {
       kDebug(5006) <<"This should never happen..";
+#ifndef KMAIL_SQLITE_INDEX
       if(using_mmap) {
         g_chunk_length = 0;
         g_chunk = 0;
       }
+#endif
       if (!storage()->recreateIndex())
         return 0;
       goto retry;
@@ -996,10 +1002,12 @@
       break;
     }
   } // for
+#ifndef KMAIL_SQLITE_INDEX
   if(using_mmap) {
     g_chunk_length = 0;
     g_chunk = 0;
   }
+#endif
 
   return ret;
 }
Index: kmfolderindex.h
===================================================================
--- kmfolderindex.h	(wersja 809596)
+++ kmfolderindex.h	(kopia robocza)
@@ -184,8 +184,14 @@
     UpdateExistingMessages //!< writeMessages() will update data for existing messages and add any new message
   };
 
+  /* Writes messages to index database for the folder. Inserts or replaces existing messages,
+   depending on @a mode. */
   int writeMessages( KMMsgBase* msg, WriteMessagesMode mode );
 
+  /* Executes "DELETE FROM messages WHERE id=.." for every id included in @a rowsToDelete. 
+   Used in readIndex() for messages with 0 serial number, especially for the outbox. */
+  bool deleteIndexRows( const QList<sqlite3_int64>& rowsToDelete );
+
   /** main SQlite db handle */
   sqlite3 *mIndexDb;
 #else
Index: networkaccount.h
===================================================================
--- networkaccount.h	(wersja 809596)
+++ networkaccount.h	(kopia robocza)
@@ -29,13 +29,14 @@
 
 #include "sieveconfig.h"
 
+#include <kio/slave.h>
+
 #include <QString>
 
 class AccountManager;
 class KConfig/*Base*/;
 class KUrl;
 namespace KIO {
-  class Slave;
   class MetaData;
 }
 
@@ -128,14 +129,14 @@
 
   protected:
     KMail::SieveConfig mSieveConfig;
-    KIO::Slave * mSlave;
+    QPointer<KIO::Slave> mSlave;
     QString mLogin, mPasswd, mAuth, mHost, mOldPassKey;
     unsigned short int mPort;
     bool mStorePasswd : 1;
     bool mUseSSL : 1;
     bool mUseTLS : 1;
     bool mAskAgain : 1;
-    bool mPasswdDirty, mStorePasswdInConfig;
+    bool mPasswdDirty : 1, mStorePasswdInConfig : 1;
   };
 
 } // namespace KMail
Index: kmfoldertree.cpp
===================================================================
--- kmfoldertree.cpp	(wersja 809596)
+++ kmfoldertree.cpp	(kopia robocza)
@@ -1349,11 +1349,14 @@
   Q3ListViewItemIterator fldIt(this);
   QMap<QString,bool> folderMap;
   KMFolderTreeItem *fti;
+  kDebug(5006) << "Fill the map:";
   for (Q3ListViewItemIterator fldIt(this); fldIt.current(); fldIt++)
   {
     fti = static_cast<KMFolderTreeItem*>(fldIt.current());
-    if (fti && fti->folder())
+    if (fti && fti->folder()) {
       folderMap.insert(fti->folder()->idString(), true);
+      kDebug(5006) << fti->folder()->idString();
+    }
   }
   QStringList groupList = config->groupList();
   QString name;
@@ -1372,7 +1375,7 @@
       }
 
       //KMessageBox::error( 0, "cleanupConfigFile: Deleting group " + *grpIt );
-      config->deleteGroup(*grpIt, KConfig::Localized);
+      config->deleteGroup(*grpIt); //js, KConfig::Localized);
       kDebug(5006) <<"Deleting information about folder" << name;
     }
   }
Index: listjob.cpp
===================================================================
--- listjob.cpp	(wersja 809596)
+++ listjob.cpp	(kopia robocza)
@@ -69,7 +69,7 @@
   if ( mAccount->makeConnection() == ImapAccountBase::Error )
   {
     kWarning(5006) <<"ListJob - got no connection";
-    delete this;
+    deleteLater();
     return;
   } else if ( mAccount->makeConnection() == ImapAccountBase::Connecting )
   {
@@ -88,7 +88,7 @@
       mPath = static_cast<KMFolderCachedImap*>(mStorage)->imapPath();
     } else {
       kError(5006) <<"ListJob - no valid path and no folder given";
-      delete this;
+      deleteLater();
       return;
     }
   }
@@ -106,9 +106,9 @@
                         mType == ImapAccountBase::ListFolderOnlySubscribed );
   jd.path = mPath;
   jd.curNamespace = mNamespace;
-  QString status = mDestFolder ? mDestFolder->prettyUrl() : QString();
   if ( mParentProgressItem )
   {
+    QString status = mDestFolder ? mDestFolder->prettyUrl() : QString();
     jd.progressItem = ProgressManager::createProgressItem(
         mParentProgressItem,
         "ListDir" + ProgressManager::getUniqueID(),
@@ -157,7 +157,7 @@
   else {
     if ( mParentProgressItem )
       mParentProgressItem->setComplete();
-    delete this;
+    deleteLater();
   }
 }
 
@@ -166,7 +166,7 @@
   ImapAccountBase::JobIterator it = mAccount->findJob( static_cast<KIO::Job *>(job) );
   if ( it == mAccount->jobsEnd() )
   {
-    delete this;
+    deleteLater();
     return;
   }
   if ( job->error() )
@@ -181,7 +181,7 @@
         mSubfolderMimeTypes, mSubfolderAttributes, *it );
     mAccount->removeJob( it );
   }
-  delete this;
+  deleteLater();
 }
 
 void ListJob::slotListEntries( KIO::Job* job, const KIO::UDSEntryList& uds )
@@ -189,13 +189,13 @@
   ImapAccountBase::JobIterator it = mAccount->findJob( job );
   if ( it == mAccount->jobsEnd() )
   {
-    delete this;
+    deleteLater();
     return;
   }
   if( (*it).progressItem )
     (*it).progressItem->setProgress( 50 );
-  for ( KIO::UDSEntryList::ConstIterator udsIt = uds.begin();
-        udsIt != uds.end(); udsIt++ )
+  for ( KIO::UDSEntryList::ConstIterator udsIt = uds.constBegin();
+        udsIt != uds.constEnd(); udsIt++ )
   {
     // get the needed information
     const QString name = udsIt->stringValue( KIO::UDSEntry::UDS_NAME );
@@ -214,7 +214,7 @@
       // Some servers send _lots_ of duplicates
       // This check is too slow for huge lists
       if ( mSubfolderPaths.count() > 100 ||
-           mSubfolderPaths.indexOf(url.path()) == -1 )
+           !mSubfolderPaths.contains(url.path()) )
       {
         mSubfolderNames.append( name );
         mSubfolderPaths.append( url.path() );
Index: actionscheduler.cpp
===================================================================
--- actionscheduler.cpp	(wersja 809596)
+++ actionscheduler.cpp	(kopia robocza)
@@ -382,7 +382,7 @@
     mExecutingLock = false;
     emit result( aResult );
     if (mAutoDestruct)
-      delete this;
+      deleteLater();
   }
   // else a message may be in the process of being fetched or filtered
   // wait until both of these commitments are finished  then this
