Revision: 201031 RCL_3
authorDremov Kirill (Nokia-D-MSW/Tampere) <kirill.dremov@nokia.com>
Thu, 19 Aug 2010 09:41:07 +0300
branchRCL_3
changeset 18 d4f567ce2e7c
parent 17 2666d9724c76
child 19 5b6f26637ad3
Revision: 201031 Kit: 201033
contacts_plat/virtual_phonebook_configuration_api/inc/phonebook/VPbkVariant.hrh
contacts_plat/virtual_phonebook_store_api/inc/CVPbkContactOperationFactory.h
logsui/AppSrc/CLogsAppListView.cpp
logsui/AppSrc/CLogsAppListView.h
logsui/AppSrc/CLogsAppUi.cpp
logsui/AppSrc/CLogsAppUi.h
logsui/AppSrc/CLogsBaseView.cpp
logsui/AppSrc/CLogsRecentListView.cpp
logsui/AppSrc/CLogsRecentListView.h
logsui/group/Logs.mmp
logsui/help/data/xhtml.zip
phonebookengines/VirtualPhonebook/VPbkCntModel/src/CCustomFilteredGroupView.cpp
phonebookengines/VirtualPhonebook/VPbkCntModel/src/CFilteredContactView.cpp
phonebookengines/VirtualPhonebook/VPbkCntModel/src/CViewContact.cpp
phonebookengines/VirtualPhonebook/VPbkCntModel/src/TContactFieldDataImpl.cpp
phonebookengines/VirtualPhonebook/VPbkEng/src/CVPbkPhoneNumberMatchStrategy.cpp
phonebookengines/VirtualPhonebook/VPbkSimStore/inc/CContact.h
phonebookengines/VirtualPhonebook/VPbkSimStore/inc/CSupportedFieldTypes.h
phonebookengines/VirtualPhonebook/VPbkSimStore/rss/VPbkSimStoreRes.rss
phonebookengines/VirtualPhonebook/VPbkSimStore/src/CContact.cpp
phonebookengines/VirtualPhonebook/VPbkSimStore/src/CContactStore.cpp
phonebookengines/VirtualPhonebook/VPbkSimStore/src/CContactStoreDomain.cpp
phonebookengines/VirtualPhonebook/VPbkSimStore/src/CSupportedFieldTypes.cpp
phonebookengines/VirtualPhonebook/VPbkSimStoreCommon/src/CVPbkSimFieldTypeFilter.cpp
phonebookengines/VirtualPhonebook/VPbkSimStoreImpl/src/CVPbkETelCntConverter.cpp
phonebookengines/VirtualPhonebook/VPbkSimStoreImpl/src/CVPbkSimCntField.cpp
phonebookengines/VirtualPhonebook/VPbkSimStoreImpl/src/CVPbkSimContact.cpp
phonebookengines/VirtualPhonebook/VPbkSimStoreImpl/src/CVPbkSimContactBase.cpp
phonebookengines/VirtualPhonebook/VPbkVCardEng/inc/CVPbkVCardImporter.h
phonebookengines/VirtualPhonebook/VPbkVCardEng/src/CVPbkImportToContactsMergeOperation.cpp
phonebookengines/VirtualPhonebook/VPbkVCardEng/src/CVPbkImportToStoreOperation.cpp
phonebookengines/VirtualPhonebook/VPbkVCardEng/src/CVPbkVCardImporter.cpp
phonebookengines/VirtualPhonebook/inc/CVPbkSimContact.h
phonebookengines/VirtualPhonebook/inc/VPbkSimCntFieldTypes.hrh
phonebookui/Phonebook/View/src/CPbkFFSCheck.cpp
phonebookui/Phonebook2/Application/rss/Pbk2MenuResources.rss
phonebookui/Phonebook2/BWINS/Pbk2UiControlsU.DEF
phonebookui/Phonebook2/Commands/inc/MPbk2CommandResourceRelease.h
phonebookui/Phonebook2/Commands/src/CPbk2CommandHandler.cpp
phonebookui/Phonebook2/Commands/src/CPbk2CommandStore.cpp
phonebookui/Phonebook2/Commands/src/cpbk2commandactivator.cpp
phonebookui/Phonebook2/CommandsExtension/inc/CPbk2SendContactCmd.h
phonebookui/Phonebook2/CommandsExtension/src/CPbk2SendContactCmd.cpp
phonebookui/Phonebook2/CommandsExtension/src/CPbk2vCardConverter.cpp
phonebookui/Phonebook2/CommonUI/src/CPbk2ContactNavigation.cpp
phonebookui/Phonebook2/EABI/Pbk2UiControlsU.DEF
phonebookui/Phonebook2/GroupExtension/inc/CPguGroupMembersView.h
phonebookui/Phonebook2/GroupExtension/inc/CPguSendMessageGroupCmd.h
phonebookui/Phonebook2/GroupExtension/rss/PguMembersListViewBase.rss
phonebookui/Phonebook2/GroupExtension/src/CPguGroupMembersView.cpp
phonebookui/Phonebook2/GroupExtension/src/CPguSendMessageGroupCmd.cpp
phonebookui/Phonebook2/MMCExtension/src/CPmuCopyFromDriveCmd.cpp
phonebookui/Phonebook2/MapExtension/src/cpmapcmd.cpp
phonebookui/Phonebook2/NamesListExtension/inc/Pbk2NamesListExView.h
phonebookui/Phonebook2/NamesListExtension/rss/Pbk2ExNamesListRes.rss
phonebookui/Phonebook2/NamesListExtension/src/CPbk2NameslistUiControlExtension.cpp
phonebookui/Phonebook2/NamesListExtension/src/NamesListExView.cpp
phonebookui/Phonebook2/NamesListExtension/src/NamesListUiExtensionPlugin.cpp
phonebookui/Phonebook2/NamesListExtension/src/cpbk2cmditemmycard.cpp
phonebookui/Phonebook2/ServerApplication/inc/CPbk2AddressSelectPhase.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2AssignAttributePhase.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2AttributeAddressSelectPhase.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2CommAddressSelectPhase.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2ContactAttributeAssigner.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2ContactFetchPhase.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2EntryFetcher.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2ItemFetcher.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2MultiAssignDataPhase.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2MultiContactDataAssigner.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2PrepareAttributeAssignPhase.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2PrepareMultipleAssignPhase.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2PrepareSingleAssignPhase.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2SelectCreateEmptyPropertyPhase.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2SelectCreateNewPropertyPhase.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2SelectMultiplePropertyPhase.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2SelectSinglePropertyPhase.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2SelectUpdateEmptyPropertyPhase.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2SingleAssignDataPhase.h
phonebookui/Phonebook2/ServerApplication/inc/CPbk2SingleContactDataAssigner.h
phonebookui/Phonebook2/ServerApplication/inc/MPbk2ServicePhase.h
phonebookui/Phonebook2/ServerApplication/inc/MPbk2UiService.h
phonebookui/Phonebook2/ServerApplication/src/CPbk2AddressSelectPhase.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2AssignAttributePhase.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2AttributeAddressSelectPhase.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2CommAddressSelectPhase.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2ContactAttributeAssigner.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2ContactFetchPhase.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2EntryFetcher.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2FetchService.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2ItemFetcher.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2MultiAssignDataPhase.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2MultiContactDataAssigner.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2PrepareAttributeAssignPhase.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2PrepareSingleAssignPhase.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2SelectCreateEmptyPropertyPhase.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2SelectCreateNewPropertyPhase.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2SelectMultiplePropertyPhase.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2SelectSinglePropertyPhase.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2SelectUpdateEmptyPropertyPhase.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2SingleAssignDataPhase.cpp
phonebookui/Phonebook2/ServerApplication/src/CPbk2SingleContactDataAssigner.cpp
phonebookui/Phonebook2/ServerApplication/src/cpbk2preparemultipleassignphase.cpp
phonebookui/Phonebook2/UIControls/inc/CPbk2ContactEditorDlgImpl.h
phonebookui/Phonebook2/UIControls/inc/CPbk2ContactEditorUIAddressField.h
phonebookui/Phonebook2/UIControls/inc/CPbk2ContactViewListBox.h
phonebookui/Phonebook2/UIControls/inc/CPbk2FetchResults.h
phonebookui/Phonebook2/UIControls/inc/CPbk2NamesListEmptyState.h
phonebookui/Phonebook2/UIControls/inc/CPbk2NamesListFilteredState.h
phonebookui/Phonebook2/UIControls/inc/CPbk2SettingsListState.h
phonebookui/Phonebook2/UIControls/inc/cpbk2contactviewcustomlistboxdata.h
phonebookui/Phonebook2/UIControls/inc/cpbk2contactviewcustomlistboxitemdrawer.h
phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorDlgImpl.cpp
phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorImageField.cpp
phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorNewContact.cpp
phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorReadonlyField.cpp
phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorRingtoneField.cpp
phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorUIAddressField.cpp
phonebookui/Phonebook2/UIControls/src/CPbk2ContactViewListBox.cpp
phonebookui/Phonebook2/UIControls/src/CPbk2FetchDlg.cpp
phonebookui/Phonebook2/UIControls/src/CPbk2FetchResults.cpp
phonebookui/Phonebook2/UIControls/src/CPbk2MergeConflictsDlg.cpp
phonebookui/Phonebook2/UIControls/src/CPbk2NamesListControl.cpp
phonebookui/Phonebook2/UIControls/src/CPbk2NamesListEmptyState.cpp
phonebookui/Phonebook2/UIControls/src/CPbk2NamesListFilteredState.cpp
phonebookui/Phonebook2/UIControls/src/CPbk2NamesListReadyState.cpp
phonebookui/Phonebook2/UIControls/src/CPbk2SettingsListControl.cpp
phonebookui/Phonebook2/UIControls/src/CPbk2SettingsListState.cpp
phonebookui/Phonebook2/UIControls/src/Pbk2ImageCommands.cpp
phonebookui/Phonebook2/UIControls/src/cpbk2contacteditornewowncontact.cpp
phonebookui/Phonebook2/UIControls/src/cpbk2contactviewcustomlistboxdata.cpp
phonebookui/Phonebook2/UIControls/src/cpbk2contactviewcustomlistboxitemdrawer.cpp
phonebookui/Phonebook2/UIPolicy/inc/CPbk2ContactViewSortPolicy.h
phonebookui/Phonebook2/UIPolicy/src/CPbk2ContactViewSortPolicy.cpp
phonebookui/Phonebook2/USIMExtension/inc/CPsu2CopyToSimFieldInfoArray.h
phonebookui/Phonebook2/USIMExtension/rss/Pbk2USimSimCopy.rss
phonebookui/Phonebook2/USIMExtension/src/CPsu2CopyToSimCmd.cpp
phonebookui/Phonebook2/USIMExtension/src/CPsu2CopyToSimFieldInfoArray.cpp
phonebookui/Phonebook2/USIMExtension/src/CPsu2SimContactProcessor.cpp
phonebookui/Phonebook2/ccapplication/ccacommlauncherplugin/inc/ccappcommlaunchercontainer.h
phonebookui/Phonebook2/ccapplication/ccacommlauncherplugin/src/ccappcommlaunchercontainer.cpp
phonebookui/Phonebook2/ccapplication/ccacommlauncherplugin/src/ccappcommlaunchermenuhandler.cpp
phonebookui/Phonebook2/ccapplication/ccacommlauncherplugin/tsrc/ut_commlaunchercontacthandler/inc/ccappcommlauncherheaders.h
phonebookui/Phonebook2/ccapplication/ccadetailsviewplugin/src/ccappdetailsviewlistboxmodel.cpp
phonebookui/Phonebook2/ccapplication/inc/ccalogger.h
phonebookui/Phonebook2/conf/phonebook2.confml
phonebookui/Phonebook2/conf/phonebook2_101f8794.crml
phonebookui/Phonebook2/group/Pbk2CommandsExtension.mmp
phonebookui/Phonebook2/help/data/xhtml.zip
phonebookui/Phonebook2/inc/CPbk2FetchDlg.h
phonebookui/Phonebook2/inc/CPbk2NamesListControl.h
phonebookui/Phonebook2/inc/MPbk2FetchDlg.h
phonebookui/Phonebook2/inc/cpbk2commandactivator.h
phonebookui/Phonebook2/xSPExtensionManager/src/CxSPViewActivator.cpp
phonebookui/Speeddial/help/data/xhtml.zip
predictivesearch/PcsAlgorithm/Algorithm1/inc/CPcsAlgorithm1.h
predictivesearch/PcsAlgorithm/Algorithm1/src/CPcsAlgorithm1.cpp
predictivesearch/PcsAlgorithm/Algorithm2/group/PcsAlgorithm2.mmp
predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsAlgorithm2.h
predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsAlgorithm2FilterHelper.h
predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsAlgorithm2Helper.h
predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsAlgorithm2MultiSearchHelper.h
predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsAlgorithm2Utils.h
predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsCache.h
predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsKeyMap.h
predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsPoolElement.h
predictivesearch/PcsAlgorithm/Algorithm2/inc/FindUtilChineseECE.h
predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsAlgorithm2.cpp
predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsAlgorithm2FilterHelper.cpp
predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsAlgorithm2Helper.cpp
predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsAlgorithm2MultiSearchHelper.cpp
predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsAlgorithm2Utils.cpp
predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsCache.cpp
predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsKeyMap.cpp
predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsPoolElement.cpp
predictivesearch/PcsAlgorithm/Algorithm2/src/CPsDataPluginInterface.cpp
predictivesearch/PcsAlgorithm/Algorithm2/src/FindUtilChineseECE.cpp
predictivesearch/PcsAlgorithm/Algorithm2/src/chinesefindutils.cpp
predictivesearch/PcsServer/inc/CPcsServer.h
predictivesearch/PcsServer/src/CPcsServer.cpp
predictivesearch/PcsServer/src/CPcsSession.cpp
predictivesearch/adapters/contacts/inc/cpcscontactstore.h
predictivesearch/adapters/contacts/src/cpcscontactstore.cpp
--- a/contacts_plat/virtual_phonebook_configuration_api/inc/phonebook/VPbkVariant.hrh	Thu Jul 15 18:22:55 2010 +0300
+++ b/contacts_plat/virtual_phonebook_configuration_api/inc/phonebook/VPbkVariant.hrh	Thu Aug 19 09:41:07 2010 +0300
@@ -131,7 +131,12 @@
     /**
      * Show email addresses in Send Message address selection.
      */
-    EVPbkLVShowEmailInSendMsg = 0x00100000
+    EVPbkLVShowEmailInSendMsg = 0x00100000,
+    
+    /**
+     * Sync contact group during vCard sync.
+     */    
+    EVPbkLVSyncGroupEnabled = 0x00200000
 	};
 
 
--- a/contacts_plat/virtual_phonebook_store_api/inc/CVPbkContactOperationFactory.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/contacts_plat/virtual_phonebook_store_api/inc/CVPbkContactOperationFactory.h	Thu Aug 19 09:41:07 2010 +0300
@@ -22,8 +22,8 @@
 #define CVPBKCONTACTOPERATIONFACTORY_H
 
 #include <e32base.h>
-#include <mvpbkcontactoperationfactory.h>
-#include <mvpbkcontactoperationfactory2.h>
+#include <MVPbkContactOperationFactory.h>
+#include <MVPbkContactOperationFactory2.h>
 
 class MVPbkContactStoreList;
 
--- a/logsui/AppSrc/CLogsAppListView.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/logsui/AppSrc/CLogsAppListView.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -160,6 +160,17 @@
     
     // Just to make sure the inputblocker is not on
     RemoveInputBlocker();
+    
+    // Avoid the flicking when transfer to foreground from background.
+    if(LogsAppUi()->IsBackground())
+       {
+           iContainer->DrawNow();        
+           iEikonEnv->AppUiFactory()->StatusPane()->DrawNow();
+           LogsAppUi()->SetCustomControl(0); 
+       
+           CCoeEnv * env = CCoeEnv::Static();
+           env->WsSession().SetWindowGroupOrdinalPosition(env->RootWin().Identifier(),0); 
+       }
     }
 
 // ----------------------------------------------------------------------------
@@ -198,5 +209,17 @@
     }
 
 
+void CLogsAppListView::ViewActivatedL(const TVwsViewId& aPrevViewId,TUid aCustomMessageId,const TDesC8& aCustomMessage)
+    {
+    // To avoid the flicking when transfer to foreground from background,we control the view show manually.
+    if(LogsAppUi()->IsBackground()  &&
+            LogsAppUi()->ActiveViewId() != ELogAppListViewId)
+        {
+            LogsAppUi()->SetCustomControl(1);
+        }    
+    CLogsBaseView::ViewActivatedL(aPrevViewId,aCustomMessageId,aCustomMessage);
+    }
+
+
 //  End of File
 
--- a/logsui/AppSrc/CLogsAppListView.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/logsui/AppSrc/CLogsAppListView.h	Thu Aug 19 09:41:07 2010 +0300
@@ -97,6 +97,13 @@
          */
         void DoDeactivate();
 
+        /**
+         * Early detection of view activation.
+         * Overrides the baseclass implementation calls CAknView::ViewActivatedL().
+         */
+        void ViewActivatedL(const TVwsViewId& aPrevViewId,TUid aCustomMessageId,const TDesC8& aCustomMessage);
+
+
     public: // from MEikCommandObserver
         /**
          * HandleCommandL. Generic view commands.
--- a/logsui/AppSrc/CLogsAppUi.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/logsui/AppSrc/CLogsAppUi.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -1211,5 +1211,13 @@
     return 0;
     }
 
+    // If Logs is background,returns is True,otherwise False.
+    TBool CLogsAppUi::IsBackground() const
+      {
+        CCoeEnv * env = CCoeEnv::Static();
+        TInt ordinal = env->RootWin().OrdinalPosition();
+        return ordinal != 0;
+      }
+
 
 //  End of File
--- a/logsui/AppSrc/CLogsAppUi.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/logsui/AppSrc/CLogsAppUi.h	Thu Aug 19 09:41:07 2010 +0300
@@ -315,6 +315,11 @@
          */  
         void SetLogsOpenedWithSendKey(TBool aLogsOpenedWithSendKey);
 		
+        /**
+         *  Returns whether Logs is background.
+         */
+        TBool IsBackground() const;
+
 	public: // from MAknTabObserver
 		void TabChangedL(TInt aIndex);
 
--- a/logsui/AppSrc/CLogsBaseView.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/logsui/AppSrc/CLogsBaseView.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -587,8 +587,18 @@
                   aViewIdToBeDeactivated.iAppUid != TUid::Uid(KLogsAppUID3) )
             {
             // Reset array, will call StateChangedL with state EStateArrayReseted and update the listbox.
-            CurrentModel()->DoDeactivate( MLogsModel::ESkipClearing,
-                                          MLogsModel::EResetOnlyArray ); 
+            if ( (aNewlyActivatedViewId.iViewUid.iUid == EStmDialledListViewId )||
+                    (aNewlyActivatedViewId.iViewUid.iUid == EStmMissedListViewId )||
+                    (aNewlyActivatedViewId.iViewUid.iUid == EStmReceivedListViewId ))
+                {
+                CurrentModel()->DoDeactivate( MLogsModel::ESkipClearing,
+                                                          MLogsModel::EKeepDBConnection ); 
+                }
+            else
+                {
+                CurrentModel()->DoDeactivate( MLogsModel::ESkipClearing,
+                                                          MLogsModel::EResetOnlyArray ); 
+                }	
             DrawComponents();
             TRAP(err, CancelSaveToPbkL());
             }
--- a/logsui/AppSrc/CLogsRecentListView.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/logsui/AppSrc/CLogsRecentListView.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -428,11 +428,10 @@
          
         // Reset array and set dirty which means refresh requested, 
         // will call StateChangedL with state EStateArrayReseted and update the listbox.
+        // Keep db connection.
         CurrentModel()->DoDeactivate( MLogsModel::ESkipClearing,
-                                      MLogsModel::EResetOnlyArrayWithDirty );
+                                      MLogsModel::EKeepDBConnection );
      
-        // On gaining foreground, do a clean read of events
-        iResetAndRefreshOnGainingForeground = MLogsModel::EResetAndRefresh;
         }       
     
     CAknView::ViewDeactivated();
@@ -513,14 +512,22 @@
         // With MLogsModel::ECloseDBConnectionAndResetArray the connection to the database is
         // closed and event array will be deleted. Calls StateChangedL with state EStateArrayReseted 
         // which will update the listbox to empty state.
+        // Keep db connection
         CurrentModel()->DoDeactivate( MLogsModel::ENormalOperation,
-                                      MLogsModel::ECloseDBConnectionAndResetArray );
+                                      MLogsModel::EKeepDBConnection );
 
+        CurrentModel()->DoActivateL( MLogsModel::EResetAndRefresh );
         // Now we can enable bring-to-foreground on view activation:
         AppUi()->SetCustomControl(0); 
         AppUi()->HideInBackground(); 
-        // When coming back to foreground, do a clean read of events
-        iResetAndRefreshOnGainingForeground = MLogsModel::EResetAndRefresh; 
+        // If listbox needs to redraw,do it.
+        if( CurrentModel()->Count()>0 && 
+              ( iContainer->ListBox()->TopItemIndex() != EventListTop() ||
+                  iContainer->ListBox()->CurrentItemIndex() != EventListCurrent())) 
+             {
+                iContainer->ListBox()->DrawDeferred();
+             }
+       
         }
     else
         {
@@ -540,11 +547,19 @@
             logsui.KillTask();  
             return;	
             }
-        
-        // By default on gaining foreground, just refresh the list. So when active applications list, 
-        // keylock or some note (like when plugin in the charger) is shown the list doesn't flicker. 
-        // When view is deactivated this is set to MLogsModel::EResetAndRefresh.
-        iResetAndRefreshOnGainingForeground = MLogsModel::ERefresh; 
+         
+        // Avoid the flicking when transfer to foreground from background.
+        if(LogsAppUi()->IsBackground())
+          {
+              iContainer->DrawNow();         
+              iEikonEnv->AppUiFactory()->StatusPane()->DrawNow(); 
+              LogsAppUi()->SetCustomControl(0);  
+          
+              CCoeEnv * env = CCoeEnv::Static();
+              env->WsSession().SetWindowGroupOrdinalPosition(env->RootWin().Identifier(),0);
+                            
+           }   
+
         }
     
     
@@ -644,8 +659,9 @@
             LOGS_DEBUG_PRINT(LOGS_DEBUG_STRING
                     ( "CLogsRecentListView::DoDeactivate - ReadingFinished" ));  
             ClearMissedCallNotifications();   //Clear cenrep new missed calls counter + notifications          
+            // Keep db connection
             CurrentModel()->DoDeactivate( MLogsModel::ENormalOperation,
-                                          MLogsModel::ECloseDBConnection );//ETrue: disconnect from db. This helps for EMSH-6JDFBV but
+                                          MLogsModel::EKeepDBConnection );//ETrue: disconnect from db. This helps for EMSH-6JDFBV but
                                               //reduces user's perceived performance for other views
                                               //(seems to keep clearing of missed duplicates process alive
                                               // so no need for EFalse here as it would increase probability of 
@@ -657,14 +673,15 @@
             {
             LOGS_DEBUG_PRINT(LOGS_DEBUG_STRING
                     ( "CLogsRecentListView::DoDeactivate - Reading interrupted" )); 
+            // Keep db connection
             CurrentModel()->DoDeactivate( MLogsModel::ESkipClearing,
-                                          MLogsModel::ECloseDBConnection );
+                                          MLogsModel::EKeepDBConnection );
             }    
         }
     else
         {
         CurrentModel()->DoDeactivate( MLogsModel::ENormalOperation,
-                                      MLogsModel::ECloseDBConnection );//ETrue: disconnect from db. This helps for EMSH-6JDFBV but
+                                      MLogsModel::EKeepDBConnection );//ETrue: disconnect from db. This helps for EMSH-6JDFBV but
                                               //reduces user's perceived performance for other views
                                               //EFalse: don't disconnect from db. This keeps read data cached in Logs.
         }
@@ -854,28 +871,7 @@
                     {
                     MenuBar()->StopDisplayingMenuBar();
                     }
-                
-                SetEventListCurrent( KErrNotFound );//just to make sure that UI does not try to read anything from eventarray                
-                TRAPD( err, model->DoActivateL( iResetAndRefreshOnGainingForeground ) );  
-                if( err ) 
-                    {
-                    iCoeEnv->HandleError( err );
-                    }
-                if( err == KErrDiskFull )
-                    {
-                    RWsSession& wsSession = CCoeEnv::Static()->WsSession();  
-                    TApaTask logsui( wsSession );
-                    TInt wgId = CCoeEnv::Static()->RootWin().WindowGroupId();
-                    logsui.SetWgId( wgId );
-                    logsui.KillTask();  
-                    return;
-                    }
-                
-                // By default on gaining foreground, just refresh the list. So when active applications list, 
-                // keylock or some note (like when plugin in the charger) is shown the list doesn't flicker. 
-                // When view is deactivated this is set to MLogsModel::EResetAndRefresh.
-                iResetAndRefreshOnGainingForeground = MLogsModel::ERefresh;
-                }
+                 }
             else
                 {
                 // Change ELogsNoChange_PbkUpdPending to ELogsNoChange now so there is no need to 
@@ -883,6 +879,8 @@
                 iFocusChangeControl = ELogsNoChange;
                 }
             }
+        // Sure "ClearMissedCallNotificationsL" is called.
+        ClearMissedCallNotificationsL();
         
         RemoveInputBlocker(); //just in case
         }                            
@@ -993,16 +991,18 @@
                 {
                  LOGS_DEBUG_PRINT(LOGS_DEBUG_STRING
                     ( "CLogsRecentListView::HandleLosingForeground - clear duplicates" ));      
+                 // Keep db connection
                 model->DoDeactivate( MLogsModel::ENormalOperation, 
-                                     MLogsModel::ECloseDBConnection );    //EFalse: don't disconnect from db 
+                                     MLogsModel::EKeepDBConnection );    //EFalse: don't disconnect from db 
                 }
             else    
                 {
                 LOGS_DEBUG_PRINT(LOGS_DEBUG_STRING
                     ( "CLogsRecentListView::HandleLosingForeground - skip clearing" )); 
                 //Other loss of foreground (call or AppKey). We'll not touch duplicate counters
+                // Keep db connection
                 model->DoDeactivate( MLogsModel::ESkipClearing, //Don't update db (for missed view)
-                                     MLogsModel::ECloseDBConnection );    //ETrue: disconnect from db in order to immediately to stop
+                                     MLogsModel::EKeepDBConnection );    //ETrue: disconnect from db in order to immediately to stop
                                                  //EFalse: don't disconnect from db                                     
                 }
             }
@@ -1094,7 +1094,9 @@
             iContainer->ControlExtension()->HandleAdditionalData( 
                 *CurrentModel(), 
                 *iContainer->ListBox() );
-            ClearMissedCallNotificationsL();
+            // Add condition check: To avoid Missing Call Note don't display ,do not call "ClearMissedCallNotificationsL" when logs is in background.
+            if(!LogsAppUi()->IsBackground())
+                ClearMissedCallNotificationsL();
             // When event reading is finished, remove inputblocker
             RemoveInputBlocker();
             }        
@@ -1271,5 +1273,17 @@
     return result;    
     }
 
+void CLogsRecentListView::ViewActivatedL(const TVwsViewId& aPrevViewId,TUid aCustomMessageId,const TDesC8& aCustomMessage)
+    {
+    //To avoid the flicking when transfer to foreground from background,we control the view show manually.
+    if(LogsAppUi()->IsBackground()  &&     
+             LogsAppUi()->ActiveViewId() != LogsCurrentRecentViewId() )
+        {
+            LogsAppUi()->SetCustomControl(1);
+        }      
+    
+      CLogsBaseView::ViewActivatedL(aPrevViewId,aCustomMessageId,aCustomMessage);
+      
+    }
 
 //  End of File  
--- a/logsui/AppSrc/CLogsRecentListView.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/logsui/AppSrc/CLogsRecentListView.h	Thu Aug 19 09:41:07 2010 +0300
@@ -227,6 +227,11 @@
         */
         TBool IgnoreViewDeactivatedOperation();
     
+        /**
+         * Early detection of view activation.
+         * Overrides the baseclass implementation calls CAknView::ViewActivatedL().
+         */
+        void ViewActivatedL(const TVwsViewId& aPrevViewId,TUid aCustomMessageId,const TDesC8& aCustomMessage);
     
     private:    // Data
         /// Own: view's control container
--- a/logsui/group/Logs.mmp	Thu Jul 15 18:22:55 2010 +0300
+++ b/logsui/group/Logs.mmp	Thu Aug 19 09:41:07 2010 +0300
@@ -31,6 +31,7 @@
 TARGETTYPE      exe
 EPOCSTACKSIZE   0x2710  //10000dec (default is 8000dec). In new architecture we need some more stack to 
                         //facilitate succesfull launching of editors (e.g. prepend number and send sms editors)
+EPOCHEAPSIZE 0x1000 0x200000
 UID             0x100039CE KLogsAppUID3
 VENDORID        VID_DEFAULT
 
Binary file logsui/help/data/xhtml.zip has changed
--- a/phonebookengines/VirtualPhonebook/VPbkCntModel/src/CCustomFilteredGroupView.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkCntModel/src/CCustomFilteredGroupView.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -195,7 +195,7 @@
 	{
 	TBool ret = EFalse;
 	
-	for ( TInt i=0; i < aMemberCount; ++i )
+	for ( TInt i=0; i < aMemberCount && !ret; ++i )
 		{
         const TContactItemId contactId = ( *aGroupMembers )[i];
         CContactItem* item = iContactStore.NativeDatabase().
--- a/phonebookengines/VirtualPhonebook/VPbkCntModel/src/CFilteredContactView.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkCntModel/src/CFilteredContactView.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -145,14 +145,8 @@
             for ( TInt matchPriority = 0;
                  matchPriority <= maxMatchPriority; ++matchPriority )
                 {
-                TBool versitIsMatched = matchingProperty->Matches(
-                       aFilterType->VersitProperties()[matchPriority]);
-                TBool excludedParmaterIsMatched =
-                       aFilterType->ExcludedParameters().
-                           ContainsAll(aFieldType.ExcludedParameters());
-                // if the FilterType is matched the Versit Property and
-                // the excludeParameter of FiledType, it needn't custom filter.
-                if ( versitIsMatched && excludedParmaterIsMatched )
+                if ( matchingProperty->Matches(
+                    aFilterType->VersitProperties()[matchPriority]) )
                     {
                     ret = EFalse;
                     break;
--- a/phonebookengines/VirtualPhonebook/VPbkCntModel/src/CViewContact.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkCntModel/src/CViewContact.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -200,7 +200,8 @@
 void CViewContactFieldCollection::SetFieldsData(
         const ::CViewContact& aViewContact )
     {
-    const TInt count = aViewContact.FieldCount();
+    const TInt count = aViewContact.FieldCount()<iFields.Count()?
+        aViewContact.FieldCount():iFields.Count();
     for (TInt i = 0; i < count; ++i)
         {
         iFields[i].SetFieldData(aViewContact.Field(i));
--- a/phonebookengines/VirtualPhonebook/VPbkCntModel/src/TContactFieldDataImpl.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkCntModel/src/TContactFieldDataImpl.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -176,7 +176,19 @@
                User::Leave(KErrNotSupported);
                }
             }
-        
+        else // If it is an IMPP field
+            {
+            TInt pos = aUri.Find(KColon);
+            // If the service name or the colon doesn't exist, let it leave the function.
+            // e.g.:
+            // (1) If the value is YAHOO:peterpan@yahoo.com, YAHOO is the service name
+            // (2) If the value is :peterpan@yahoo.com, the service name is NULL
+            // (3) If the value is peterpan@yahoo.com, neither the service name and the colon exists
+            if( 0 == pos || KErrNotFound == pos )
+                {
+                User::Leave(KErrNotSupported);
+                }
+            }
         }
     iCntModelField->TextStorage()->SetTextL(aUri);
     }
--- a/phonebookengines/VirtualPhonebook/VPbkEng/src/CVPbkPhoneNumberMatchStrategy.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkEng/src/CVPbkPhoneNumberMatchStrategy.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -42,7 +42,14 @@
 
 #include "CVPbkPhoneNumberSequentialMatchStrategy.h"
 #include "CVPbkPhoneNumberParallelMatchStrategy.h"
+#include "CVPbkETelCntConverter.h"
 
+#include <cntdb.h>
+#include <ecom/ecom.h>
+
+#ifdef SYMBIAN_ENABLE_SPLIT_HEADERS
+#include <cntphonenumparser.h>
+#endif
 // CONSTANTS
 // Unnamed namespace for local definitions
 namespace {
@@ -162,6 +169,11 @@
         */
         void RefineDuplicatedNumbersL();
         
+        /**
+         * Load number parser plugin.
+        */
+        void LoadNumberParserPluginL();
+        
     private: // Data
         CVPbkPhoneNumberMatchStrategy& iParent;
         /// Ref: The contact manager instance to be used for searching.
@@ -210,6 +222,8 @@
         TBool iDoubledContacts;
         /// type of iPhoneNumber
         TNumberType iPhoneNumberType;
+        // Own: parser
+        CContactPhoneNumberParser* iParser;
     };
 
 CVPbkPhoneNumberMatchStrategyImpl::CVPbkPhoneNumberMatchStrategyImpl(
@@ -268,6 +282,8 @@
     	}
 
     CleanupStack::PopAndDestroy( &resFile );
+    
+    LoadNumberParserPluginL();
     }
 
 CVPbkPhoneNumberMatchStrategyImpl* CVPbkPhoneNumberMatchStrategyImpl::NewL(
@@ -300,6 +316,8 @@
     iNameTokensArray.ResetAndDestroy();
     iTempNameTokensArray.ResetAndDestroy();
     iStoresToMatch.Close();
+    delete iParser;
+    REComSession::FinalClose();
     }
 
 void CVPbkPhoneNumberMatchStrategyImpl::MatchL(const TDesC& aPhoneNumber)
@@ -762,21 +780,30 @@
     _LIT( KOneZeroPattern, "0*" );
     _LIT( KTwoZerosPattern, "00*" );
     _LIT( KPlusPattern, "+*" );
+    _LIT( KPlusString, "+" );
     const TChar KPlus = TChar('+');
     const TChar KZero = TChar('0');
     const TChar KAsterisk = TChar('*');
     const TChar KHash = TChar('#');
     
-    for( TInt pos = 0; pos < aNumber.Length(); ++pos )
+    HBufC* numberBuf = HBufC::NewL( aNumber.Length() );
+    TPtr number = numberBuf->Des();
+    if ( iParser )
         {
-        TChar chr = aNumber[pos];
-        if ( !chr.IsDigit() && !( pos == 0 && chr == KPlus  )
-                && !( chr == KAsterisk ) && !( chr == KHash ) )
-            {
-            aNumber.Delete( pos, 1 );
-            --pos;
-            }
+        iParser->ExtractRawNumber( aNumber, number );
         }
+    TInt pos = aNumber.Find( number );
+    
+    if ( pos > 0 && aNumber[pos-1] == KPlus )
+        {
+        number.Insert( 0, KPlusString );
+        }
+    
+    if ( number.Length() > 0)
+        {
+        aNumber.Copy( number );
+        }
+    delete numberBuf;
     
 	TInt format;
 	
@@ -1108,6 +1135,21 @@
     return EFalse;
     }
 
+void CVPbkPhoneNumberMatchStrategyImpl::LoadNumberParserPluginL()
+    {    
+    RImplInfoPtrArray   implInfoArray;
+    CleanupResetAndDestroyPushL( implInfoArray );
+    REComSession::ListImplementationsL( KUidEcomCntPhoneNumberParserInterface, 
+                                        implInfoArray );
+    // Load the first implementation found for KUidEcomCntPhoneNumberParserInterface 
+    const TInt count = implInfoArray.Count();
+    __ASSERT_ALWAYS( count > 0, User::Leave( KErrNotFound ) );
+    const TUid firstImplementationFound = implInfoArray[0]->ImplementationUid();
+    iParser = reinterpret_cast<CContactPhoneNumberParser*> 
+        ( CContactEcomPhoneNumberParser::NewL( firstImplementationFound ) );
+    CleanupStack::PopAndDestroy( &implInfoArray );
+    }
+
 CVPbkPhoneNumberMatchStrategy::CVPbkPhoneNumberMatchStrategy()
     {
     }
--- a/phonebookengines/VirtualPhonebook/VPbkSimStore/inc/CContact.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkSimStore/inc/CContact.h	Thu Aug 19 09:41:07 2010 +0300
@@ -233,6 +233,20 @@
         /// Resets the contact state after contact operation
         void ResetContactOperationState();
         
+        /**
+        * Remove empty field from aSimContact, these empty field was added 
+        * in the sim contact before save it to keep the order of additional 
+        * numbers in the USIM card. 
+        */
+        void RemoveAllEmptyFields( CVPbkSimContact& aSimContact );
+        
+        /**
+        * Fill some empty field in the sim contact. hese empty field was added 
+        * in the sim contact before save it to keep the order of additional 
+        * numbers in the USIM card. 
+        */
+        void FillWithEmptyFieldsL() const;
+               
     private:  // Data
 
         TStoreContactFieldCollection iFields;
--- a/phonebookengines/VirtualPhonebook/VPbkSimStore/inc/CSupportedFieldTypes.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkSimStore/inc/CSupportedFieldTypes.h	Thu Aug 19 09:41:07 2010 +0300
@@ -26,6 +26,7 @@
 
 // FORWARD DECLARATIONS
 struct TVPbkGsmStoreProperty;
+struct TVPbkUSimStoreProperty;  
 
 namespace VPbkSimStore {
 
@@ -52,6 +53,15 @@
         static CSupportedFieldTypes* NewL(
             const CFieldTypeMappings& aFieldTypeMappings,
             TVPbkGsmStoreProperty& aSimStoreProperty );
+        /**
+        * Two-phased constructor.
+        * @param aSimStoreProperty sim store properties
+        * @return a new instance of this class
+        */
+        static CSupportedFieldTypes* NewL(
+            const CFieldTypeMappings& aFieldTypeMappings,
+            TVPbkGsmStoreProperty& aSimStoreProperty,
+            TVPbkUSimStoreProperty& aUSimStoreProperty ); 
         
         /**
         * Destructor.
@@ -109,7 +119,8 @@
         * By default Symbian 2nd phase constructor is private.
         */
         void ConstructL( const CFieldTypeMappings& aFieldTypeMappings,
-            TVPbkGsmStoreProperty& aSimStoreProperty );
+            TVPbkGsmStoreProperty& aSimStoreProperty,
+            TVPbkUSimStoreProperty* aUSimStoreProperty = NULL ); 
 
     private:    // Data
         ///Ref: An array for the supported types. Doesn't own types
--- a/phonebookengines/VirtualPhonebook/VPbkSimStore/rss/VPbkSimStoreRes.rss	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkSimStore/rss/VPbkSimStoreRes.rss	Thu Aug 19 09:41:07 2010 +0300
@@ -105,4 +105,107 @@
         };
     }
 
+//  For USIM with additional numbers
+RESOURCE FIELDTYPE_MAPPINGS r_vpbk_usim_versit_field_type_mappings
+	{
+	items =
+	        {
+	        // SIM name = Last name
+	        VERSIT_FIELDTYPE_MAPPING
+	            {
+	            simFieldId = EVPbkSimName;
+	            versitProperty = VBK_FIELD_VERSIT_PROPERTY
+	                {
+	                name = EVPbkVersitNameN;
+	                subField = EVPbkVersitSubFieldFamilyName;
+	                };
+	            },
+	        // USIM second name = reading in japanese variant
+	        VERSIT_FIELDTYPE_MAPPING
+	            {
+	            simFieldId = EVPbkSimReading;
+	            versitProperty = VBK_FIELD_VERSIT_PROPERTY
+	                {
+	                name = EVPbkVersitNameSOUND;
+	                subField = EVPbkVersitSubFieldFamilyNamePronunciation;
+	                };
+	            },
+	        // SIM GSM number = general mobile
+	        VERSIT_FIELDTYPE_MAPPING
+	            {
+	            simFieldId = EVPbkSimGsmNumber;
+	            versitProperty = VBK_FIELD_VERSIT_PROPERTY
+	                {
+	                name = EVPbkVersitNameTEL;
+	                parameters = { EVPbkVersitParamCELL };
+	                };
+	            },
+	        // USIM additional numbers = general mobile
+	        VERSIT_FIELDTYPE_MAPPING
+	            {
+	            simFieldId = EVPbkSimAdditionalNumber;
+	            versitProperty = VBK_FIELD_VERSIT_PROPERTY
+	                {
+	                name = EVPbkVersitNameTEL;
+	                parameters = { EVPbkVersitParamCELL };
+	                };
+	            },
+	        // USIM additional numbers = home landphone 
+	        VERSIT_FIELDTYPE_MAPPING
+	            {
+	            simFieldId = EVPbkSimAdditionalNumber1;
+	            versitProperty = VBK_FIELD_VERSIT_PROPERTY
+	                {
+	                name = EVPbkVersitNameTEL;
+	                parameters = { EVPbkVersitParamHOME };
+	                };
+	            },
+	        // USIM additional numbers = work landphone 
+	        VERSIT_FIELDTYPE_MAPPING
+	            {
+	            simFieldId = EVPbkSimAdditionalNumber2;
+	            versitProperty = VBK_FIELD_VERSIT_PROPERTY
+	                {
+	                name = EVPbkVersitNameTEL;
+	                parameters = { EVPbkVersitParamWORK };
+	                };
+	            },
+	        // USIM additional numbers = general fax
+	        VERSIT_FIELDTYPE_MAPPING
+	            {
+	            simFieldId = EVPbkSimAdditionalNumber3;
+	            versitProperty = VBK_FIELD_VERSIT_PROPERTY
+	                {
+	                name = EVPbkVersitNameTEL;
+	                parameters = { EVPbkVersitParamFAX };
+	                };
+	            },
+	        /*you can define more field type mappings here to adapt the
+	         * increase of the additional number field of USIM card.*/
+	        // USIM email = general email
+	        VERSIT_FIELDTYPE_MAPPING
+	            {
+	            simFieldId = EVPbkSimEMailAddress;
+	            versitProperty = VBK_FIELD_VERSIT_PROPERTY
+	                {
+	                name = EVPbkVersitNameEMAIL;
+	                parameters = 
+	                    {
+	                    EVPbkVersitParamINTERNET
+	                    };
+	                };
+	            },
+	        // USIM second name = nick name in variants other than japan
+	        VERSIT_FIELDTYPE_MAPPING
+	            {
+	            simFieldId = EVPbkSimNickName;
+	            versitProperty = VBK_FIELD_VERSIT_PROPERTY
+	                {
+	                name = EVPbkVersitNameX;
+	                extensionName = "X-NICKNAME";
+	                };
+	            }
+	        };
+	}
+
 // End of File
--- a/phonebookengines/VirtualPhonebook/VPbkSimStore/src/CContact.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkSimStore/src/CContact.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -30,6 +30,8 @@
 #include <CVPbkAsyncOperation.h>
 #include <CVPbkContactLinkArray.h>
 #include <CVPbkSimContact.h>
+#include <CVPbkSimCntField.h>
+#include <featmgr.h>
 #include <MVPbkSimCntStore.h>
 #include <MVPbkContactViewBase.h>
 #include <MVPbkContactStoreProperties.h>
@@ -48,6 +50,8 @@
     KNewContact = 1
     };
 
+const TInt KDefinedAnrFieldTypeCount = 3;   // count of defined additional number types
+
 // ============================= LOCAL FUNCTIONS ===============================
 
 MVPbkContactObserver::TContactOp ConvertContactOperation(
@@ -98,15 +102,35 @@
             break;
             }
         case EVPbkSimGsmNumber: // FALLTHROUGH
-        case EVPbkSimAdditionalNumber:
+        case EVPbkSimAdditionalNumberLast:    // the EVPbkSimAdditionalNumber
             {
             ++result; // always at least one number
             if ( aUsimProp.iMaxNumOfAnrs != KVPbkSimStorePropertyUndefined )
                 {
-                result += aUsimProp.iMaxNumOfAnrs;
+                if ( !FeatureManager::FeatureSupported(
+                             KFeatureIdFfTdClmcontactreplicationfromphonebooktousimcard ) )
+                    {
+                    result += aUsimProp.iMaxNumOfAnrs;
+                    }
+                else
+                    {
+                    if ( aUsimProp.iMaxNumOfAnrs - KDefinedAnrFieldTypeCount > 0 )
+                        {
+                        result += (aUsimProp.iMaxNumOfAnrs - KDefinedAnrFieldTypeCount);
+                        }
+                    }
                 }
             break;
             }
+        case EVPbkSimAdditionalNumber1:
+            result = aUsimProp.iMaxNumOfAnrs >= 1 ? 1 : 0;   // according the max number of anrs.
+            break;
+        case EVPbkSimAdditionalNumber2:
+            result = aUsimProp.iMaxNumOfAnrs >= 2 ? 1 : 0;
+            break;
+        case EVPbkSimAdditionalNumber3:
+            result = aUsimProp.iMaxNumOfAnrs >= 3 ? 1 : 0;	
+            break;
         default:
             {
             // Do nothing
@@ -119,6 +143,7 @@
 
 namespace VPbkSimStore {
 
+_LIT( KEmptyData, "+" );    //the empty data, modifiy this string to keep its a special string.
 // ============================ MEMBER FUNCTIONS ===============================
 
 // -----------------------------------------------------------------------------
@@ -144,6 +169,11 @@
         {
         iFlags.Set( KNewContact );
         }
+    if( FeatureManager::FeatureSupported( 
+                        KFeatureIdFfTdClmcontactreplicationfromphonebooktousimcard ) )
+        {
+        RemoveAllEmptyFields( aSimContact );    //  remove the empty contacts where added before save.
+        }
     iFields.SetContact( *this, aSimContact );
     iAsyncOp = new( ELeave ) VPbkEngUtils::CVPbkAsyncOperation;
     }
@@ -174,6 +204,126 @@
     }
 
 // -----------------------------------------------------------------------------
+// CContact::RemoveAllEmptyFields
+// -----------------------------------------------------------------------------
+//
+void CContact::RemoveAllEmptyFields( CVPbkSimContact& aSimContact )
+    {
+    TInt i = aSimContact.FieldCount() - 1 ;
+    while( i >= 0 )
+        {
+		CVPbkSimCntField& cntField = aSimContact.FieldAt( i );
+		TVPbkSimCntFieldType simCntType = cntField.Type();
+        if( simCntType ==  EVPbkSimGsmNumber
+		    || simCntType == EVPbkSimAdditionalNumber1
+			|| simCntType == EVPbkSimAdditionalNumber2
+			|| simCntType == EVPbkSimAdditionalNumber3
+			|| simCntType == EVPbkSimAdditionalNumberLast )
+        	{
+			if( cntField. Data().Compare( KEmptyData ) == 0 )
+				{
+				aSimContact.DeleteField( i );
+				}
+        	}
+        i --;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CContact::FillWithEmptyFieldsL
+// -----------------------------------------------------------------------------
+//
+void CContact::FillWithEmptyFieldsL() const
+    {
+    RPointerArray<CVPbkSimCntField> & contactFieldArray = iSimContact->FieldArray();
+    TInt i = contactFieldArray.Count() - 1 ;
+	while( i >= 0 ) // remove all empty content.
+		{
+		CVPbkSimCntField& cntField = iSimContact->FieldAt( i );
+		TVPbkSimCntFieldType type = cntField.Type();
+		if( cntField. Data().Length() == 0 )
+			{
+			iSimContact->DeleteField( i );
+			}
+		i --;
+		}
+	
+    if( contactFieldArray.Count() == 0 )  // no un-empty fields.
+        {
+        return;
+        }
+    CVPbkSimContact::TFieldLookup lookupAdnNumber = 
+                       iSimContact->FindField( EVPbkSimAdditionalNumber );  
+    if( lookupAdnNumber.EndOfLookup())  // if there is no additional number in the contact then no need to add placeholder
+    	{
+		return;
+    	}
+    RPointerArray<CVPbkSimCntField> tempFieldArray;
+    CleanupClosePushL( tempFieldArray );
+    // mappings 
+    CFieldTypeMappings & mappings = iParentStore.FieldTypeMappings();
+    // supported types.
+    const CSupportedFieldTypes& supportedTypes = iParentStore.SupportedFieldTypes();
+
+    // check all supported field types in the fields list. If not exist created new.
+    // if data length is 0, set data to empty data.
+    for( int i = 0; i < supportedTypes.FieldTypeCount(); i ++ )
+        {
+        const MVPbkFieldType& fieldType = supportedTypes.FieldTypeAt( i );
+        TVPbkSimCntFieldType simCntType = mappings.Match( fieldType );
+        if( simCntType ==  EVPbkSimGsmNumber
+		    || simCntType == EVPbkSimAdditionalNumber1
+			|| simCntType == EVPbkSimAdditionalNumber2
+			|| simCntType == EVPbkSimAdditionalNumber3
+			|| simCntType == EVPbkSimAdditionalNumberLast )
+            {
+            CVPbkSimCntField * field = NULL;
+            CVPbkSimContact::TFieldLookup lookup = 
+                   iSimContact->FindField( simCntType );
+
+            if( lookup.EndOfLookup() )
+                {
+                field= iSimContact->CreateFieldLC( simCntType );
+                field->SetDataL( KEmptyData );
+                tempFieldArray.Append( field );
+                CleanupStack::Pop();
+                }
+             else
+                {
+                field = contactFieldArray[lookup.Index()];
+                if( field->Data().Length() == 0 )
+                    {
+                    field->SetDataL( KEmptyData );
+                    }
+                if( simCntType == EVPbkSimAdditionalNumber1 
+                    || simCntType == EVPbkSimAdditionalNumber2
+                    || simCntType == EVPbkSimAdditionalNumber3 )
+                    {
+                    contactFieldArray.Remove( lookup.Index() );
+                    tempFieldArray.AppendL( field );
+                    }
+                }
+            }
+        }
+    TInt j = contactFieldArray.Count() - 1;
+    while( j >= 0 )  //  EVPbkSimAdditionalNumberLast type field will append at last.
+        {
+        if( contactFieldArray[j]->Type() == EVPbkSimAdditionalNumberLast )
+            {
+            tempFieldArray.AppendL( contactFieldArray[ j ] );
+            contactFieldArray.Remove( j );
+            }
+        j --;
+        }
+    for( int i = 0; i < tempFieldArray.Count(); i ++ )
+        {
+        contactFieldArray.AppendL( tempFieldArray[i]);
+        }
+    tempFieldArray.Reset();
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
 // CContact::ParentObject
 // -----------------------------------------------------------------------------
 //
@@ -301,7 +451,7 @@
         VPbkSimStore::Panic( ESimFieldTypeNotFound ) );
 
     if ( simType == EVPbkSimGsmNumber || 
-         simType == EVPbkSimAdditionalNumber )
+         simType == EVPbkSimAdditionalNumberLast )  //the same field type as EVPbkSimGsmNumber
         {
         // EVPbkSimGsmNumber and EVPbkSimAdditionalNumber maps to same
         // VPbk field type. A sim contact can have only one EVPbkSimGsmNumber
@@ -320,7 +470,7 @@
             }
         else
             {
-            simType = EVPbkSimAdditionalNumber;
+            simType = EVPbkSimAdditionalNumberLast; 
             }
         }
 
@@ -421,6 +571,10 @@
             }
         // From the client point of view the MVPbkStoreContact is constant but
         // implementation needs a non const contact.
+        if( FeatureManager::FeatureSupported( KFeatureIdFfTdClmcontactreplicationfromphonebooktousimcard ) )
+            {
+            FillWithEmptyFieldsL();
+            }
         iStoreOperation = iSimContact->SaveL( const_cast<CContact&>( *this ));
         iObserver = &aObserver;
         }
@@ -498,6 +652,12 @@
     
     MVPbkContactObserver* observer = iObserver;
     ResetContactOperationState();
+    
+    // remove filled placeholder fields.
+    if( vpbkOpResult.iOpCode == MVPbkContactObserver::EContactCommit )
+    	{
+		RemoveAllEmptyFields( *iSimContact );
+    	}
     observer->ContactOperationCompleted( vpbkOpResult );
     }
 
@@ -516,6 +676,12 @@
     MVPbkContactObserver* observer = iObserver;
     ResetContactOperationState();
     MVPbkContactObserver::TContactOp op = ConvertContactOperation( aEvent );
+    
+    // remove filled placeholder fields.
+    if( op == MVPbkContactObserver::EContactCommit )
+    	{
+		RemoveAllEmptyFields( *iSimContact );
+    	}
     observer->ContactOperationFailed( op, aError, EFalse );
     } 
 
--- a/phonebookengines/VirtualPhonebook/VPbkSimStore/src/CContactStore.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkSimStore/src/CContactStore.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -48,6 +48,7 @@
 #include <VPbkSimStoreTemplateFunctions.h>
 #include <CVPbkAsyncCallback.h>
 
+#include <featmgr.h>  
 namespace VPbkSimStore {
 
 // LOCAL
@@ -580,17 +581,38 @@
 void CContactStore::StoreReady( MVPbkSimCntStore& /*aStore*/ )
     {
     TVPbkGsmStoreProperty gsmProperties;
-    TInt res = iNativeStore->GetGsmStoreProperties( gsmProperties );
-
-    if ( res == KErrNone )
+    TInt res = KErrNone;  
+    if( !FeatureManager::FeatureSupported( KFeatureIdFfTdClmcontactreplicationfromphonebooktousimcard ) )
+        {
+        res= iNativeStore->GetGsmStoreProperties( gsmProperties );
+        if ( res == KErrNone )
+            {
+            delete iSupportedFieldTypes;
+            iSupportedFieldTypes = NULL;
+            TRAP( res, iSupportedFieldTypes = CSupportedFieldTypes::NewL(
+                    iStoreDomain.FieldTypeMappings(), gsmProperties ) );
+                    iSimStoreCapabilities = gsmProperties.iCaps;
+            }
+        }
+    else  // if contact replication from phonebook to usim card.
         {
-        delete iSupportedFieldTypes;
-        iSupportedFieldTypes = NULL;
-        TRAP( res, iSupportedFieldTypes = CSupportedFieldTypes::NewL(
-            iStoreDomain.FieldTypeMappings(), gsmProperties ) );
-        iSimStoreCapabilities = gsmProperties.iCaps;
+        TInt resGsm = iNativeStore->GetGsmStoreProperties( gsmProperties );
+        TVPbkUSimStoreProperty usimProperties;
+        TInt resUsim = iNativeStore->GetUSimStoreProperties( usimProperties );	
+        if( resGsm == KErrNone && resUsim == KErrNone )
+            {
+            delete iSupportedFieldTypes;
+            iSupportedFieldTypes = NULL;
+            TRAP( res, iSupportedFieldTypes = CSupportedFieldTypes::NewL(
+                    iStoreDomain.FieldTypeMappings(), gsmProperties, usimProperties ) ); 
+                    iSimStoreCapabilities = gsmProperties.iCaps;
+            }
+        else
+            {
+            res = ( resGsm != KErrNone ? resGsm : resUsim );
+            }
         }
-
+   
     if ( res != KErrNone )
         {
         iStoreState = EStoreNotAvailable;
--- a/phonebookengines/VirtualPhonebook/VPbkSimStore/src/CContactStoreDomain.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkSimStore/src/CContactStoreDomain.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -36,6 +36,7 @@
 
 #include <barsc.h>
 #include <barsread.h>
+#include <featmgr.h>
 
 namespace VPbkSimStore {
 
@@ -80,10 +81,20 @@
     
     VPbkEngUtils::RLocalizedResourceFile resFile;
     resFile.OpenLC( iFs, KVPbkRomFileDrive, KDC_RESOURCE_FILES_DIR, KResFile );
-    
+    FeatureManager::InitializeLibL();
     TResourceReader resReader;
-    resReader.SetBuffer( resFile.AllocReadLC( 
-        R_VPBK_VERSIT_FIELD_TYPE_MAPPINGS ) );
+    
+    if ( !FeatureManager::FeatureSupported(
+            KFeatureIdFfTdClmcontactreplicationfromphonebooktousimcard ) )
+        {
+        resReader.SetBuffer( resFile.AllocReadLC(
+                R_VPBK_VERSIT_FIELD_TYPE_MAPPINGS ) );
+        }
+    else
+        {
+        resReader.SetBuffer( resFile.AllocReadLC(
+                R_VPBK_USIM_VERSIT_FIELD_TYPE_MAPPINGS ) );
+        }
     // Read versit types
     iFieldTypeMappings->InitVersitMappingsL( resReader );
     resReader.SetBuffer( resFile.AllocReadLC( 
@@ -153,6 +164,7 @@
     delete iContactStoreList;
     delete iTextStore;
     iFs.Close();
+    FeatureManager::UnInitializeLib();
     }
 
 // -----------------------------------------------------------------------------
--- a/phonebookengines/VirtualPhonebook/VPbkSimStore/src/CSupportedFieldTypes.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkSimStore/src/CSupportedFieldTypes.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -44,23 +44,55 @@
 //
 void CSupportedFieldTypes::ConstructL( 
     const CFieldTypeMappings& aFieldTypeMappings,
-    TVPbkGsmStoreProperty& aSimStoreProperty )
+    TVPbkGsmStoreProperty& aSimStoreProperty,
+    TVPbkUSimStoreProperty* aUSimStoreProperty )
     {
     // SIM supports always the name field
     const MVPbkFieldType* vpbkType = aFieldTypeMappings.Match( EVPbkSimName );
     iSupportedTypes.AppendL( vpbkType );
     // SIM supports always one number field
     vpbkType = aFieldTypeMappings.Match( EVPbkSimGsmNumber );
+    const MVPbkFieldType* vpbkGsmType = vpbkType;
     iSupportedTypes.AppendL( vpbkType );
     // USIM can support additional numbers
     if ( aSimStoreProperty.iCaps & VPbkSimStoreImpl::KAdditionalNumUsed )
         {
-        vpbkType = aFieldTypeMappings.Match( EVPbkSimAdditionalNumber );
-        // Check if the VPbk type is different than the type for
-        // already added EVPbkSimGsmNumber
-        if ( iSupportedTypes.Find( vpbkType ) == KErrNotFound )
+        if( aUSimStoreProperty )
             {
-            iSupportedTypes.AppendL( vpbkType );
+            for( TInt i = 1; i <= aUSimStoreProperty->iMaxNumOfAnrs; i ++ )
+                {
+                TVPbkSimCntFieldType type;
+                switch( i )
+                    {
+                    case 1:  // first additional number field type 
+                        type = EVPbkSimAdditionalNumber1;
+                        break;
+                    case 2: // second additional number field type
+                        type = EVPbkSimAdditionalNumber2;
+                        break;
+                    case 3: // third additional number field type
+                        type = EVPbkSimAdditionalNumber3;
+                        break;
+                    default: // four and so on 
+                        type = EVPbkSimAdditionalNumberLast;
+                        break;
+                    }
+                vpbkType = aFieldTypeMappings.Match( type );
+                if( !( vpbkGsmType->IsSame( *vpbkType ) ) )   // if not the same as GSM type.
+                    {
+                    iSupportedTypes.AppendL( vpbkType );
+                    }
+                }
+            }
+        else
+            {
+            vpbkType = aFieldTypeMappings.Match( EVPbkSimAdditionalNumber );
+            // Check if the VPbk type is different than the type for
+            // already added EVPbkSimGsmNumber
+            if ( iSupportedTypes.Find( vpbkType ) == KErrNotFound )
+                {
+                iSupportedTypes.AppendL( vpbkType );
+                }
             }
         }
     if ( aSimStoreProperty.iCaps & VPbkSimStoreImpl::KSecondNameUsed )
@@ -93,6 +125,23 @@
     return self;
     }
 
+// -----------------------------------------------------------------------------
+// CSupportedFieldTypes::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CSupportedFieldTypes* CSupportedFieldTypes::NewL(
+    const CFieldTypeMappings& aFieldTypeMappings,
+    TVPbkGsmStoreProperty& aSimStoreProperty,
+    TVPbkUSimStoreProperty& aUSimStoreProperty )  
+    {
+    CSupportedFieldTypes* self = new( ELeave ) CSupportedFieldTypes;
+    CleanupStack::PushL( self );
+    self->ConstructL( aFieldTypeMappings, aSimStoreProperty, &aUSimStoreProperty );  
+    CleanupStack::Pop( self );
+    return self;
+    }
+
 // Destructor
 CSupportedFieldTypes::~CSupportedFieldTypes()
     {    
--- a/phonebookengines/VirtualPhonebook/VPbkSimStoreCommon/src/CVPbkSimFieldTypeFilter.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkSimStoreCommon/src/CVPbkSimFieldTypeFilter.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -112,8 +112,11 @@
             ret = ESimFilterCriteriaGsmNumber;
             break;
             }
-
-        case EVPbkSimAdditionalNumber:
+         
+         case EVPbkSimAdditionalNumber1:  // FALLTHROUGH
+         case EVPbkSimAdditionalNumber2:  // FALLTHROUGH
+         case EVPbkSimAdditionalNumber3:  // FALLTHROUGH
+         case EVPbkSimAdditionalNumberLast: // the same as EVPbkSimAdditionalNumber.
             {
             ret = ESimFilterCriteriaAdditionalNumber;
             break;
--- a/phonebookengines/VirtualPhonebook/VPbkSimStoreImpl/src/CVPbkETelCntConverter.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkSimStoreImpl/src/CVPbkETelCntConverter.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -61,7 +61,10 @@
             break;
             }
         case EVPbkSimGsmNumber: // FALLTHROUGH
-        case EVPbkSimAdditionalNumber:
+        case EVPbkSimAdditionalNumber1:  // FALLTHROUGH
+        case EVPbkSimAdditionalNumber2:  // FALLTHROUGH
+        case EVPbkSimAdditionalNumber3:  // FALLTHROUGH
+        case EVPbkSimAdditionalNumberLast:  // same as EVPbkSimAdditionalNumber
             {
             result = RMobilePhoneBookStore::ETagPBNumber;
             break;
@@ -187,7 +190,10 @@
     const TDesC& data = aField.Data();
     if ( data.Length() > 0 )
         {
-        if ( aField.Type() == EVPbkSimAdditionalNumber )
+        if( aField.Type() == EVPbkSimAdditionalNumber1 
+                || aField.Type() == EVPbkSimAdditionalNumber2 
+                || aField.Type() == EVPbkSimAdditionalNumber3 
+                || aField.Type()== EVPbkSimAdditionalNumberLast ) // all these four types are all additional field types.
             {
             // Additional number needs own tag that must be added before data
             aETelBuffer.AddNewNumberTag();
--- a/phonebookengines/VirtualPhonebook/VPbkSimStoreImpl/src/CVPbkSimCntField.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkSimStoreImpl/src/CVPbkSimCntField.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -77,36 +77,39 @@
         TVPbkUSimStoreProperty uprop;
         TInt err = aStore.GetUSimStoreProperties( uprop );
         if( err == KErrNone )
-        	{
-	        switch ( aType )
-	            {
-	            case EVPbkSimAdditionalNumber:
-	                {
-	                result = uprop.iMaxAnrLength;
-	                break;
-	                }
-	            case EVPbkSimReading:
-	            case EVPbkSimNickName:
-	                {
-	                result = uprop.iMaxScndNameLength;
-	                break;
-	                }
-	            case EVPbkSimEMailAddress:
-	                {
-	                result = uprop.iMaxEmailLength;
-	                break;
-	                }
-	            case EVPbkSimGroupName:
-	                {
-	                result = uprop.iMaxGroupNameLength;
-	                break;
-	                }
-	            default:
-	                {
-	                break;
-	                }
-	            }
-        	}
+            {
+            switch ( aType )
+                {
+                case EVPbkSimAdditionalNumber1:  // FALLTHROUGH
+                case EVPbkSimAdditionalNumber2:  // FALLTHROUGH
+                case EVPbkSimAdditionalNumber3:  // FALLTHROUGH
+                case EVPbkSimAdditionalNumberLast: // same as EVPbkSimAdditionalNumber
+                    {
+                    result = uprop.iMaxAnrLength;
+                    break;
+                    }
+                case EVPbkSimReading:  // FALLTHROUGH
+                case EVPbkSimNickName:
+                    {
+                    result = uprop.iMaxScndNameLength;
+                    break;
+                    }
+                case EVPbkSimEMailAddress:
+                    {
+                    result = uprop.iMaxEmailLength;
+                    break;
+                    }
+                case EVPbkSimGroupName:
+                    {
+                    result = uprop.iMaxGroupNameLength;
+                    break;
+                    }
+                default:
+                    {
+                    break;
+                    }
+                }
+            }
         }
     return (TInt16)result;
     }
@@ -289,7 +292,11 @@
     
     // Max length must be calculated for number types only because other
     // types are not splitted in several records in SIM card.
-    if ( iType == EVPbkSimGsmNumber || iType == EVPbkSimAdditionalNumber )
+    if ( iType == EVPbkSimGsmNumber 
+            || iType == EVPbkSimAdditionalNumber1
+            || iType == EVPbkSimAdditionalNumber2
+            || iType == EVPbkSimAdditionalNumber3
+            || iType == EVPbkSimAdditionalNumberLast ) // same as EVPbkSimAdditionalNumber
         {
         TInt currentMaxLength = MaxLength( iType, 
             iParentContact.ParentStore() );
--- a/phonebookengines/VirtualPhonebook/VPbkSimStoreImpl/src/CVPbkSimContact.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkSimStoreImpl/src/CVPbkSimContact.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -18,6 +18,7 @@
 
 
 // INCLUDE FILES
+#include <featmgr.h>
 #include "CVPbkSimContact.h"
 
 #include "CVPbkSimCntField.h"
@@ -50,6 +51,10 @@
     if ( aETelContact )
         {
         SetL( *aETelContact );
+        if( FeatureManager::FeatureSupported( KFeatureIdFfTdClmcontactreplicationfromphonebooktousimcard ) )
+        	{
+			IndentifyAdditionalFields();
+        	}
         }
     }
 
@@ -234,6 +239,37 @@
     }
 
 // -----------------------------------------------------------------------------
+// CVPbkSimContact::IndentifyAdditionalFields()
+// -----------------------------------------------------------------------------
+//
+void CVPbkSimContact::IndentifyAdditionalFields()
+    {
+    TInt anrNumberFieldCount = 0;
+    for( int i = 0; i < iFieldArray.Count(); i ++ )
+        {
+        if( iFieldArray[i]->Type() == EVPbkSimAdditionalNumber )
+            {
+            anrNumberFieldCount ++;
+            switch( anrNumberFieldCount )
+                {
+                case 1:
+                    iFieldArray[i]->SetType( EVPbkSimAdditionalNumber1 );
+                    break;
+                case 2:
+                    iFieldArray[i]->SetType( EVPbkSimAdditionalNumber2 );
+                    break;
+                case 3:
+                    iFieldArray[i]->SetType( EVPbkSimAdditionalNumber3 );
+                    break;
+                default:
+                    iFieldArray[i]->SetType( EVPbkSimAdditionalNumberLast );
+                    break;
+                }
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
 // CVPbkSimContact::CreateETelContactL
 // -----------------------------------------------------------------------------
 // 
--- a/phonebookengines/VirtualPhonebook/VPbkSimStoreImpl/src/CVPbkSimContactBase.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkSimStoreImpl/src/CVPbkSimContactBase.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -88,11 +88,27 @@
     aLookup.SetPos( KErrNotFound );
     for ( ; i < count; ++i )
         {
-        if ( ConstFieldAt( i ).Type() == aLookup.Type() )
+        if( aLookup.Type() == EVPbkSimAdditionalNumber )
             {
-            aLookup.SetIndex( i );
-            aLookup.SetPos( i + 1 );
-            break;
+            const CVPbkSimCntField& field = ConstFieldAt( i );
+            if ( field.Type() == EVPbkSimAdditionalNumber1 
+                    || field.Type() == EVPbkSimAdditionalNumber2
+                    || field.Type() == EVPbkSimAdditionalNumber3
+                    || field.Type() == EVPbkSimAdditionalNumberLast ) // the same as EVPbkSimAdditionalNumber
+                {
+                aLookup.SetIndex( i );
+                aLookup.SetPos( i + 1 );
+                break;
+                }
+            }
+        else
+            {
+            if ( ConstFieldAt( i ).Type() == aLookup.Type() )
+                {
+                aLookup.SetIndex( i );
+                aLookup.SetPos( i + 1 );
+                break;
+                }
             }
         }
     }
--- a/phonebookengines/VirtualPhonebook/VPbkVCardEng/inc/CVPbkVCardImporter.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkVCardEng/inc/CVPbkVCardImporter.h	Thu Aug 19 09:41:07 2010 +0300
@@ -119,7 +119,6 @@
             
         void IssueRequest();
         CParserProperty* NextProperty();
-        CParserProperty* GetCurrentProperty();
         void ParseNextL();
         TInt FindContactFieldL( 
                 MVPbkStoreContact* aContact, 
--- a/phonebookengines/VirtualPhonebook/VPbkVCardEng/src/CVPbkImportToContactsMergeOperation.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkVCardEng/src/CVPbkImportToContactsMergeOperation.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -19,6 +19,8 @@
 #include "CVPbkImportToContactsMergeOperation.h"
 #include "VPbkVCardEngError.h"
 #include "CVPbkVCardImporter.h"
+#include "CVPbkDefaultAttribute.h"
+#include "CVPbkLocalVariationManager.h"
 
 // Virtual Phonebook
 #include <MVPbkStoreContact.h>
@@ -31,7 +33,6 @@
 #include <MVPbkContactFieldUriData.h>
 #include <MVPbkContactFieldTextData.h>
 #include <MVPbkSingleContactOperationObserver.h>
-#include "CVPbkDefaultAttribute.h"
 const TInt KGranularity = 4;
 
 namespace{
@@ -223,7 +224,8 @@
                 }
             case EComplete:
                 {
-                if(iGroupcardHandler && ((CVPbkVCardImporter *)iOperationImpl)->IsGroupcard())
+                TBool isGroupCard = ((CVPbkVCardImporter *)iOperationImpl)->IsGroupcard();
+                if(iGroupcardHandler && isGroupCard)
                     {
                     iGroupcardHandler->BuildContactGroupsHashMapL(iContact->ParentStore());
                     const MVPbkContactLink* contact = iContact->CreateLinkLC();
@@ -231,6 +233,19 @@
                     CleanupStack::PopAndDestroy(); // For contact
                     iGroupcardHandler->DecodeContactGroupInVCardL(((CVPbkVCardImporter *)iOperationImpl)->GetGroupcardvalue());
                     }
+                
+                CVPbkLocalVariationManager* lvm = CVPbkLocalVariationManager::NewL(); 
+                TBool supportSyncGroupVcard = lvm->LocallyVariatedFeatureEnabled( EVPbkLVSyncGroupEnabled );
+                delete lvm;    
+                if (supportSyncGroupVcard && iGroupcardHandler && !isGroupCard)
+                    {
+                    iGroupcardHandler->BuildContactGroupsHashMapL(iContact->ParentStore());
+                    const MVPbkContactLink *aContact = iContact->CreateLinkLC();
+                    iGroupcardHandler->GetContactGroupStoreL(*aContact);
+                    CleanupStack::PopAndDestroy();
+                    iGroupcardHandler->DeleteContactFromGroupsL();
+                    }
+
                 iObserver.VPbkSingleContactOperationComplete( *this, iContact );
                 iContact = NULL;
                 break;
--- a/phonebookengines/VirtualPhonebook/VPbkVCardEng/src/CVPbkImportToStoreOperation.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkVCardEng/src/CVPbkImportToStoreOperation.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -22,6 +22,7 @@
 #include "CVPbkVCardImporter.h"
 #include "CVPbkVCardData.h"
 #include "VPbkVCardEngError.h"
+#include "CVPbkLocalVariationManager.h"
 
 // From Virtual Phonebook
 #include <MVPbkStoreContact.h>
@@ -371,7 +372,8 @@
 	    	}
 		
      TBool destroyed = EFalse;
-     if(iGroupcardHandler && ((CVPbkVCardImporter *)iOperationImpl)->IsGroupcard())
+     TBool isGroupCard = ((CVPbkVCardImporter *)iOperationImpl)->IsGroupcard();   
+     if(iGroupcardHandler && isGroupCard )
          {
          // CVPbkGroupCardHandler uses nested activescheduler loop to make
          // async requests synchronous (why?). Hence it is possible that when 
@@ -398,6 +400,17 @@
              destroyed = ETrue;
              }
          }
+     
+     CVPbkLocalVariationManager* lvm = CVPbkLocalVariationManager::NewL(); 
+     TBool supportSyncGroupVcard = lvm->LocallyVariatedFeatureEnabled( EVPbkLVSyncGroupEnabled );
+     delete lvm;    
+     if (supportSyncGroupVcard && iGroupcardHandler && !isGroupCard)        
+         {
+         iGroupcardHandler->BuildContactGroupsHashMapL(iTargetStore);
+         iGroupcardHandler->GetContactGroupStoreL(aResults->At(0));
+         iGroupcardHandler->DeleteContactFromGroupsL();
+         }
+     
     CleanupStack::PopAndDestroy(); // aResults
 
     if ( !destroyed )
--- a/phonebookengines/VirtualPhonebook/VPbkVCardEng/src/CVPbkVCardImporter.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/VPbkVCardEng/src/CVPbkVCardImporter.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -205,19 +205,6 @@
     iObserver = &aObserver;
     }
 
-CParserProperty* CVPbkVCardImporter::GetCurrentProperty()
-    {
-    // Get current property from parser array
-    CParserProperty* property = NULL;
-    TInt elementCount = iParser->ArrayOfProperties( EFalse )->Count();
-    if ( iArrayElementIndex < elementCount ) 
-        {        
-        property = 
-            iParser->ArrayOfProperties( EFalse )->At( iArrayElementIndex );
-        }
-    return property;
-    }
-
 CParserProperty* CVPbkVCardImporter::NextProperty()
     {
     // Get next property from parser array
@@ -346,15 +333,17 @@
          aData.Uid() == TUid::Uid( KVersitPropertyCDesCArrayUid ) )
         {
         const TDesC& value = converter.GetDesCData( aData );
+        // If it is an IMPP field
         if ( aData.FieldType().FieldTypeResId() == R_VPBK_FIELD_TYPE_IMPP )
             {
             TInt pos = value.Find(KColon);
-            if( 0 == pos )
+            if( 0 == pos || KErrNotFound == pos )
                 {
-                // If the service name is NULL and it's a IMPP field, don't save the data.
+                // If the service name or the colon doesn't exist, don't save the data.
                 // e.g.:
                 // (1) If the value is YAHOO:peterpan@yahoo.com, YAHOO is the service name
                 // (2) If the value is :peterpan@yahoo.com, the service name is NULL
+                // (3) If the value is peterpan@yahoo.com, neither the service name and the colon exists
                 isSaved = EFalse;
                 }
             }
@@ -479,13 +468,17 @@
         {
         delete iAddFieldOperation;
         iAddFieldOperation = NULL;
-        StartAsync( ESaveField );
         }    
     if (&aOperation == iAddCntContactFieldOperation)
         {
         delete iAddCntContactFieldOperation;
         iAddCntContactFieldOperation = NULL;
         }
+    // When both operations have completed
+    if ( !iAddFieldOperation && !iAddCntContactFieldOperation )
+        {
+        StartAsync( ESaveField );
+        }
     }
     
 void CVPbkVCardImporter::FieldAddingFailed(
--- a/phonebookengines/VirtualPhonebook/inc/CVPbkSimContact.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/inc/CVPbkSimContact.h	Thu Aug 19 09:41:07 2010 +0300
@@ -178,6 +178,12 @@
     private:    // New functions
         /// Creates ETel contact from native fields
         void CreateETelContactL() const;
+        
+		/*
+		* Used to indentify the different additional number field types 
+		* according the order in the field array.
+		*/
+        void IndentifyAdditionalFields();
 
     private:    // Data
         /// The array for the fields
--- a/phonebookengines/VirtualPhonebook/inc/VPbkSimCntFieldTypes.hrh	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookengines/VirtualPhonebook/inc/VPbkSimCntFieldTypes.hrh	Thu Aug 19 09:41:07 2010 +0300
@@ -30,7 +30,11 @@
     EVPbkSimReading = 5, // ETel ETagPBSecondName
     EVPbkSimEMailAddress = 6, // ETagPBEmailAddress
     EVPbkSimGroupName = 7, // ETel ETagPBGroupName
-    EVPbkSimUnknownType = 8
+    EVPbkSimUnknownType = 8,
+    EVPbkSimAdditionalNumber1 = 9,  // ETagPBAnrStart the first additional number
+    EVPbkSimAdditionalNumber2 = 10,  // ETagPBAnrStart the second additional number
+    EVPbkSimAdditionalNumber3 = 11,  // ETagPBAnrStart the third additional number
+    EVPbkSimAdditionalNumberLast = EVPbkSimAdditionalNumber  // ETagPBAnrStart the fourth additional number and so on.
     };
 
 
--- a/phonebookui/Phonebook/View/src/CPbkFFSCheck.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook/View/src/CPbkFFSCheck.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -59,7 +59,12 @@
 
 EXPORT_C TBool CPbkFFSCheck::FFSClCheckL(TInt aBytesToWrite/*=0*/)
     {
-    if (SysUtil::FFSSpaceBelowCriticalLevelL(&iConeEnv->FsSession(),aBytesToWrite) ||
+    RFs* rfSession = NULL;
+    if ( iConeEnv )
+        {
+        rfSession = &iConeEnv->FsSession();
+        }
+    if (SysUtil::FFSSpaceBelowCriticalLevelL( rfSession, aBytesToWrite ) ||
         DebugFailNext())
         {
         // Show not enough memory note
--- a/phonebookui/Phonebook2/Application/rss/Pbk2MenuResources.rss	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/Application/rss/Pbk2MenuResources.rss	Thu Aug 19 09:41:07 2010 +0300
@@ -106,7 +106,7 @@
             },
         MENU_TITLE
             {
-            menu_pane = R_AVKON_MENUPANE_MARKABLE_LIST;
+            menu_pane = R_AVKON_MENUPANE_MARK_MULTIPLE;
             },            
         MENU_TITLE
             {
@@ -194,37 +194,6 @@
         };
     }
 
-// --------------------------------------------------------------------------
-// Names List View's Context sensitive menu bar
-// when items are marked
-// --------------------------------------------------------------------------
-//
-RESOURCE MENU_BAR r_phonebook2_nameslist_context_menubar_items_marked
-    {
-    titles =
-        {
-        MENU_TITLE
-            {
-            menu_pane = R_PHONEBOOK2_MARKABLE_LIST_CONTEXT_MENU;
-            },            
-        MENU_TITLE
-            {
-            menu_pane = R_PHONEBOOK2_NAMESLIST_COPY_CONTEXT_MENU;
-            },
-        MENU_TITLE
-            {
-            menu_pane = R_PHONEBOOK2_NAMESLIST_CONTEXT_MENU_MARKED_ITEMS;
-            },
-        MENU_TITLE
-            {
-            menu_pane = R_PHONEBOOK2_BCARD_SEND_MENU;
-            },            
-        MENU_TITLE
-            {
-            menu_pane = R_PHONEBOOK2_NAMELIST_CREATE_MESSAGE_MENU;
-            }
-        };
-    }
 
 // --------------------------------------------------------------------------
 // Contact Info View's menu bar
--- a/phonebookui/Phonebook2/BWINS/Pbk2UiControlsU.DEF	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/BWINS/Pbk2UiControlsU.DEF	Thu Aug 19 09:41:07 2010 +0300
@@ -1,124 +1,124 @@
 EXPORTS
-	??0CPbk2NamesListControl@@QAE@PBVCCoeControl@@AAVCVPbkContactManager@@AAVMVPbkContactViewBase@@AAVMPbk2ContactNameFormatter@@AAVCPbk2StorePropertyArray@@@Z @ 1 NONAME ; CPbk2NamesListControl::CPbk2NamesListControl(class CCoeControl const *, class CVPbkContactManager &, class MVPbkContactViewBase &, class MPbk2ContactNameFormatter &, class CPbk2StorePropertyArray &)
-	??0TParams@CPbk2FetchDlg@@QAE@XZ @ 2 NONAME ; CPbk2FetchDlg::TParams::TParams(void)
-	??0TPbk2AddItemWrapper@@QAE@ABVCPbk2FieldPropertyGroup@@@Z @ 3 NONAME ; TPbk2AddItemWrapper::TPbk2AddItemWrapper(class CPbk2FieldPropertyGroup const &)
-	??0TPbk2AddItemWrapper@@QAE@ABVMPbk2FieldProperty@@@Z @ 4 NONAME ; TPbk2AddItemWrapper::TPbk2AddItemWrapper(class MPbk2FieldProperty const &)
-	??0TPbk2AddressSelectParams@@QAE@AAVMVPbkStoreContact@@ABVCVPbkContactManager@@AAVMPbk2ContactNameFormatter@@ABVCPbk2FieldPropertyArray@@AAVTResourceReader@@H@Z @ 5 NONAME ; TPbk2AddressSelectParams::TPbk2AddressSelectParams(class MVPbkStoreContact &, class CVPbkContactManager const &, class MPbk2ContactNameFormatter &, class CPbk2FieldPropertyArray const &, class TResourceReader &, int)
-	??1CPbk2AddressSelect@@UAE@XZ @ 6 NONAME ; CPbk2AddressSelect::~CPbk2AddressSelect(void)
-	??1CPbk2ContactUiControlSubstitute@@UAE@XZ @ 7 NONAME ; CPbk2ContactUiControlSubstitute::~CPbk2ContactUiControlSubstitute(void)
-	??BTParams@CPbk2FetchDlg@@QAE?AVTCleanupItem@@XZ @ 8 NONAME ; CPbk2FetchDlg::TParams::operator class TCleanupItem(void)
-	?AcceptDelayedFetchL@CPbk2FetchDlg@@QAEXABVTDesC8@@@Z @ 9 NONAME ; void CPbk2FetchDlg::AcceptDelayedFetchL(class TDesC8 const &)
-	?AddObserverL@CPbk2ContactInfoControl@@QAEXAAVMPbk2ControlObserver@@@Z @ 10 NONAME ; void CPbk2ContactInfoControl::AddObserverL(class MPbk2ControlObserver &)
-	?AddObserverL@CPbk2NamesListControl@@QAEXAAVMPbk2ControlObserver@@@Z @ 11 NONAME ; void CPbk2NamesListControl::AddObserverL(class MPbk2ControlObserver &)
-	?AttemptExitL@CPbk2AddressSelect@@QAEXH@Z @ 12 NONAME ; void CPbk2AddressSelect::AttemptExitL(int)
-	?CommitSettingsL@CPbk2SettingsListControl@@QAEXXZ @ 13 NONAME ; void CPbk2SettingsListControl::CommitSettingsL(void)
-	?CreatePhoneNumberFormatterL@Pbk2PhoneNumberFormatterFactory@@SAPAVMPbk2PhoneNumberFormatter@@H@Z @ 14 NONAME ; class MPbk2PhoneNumberFormatter * Pbk2PhoneNumberFormatterFactory::CreatePhoneNumberFormatterL(int)
-	?ExecuteLD@CPbk2AddItemToContactDlg@@QAEHAAV?$RArray@VTPbk2AddItemWrapper@@@@PBVTPbk2AddItemDialogParams@@@Z @ 15 NONAME ; int CPbk2AddItemToContactDlg::ExecuteLD(class RArray<class TPbk2AddItemWrapper> &, class TPbk2AddItemDialogParams const *)
-	?ExecuteLD@CPbk2AddressSelect@@QAEPAVMVPbkStoreContactField@@XZ @ 16 NONAME ; class MVPbkStoreContactField * CPbk2AddressSelect::ExecuteLD(void)
-	?ExecuteLD@CPbk2ContactEditorDlg@@QAEXXZ @ 17 NONAME ; void CPbk2ContactEditorDlg::ExecuteLD(void)
-	?ExecuteLD@CPbk2FetchDlg@@QAEHXZ @ 18 NONAME ; int CPbk2FetchDlg::ExecuteLD(void)
-	?ExecuteLD@CPbk2GeneralConfirmationQuery@@QAEHABVMVPbkBaseContact@@H@Z @ 19 NONAME ; int CPbk2GeneralConfirmationQuery::ExecuteLD(class MVPbkBaseContact const &, int)
-	?ExecuteLD@CPbk2GeneralConfirmationQuery@@QAEHHH@Z @ 20 NONAME ; int CPbk2GeneralConfirmationQuery::ExecuteLD(int, int)
-	?ExecuteLD@CPbk2MemoryEntryDefaultsAssignDlg@@QAEHABVCPbk2PresentationContactFieldCollection@@ABVCVPbkContactManager@@ABVMPbk2FieldPropertyArray@@@Z @ 21 NONAME ABSENT ; int CPbk2MemoryEntryDefaultsAssignDlg::ExecuteLD(class CPbk2PresentationContactFieldCollection const &, class CVPbkContactManager const &, class MPbk2FieldPropertyArray const &)
-	?ExecuteLD@CPbk2MemoryEntryDefaultsDlg@@QAEXXZ @ 22 NONAME ; void CPbk2MemoryEntryDefaultsDlg::ExecuteLD(void)
-	?ExecuteLD@CPbk2PhonebookInfoDlg@@QAEXAAVCVPbkContactStoreUriArray@@@Z @ 23 NONAME ; void CPbk2PhonebookInfoDlg::ExecuteLD(class CVPbkContactStoreUriArray &)
-	?ExecuteLD@CPbk2StoreListQuery@@QAEHABVTDesC16@@AAVCVPbkContactStoreUriArray@@@Z @ 24 NONAME ; int CPbk2StoreListQuery::ExecuteLD(class TDesC16 const &, class CVPbkContactStoreUriArray &)
-	?FormatFieldContentL@CPbk2FieldFormatter@@QAE?AVTPtrC16@@ABVMVPbkBaseContactField@@ABVMVPbkFieldType@@@Z @ 25 NONAME ; class TPtrC16 CPbk2FieldFormatter::FormatFieldContentL(class MVPbkBaseContactField const &, class MVPbkFieldType const &)
-	?HideThumbnail@CPbk2ThumbnailLoader@@QAEXXZ @ 26 NONAME ; void CPbk2ThumbnailLoader::HideThumbnail(void)
-	?IsWaiting@CPbk2InputAbsorber@@QBEHXZ @ 27 NONAME ; int CPbk2InputAbsorber::IsWaiting(void) const
-	?LoadThumbnail@CPbk2ThumbnailLoader@@QAEXPAVMVPbkStoreContact@@PBVCEikListBox@@W4TPbk2ThumbnailLocation@@@Z @ 28 NONAME ; void CPbk2ThumbnailLoader::LoadThumbnail(class MVPbkStoreContact *, class CEikListBox const *, enum TPbk2ThumbnailLocation)
-	?LoadThumbnailL@CPbk2ThumbnailLoader@@QAEXPAVMVPbkContactLink@@PBVCEikListBox@@W4TPbk2ThumbnailLocation@@@Z @ 29 NONAME ; void CPbk2ThumbnailLoader::LoadThumbnailL(class MVPbkContactLink *, class CEikListBox const *, enum TPbk2ThumbnailLocation)
-	?NewL@CPbk2AddItemToContactDlg@@SAPAV1@XZ @ 30 NONAME ; class CPbk2AddItemToContactDlg * CPbk2AddItemToContactDlg::NewL(void)
-	?NewL@CPbk2AddressSelect@@SAPAV1@AAVTPbk2AddressSelectParams@@@Z @ 31 NONAME ; class CPbk2AddressSelect * CPbk2AddressSelect::NewL(class TPbk2AddressSelectParams &)
-	?NewL@CPbk2ContactEditorDlg@@SAPAV1@AAVTPbk2ContactEditorParams@@PAVMVPbkStoreContact@@AAVMPbk2EditedContactObserver@@@Z @ 32 NONAME ; class CPbk2ContactEditorDlg * CPbk2ContactEditorDlg::NewL(class TPbk2ContactEditorParams &, class MVPbkStoreContact *, class MPbk2EditedContactObserver &)
-	?NewL@CPbk2ContactInfoControl@@SAPAV1@PBVCCoeControl@@AAVCVPbkContactManager@@AAVMPbk2ContactNameFormatter@@AAVMPbk2FieldPropertyArray@@AAVCPbk2StorePropertyArray@@PAVMPbk2ContactNavigation@@@Z @ 33 NONAME ; class CPbk2ContactInfoControl * CPbk2ContactInfoControl::NewL(class CCoeControl const *, class CVPbkContactManager &, class MPbk2ContactNameFormatter &, class MPbk2FieldPropertyArray &, class CPbk2StorePropertyArray &, class MPbk2ContactNavigation *)
-	?NewL@CPbk2ContactUiControlSubstitute@@SAPAV1@XZ @ 34 NONAME ; class CPbk2ContactUiControlSubstitute * CPbk2ContactUiControlSubstitute::NewL(void)
-	?NewL@CPbk2FetchDlg@@SAPAV1@VTParams@1@AAVMPbk2FetchDlgObserver@@@Z @ 35 NONAME ; class CPbk2FetchDlg * CPbk2FetchDlg::NewL(class CPbk2FetchDlg::TParams, class MPbk2FetchDlgObserver &)
-	?NewL@CPbk2FieldFormatter@@SAPAV1@ABVMPbk2FieldPropertyArray@@ABVMVPbkFieldTypeList@@@Z @ 36 NONAME ; class CPbk2FieldFormatter * CPbk2FieldFormatter::NewL(class MPbk2FieldPropertyArray const &, class MVPbkFieldTypeList const &)
-	?NewL@CPbk2GeneralConfirmationQuery@@SAPAV1@XZ @ 37 NONAME ; class CPbk2GeneralConfirmationQuery * CPbk2GeneralConfirmationQuery::NewL(void)
-	?NewL@CPbk2InputAbsorber@@SAPAV1@H@Z @ 38 NONAME ; class CPbk2InputAbsorber * CPbk2InputAbsorber::NewL(int)
-	?NewL@CPbk2MemoryEntryDefaultsAssignDlg@@SAPAV1@XZ @ 39 NONAME ; class CPbk2MemoryEntryDefaultsAssignDlg * CPbk2MemoryEntryDefaultsAssignDlg::NewL(void)
-	?NewL@CPbk2MemoryEntryDefaultsDlg@@SAPAV1@AAVCPbk2PresentationContact@@AAVCVPbkContactManager@@@Z @ 40 NONAME ; class CPbk2MemoryEntryDefaultsDlg * CPbk2MemoryEntryDefaultsDlg::NewL(class CPbk2PresentationContact &, class CVPbkContactManager &)
-	?NewL@CPbk2NamesListControl@@SAPAV1@HPBVCCoeControl@@AAVCVPbkContactManager@@AAVMVPbkContactViewBase@@AAVMPbk2ContactNameFormatter@@AAVCPbk2StorePropertyArray@@@Z @ 41 NONAME ; class CPbk2NamesListControl * CPbk2NamesListControl::NewL(int, class CCoeControl const *, class CVPbkContactManager &, class MVPbkContactViewBase &, class MPbk2ContactNameFormatter &, class CPbk2StorePropertyArray &)
-	?NewL@CPbk2PhonebookInfoDlg@@SAPAV1@XZ @ 42 NONAME ; class CPbk2PhonebookInfoDlg * CPbk2PhonebookInfoDlg::NewL(void)
-	?NewL@CPbk2PrependDlg@@SAPAV1@AAVTDes16@@@Z @ 43 NONAME ; class CPbk2PrependDlg * CPbk2PrependDlg::NewL(class TDes16 &)
-	?NewL@CPbk2SettingsListControl@@SAPAV1@PBVCCoeControl@@AAVCPbk2SortOrderManager@@AAVMPbk2SettingsControlExtension@@@Z @ 44 NONAME ; class CPbk2SettingsListControl * CPbk2SettingsListControl::NewL(class CCoeControl const *, class CPbk2SortOrderManager &, class MPbk2SettingsControlExtension &)
-	?NewL@CPbk2StoreListQuery@@SAPAV1@XZ @ 45 NONAME ; class CPbk2StoreListQuery * CPbk2StoreListQuery::NewL(void)
-	?NewL@CPbk2ThumbnailLoader@@SAPAV1@AAVCVPbkContactManager@@@Z @ 46 NONAME ; class CPbk2ThumbnailLoader * CPbk2ThumbnailLoader::NewL(class CVPbkContactManager &)
-	?NewLC@CPbk2InputAbsorber@@SAPAV1@H@Z @ 47 NONAME ; class CPbk2InputAbsorber * CPbk2InputAbsorber::NewLC(int)
-	?Pbk2ControlKeyEventL@CPbk2AddressSelect@@UAE?AW4TKeyResponse@@ABUTKeyEvent@@W4TEventCode@@@Z @ 48 NONAME ; enum TKeyResponse CPbk2AddressSelect::Pbk2ControlKeyEventL(struct TKeyEvent const &, enum TEventCode)
-	?PropertyAt@TPbk2AddItemWrapper@@QBEABVMPbk2FieldProperty@@H@Z @ 49 NONAME ; class MPbk2FieldProperty const & TPbk2AddItemWrapper::PropertyAt(int) const
-	?PropertyCount@TPbk2AddItemWrapper@@QBEHXZ @ 50 NONAME ; int TPbk2AddItemWrapper::PropertyCount(void) const
-	?Refresh@CPbk2ThumbnailLoader@@QAEXXZ @ 51 NONAME ; void CPbk2ThumbnailLoader::Refresh(void)
-	?RemoveObserver@CPbk2ContactInfoControl@@QAEXAAVMPbk2ControlObserver@@@Z @ 52 NONAME ; void CPbk2ContactInfoControl::RemoveObserver(class MPbk2ControlObserver &)
-	?RemoveObserver@CPbk2NamesListControl@@QAEXAAVMPbk2ControlObserver@@@Z @ 53 NONAME ; void CPbk2NamesListControl::RemoveObserver(class MPbk2ControlObserver &)
-	?Reset@CPbk2NamesListControl@@QAEXXZ @ 54 NONAME ; void CPbk2NamesListControl::Reset(void)
-	?Reset@CPbk2ThumbnailLoader@@QAEXXZ @ 55 NONAME ; void CPbk2ThumbnailLoader::Reset(void)
-	?SetAllItemTextL@CPbk2StoreListQuery@@QAEXABVTDesC16@@H@Z @ 56 NONAME ; void CPbk2StoreListQuery::SetAllItemTextL(class TDesC16 const &, int)
-	?SetCba@CPbk2AddressSelect@@QAEXH@Z @ 57 NONAME ; void CPbk2AddressSelect::SetCba(int)
-	?SetCommandObserver@CPbk2InputAbsorber@@QAEXPAVMEikCommandObserver@@@Z @ 58 NONAME ; void CPbk2InputAbsorber::SetCommandObserver(class MEikCommandObserver *)
-	?SetDefaultPriorities@TPbk2AddressSelectParams@@QAEXABVRVPbkContactFieldDefaultPriorities@@@Z @ 59 NONAME ; void TPbk2AddressSelectParams::SetDefaultPriorities(class RVPbkContactFieldDefaultPriorities const &)
-	?SetFocusedField@CPbk2ContactUiControlSubstitute@@QAEXABVMVPbkBaseContactField@@@Z @ 60 NONAME ; void CPbk2ContactUiControlSubstitute::SetFocusedField(class MVPbkBaseContactField const &)
-	?SetFocusedField@TPbk2AddressSelectParams@@QAEXPBVMVPbkStoreContactField@@@Z @ 61 NONAME ; void TPbk2AddressSelectParams::SetFocusedField(class MVPbkStoreContactField const *)
-	?SetFocusedFieldIndex@CPbk2ContactUiControlSubstitute@@UAEXH@Z @ 62 NONAME ; void CPbk2ContactUiControlSubstitute::SetFocusedFieldIndex(int)
-	?SetFocusedStoreContact@CPbk2ContactUiControlSubstitute@@QAEXABVMVPbkStoreContact@@@Z @ 63 NONAME ; void CPbk2ContactUiControlSubstitute::SetFocusedStoreContact(class MVPbkStoreContact const &)
-	?SetParentUiControl@CPbk2ContactUiControlSubstitute@@QAEXAAVMPbk2ContactUiControl@@@Z @ 64 NONAME ; void CPbk2ContactUiControlSubstitute::SetParentUiControl(class MPbk2ContactUiControl &)
-	?SetQueryAlways@TPbk2AddressSelectParams@@QAEXH@Z @ 65 NONAME ; void TPbk2AddressSelectParams::SetQueryAlways(int)
-	?SetSelectedStore@CPbk2ContactUiControlSubstitute@@QAEXAAVMVPbkContactStore@@@Z @ 66 NONAME ; void CPbk2ContactUiControlSubstitute::SetSelectedStore(class MVPbkContactStore &)
-	?SetTimeFormatL@CPbk2FieldFormatter@@QAEXABVTDesC16@@@Z @ 67 NONAME ; void CPbk2FieldFormatter::SetTimeFormatL(class TDesC16 const &)
-	?SetUseDefaultDirectly@TPbk2AddressSelectParams@@QAEXH@Z @ 68 NONAME ; void TPbk2AddressSelectParams::SetUseDefaultDirectly(int)
-	?SetViewL@CPbk2NamesListControl@@QAEXAAVMVPbkContactViewBase@@@Z @ 69 NONAME ; void CPbk2NamesListControl::SetViewL(class MVPbkContactViewBase &)
-	?StopWait@CPbk2InputAbsorber@@QAEXXZ @ 70 NONAME ; void CPbk2InputAbsorber::StopWait(void)
-	?Wait@CPbk2InputAbsorber@@QAEXXZ @ 71 NONAME ; void CPbk2InputAbsorber::Wait(void)
-	?CreateTitlePanePictureLC@Pbk2TitlePanePictureFactory@@SAPAVCEikImage@@PBVMVPbkStoreContact@@AAVCPbk2StorePropertyArray@@@Z @ 72 NONAME ; class CEikImage * Pbk2TitlePanePictureFactory::CreateTitlePanePictureLC(class MVPbkStoreContact const *, class CPbk2StorePropertyArray &)
-	?NewL@CPbk2DefaultAttributeProcess@@SAPAV1@AAVCVPbkContactManager@@AAVMVPbkStoreContact@@AAVMPbk2DefaultAttributeProcessObserver@@@Z @ 73 NONAME ; class CPbk2DefaultAttributeProcess * CPbk2DefaultAttributeProcess::NewL(class CVPbkContactManager &, class MVPbkStoreContact &, class MPbk2DefaultAttributeProcessObserver &)
-	?RemoveDefaultL@CPbk2DefaultAttributeProcess@@QAEXW4TVPbkDefaultType@@@Z @ 74 NONAME ; void CPbk2DefaultAttributeProcess::RemoveDefaultL(enum TVPbkDefaultType)
-	?RemoveDefaultsL@CPbk2DefaultAttributeProcess@@QAEXPAV?$CArrayFixFlat@W4TVPbkDefaultType@@@@@Z @ 75 NONAME ; void CPbk2DefaultAttributeProcess::RemoveDefaultsL(class CArrayFixFlat<enum TVPbkDefaultType> *)
-	?SetDefaultL@CPbk2DefaultAttributeProcess@@QAEXW4TVPbkDefaultType@@AAVMVPbkStoreContactField@@@Z @ 76 NONAME ; void CPbk2DefaultAttributeProcess::SetDefaultL(enum TVPbkDefaultType, class MVPbkStoreContactField &)
-	?SetDefaultsL@CPbk2DefaultAttributeProcess@@QAEXPAV?$CArrayFixFlat@W4TVPbkDefaultType@@@@AAVMVPbkStoreContactField@@@Z @ 77 NONAME ; void CPbk2DefaultAttributeProcess::SetDefaultsL(class CArrayFixFlat<enum TVPbkDefaultType> *, class MVPbkStoreContactField &)
-	?SetTitleToIncludeContactName@TPbk2AddressSelectParams@@QAEXH@Z @ 78 NONAME ; void TPbk2AddressSelectParams::SetTitleToIncludeContactName(int)
-	?GiveViewL@CPbk2NamesListControl@@QAEXPAVMVPbkContactViewBase@@@Z @ 79 NONAME ; void CPbk2NamesListControl::GiveViewL(class MVPbkContactViewBase *)
-	?SetSuppressWarnings@TPbk2AddressSelectParams@@QAEXH@Z @ 80 NONAME ; void TPbk2AddressSelectParams::SetSuppressWarnings(int)
-	?AllowPointerEvents@CPbk2NamesListControl@@QAEXH@Z @ 81 NONAME ; void CPbk2NamesListControl::AllowPointerEvents(int)
-	?CreateListboxIconArrayL@CPbk2ContactIconsUtils@@SAPAVCPbk2IconArray@@H@Z @ 82 NONAME ; class CPbk2IconArray * CPbk2ContactIconsUtils::CreateListboxIconArrayL(int)
-	?GetIconIdsForContactL@CPbk2ContactIconsUtils@@QBEXABVMVPbkViewContact@@AAV?$RArray@VTPbk2IconId@@@@@Z @ 83 NONAME ; void CPbk2ContactIconsUtils::GetIconIdsForContactL(class MVPbkViewContact const &, class RArray<class TPbk2IconId> &) const
-	?NewL@CPbk2ContactIconsUtils@@SAPAV1@AAVCPbk2StorePropertyArray@@PAVMPbk2ContactUiControlExtension@@@Z @ 84 NONAME ; class CPbk2ContactIconsUtils * CPbk2ContactIconsUtils::NewL(class CPbk2StorePropertyArray &, class MPbk2ContactUiControlExtension *)
-	?NewL@CPbk2AddressSelect@@SAPAV1@AAVTPbk2AddressSelectParams@@AAVCVPbkFieldTypeSelector@@PBV?$TArray@PAVMVPbkStoreContact@@@@PBV?$TArray@PAVCPbk2PresenceIconInfo@@@@@Z @ 85 NONAME ; class CPbk2AddressSelect * CPbk2AddressSelect::NewL(class TPbk2AddressSelectParams &, class CVPbkFieldTypeSelector &, class TArray<class MVPbkStoreContact *> const *, class TArray<class CPbk2PresenceIconInfo *> const *)
-	?MapViewTypeToAddress@Pbk2AddressTools@@SA?AW4TPbk2FieldGroupId@@W4TActiveView@TPbk2ContactEditorParams@@@Z @ 86 NONAME ; enum TPbk2FieldGroupId Pbk2AddressTools::MapViewTypeToAddress(enum TPbk2ContactEditorParams::TActiveView)
-	?GetAddressShortPreviewLC@Pbk2AddressTools@@SAXAAVMVPbkStoreContact@@W4TPbk2FieldGroupId@@AAVRBuf16@@@Z @ 87 NONAME ; void Pbk2AddressTools::GetAddressShortPreviewLC(class MVPbkStoreContact &, enum TPbk2FieldGroupId, class RBuf16 &)
-	?InitializeL@CPbk2ContactEditorReadonlyField@@QAEXPAVMPbk2ContactEditorUIField@@@Z @ 88 NONAME ; void CPbk2ContactEditorReadonlyField::InitializeL(class MPbk2ContactEditorUIField *)
-	?SetTextL@CPbk2ContactEditorReadonlyField@@QAEXPBVTDesC16@@@Z @ 89 NONAME ; void CPbk2ContactEditorReadonlyField::SetTextL(class TDesC16 const *)
-	?FieldLabel@CPbk2ContactEditorUIFieldBase@@UBEABVTDesC16@@XZ @ 90 NONAME ; class TDesC16 const & CPbk2ContactEditorUIFieldBase::FieldLabel(void) const
-	?MapAddressToVersitParam@Pbk2AddressTools@@SA?AW4TVPbkFieldTypeParameter@@W4TPbk2FieldGroupId@@@Z @ 91 NONAME ; enum TVPbkFieldTypeParameter Pbk2AddressTools::MapAddressToVersitParam(enum TPbk2FieldGroupId)
-	?HandleCustomFieldCommandL@CPbk2ContactEditorUIFieldBase@@UAEHH@Z @ 92 NONAME ; int CPbk2ContactEditorUIFieldBase::HandleCustomFieldCommandL(int)
-	?SetFieldLabelL@CPbk2ContactEditorUIFieldBase@@UAEXABVTDesC16@@@Z @ 93 NONAME ; void CPbk2ContactEditorUIFieldBase::SetFieldLabelL(class TDesC16 const &)
-	?SetFocus@CPbk2ContactEditorUIFieldBase@@UAEXXZ @ 94 NONAME ; void CPbk2ContactEditorUIFieldBase::SetFocus(void)
-	?NewL@CPbk2UIFieldArray@@SAPAV1@ABVTDesC16@@AAVRFs@@AAVMPbk2UIFieldFactory@@@Z @ 95 NONAME ; class CPbk2UIFieldArray * CPbk2UIFieldArray::NewL(class TDesC16 const &, class RFs &, class MPbk2UIFieldFactory &)
-	?ControlId@CPbk2ContactEditorUIFieldBase@@UAEHXZ @ 96 NONAME ; int CPbk2ContactEditorUIFieldBase::ControlId(void)
-	??1CPbk2ContactEditorUIFieldBase@@UAE@XZ @ 97 NONAME ; CPbk2ContactEditorUIFieldBase::~CPbk2ContactEditorUIFieldBase(void)
-	?GetAddressPreviewLC@Pbk2AddressTools@@SAXAAVMVPbkStoreContact@@W4TPbk2FieldGroupId@@AAVRBuf16@@@Z @ 98 NONAME ; void Pbk2AddressTools::GetAddressPreviewLC(class MVPbkStoreContact &, enum TPbk2FieldGroupId, class RBuf16 &)
-	?GetAddressFieldsLC@Pbk2AddressTools@@SAXAAVMVPbkStoreContact@@W4TPbk2FieldGroupId@@AAV?$RHashMap@HVTPtrC16@@@@@Z @ 99 NONAME ; void Pbk2AddressTools::GetAddressFieldsLC(class MVPbkStoreContact &, enum TPbk2FieldGroupId, class RHashMap<int, class TPtrC16> &)
-	??0CPbk2ContactEditorUIFieldBase@@IAE@PAVMPbk2UIField@@AAVMPbk2ContactEditorUiBuilder@@AAVCPbk2IconInfoContainer@@H@Z @ 100 NONAME ; CPbk2ContactEditorUIFieldBase::CPbk2ContactEditorUIFieldBase(class MPbk2UIField *, class MPbk2ContactEditorUiBuilder &, class CPbk2IconInfoContainer &, int)
-	?LoadBitmapToFieldL@CPbk2ContactEditorUIFieldBase@@UAEXABVTPbk2IconId@@@Z @ 101 NONAME ; void CPbk2ContactEditorUIFieldBase::LoadBitmapToFieldL(class TPbk2IconId const &)
-	?MapCtrlTypeToAddress@Pbk2AddressTools@@SA?AW4TPbk2FieldGroupId@@H@Z @ 102 NONAME ; enum TPbk2FieldGroupId Pbk2AddressTools::MapCtrlTypeToAddress(int)
-	?ConsumesKeyEvent@CPbk2ContactEditorUIFieldBase@@UAEHABUTKeyEvent@@W4TEventCode@@@Z @ 103 NONAME ; int CPbk2ContactEditorUIFieldBase::ConsumesKeyEvent(struct TKeyEvent const &, enum TEventCode)
-	?MapCtrlTypeToViewType@Pbk2AddressTools@@SA?AW4TActiveView@TPbk2ContactEditorParams@@H@Z @ 104 NONAME ; enum TPbk2ContactEditorParams::TActiveView Pbk2AddressTools::MapCtrlTypeToViewType(int)
-	?UIField@CPbk2ContactEditorUIFieldBase@@UBEPAVMPbk2UIField@@XZ @ 105 NONAME ; class MPbk2UIField * CPbk2ContactEditorUIFieldBase::UIField(void) const
-	?MapAddressToOrdering@Pbk2AddressTools@@SAHW4TPbk2FieldGroupId@@@Z @ 106 NONAME ; int Pbk2AddressTools::MapAddressToOrdering(enum TPbk2FieldGroupId)
-	?ControlText@CPbk2ContactEditorUIFieldBase@@UBEABVTDesC16@@XZ @ 107 NONAME ; class TDesC16 const & CPbk2ContactEditorUIFieldBase::ControlText(void) const
-	?ExecuteLD@CPbk2GeneralConfirmationQuery@@QAEHABVMVPbkBaseContact@@HH@Z @ 108 NONAME ; int CPbk2GeneralConfirmationQuery::ExecuteLD(class MVPbkBaseContact const &, int, int)
-	?SetCurrentGroupLinkL@CPbk2NamesListControl@@QAEXPAVMVPbkContactLink@@@Z @ 109 NONAME ; void CPbk2NamesListControl::SetCurrentGroupLinkL(class MVPbkContactLink *)
-	?NewL@CPbk2ThumbnailManager@@SAPAV1@AAVCVPbkContactManager@@@Z @ 110 NONAME ; class CPbk2ThumbnailManager * CPbk2ThumbnailManager::NewL(class CVPbkContactManager &)
-	?NewL@CPbk2NamesListControl@@SAPAV1@HPBVCCoeControl@@AAVCVPbkContactManager@@AAVMVPbkContactViewBase@@AAVMPbk2ContactNameFormatter@@AAVCPbk2StorePropertyArray@@PAVCPbk2ThumbnailManager@@@Z @ 111 NONAME ; class CPbk2NamesListControl * CPbk2NamesListControl::NewL(int, class CCoeControl const *, class CVPbkContactManager &, class MVPbkContactViewBase &, class MPbk2ContactNameFormatter &, class CPbk2StorePropertyArray &, class CPbk2ThumbnailManager *)
-	?ExecuteLD@CPbk2MemoryEntryDefaultsAssignDlg@@QAEHABVCPbk2PresentationContactFieldCollection@@ABVCVPbkContactManager@@ABVMPbk2FieldPropertyArray@@W4TVPbkContactActionTypeSelector@VPbkFieldTypeSelectorFactory@@@Z @ 112 NONAME ; int CPbk2MemoryEntryDefaultsAssignDlg::ExecuteLD(class CPbk2PresentationContactFieldCollection const &, class CVPbkContactManager const &, class MPbk2FieldPropertyArray const &, enum VPbkFieldTypeSelectorFactory::TVPbkContactActionTypeSelector)
-	?NewL@CPbk2ContactEditorDlg@@SAPAV1@AAVTPbk2ContactEditorParams@@PAVMVPbkStoreContact@@AAVMPbk2EditedContactObserver@@PAVMPbk2ApplicationServices@@PAVHBufC16@@H@Z @ 113 NONAME ; class CPbk2ContactEditorDlg * CPbk2ContactEditorDlg::NewL(class TPbk2ContactEditorParams &, class MVPbkStoreContact *, class MPbk2EditedContactObserver &, class MPbk2ApplicationServices *, class HBufC16 *, int)
-	?NewL@CPbk2AddItemToContactDlg@@SAPAV1@PAVMPbk2ApplicationServices@@@Z @ 114 NONAME ; class CPbk2AddItemToContactDlg * CPbk2AddItemToContactDlg::NewL(class MPbk2ApplicationServices *)
-	?NewL@CPbk2MergeConflictsDlg@@SAPAV1@PAVMPbk2MergeResolver@@H@Z @ 115 NONAME ; class CPbk2MergeConflictsDlg * CPbk2MergeConflictsDlg::NewL(class MPbk2MergeResolver *, int)
-	?NewL@CPbk2MergePhotoConflictDlg@@SAPAV1@PAVMVPbkBaseContact@@0PAH@Z @ 116 NONAME ; class CPbk2MergePhotoConflictDlg * CPbk2MergePhotoConflictDlg::NewL(class MVPbkBaseContact *, class MVPbkBaseContact *, int *)
-	?StopQuery@CPbk2GeneralConfirmationQuery@@QAEXXZ @ 117 NONAME ; void CPbk2GeneralConfirmationQuery::StopQuery(void)
-	?HandleViewForegroundEventL@CPbk2NamesListControl@@QAEXH@Z @ 118 NONAME ; void CPbk2NamesListControl::HandleViewForegroundEventL(int)
-	?MapVPbkFieldTypeToAddressGroupId@Pbk2AddressTools@@SA?AW4TPbk2FieldGroupId@@PBVMVPbkFieldType@@@Z @ 119 NONAME ; enum TPbk2FieldGroupId Pbk2AddressTools::MapVPbkFieldTypeToAddressGroupId(class MVPbkFieldType const *)
-	?IsAddressPreviewEmptyL@Pbk2AddressTools@@SAHAAVMVPbkStoreContact@@W4TPbk2FieldGroupId@@@Z @ 120 NONAME ; int Pbk2AddressTools::IsAddressPreviewEmptyL(class MVPbkStoreContact &, enum TPbk2FieldGroupId)
-	?MassUpdateSkipProgressNote@CPbk2NamesListControl@@QAEXH@Z @ 121 NONAME ; void CPbk2NamesListControl::MassUpdateSkipProgressNote(int)
-	?SetOpeningCca@CPbk2NamesListControl@@QAEXH@Z @ 122 NONAME ; void CPbk2NamesListControl::SetOpeningCca(int)
+	?ExecuteLD@CPbk2GeneralConfirmationQuery@@QAEHABVMVPbkBaseContact@@H@Z @ 1 NONAME ; int CPbk2GeneralConfirmationQuery::ExecuteLD(class MVPbkBaseContact const &, int)
+	?NewL@CPbk2ContactInfoControl@@SAPAV1@PBVCCoeControl@@AAVCVPbkContactManager@@AAVMPbk2ContactNameFormatter@@AAVMPbk2FieldPropertyArray@@AAVCPbk2StorePropertyArray@@PAVMPbk2ContactNavigation@@@Z @ 2 NONAME ; class CPbk2ContactInfoControl * CPbk2ContactInfoControl::NewL(class CCoeControl const *, class CVPbkContactManager &, class MPbk2ContactNameFormatter &, class MPbk2FieldPropertyArray &, class CPbk2StorePropertyArray &, class MPbk2ContactNavigation *)
+	?MapViewTypeToAddress@Pbk2AddressTools@@SA?AW4TPbk2FieldGroupId@@W4TActiveView@TPbk2ContactEditorParams@@@Z @ 3 NONAME ; enum TPbk2FieldGroupId Pbk2AddressTools::MapViewTypeToAddress(enum TPbk2ContactEditorParams::TActiveView)
+	??0TParams@CPbk2FetchDlg@@QAE@XZ @ 4 NONAME ; CPbk2FetchDlg::TParams::TParams(void)
+	?SetAllItemTextL@CPbk2StoreListQuery@@QAEXABVTDesC16@@H@Z @ 5 NONAME ; void CPbk2StoreListQuery::SetAllItemTextL(class TDesC16 const &, int)
+	??0TPbk2AddItemWrapper@@QAE@ABVMPbk2FieldProperty@@@Z @ 6 NONAME ; TPbk2AddItemWrapper::TPbk2AddItemWrapper(class MPbk2FieldProperty const &)
+	?ExecuteLD@CPbk2PhonebookInfoDlg@@QAEXAAVCVPbkContactStoreUriArray@@@Z @ 7 NONAME ; void CPbk2PhonebookInfoDlg::ExecuteLD(class CVPbkContactStoreUriArray &)
+	?SetTimeFormatL@CPbk2FieldFormatter@@QAEXABVTDesC16@@@Z @ 8 NONAME ; void CPbk2FieldFormatter::SetTimeFormatL(class TDesC16 const &)
+	?StopWait@CPbk2InputAbsorber@@QAEXXZ @ 9 NONAME ; void CPbk2InputAbsorber::StopWait(void)
+	??0TPbk2AddItemWrapper@@QAE@ABVCPbk2FieldPropertyGroup@@@Z @ 10 NONAME ; TPbk2AddItemWrapper::TPbk2AddItemWrapper(class CPbk2FieldPropertyGroup const &)
+	?RemoveDefaultsL@CPbk2DefaultAttributeProcess@@QAEXPAV?$CArrayFixFlat@W4TVPbkDefaultType@@@@@Z @ 11 NONAME ; void CPbk2DefaultAttributeProcess::RemoveDefaultsL(class CArrayFixFlat<enum TVPbkDefaultType> *)
+	?NewL@CPbk2DefaultAttributeProcess@@SAPAV1@AAVCVPbkContactManager@@AAVMVPbkStoreContact@@AAVMPbk2DefaultAttributeProcessObserver@@@Z @ 12 NONAME ; class CPbk2DefaultAttributeProcess * CPbk2DefaultAttributeProcess::NewL(class CVPbkContactManager &, class MVPbkStoreContact &, class MPbk2DefaultAttributeProcessObserver &)
+	?SetDefaultL@CPbk2DefaultAttributeProcess@@QAEXW4TVPbkDefaultType@@AAVMVPbkStoreContactField@@@Z @ 13 NONAME ; void CPbk2DefaultAttributeProcess::SetDefaultL(enum TVPbkDefaultType, class MVPbkStoreContactField &)
+	?ExecuteLD@CPbk2AddItemToContactDlg@@QAEHAAV?$RArray@VTPbk2AddItemWrapper@@@@PBVTPbk2AddItemDialogParams@@@Z @ 14 NONAME ; int CPbk2AddItemToContactDlg::ExecuteLD(class RArray<class TPbk2AddItemWrapper> &, class TPbk2AddItemDialogParams const *)
+	?SetFocusedStoreContact@CPbk2ContactUiControlSubstitute@@QAEXABVMVPbkStoreContact@@@Z @ 15 NONAME ; void CPbk2ContactUiControlSubstitute::SetFocusedStoreContact(class MVPbkStoreContact const &)
+	?NewL@CPbk2ThumbnailManager@@SAPAV1@AAVCVPbkContactManager@@@Z @ 16 NONAME ; class CPbk2ThumbnailManager * CPbk2ThumbnailManager::NewL(class CVPbkContactManager &)
+	?NewL@CPbk2SettingsListControl@@SAPAV1@PBVCCoeControl@@AAVCPbk2SortOrderManager@@AAVMPbk2SettingsControlExtension@@@Z @ 17 NONAME ; class CPbk2SettingsListControl * CPbk2SettingsListControl::NewL(class CCoeControl const *, class CPbk2SortOrderManager &, class MPbk2SettingsControlExtension &)
+	?NewL@CPbk2ContactUiControlSubstitute@@SAPAV1@XZ @ 18 NONAME ; class CPbk2ContactUiControlSubstitute * CPbk2ContactUiControlSubstitute::NewL(void)
+	?ExecuteLD@CPbk2GeneralConfirmationQuery@@QAEHHH@Z @ 19 NONAME ; int CPbk2GeneralConfirmationQuery::ExecuteLD(int, int)
+	?Wait@CPbk2InputAbsorber@@QAEXXZ @ 20 NONAME ; void CPbk2InputAbsorber::Wait(void)
+	?StopQuery@CPbk2GeneralConfirmationQuery@@QAEXXZ @ 21 NONAME ; void CPbk2GeneralConfirmationQuery::StopQuery(void)
+	?SetCba@CPbk2AddressSelect@@QAEXH@Z @ 22 NONAME ; void CPbk2AddressSelect::SetCba(int)
+	?LoadThumbnailL@CPbk2ThumbnailLoader@@QAEXPAVMVPbkContactLink@@PBVCEikListBox@@W4TPbk2ThumbnailLocation@@@Z @ 23 NONAME ; void CPbk2ThumbnailLoader::LoadThumbnailL(class MVPbkContactLink *, class CEikListBox const *, enum TPbk2ThumbnailLocation)
+	?NewL@CPbk2MemoryEntryDefaultsAssignDlg@@SAPAV1@XZ @ 24 NONAME ; class CPbk2MemoryEntryDefaultsAssignDlg * CPbk2MemoryEntryDefaultsAssignDlg::NewL(void)
+	?ExecuteLD@CPbk2GeneralConfirmationQuery@@QAEHABVMVPbkBaseContact@@HH@Z @ 25 NONAME ; int CPbk2GeneralConfirmationQuery::ExecuteLD(class MVPbkBaseContact const &, int, int)
+	??1CPbk2AddressSelect@@UAE@XZ @ 26 NONAME ; CPbk2AddressSelect::~CPbk2AddressSelect(void)
+	?MapVPbkFieldTypeToAddressGroupId@Pbk2AddressTools@@SA?AW4TPbk2FieldGroupId@@PBVMVPbkFieldType@@@Z @ 27 NONAME ; enum TPbk2FieldGroupId Pbk2AddressTools::MapVPbkFieldTypeToAddressGroupId(class MVPbkFieldType const *)
+	?GetAddressShortPreviewLC@Pbk2AddressTools@@SAXAAVMVPbkStoreContact@@W4TPbk2FieldGroupId@@AAVRBuf16@@@Z @ 28 NONAME ; void Pbk2AddressTools::GetAddressShortPreviewLC(class MVPbkStoreContact &, enum TPbk2FieldGroupId, class RBuf16 &)
+	?NewL@CPbk2NamesListControl@@SAPAV1@HPBVCCoeControl@@AAVCVPbkContactManager@@AAVMVPbkContactViewBase@@AAVMPbk2ContactNameFormatter@@AAVCPbk2StorePropertyArray@@PAVCPbk2ThumbnailManager@@@Z @ 29 NONAME ; class CPbk2NamesListControl * CPbk2NamesListControl::NewL(int, class CCoeControl const *, class CVPbkContactManager &, class MVPbkContactViewBase &, class MPbk2ContactNameFormatter &, class CPbk2StorePropertyArray &, class CPbk2ThumbnailManager *)
+	?AcceptDelayedFetchL@CPbk2FetchDlg@@QAEXABVTDesC8@@@Z @ 30 NONAME ; void CPbk2FetchDlg::AcceptDelayedFetchL(class TDesC8 const &)
+	?SetViewL@CPbk2NamesListControl@@QAEXAAVMVPbkContactViewBase@@@Z @ 31 NONAME ; void CPbk2NamesListControl::SetViewL(class MVPbkContactViewBase &)
+	?CreateTitlePanePictureLC@Pbk2TitlePanePictureFactory@@SAPAVCEikImage@@PBVMVPbkStoreContact@@AAVCPbk2StorePropertyArray@@@Z @ 32 NONAME ; class CEikImage * Pbk2TitlePanePictureFactory::CreateTitlePanePictureLC(class MVPbkStoreContact const *, class CPbk2StorePropertyArray &)
+	?SetCommandObserver@CPbk2InputAbsorber@@QAEXPAVMEikCommandObserver@@@Z @ 33 NONAME ; void CPbk2InputAbsorber::SetCommandObserver(class MEikCommandObserver *)
+	?InitializeL@CPbk2ContactEditorReadonlyField@@QAEXPAVMPbk2ContactEditorUIField@@@Z @ 34 NONAME ; void CPbk2ContactEditorReadonlyField::InitializeL(class MPbk2ContactEditorUIField *)
+	?SetCurrentGroupLinkL@CPbk2NamesListControl@@QAEXPAVMVPbkContactLink@@@Z @ 35 NONAME ; void CPbk2NamesListControl::SetCurrentGroupLinkL(class MVPbkContactLink *)
+	?Reset@CPbk2NamesListControl@@QAEXXZ @ 36 NONAME ; void CPbk2NamesListControl::Reset(void)
+	?RemoveObserver@CPbk2ContactInfoControl@@QAEXAAVMPbk2ControlObserver@@@Z @ 37 NONAME ; void CPbk2ContactInfoControl::RemoveObserver(class MPbk2ControlObserver &)
+	?NewL@CPbk2StoreListQuery@@SAPAV1@XZ @ 38 NONAME ; class CPbk2StoreListQuery * CPbk2StoreListQuery::NewL(void)
+	?NewLC@CPbk2InputAbsorber@@SAPAV1@H@Z @ 39 NONAME ; class CPbk2InputAbsorber * CPbk2InputAbsorber::NewLC(int)
+	?NewL@CPbk2MergePhotoConflictDlg@@SAPAV1@PAVMVPbkBaseContact@@0PAH@Z @ 40 NONAME ; class CPbk2MergePhotoConflictDlg * CPbk2MergePhotoConflictDlg::NewL(class MVPbkBaseContact *, class MVPbkBaseContact *, int *)
+	??0CPbk2NamesListControl@@QAE@PBVCCoeControl@@AAVCVPbkContactManager@@AAVMVPbkContactViewBase@@AAVMPbk2ContactNameFormatter@@AAVCPbk2StorePropertyArray@@@Z @ 41 NONAME ; CPbk2NamesListControl::CPbk2NamesListControl(class CCoeControl const *, class CVPbkContactManager &, class MVPbkContactViewBase &, class MPbk2ContactNameFormatter &, class CPbk2StorePropertyArray &)
+	?SetTextL@CPbk2ContactEditorReadonlyField@@QAEXPBVTDesC16@@@Z @ 42 NONAME ; void CPbk2ContactEditorReadonlyField::SetTextL(class TDesC16 const *)
+	?GiveViewL@CPbk2NamesListControl@@QAEXPAVMVPbkContactViewBase@@@Z @ 43 NONAME ; void CPbk2NamesListControl::GiveViewL(class MVPbkContactViewBase *)
+	?FieldLabel@CPbk2ContactEditorUIFieldBase@@UBEABVTDesC16@@XZ @ 44 NONAME ; class TDesC16 const & CPbk2ContactEditorUIFieldBase::FieldLabel(void) const
+	?RemoveDefaultL@CPbk2DefaultAttributeProcess@@QAEXW4TVPbkDefaultType@@@Z @ 45 NONAME ; void CPbk2DefaultAttributeProcess::RemoveDefaultL(enum TVPbkDefaultType)
+	?MassUpdateSkipProgressNote@CPbk2NamesListControl@@QAEXH@Z @ 46 NONAME ; void CPbk2NamesListControl::MassUpdateSkipProgressNote(int)
+	?MapAddressToVersitParam@Pbk2AddressTools@@SA?AW4TVPbkFieldTypeParameter@@W4TPbk2FieldGroupId@@@Z @ 47 NONAME ; enum TVPbkFieldTypeParameter Pbk2AddressTools::MapAddressToVersitParam(enum TPbk2FieldGroupId)
+	??0TPbk2AddressSelectParams@@QAE@AAVMVPbkStoreContact@@ABVCVPbkContactManager@@AAVMPbk2ContactNameFormatter@@ABVCPbk2FieldPropertyArray@@AAVTResourceReader@@H@Z @ 48 NONAME ; TPbk2AddressSelectParams::TPbk2AddressSelectParams(class MVPbkStoreContact &, class CVPbkContactManager const &, class MPbk2ContactNameFormatter &, class CPbk2FieldPropertyArray const &, class TResourceReader &, int)
+	?NewL@CPbk2MergeConflictsDlg@@SAPAV1@PAVMPbk2MergeResolver@@H@Z @ 49 NONAME ; class CPbk2MergeConflictsDlg * CPbk2MergeConflictsDlg::NewL(class MPbk2MergeResolver *, int)
+	?NewL@CPbk2ContactIconsUtils@@SAPAV1@AAVCPbk2StorePropertyArray@@PAVMPbk2ContactUiControlExtension@@@Z @ 50 NONAME ; class CPbk2ContactIconsUtils * CPbk2ContactIconsUtils::NewL(class CPbk2StorePropertyArray &, class MPbk2ContactUiControlExtension *)
+	?HandleCustomFieldCommandL@CPbk2ContactEditorUIFieldBase@@UAEHH@Z @ 51 NONAME ; int CPbk2ContactEditorUIFieldBase::HandleCustomFieldCommandL(int)
+	?NewL@CPbk2InputAbsorber@@SAPAV1@H@Z @ 52 NONAME ; class CPbk2InputAbsorber * CPbk2InputAbsorber::NewL(int)
+	??BTParams@CPbk2FetchDlg@@QAE?AVTCleanupItem@@XZ @ 53 NONAME ; CPbk2FetchDlg::TParams::operator class TCleanupItem(void)
+	?SetDefaultPriorities@TPbk2AddressSelectParams@@QAEXABVRVPbkContactFieldDefaultPriorities@@@Z @ 54 NONAME ; void TPbk2AddressSelectParams::SetDefaultPriorities(class RVPbkContactFieldDefaultPriorities const &)
+	?CreatePhoneNumberFormatterL@Pbk2PhoneNumberFormatterFactory@@SAPAVMPbk2PhoneNumberFormatter@@H@Z @ 55 NONAME ; class MPbk2PhoneNumberFormatter * Pbk2PhoneNumberFormatterFactory::CreatePhoneNumberFormatterL(int)
+	?RemoveObserver@CPbk2NamesListControl@@QAEXAAVMPbk2ControlObserver@@@Z @ 56 NONAME ; void CPbk2NamesListControl::RemoveObserver(class MPbk2ControlObserver &)
+	?HideThumbnail@CPbk2ThumbnailLoader@@QAEXXZ @ 57 NONAME ; void CPbk2ThumbnailLoader::HideThumbnail(void)
+	?CreateListboxIconArrayL@CPbk2ContactIconsUtils@@SAPAVCPbk2IconArray@@H@Z @ 58 NONAME ; class CPbk2IconArray * CPbk2ContactIconsUtils::CreateListboxIconArrayL(int)
+	?SetFieldLabelL@CPbk2ContactEditorUIFieldBase@@UAEXABVTDesC16@@@Z @ 59 NONAME ; void CPbk2ContactEditorUIFieldBase::SetFieldLabelL(class TDesC16 const &)
+	?NewL@CPbk2ThumbnailLoader@@SAPAV1@AAVCVPbkContactManager@@@Z @ 60 NONAME ; class CPbk2ThumbnailLoader * CPbk2ThumbnailLoader::NewL(class CVPbkContactManager &)
+	?NewL@CPbk2PhonebookInfoDlg@@SAPAV1@XZ @ 61 NONAME ; class CPbk2PhonebookInfoDlg * CPbk2PhonebookInfoDlg::NewL(void)
+	?NewL@CPbk2NamesListControl@@SAPAV1@HPBVCCoeControl@@AAVCVPbkContactManager@@AAVMVPbkContactViewBase@@AAVMPbk2ContactNameFormatter@@AAVCPbk2StorePropertyArray@@@Z @ 62 NONAME ; class CPbk2NamesListControl * CPbk2NamesListControl::NewL(int, class CCoeControl const *, class CVPbkContactManager &, class MVPbkContactViewBase &, class MPbk2ContactNameFormatter &, class CPbk2StorePropertyArray &)
+	?AllowPointerEvents@CPbk2NamesListControl@@QAEXH@Z @ 63 NONAME ; void CPbk2NamesListControl::AllowPointerEvents(int)
+	?GetIconIdsForContactL@CPbk2ContactIconsUtils@@QBEXABVMVPbkViewContact@@AAV?$RArray@VTPbk2IconId@@@@@Z @ 64 NONAME ; void CPbk2ContactIconsUtils::GetIconIdsForContactL(class MVPbkViewContact const &, class RArray<class TPbk2IconId> &) const
+	?ExecuteLD@CPbk2MemoryEntryDefaultsDlg@@QAEXXZ @ 65 NONAME ; void CPbk2MemoryEntryDefaultsDlg::ExecuteLD(void)
+	?NewL@CPbk2GeneralConfirmationQuery@@SAPAV1@XZ @ 66 NONAME ; class CPbk2GeneralConfirmationQuery * CPbk2GeneralConfirmationQuery::NewL(void)
+	?SetDefaultsL@CPbk2DefaultAttributeProcess@@QAEXPAV?$CArrayFixFlat@W4TVPbkDefaultType@@@@AAVMVPbkStoreContactField@@@Z @ 67 NONAME ; void CPbk2DefaultAttributeProcess::SetDefaultsL(class CArrayFixFlat<enum TVPbkDefaultType> *, class MVPbkStoreContactField &)
+	?NewL@CPbk2MemoryEntryDefaultsDlg@@SAPAV1@AAVCPbk2PresentationContact@@AAVCVPbkContactManager@@@Z @ 68 NONAME ; class CPbk2MemoryEntryDefaultsDlg * CPbk2MemoryEntryDefaultsDlg::NewL(class CPbk2PresentationContact &, class CVPbkContactManager &)
+	?AttemptExitL@CPbk2AddressSelect@@QAEXH@Z @ 69 NONAME ; void CPbk2AddressSelect::AttemptExitL(int)
+	?SetFocusedFieldIndex@CPbk2ContactUiControlSubstitute@@UAEXH@Z @ 70 NONAME ; void CPbk2ContactUiControlSubstitute::SetFocusedFieldIndex(int)
+	?SetUseDefaultDirectly@TPbk2AddressSelectParams@@QAEXH@Z @ 71 NONAME ; void TPbk2AddressSelectParams::SetUseDefaultDirectly(int)
+	?ExecuteLD@CPbk2ContactEditorDlg@@QAEXXZ @ 72 NONAME ; void CPbk2ContactEditorDlg::ExecuteLD(void)
+	?SetFocus@CPbk2ContactEditorUIFieldBase@@UAEXXZ @ 73 NONAME ; void CPbk2ContactEditorUIFieldBase::SetFocus(void)
+	?Refresh@CPbk2ThumbnailLoader@@QAEXXZ @ 74 NONAME ; void CPbk2ThumbnailLoader::Refresh(void)
+	?ExecuteLD@CPbk2FetchDlg@@QAEHXZ @ 75 NONAME ; int CPbk2FetchDlg::ExecuteLD(void)
+	?NewL@CPbk2UIFieldArray@@SAPAV1@ABVTDesC16@@AAVRFs@@AAVMPbk2UIFieldFactory@@@Z @ 76 NONAME ; class CPbk2UIFieldArray * CPbk2UIFieldArray::NewL(class TDesC16 const &, class RFs &, class MPbk2UIFieldFactory &)
+	?CommitSettingsL@CPbk2SettingsListControl@@QAEXXZ @ 77 NONAME ; void CPbk2SettingsListControl::CommitSettingsL(void)
+	?NewL@CPbk2AddressSelect@@SAPAV1@AAVTPbk2AddressSelectParams@@@Z @ 78 NONAME ; class CPbk2AddressSelect * CPbk2AddressSelect::NewL(class TPbk2AddressSelectParams &)
+	?Reset@CPbk2ThumbnailLoader@@QAEXXZ @ 79 NONAME ; void CPbk2ThumbnailLoader::Reset(void)
+	?ExecuteLD@CPbk2MemoryEntryDefaultsAssignDlg@@QAEHABVCPbk2PresentationContactFieldCollection@@ABVCVPbkContactManager@@ABVMPbk2FieldPropertyArray@@W4TVPbkContactActionTypeSelector@VPbkFieldTypeSelectorFactory@@@Z @ 80 NONAME ; int CPbk2MemoryEntryDefaultsAssignDlg::ExecuteLD(class CPbk2PresentationContactFieldCollection const &, class CVPbkContactManager const &, class MPbk2FieldPropertyArray const &, enum VPbkFieldTypeSelectorFactory::TVPbkContactActionTypeSelector)
+	?NewL@CPbk2AddressSelect@@SAPAV1@AAVTPbk2AddressSelectParams@@AAVCVPbkFieldTypeSelector@@PBV?$TArray@PAVMVPbkStoreContact@@@@PBV?$TArray@PAVCPbk2PresenceIconInfo@@@@@Z @ 81 NONAME ; class CPbk2AddressSelect * CPbk2AddressSelect::NewL(class TPbk2AddressSelectParams &, class CVPbkFieldTypeSelector &, class TArray<class MVPbkStoreContact *> const *, class TArray<class CPbk2PresenceIconInfo *> const *)
+	?PropertyCount@TPbk2AddItemWrapper@@QBEHXZ @ 82 NONAME ; int TPbk2AddItemWrapper::PropertyCount(void) const
+	?ExecuteLD@CPbk2AddressSelect@@QAEPAVMVPbkStoreContactField@@XZ @ 83 NONAME ; class MVPbkStoreContactField * CPbk2AddressSelect::ExecuteLD(void)
+	?ControlId@CPbk2ContactEditorUIFieldBase@@UAEHXZ @ 84 NONAME ; int CPbk2ContactEditorUIFieldBase::ControlId(void)
+	?IsWaiting@CPbk2InputAbsorber@@QBEHXZ @ 85 NONAME ; int CPbk2InputAbsorber::IsWaiting(void) const
+	??1CPbk2ContactEditorUIFieldBase@@UAE@XZ @ 86 NONAME ; CPbk2ContactEditorUIFieldBase::~CPbk2ContactEditorUIFieldBase(void)
+	?SetFocusedField@CPbk2ContactUiControlSubstitute@@QAEXABVMVPbkBaseContactField@@@Z @ 87 NONAME ; void CPbk2ContactUiControlSubstitute::SetFocusedField(class MVPbkBaseContactField const &)
+	?GetAddressPreviewLC@Pbk2AddressTools@@SAXAAVMVPbkStoreContact@@W4TPbk2FieldGroupId@@AAVRBuf16@@@Z @ 88 NONAME ; void Pbk2AddressTools::GetAddressPreviewLC(class MVPbkStoreContact &, enum TPbk2FieldGroupId, class RBuf16 &)
+	?NewL@CPbk2AddItemToContactDlg@@SAPAV1@XZ @ 89 NONAME ; class CPbk2AddItemToContactDlg * CPbk2AddItemToContactDlg::NewL(void)
+	?NewL@CPbk2FieldFormatter@@SAPAV1@ABVMPbk2FieldPropertyArray@@ABVMVPbkFieldTypeList@@@Z @ 90 NONAME ; class CPbk2FieldFormatter * CPbk2FieldFormatter::NewL(class MPbk2FieldPropertyArray const &, class MVPbkFieldTypeList const &)
+	?NewL@CPbk2PrependDlg@@SAPAV1@AAVTDes16@@@Z @ 91 NONAME ; class CPbk2PrependDlg * CPbk2PrependDlg::NewL(class TDes16 &)
+	?AddObserverL@CPbk2NamesListControl@@QAEXAAVMPbk2ControlObserver@@@Z @ 92 NONAME ; void CPbk2NamesListControl::AddObserverL(class MPbk2ControlObserver &)
+	?FormatFieldContentL@CPbk2FieldFormatter@@QAE?AVTPtrC16@@ABVMVPbkBaseContactField@@ABVMVPbkFieldType@@@Z @ 93 NONAME ; class TPtrC16 CPbk2FieldFormatter::FormatFieldContentL(class MVPbkBaseContactField const &, class MVPbkFieldType const &)
+	?SetTitleToIncludeContactName@TPbk2AddressSelectParams@@QAEXH@Z @ 94 NONAME ; void TPbk2AddressSelectParams::SetTitleToIncludeContactName(int)
+	?SetSelectedStore@CPbk2ContactUiControlSubstitute@@QAEXAAVMVPbkContactStore@@@Z @ 95 NONAME ; void CPbk2ContactUiControlSubstitute::SetSelectedStore(class MVPbkContactStore &)
+	?SetFocusedField@TPbk2AddressSelectParams@@QAEXPBVMVPbkStoreContactField@@@Z @ 96 NONAME ; void TPbk2AddressSelectParams::SetFocusedField(class MVPbkStoreContactField const *)
+	?GetAddressFieldsLC@Pbk2AddressTools@@SAXAAVMVPbkStoreContact@@W4TPbk2FieldGroupId@@AAV?$RHashMap@HVTPtrC16@@@@@Z @ 97 NONAME ; void Pbk2AddressTools::GetAddressFieldsLC(class MVPbkStoreContact &, enum TPbk2FieldGroupId, class RHashMap<int, class TPtrC16> &)
+	?SetParentUiControl@CPbk2ContactUiControlSubstitute@@QAEXAAVMPbk2ContactUiControl@@@Z @ 98 NONAME ; void CPbk2ContactUiControlSubstitute::SetParentUiControl(class MPbk2ContactUiControl &)
+	?ExecuteLD@CPbk2StoreListQuery@@QAEHABVTDesC16@@AAVCVPbkContactStoreUriArray@@@Z @ 99 NONAME ; int CPbk2StoreListQuery::ExecuteLD(class TDesC16 const &, class CVPbkContactStoreUriArray &)
+	?DenyDelayedFetchL@CPbk2FetchDlg@@QAEXABVTDesC8@@@Z @ 100 NONAME ; void CPbk2FetchDlg::DenyDelayedFetchL(class TDesC8 const &)
+	??0CPbk2ContactEditorUIFieldBase@@IAE@PAVMPbk2UIField@@AAVMPbk2ContactEditorUiBuilder@@AAVCPbk2IconInfoContainer@@H@Z @ 101 NONAME ; CPbk2ContactEditorUIFieldBase::CPbk2ContactEditorUIFieldBase(class MPbk2UIField *, class MPbk2ContactEditorUiBuilder &, class CPbk2IconInfoContainer &, int)
+	?LoadThumbnail@CPbk2ThumbnailLoader@@QAEXPAVMVPbkStoreContact@@PBVCEikListBox@@W4TPbk2ThumbnailLocation@@@Z @ 102 NONAME ; void CPbk2ThumbnailLoader::LoadThumbnail(class MVPbkStoreContact *, class CEikListBox const *, enum TPbk2ThumbnailLocation)
+	?LoadBitmapToFieldL@CPbk2ContactEditorUIFieldBase@@UAEXABVTPbk2IconId@@@Z @ 103 NONAME ; void CPbk2ContactEditorUIFieldBase::LoadBitmapToFieldL(class TPbk2IconId const &)
+	?MapCtrlTypeToAddress@Pbk2AddressTools@@SA?AW4TPbk2FieldGroupId@@H@Z @ 104 NONAME ; enum TPbk2FieldGroupId Pbk2AddressTools::MapCtrlTypeToAddress(int)
+	?MapAddressToOrdering@Pbk2AddressTools@@SAHW4TPbk2FieldGroupId@@@Z @ 105 NONAME ; int Pbk2AddressTools::MapAddressToOrdering(enum TPbk2FieldGroupId)
+	?SetOpeningCca@CPbk2NamesListControl@@QAEXH@Z @ 106 NONAME ; void CPbk2NamesListControl::SetOpeningCca(int)
+	?ConsumesKeyEvent@CPbk2ContactEditorUIFieldBase@@UAEHABUTKeyEvent@@W4TEventCode@@@Z @ 107 NONAME ; int CPbk2ContactEditorUIFieldBase::ConsumesKeyEvent(struct TKeyEvent const &, enum TEventCode)
+	?IsAddressPreviewEmptyL@Pbk2AddressTools@@SAHAAVMVPbkStoreContact@@W4TPbk2FieldGroupId@@@Z @ 108 NONAME ; int Pbk2AddressTools::IsAddressPreviewEmptyL(class MVPbkStoreContact &, enum TPbk2FieldGroupId)
+	?MapCtrlTypeToViewType@Pbk2AddressTools@@SA?AW4TActiveView@TPbk2ContactEditorParams@@H@Z @ 109 NONAME ; enum TPbk2ContactEditorParams::TActiveView Pbk2AddressTools::MapCtrlTypeToViewType(int)
+	?NewL@CPbk2AddItemToContactDlg@@SAPAV1@PAVMPbk2ApplicationServices@@@Z @ 110 NONAME ; class CPbk2AddItemToContactDlg * CPbk2AddItemToContactDlg::NewL(class MPbk2ApplicationServices *)
+	?SetQueryAlways@TPbk2AddressSelectParams@@QAEXH@Z @ 111 NONAME ; void TPbk2AddressSelectParams::SetQueryAlways(int)
+	?PropertyAt@TPbk2AddItemWrapper@@QBEABVMPbk2FieldProperty@@H@Z @ 112 NONAME ; class MPbk2FieldProperty const & TPbk2AddItemWrapper::PropertyAt(int) const
+	?Pbk2ControlKeyEventL@CPbk2AddressSelect@@UAE?AW4TKeyResponse@@ABUTKeyEvent@@W4TEventCode@@@Z @ 113 NONAME ; enum TKeyResponse CPbk2AddressSelect::Pbk2ControlKeyEventL(struct TKeyEvent const &, enum TEventCode)
+	?AddObserverL@CPbk2ContactInfoControl@@QAEXAAVMPbk2ControlObserver@@@Z @ 114 NONAME ; void CPbk2ContactInfoControl::AddObserverL(class MPbk2ControlObserver &)
+	?HandleViewForegroundEventL@CPbk2NamesListControl@@QAEXH@Z @ 115 NONAME ; void CPbk2NamesListControl::HandleViewForegroundEventL(int)
+	?NewL@CPbk2ContactEditorDlg@@SAPAV1@AAVTPbk2ContactEditorParams@@PAVMVPbkStoreContact@@AAVMPbk2EditedContactObserver@@PAVMPbk2ApplicationServices@@PAVHBufC16@@H@Z @ 116 NONAME ; class CPbk2ContactEditorDlg * CPbk2ContactEditorDlg::NewL(class TPbk2ContactEditorParams &, class MVPbkStoreContact *, class MPbk2EditedContactObserver &, class MPbk2ApplicationServices *, class HBufC16 *, int)
+	?UIField@CPbk2ContactEditorUIFieldBase@@UBEPAVMPbk2UIField@@XZ @ 117 NONAME ; class MPbk2UIField * CPbk2ContactEditorUIFieldBase::UIField(void) const
+	?SetSuppressWarnings@TPbk2AddressSelectParams@@QAEXH@Z @ 118 NONAME ; void TPbk2AddressSelectParams::SetSuppressWarnings(int)
+	?NewL@CPbk2FetchDlg@@SAPAV1@VTParams@1@AAVMPbk2FetchDlgObserver@@@Z @ 119 NONAME ; class CPbk2FetchDlg * CPbk2FetchDlg::NewL(class CPbk2FetchDlg::TParams, class MPbk2FetchDlgObserver &)
+	??1CPbk2ContactUiControlSubstitute@@UAE@XZ @ 120 NONAME ; CPbk2ContactUiControlSubstitute::~CPbk2ContactUiControlSubstitute(void)
+	?ControlText@CPbk2ContactEditorUIFieldBase@@UBEABVTDesC16@@XZ @ 121 NONAME ; class TDesC16 const & CPbk2ContactEditorUIFieldBase::ControlText(void) const
+	?NewL@CPbk2ContactEditorDlg@@SAPAV1@AAVTPbk2ContactEditorParams@@PAVMVPbkStoreContact@@AAVMPbk2EditedContactObserver@@@Z @ 122 NONAME ; class CPbk2ContactEditorDlg * CPbk2ContactEditorDlg::NewL(class TPbk2ContactEditorParams &, class MVPbkStoreContact *, class MPbk2EditedContactObserver &)
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/phonebookui/Phonebook2/Commands/inc/MPbk2CommandResourceRelease.h	Thu Aug 19 09:41:07 2010 +0300
@@ -0,0 +1,39 @@
+/*
+* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A command extension interface for release resource.
+*
+*/
+
+#ifndef MPBK2COMMANDRESOURCERELEASE_H_
+#define MPBK2COMMANDRESOURCERELEASE_H_
+
+/// Phonebook 2 Command MPbk2ResourceRelease interface UID
+#define MPbk2ResourceReleaseUID              0xE9D61489
+
+// CLASS DECLARATIONS
+
+/**
+ * Phonebook 2 command release resource interface.
+ */
+class MPbk2ResourceRelease
+    {
+    public:
+        /**
+         * Release resource.
+         */
+        virtual void ReleaseResource() = 0;
+     
+    };
+
+#endif /* MPBK2COMMANDRESOURCERELEASE_H_ */
--- a/phonebookui/Phonebook2/Commands/src/CPbk2CommandHandler.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/Commands/src/CPbk2CommandHandler.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -511,13 +511,9 @@
                 {
                 aMenuPane->SetItemDimmed( EPbk2CmdDeleteMe, ETrue );
                 }
-            if ( aControl.ContactsMarked() )
-                {
-                aMenuPane->SetItemSpecific( EPbk2CmdDeleteMe, EFalse );
-                }
             break;
             }
-
+        
         case R_PHONEBOOK2_NAMELIST_CALL_CONTACT_MENU:
             {
             // Weed out commands not meant to be used with marked items
@@ -548,7 +544,6 @@
 
             if ( aControl.ContactsMarked() )
                 {
-                aMenuPane->SetItemDimmed( EPbk2CmdSend, ETrue );
                 aMenuPane->SetItemDimmed( EPbk2CmdGoToURL, ETrue );
                 }
             break;
--- a/phonebookui/Phonebook2/Commands/src/CPbk2CommandStore.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/Commands/src/CPbk2CommandStore.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -18,6 +18,7 @@
 
 // INCLUDE FILES
 #include "CPbk2CommandStore.h"
+#include "MPbk2CommandResourceRelease.h"
 
 // Phonebook 2
 #include <MPbk2Command.h>
@@ -222,11 +223,25 @@
             MPbk2Command* arrayCmd = iCommandArray[j];
             if (idleDestCmd == arrayCmd)
                 {
+                iIdleDestructableCommands.Remove(i);
+                                
+                // Try to get MPbk2ResourceRelease interface.
+                TUid uid;
+                uid.iUid = MPbk2ResourceReleaseUID;
+                MPbk2ResourceRelease* release = static_cast<MPbk2ResourceRelease *>(idleDestCmd->CommandExtension(uid));
+                if (release)
+                  {
+                    // Call ReleaseResource before delete.
+                    release->ReleaseResource();
+                  }
+              
                 // Remove from command array
-                iCommandArray.Remove(j);
-                iIdleDestructableCommands.Remove(i);
+                iCommandArray.Remove(j);                
+                
                 delete idleDestCmd;
                 idleDestCmd = NULL;
+                
+                break;
                 }
             }
         }
--- a/phonebookui/Phonebook2/Commands/src/cpbk2commandactivator.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/Commands/src/cpbk2commandactivator.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -188,5 +188,20 @@
     iObserver->CommandFinished( *this );
     }
   
+// --------------------------------------------------------------------------
+// CPbk2CommandActivator::CommandExtension
+// --------------------------------------------------------------------------
+//
+TAny* CPbk2CommandActivator::CommandExtension(TUid aExtensionUid )
+    {
+      if( iCommand )
+        {
+          return iCommand->CommandExtension(aExtensionUid);
+        }
+      else
+        {
+          return NULL;
+        }
+    }
 
 //  End of File  
--- a/phonebookui/Phonebook2/CommandsExtension/inc/CPbk2SendContactCmd.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/CommandsExtension/inc/CPbk2SendContactCmd.h	Thu Aug 19 09:41:07 2010 +0300
@@ -20,6 +20,9 @@
 #define CPBK2SENDCONTACTCMD_H
 
 // INCLUDES
+
+#include "MPbk2CommandResourceRelease.h"
+
 #include <e32base.h>
 #include <MPbk2Command.h>
 #include <MVPbkSingleContactOperationObserver.h>
@@ -60,7 +63,8 @@
         public MPbk2Command,
         public MPbk2vCardConverterObserver,
         public MVPbkSingleContactOperationObserver,
-        private MPbk2ProcessDecoratorObserver
+        private MPbk2ProcessDecoratorObserver,
+        public MPbk2ResourceRelease
     {
     public: // Construction and destruction
         /**
@@ -81,7 +85,14 @@
         void AddObserver(
                 MPbk2CommandObserver& aObserver );
         void ResetUiControl(MPbk2ContactUiControl& aUiControl);
-
+        TAny* CommandExtension(TUid /*aExtensionUid*/);
+    public: // From MPbk2ResourceRelease
+        /*-
+         * Delete all temp files.
+         * @Remark It not return until finish deleting all files.
+         *         It is non-reentrant.  
+         */
+        void ReleaseResource();
     private: // From CActive
         void RunL();
         TInt RunError(
@@ -134,7 +145,7 @@
         void SendMsgUsingSendUI(
                 CMessageData* aMsgData );
         TBool IsMoreThanOneContact();
-
+        
     private: // Data structures
         /// Process states
         enum TState
@@ -143,7 +154,8 @@
             ERetrievingContact,
             ESelectingSentData,
             EStopping,
-            ECancelling
+            ECancelling,
+            EReleaseResource
             };
 
     private: // Data
@@ -185,6 +197,9 @@
         CPbk2ApplicationServices* iAppServices;
         /// Own: Send UI
         CSendUi* iSendUi;
+        /// Own:
+        CActiveSchedulerWait* iWaiter;
+       
     };
 
 #endif // CPBK2SENDCONTACTCMD_H
--- a/phonebookui/Phonebook2/CommandsExtension/src/CPbk2SendContactCmd.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/CommandsExtension/src/CPbk2SendContactCmd.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -369,6 +369,7 @@
         iUiControl->RegisterCommand( NULL );
         }
 
+    delete iWaiter;
     delete iSelectedContacts;
     delete iConverter;
     delete iVCardSender;
@@ -546,6 +547,25 @@
             ProcessDone( KErrCancel );
             break;
             }
+        case EReleaseResource:
+            {
+            CPbk2AttachmentFileArray& fileArray = iConverter->AttachmentFileArray();
+            TInt count = fileArray.Count();
+            TInt deleteIndex = count -1;
+            CPbk2AttachmentFile * file = fileArray.At(deleteIndex);
+            fileArray.Delete(deleteIndex);
+            delete file;
+            
+            if ( count > 1) 
+            {
+              IssueRequest();
+            }
+            else
+            {
+              iWaiter->AsyncStop();
+            }
+            break;
+            }
         }
     }
 
@@ -555,6 +575,9 @@
 //
 TInt CPbk2SendContactCmd::RunError(TInt aError)
     {
+    if( iWaiter && iWaiter->IsStarted() )
+        iWaiter->AsyncStop();
+    
     return FilterErrors(aError);
     }
 
@@ -564,6 +587,9 @@
 //
 void CPbk2SendContactCmd::DoCancel()
     {
+    if( iWaiter && iWaiter->IsStarted() )
+        iWaiter->AsyncStop();
+    
     delete iRetrieveOperation;
     iRetrieveOperation = NULL;
     }
@@ -1259,4 +1285,51 @@
     return result;
     }
 
+// --------------------------------------------------------------------------
+// CPbk2SendContactCmd::CommandExtension
+// --------------------------------------------------------------------------
+//
+TAny* CPbk2SendContactCmd::CommandExtension(TUid aExtensionUid )
+    {
+     if( aExtensionUid == TUid::Uid(MPbk2ResourceReleaseUID) )
+        {
+        return static_cast<MPbk2ResourceRelease *>(this);
+        }
+     else
+        {
+        return NULL;
+        }
+    }
+
+// --------------------------------------------------------------------------
+// CPbk2SendContactCmd::ReleaseResource
+// --------------------------------------------------------------------------
+//
+void CPbk2SendContactCmd::ReleaseResource()
+    {
+    Cancel();
+    if (iConverter)
+        {
+        iConverter->Cancel();
+        CPbk2AttachmentFileArray& fileArray = iConverter->AttachmentFileArray();        
+        if (fileArray.Count() > 0)
+            {
+            if ( !iWaiter )
+                {
+                TInt err( KErrNone );
+                TRAP( err,iWaiter = new (ELeave) CActiveSchedulerWait());
+                if ( err != KErrNone )
+                    {
+                    fileArray.ResetAndDestroy();
+                    return;
+                    }
+                 }
+            
+              iState = EReleaseResource;
+              IssueRequest();         
+              iWaiter->Start();
+            }
+       }
+    }
+
 // End of File
--- a/phonebookui/Phonebook2/CommandsExtension/src/CPbk2vCardConverter.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/CommandsExtension/src/CPbk2vCardConverter.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -138,6 +138,7 @@
         delete iVcardFiles;
         }
     delete iVCardFile;
+    delete iRetrieveOperation;
     delete iVCardContact;
     iFileWriteStream.Close();
     delete iContactOperation;
--- a/phonebookui/Phonebook2/CommonUI/src/CPbk2ContactNavigation.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/CommonUI/src/CPbk2ContactNavigation.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -141,7 +141,14 @@
         {
         decorator->SetNaviDecoratorObserver
             (  const_cast<CPbk2ContactNavigation*>( this ) );
-        decorator->MakeScrollButtonVisible( ETrue );
+        CAknNavigationDecorator::TControlType controlType = 
+            decorator->ControlType();
+        // Set ScrollButtonVisible to ETrue except
+        // the controlType is CAknNavigationDecorator::ENaviLabel
+        if( CAknNavigationDecorator::ENaviLabel != controlType )
+            {
+            decorator->MakeScrollButtonVisible( ETrue );
+            }
         }
 
     TInt index = 0;
--- a/phonebookui/Phonebook2/EABI/Pbk2UiControlsU.DEF	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/EABI/Pbk2UiControlsU.DEF	Thu Aug 19 09:41:07 2010 +0300
@@ -1,206 +1,207 @@
 EXPORTS
-	_ZN13CPbk2FetchDlg19AcceptDelayedFetchLERK6TDesC8 @ 1 NONAME
-	_ZN13CPbk2FetchDlg4NewLENS_7TParamsER21MPbk2FetchDlgObserver @ 2 NONAME
-	_ZN13CPbk2FetchDlg7TParamsC1Ev @ 3 NONAME
-	_ZN13CPbk2FetchDlg7TParamsC2Ev @ 4 NONAME
-	_ZN13CPbk2FetchDlg7TParamscv12TCleanupItemEv @ 5 NONAME
-	_ZN13CPbk2FetchDlg9ExecuteLDEv @ 6 NONAME
-	_ZN15CPbk2PrependDlg4NewLER6TDes16 @ 7 NONAME
-	_ZN18CPbk2AddressSelect12AttemptExitLEi @ 8 NONAME
-	_ZN18CPbk2AddressSelect20Pbk2ControlKeyEventLERK9TKeyEvent10TEventCode @ 9 NONAME
-	_ZN18CPbk2AddressSelect4NewLER24TPbk2AddressSelectParams @ 10 NONAME
-	_ZN18CPbk2AddressSelect6SetCbaEi @ 11 NONAME
-	_ZN18CPbk2AddressSelect9ExecuteLDEv @ 12 NONAME
-	_ZN18CPbk2AddressSelectD0Ev @ 13 NONAME
-	_ZN18CPbk2AddressSelectD1Ev @ 14 NONAME
-	_ZN18CPbk2AddressSelectD2Ev @ 15 NONAME
-	_ZN18CPbk2InputAbsorber18SetCommandObserverEP19MEikCommandObserver @ 16 NONAME
-	_ZN18CPbk2InputAbsorber4NewLEi @ 17 NONAME
-	_ZN18CPbk2InputAbsorber4WaitEv @ 18 NONAME
-	_ZN18CPbk2InputAbsorber5NewLCEi @ 19 NONAME
-	_ZN18CPbk2InputAbsorber8StopWaitEv @ 20 NONAME
-	_ZN19CPbk2FieldFormatter14SetTimeFormatLERK7TDesC16 @ 21 NONAME
-	_ZN19CPbk2FieldFormatter19FormatFieldContentLERK21MVPbkBaseContactFieldRK14MVPbkFieldType @ 22 NONAME
-	_ZN19CPbk2FieldFormatter4NewLERK23MPbk2FieldPropertyArrayRK18MVPbkFieldTypeList @ 23 NONAME
-	_ZN19CPbk2StoreListQuery15SetAllItemTextLERK7TDesC16i @ 24 NONAME
-	_ZN19CPbk2StoreListQuery4NewLEv @ 25 NONAME
-	_ZN19CPbk2StoreListQuery9ExecuteLDERK7TDesC16R25CVPbkContactStoreUriArray @ 26 NONAME
-	_ZN19TPbk2AddItemWrapperC1ERK18MPbk2FieldProperty @ 27 NONAME
-	_ZN19TPbk2AddItemWrapperC1ERK23CPbk2FieldPropertyGroup @ 28 NONAME
-	_ZN19TPbk2AddItemWrapperC2ERK18MPbk2FieldProperty @ 29 NONAME
-	_ZN19TPbk2AddItemWrapperC2ERK23CPbk2FieldPropertyGroup @ 30 NONAME
-	_ZN20CPbk2ThumbnailLoader13HideThumbnailEv @ 31 NONAME
-	_ZN20CPbk2ThumbnailLoader13LoadThumbnailEP17MVPbkStoreContactPK11CEikListBox22TPbk2ThumbnailLocation @ 32 NONAME
-	_ZN20CPbk2ThumbnailLoader14LoadThumbnailLEP16MVPbkContactLinkPK11CEikListBox22TPbk2ThumbnailLocation @ 33 NONAME
-	_ZN20CPbk2ThumbnailLoader4NewLER19CVPbkContactManager @ 34 NONAME
-	_ZN20CPbk2ThumbnailLoader5ResetEv @ 35 NONAME
-	_ZN20CPbk2ThumbnailLoader7RefreshEv @ 36 NONAME
-	_ZN21CPbk2ContactEditorDlg4NewLER24TPbk2ContactEditorParamsP17MVPbkStoreContactR26MPbk2EditedContactObserver @ 37 NONAME
-	_ZN21CPbk2ContactEditorDlg9ExecuteLDEv @ 38 NONAME
-	_ZN21CPbk2NamesListControl12AddObserverLER20MPbk2ControlObserver @ 39 NONAME
-	_ZN21CPbk2NamesListControl14RemoveObserverER20MPbk2ControlObserver @ 40 NONAME
-	_ZN21CPbk2NamesListControl4NewLEiPK11CCoeControlR19CVPbkContactManagerR20MVPbkContactViewBaseR25MPbk2ContactNameFormatterR23CPbk2StorePropertyArray @ 41 NONAME
-	_ZN21CPbk2NamesListControl5ResetEv @ 42 NONAME
-	_ZN21CPbk2NamesListControl8SetViewLER20MVPbkContactViewBase @ 43 NONAME
-	_ZN21CPbk2NamesListControlC1EPK11CCoeControlR19CVPbkContactManagerR20MVPbkContactViewBaseR25MPbk2ContactNameFormatterR23CPbk2StorePropertyArray @ 44 NONAME
-	_ZN21CPbk2NamesListControlC2EPK11CCoeControlR19CVPbkContactManagerR20MVPbkContactViewBaseR25MPbk2ContactNameFormatterR23CPbk2StorePropertyArray @ 45 NONAME
-	_ZN21CPbk2PhonebookInfoDlg4NewLEv @ 46 NONAME
-	_ZN21CPbk2PhonebookInfoDlg9ExecuteLDER25CVPbkContactStoreUriArray @ 47 NONAME
-	_ZN23CPbk2ContactInfoControl12AddObserverLER20MPbk2ControlObserver @ 48 NONAME
-	_ZN23CPbk2ContactInfoControl14RemoveObserverER20MPbk2ControlObserver @ 49 NONAME
-	_ZN23CPbk2ContactInfoControl4NewLEPK11CCoeControlR19CVPbkContactManagerR25MPbk2ContactNameFormatterR23MPbk2FieldPropertyArrayR23CPbk2StorePropertyArrayP22MPbk2ContactNavigation @ 50 NONAME
-	_ZN24CPbk2AddItemToContactDlg4NewLEv @ 51 NONAME
-	_ZN24CPbk2AddItemToContactDlg9ExecuteLDER6RArrayI19TPbk2AddItemWrapperEPK24TPbk2AddItemDialogParams @ 52 NONAME
-	_ZN24CPbk2SettingsListControl15CommitSettingsLEv @ 53 NONAME
-	_ZN24CPbk2SettingsListControl4NewLEPK11CCoeControlR21CPbk2SortOrderManagerR29MPbk2SettingsControlExtension @ 54 NONAME
-	_ZN24TPbk2AddressSelectParams14SetQueryAlwaysEi @ 55 NONAME
-	_ZN24TPbk2AddressSelectParams15SetFocusedFieldEPK22MVPbkStoreContactField @ 56 NONAME
-	_ZN24TPbk2AddressSelectParams20SetDefaultPrioritiesERK34RVPbkContactFieldDefaultPriorities @ 57 NONAME
-	_ZN24TPbk2AddressSelectParams21SetUseDefaultDirectlyEi @ 58 NONAME
-	_ZN24TPbk2AddressSelectParamsC1ER17MVPbkStoreContactRK19CVPbkContactManagerR25MPbk2ContactNameFormatterRK23CPbk2FieldPropertyArrayR15TResourceReaderi @ 59 NONAME
-	_ZN24TPbk2AddressSelectParamsC2ER17MVPbkStoreContactRK19CVPbkContactManagerR25MPbk2ContactNameFormatterRK23CPbk2FieldPropertyArrayR15TResourceReaderi @ 60 NONAME
-	_ZN27CPbk2MemoryEntryDefaultsDlg4NewLER24CPbk2PresentationContactR19CVPbkContactManager @ 61 NONAME
-	_ZN27CPbk2MemoryEntryDefaultsDlg9ExecuteLDEv @ 62 NONAME
-	_ZN29CPbk2GeneralConfirmationQuery4NewLEv @ 63 NONAME
-	_ZN29CPbk2GeneralConfirmationQuery9ExecuteLDERK16MVPbkBaseContacti @ 64 NONAME
-	_ZN29CPbk2GeneralConfirmationQuery9ExecuteLDEii @ 65 NONAME
-	_ZN31CPbk2ContactUiControlSubstitute15SetFocusedFieldERK21MVPbkBaseContactField @ 66 NONAME
-	_ZN31CPbk2ContactUiControlSubstitute16SetSelectedStoreER17MVPbkContactStore @ 67 NONAME
-	_ZN31CPbk2ContactUiControlSubstitute18SetParentUiControlER21MPbk2ContactUiControl @ 68 NONAME
-	_ZN31CPbk2ContactUiControlSubstitute20SetFocusedFieldIndexEi @ 69 NONAME
-	_ZN31CPbk2ContactUiControlSubstitute22SetFocusedStoreContactERK17MVPbkStoreContact @ 70 NONAME
-	_ZN31CPbk2ContactUiControlSubstitute4NewLEv @ 71 NONAME
-	_ZN31CPbk2ContactUiControlSubstituteD0Ev @ 72 NONAME
-	_ZN31CPbk2ContactUiControlSubstituteD1Ev @ 73 NONAME
-	_ZN31CPbk2ContactUiControlSubstituteD2Ev @ 74 NONAME
-	_ZN31Pbk2PhoneNumberFormatterFactory27CreatePhoneNumberFormatterLEi @ 75 NONAME
-	_ZN33CPbk2MemoryEntryDefaultsAssignDlg4NewLEv @ 76 NONAME
-	_ZN33CPbk2MemoryEntryDefaultsAssignDlg9ExecuteLDERK39CPbk2PresentationContactFieldCollectionRK19CVPbkContactManagerRK23MPbk2FieldPropertyArrayN28VPbkFieldTypeSelectorFactory30TVPbkContactActionTypeSelectorE @ 77 NONAME
-	_ZNK18CPbk2InputAbsorber9IsWaitingEv @ 78 NONAME
-	_ZNK19TPbk2AddItemWrapper10PropertyAtEi @ 79 NONAME
-	_ZNK19TPbk2AddItemWrapper13PropertyCountEv @ 80 NONAME
-	_ZTI13CPbk2FetchDlg @ 81 NONAME ; #<TI>#
-	_ZTI15CPbk2PrependDlg @ 82 NONAME ; #<TI>#
-	_ZTI18CPbk2AddressSelect @ 83 NONAME ; #<TI>#
-	_ZTI18CPbk2InputAbsorber @ 84 NONAME ; #<TI>#
-	_ZTI19CPbk2StoreListQuery @ 85 NONAME ; #<TI>#
-	_ZTI19CPbk2ThumbnailPopup @ 86 NONAME ; #<TI>#
-	_ZTI21CPbk2ContactEditorDlg @ 87 NONAME ; #<TI>#
-	_ZTI21CPbk2NamesListControl @ 88 NONAME ; #<TI>#
-	_ZTI21CPbk2PhonebookInfoDlg @ 89 NONAME ; #<TI>#
-	_ZTI23CPbk2ContactInfoControl @ 90 NONAME ; #<TI>#
-	_ZTI24CPbk2AddItemToContactDlg @ 91 NONAME ; #<TI>#
-	_ZTI24CPbk2SettingsListControl @ 92 NONAME ; #<TI>#
-	_ZTI25CPbk2ContactEditorDlgImpl @ 93 NONAME ; #<TI>#
-	_ZTI25CPbk2StoreInfoItemBuilder @ 94 NONAME ; #<TI>#
-	_ZTI27CPbk2MemoryEntryDefaultsDlg @ 95 NONAME ; #<TI>#
-	_ZTI29CPbk2GeneralConfirmationQuery @ 96 NONAME ; #<TI>#
-	_ZTI31CPbk2ContactUiControlSubstitute @ 97 NONAME ; #<TI>#
-	_ZTV13CPbk2FetchDlg @ 98 NONAME ; #<VT>#
-	_ZTV15CPbk2PrependDlg @ 99 NONAME ; #<VT>#
-	_ZTV18CPbk2AddressSelect @ 100 NONAME ; #<VT>#
-	_ZTV18CPbk2InputAbsorber @ 101 NONAME ; #<VT>#
-	_ZTV19CPbk2StoreListQuery @ 102 NONAME ; #<VT>#
-	_ZTV19CPbk2ThumbnailPopup @ 103 NONAME ; #<VT>#
-	_ZTV21CPbk2ContactEditorDlg @ 104 NONAME ; #<VT>#
-	_ZTV21CPbk2NamesListControl @ 105 NONAME ; #<VT>#
-	_ZTV21CPbk2PhonebookInfoDlg @ 106 NONAME ; #<VT>#
-	_ZTV23CPbk2ContactInfoControl @ 107 NONAME ; #<VT>#
-	_ZTV24CPbk2AddItemToContactDlg @ 108 NONAME ; #<VT>#
-	_ZTV24CPbk2SettingsListControl @ 109 NONAME ; #<VT>#
-	_ZTV25CPbk2ContactEditorDlgImpl @ 110 NONAME ; #<VT>#
-	_ZTV25CPbk2StoreInfoItemBuilder @ 111 NONAME ; #<VT>#
-	_ZTV27CPbk2MemoryEntryDefaultsDlg @ 112 NONAME ; #<VT>#
-	_ZTV29CPbk2GeneralConfirmationQuery @ 113 NONAME ; #<VT>#
-	_ZTV31CPbk2ContactUiControlSubstitute @ 114 NONAME ; #<VT>#
-	_ZThn52_N31CPbk2ContactUiControlSubstitute20SetFocusedFieldIndexEi @ 115 NONAME ; #<thunk>#
-	_ZThn52_N31CPbk2ContactUiControlSubstituteD0Ev @ 116 NONAME ; #<thunk>#
-	_ZThn52_N31CPbk2ContactUiControlSubstituteD1Ev @ 117 NONAME ; #<thunk>#
-	_ZN27Pbk2TitlePanePictureFactory24CreateTitlePanePictureLCEPK17MVPbkStoreContactR23CPbk2StorePropertyArray @ 118 NONAME
-	_ZN28CPbk2DefaultAttributeProcess11SetDefaultLE16TVPbkDefaultTypeR22MVPbkStoreContactField @ 119 NONAME
-	_ZN28CPbk2DefaultAttributeProcess12SetDefaultsLEP13CArrayFixFlatI16TVPbkDefaultTypeER22MVPbkStoreContactField @ 120 NONAME
-	_ZN28CPbk2DefaultAttributeProcess14RemoveDefaultLE16TVPbkDefaultType @ 121 NONAME
-	_ZN28CPbk2DefaultAttributeProcess15RemoveDefaultsLEP13CArrayFixFlatI16TVPbkDefaultTypeE @ 122 NONAME
-	_ZN28CPbk2DefaultAttributeProcess4NewLER19CVPbkContactManagerR17MVPbkStoreContactR36MPbk2DefaultAttributeProcessObserver @ 123 NONAME
-	_ZN24TPbk2AddressSelectParams28SetTitleToIncludeContactNameEi @ 124 NONAME
-	_ZN21CPbk2NamesListControl9GiveViewLEP20MVPbkContactViewBase @ 125 NONAME
-	_ZN24TPbk2AddressSelectParams19SetSuppressWarningsEi @ 126 NONAME
-	_ZN21CPbk2NamesListControl18AllowPointerEventsEi @ 127 NONAME
-	_ZN22CPbk2ContactIconsUtils23CreateListboxIconArrayLEi @ 128 NONAME
-	_ZN22CPbk2ContactIconsUtils4NewLER23CPbk2StorePropertyArrayP30MPbk2ContactUiControlExtension @ 129 NONAME
+	_ZN13CPbk2FetchDlg17DenyDelayedFetchLERK6TDesC8 @ 1 NONAME
+	_ZN13CPbk2FetchDlg19AcceptDelayedFetchLERK6TDesC8 @ 2 NONAME
+	_ZN13CPbk2FetchDlg4NewLENS_7TParamsER21MPbk2FetchDlgObserver @ 3 NONAME
+	_ZN13CPbk2FetchDlg7TParamsC1Ev @ 4 NONAME
+	_ZN13CPbk2FetchDlg7TParamsC2Ev @ 5 NONAME
+	_ZN13CPbk2FetchDlg7TParamscv12TCleanupItemEv @ 6 NONAME
+	_ZN13CPbk2FetchDlg9ExecuteLDEv @ 7 NONAME
+	_ZN15CPbk2PrependDlg4NewLER6TDes16 @ 8 NONAME
+	_ZN16Pbk2AddressTools18GetAddressFieldsLCER17MVPbkStoreContact17TPbk2FieldGroupIdR8RHashMapIi7TPtrC16E @ 9 NONAME
+	_ZN16Pbk2AddressTools19GetAddressPreviewLCER17MVPbkStoreContact17TPbk2FieldGroupIdR6RBuf16 @ 10 NONAME
+	_ZN16Pbk2AddressTools20MapAddressToOrderingE17TPbk2FieldGroupId @ 11 NONAME
+	_ZN16Pbk2AddressTools20MapCtrlTypeToAddressEi @ 12 NONAME
+	_ZN16Pbk2AddressTools20MapViewTypeToAddressEN24TPbk2ContactEditorParams11TActiveViewE @ 13 NONAME
+	_ZN16Pbk2AddressTools21MapCtrlTypeToViewTypeEi @ 14 NONAME
+	_ZN16Pbk2AddressTools22IsAddressPreviewEmptyLER17MVPbkStoreContact17TPbk2FieldGroupId @ 15 NONAME
+	_ZN16Pbk2AddressTools23MapAddressToVersitParamE17TPbk2FieldGroupId @ 16 NONAME
+	_ZN16Pbk2AddressTools24GetAddressShortPreviewLCER17MVPbkStoreContact17TPbk2FieldGroupIdR6RBuf16 @ 17 NONAME
+	_ZN16Pbk2AddressTools32MapVPbkFieldTypeToAddressGroupIdEPK14MVPbkFieldType @ 18 NONAME
+	_ZN17CPbk2UIFieldArray4NewLERK7TDesC16R3RFsR19MPbk2UIFieldFactory @ 19 NONAME
+	_ZN18CPbk2AddressSelect12AttemptExitLEi @ 20 NONAME
+	_ZN18CPbk2AddressSelect20Pbk2ControlKeyEventLERK9TKeyEvent10TEventCode @ 21 NONAME
+	_ZN18CPbk2AddressSelect4NewLER24TPbk2AddressSelectParams @ 22 NONAME
+	_ZN18CPbk2AddressSelect4NewLER24TPbk2AddressSelectParamsR22CVPbkFieldTypeSelectorPK6TArrayIP17MVPbkStoreContactEPKS4_IP21CPbk2PresenceIconInfoE @ 23 NONAME
+	_ZN18CPbk2AddressSelect6SetCbaEi @ 24 NONAME
+	_ZN18CPbk2AddressSelect9ExecuteLDEv @ 25 NONAME
+	_ZN18CPbk2AddressSelectD0Ev @ 26 NONAME
+	_ZN18CPbk2AddressSelectD1Ev @ 27 NONAME
+	_ZN18CPbk2AddressSelectD2Ev @ 28 NONAME
+	_ZN18CPbk2InputAbsorber18SetCommandObserverEP19MEikCommandObserver @ 29 NONAME
+	_ZN18CPbk2InputAbsorber4NewLEi @ 30 NONAME
+	_ZN18CPbk2InputAbsorber4WaitEv @ 31 NONAME
+	_ZN18CPbk2InputAbsorber5NewLCEi @ 32 NONAME
+	_ZN18CPbk2InputAbsorber8StopWaitEv @ 33 NONAME
+	_ZN19CPbk2FieldFormatter14SetTimeFormatLERK7TDesC16 @ 34 NONAME
+	_ZN19CPbk2FieldFormatter19FormatFieldContentLERK21MVPbkBaseContactFieldRK14MVPbkFieldType @ 35 NONAME
+	_ZN19CPbk2FieldFormatter4NewLERK23MPbk2FieldPropertyArrayRK18MVPbkFieldTypeList @ 36 NONAME
+	_ZN19CPbk2StoreListQuery15SetAllItemTextLERK7TDesC16i @ 37 NONAME
+	_ZN19CPbk2StoreListQuery4NewLEv @ 38 NONAME
+	_ZN19CPbk2StoreListQuery9ExecuteLDERK7TDesC16R25CVPbkContactStoreUriArray @ 39 NONAME
+	_ZN19TPbk2AddItemWrapperC1ERK18MPbk2FieldProperty @ 40 NONAME
+	_ZN19TPbk2AddItemWrapperC1ERK23CPbk2FieldPropertyGroup @ 41 NONAME
+	_ZN19TPbk2AddItemWrapperC2ERK18MPbk2FieldProperty @ 42 NONAME
+	_ZN19TPbk2AddItemWrapperC2ERK23CPbk2FieldPropertyGroup @ 43 NONAME
+	_ZN20CPbk2ThumbnailLoader13HideThumbnailEv @ 44 NONAME
+	_ZN20CPbk2ThumbnailLoader13LoadThumbnailEP17MVPbkStoreContactPK11CEikListBox22TPbk2ThumbnailLocation @ 45 NONAME
+	_ZN20CPbk2ThumbnailLoader14LoadThumbnailLEP16MVPbkContactLinkPK11CEikListBox22TPbk2ThumbnailLocation @ 46 NONAME
+	_ZN20CPbk2ThumbnailLoader4NewLER19CVPbkContactManager @ 47 NONAME
+	_ZN20CPbk2ThumbnailLoader5ResetEv @ 48 NONAME
+	_ZN20CPbk2ThumbnailLoader7RefreshEv @ 49 NONAME
+	_ZN21CPbk2ContactEditorDlg4NewLER24TPbk2ContactEditorParamsP17MVPbkStoreContactR26MPbk2EditedContactObserver @ 50 NONAME
+	_ZN21CPbk2ContactEditorDlg4NewLER24TPbk2ContactEditorParamsP17MVPbkStoreContactR26MPbk2EditedContactObserverP24MPbk2ApplicationServicesP7HBufC16i @ 51 NONAME
+	_ZN21CPbk2ContactEditorDlg9ExecuteLDEv @ 52 NONAME
+	_ZN21CPbk2NamesListControl12AddObserverLER20MPbk2ControlObserver @ 53 NONAME
+	_ZN21CPbk2NamesListControl13SetOpeningCcaEi @ 54 NONAME
+	_ZN21CPbk2NamesListControl14RemoveObserverER20MPbk2ControlObserver @ 55 NONAME
+	_ZN21CPbk2NamesListControl18AllowPointerEventsEi @ 56 NONAME
+	_ZN21CPbk2NamesListControl20SetCurrentGroupLinkLEP16MVPbkContactLink @ 57 NONAME
+	_ZN21CPbk2NamesListControl26HandleViewForegroundEventLEi @ 58 NONAME
+	_ZN21CPbk2NamesListControl26MassUpdateSkipProgressNoteEi @ 59 NONAME
+	_ZN21CPbk2NamesListControl4NewLEiPK11CCoeControlR19CVPbkContactManagerR20MVPbkContactViewBaseR25MPbk2ContactNameFormatterR23CPbk2StorePropertyArray @ 60 NONAME
+	_ZN21CPbk2NamesListControl4NewLEiPK11CCoeControlR19CVPbkContactManagerR20MVPbkContactViewBaseR25MPbk2ContactNameFormatterR23CPbk2StorePropertyArrayP21CPbk2ThumbnailManager @ 61 NONAME
+	_ZN21CPbk2NamesListControl5ResetEv @ 62 NONAME
+	_ZN21CPbk2NamesListControl8SetViewLER20MVPbkContactViewBase @ 63 NONAME
+	_ZN21CPbk2NamesListControl9GiveViewLEP20MVPbkContactViewBase @ 64 NONAME
+	_ZN21CPbk2NamesListControlC1EPK11CCoeControlR19CVPbkContactManagerR20MVPbkContactViewBaseR25MPbk2ContactNameFormatterR23CPbk2StorePropertyArray @ 65 NONAME
+	_ZN21CPbk2NamesListControlC2EPK11CCoeControlR19CVPbkContactManagerR20MVPbkContactViewBaseR25MPbk2ContactNameFormatterR23CPbk2StorePropertyArray @ 66 NONAME
+	_ZN21CPbk2PhonebookInfoDlg4NewLEv @ 67 NONAME
+	_ZN21CPbk2PhonebookInfoDlg9ExecuteLDER25CVPbkContactStoreUriArray @ 68 NONAME
+	_ZN21CPbk2ThumbnailManager4NewLER19CVPbkContactManager @ 69 NONAME
+	_ZN22CPbk2ContactIconsUtils23CreateListboxIconArrayLEi @ 70 NONAME
+	_ZN22CPbk2ContactIconsUtils4NewLER23CPbk2StorePropertyArrayP30MPbk2ContactUiControlExtension @ 71 NONAME
+	_ZN22CPbk2MergeConflictsDlg4NewLEP18MPbk2MergeResolveri @ 72 NONAME
+	_ZN23CPbk2ContactInfoControl12AddObserverLER20MPbk2ControlObserver @ 73 NONAME
+	_ZN23CPbk2ContactInfoControl14RemoveObserverER20MPbk2ControlObserver @ 74 NONAME
+	_ZN23CPbk2ContactInfoControl4NewLEPK11CCoeControlR19CVPbkContactManagerR25MPbk2ContactNameFormatterR23MPbk2FieldPropertyArrayR23CPbk2StorePropertyArrayP22MPbk2ContactNavigation @ 75 NONAME
+	_ZN24CPbk2AddItemToContactDlg4NewLEP24MPbk2ApplicationServices @ 76 NONAME
+	_ZN24CPbk2AddItemToContactDlg4NewLEv @ 77 NONAME
+	_ZN24CPbk2AddItemToContactDlg9ExecuteLDER6RArrayI19TPbk2AddItemWrapperEPK24TPbk2AddItemDialogParams @ 78 NONAME
+	_ZN24CPbk2SettingsListControl15CommitSettingsLEv @ 79 NONAME
+	_ZN24CPbk2SettingsListControl4NewLEPK11CCoeControlR21CPbk2SortOrderManagerR29MPbk2SettingsControlExtension @ 80 NONAME
+	_ZN24TPbk2AddressSelectParams14SetQueryAlwaysEi @ 81 NONAME
+	_ZN24TPbk2AddressSelectParams15SetFocusedFieldEPK22MVPbkStoreContactField @ 82 NONAME
+	_ZN24TPbk2AddressSelectParams19SetSuppressWarningsEi @ 83 NONAME
+	_ZN24TPbk2AddressSelectParams20SetDefaultPrioritiesERK34RVPbkContactFieldDefaultPriorities @ 84 NONAME
+	_ZN24TPbk2AddressSelectParams21SetUseDefaultDirectlyEi @ 85 NONAME
+	_ZN24TPbk2AddressSelectParams28SetTitleToIncludeContactNameEi @ 86 NONAME
+	_ZN24TPbk2AddressSelectParamsC1ER17MVPbkStoreContactRK19CVPbkContactManagerR25MPbk2ContactNameFormatterRK23CPbk2FieldPropertyArrayR15TResourceReaderi @ 87 NONAME
+	_ZN24TPbk2AddressSelectParamsC2ER17MVPbkStoreContactRK19CVPbkContactManagerR25MPbk2ContactNameFormatterRK23CPbk2FieldPropertyArrayR15TResourceReaderi @ 88 NONAME
+	_ZN26CPbk2MergePhotoConflictDlg4NewLEP16MVPbkBaseContactS1_Pi @ 89 NONAME
+	_ZN27CPbk2MemoryEntryDefaultsDlg4NewLER24CPbk2PresentationContactR19CVPbkContactManager @ 90 NONAME
+	_ZN27CPbk2MemoryEntryDefaultsDlg9ExecuteLDEv @ 91 NONAME
+	_ZN27Pbk2TitlePanePictureFactory24CreateTitlePanePictureLCEPK17MVPbkStoreContactR23CPbk2StorePropertyArray @ 92 NONAME
+	_ZN28CPbk2DefaultAttributeProcess11SetDefaultLE16TVPbkDefaultTypeR22MVPbkStoreContactField @ 93 NONAME
+	_ZN28CPbk2DefaultAttributeProcess12SetDefaultsLEP13CArrayFixFlatI16TVPbkDefaultTypeER22MVPbkStoreContactField @ 94 NONAME
+	_ZN28CPbk2DefaultAttributeProcess14RemoveDefaultLE16TVPbkDefaultType @ 95 NONAME
+	_ZN28CPbk2DefaultAttributeProcess15RemoveDefaultsLEP13CArrayFixFlatI16TVPbkDefaultTypeE @ 96 NONAME
+	_ZN28CPbk2DefaultAttributeProcess4NewLER19CVPbkContactManagerR17MVPbkStoreContactR36MPbk2DefaultAttributeProcessObserver @ 97 NONAME
+	_ZN29CPbk2ContactEditorUIFieldBase14SetFieldLabelLERK7TDesC16 @ 98 NONAME
+	_ZN29CPbk2ContactEditorUIFieldBase16ConsumesKeyEventERK9TKeyEvent10TEventCode @ 99 NONAME
+	_ZN29CPbk2ContactEditorUIFieldBase18LoadBitmapToFieldLERK11TPbk2IconId @ 100 NONAME
+	_ZN29CPbk2ContactEditorUIFieldBase25HandleCustomFieldCommandLEi @ 101 NONAME
+	_ZN29CPbk2ContactEditorUIFieldBase8SetFocusEv @ 102 NONAME
+	_ZN29CPbk2ContactEditorUIFieldBase9ControlIdEv @ 103 NONAME
+	_ZN29CPbk2ContactEditorUIFieldBaseC2EP12MPbk2UIFieldR27MPbk2ContactEditorUiBuilderR22CPbk2IconInfoContaineri @ 104 NONAME
+	_ZN29CPbk2ContactEditorUIFieldBaseD0Ev @ 105 NONAME
+	_ZN29CPbk2ContactEditorUIFieldBaseD1Ev @ 106 NONAME
+	_ZN29CPbk2ContactEditorUIFieldBaseD2Ev @ 107 NONAME
+	_ZN29CPbk2GeneralConfirmationQuery4NewLEv @ 108 NONAME
+	_ZN29CPbk2GeneralConfirmationQuery9ExecuteLDERK16MVPbkBaseContacti @ 109 NONAME
+	_ZN29CPbk2GeneralConfirmationQuery9ExecuteLDERK16MVPbkBaseContactii @ 110 NONAME
+	_ZN29CPbk2GeneralConfirmationQuery9ExecuteLDEii @ 111 NONAME
+	_ZN29CPbk2GeneralConfirmationQuery9StopQueryEv @ 112 NONAME
+	_ZN31CPbk2ContactEditorReadonlyField11InitializeLEP25MPbk2ContactEditorUIField @ 113 NONAME
+	_ZN31CPbk2ContactEditorReadonlyField8SetTextLEPK7TDesC16 @ 114 NONAME
+	_ZN31CPbk2ContactUiControlSubstitute15SetFocusedFieldERK21MVPbkBaseContactField @ 115 NONAME
+	_ZN31CPbk2ContactUiControlSubstitute16SetSelectedStoreER17MVPbkContactStore @ 116 NONAME
+	_ZN31CPbk2ContactUiControlSubstitute18SetParentUiControlER21MPbk2ContactUiControl @ 117 NONAME
+	_ZN31CPbk2ContactUiControlSubstitute20SetFocusedFieldIndexEi @ 118 NONAME
+	_ZN31CPbk2ContactUiControlSubstitute22SetFocusedStoreContactERK17MVPbkStoreContact @ 119 NONAME
+	_ZN31CPbk2ContactUiControlSubstitute4NewLEv @ 120 NONAME
+	_ZN31CPbk2ContactUiControlSubstituteD0Ev @ 121 NONAME
+	_ZN31CPbk2ContactUiControlSubstituteD1Ev @ 122 NONAME
+	_ZN31CPbk2ContactUiControlSubstituteD2Ev @ 123 NONAME
+	_ZN31Pbk2PhoneNumberFormatterFactory27CreatePhoneNumberFormatterLEi @ 124 NONAME
+	_ZN33CPbk2MemoryEntryDefaultsAssignDlg4NewLEv @ 125 NONAME
+	_ZN33CPbk2MemoryEntryDefaultsAssignDlg9ExecuteLDERK39CPbk2PresentationContactFieldCollectionRK19CVPbkContactManagerRK23MPbk2FieldPropertyArrayN28VPbkFieldTypeSelectorFactory30TVPbkContactActionTypeSelectorE @ 126 NONAME
+	_ZNK18CPbk2InputAbsorber9IsWaitingEv @ 127 NONAME
+	_ZNK19TPbk2AddItemWrapper10PropertyAtEi @ 128 NONAME
+	_ZNK19TPbk2AddItemWrapper13PropertyCountEv @ 129 NONAME
 	_ZNK22CPbk2ContactIconsUtils21GetIconIdsForContactLERK16MVPbkViewContactR6RArrayI11TPbk2IconIdE @ 130 NONAME
-	_ZTI22CPbk2ContactIconsUtils @ 131 NONAME ; #<TI>#
-	_ZTV22CPbk2ContactIconsUtils @ 132 NONAME ; #<VT>#
-	_ZN18CPbk2AddressSelect4NewLER24TPbk2AddressSelectParamsR22CVPbkFieldTypeSelectorPK6TArrayIP17MVPbkStoreContactEPKS4_IP21CPbk2PresenceIconInfoE @ 133 NONAME
-	_ZTIN17CPbk2FetchResults20CFRConatactOperationE @ 134 NONAME ; #<TI>#
-	_ZTVN17CPbk2FetchResults20CFRConatactOperationE @ 135 NONAME ; #<VT>#
-	_ZThn56_N31CPbk2ContactUiControlSubstituteD0Ev @ 136 NONAME ; #<thunk>#
-	_ZThn56_N31CPbk2ContactUiControlSubstituteD1Ev @ 137 NONAME ; #<thunk>#
-	_ZN16Pbk2AddressTools18GetAddressFieldsLCER17MVPbkStoreContact17TPbk2FieldGroupIdR8RHashMapIi7TPtrC16E @ 138 NONAME
-	_ZN16Pbk2AddressTools19GetAddressPreviewLCER17MVPbkStoreContact17TPbk2FieldGroupIdR6RBuf16 @ 139 NONAME
-	_ZN16Pbk2AddressTools20MapAddressToOrderingE17TPbk2FieldGroupId @ 140 NONAME
-	_ZN16Pbk2AddressTools20MapCtrlTypeToAddressEi @ 141 NONAME
-	_ZN16Pbk2AddressTools20MapViewTypeToAddressEN24TPbk2ContactEditorParams11TActiveViewE @ 142 NONAME
-	_ZN16Pbk2AddressTools21MapCtrlTypeToViewTypeEi @ 143 NONAME
-	_ZN16Pbk2AddressTools23MapAddressToVersitParamE17TPbk2FieldGroupId @ 144 NONAME
-	_ZN16Pbk2AddressTools24GetAddressShortPreviewLCER17MVPbkStoreContact17TPbk2FieldGroupIdR6RBuf16 @ 145 NONAME
-	_ZN17CPbk2UIFieldArray4NewLERK7TDesC16R3RFsR19MPbk2UIFieldFactory @ 146 NONAME
-	_ZN29CPbk2ContactEditorUIFieldBase14SetFieldLabelLERK7TDesC16 @ 147 NONAME
-	_ZN29CPbk2ContactEditorUIFieldBase16ConsumesKeyEventERK9TKeyEvent10TEventCode @ 148 NONAME
-	_ZN29CPbk2ContactEditorUIFieldBase18LoadBitmapToFieldLERK11TPbk2IconId @ 149 NONAME
-	_ZN29CPbk2ContactEditorUIFieldBase25HandleCustomFieldCommandLEi @ 150 NONAME
-	_ZN29CPbk2ContactEditorUIFieldBase8SetFocusEv @ 151 NONAME
-	_ZN29CPbk2ContactEditorUIFieldBase9ControlIdEv @ 152 NONAME
-	_ZN29CPbk2ContactEditorUIFieldBaseC2EP12MPbk2UIFieldR27MPbk2ContactEditorUiBuilderR22CPbk2IconInfoContaineri @ 153 NONAME
-	_ZN29CPbk2ContactEditorUIFieldBaseD0Ev @ 154 NONAME
-	_ZN29CPbk2ContactEditorUIFieldBaseD1Ev @ 155 NONAME
-	_ZN29CPbk2ContactEditorUIFieldBaseD2Ev @ 156 NONAME
-	_ZN31CPbk2ContactEditorReadonlyField11InitializeLEP25MPbk2ContactEditorUIField @ 157 NONAME
-	_ZN31CPbk2ContactEditorReadonlyField8SetTextLEPK7TDesC16 @ 158 NONAME
-	_ZNK29CPbk2ContactEditorUIFieldBase10FieldLabelEv @ 159 NONAME
-	_ZNK29CPbk2ContactEditorUIFieldBase11ControlTextEv @ 160 NONAME
-	_ZNK29CPbk2ContactEditorUIFieldBase7UIFieldEv @ 161 NONAME
-	_ZTI12CPbk2UIField @ 162 NONAME ; #<TI>#
-	_ZTI17CPbk2UIFieldArray @ 163 NONAME ; #<TI>#
-	_ZTI27CPbk2ContactEditorArrayItem @ 164 NONAME ; #<TI>#
-	_ZTI29CPbk2ContactEditorUIFieldBase @ 165 NONAME ; #<TI>#
-	_ZTI30CPbk2ContactEditorFieldFactory @ 166 NONAME ; #<TI>#
-	_ZTI31CPbk2ContactEditorReadonlyField @ 167 NONAME ; #<TI>#
-	_ZTV12CPbk2UIField @ 168 NONAME ; #<VT>#
-	_ZTV17CPbk2UIFieldArray @ 169 NONAME ; #<VT>#
-	_ZTV27CPbk2ContactEditorArrayItem @ 170 NONAME ; #<VT>#
-	_ZTV29CPbk2ContactEditorUIFieldBase @ 171 NONAME ; #<VT>#
-	_ZTV30CPbk2ContactEditorFieldFactory @ 172 NONAME ; #<VT>#
-	_ZTV31CPbk2ContactEditorReadonlyField @ 173 NONAME ; #<VT>#
-	_ZThn4_N29CPbk2ContactEditorUIFieldBase14SetFieldLabelLERK7TDesC16 @ 174 NONAME ; #<thunk>#
-	_ZThn4_N29CPbk2ContactEditorUIFieldBase16ConsumesKeyEventERK9TKeyEvent10TEventCode @ 175 NONAME ; #<thunk>#
-	_ZThn4_N29CPbk2ContactEditorUIFieldBase18LoadBitmapToFieldLERK11TPbk2IconId @ 176 NONAME ; #<thunk>#
-	_ZThn4_N29CPbk2ContactEditorUIFieldBase25HandleCustomFieldCommandLEi @ 177 NONAME ; #<thunk>#
-	_ZThn4_N29CPbk2ContactEditorUIFieldBase8SetFocusEv @ 178 NONAME ; #<thunk>#
-	_ZThn4_N29CPbk2ContactEditorUIFieldBase9ControlIdEv @ 179 NONAME ; #<thunk>#
-	_ZThn4_N29CPbk2ContactEditorUIFieldBaseD0Ev @ 180 NONAME ; #<thunk>#
-	_ZThn4_N29CPbk2ContactEditorUIFieldBaseD1Ev @ 181 NONAME ; #<thunk>#
-	_ZThn4_NK29CPbk2ContactEditorUIFieldBase10FieldLabelEv @ 182 NONAME ; #<thunk>#
-	_ZThn4_NK29CPbk2ContactEditorUIFieldBase11ControlTextEv @ 183 NONAME ; #<thunk>#
-	_ZThn4_NK29CPbk2ContactEditorUIFieldBase7UIFieldEv @ 184 NONAME ; #<thunk>#
-	_ZTI30CPbk2FilteredViewStackObserver @ 185 NONAME ; #<TI>#
-	_ZTV30CPbk2FilteredViewStackObserver @ 186 NONAME ; #<VT>#
-	_ZN29CPbk2GeneralConfirmationQuery9ExecuteLDERK16MVPbkBaseContactii @ 187 NONAME
-	_ZTI33CPbk2ContactViewCustomListBoxData @ 188 NONAME
-	_ZTI39CPbk2ContactViewCustomListBoxItemDrawer @ 189 NONAME
-	_ZTV33CPbk2ContactViewCustomListBoxData @ 190 NONAME
-	_ZTV39CPbk2ContactViewCustomListBoxItemDrawer @ 191 NONAME
-	_ZN21CPbk2NamesListControl20SetCurrentGroupLinkLEP16MVPbkContactLink @ 192 NONAME
-	_ZN21CPbk2NamesListControl4NewLEiPK11CCoeControlR19CVPbkContactManagerR20MVPbkContactViewBaseR25MPbk2ContactNameFormatterR23CPbk2StorePropertyArrayP21CPbk2ThumbnailManager @ 193 NONAME
-	_ZN21CPbk2ThumbnailManager4NewLER19CVPbkContactManager @ 194 NONAME
-	_ZN21CPbk2ContactEditorDlg4NewLER24TPbk2ContactEditorParamsP17MVPbkStoreContactR26MPbk2EditedContactObserverP24MPbk2ApplicationServicesP7HBufC16i @ 195 NONAME
-	_ZN24CPbk2AddItemToContactDlg4NewLEP24MPbk2ApplicationServices @ 196 NONAME
-	_ZN22CPbk2MergeConflictsDlg4NewLEP18MPbk2MergeResolveri @ 197 NONAME
-	_ZN26CPbk2MergePhotoConflictDlg4NewLEP16MVPbkBaseContactS1_Pi @ 198 NONAME
-	_ZN29CPbk2GeneralConfirmationQuery9StopQueryEv @ 199 NONAME
-	_ZN21CPbk2NamesListControl26HandleViewForegroundEventLEi @ 200 NONAME
-	_ZN16Pbk2AddressTools22IsAddressPreviewEmptyLER17MVPbkStoreContact17TPbk2FieldGroupId @ 201 NONAME
-	_ZN16Pbk2AddressTools32MapVPbkFieldTypeToAddressGroupIdEPK14MVPbkFieldType @ 202 NONAME
-	_ZN21CPbk2NamesListControl26MassUpdateSkipProgressNoteEi @ 203 NONAME
-	_ZN21CPbk2NamesListControl13SetOpeningCcaEi @ 204 NONAME
+	_ZNK29CPbk2ContactEditorUIFieldBase10FieldLabelEv @ 131 NONAME
+	_ZNK29CPbk2ContactEditorUIFieldBase11ControlTextEv @ 132 NONAME
+	_ZNK29CPbk2ContactEditorUIFieldBase7UIFieldEv @ 133 NONAME
+	_ZTI12CPbk2UIField @ 134 NONAME
+	_ZTI13CPbk2FetchDlg @ 135 NONAME
+	_ZTI15CPbk2PrependDlg @ 136 NONAME
+	_ZTI17CPbk2UIFieldArray @ 137 NONAME
+	_ZTI18CPbk2AddressSelect @ 138 NONAME
+	_ZTI18CPbk2InputAbsorber @ 139 NONAME
+	_ZTI19CPbk2StoreListQuery @ 140 NONAME
+	_ZTI19CPbk2ThumbnailPopup @ 141 NONAME
+	_ZTI21CPbk2ContactEditorDlg @ 142 NONAME
+	_ZTI21CPbk2NamesListControl @ 143 NONAME
+	_ZTI21CPbk2PhonebookInfoDlg @ 144 NONAME
+	_ZTI22CPbk2ContactIconsUtils @ 145 NONAME
+	_ZTI23CPbk2ContactInfoControl @ 146 NONAME
+	_ZTI24CPbk2AddItemToContactDlg @ 147 NONAME
+	_ZTI24CPbk2SettingsListControl @ 148 NONAME
+	_ZTI25CPbk2ContactEditorDlgImpl @ 149 NONAME
+	_ZTI25CPbk2StoreInfoItemBuilder @ 150 NONAME
+	_ZTI27CPbk2ContactEditorArrayItem @ 151 NONAME
+	_ZTI27CPbk2MemoryEntryDefaultsDlg @ 152 NONAME
+	_ZTI29CPbk2ContactEditorUIFieldBase @ 153 NONAME
+	_ZTI29CPbk2GeneralConfirmationQuery @ 154 NONAME
+	_ZTI30CPbk2ContactEditorFieldFactory @ 155 NONAME
+	_ZTI30CPbk2FilteredViewStackObserver @ 156 NONAME
+	_ZTI31CPbk2ContactEditorReadonlyField @ 157 NONAME
+	_ZTI31CPbk2ContactUiControlSubstitute @ 158 NONAME
+	_ZTI33CPbk2ContactViewCustomListBoxData @ 159 NONAME
+	_ZTI39CPbk2ContactViewCustomListBoxItemDrawer @ 160 NONAME
+	_ZTIN17CPbk2FetchResults20CFRConatactOperationE @ 161 NONAME
+	_ZTV12CPbk2UIField @ 162 NONAME
+	_ZTV13CPbk2FetchDlg @ 163 NONAME
+	_ZTV15CPbk2PrependDlg @ 164 NONAME
+	_ZTV17CPbk2UIFieldArray @ 165 NONAME
+	_ZTV18CPbk2AddressSelect @ 166 NONAME
+	_ZTV18CPbk2InputAbsorber @ 167 NONAME
+	_ZTV19CPbk2StoreListQuery @ 168 NONAME
+	_ZTV19CPbk2ThumbnailPopup @ 169 NONAME
+	_ZTV21CPbk2ContactEditorDlg @ 170 NONAME
+	_ZTV21CPbk2NamesListControl @ 171 NONAME
+	_ZTV21CPbk2PhonebookInfoDlg @ 172 NONAME
+	_ZTV22CPbk2ContactIconsUtils @ 173 NONAME
+	_ZTV23CPbk2ContactInfoControl @ 174 NONAME
+	_ZTV24CPbk2AddItemToContactDlg @ 175 NONAME
+	_ZTV24CPbk2SettingsListControl @ 176 NONAME
+	_ZTV25CPbk2ContactEditorDlgImpl @ 177 NONAME
+	_ZTV25CPbk2StoreInfoItemBuilder @ 178 NONAME
+	_ZTV27CPbk2ContactEditorArrayItem @ 179 NONAME
+	_ZTV27CPbk2MemoryEntryDefaultsDlg @ 180 NONAME
+	_ZTV29CPbk2ContactEditorUIFieldBase @ 181 NONAME
+	_ZTV29CPbk2GeneralConfirmationQuery @ 182 NONAME
+	_ZTV30CPbk2ContactEditorFieldFactory @ 183 NONAME
+	_ZTV30CPbk2FilteredViewStackObserver @ 184 NONAME
+	_ZTV31CPbk2ContactEditorReadonlyField @ 185 NONAME
+	_ZTV31CPbk2ContactUiControlSubstitute @ 186 NONAME
+	_ZTV33CPbk2ContactViewCustomListBoxData @ 187 NONAME
+	_ZTV39CPbk2ContactViewCustomListBoxItemDrawer @ 188 NONAME
+	_ZTVN17CPbk2FetchResults20CFRConatactOperationE @ 189 NONAME
+	_ZThn4_N29CPbk2ContactEditorUIFieldBase14SetFieldLabelLERK7TDesC16 @ 190 NONAME
+	_ZThn4_N29CPbk2ContactEditorUIFieldBase16ConsumesKeyEventERK9TKeyEvent10TEventCode @ 191 NONAME
+	_ZThn4_N29CPbk2ContactEditorUIFieldBase18LoadBitmapToFieldLERK11TPbk2IconId @ 192 NONAME
+	_ZThn4_N29CPbk2ContactEditorUIFieldBase25HandleCustomFieldCommandLEi @ 193 NONAME
+	_ZThn4_N29CPbk2ContactEditorUIFieldBase8SetFocusEv @ 194 NONAME
+	_ZThn4_N29CPbk2ContactEditorUIFieldBase9ControlIdEv @ 195 NONAME
+	_ZThn4_N29CPbk2ContactEditorUIFieldBaseD0Ev @ 196 NONAME
+	_ZThn4_N29CPbk2ContactEditorUIFieldBaseD1Ev @ 197 NONAME
+	_ZThn4_NK29CPbk2ContactEditorUIFieldBase10FieldLabelEv @ 198 NONAME
+	_ZThn4_NK29CPbk2ContactEditorUIFieldBase11ControlTextEv @ 199 NONAME
+	_ZThn4_NK29CPbk2ContactEditorUIFieldBase7UIFieldEv @ 200 NONAME
+	_ZThn52_N31CPbk2ContactUiControlSubstitute20SetFocusedFieldIndexEi @ 201 NONAME
+	_ZThn52_N31CPbk2ContactUiControlSubstituteD0Ev @ 202 NONAME
+	_ZThn52_N31CPbk2ContactUiControlSubstituteD1Ev @ 203 NONAME
+	_ZThn56_N31CPbk2ContactUiControlSubstituteD0Ev @ 204 NONAME
+	_ZThn56_N31CPbk2ContactUiControlSubstituteD1Ev @ 205 NONAME
 
--- a/phonebookui/Phonebook2/GroupExtension/inc/CPguGroupMembersView.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/GroupExtension/inc/CPguGroupMembersView.h	Thu Aug 19 09:41:07 2010 +0300
@@ -24,6 +24,7 @@
 #include <vwsdef.h>
 #include <MPbk2UIExtensionView.h>
 #include <eiklbo.h>
+#include <aknmarkingmodeobserver.h>
 
 // FORWARD DECLARATIONS
 class CPbk2UIExtensionView;
@@ -82,7 +83,8 @@
 class CPguGroupMembersView : public CBase,
                              public MPbk2UIExtensionView,
                              public MEikListBoxObserver,
-                             private MPbk2GroupMembersViewActivationCallback
+                             private MPbk2GroupMembersViewActivationCallback,
+                             public MAknMarkingModeObserver 
                              
 
     {
@@ -125,6 +127,23 @@
                 const TPoint& aPenEventLocation,
                 const TPoint& aPenEventScreenLocation );
 
+    public: // From MAknMarkingModeObserver 
+            
+        /**
+         * This method is called when marking mode is activated or deactivated.
+         * 
+         * @param aActivated @c ETrue if marking mode was activate, @c EFalse
+         *                   if marking mode was deactivated.
+         */
+        void MarkingModeStatusChanged( TBool aActivated );
+
+        /**
+         * This method is called just before marking mode is closed. Client can 
+         * either accept or decline closing.
+         * 
+         * @return @c ETrue if marking mode should be closed, otherwise @c EFalse.
+         */
+        TBool ExitMarkingMode() const;
 
     protected: 
         // from MEikListBoxObserver
@@ -152,7 +171,6 @@
         void ReturnToPreviousViewL() const;
         void ShowContextMenuL();
 
-
     private: // Data
         /// Ref: View that contains this extension view
         CPbk2UIExtensionView& iView;
--- a/phonebookui/Phonebook2/GroupExtension/inc/CPguSendMessageGroupCmd.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/GroupExtension/inc/CPguSendMessageGroupCmd.h	Thu Aug 19 09:41:07 2010 +0300
@@ -151,6 +151,8 @@
         TProcessState iState;
         /// Ref: Group UI extension
         CPguUIExtensionPlugin* iPguUIExtensionPlugin;
+        /// Own: Send Message indicator
+        TBool iSendMessage;
     };
 
 #endif // CPGUSENDMESSAGEGROUPCMD_H
--- a/phonebookui/Phonebook2/GroupExtension/rss/PguMembersListViewBase.rss	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/GroupExtension/rss/PguMembersListViewBase.rss	Thu Aug 19 09:41:07 2010 +0300
@@ -54,38 +54,6 @@
         };
     }
 
-// ---------------------------------------------------------
-// Groups Members View's context menu bar
-// ---------------------------------------------------------
-//
-RESOURCE MENU_PANE r_phonebook2_groupmembers_markable_list_menu
-    {
-    items =
-        {
-        MENU_ITEM
-            {
-            command = EAknCmdMark;
-            txt = qtn_options_list_mark_one;
-            flags = EEikMenuItemSpecific;
-            },
-        MENU_ITEM
-            {
-            command = EAknCmdUnmark;
-            txt = qtn_options_list_unmark_one;
-            flags = EEikMenuItemSpecific;
-            },
-        MENU_ITEM
-            {
-            command = EAknMarkAll;
-            txt = qtn_options_list_mark_all;
-            },
-        MENU_ITEM
-            {
-            command = EAknUnmarkAll;
-            txt = qtn_options_list_unmark_all;
-            }
-        };
-    }
 
 // ---------------------------------------------------------
 // Groups Members View's menu bar
@@ -101,7 +69,7 @@
             },
         MENU_TITLE
             {
-            menu_pane = R_AVKON_MENUPANE_MARKABLE_LIST;
+            menu_pane = R_AVKON_MENUPANE_MARK_MULTIPLE;
             },             
         MENU_TITLE
             {
@@ -140,27 +108,5 @@
         };
     }
     
-// ---------------------------------------------------------
-// Groups Members View's context menu bar
-// ---------------------------------------------------------
-//
-RESOURCE MENU_BAR r_phonebook2_groupmembers_context_menubar
-    {
-    titles = 
-        {
-        MENU_TITLE
-            {
-            menu_pane = R_PHONEBOOK2_MARKABLE_LIST_CONTEXT_MENU;
-            },                
-        MENU_TITLE
-            {
-            menu_pane = R_PHONEBOOK2_BCARD_SEND_MENU;
-            },
-        MENU_TITLE
-            {
-            menu_pane = r_phonebook2_groupmembers_context_menu;
-            }
-        };
-    }
 
 // End of File
--- a/phonebookui/Phonebook2/GroupExtension/src/CPguGroupMembersView.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/GroupExtension/src/CPguGroupMembersView.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -468,10 +468,26 @@
          */
         virtual ~CGroupMembersViewImpl()
             {}
+        
+    public:
+        
+        void SetMarkingModeOn( TBool aMarkingModeOn )
+            {
+            iMarkingModeOn = aMarkingModeOn;
+            }
+        
+        TBool IsMarkingModeOn()
+            {
+            return iMarkingModeOn;
+            }
 
     protected: // Implementation
-        CGroupMembersViewImpl()
+        CGroupMembersViewImpl() : iMarkingModeOn( EFalse )
             {}
+        
+    protected:
+        // Flag to indicate whether Marking mode is active
+        TBool iMarkingModeOn;
     };
 
 
@@ -1119,7 +1135,7 @@
     iCommandHandler.AddMenuCommandObserver(*this);
 
     iStoreConf = &( Phonebook2::Pbk2AppUi()->ApplicationServices().
-    	StoreConfiguration() );
+        StoreConfiguration() );
     iStoreConf->AddObserverL( *this );
 
     // Expand the group members view from the all groups view
@@ -1426,17 +1442,15 @@
             case EKeyOK:
                 {
                 if ( !ShiftDown(aKeyEvent) ) // pure OK or ENTER key
-					{	
+                    {
                     if ( iControl->ContactsMarked() && itemSpecEnabled )
-                    	{
-                    	iView.LaunchPopupMenuL(
-                    		R_PHONEBOOK2_GROUPMEMBERS_CONTEXT_MENUBAR);
-						result = ETrue;
-						}
-					else if ( iControl->NumberOfContacts() == 0 )
-						{
-						result = ETrue;
-						}
+                        {
+                        result = ETrue;
+                        }
+                    else if ( iControl->NumberOfContacts() == 0 )
+                        {
+                        result = ETrue;
+                        }
                     }
                 break;
                 }
@@ -1531,7 +1545,6 @@
                 {
                 aMenuPane->SetItemDimmed( EPbk2CmdBelongsToGroups, ETrue );
                 aMenuPane->SetItemDimmed( EPbk2CmdAddMembers, ETrue );
-                aMenuPane->SetItemSpecific( EPbk2CmdRemoveFromGroup, EFalse );
                 }
             // Weed out commands not meant to be if names list is empty
             if ( Phonebook2::Pbk2AppUi()->ApplicationServices().
@@ -1549,9 +1562,12 @@
                 {
                 aMenuPane->SetItemDimmed( EPbk2CmdSend, ETrue );
                 }
-            if ( iControl->ContactsMarked() )
+                
+            // When Marking mode is active,
+            // Send as business card item should be shown in pop up menu.
+            if( iMarkingModeOn )
                 {
-                aMenuPane->SetItemSpecific( EPbk2CmdSend, EFalse );
+                aMenuPane->SetItemSpecific( EPbk2CmdSend, ETrue );
                 }
             break;
             }
@@ -1786,9 +1802,6 @@
                     R_PBK2_SOFTKEYS_OPTIONS_BACK_CONTEXT);
                 }
             iView.Cba()->DrawDeferred();
-            // Change context menu when marked items
-            iView.MenuBar()->SetContextMenuTitleResourceId
-                ( R_PHONEBOOK2_GROUPMEMBERS_CONTEXT_MENUBAR );
             }
         }
     }
@@ -1900,11 +1913,6 @@
                     // Select key is mapped to "Open Contact" command
                     HandleCommandL( EPbk2CmdOpenCca );
                     }
-                else
-                    {
-                    iView.LaunchPopupMenuL(
-                            R_PHONEBOOK2_GROUPMEMBERS_CONTEXT_MENUBAR);
-                    }
                 break;
                 }
             default:
@@ -1953,12 +1961,7 @@
         if ( iControl->NumberOfContacts() > 0 && 
                 iPointerEventInspector->FocusedItemPointed() )
             {
-            if ( iControl->ContactsMarked() )
-                {
-                iView.LaunchPopupMenuL(
-                    R_PHONEBOOK2_GROUPMEMBERS_CONTEXT_MENUBAR );
-                }
-            else
+            if ( !iControl->ContactsMarked() )
                 {
                 // Open contact
                 HandleCommandL(EPbk2CmdOpenCca);
@@ -2187,11 +2190,15 @@
         }
 
     iViewImpl->CreateControlL(iView.ClientRect());
-    
+
     CPbk2NamesListControl* nlctrl=static_cast <CPbk2NamesListControl*> (iViewImpl->Control());
+
+    // It will return the listbox by calling nlctrl->ComponentControl(0),
+    // which is defined in CPbk2NamesListControl::ComponentControl(TInt aIndex).
     CCoeControl* ctrl=nlctrl->ComponentControl(0);
     CEikListBox* listbox=static_cast <CEikListBox*> (ctrl);
-    listbox->SetListBoxObserver( this ); 
+    listbox->SetListBoxObserver( this );
+    listbox->SetMarkingModeObserver( this );
 
     iPreviousViewId = aPrevViewId;
 
@@ -2277,7 +2284,7 @@
             {
             case EEventItemDoubleClicked:
             case EEventItemSingleClicked:
-		    case EEventEnterKeyPressed:
+            case EEventEnterKeyPressed:
                 {
 
                 if ( iViewImpl )
@@ -2306,10 +2313,11 @@
 void CPguGroupMembersView::HandlePointerEventL(
         const TPointerEvent& aPointerEvent)
     {
-    if ( iViewImpl )
+    if ( iViewImpl && !iViewImpl->IsMarkingModeOn() )
         {
-        // route the pointer events to the view implementing the application
-        // view currently
+        // Route the pointer events to the view implementing the application
+        // view currently except the Marking mode is active, 
+        // because the event is handled by avkon when marking mode is active.
         iViewImpl->HandlePointerEventL(aPointerEvent);
         }
     }
@@ -2331,6 +2339,46 @@
         }
     }
 
+// -----------------------------------------------------------------------------
+// CPguGroupMembersView::MarkingModeStatusChanged
+// -----------------------------------------------------------------------------
+//
+void CPguGroupMembersView::MarkingModeStatusChanged( TBool aActivated )
+    {
+    if( iViewImpl )
+        {
+        iViewImpl->SetMarkingModeOn( aActivated );
+        CPbk2NamesListControl* nlctrl = 
+            static_cast <CPbk2NamesListControl*> (iViewImpl->Control());
+        if( !aActivated )
+            {
+            // It will return the findbox by calling 
+            // nlctrl->ComponentControl(1), which is defined in 
+            // CPbk2NamesListControl::ComponentControl(TInt aIndex).
+            CCoeControl* ctrl=nlctrl->ComponentControl(1);
+            if( ctrl->IsVisible() )
+                {
+                // Clear the text of the FindBox
+                // when canceling from Marking mode.
+                TRAP_IGNORE( nlctrl->ResetFindL() );
+                }
+            }
+        nlctrl->SetMarkingMode( aActivated );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CPguGroupMembersView::ExitMarkingMode
+// Called by avkon, if the return value is ETrue, 
+// the Marking mode will be canceled after any operation,
+// otherwise the Marking mode keep active.
+// -----------------------------------------------------------------------------
+//
+TBool CPguGroupMembersView::ExitMarkingMode() const
+    {
+    return EFalse; 
+    }
+
 // --------------------------------------------------------------------------
 // CPguGroupMembersView::TransformViewActivationStateToReady
 // --------------------------------------------------------------------------
--- a/phonebookui/Phonebook2/GroupExtension/src/CPguSendMessageGroupCmd.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/GroupExtension/src/CPguSendMessageGroupCmd.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -262,6 +262,7 @@
             }
         case EStopping:
             {
+            iSendMessage = EFalse;
             ProcessDismissed( KErrNone );
             break;
             }
@@ -369,32 +370,35 @@
     PBK2_DEBUG_PRINT(PBK2_DEBUG_STRING
         ("CPguSendMessageGroupCmd::DoSendMessageL() start") );
 
-    // Gets current tile pane and saves it to title
-    HBufC* title = NULL;
-    CAknTitlePane* titlePane = NULL;
-    CEikStatusPane *sp = CEikonEnv::Static()->AppUiFactory()->StatusPane();
-    titlePane = STATIC_CAST( CAknTitlePane*, 
-        sp->ControlL( TUid::Uid( EEikStatusPaneUidTitle ) ) );
-    title = titlePane->Text()->AllocLC();
-
-    Phonebook2::Pbk2AppUi()->ApplicationServices().SendUiL()->
-        CreateAndSendMessageL( iMtmUid, iMessageData );
-
-    if( !Layout_Meta_Data::IsLandscapeOrientation() )
+    if ( iSendMessage )
         {
-        sp->SwitchLayoutL( R_AVKON_STATUS_PANE_LAYOUT_USUAL );
-        sp->MakeVisible( ETrue );
-        
-        // Sets title pane for tile which was save
-        titlePane->SetText( title );
-        sp->DrawNow();
+        // Gets current tile pane and saves it to title
+        HBufC* title = NULL;
+        CAknTitlePane* titlePane = NULL;
+        CEikStatusPane *sp = CEikonEnv::Static()->AppUiFactory()->StatusPane();
+        titlePane = STATIC_CAST( CAknTitlePane*, 
+            sp->ControlL( TUid::Uid( EEikStatusPaneUidTitle ) ) );
+        title = titlePane->Text()->AllocLC();
+
+        Phonebook2::Pbk2AppUi()->ApplicationServices().SendUiL()->
+            CreateAndSendMessageL( iMtmUid, iMessageData );
+
+        if( !Layout_Meta_Data::IsLandscapeOrientation() )
+            {
+            sp->SwitchLayoutL( R_AVKON_STATUS_PANE_LAYOUT_USUAL );
+            sp->MakeVisible( ETrue );
+            
+            // Sets title pane for tile which was save
+            titlePane->SetText( title );
+            sp->DrawNow();
+            }
+        else
+            {
+            // Sets title pane for tile which was save
+            titlePane->SetText( title );
+            }
+        CleanupStack::Pop();
         }
-    else
-        {
-        // Sets title pane for tile which was save
-        titlePane->SetText( title );
-        }
-    CleanupStack::Pop();
 
     iState = EStopping;
     IssueRequest();
@@ -456,6 +460,7 @@
         SetAddressFromFieldL( *selectedField );
         CleanupStack::PopAndDestroy(); // selectedField
         iState = ERetrieving;
+        iSendMessage = ETrue;
         }
     else 
         {
--- a/phonebookui/Phonebook2/MMCExtension/src/CPmuCopyFromDriveCmd.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/MMCExtension/src/CPmuCopyFromDriveCmd.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -402,9 +402,14 @@
 // --------------------------------------------------------------------------
 //
 void CPmuCopyFromMmcCmd::ContactsSavingFailed
-        ( MVPbkContactOperationBase& aOperation, TInt /*aError*/ )
+        ( MVPbkContactOperationBase& aOperation, TInt aError )
     {
-    if ( &aOperation == iImportOperation )
+    // Stop copying if the disk is full
+    if ( aError == KErrDiskFull )
+        {
+        RunError( aError );
+        }
+    else if ( &aOperation == iImportOperation )
         {
         delete iImportOperation;
         iImportOperation = NULL;
--- a/phonebookui/Phonebook2/MapExtension/src/cpmapcmd.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/MapExtension/src/cpmapcmd.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -909,16 +909,7 @@
 		iMapView->AddLandmarksToShowL( landmarks );
 		iNoAddress = EFalse;
 		}
-    else
-        {
-        landmark->SetPositionFieldL(EPositionFieldCity,KNullDesC16);
-        TLocality tempLoc;
-        tempLoc.SetCoordinate(-0.0,-0.0);
-        landmark->SetPositionL(tempLoc);
-        
-        landmarks.AppendL( landmark );
-        iMapView->AddLandmarksToShowL( landmarks );
-        }
+    
 
 	iMapView->SelectFromMapL( iStatus );
 	iCurrentMapLaunchedByState = EMapAssignFromMaps;
--- a/phonebookui/Phonebook2/NamesListExtension/inc/Pbk2NamesListExView.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/NamesListExtension/inc/Pbk2NamesListExView.h	Thu Aug 19 09:41:07 2010 +0300
@@ -32,6 +32,7 @@
 #include <coemain.h>
 
 #include <Pbk2Commands.hrh> 
+#include <aknmarkingmodeobserver.h>
 
 // FORWARD DECLARATIONS
 template<class ControlType> class CPbk2ControlContainer;
@@ -70,7 +71,8 @@
                              public MCoeControlObserver,
                              public MEikListBoxObserver,
                              private MCoeForegroundObserver,
-                             public MPbk2UIExtensionView2
+                             public MPbk2UIExtensionView2,
+                             public MAknMarkingModeObserver
     {
     public: // Construction and destruction
 
@@ -162,6 +164,24 @@
                 CCoeControl* aControl,
                 TCoeEvent aEventType );
 
+    public: // From MAknMarkingModeObserver 
+            
+        /**
+         * This method is called when marking mode is activated or deactivated.
+         * 
+         * @param aActivated @c ETrue if marking mode was activate, @c EFalse
+         *                   if marking mode was deactivated.
+         */
+        void MarkingModeStatusChanged( TBool aActivated );
+
+        /**
+         * This method is called just before marking mode is closed. Client can 
+         * either accept or decline closing.
+         * 
+         * @return @c ETrue if marking mode should be closed, otherwise @c EFalse.
+         */
+        TBool ExitMarkingMode() const;  
+
     private: // Implementation
         CPbk2NamesListExView( 
             CPbk2UIExtensionView& aView,
@@ -262,8 +282,10 @@
         CSpbContentProvider&  iContentProvider;
         // Not own. CCA launcher connection
         MCCAConnection*& iCCAConnection;
-        /// Own: Context launcher
+        // Own: Context launcher
         CPbk2ContextLaunch* iContextLauncher;
+        // Flag to indicate whether Marking mode is active
+        TBool iMarkingModeOn;
     };
 
 #endif // CPBK2NAMESLISTEXVIEW_H
--- a/phonebookui/Phonebook2/NamesListExtension/rss/Pbk2ExNamesListRes.rss	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/NamesListExtension/rss/Pbk2ExNamesListRes.rss	Thu Aug 19 09:41:07 2010 +0300
@@ -367,8 +367,8 @@
             KPbk2ContactViewListControlDoubleRow;
     listbox = LISTBOX
         {
-        flags = EAknListBoxMarkableList | EAknListBoxLoopScrolling |
-                EAknListBoxShiftEnterMarks;
+        flags = EAknListBoxStylusMarkableList | EAknListBoxLoopScrolling |
+        EAknListBoxPointerMarkableList;    
         };
     iconArray = R_PBK2_CONTACT_LIST_ICONS;
     emptyIconId = PHONEBOOK2_ICON_ID
--- a/phonebookui/Phonebook2/NamesListExtension/src/CPbk2NameslistUiControlExtension.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/NamesListExtension/src/CPbk2NameslistUiControlExtension.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -371,6 +371,13 @@
 			TRAP_IGNORE( AddMyCardThumbnailToIconArrayL() );
 			}
 		}
+    // Refresh mycard list item if thumbnail has changed
+    if( iCommandUpdater &&
+        ( aEvent == EStateThumbnailLoaded ||
+          aEvent == EStateThumbnailNotFound ) )
+        {
+        iCommandUpdater->UpdateCommandItem( EPbk2CmdOpenMyCard );
+        }
 	}
 
 // -----------------------------------------------------------------------------
--- a/phonebookui/Phonebook2/NamesListExtension/src/NamesListExView.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/NamesListExtension/src/NamesListExView.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -62,6 +62,7 @@
 #include <pbk2mapcommands.hrh>
 #include "Pbk2InternalCommands.hrh"
 #include "CPbk2ContactViewListBox.h"
+#include <pbk2doublelistboxcmditemextension.h>
 
 #include "CVPbkContactManager.h"
 #include "MVPbkContactStoreList.h"
@@ -111,6 +112,7 @@
 #include <CPbk2StoreConfiguration.h>
 #include <VPbkContactStoreUris.h>
 #include <TVPbkContactStoreUriPtr.h>
+#include <Pbk2InternalUID.h>
 
 /// Unnamed namespace for local definitions
 namespace {
@@ -201,7 +203,8 @@
         iCtrlVisibleStateBeforeLosingForground( ETrue ),
         iFirstTimeActivated( ETrue ),
         iContentProvider( aStatusProvider ),
-        iCCAConnection( aCCAConnection )
+        iCCAConnection( aCCAConnection ),
+        iMarkingModeOn( EFalse )
     {
     }
 
@@ -416,9 +419,9 @@
         }
     
     if ( EPbk2CmdOpenCca == aCommandId )
-    	{
+        {
         iControl->SetOpeningCca( ETrue );
-    	}
+        }
 
     // Set focus, keep current focus on the area of the client screen
     // when scoll to the bottom of Names list view.
@@ -563,7 +566,7 @@
     // The application is set here to background if application exit occurs
     PBK2_PROFILE_START
         ( Pbk2Profile::ENamesListViewDoActivateNotifyViewActivatation );
-
+    
     // The application is set here to background if application exit occurs
     // When the device is powered on, Phonebook will start up automatically and
     // hide itself in the background. At the first time of names list view activation,
@@ -595,9 +598,12 @@
 
     PBK2_PROFILE_END(Pbk2Profile::ENamesListViewDoActivateL);
 
+    // It will return the listbox by calling iControl->ComponentControl(0),
+    // which is defined in CPbk2NamesListControl::ComponentControl(TInt aIndex).
     CCoeControl* ctrl=iControl->ComponentControl(0);
     CEikListBox* listbox=static_cast <CEikListBox*> (ctrl);
     listbox->SetListBoxObserver( this );
+    listbox->SetMarkingModeObserver( this );
 
     // iCtrlVisibleStateBeforeLosingForground records the names list control states before
     // losing foreground during a command execution. Set the iCtrlVisibleStateBeforeLosingForground
@@ -620,17 +626,17 @@
     // Check if there is need to create MyCard
     if( FeatureManager::FeatureSupported( KFeatureIdffContactsMycard ) &&
         ( !iMyCard && IsPhoneMemoryUsedL() ) )
-    	{				
-		// Get the phoneStore for MyCard
-		MVPbkContactStore* phoneStore = iContactManager->ContactStoresL()
-    		.Find(VPbkContactStoreUris::DefaultCntDbUri() );
-		
-		if( phoneStore )
-			{
-			// Create MyCard if not already exist and the phone memory selected
-			iMyCard = CPbk2MyCard::NewL( *phoneStore );
-			}
-    	}
+        {
+        // Get the phoneStore for MyCard
+        MVPbkContactStore* phoneStore = iContactManager->ContactStoresL()
+            .Find(VPbkContactStoreUris::DefaultCntDbUri() );
+        
+        if( phoneStore )
+            {
+            // Create MyCard if not already exist and the phone memory selected
+            iMyCard = CPbk2MyCard::NewL( *phoneStore );
+            }
+        }
     
     // Add the MyCard item to the top of the list
     if( iMyCard && IsPhoneMemoryUsedL() )
@@ -652,13 +658,13 @@
    // promotion item disabled until we can support command items at the bottom of the list
    // if ( IsRclOnL() )  
     if( 0 )
-	    {
+        {
         CPbk2CmdItemRemoteContactLookup* rclCmd = CPbk2CmdItemRemoteContactLookup::NewLC();
         // Add the command item to the bottom of the command list
         iControl->AddCommandItemL( rclCmd, commandCount ); // ownership transferred
         CleanupStack::Pop( rclCmd );
         commandCount++;
-	    }
+        }
     }
 
 // --------------------------------------------------------------------------
@@ -698,17 +704,17 @@
 // --------------------------------------------------------------------------
 //
 CPbk2MyCard* CPbk2NamesListExView::MyCard() const
-    {			
-	TBool phoneMemory = EFalse;
-	
-	TRAP_IGNORE( phoneMemory = IsPhoneMemoryUsedL() );
-	
-	if( phoneMemory )
-		{
-		return iMyCard;
-		}
-	
-	return NULL;
+    {
+    TBool phoneMemory = EFalse;
+    
+    TRAP_IGNORE( phoneMemory = IsPhoneMemoryUsedL() );
+    
+    if( phoneMemory )
+        {
+        return iMyCard;
+        }
+    
+    return NULL;
     }
 
 // --------------------------------------------------------------------------
@@ -758,6 +764,15 @@
     if (iContainer)
         {
         CCoeEnv::Static()->AppUi()->RemoveFromStack(iContainer);
+        if( iMarkingModeOn )
+            {
+            // It will return the listbox by calling
+            // iControl->ComponentControl(0), which is defined
+            // in CPbk2NamesListControl::ComponentControl(TInt aIndex).
+            CCoeControl* ctrl=iControl->ComponentControl(0);
+            CEikListBox* listbox=static_cast <CEikListBox*> (ctrl);
+            listbox->SetMarkingMode(EFalse);
+            }
         // Store current state, safe to ignore. There's no real harm,
         // if theres no stored state when activating this view again
         TRAP_IGNORE(StoreStateL());
@@ -790,17 +805,35 @@
     //there.
     switch (aResourceId)
         {
+        case R_AVKON_MENUPANE_MARK_MULTIPLE:
+            {
+            TInt pos;
+            if ( aMenuPane->MenuItemExists( EAknCmdMarkingModeEnter, pos ) &&
+                    iControl->NumberOfContacts() <= 0 )
+                {
+                aMenuPane->SetItemDimmed( EAknCmdMarkingModeEnter, ETrue );
+                }
+            break;
+            }
         case R_PHONEBOOK2_NAMESLIST_SEND_URL_MENU:
             {
             DimItem( aMenuPane, EPbk2CmdGoToURL );
+            if ( iControl->ContactsMarked() && iMarkingModeOn )
+                {
+                aMenuPane->SetItemDimmed( EPbk2CmdSend, EFalse );
+                }
             break;
             }
-        case R_PHONEBOOK2_NAMELIST_CREATE_MESSAGE_MENU:
+        case R_PHONEBOOK2_NAMESLIST_COPY_MENU:  
             {
             TInt pos;
-            if ( aMenuPane->MenuItemExists( EPbk2CmdWriteNoQuery, pos ) )
+            if ( aMenuPane->MenuItemExists( EPbk2CmdCopy, pos ) && iMarkingModeOn
+                    && iControl->NumberOfContacts() > 0  )
                 {
-                aMenuPane->SetItemSpecific( EPbk2CmdWriteNoQuery, !iControl->ContactsMarked() );
+                // Show Copy item both in pop up menu and Options
+                // when Marking mode is active.
+                aMenuPane->SetItemSpecific( EPbk2CmdCopy, ETrue );
+                aMenuPane->SetItemDimmed( EPbk2CmdCopy, EFalse );
                 }
             break;
             }
@@ -900,14 +933,44 @@
                 }
             case EKeyBackspace:
                 {
-                if ( (itemSpecEnabled && (iControl->NumberOfContacts() > 0))
-                    || iControl->ContactsMarked() )
+                if ( itemSpecEnabled &&  ( iControl->FindTextL() == KNullDesC ) )
                     {
-                    if (iControl->FindTextL() == KNullDesC)
+                    TBool contactsMarked( iControl->ContactsMarked() );
+
+                    MPbk2UiControlCmdItem* cmdItem = const_cast<MPbk2UiControlCmdItem*> ( iControl->FocusedCommandItem() );
+
+                    TBool onMyCard = cmdItem && ( EPbk2CmdOpenMyCard == cmdItem->CommandId() );
+
+                    if ( !contactsMarked && onMyCard )
                         {
+                        //Check to see whether the current focus is on MyCard or not
+                        //When none of the contacts are marked and with focus on MyCard,
+                        //  pressing BackSpace/Del key leads to deletion of MyCard
+    
+                        // get extension point and my card link
+                        TAny* object = cmdItem->ControlCmdItemExtension( TUid::Uid( KPbk2ControlCmdItemExtensionUID ) );
+                        if(  object )
+                            {
+                            MPbk2DoubleListboxCmdItemExtension* extension =
+                                    static_cast<MPbk2DoubleListboxCmdItemExtension*>( object );
+                            // if extension exists
+                            if( extension )
+                                {
+                                const MVPbkContactLink* link = extension->Link();
+                                // if link exists, then MyCard has been Assigned
+                                if( link )
+                                    {
+                                    HandleCommandL( EPbk2CmdDeleteMyCard );
+                                    result = ETrue;
+                                    }
+                                }
+                            }
+                        }
+                    else if(  ( contactsMarked ) || (iControl->NumberOfContacts() > 0) )
+                       {
                         HandleCommandL(EPbk2CmdDeleteMe);
                         result = ETrue;
-                        }
+                       }
                     }
                 break;
                 }
@@ -916,18 +979,12 @@
             case EKeyOK:
                 {
                 if ( !ShiftDown(aKeyEvent) ) // pure OK key
-					{
-					if ( iControl->ContactsMarked() && itemSpecEnabled )					
-					    {
-                        iView.LaunchPopupMenuL(
-                            R_PHONEBOOK2_NAMESLIST_CONTEXT_MENUBAR_ITEMS_MARKED);
-                        result = ETrue;
-					    }
-					else if ( iControl->NumberOfContacts() == 0 )
-					    {
-                        result = ETrue;
-					    }
-					}
+                    {
+                    if ( iControl->ContactsMarked() && itemSpecEnabled )
+                        {
+                        result = EFalse;
+                        }
+                    }
                 break;
                 }
             default:
@@ -958,11 +1015,11 @@
         switch ( aEventType )
             {
             case EEventItemSingleClicked:
-            	{
+                {
                 ShowContextMenuL();
                 break;
                 }
-#if 0            	
+#if 0                
             case EEventEmptyAreaClicked:  //An empty area of non-empty listbox was clicked 
             case EEventEmptyListClicked:  //An empty listbox was clicked                
                 {
@@ -995,11 +1052,6 @@
                     // Select key is mapped to "Open Contact" command
                     HandleCommandL(EPbk2CmdOpenCca);
                     }
-                else if (iControl->ContactsMarked())
-            		{
-                	iView.LaunchPopupMenuL(
-                    	R_PHONEBOOK2_NAMESLIST_CONTEXT_MENUBAR_ITEMS_MARKED);
-                    }
                 break;
                 }
             default:
@@ -1082,13 +1134,7 @@
             {
             if ( iPointerEventInspector->FocusedItemPointed() )
                 {
-                if ( iControl->ContactsMarked() )
-                    {
-                    // Display marked items context menu
-                    iView.LaunchPopupMenuL
-                        ( R_PHONEBOOK2_NAMESLIST_CONTEXT_MENUBAR_ITEMS_MARKED );
-                    }
-                else
+                if ( !iControl->ContactsMarked() )
                     {
                     // cancel the long tap animation with pointer up event
                     TPointerEvent event;
@@ -1131,9 +1177,9 @@
             {
             MTouchFeedback* feedback = MTouchFeedback::Instance();
             if ( feedback )
-                   {
-                   feedback->InstantFeedback( ETouchFeedbackBasic );
-                   }			
+                {
+                feedback->InstantFeedback( ETouchFeedbackBasic );
+                }
             HandleCommandL( EPbk2CmdCreateNew );
             }
         }    
@@ -1243,22 +1289,22 @@
     Reset();
            
     if( iMyCard )
-    	{
-		return;
-    	}
+        {
+        return;
+        }
        
     if( FeatureManager::FeatureSupported( KFeatureIdffContactsMycard ) )
-	   {    				
-		// Get the phoneStore for MyCard
-		TRAP_IGNORE( phoneStore = iContactManager->ContactStoresL().
-			Find( VPbkContactStoreUris::DefaultCntDbUri() ) );    		
-	   }
+        {
+        // Get the phoneStore for MyCard
+        TRAP_IGNORE( phoneStore = iContactManager->ContactStoresL().
+            Find( VPbkContactStoreUris::DefaultCntDbUri() ) );
+        }
                
     if( !phoneStore )
-    	{
+        {
         TRAP_IGNORE( iContactManager->LoadContactStoreL( 
                 VPbkContactStoreUris::DefaultCntDbUri() ) );
-    	}
+        }
     }
 
 // --------------------------------------------------------------------------
@@ -1515,13 +1561,51 @@
         }
     }
 
+// -----------------------------------------------------------------------------
+// CPbk2NamesListExView::MarkingModeStatusChanged
+// -----------------------------------------------------------------------------
+//
+void CPbk2NamesListExView::MarkingModeStatusChanged( TBool aActivated )
+    {
+    iMarkingModeOn = aActivated;
+
+    // It will return the control findbox by calling
+    // iControl->ComponentControl(1), which is defined
+    // in CPbk2NamesListControl::ComponentControl(TInt aIndex).
+    if ( !iMarkingModeOn && iControl->ComponentControl(1)->IsVisible() )
+        {
+        // Clear the text of the FindBox, when canceling from Marking mode.
+        TRAP_IGNORE( iControl->ResetFindL() );
+        }
+    iControl->SetMarkingMode( aActivated );
+
+    // It will return the control listbox by calling
+    // iControl->ComponentControl(0), which is defined
+    // in CPbk2NamesListControl::ComponentControl(TInt aIndex).
+    CPbk2ContactViewListBox* listbox = 
+        static_cast<CPbk2ContactViewListBox*>(iControl->ComponentControl(0));
+    listbox->SetMarkingModeState( aActivated );
+    }
+
+// -----------------------------------------------------------------------------
+// CPbk2NamesListExView::ExitMarkingMode
+// Called by avkon, if the return value is ETrue, 
+// the Marking mode will be canceled after any operation, 
+// otherwise the Marking mode keep active.
+// -----------------------------------------------------------------------------
+//
+TBool CPbk2NamesListExView::ExitMarkingMode() const
+    {
+    return EFalse; 
+    }
+    
 //---------------------------------------------------------------------------
 // CPbk2NamesListExView::CreateControlsL
 // --------------------------------------------------------------------------
 //
 inline void CPbk2NamesListExView::CreateControlsL()
     {
-	
+    
     if (!iContainer)
         {
         PBK2_PROFILE_START(Pbk2Profile::ENamesListViewCreateControls);
@@ -1628,9 +1712,6 @@
             {
             // Set middle softkey as Context Icon
             iView.Cba()->SetCommandSetL( R_PBK2_SOFTKEYS_OPTIONS_EXIT_CONTEXT );
-            // Change context menu when marked items
-            iView.MenuBar()->SetContextMenuTitleResourceId
-                ( R_PHONEBOOK2_NAMESLIST_CONTEXT_MENUBAR_ITEMS_MARKED );
             }
         else // not listContainsContacts && not contactsMarked
             {
@@ -1856,25 +1937,25 @@
 // --------------------------------------------------------------------------
 //
 TBool CPbk2NamesListExView::IsPhoneMemoryUsedL() const
-	{
-	CPbk2ApplicationServices* appServices = CPbk2ApplicationServices::InstanceL();
-			
-	// Get current configuration
-	CPbk2StoreConfiguration& storeConfig = appServices->StoreConfiguration();
-	
-	CVPbkContactStoreUriArray* uriArray = storeConfig.CurrentConfigurationL();
-			
-	TVPbkContactStoreUriPtr contactUri( VPbkContactStoreUris::DefaultCntDbUri() );		
-			
-	// Check is phone memory included
-	TBool phoneMemory = uriArray->IsIncluded( contactUri );
-	
-	delete uriArray;		
-	Release( appServices );
-	
-	return phoneMemory;
-	}
-	
+    {
+    CPbk2ApplicationServices* appServices = CPbk2ApplicationServices::InstanceL();
+            
+    // Get current configuration
+    CPbk2StoreConfiguration& storeConfig = appServices->StoreConfiguration();
+    
+    CVPbkContactStoreUriArray* uriArray = storeConfig.CurrentConfigurationL();
+            
+    TVPbkContactStoreUriPtr contactUri( VPbkContactStoreUris::DefaultCntDbUri() );
+            
+    // Check is phone memory included
+    TBool phoneMemory = uriArray->IsIncluded( contactUri );
+    
+    delete uriArray;        
+    Release( appServices );
+    
+    return phoneMemory;
+    }
+    
 // --------------------------------------------------------------------------
 // CPbk2NamesListExView::HandleGainingForeground
 // --------------------------------------------------------------------------
--- a/phonebookui/Phonebook2/NamesListExtension/src/NamesListUiExtensionPlugin.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/NamesListExtension/src/NamesListUiExtensionPlugin.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -371,41 +371,7 @@
             break;
             }
 #endif            
-        case R_AVKON_MENUPANE_MARKABLE_LIST_IMPLEMENTATION:
-        	{
-
-            if ( Pbk2NlxMenuFiltering::AddToFavoritesCmdSelected( aControl ) )
-                {
-                DimItem( aMenuPane, EAknCmdMark );
-                }
-            if ( Pbk2NlxMenuFiltering::MyCardCmdSelected( aControl ) )
-                {
-                DimItem( aMenuPane, EAknCmdMark );
-                }
-        	break;
-        	}
-        case R_PHONEBOOK2_MARKABLE_LIST_CONTEXT_MENU:
-            {
-            if ( Pbk2NlxMenuFiltering::AddToFavoritesCmdSelected( aControl ) )
-                {
-                DimItem( aMenuPane, EAknCmdMark );
-                DimItem( aMenuPane, EAknCmdUnmark );
-                }
-            if ( Pbk2NlxMenuFiltering::MyCardCmdSelected( aControl ) )
-                {
-                DimItem( aMenuPane, EAknCmdMark );
-                DimItem( aMenuPane, EAknCmdUnmark );
-                }
-            break;
-            }
-        case R_AVKON_MENUPANE_MARKABLE_LIST:
-            {
-            if ( !aControl.NumberOfContacts() )
-                {
-                DimItem( aMenuPane, EAknCmdEditListMenu );
-                }
-            break;
-            }
+       
         case R_PHONEBOOK2_NAMESLIST_COPY_MENU:
             {
             MPbk2ContactUiControl2* tempControl = 
--- a/phonebookui/Phonebook2/NamesListExtension/src/cpbk2cmditemmycard.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/NamesListExtension/src/cpbk2cmditemmycard.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -118,23 +118,10 @@
     return NULL;
     }
 
-void CPbk2CmdItemMyCard::MyCardEvent( MPbk2MyCardObserver::TMyCardStatusEvent aEvent )
+void CPbk2CmdItemMyCard::MyCardEvent( MPbk2MyCardObserver::TMyCardStatusEvent /*aEvent*/ )
     {
-	// always inform these
-    if( aEvent == EStateThumbnailLoaded ||
-    	aEvent == EStateThumbnailNotFound )
-    	{
-		if( iObserver )
-			{
-			iObserver->CmdItemVisibilityChanged( CommandId(), ETrue );
-			}
-    	}
-    // status change
-    else
-    	{
-		NotifyVisibiltyChange( IsEnabled() ) ;    
-    	}
-	}
+    NotifyVisibiltyChange( IsEnabled() );
+    }
 
 void CPbk2CmdItemMyCard::FormatDataL(
                 MPbk2DoubleListboxDataElement& aDataElement )
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2AddressSelectPhase.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2AddressSelectPhase.h	Thu Aug 19 09:41:07 2010 +0300
@@ -81,6 +81,8 @@
                 TInt aExitCommandId );
         void AcceptDelayedL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedL(
+                const TDesC8& aContactLinkBuffer );
         MVPbkContactLinkArray* Results() const;
         TInt ExtraResultData() const;
         MVPbkStoreContact* TakeStoreContact();
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2AssignAttributePhase.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2AssignAttributePhase.h	Thu Aug 19 09:41:07 2010 +0300
@@ -79,6 +79,8 @@
                 TInt aExitCommandId );
         void AcceptDelayedL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedL(
+                const TDesC8& aContactLinkBuffer );
         MVPbkContactLinkArray* Results() const;
         TInt ExtraResultData() const;
         MVPbkStoreContact* TakeStoreContact();
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2AttributeAddressSelectPhase.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2AttributeAddressSelectPhase.h	Thu Aug 19 09:41:07 2010 +0300
@@ -82,6 +82,8 @@
                 TInt aExitCommandId );
         void AcceptDelayedL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedL(
+                const TDesC8& aContactLinkBuffer );
         MVPbkContactLinkArray* Results() const;
         TInt ExtraResultData() const;
         MVPbkStoreContact* TakeStoreContact();
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2CommAddressSelectPhase.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2CommAddressSelectPhase.h	Thu Aug 19 09:41:07 2010 +0300
@@ -127,6 +127,8 @@
                 TInt aExitCommandId );
         void AcceptDelayedL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedL(
+                const TDesC8& aContactLinkBuffer );
         MVPbkContactLinkArray* Results() const;
         TInt ExtraResultData() const;
         MVPbkStoreContact* TakeStoreContact();
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2ContactAttributeAssigner.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2ContactAttributeAssigner.h	Thu Aug 19 09:41:07 2010 +0300
@@ -67,6 +67,8 @@
         void CancelService();
         void AcceptDelayedContactsL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedContactsL(
+                const TDesC8& aContactLinkBuffer );
         void ExitServiceL(
                 TInt aExitCommandId );
         void ServiceResults(TServiceResults* aResults) const;
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2ContactFetchPhase.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2ContactFetchPhase.h	Thu Aug 19 09:41:07 2010 +0300
@@ -89,6 +89,8 @@
                 TInt aExitCommandId );
         void AcceptDelayedL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedL(
+                const TDesC8& aContactLinkBuffer );
         MVPbkContactLinkArray* Results() const;
         TInt ExtraResultData() const;
         MVPbkStoreContact* TakeStoreContact();
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2EntryFetcher.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2EntryFetcher.h	Thu Aug 19 09:41:07 2010 +0300
@@ -68,6 +68,8 @@
         void CancelService();
         void AcceptDelayedContactsL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedContactsL(
+                const TDesC8& aContactLinkBuffer );
         void ExitServiceL(
                 TInt aExitCommandId );
         void ServiceResults(TServiceResults* aResults) const;
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2ItemFetcher.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2ItemFetcher.h	Thu Aug 19 09:41:07 2010 +0300
@@ -71,6 +71,8 @@
         void CancelService();
         void AcceptDelayedContactsL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedContactsL(
+                const TDesC8& aContactLinkBuffer );
         void ExitServiceL(
                 TInt aExitCommandId );
         void ServiceResults(TServiceResults* aResults) const;
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2MultiAssignDataPhase.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2MultiAssignDataPhase.h	Thu Aug 19 09:41:07 2010 +0300
@@ -86,6 +86,8 @@
                 TInt aExitCommandId );
         void AcceptDelayedL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedL(
+                const TDesC8& aContactLinkBuffer );
         MVPbkContactLinkArray* Results() const;
         TInt ExtraResultData() const;
         MVPbkStoreContact* TakeStoreContact();
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2MultiContactDataAssigner.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2MultiContactDataAssigner.h	Thu Aug 19 09:41:07 2010 +0300
@@ -68,6 +68,8 @@
         void CancelService();
         void AcceptDelayedContactsL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedContactsL(
+                const TDesC8& aContactLinkBuffer );
         void ExitServiceL(
                 TInt aExitCommandId );
         void ServiceResults(TServiceResults* aResults) const;
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2PrepareAttributeAssignPhase.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2PrepareAttributeAssignPhase.h	Thu Aug 19 09:41:07 2010 +0300
@@ -78,6 +78,8 @@
                 TInt aExitCommandId );
         void AcceptDelayedL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedL(
+                const TDesC8& aContactLinkBuffer );
         MVPbkContactLinkArray* Results() const;
         TInt ExtraResultData() const;
         MVPbkStoreContact* TakeStoreContact();
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2PrepareMultipleAssignPhase.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2PrepareMultipleAssignPhase.h	Thu Aug 19 09:41:07 2010 +0300
@@ -81,6 +81,8 @@
                 TInt aExitCommandId );
         void AcceptDelayedL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedL(
+                const TDesC8& aContactLinkBuffer );
         MVPbkContactLinkArray* Results() const;
         TInt ExtraResultData() const;
         MVPbkStoreContact* TakeStoreContact();
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2PrepareSingleAssignPhase.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2PrepareSingleAssignPhase.h	Thu Aug 19 09:41:07 2010 +0300
@@ -83,6 +83,8 @@
                 TInt aExitCommandId );
         void AcceptDelayedL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedL(
+                const TDesC8& aContactLinkBuffer );
         MVPbkContactLinkArray* Results() const;
         TInt ExtraResultData() const;
         MVPbkStoreContact* TakeStoreContact();
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2SelectCreateEmptyPropertyPhase.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2SelectCreateEmptyPropertyPhase.h	Thu Aug 19 09:41:07 2010 +0300
@@ -72,6 +72,8 @@
                 TInt aExitCommandId );
         void AcceptDelayedL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedL(
+                const TDesC8& aContactLinkBuffer );
         MVPbkContactLinkArray* Results() const;
         MVPbkStoreContact* TakeStoreContact();
         TInt ExtraResultData() const;
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2SelectCreateNewPropertyPhase.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2SelectCreateNewPropertyPhase.h	Thu Aug 19 09:41:07 2010 +0300
@@ -78,6 +78,8 @@
                 TInt aExitCommandId );
         void AcceptDelayedL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedL(
+                const TDesC8& aContactLinkBuffer );
         MVPbkContactLinkArray* Results() const;
         TInt ExtraResultData() const;
         MVPbkStoreContact* TakeStoreContact();
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2SelectMultiplePropertyPhase.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2SelectMultiplePropertyPhase.h	Thu Aug 19 09:41:07 2010 +0300
@@ -73,6 +73,8 @@
                 TInt aExitCommandId );
         void AcceptDelayedL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedL(
+                const TDesC8& aContactLinkBuffer );
         MVPbkContactLinkArray* Results() const;
         TInt ExtraResultData() const;
         MVPbkStoreContact* TakeStoreContact();
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2SelectSinglePropertyPhase.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2SelectSinglePropertyPhase.h	Thu Aug 19 09:41:07 2010 +0300
@@ -79,6 +79,8 @@
                 TInt aExitCommandId );
         void AcceptDelayedL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedL(
+                const TDesC8& aContactLinkBuffer );
         MVPbkContactLinkArray* Results() const;
         TInt ExtraResultData() const;
         MVPbkStoreContact* TakeStoreContact();
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2SelectUpdateEmptyPropertyPhase.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2SelectUpdateEmptyPropertyPhase.h	Thu Aug 19 09:41:07 2010 +0300
@@ -76,6 +76,8 @@
                 TInt aExitCommandId );
         void AcceptDelayedL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedL(
+                const TDesC8& aContactLinkBuffer );
         MVPbkContactLinkArray* Results() const;
         MVPbkStoreContact* TakeStoreContact();
         TInt ExtraResultData() const; 
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2SingleAssignDataPhase.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2SingleAssignDataPhase.h	Thu Aug 19 09:41:07 2010 +0300
@@ -91,6 +91,8 @@
                 TInt aExitCommandId );
         void AcceptDelayedL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedL(
+                const TDesC8& aContactLinkBuffer );
         MVPbkContactLinkArray* Results() const;
         TInt ExtraResultData() const;
         MVPbkStoreContact* TakeStoreContact();
--- a/phonebookui/Phonebook2/ServerApplication/inc/CPbk2SingleContactDataAssigner.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/CPbk2SingleContactDataAssigner.h	Thu Aug 19 09:41:07 2010 +0300
@@ -70,6 +70,8 @@
         void CancelService();
         void AcceptDelayedContactsL(
                 const TDesC8& aContactLinkBuffer );
+        void DenyDelayedContactsL(
+                const TDesC8& aContactLinkBuffer );
         void ExitServiceL(
                 TInt aExitCommandId );
         void ServiceResults(TServiceResults* aResults) const;
--- a/phonebookui/Phonebook2/ServerApplication/inc/MPbk2ServicePhase.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/MPbk2ServicePhase.h	Thu Aug 19 09:41:07 2010 +0300
@@ -68,6 +68,18 @@
                 const TDesC8& aContactLinkBuffer ) = 0;
 
         /**
+         * Notifies of delayed acception.
+         *
+         * Purpose: Sometimes client maybe deny the selected contact, 
+         * the function is used to deliver the client's feedback to phonebook.
+         * 
+         * @param aContactLinkBuffer    Buffer containing denied
+         *                              contact links.
+         */
+        virtual void DenyDelayedL(
+                const TDesC8& aContactLinkBuffer ) = 0;
+        
+        /**
          * Returns the results.
          *
          * @return  Results.
--- a/phonebookui/Phonebook2/ServerApplication/inc/MPbk2UiService.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/inc/MPbk2UiService.h	Thu Aug 19 09:41:07 2010 +0300
@@ -68,6 +68,18 @@
                 const TDesC8& aContactLinkBuffer ) = 0;
 
         /**
+         * Deny the delayed contacts as part of
+         * the contact set used in the service.
+         * 
+         * Purpose: Sometimes client maybe deny the selected contact, 
+         * the function is used to deliver the client's feedback to phonebook.
+         * 
+         * @param aContactLinkBuffer    Denied contacts.
+         */
+        virtual void DenyDelayedContactsL(
+                const TDesC8& aContactLinkBuffer) = 0;
+        
+        /**
          * Exits the service.
          *
          * @param aExitCommandId    The id of the exit command.
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2AddressSelectPhase.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2AddressSelectPhase.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -206,6 +206,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2AddressSelectPhase::DenyDelayed
+// --------------------------------------------------------------------------
+//
+void CPbk2AddressSelectPhase::DenyDelayedL
+        ( const TDesC8& /*aContactLinkBuffer*/ )
+    {
+    // Nothing to deny
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2AddressSelectPhase::Results
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2AssignAttributePhase.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2AssignAttributePhase.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -164,6 +164,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2AssignAttributePhase::DenyDelayed
+// --------------------------------------------------------------------------
+//
+void CPbk2AssignAttributePhase::DenyDelayedL
+        ( const TDesC8& /*aContactLinkBuffer*/ )
+    {
+    // Nothing to do
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2AssignAttributePhase::Results
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2AttributeAddressSelectPhase.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2AttributeAddressSelectPhase.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -199,6 +199,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2AttributeAddressSelectPhase::DenyDelayed
+// --------------------------------------------------------------------------
+//
+void CPbk2AttributeAddressSelectPhase::DenyDelayedL
+        ( const TDesC8& /*aContactLinkBuffer*/ )
+    {
+    // Nothing to deny
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2AttributeAddressSelectPhase::Results
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2CommAddressSelectPhase.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2CommAddressSelectPhase.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -307,6 +307,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2CommAddressSelectPhase::DenyDelayed
+// --------------------------------------------------------------------------
+//
+void CPbk2CommAddressSelectPhase::DenyDelayedL
+        ( const TDesC8& /*aContactLinkBuffer*/ )
+    {
+    // Nothing to deny
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2CommAddressSelectPhase::Results
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2ContactAttributeAssigner.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2ContactAttributeAssigner.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -268,6 +268,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2ContactAttributeAssigner::DenyDelayedContactsL
+// --------------------------------------------------------------------------
+//
+void CPbk2ContactAttributeAssigner::DenyDelayedContactsL
+        ( const TDesC8& /*aContactLinkBuffer*/ )
+    {
+    // Do nothing
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2ContactAttributeAssigner::ExitServiceL
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2ContactFetchPhase.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2ContactFetchPhase.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -186,6 +186,19 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2ContactFetchPhase::DenyDelayed
+// --------------------------------------------------------------------------
+//
+void CPbk2ContactFetchPhase::DenyDelayedL
+        ( const TDesC8& aContactLinkBuffer )
+    {
+    if ( iFetchDlg )
+        {
+        iFetchDlg->DenyDelayedFetchL( aContactLinkBuffer );
+        }
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2ContactFetchPhase::Results
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2EntryFetcher.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2EntryFetcher.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -190,6 +190,22 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2EntryFetcher::DenyDelayedContactsL
+// --------------------------------------------------------------------------
+//
+void CPbk2EntryFetcher::DenyDelayedContactsL
+        ( const TDesC8& aContactLinkBuffer )
+    {
+    PBK2_DEBUG_PRINT( PBK2_DEBUG_STRING
+        ("CPbk2EntryFetcher::DenyDelayedContactsL()") );
+
+    if ( iFetchPhase )
+        {
+        iFetchPhase->DenyDelayedL( aContactLinkBuffer );
+        }
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2EntryFetcher::ExitServiceL
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2FetchService.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2FetchService.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -276,13 +276,23 @@
     TPckg<TBool> acceptedPkg( accepted );
     aMessage.ReadL( KAcceptServiceSlot, acceptedPkg );
 
-    if ( iUiService && accepted )
+    if ( iUiService )
         {
         HBufC8* buffer = HBufC8::NewLC(
             aMessage.GetDesMaxLengthL( KSelectedContactSlot ) );
         TPtr8 ptr = buffer->Des();
         aMessage.ReadL( KSelectedContactSlot, ptr );
-        iUiService->AcceptDelayedContactsL( *buffer );
+        
+        // If client accepts selected contact, call AcceptDelayedContacts
+        // Otherwise call DenyDelayedContactsL
+        if( accepted )
+            {
+            iUiService->AcceptDelayedContactsL( *buffer );
+            }
+        else
+            {
+            iUiService->DenyDelayedContactsL( *buffer );
+            }
         CleanupStack::PopAndDestroy(); // buffer
         }
 
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2ItemFetcher.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2ItemFetcher.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -409,6 +409,31 @@
         iFetchPhase->AcceptDelayedL( aContactLinkBuffer );
         }
     }
+// --------------------------------------------------------------------------
+// CPbk2ItemFetcher::DenyDelayedContactsL
+// --------------------------------------------------------------------------
+//
+void CPbk2ItemFetcher::DenyDelayedContactsL
+        ( const TDesC8& aContactLinkBuffer )
+    {
+    PBK2_DEBUG_PRINT( PBK2_DEBUG_STRING
+        ("CPbk2ItemFetcher::DenyDelayedContactsL()") );
+
+    if ( iAddressSelectPhase )
+        {
+        iAddressSelectPhase->DenyDelayedL( aContactLinkBuffer );
+        }
+
+    if ( iCommAddressSelectPhase )
+        {
+        iCommAddressSelectPhase->DenyDelayedL( aContactLinkBuffer );
+        }
+
+    if ( iFetchPhase )
+        {
+        iFetchPhase->DenyDelayedL( aContactLinkBuffer );
+        }
+    }
 
 // --------------------------------------------------------------------------
 // CPbk2ItemFetcher::ExitServiceL
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2MultiAssignDataPhase.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2MultiAssignDataPhase.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -206,6 +206,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2MultiAssignDataPhase::DenyDelayed
+// --------------------------------------------------------------------------
+//
+void CPbk2MultiAssignDataPhase::DenyDelayedL
+        ( const TDesC8& /*aContactLinkBuffer*/ )
+    {
+    // Nothing to do
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2MultiAssignDataPhase::Results
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2MultiContactDataAssigner.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2MultiContactDataAssigner.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -231,6 +231,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2MultiContactDataAssigner::AcceptDelayedContactsL
+// --------------------------------------------------------------------------
+//
+void CPbk2MultiContactDataAssigner::DenyDelayedContactsL
+        ( const TDesC8& /*aContactLinkBuffer*/ )
+    {
+    // Do nothing
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2MultiContactDataAssigner::ExitServiceL
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2PrepareAttributeAssignPhase.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2PrepareAttributeAssignPhase.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -204,6 +204,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2PrepareAttributeAssignPhase::DenyDelayed
+// --------------------------------------------------------------------------
+//
+void CPbk2PrepareAttributeAssignPhase::DenyDelayedL
+        ( const TDesC8& /*aContactLinkBuffer*/ )
+    {
+    // Nothing to do
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2PrepareAttributeAssignPhase::Results
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2PrepareSingleAssignPhase.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2PrepareSingleAssignPhase.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -191,6 +191,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2PrepareSingleAssignPhase::DenyDelayed
+// --------------------------------------------------------------------------
+//
+void CPbk2PrepareSingleAssignPhase::DenyDelayedL
+        ( const TDesC8& /*aContactLinkBuffer*/ )
+    {
+    // Nothing to do
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2PrepareSingleAssignPhase::Results
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2SelectCreateEmptyPropertyPhase.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2SelectCreateEmptyPropertyPhase.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -127,6 +127,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2SelectCreateEmptyPropertyPhase::DenyDelayed
+// --------------------------------------------------------------------------
+//
+void CPbk2SelectCreateEmptyPropertyPhase::DenyDelayedL
+        ( const TDesC8& /*aContactLinkBuffer*/ )
+    {
+    // Nothing to do
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2SelectCreateEmptyPropertyPhase::Results
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2SelectCreateNewPropertyPhase.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2SelectCreateNewPropertyPhase.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -153,6 +153,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2SelectCreateNewPropertyPhase::DenyDelayed
+// --------------------------------------------------------------------------
+//
+void CPbk2SelectCreateNewPropertyPhase::DenyDelayedL
+        ( const TDesC8& /*aContactLinkBuffer*/ )
+    {
+    // Nothing to do
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2SelectCreateNewPropertyPhase::Results
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2SelectMultiplePropertyPhase.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2SelectMultiplePropertyPhase.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -180,6 +180,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2SelectMultiplePropertyPhase::DenyDelayed
+// --------------------------------------------------------------------------
+//
+void CPbk2SelectMultiplePropertyPhase::DenyDelayedL
+        ( const TDesC8& /*aContactLinkBuffer*/ )
+    {
+    // Nothing to do
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2SelectMultiplePropertyPhase::Results
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2SelectSinglePropertyPhase.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2SelectSinglePropertyPhase.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -182,6 +182,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2SelectSinglePropertyPhase::DenyDelayed
+// --------------------------------------------------------------------------
+//
+void CPbk2SelectSinglePropertyPhase::DenyDelayedL
+        ( const TDesC8& /*aContactLinkBuffer*/ )
+    {
+    // Nothing to do
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2SelectSinglePropertyPhase::Results
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2SelectUpdateEmptyPropertyPhase.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2SelectUpdateEmptyPropertyPhase.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -162,6 +162,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2SelectUpdateEmptyPropertyPhase::DenyDelayed
+// --------------------------------------------------------------------------
+//
+void CPbk2SelectUpdateEmptyPropertyPhase::DenyDelayedL
+        ( const TDesC8& /*aContactLinkBuffer*/ )
+    {
+    // Nothing to do
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2SelectUpdateEmptyPropertyPhase::Results
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2SingleAssignDataPhase.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2SingleAssignDataPhase.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -174,6 +174,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2SingleAssignDataPhase::DenyDelayed
+// --------------------------------------------------------------------------
+//
+void CPbk2SingleAssignDataPhase::DenyDelayedL
+        ( const TDesC8& /*aContactLinkBuffer*/ )
+    {
+    // Nothing to do
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2SingleAssignDataPhase::Results
 // --------------------------------------------------------------------------
 //
@@ -540,9 +550,16 @@
 void CPbk2SingleAssignDataPhase::FinalizeL
         ( const MVPbkStoreContact* aStoreContact )
     {
+    TBool thisDestroyed = EFalse;
+    iDestroyedPtr = &thisDestroyed;
+        
     AppendResultL( aStoreContact );
-    DisplayNotesL();
-    iObserver.NextPhase( *this );
+    DisplayNotesL();    
+     
+    if ( !thisDestroyed )
+        {
+        iObserver.NextPhase( *this );
+        }    
     }
 
 // End of File
--- a/phonebookui/Phonebook2/ServerApplication/src/CPbk2SingleContactDataAssigner.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/CPbk2SingleContactDataAssigner.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -236,6 +236,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2SingleContactDataAssigner::DenyDelayedContactsL
+// --------------------------------------------------------------------------
+//
+void CPbk2SingleContactDataAssigner::DenyDelayedContactsL
+        ( const TDesC8& /*aContactLinkBuffer*/ )
+    {
+    // Do nothing
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2SingleContactDataAssigner::ExitServiceL
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/ServerApplication/src/cpbk2preparemultipleassignphase.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ServerApplication/src/cpbk2preparemultipleassignphase.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -212,6 +212,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2PrepareMultipleAssignPhase::DenyDelayed
+// --------------------------------------------------------------------------
+//
+void CPbk2PrepareMultipleAssignPhase::DenyDelayedL
+        ( const TDesC8& /*aContactLinkBuffer*/ )
+    {
+    // Nothing to do
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2PrepareMultipleAssignPhase::Results
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/UIControls/inc/CPbk2ContactEditorDlgImpl.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/inc/CPbk2ContactEditorDlgImpl.h	Thu Aug 19 09:41:07 2010 +0300
@@ -373,6 +373,8 @@
                 TEventCode aType );
         void RestorePrevNaviDecoratorL();
         void RestoreStatusPaneL(); 
+        static TInt DelayDlgDeleteCallBack( TAny* aCallBack );
+        void DelayDlgDelete();
 
     private: // Data structures
 
@@ -472,6 +474,8 @@
         CAknNavigationDecorator* iPrevNaviDecorator;
         
         TInt iCurrentstatuspane;
+        /// Own: For asynchronously delete editordlg.
+        CIdle* iDelayDelete;
     };
 
 #endif // CPBK2CONTACTEDITORDLGIMPL_H
--- a/phonebookui/Phonebook2/UIControls/inc/CPbk2ContactEditorUIAddressField.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/inc/CPbk2ContactEditorUIAddressField.h	Thu Aug 19 09:41:07 2010 +0300
@@ -61,6 +61,7 @@
         void ActivateL();
         TInt ControlId();
         TBool HandleCustomFieldCommandL(TInt aCommand);
+        TBool ConsumesKeyEvent( const TKeyEvent& aKeyEvent, TEventCode aType );
   
 
     private:
--- a/phonebookui/Phonebook2/UIControls/inc/CPbk2ContactViewListBox.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/inc/CPbk2ContactViewListBox.h	Thu Aug 19 09:41:07 2010 +0300
@@ -178,6 +178,14 @@
         void HandlePopupCharacter( CWindowGc* aGc,
                                    const TRect& aRectOfListBoxItem ) const;
 
+        /**
+         * Set the state of the Marking mode 
+         */
+        inline void SetMarkingModeState( TBool aActived )
+            {
+            iMarkingModeOn = aActived;
+            }
+
     public: // From MPbk2ClipListBoxText
         TBool ClipFromBeginning(
                 TDes& aBuffer,
@@ -226,6 +234,9 @@
 
         TBool IsContact( TInt aIndex ) const;
         
+    private:
+        void RecalcWidthInMarkingMode( TInt& aWidth, const CFont& aFont, TChar aChar );
+        
     private: // Data structures
         /// Data loaded from resources
         struct TResourceData
@@ -266,6 +277,8 @@
         CPbk2PredictiveSearchFilter &iSearchFilter;
         // ref: used fro checking command item count
         CCoeControl& iContainer;
+        // Flag to indicate whether Marking mode is active
+        TBool iMarkingModeOn;
         
     };
 
--- a/phonebookui/Phonebook2/UIControls/inc/CPbk2FetchResults.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/inc/CPbk2FetchResults.h	Thu Aug 19 09:41:07 2010 +0300
@@ -35,6 +35,7 @@
 class MPbk2FetchDlgPages;
 class MPbk2FetchDlgObserver;
 class MPbk2FetchResultsObserver;
+class CAknInputBlock;
 
 // CLASS DECLARATION
 
@@ -88,7 +89,15 @@
          */
         void AppendDelayedL(
                 const MVPbkContactLink& aLink );
-        
+
+        /**
+         * Deny to Append a delayed contact link to selection.
+         *
+         * @param aLink     The link to deny append.
+         */
+        void DenyAppendDelayedL(
+                const MVPbkContactLink& aLink );
+
         /**
          * Appends a contact link to fetch results.
          *
@@ -110,6 +119,10 @@
          */
         void ResetAndDestroy();
 
+        /**
+         * Wait operations to complete
+         */
+        void WaitOperationsCompleteL();
     public: // From MVPbkContactLinkArray
         TInt Count() const;
         const MVPbkContactLink& At(
@@ -233,6 +246,12 @@
         CArrayFixFlat<CFRConatactOperation*>* iOperationQueue;
         /// Own: Contact retrieve operation
         MVPbkContactOperationBase* iRetrieveOperation;
+        /// Own: Is it waiting the acceptance, initialized to EFalse
+        TBool iWaitingForDelayedAppend;
+        /// Own: Wait until finish contact store operation
+        CActiveSchedulerWait* iWaitForAllOperationComplete;
+        /// Own: User input blocker
+        CAknInputBlock* iInputBlock;
     };
 
 #endif // CPBK2FETCHRESULTS_H
--- a/phonebookui/Phonebook2/UIControls/inc/CPbk2NamesListEmptyState.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/inc/CPbk2NamesListEmptyState.h	Thu Aug 19 09:41:07 2010 +0300
@@ -187,7 +187,8 @@
         TInt CalculateListboxIndex(TInt aCommandIndex) const;       
         void UnsubscribeCmdItemsVisibility() const;					
         void SubscribeCmdItemsVisibility();							
-        void HandleListboxEventL(TInt aEvent, TInt aListboxIndex, TBool aMantainFocus);  
+        void HandleListboxEventL(TInt aEvent, TInt aListboxIndex, TBool aMantainFocus);
+        TInt EnabledCommandCount() const; 
 
     private: // Data
         /// Ref: Parent coecontrol
--- a/phonebookui/Phonebook2/UIControls/inc/CPbk2NamesListFilteredState.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/inc/CPbk2NamesListFilteredState.h	Thu Aug 19 09:41:07 2010 +0300
@@ -208,7 +208,8 @@
         TInt CalculateListboxIndex(TInt aCommandIndex) const;       
         void UnsubscribeCmdItemsVisibility() const;					
         void SubscribeCmdItemsVisibility();							
-        void HandleListboxEventL(TInt aEvent, TInt aListboxIndex, TBool aMantainFocus);  
+        void HandleListboxEventL(TInt aEvent, TInt aListboxIndex, TBool aMantainFocus);
+        TInt EnabledCommandCount() const; 
 
     private: // Data
         /// Ref: Parent coecontrol
--- a/phonebookui/Phonebook2/UIControls/inc/CPbk2SettingsListState.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/inc/CPbk2SettingsListState.h	Thu Aug 19 09:41:07 2010 +0300
@@ -55,6 +55,13 @@
          * @return  Selection item list.
          */
         CSelectionItemList& SelectionItemList();
+        
+        /**
+         * Returns a copy of selection item list.
+         *
+         * @return old item list state.
+         */
+        CSelectionItemList& ItemListState();
 
         /**
          * Returns supported store configuration.
--- a/phonebookui/Phonebook2/UIControls/inc/cpbk2contactviewcustomlistboxdata.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/inc/cpbk2contactviewcustomlistboxdata.h	Thu Aug 19 09:41:07 2010 +0300
@@ -102,8 +102,8 @@
          */
         TRgb iHighlightedBack;
         };
-//Start of Code Added for PhoneBook2
-public: //Function below are added to suit PhoneBook2 Requirements
+
+public: 
     
     /**
      * Set internal data model to work with special PCS data
@@ -148,12 +148,11 @@
      */
     void SetListCommands( const RPointerArray<MPbk2UiControlCmdItem>* aCommands );
     
-private:
     TBool IsContactAtListboxIndex( TInt aListboxIndex ) const;
+	
+private:    
     TInt CommandItemCount() const;
     
-//End of Code Added for PhoneBook2
-    
 public:
 
     /**
--- a/phonebookui/Phonebook2/UIControls/inc/cpbk2contactviewcustomlistboxitemdrawer.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/inc/cpbk2contactviewcustomlistboxitemdrawer.h	Thu Aug 19 09:41:07 2010 +0300
@@ -200,17 +200,7 @@
 
 protected:
 
-#ifndef RD_TOUCH2
-    /**
-     * Draw the item background.
-     *
-     * Internal member, not intended for use.
-     *
-     * @param aRect Drawing area. 
-     */
-    void DrawCurrentItemRect(const TRect& aRect) const;
 
-#endif
     
     /** 
      * Array of properties.
--- a/phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorDlgImpl.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorDlgImpl.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -207,14 +207,14 @@
         }
     
     if( iAppServices )
-    	{
-    	iAppServices->StoreObservationRegister().DeregisterStoreEvents( *this );
-    	}
+        {
+        iAppServices->StoreObservationRegister().DeregisterStoreEvents( *this );
+        }
     else
-    	{
-    	Phonebook2::Pbk2AppUi()->ApplicationServices().
-    	        StoreObservationRegister().DeregisterStoreEvents( *this );
-    	}
+        {
+        Phonebook2::Pbk2AppUi()->ApplicationServices().
+                StoreObservationRegister().DeregisterStoreEvents( *this );
+        }
               
     if ( iEikonEnv && iContextMenuBar )
         {
@@ -237,12 +237,13 @@
     delete iEditorExtension;
     delete iUiFieldArray;
     Release(iExtensionManager);
-	delete iTitleText;    
+    delete iTitleText;    
     iTitleText = NULL;
     delete iStoredTitlePaneText;
     iStoredTitlePaneText = NULL;
 
     delete iConverter;
+    delete iDelayDelete;
     }
 
 // --------------------------------------------------------------------------
@@ -256,7 +257,7 @@
         MPbk2EditedContactObserver& aContactObserver,
         MPbk2ContactEditorStrategy& aEditorStrategy,
         MPbk2ContactEditorContactRelocator& aRelocator)
-    {	
+    {    
     CPbk2ContactEditorDlgImpl* self =
         new ( ELeave ) CPbk2ContactEditorDlgImpl(aParams, aContact,
             aFieldProperties, aContactObserver,
@@ -272,24 +273,24 @@
 // --------------------------------------------------------------------------
 //
 CPbk2ContactEditorDlgImpl* CPbk2ContactEditorDlgImpl::NewL(
-		TPbk2ContactEditorParams& aParams,
-		CPbk2PresentationContact& aContact,
-		CPbk2FieldPropertyArray& aFieldProperties,
-		MPbk2EditedContactObserver& aContactObserver,
-		MPbk2ContactEditorStrategy& aEditorStrategy,
-		MPbk2ContactEditorContactRelocator& aRelocator,
-		MPbk2ApplicationServices* aAppServices,
-		HBufC* aTitleText )
-	{
-	CPbk2ContactEditorDlgImpl* self =
-		new ( ELeave ) CPbk2ContactEditorDlgImpl(aParams, aContact,
-			aFieldProperties, aContactObserver,
-			aEditorStrategy, aRelocator, aAppServices, aTitleText );
-	CleanupStack::PushL(self);
-	self->ConstructL();
-	CleanupStack::Pop(self);
-	return self;
-	}
+        TPbk2ContactEditorParams& aParams,
+        CPbk2PresentationContact& aContact,
+        CPbk2FieldPropertyArray& aFieldProperties,
+        MPbk2EditedContactObserver& aContactObserver,
+        MPbk2ContactEditorStrategy& aEditorStrategy,
+        MPbk2ContactEditorContactRelocator& aRelocator,
+        MPbk2ApplicationServices* aAppServices,
+        HBufC* aTitleText )
+    {
+    CPbk2ContactEditorDlgImpl* self =
+        new ( ELeave ) CPbk2ContactEditorDlgImpl(aParams, aContact,
+            aFieldProperties, aContactObserver,
+            aEditorStrategy, aRelocator, aAppServices, aTitleText );
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop(self);
+    return self;
+    }
 
 // --------------------------------------------------------------------------
 // CPbk2ContactEditorDlgImpl::ConstructL
@@ -335,20 +336,20 @@
     // iContact's store becomes unavailable.
     
     /*
-	 * Use iAppServices if provided. This is to enable editor use outside from pbk2 context
-	 */
+     * Use iAppServices if provided. This is to enable editor use outside from pbk2 context
+     */
     if( iAppServices )
-    	{
-    	iAppServices->StoreObservationRegister().RegisterStoreEventsL( *this );
-    	iNameFormatter = &iAppServices->NameFormatter();
-    	}
+        {
+        iAppServices->StoreObservationRegister().RegisterStoreEventsL( *this );
+        iNameFormatter = &iAppServices->NameFormatter();
+        }
     else
-    	{
-    	Phonebook2::Pbk2AppUi()->ApplicationServices().
-			StoreObservationRegister().RegisterStoreEventsL( *this );
-    	iNameFormatter =
-    	        &Phonebook2::Pbk2AppUi()->ApplicationServices().NameFormatter();
-    	}
+        {
+        Phonebook2::Pbk2AppUi()->ApplicationServices().
+            StoreObservationRegister().RegisterStoreEventsL( *this );
+        iNameFormatter =
+                &Phonebook2::Pbk2AppUi()->ApplicationServices().NameFormatter();
+        }
 
    
     StoreTitlePaneTextL();
@@ -357,24 +358,24 @@
     iExtensionManager = CPbk2UIExtensionManager::InstanceL();
     
     /*
-	 * Use iAppServices if provided. This is to enable editor use outside from pbk2 context
-	 */
+     * Use iAppServices if provided. This is to enable editor use outside from pbk2 context
+     */
     CVPbkContactManager* manager = NULL;
     if( iAppServices )
-    	{
-    	manager = &iAppServices->ContactManager();
-    	}
+        {
+        manager = &iAppServices->ContactManager();
+        }
     else
-    	{
-    	manager = &Phonebook2::Pbk2AppUi()->ApplicationServices().ContactManager();
-    	}
+        {
+        manager = &Phonebook2::Pbk2AppUi()->ApplicationServices().ContactManager();
+        }
     
     iEditorExtension = iExtensionManager->FactoryL()->
         CreatePbk2ContactEditorExtensionL( *manager, iContact, *this );
 
     iFieldFactory = CPbk2ContactEditorFieldFactory::NewL(*this, *iEditorExtension);
     iUiFieldArray = CPbk2ContactEditorFieldArray::NewL(
-    *manager, iContact, *this, *iFieldFactory, iAppServices );	
+    *manager, iContact, *this, *iFieldFactory, iAppServices );    
     
     iUseState = EUseReady;
     }
@@ -781,7 +782,7 @@
     iEditorExtension->ModifyButtonGroupContainerL(ButtonGroupContainer());
 
     ConstructNaviPaneL();
-	UpdateTitleL();
+    UpdateTitleL();
     UpdateTitlePictureL();
     }
 
@@ -1158,6 +1159,37 @@
     iAddressView = NULL;
     iParams.iActiveView = TPbk2ContactEditorParams::EEditorView;
     UpdateControlsL();
+    
+    // The if-expression refers to the situation that need to
+    // delete editor dialog after address dialog exit completely,
+    // such as the store-unavailable situation    
+    if ( iDelayDelete )
+        {
+        iDelayDelete->Start( TCallBack( &DelayDlgDeleteCallBack, this ) );
+        }
+    }
+
+// --------------------------------------------------------------------------
+// CPbk2ContactEditorDlgImpl::DelayDlgDeleteCallBack
+// --------------------------------------------------------------------------
+//
+TInt CPbk2ContactEditorDlgImpl::DelayDlgDeleteCallBack( TAny* aCallBack )
+    {
+    static_cast<CPbk2ContactEditorDlgImpl*>( aCallBack )->DelayDlgDelete();
+    return EFalse;    
+    }
+
+// --------------------------------------------------------------------------
+// CPbk2ContactEditorDlgImpl::DelayDlgDelete
+// --------------------------------------------------------------------------
+//
+void CPbk2ContactEditorDlgImpl::DelayDlgDelete()
+    {
+    // Need to inform editor-observer that contact editing is
+    // aborted, at the same time, exit editor dialog directly 
+    // without saving the changes.
+    iContactObserver.ContactEditingAborted();
+    delete this;
     }
 
 // --------------------------------------------------------------------------
@@ -1934,7 +1966,7 @@
 //
 void CPbk2ContactEditorDlgImpl::CloseDialog()
 	{
-    // Ignor error and close editor without further user interaction
+    // Ignore error and close editor without further user interaction
     MVPbkContactObserver::TContactOpResult exitResult;
     exitResult.iExtension = NULL;
     exitResult.iStoreContact = NULL;
@@ -1957,7 +1989,7 @@
         }
       
     ContactEditorOperationCompleted(exitResult, exitParams);
-	}
+    }
 
 // --------------------------------------------------------------------------
 // CPbk2ContactEditorDlgImpl::ContactEditorOperationFailed
@@ -2329,24 +2361,22 @@
     {
     if ( &aContactStore == &iContact.ParentStore() )
         {
-        /*
-		 * Use iAppServices if provided. This is to enable editor use outside from pbk2 context
-		 */
+        // Use iAppServices if provided. This is to enable editor use outside from pbk2 context		
         const CPbk2StoreProperty* property = NULL;
         if( iAppServices )
-        	{
-        	property =
-					iAppServices->StoreProperties().FindProperty
-							( aContactStore.StoreProperties().Uri() );
-        	}
+            {
+            property =
+                    iAppServices->StoreProperties().FindProperty
+                            ( aContactStore.StoreProperties().Uri() );
+            }
         else
-        	{
-        	property =
-					Phonebook2::Pbk2AppUi()->ApplicationServices().
-						StoreProperties().FindProperty
-							( aContactStore.StoreProperties().Uri() );
-        	}
-        
+            {
+            property =
+                    Phonebook2::Pbk2AppUi()->ApplicationServices().
+                        StoreProperties().FindProperty
+                            ( aContactStore.StoreProperties().Uri() );
+            }
+
 
         TPtrC storeName;
         if ( property )
@@ -2358,11 +2388,26 @@
         // Cannot do anything about that
         TRAP_IGNORE( ShowStoreNotAvailableNoteL( storeName ) );
 
-        // Close editor if store which came unavailable is iContact's store
-        iContactObserver.ContactEditingAborted();
-        // TryExitL is not called because it would call OkToExitL
-        // which is not wanted
-        delete this;
+        // If the address dialog is opened, delete address dialog first,
+        // then after address dialog exit completely, delete the editor dialog
+        // via DelayDlgDeleteCallBack; if there isn't the address dialog, 
+        // delete editor dialog directly.         
+        if (iAddressView )
+            {
+            // Create the CIdle object to delete editor dialog later.
+            if ( !iDelayDelete )
+                {
+                iDelayDelete = CIdle::NewL( CActive::EPriorityStandard );
+                }
+            delete iAddressView;
+            }
+       else
+            {
+            // At the store unavailable situation, informs editor observer 
+            // that contact editing is aborted without saving the changes.
+            iContactObserver.ContactEditingAborted();
+            delete this;
+            }
         }
     }
 
@@ -2475,24 +2520,24 @@
         switch (iParams.iActiveView)
             {
             case TPbk2ContactEditorParams::EEditorAddressView:
-            	if( !iTitleText )
-            		{
-            		title = StringLoader::LoadL(R_QTN_PHOB_HEADER_ADDRESS);
-            		}
+                if( !iTitleText )
+                    {
+                    title = StringLoader::LoadL(R_QTN_PHOB_HEADER_ADDRESS);
+                    }
                 break;
             case TPbk2ContactEditorParams::EEditorAddressHomeView:
-            	if( !iTitleText )
-            		{
-            		title = StringLoader::LoadL(
-            				R_QTN_PHOB_HEADER_ADDRESS_HOME);
-            		}
+                if( !iTitleText )
+                    {
+                    title = StringLoader::LoadL(
+                            R_QTN_PHOB_HEADER_ADDRESS_HOME);
+                    }
                 break;
             case TPbk2ContactEditorParams::EEditorAddressOfficeView:
-            	if( !iTitleText )
-            		{
-            		title = StringLoader::LoadL(
-            				R_QTN_PHOB_HEADER_ADDRESS_WORK);
-            		}
+                if( !iTitleText )
+                    {
+                    title = StringLoader::LoadL(
+                            R_QTN_PHOB_HEADER_ADDRESS_WORK);
+                    }
                 break;
             case TPbk2ContactEditorParams::EEditorView:
                 {
@@ -2529,10 +2574,10 @@
                         }
                     }
                 if( !iTitleText )
-                	{
-                	title = iNameFormatter->GetContactTitleOrNullL(iStoreContact->Fields(),
-                			KEditorNameFormatFlags);
-                	}
+                    {
+                    title = iNameFormatter->GetContactTitleOrNullL(iStoreContact->Fields(),
+                            KEditorNameFormatFlags);
+                    }
                 break;
                 }
             default:
@@ -2541,20 +2586,20 @@
         
         // if custom title text is provided
         if( iTitleText )
-        	{
-        	iTitlePane->SetTextL( iTitleText->Des() );
-        	}
+            {
+            iTitlePane->SetTextL( iTitleText->Des() );
+            }
         else 
-        	{
-        	 if (title)
-				{
-				iTitlePane->SetText(title);
-				}
-			else
-				{
-				iTitlePane->SetTextL(iEditorStrategy.DefaultTitle());
-				}
-        	}
+            {
+             if (title)
+                {
+                iTitlePane->SetText(title);
+                }
+            else
+                {
+                iTitlePane->SetTextL(iEditorStrategy.DefaultTitle());
+                }
+            }
         }
     CEikStatusPane* statusPane = iAvkonAppUi->StatusPane();
     
@@ -2580,24 +2625,24 @@
         // Update picture in title pane
         
         /*
-		 * Use iAppServices if provided. This is to enable editor use outside from pbk2 context
-		 */
+         * Use iAppServices if provided. This is to enable editor use outside from pbk2 context
+         */
         CEikImage* image = NULL;
         if( iAppServices )
-        	{
-        	image =
-				Pbk2TitlePanePictureFactory::CreateTitlePanePictureLC
-					( &iContact.StoreContact(),
-							iAppServices->StoreProperties() );
-        	}
+            {
+            image =
+                Pbk2TitlePanePictureFactory::CreateTitlePanePictureLC
+                    ( &iContact.StoreContact(),
+                            iAppServices->StoreProperties() );
+            }
         else
-        	{
-        	image =
-				Pbk2TitlePanePictureFactory::CreateTitlePanePictureLC
-					( &iContact.StoreContact(),
-					  Phonebook2::Pbk2AppUi()->ApplicationServices().
-						StoreProperties() );
-        	}
+            {
+            image =
+                Pbk2TitlePanePictureFactory::CreateTitlePanePictureLC
+                    ( &iContact.StoreContact(),
+                      Phonebook2::Pbk2AppUi()->ApplicationServices().
+                        StoreProperties() );
+            }
         
         
         // ownership of the picture is transfered to title pane
@@ -2687,7 +2732,7 @@
 
         // Dialog is closed so there is nothing to do if
         // HandleCommandL leaves. 
-		TRAP_IGNORE(CEikonEnv::Static()->EikAppUi()->HandleCommandL(aCommandId)); 
+        TRAP_IGNORE(CEikonEnv::Static()->EikAppUi()->HandleCommandL(aCommandId)); 
         }
     }
 
@@ -2981,9 +3026,9 @@
                         CloseDialog();
                         }
                     else
-                    	{
-                    	iExitRecord.Clear( EExitOrdered );
-                    	}
+                        {
+                        iExitRecord.Clear( EExitOrdered );
+                        }
                     }
                 }
             }
@@ -3360,8 +3405,8 @@
 //    
 void CPbk2ContactEditorDlgImpl::CheckCurrentFieldTextL( 
         CPbk2ContactEditorArrayItem* aCurrentField,
-		const TKeyEvent& aKeyEvent, 
-		TEventCode aType )
+        const TKeyEvent& aKeyEvent, 
+        TEventCode aType )
     {
     MPbk2ContactEditorField* editorField = aCurrentField->ContactEditorField();
     if ( editorField )
--- a/phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorImageField.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorImageField.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -292,8 +292,16 @@
 // -----------------------------------------------------------------------------
 //
 TBool CPbk2ContactEditorImageField::ConsumesKeyEvent
-        ( const TKeyEvent& /*aKeyEvent*/, TEventCode /*aType*/ )
+        ( const TKeyEvent& aKeyEvent, TEventCode aType )
     {
+    
+    TKeyResponse keyResponse = iControl->OfferKeyEventL( aKeyEvent, aType );
+
+    if ( EKeyWasConsumed == keyResponse )
+        {
+        return ETrue;
+        }
+            
     return EFalse;
     }   
 
--- a/phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorNewContact.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorNewContact.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -224,14 +224,14 @@
         ( "CPbk2ContactEditorNewContact::HandleIdleDelete(0x%x)" ), this );
 
     iInputAbsorber->StopWait();
-    MPbk2ContactEditorEventObserver* observer = iObserver;
-    iObserver = NULL;
-    MVPbkContactObserver::TContactOpResult result;
-    // Disable warnings by nulling the data members
-    result.iStoreContact = NULL;
-    result.iExtension = NULL;
-    result.iOpCode = MVPbkContactObserver::EContactDelete;
-    observer->ContactEditorOperationCompleted( result, iEditorParams );
+    // Notify client asynchronously to let Delete Operation complete firstly and
+    // then the client will be notified to do the other things in the RunL() function.
+    iLatestResult.iExtension = NULL;
+    iLatestResult.iStoreContact = NULL;
+    iLatestResult.iOpCode = MVPbkContactObserver::EContactDelete;
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete(status, KErrNone);
+    SetActive();
     }
 
 // --------------------------------------------------------------------------
--- a/phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorReadonlyField.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorReadonlyField.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -25,6 +25,9 @@
 #include <Pbk2Commands.hrh>
 #include <MPbk2ContactEditorField2.h>
 #include <MPbk2ContactEditorUIField.h>
+#include <MVPbkStoreContactField.h>
+#include <MVPbkContactFieldData.h>
+
 
 /// Unnamed namespace for local definitions
 namespace
@@ -127,7 +130,7 @@
             case EKeyDelete:
             case EKeyBackspace:
                 {
-                if (iPbk2ContactEditorField)
+                if (iPbk2ContactEditorField && !iPbk2ContactEditorField->ContactField().FieldData().IsEmpty() )
                     {
                     MPbk2ContactEditorField2* tempContactEditorField =
                         reinterpret_cast<MPbk2ContactEditorField2*> (iPbk2ContactEditorField->ContactEditorFieldExtension(
--- a/phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorRingtoneField.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorRingtoneField.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -281,8 +281,15 @@
 // -----------------------------------------------------------------------------
 //
 TBool CPbk2ContactEditorRingtoneField::ConsumesKeyEvent
-        ( const TKeyEvent& /*aKeyEvent*/, TEventCode /*aType*/ )
+        ( const TKeyEvent& aKeyEvent, TEventCode aType )
     {
+    TKeyResponse keyResponse = iControl->OfferKeyEventL( aKeyEvent, aType );
+
+    if ( EKeyWasConsumed == keyResponse )
+        {
+        return ETrue;
+        }
+            
     return EFalse;
     }   
 
--- a/phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorUIAddressField.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/CPbk2ContactEditorUIAddressField.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -152,5 +152,22 @@
     iControl->SetTextL(&aText);
     }
 
+// -----------------------------------------------------------------------------
+// CPbk2ContactEditorUIAddressField::ConsumesKeyEvent
+// -----------------------------------------------------------------------------
+//
+TBool CPbk2ContactEditorUIAddressField::ConsumesKeyEvent
+        ( const TKeyEvent& aKeyEvent, TEventCode aType )
+    {
+    TKeyResponse keyResponse = iControl->OfferKeyEventL( aKeyEvent, aType );
+
+    if ( EKeyWasConsumed == keyResponse )
+        {
+        return ETrue;
+        }
+            
+    return EFalse;
+    }   
+
 
 // End of File  
--- a/phonebookui/Phonebook2/UIControls/src/CPbk2ContactViewListBox.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/CPbk2ContactViewListBox.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -41,6 +41,7 @@
 
 #include <aknappui.h>
 #include <aknViewAppUi.h>
+#include <aknlayoutscalable_avkon.cdl.h>
 
 // Debugging headers
 #include <Pbk2Debug.h>
@@ -59,6 +60,7 @@
 // LOCAL FUNCTIONS
 
 _LIT( KTabChar, "\t" );
+const TInt KCheckboxMargin = 1; // Checkbox margin pixels
 
 /**
  * Returns icon array from given list box.
@@ -109,7 +111,8 @@
                 iContainer(aContainer), 
                 iChangedIndexes( 1 ), // allocation granularity
                 iUiExtension( aUiExtension ),
-                iSearchFilter( aSearchFilter )
+                iSearchFilter( aSearchFilter ),
+                iMarkingModeOn( EFalse )
     {
     }
 
@@ -442,9 +445,28 @@
 TBool CPbk2ContactViewListBox::ClipFromBeginning
         ( TDes& aBuffer, TInt aItemIndex, TInt aSubCellNumber )
     {
-    return AknTextUtils::ClipToFit( aBuffer,
-        AknTextUtils::EClipFromBeginning, this,  aItemIndex,
-        aSubCellNumber );
+    CColumnListBoxData *data = ItemDrawer()->ColumnData();
+    const CFont *font =
+        data->Font(ItemDrawer()->Properties(aItemIndex), aSubCellNumber);
+    // The width of the subcell displaying the characters.
+    TInt cellWidth = data->ColumnWidthPixel(aSubCellNumber);
+    // The margin of the subcell.
+    TMargins margin = data->ColumnMargins(aSubCellNumber);
+    // The valid width width displaying the characters.
+    TInt width = cellWidth - margin.iLeft - margin.iRight;
+    // If Marking mode is active, recalculate the valid width displaying characters.
+    // contact entry of name list view in marking mode
+    //
+    // |checkbox|Icon|name  |
+    // |        |    |number|
+    if( iMarkingModeOn )
+        {
+        RecalcWidthInMarkingMode(width, *font, aBuffer[0]);
+        }
+    TInt clipGap = data->ColumnTextClipGap(aSubCellNumber);
+    
+    return AknTextUtils::ClipToFit(
+        aBuffer, *font, width, AknTextUtils::EClipFromBeginning, width + clipGap);
     }
 
 // --------------------------------------------------------------------------
@@ -531,9 +553,9 @@
         }
     // Wrap the original model.
     iListboxModelDecorator = DoCreateDecoratorL( 
-    		*IconArray( *this ),
-			iResourceData.iEmptyIconId,
-			iResourceData.iDefaultIconId );
+            *IconArray( *this ),
+            iResourceData.iEmptyIconId,
+            iResourceData.iDefaultIconId );
     
     
     iListboxModelDecorator->SetDecoratedModel( *iModel );
@@ -557,15 +579,15 @@
 // --------------------------------------------------------------------------
 //
 CPbk2ListboxModelCmdDecorator* CPbk2ContactViewListBox::DoCreateDecoratorL( 
-        		const CPbk2IconArray& aIconArray,
-        		TPbk2IconId aEmptyIconId,
-        		TPbk2IconId aDefaultIconId )
-	{
-	return CPbk2ListboxModelCmdDecorator::NewL(
-				aIconArray,
-				aEmptyIconId,
-				aDefaultIconId );
-	}
+                const CPbk2IconArray& aIconArray,
+                TPbk2IconId aEmptyIconId,
+                TPbk2IconId aDefaultIconId )
+    {
+    return CPbk2ListboxModelCmdDecorator::NewL(
+                aIconArray,
+                aEmptyIconId,
+                aDefaultIconId );
+    }
 
 
 // --------------------------------------------------------------------------
@@ -622,7 +644,7 @@
 //
 void CPbk2ContactViewListBox::HandleGainingForeground()
     {
-	DrawDeferred();
+    DrawDeferred();
     }
 
 // --------------------------------------------------------------------------
@@ -704,7 +726,7 @@
         textLayout.LayoutText(layout.Rect(), AknLayoutScalable_Apps::popup_navstr_preview_pane_t1(0).LayoutLine());
 
         TPtrC desc(Model()->ItemTextArray()->MdcaPoint(View()->TopItemIndex()));
-		
+        
         //Add "if-clause" to avaid the error that argument of Mid() out of range.
         TInt index = desc.Find( KTabChar );
         if ( index != KErrNotFound && index < desc.Length()-1 )
@@ -720,4 +742,56 @@
             }
         }
     }
+
+// --------------------------------------------------------------------------
+// CPbk2ContactViewListBox::RecalcWidthInMarkingMode
+// Recalculate the width of space displaying the third column of the schema
+// below when Marking Mode is active.
+// contact entry of name list view in marking mode
+// The schema:
+// |checkbox|Icon|name  |
+// |        |    |number|
+// --------------------------------------------------------------------------
+//
+void CPbk2ContactViewListBox::RecalcWidthInMarkingMode(
+                              TInt& aWidth,
+                              const CFont& aFont,
+                              TChar aChar )
+    {
+    if( aWidth > 0 )
+        {
+        aWidth -= KCheckboxMargin;
+        // Get the coordinate for the right margin of the checkbox.
+        TInt checkBoxRight = AknLayoutScalable_Avkon::list_single_graphic_pane_t1( 0 ).r();
+        // Get the coordinate for the left margin of the checkbox.
+        TInt checkBoxLeft = AknLayoutScalable_Avkon::list_single_graphic_pane_t1( 0 ).l();
+        // The width to display one char.
+        TInt charWidth = aFont.CharWidthInPixels(aChar);
+        TInt checkBoxWidth = checkBoxRight - checkBoxLeft;
+        if( 0 > checkBoxWidth )
+            {
+            checkBoxWidth *= -1; // To make sure the value is positive.
+            }
+        if( charWidth > 0 && checkBoxWidth > 0 )
+            {
+            // The width of the characters which should be dropped, when marking
+            // mode is active.
+            TInt width;
+            if( 0 == checkBoxWidth%charWidth )
+                {
+                width = checkBoxWidth;
+                }
+            else
+                {
+                // The width should be divisible by charWidth.
+                width = ( checkBoxWidth/charWidth + 1 ) * charWidth;
+                }
+            // When marking mode is on,
+            // the width should minus the part of checkbox in the front of
+            // a listbox item.
+            aWidth -= width;
+            }
+        }
+    }
+
 // End of File
--- a/phonebookui/Phonebook2/UIControls/src/CPbk2FetchDlg.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/CPbk2FetchDlg.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -149,7 +149,8 @@
 inline CPbk2FetchDlg::CPbk2FetchDlg
         ( TParams aParams, MPbk2FetchDlgObserver& aObserver ) :
             iParams( aParams ),
-            iObserver( aObserver )
+            iObserver( aObserver ),
+            iSelectPermitted( ETrue )
     {
     }
 
@@ -258,6 +259,7 @@
         ( aContactLink, Phonebook2::Pbk2AppUi()->ApplicationServices().
             ContactManager().ContactStoresL() );
 
+    // Append the selected contact to results.
     if ( linkArray->Count() > 0 )
         {
         const MVPbkContactLink& link = linkArray->At( KFirstElement );
@@ -268,6 +270,28 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2FetchDlg::AcceptDelayedFetchL
+// --------------------------------------------------------------------------
+//
+EXPORT_C void CPbk2FetchDlg::DenyDelayedFetchL
+        ( const TDesC8& aContactLink )
+    {
+    CVPbkContactLinkArray* linkArray = CVPbkContactLinkArray::NewLC
+        ( aContactLink, Phonebook2::Pbk2AppUi()->ApplicationServices().
+            ContactManager().ContactStoresL() );
+
+    // Unmark the selected contact
+    if ( linkArray->Count() > 0 )
+        {
+        const MVPbkContactLink& link = linkArray->At( KFirstElement );
+        iResults->DenyAppendDelayedL( link );
+        iPages->SelectContactL( link, EFalse );
+        }
+
+    CleanupStack::PopAndDestroy(); // linkArray
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2FetchDlg::ExecuteLD
 // --------------------------------------------------------------------------
 //
@@ -388,6 +412,12 @@
             }
         }
 
+    // Only multiple fetch needs to wait buffered operations finished
+    if ( !canceled && ( iParams.iFlags & EFetchMultiple ) )
+        {
+        iResults->WaitOperationsCompleteL();
+        }
+    
     // Notify observer
     if ( canceled )
         {
@@ -435,6 +465,11 @@
         // Reset results
         iResults->ResetAndDestroy();
         }
+    else
+        {
+        // Permit selection again
+        iSelectPermitted = ETrue;
+        }
     
     iExitRecord.Set( EExitOrdered );    // exit is now ordered and
                                         // when client later requests
@@ -525,6 +560,12 @@
         }
     else
         {
+        // EKeyApplicationF means left softkey is pressed
+        if ( EKeyApplicationF == aKeyEvent.iCode && 
+                ( iParams.iFlags & EFetchMultiple ) )
+            {
+            iSelectPermitted = EFalse;
+            }
         if( !Phonebook2::Pbk2AppUi()->KeyEventHandler().Pbk2ProcessKeyEventL( aKeyEvent, aType ) )
             {
             
@@ -788,6 +829,14 @@
         	}
         }
     }
+// --------------------------------------------------------------------------
+// CPbk2FetchDlg::IsSelectPermitted
+// --------------------------------------------------------------------------
+//
+TBool CPbk2FetchDlg::IsSelectPermitted()
+    {
+    return iSelectPermitted;
+    }
 
 // --------------------------------------------------------------------------
 // CPbk2FetchDlg::HandleControlEventL
--- a/phonebookui/Phonebook2/UIControls/src/CPbk2FetchResults.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/CPbk2FetchResults.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -38,6 +38,7 @@
 
 // System includes
 #include <coemain.h>
+#include <akninputblock.h>
 
 // Debugging headers
 #include <Pbk2Debug.h>
@@ -56,7 +57,9 @@
                 iFetchDlg( aFetchDlg ),
                 iPages( aPages ),
                 iObserver( aObserver ),
-                iResultsObserver( aResultsObserver )
+                iResultsObserver( aResultsObserver ),
+                iWaitingForDelayedAppend( EFalse ),
+                iInputBlock( NULL )
     {
     }
 
@@ -86,6 +89,8 @@
         
         delete iOperationQueue;
         }
+    
+    delete iWaitForAllOperationComplete;
     }
 
 // --------------------------------------------------------------------------
@@ -107,6 +112,8 @@
         }
     
     iOperationQueue = new (ELeave) CArrayFixFlat<CFRConatactOperation*>(4);
+    
+    iWaitForAllOperationComplete = new (ELeave) CActiveSchedulerWait();
     }
 
 // --------------------------------------------------------------------------
@@ -133,10 +140,17 @@
 // --------------------------------------------------------------------------
 //
 void CPbk2FetchResults::AppendL( const MVPbkContactLink& aLink )
-    {
-    CFRConatactOperation* newAppendOperation = CFRConatactOperation::NewL( aLink, CFRConatactOperation::EAppendContact );
-    AppendContactOperationL(newAppendOperation);
-    ProcessNextContactOperationL();
+    { 
+    if ( iFetchDlg.IsSelectPermitted() )
+        {
+        CFRConatactOperation* newAppendOperation = CFRConatactOperation::NewL( aLink, CFRConatactOperation::EAppendContact );
+        AppendContactOperationL(newAppendOperation);
+        ProcessNextContactOperationL();
+        }
+    else
+        {
+        iPages.SelectContactL( aLink, EFalse );
+        }
     }
 
 // --------------------------------------------------------------------------
@@ -145,8 +159,24 @@
 //
 void CPbk2FetchResults::AppendDelayedL( const MVPbkContactLink& aLink )
     {
+    // Add the feedback contact's operation to the head of the queue
+    // in order to ensure that the checked contact's operation to be
+    // handled firstly when phonebook receives the client feedback.
     CFRConatactOperation* newAppendOperation = CFRConatactOperation::NewL( aLink, CFRConatactOperation::EAppendContactDelayed );
-    AppendContactOperationL(newAppendOperation);
+    iOperationQueue->InsertL( 0, newAppendOperation ); 
+    // Waiting is over.
+    iWaitingForDelayedAppend = EFalse;
+    ProcessNextContactOperationL();
+    }
+
+// --------------------------------------------------------------------------
+// CPbk2FetchResults::DenyAppendDelayedL
+// --------------------------------------------------------------------------
+//
+void CPbk2FetchResults::DenyAppendDelayedL( const MVPbkContactLink& aLink )
+    {
+    // Waiting is over, process next contact operation
+    iWaitingForDelayedAppend = EFalse;
     ProcessNextContactOperationL();
     }
 
@@ -176,6 +206,21 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2FetchResults::WaitOperationsCompleteL
+// --------------------------------------------------------------------------
+//
+void CPbk2FetchResults::WaitOperationsCompleteL()
+    {
+    if ( iWaitingForDelayedAppend || iOperationQueue->Count()>0 )
+        {
+        iInputBlock = CAknInputBlock::NewLC();
+        CleanupStack::Pop( iInputBlock );
+        
+        iWaitForAllOperationComplete->Start();
+        }
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2FetchResults::Count
 // --------------------------------------------------------------------------
 //
@@ -328,6 +373,13 @@
         {
         // Observer needs to asked
         accept = iObserver.AcceptFetchSelectionL( count, *link );
+        // Determine whether accept query is needed
+        if ( MPbk2FetchDlgObserver::EFetchDelayed == accept )
+            {
+            // Start to wait client feedback, block the operation queue,
+            // process next operation until receive client feedback.
+            iWaitingForDelayedAppend = ETrue;
+            }
         }
 
     if ( accept == MPbk2FetchDlgObserver::EFetchNo )
@@ -489,8 +541,6 @@
     // Remove executed operation from queue
     RemoveCurrentContactOperation();
     
-    // Initialize next operation from queue
-    ProcessNextContactOperationL();   
     
     /**********************************************************************/
     /**************! Dont use class members after SWITCH !*****************/
@@ -505,17 +555,26 @@
         case CFRConatactOperation::EAppendContact:
             {
             DoAppendContactL( *aContact, EFalse );
+            // Check whether next operation can be processed
+            // after sending check request to client.
+            ProcessNextContactOperationL();
             break;
             }
             
         case CFRConatactOperation::EAppendContactDelayed:
             {
+            // Process new contact opretation before appending 
+            // the delayed contact to results. It can save time.
+            ProcessNextContactOperationL();   
             DoAppendContactL( *aContact, ETrue );
             break;
             }
         
         case CFRConatactOperation::ERemoveContact:
             {
+            // Process new contact opretation before removing contact 
+            // from results. It can save time.
+            ProcessNextContactOperationL();   
             DoRemoveContactL( *aContact );
             break;
             }
@@ -530,7 +589,7 @@
 //
 void CPbk2FetchResults::ProcessNextContactOperationL()
     {
-    if( !iRetrieveOperation )
+    if( !iRetrieveOperation && !iWaitingForDelayedAppend )
         {        
         // No operation is executing -> process next one
         
@@ -538,13 +597,23 @@
             {
             // Start asynchronous contact retrieve operation, which completes
             // in CPbk2FetchResults::HandleContactOperationCompleteL.
-            iRetrieveOperation =  iContactManager.RetrieveContactL( *( GetCurrentContactOperation()->GetContactLink() ),
-                                                                   *this );
+			iRetrieveOperation =  iContactManager.RetrieveContactL( 
+                    *( GetCurrentContactOperation()->GetContactLink() ),
+                    *this );
             }
         else
             {
-            // Empty operation queue -> do nothing
-            PBK2_DEBUG_PRINT(PBK2_DEBUG_STRING( "CPbk2FetchResults::ProcessNextContactOperationL emtpy queue" ));
+            if ( !iWaitingForDelayedAppend )
+                {
+                // Every seleced contacts' operation finishes,
+                // stop the scheduler waiting for every operation.
+                if (iWaitForAllOperationComplete->IsStarted())
+                    iWaitForAllOperationComplete->AsyncStop();
+                
+                // Stop blocking input 
+                delete iInputBlock;
+                iInputBlock = NULL;
+                }
             }
         }
     else
--- a/phonebookui/Phonebook2/UIControls/src/CPbk2MergeConflictsDlg.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/CPbk2MergeConflictsDlg.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -212,7 +212,7 @@
     {     
     if( AknLayoutUtils::PenEnabled() )  
         {
-        if ( aEventType == EEventItemSingleClicked )
+        if ( aEventType == EEventItemSingleClicked || aEventType == EEventEnterKeyPressed)
             {
             SwitchRadioButtonL();
             }
--- a/phonebookui/Phonebook2/UIControls/src/CPbk2NamesListControl.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/CPbk2NamesListControl.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -331,7 +331,7 @@
        
        /**
         * Call this function to skip the showing of blocking progress note.
-		* When done MassUpdateSkipProgressNote( EFalse ) must be called to reset.
+        * When done MassUpdateSkipProgressNote( EFalse ) must be called to reset.
         */
       void MassUpdateSkipProgressNote( TBool aSkip );       
 
@@ -347,14 +347,14 @@
         static TInt HandleMassUpdateTimerCallBack(TAny* aAny);
 
     private:
-		CEikListBox& iListBox;
+        CEikListBox& iListBox;
         TBool iHandleMassUpdateDetected;
         TTime iHandleMassUpdateFirst;
         TTime iHandleMassUpdatePrev;
         TInt  iHandleMassUpdateCount;
         TBool iHandleMassUpdateSkipDialog;        
         CPeriodic* iHandleMassUpdateTimer;
-		CAknWaitDialog*  iHandleMassUpdateDialog;
+        CAknWaitDialog*  iHandleMassUpdateDialog;
     };
 
 // --------------------------------------------------------------------------
@@ -714,8 +714,8 @@
 //
 TBool CPbk2HandleMassUpdate::MassUpdateDetected()
     {
-	return iHandleMassUpdateDetected;
-	}
+    return iHandleMassUpdateDetected;
+    }
 
 // --------------------------------------------------------------------------
 // CPbk2HandleMassUpdate::MassUpdateSkipProgressNote
@@ -877,7 +877,8 @@
                 iNameFormatter( aNameFormatter ),
                 iStoreProperties( aStoreProperties ),
                 iAllowPointerEvents( ETrue ),
-                iOpeningCca( EFalse )
+                iOpeningCca( EFalse ),
+                iMarkingModeOn( EFalse )
     {
     }
 
@@ -935,7 +936,7 @@
         }
     iObservers.Reset();
     iCommandItems.ResetAndDestroy();
-	delete iCheckMassUpdate;
+    delete iCheckMassUpdate;
     delete iListBoxSelectionObserver;
     delete iStateFactory;
     delete iListBox;
@@ -1111,6 +1112,9 @@
     iListBox->SetObserver( this );
     iListBox->SetScrollEventObserver( this );
     iListBox->SetListBoxObserver(this);
+    
+    iListBox->SetMarkingModeObserver( this );
+    
     iUiExtension->SetContactUiControlUpdate( this );
     // set command item updater
     TAny* ext = iUiExtension->ContactUiControlExtensionExtension(
@@ -1201,9 +1205,6 @@
     PBK2_DEBUG_PRINT(PBK2_DEBUG_STRING("CPbk2NamesListControl::Reset(0x%x) - IN"),
         this );
 
-    // Unmark all contacts and reset the toolbar so that the Call button
-    // won't be dimmed
-    TRAP_IGNORE( ProcessCommandL( EAknUnmarkAll ) );
     // Reset find box
     TRAP_IGNORE( ResetFindL() );
     // Destroy all the filtered views from the stack
@@ -1220,6 +1221,9 @@
     TRAP_IGNORE( iCurrentState->SetFocusedContactIndexL( firstContactIndex ) );
     //scroll listbox into beginning (ignore focus that may be below promotion items)
     iListBox->SetTopItemIndex(firstContactIndex);
+    
+    //cancel the marking mode
+    iListBox->SetMarkingMode( EFalse );
 
     // Switch to the background state. This enables the next state to avtivate fully (ActivateStateL()) once phonebook
     // comes from the background.
@@ -1487,7 +1491,7 @@
     {
     if( !iAllowPointerEvents )
         {
-		//Passing event to listbox needed even if iCurrentState would be skipped (fix for ou1cimx1#316139)
+        //Passing event to listbox needed even if iCurrentState would be skipped (fix for ou1cimx1#316139)
         iListBox->HandlePointerEventL( aPointerEvent ); 
         return;
         }
@@ -1685,7 +1689,7 @@
 void CPbk2NamesListControl::ClearMarks()
     {
     iCurrentState->ClearMarks();
-	ClearMarkedContactsInfo();
+    ClearMarkedContactsInfo();
     }
 
 // --------------------------------------------------------------------------
@@ -2089,7 +2093,7 @@
 // --------------------------------------------------------------------------
 //
 void CPbk2NamesListControl::FilteredContactRemovedFromView(
-		MVPbkContactViewBase& /*aView*/ )
+        MVPbkContactViewBase& /*aView*/ )
     {    
     DrawDeferred();
     }
@@ -2247,11 +2251,11 @@
 //
 void CPbk2NamesListControl::DoHandleContactAdditionL( TInt aIndex )
     {
-	//Prevent messing with focus with always-on when Phonebook hidden in
-	//reseted state. Otherwise background-added contacts will change focus.
-	//This would cause Phonebook not to look like freshly started when opened again.
-	//And also make sure foreground-added contact will show the new contact
-	//even though the focus is not seen.
+    //Prevent messing with focus with always-on when Phonebook hidden in
+    //reseted state. Otherwise background-added contacts will change focus.
+    //This would cause Phonebook not to look like freshly started when opened again.
+    //And also make sure foreground-added contact will show the new contact
+    //even though the focus is not seen.
     if( (static_cast<CPbk2AppUi*>(
             CEikonEnv::Static()->AppUi()))->IsForeground() )
         {
@@ -2404,7 +2408,7 @@
     TRAPD( res,
         {
         // This will reset back to base view, however retain original view
-		//when opening CCA
+        //when opening CCA
         if( !iOpeningCca ) 
             {
             iCurrentState->ResetFindL(); 
@@ -2428,8 +2432,11 @@
             }
         else
             {              
-            Reset();
-            }	
+            if( !iMarkingModeOn )
+                {
+                Reset();
+                }
+            }
         }
 
     // Do not handle contact addition here (DoHandleContactAdditionL),
@@ -2542,9 +2549,29 @@
     TRAP_IGNORE(iCurrentState->HandleControlEventL( aSearchField, MCoeControlObserver::EEventStateChanged, ETrue));
     }
 
+
+// -----------------------------------------------------------------------------
+// CPbk2NamesListControl::MarkingModeStatusChanged
+// -----------------------------------------------------------------------------
+//
+void CPbk2NamesListControl::MarkingModeStatusChanged( TBool /*aActivated*/ )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CPbk2NamesListControl::ExitMarkingMode
+// Called by avkon, if the return value is ETrue, 
+// the Marking mode will be canceled after any operation, 
+// otherwise the Marking mode keep active.
+// -----------------------------------------------------------------------------
+//
+TBool CPbk2NamesListControl::ExitMarkingMode() const
+    {
+    return ETrue;
+    }
+    
 // --------------------------------------------------------------------------
 // CPbk2NamesListControl::HandleForegroundEventL
-//
 // --------------------------------------------------------------------------
 //
 void CPbk2NamesListControl::HandleForegroundEventL(TBool aForeground)
@@ -2628,9 +2655,9 @@
 // ---------------------------------------------------------------------------
 //
 EXPORT_C void CPbk2NamesListControl::SetOpeningCca( TBool aIsOpening )
-	{
-	iOpeningCca = aIsOpening;
-	}
+    {
+    iOpeningCca = aIsOpening;
+    }
 
 // ---------------------------------------------------------------------------
 // CPbk2NamesListControlBgTask::CPbk2NamesListControlBgTask
--- a/phonebookui/Phonebook2/UIControls/src/CPbk2NamesListEmptyState.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/CPbk2NamesListEmptyState.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -41,6 +41,10 @@
 // Debugging headers
 #include <Pbk2Debug.h>
 
+#include <aknnavi.h>
+#include <aknnavide.h> 
+#include <aknnavilabel.h>
+
 
 /// Unnamed namespace for local definitions
 namespace {
@@ -124,12 +128,35 @@
 //
 void CPbk2NamesListEmptyState::ActivateStateL()
     {
-    AllowCommandsToShowThemselves( ETrue );  
-	
-	// hide findbox since there is no contact
+    AllowCommandsToShowThemselves( ETrue );
+    CPbk2NamesListControl& namesListControl = 
+        reinterpret_cast<CPbk2NamesListControl&>(CoeControl());
+    if( namesListControl.GetMarkingMode() )
+        {
+        // If NamesListEmptyState and Marking mode are both active,
+        // the Marking mode should be canceled. 
+        iListBox.SetMarkingMode(EFalse);
+        CEikonEnv* eikonEnv = CEikonEnv::Static();
+        if ( eikonEnv && eikonEnv->AppUiFactory() )
+            {
+            CEikStatusPane* statusPane = eikonEnv->AppUiFactory()->StatusPane();
+            if ( statusPane )
+                {
+
+                CAknNavigationControlContainer* naviPane =
+                        (CAknNavigationControlContainer *)statusPane->ControlL(
+                                TUid::Uid(EEikStatusPaneUidNavi));
+                CAknNavigationDecorator* decorator = naviPane->Top();
+                        naviPane->Pop( decorator );
+                naviPane->DrawDeferred();
+                }
+            }
+        }
+
+    // hide findbox since there is no contact
     if ( iFindBox && iFindBox->IsVisible() )
         {
-        iFindBox->MakeVisible( EFalse );                
+        iFindBox->MakeVisible( EFalse );
         }
 
     }
@@ -140,8 +167,8 @@
 //
 void CPbk2NamesListEmptyState::DeactivateState()
     {
-    AllowCommandsToShowThemselves( EFalse );  	
-	
+    AllowCommandsToShowThemselves( EFalse );
+
     if ( iFindBox && !iFindBox->IsFocused() )
         {
         iFindBox->SetFocus( ETrue );
@@ -297,7 +324,7 @@
 //
 void CPbk2NamesListEmptyState::HandleListboxEventL
         (TInt aEvent, TInt aListboxIndex,
-		TBool /*aMantainFocus*/) 
+        TBool /*aMantainFocus*/) 
     {
     iListBox.HandleEventL( aEvent, aListboxIndex );
     iParent.DrawDeferred();
@@ -349,9 +376,9 @@
     // The listbox can also have command items.
     TInt result = iListBox.NumberOfItems() - CommandItemCount();
     if ( result < 0 )
-    	{
-    	result = KNumberOfContacts; // No contacts 
-    	}
+        {
+        result = KNumberOfContacts; // No contacts 
+        }
     return result;
     }
 
@@ -491,53 +518,53 @@
 MVPbkContactLinkArray*
         CPbk2NamesListEmptyState::SelectedContactsOrFocusedContactL() const
     {
-	CVPbkContactLinkArray* array = NULL;
-	// my card is showing on empty list, check if the wanted contact is it
-	TInt currentItem = iListBox.CurrentItemIndex();
-	// if focused index is command item
-	if( currentItem < CommandItemCount() )
-		{
-		// check if the command is my card ( this search is copied from CommandItemAt - function to avoid const cast)
-		// Some of the commands might be disabled. Skip those.
-		TInt enabledCount = 0;
-		TInt indexOfResult = KErrNotFound;
-		for ( TInt n = 0; n < iCommandItems.Count() && indexOfResult == KErrNotFound; ++n )
-			{
-			if ( iCommandItems[ n ]->IsEnabled() )
-				{
-				enabledCount++;
-				if ( enabledCount-1 == currentItem )
-					{
-					indexOfResult = n;
-					}
-				}
-			}
-		MPbk2UiControlCmdItem* item = iCommandItems[ indexOfResult ];
-		// check if the command item was a my card
-		if( item->CommandId() == EPbk2CmdOpenMyCard )
-			{
-			// get extension point and my card link
-			TAny* object = item->ControlCmdItemExtension( TUid::Uid( KPbk2ControlCmdItemExtensionUID ) );
-			if(  object )
-				{
-				MPbk2DoubleListboxCmdItemExtension* extension = 
-						static_cast<MPbk2DoubleListboxCmdItemExtension*>( object );
-				// if extension exists
-				if( extension )
-					{
-					const MVPbkContactLink* link = extension->Link();
-					// if link exists, add it to the array
-					if( link )
-						{
-						array = CVPbkContactLinkArray::NewLC();
-						array->AppendL( link->CloneLC() );
-						CleanupStack::Pop( 2 );	// array, link
-						}
-					}
-				}
-			}
-		}
-	return array;
+    CVPbkContactLinkArray* array = NULL;
+    // my card is showing on empty list, check if the wanted contact is it
+    TInt currentItem = iListBox.CurrentItemIndex();
+    // if focused index is command item
+    if( currentItem < CommandItemCount() )
+        {
+        // check if the command is my card ( this search is copied from CommandItemAt - function to avoid const cast)
+        // Some of the commands might be disabled. Skip those.
+        TInt enabledCount = 0;
+        TInt indexOfResult = KErrNotFound;
+        for ( TInt n = 0; n < iCommandItems.Count() && indexOfResult == KErrNotFound; ++n )
+            {
+            if ( iCommandItems[ n ]->IsEnabled() )
+                {
+                enabledCount++;
+                if ( enabledCount-1 == currentItem )
+                    {
+                    indexOfResult = n;
+                    }
+                }
+            }
+        MPbk2UiControlCmdItem* item = iCommandItems[ indexOfResult ];
+        // check if the command item was a my card
+        if( item->CommandId() == EPbk2CmdOpenMyCard )
+            {
+            // get extension point and my card link
+            TAny* object = item->ControlCmdItemExtension( TUid::Uid( KPbk2ControlCmdItemExtensionUID ) );
+            if(  object )
+                {
+                MPbk2DoubleListboxCmdItemExtension* extension = 
+                        static_cast<MPbk2DoubleListboxCmdItemExtension*>( object );
+                // if extension exists
+                if( extension )
+                    {
+                    const MVPbkContactLink* link = extension->Link();
+                    // if link exists, add it to the array
+                    if( link )
+                        {
+                        array = CVPbkContactLinkArray::NewLC();
+                        array->AppendL( link->CloneLC() );
+                        CleanupStack::Pop( 2 );    // array, link
+                        }
+                    }
+                }
+            }
+        }
+    return array;
     }
 
 // --------------------------------------------------------------------------
@@ -607,17 +634,17 @@
 // --------------------------------------------------------------------------
 //
 TInt CPbk2NamesListEmptyState::CommandItemCount() const
-	{
+    {
     // Some of the commands might be disabled. Don't count those.
-	TInt enabledCommandCount = 0;
-	for ( TInt n = 0; n < iCommandItems.Count(); ++n ) 
-		{
-		if ( iCommandItems[ n ]->IsEnabled() )
-			{
-			enabledCommandCount++;
-			}
-		}
-	return enabledCommandCount;
+    TInt enabledCommandCount = 0;
+    for ( TInt n = 0; n < iCommandItems.Count(); ++n ) 
+        {
+        if ( iCommandItems[ n ]->IsEnabled() )
+            {
+            enabledCommandCount++;
+            }
+        }
+    return enabledCommandCount;
     }
 
 // --------------------------------------------------------------------------
@@ -626,24 +653,24 @@
 //
 const MPbk2UiControlCmdItem&
 CPbk2NamesListEmptyState::CommandItemAt( TInt aIndex ) const
-	{
+    {
     // Some of the commands might be disabled. Skip those.
-	TInt enabledCount = 0;
-	TInt indexOfResult = KErrNotFound;
-	for ( TInt n = 0; n < iCommandItems.Count()&& indexOfResult == KErrNotFound; ++n ) 
-	
-		{
-		if ( iCommandItems[ n ]->IsEnabled() )
-			{
-			enabledCount++;
-			if ( enabledCount-1 == aIndex )
-				{
-				indexOfResult = n;
-				}
-			}
-		}
-	return *iCommandItems[ indexOfResult ];
-	}
+    TInt enabledCount = 0;
+    TInt indexOfResult = KErrNotFound;
+    for ( TInt n = 0; n < iCommandItems.Count()&& indexOfResult == KErrNotFound; ++n ) 
+    
+        {
+        if ( iCommandItems[ n ]->IsEnabled() )
+            {
+            enabledCount++;
+            if ( enabledCount-1 == aIndex )
+                {
+                indexOfResult = n;
+                }
+            }
+        }
+    return *iCommandItems[ indexOfResult ];
+    }
 
 // --------------------------------------------------------------------------
 // CPbk2NamesListEmptyState::FocusedCommandItem
@@ -651,9 +678,9 @@
 //
 const MPbk2UiControlCmdItem*
 CPbk2NamesListEmptyState::FocusedCommandItem() const
-	{
-	const MPbk2UiControlCmdItem* cmdItem = NULL;
-	// Is the focus on a command item:
+    {
+    const MPbk2UiControlCmdItem* cmdItem = NULL;
+    // Is the focus on a command item:
     TInt focusListIndex = iListBox.CurrentItemIndex();
     const TInt commandItemCount = CommandItemCount();
     if ( focusListIndex != KErrNotFound && focusListIndex < commandItemCount )
@@ -661,7 +688,7 @@
         // Yes it's a command item.
         cmdItem = &CommandItemAt(focusListIndex); 
         }
-	return cmdItem;
+    return cmdItem;
     }
 
 // --------------------------------------------------------------------------
@@ -669,7 +696,7 @@
 // --------------------------------------------------------------------------
 //
 void CPbk2NamesListEmptyState::DeleteCommandItemL( TInt /*aIndex*/ )
-	{
+    {
     // ownership & management of iCommandItems is wasted in names list
     // control. Do nothing here
     }
@@ -682,7 +709,7 @@
     {
     // ownership & management of iCommandItems is wasted in names list
     // control. Do nothing here
-	}	
+    }    
 
 // --------------------------------------------------------------------------
 // CPbk2NamesListEmptyState::DynInitMenuPaneL
@@ -698,13 +725,9 @@
     TInt pos; // Stores the position of the searched menu item.
             // This position is not needed or used anywhere
     
-    if (aMenuPane->MenuItemExists(EAknUnmarkAll, pos))
+    if ( aMenuPane->MenuItemExists ( EAknCmdMarkingModeEnter, pos ) )
         {
-        aMenuPane->SetItemDimmed(EAknUnmarkAll, ETrue);
-        }
-    if (aMenuPane->MenuItemExists(EAknMarkAll, pos))
-        {
-        aMenuPane->SetItemDimmed(EAknMarkAll, ETrue);
+        aMenuPane->SetItemDimmed( EAknCmdMarkingModeEnter, ETrue );
         }
     }
 
@@ -944,9 +967,9 @@
         // ownership not transferred
         iListBox.SetListCommands( &iCommandItems );
         SubscribeCmdItemsVisibility();        
-        UpdateCommandEnabled( EPbk2CmdRcl, ETrue ); 			
+        UpdateCommandEnabled( EPbk2CmdRcl, ETrue );             
         UpdateCommandEnabled( EPbk2CmdAddFavourites, EFalse ); 
-		//MyCard is stored separately and may also contain data         
+        //MyCard is stored separately and may also contain data         
         UpdateCommandEnabled( EPbk2CmdOpenMyCard, ETrue ); 
         }
     else
@@ -962,9 +985,20 @@
 void CPbk2NamesListEmptyState::CmdItemVisibilityChanged( TInt aCmdItemId, TBool aVisible ) 
     {
     TInt cmdItemIndex = FindCommand(aCmdItemId);
-    TRAP_IGNORE( HandleCommandEventL(
+    TRAP_IGNORE(
+        // If command item is changed to be visible, set its hidden selection to ETrue.
+        if( aVisible )
+            {
+            TInt enableCmdCount = EnabledCommandCount();
+            TListItemProperties prop( iListBox.ItemDrawer()->Properties(enableCmdCount) );
+            prop.SetHiddenSelection(aVisible);
+            iListBox.ItemDrawer()->SetPropertiesL(enableCmdCount-1, prop);
+            }
+    
+        HandleCommandEventL(
                 (aVisible ? EItemAdded : EItemRemoved),
-                 cmdItemIndex) );		
+                 cmdItemIndex);
+        );
     }
 
 // --------------------------------------------------------------------------
@@ -1049,4 +1083,21 @@
         }
     }
 
+// --------------------------------------------------------------------------
+// CPbk2NamesListEmptyState::EnabledCommandCount
+// --------------------------------------------------------------------------
+// 
+TInt CPbk2NamesListEmptyState::EnabledCommandCount() const
+    {
+    TInt result = 0;
+    for ( TInt i = 0; i < iCommandItems.Count(); ++i )
+        {
+        if(iCommandItems[i]->IsEnabled())
+            {
+            result++;
+            }
+        }
+    return result;    
+    }
+
 //  End of File
--- a/phonebookui/Phonebook2/UIControls/src/CPbk2NamesListFilteredState.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/CPbk2NamesListFilteredState.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -1130,9 +1130,21 @@
 void CPbk2NamesListFilteredState::CmdItemVisibilityChanged( TInt aCmdItemId, TBool aVisible ) 
     {
     TInt cmdItemIndex = FindCommand(aCmdItemId);
-    TRAP_IGNORE( HandleCommandEventL(
+    TInt cmdListBoxIndex = EnabledCommandCount();
+    if( aVisible )
+        {
+        cmdListBoxIndex--;
+        }
+    // Update the HiddenSelection property of the command items.
+    TListItemProperties prop( iListBox.ItemDrawer()->Properties(cmdListBoxIndex) );
+    prop.SetHiddenSelection(aVisible);
+    TRAP_IGNORE(        
+        iListBox.ItemDrawer()->SetPropertiesL(cmdListBoxIndex, prop);
+    
+        HandleCommandEventL(
                 (aVisible ? EItemAdded : EItemRemoved),
-                 cmdItemIndex) );		
+                 cmdItemIndex);
+        );		
     }
 
 // --------------------------------------------------------------------------
@@ -1217,4 +1229,21 @@
         }
     }
 
+// --------------------------------------------------------------------------
+// CPbk2NamesListFilteredState::EnabledCommandCount
+// --------------------------------------------------------------------------
+//  
+TInt CPbk2NamesListFilteredState::EnabledCommandCount() const
+    {
+    TInt result = 0;
+    for ( TInt i = 0; i < iCommandItems.Count(); ++i )
+        {
+        if(iCommandItems[i]->IsEnabled())
+            {
+            result++;
+            }
+        }
+    return result;    
+    }
+
 //  End of File
--- a/phonebookui/Phonebook2/UIControls/src/CPbk2NamesListReadyState.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/CPbk2NamesListReadyState.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -736,6 +736,7 @@
         {
         // Send selection events based on marking
         TInt focusIndex = iListBox.CurrentItemIndex();
+        TInt commands = CommandItemCount();
         const TBool markedAfter = iListBox.View()->ItemIsSelected( focusIndex );
 
         TPbk2ControlEvent event( TPbk2ControlEvent::EContactSelected );
@@ -744,6 +745,10 @@
             {
             event.iEventType = TPbk2ControlEvent::EContactUnselected;
             }
+        else if ( focusIndex <  commands)
+            {
+            UnmarkCommands();
+            }
         iEventSender.SendEventToObserversL( event );
 
         }
@@ -1491,56 +1496,21 @@
 void CPbk2NamesListReadyState::DynInitMenuPaneL(
         TInt aResourceId, CEikMenuPane* aMenuPane) const
     {
-    AknSelectionService::HandleMarkableListDynInitMenuPane
-        (aResourceId, aMenuPane, &iListBox);
-    
-    TInt focusedItem = iListBox.View()->CurrentItemIndex();
-    TBool markHidden = iListBox.View()->ItemIsSelected( focusedItem );
-    TBool unmarkHidden = !iListBox.View()->ItemIsSelected( focusedItem );
-    TBool markAllHidden = ( iListBox.Model()->NumberOfItems() == 0 ) || 
-        ( iListBox.SelectionIndexes()->Count() == iListBox.Model()->NumberOfItems() );
-    TBool unmarkAllHidden = ( iListBox.Model()->NumberOfItems() == 0 ) || 
-        ( iListBox.SelectionIndexes()->Count() == 0 );
-    
-    TInt position;
-    if (aMenuPane->MenuItemExists(EAknCmdMark, position))
-        {
-        aMenuPane->SetItemDimmed(EAknCmdMark, markHidden);
-        }
-    if (aMenuPane->MenuItemExists(EAknCmdUnmark, position))
-        {
-        aMenuPane->SetItemDimmed(EAknCmdUnmark, unmarkHidden);
-        }
-    if (aMenuPane->MenuItemExists(EAknMarkAll, position))
+    TInt commandItemCount = CommandItemCount();
+	
+    // Stores the position of the searched menu item.
+    // This position is not needed or used anywhere
+    TInt pos; 
+
+    if ((iListBox.SelectionIndexes()->Count() + commandItemCount ) 
+            == iListBox.Model()->NumberOfItems())
         {
-        aMenuPane->SetItemDimmed(EAknMarkAll, markAllHidden);
-        }
-    if (aMenuPane->MenuItemExists(EAknUnmarkAll, position))
-        {
-        aMenuPane->SetItemDimmed(EAknUnmarkAll, unmarkAllHidden);
-        }
-    
-    // When all contacts are marked in the listbox, the command items are not marked.
-    // This code snippet dims out the  Mark All menu item which is shown since the
-    // list box cannot differentiate a command and a contact item
-
-    TInt commandItemCount = CommandItemCount();
-
-
-    if ((iListBox.SelectionIndexes()->Count() + commandItemCount ) == iListBox.Model()->NumberOfItems())
-        {
-        TInt i; // Stores the position of the searched menu item.
-                // This position is not needed or used anywhere
-        if (aMenuPane->MenuItemExists(EAknMarkAll, i))
+        if (aMenuPane->MenuItemExists( EAknCmdMarkingModeEnter, pos ) )
             {
-            aMenuPane->SetItemDimmed(EAknMarkAll, ETrue);
+            aMenuPane->SetItemDimmed( EAknCmdMarkingModeEnter, ETrue );
             }
         }
 
-    // If there's any, command items are always placed at the top of the list box.
-    // By comparing the list box current item index with the command item count, we are trying to find out
-    // if the current focused item is command item or not.
-
     }
 
 // --------------------------------------------------------------------------
@@ -2072,9 +2042,22 @@
 void CPbk2NamesListReadyState::CmdItemVisibilityChanged( TInt aCmdItemId, TBool aVisible )
     {
     TInt cmdItemIndex = FindCommand(aCmdItemId);
-    TRAP_IGNORE( HandleCommandEventL(
-                (aVisible ? EItemAdded : EItemRemoved),
-                cmdItemIndex) );
+    TInt cmdListBoxIndex = EnabledCommandCount();
+    if( aVisible )
+        {
+        cmdListBoxIndex--;
+        }
+    // Update the HiddenSelection property of the command items.
+    TListItemProperties prop( iListBox.ItemDrawer()->Properties(cmdListBoxIndex) );
+    prop.SetHiddenSelection(aVisible);
+    
+    TRAP_IGNORE(
+        iListBox.ItemDrawer()->SetPropertiesL(cmdListBoxIndex, prop);
+    
+        HandleCommandEventL(
+            (aVisible ? EItemAdded : EItemRemoved),
+            cmdItemIndex);
+        );
     }
 
 // --------------------------------------------------------------------------
--- a/phonebookui/Phonebook2/UIControls/src/CPbk2SettingsListControl.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/CPbk2SettingsListControl.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -38,6 +38,8 @@
 #include <centralrepository.h>
 #include <featmgr.h>
 #include <AknFepInternalCRKeys.h>
+#include <akncheckboxsettingpage.h>
+#include <sysutil.h>
 
 //Pbk2Debug
 #include "Pbk2Debug.h"
@@ -309,6 +311,26 @@
         //Edit selection setting item 
         //result is ETrue if OK pressed
         result = iSelectionSettingItem->EditItemL();
+        
+        TBool driveSpaceFull( EFalse );
+        driveSpaceFull = SysUtil::FFSSpaceBelowCriticalLevelL( &CCoeEnv::Static()->FsSession() );
+        if ( driveSpaceFull )
+            {
+            //If the disk is full, a write operation cannot complete. So restore 
+            //the previous state.
+            iEikonEnv->HandleError(KErrDiskFull);
+            CSelectionItemList& oldItem( iSettingListState->ItemListState() );
+            CSelectionItemList& item( iSettingListState->SelectionItemList() );
+            TInt count = item.Count();
+            for ( TInt i(0); i < count; ++i )
+                {
+                TBool select = oldItem.At(i)->SelectionStatus();
+                item.At(i)->SetSelectionStatus( select );
+                }
+            iSelectionSettingItem->RestoreStateL();
+            result = EFalse;
+            }
+        
         if ( result )
             {
             //Is selection setting list changed by user
--- a/phonebookui/Phonebook2/UIControls/src/CPbk2SettingsListState.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/CPbk2SettingsListState.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -135,6 +135,16 @@
     }
 
 // --------------------------------------------------------------------------
+// CPbk2SettingsListState::ItemListState
+// --------------------------------------------------------------------------
+//
+CSelectionItemList& CPbk2SettingsListState::ItemListState()
+    {
+    __ASSERT_DEBUG( iItemListState, Panic(EPanicItemListStateNULL));
+    return *iItemListState;
+    }
+
+// --------------------------------------------------------------------------
 // CPbk2SettingsListState::SupportedStores
 // --------------------------------------------------------------------------
 //
--- a/phonebookui/Phonebook2/UIControls/src/Pbk2ImageCommands.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/Pbk2ImageCommands.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -619,27 +619,34 @@
         services.ContactManager() );
 	CleanupStack::PushL( imageManager );
 	
-    if( CAknQueryDialog::NewL()->ExecuteLD(
-            R_PHONEBOOK2_REMOVE_IMAGE_CONFIRMATION_DIALOG ) )
-        {
-        TPbk2StoreContactAnalyzer analyzer(
-            services.ContactManager(), aContact );
-        TInt imageIndex = analyzer.HasFieldL( R_PHONEBOOK2_IMAGE_SELECTOR );
+	const MVPbkFieldType* thumbType = services.ContactManager().FieldTypes().Find(
+	                R_VPBK_FIELD_TYPE_THUMBNAILPIC );
+	
+	// show a confirmation query if contact has an image
+	if (thumbType && imageManager->HasImage( *aContact, *thumbType ) )
+	    {
+	    if ( CAknQueryDialog::NewL()->ExecuteLD( 
+	            R_PHONEBOOK2_REMOVE_IMAGE_CONFIRMATION_DIALOG ) )
+	        {
+	        TPbk2StoreContactAnalyzer analyzer(
+	                services.ContactManager(), aContact );
+	        TInt imageIndex = analyzer.HasFieldL( R_PHONEBOOK2_IMAGE_SELECTOR );
         
-        if ( imageIndex != KErrNotFound )
-            {
-            //aContact->RemoveField( imageIndex );
-            //Instead of above we don't remove the field, just zero it's data
-            MVPbkContactFieldData& data(aContact->Fields().
-                FieldAt( imageIndex ).FieldData());
-            MVPbkContactFieldTextData::Cast( data ).SetTextL(KNullDesC);
-            }
+	        if ( imageIndex != KErrNotFound )
+	            {
+	            //aContact->RemoveField( imageIndex );
+	            //Instead of above we don't remove the field, just zero it's data
+	            MVPbkContactFieldData& data(aContact->Fields().
+	                    FieldAt( imageIndex ).FieldData());
+	            MVPbkContactFieldTextData::Cast( data ).SetTextL(KNullDesC);
+	            }
         
-        const MVPbkFieldType* thumbFieldType = ThumbnailFieldTypeL(services);
-        imageManager->RemoveImage( *aContact, *thumbFieldType );
-        }
+	        const MVPbkFieldType* thumbFieldType = ThumbnailFieldTypeL(services);
+	        imageManager->RemoveImage( *aContact, *thumbFieldType );
+	        }
+	    }
+	
     CleanupStack::PopAndDestroy( imageManager );
-
     CleanupStack::PopAndDestroy(); // services
     
     return NULL; // synchronous operation
--- a/phonebookui/Phonebook2/UIControls/src/cpbk2contacteditornewowncontact.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/cpbk2contacteditornewowncontact.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -224,16 +224,15 @@
     {
     PBK2_DEBUG_PRINT( PBK2_DEBUG_STRING
         ( "CPbk2ContactEditorNewOwnContact::HandleIdleDelete(0x%x)" ), this );
-
-    iInputAbsorber->StopWait();
-    MPbk2ContactEditorEventObserver* observer = iObserver;
-    iObserver = NULL;
-    MVPbkContactObserver::TContactOpResult result;
-    // Disable warnings by nulling the data members
-    result.iStoreContact = NULL;
-    result.iExtension = NULL;
-    result.iOpCode = MVPbkContactObserver::EContactDelete;
-    observer->ContactEditorOperationCompleted( result, iEditorParams );
+    iInputAbsorber->StopWait();   
+    // Notify client asynchronously to let Delete Operation complete firstly and
+    // then the client will be notified to do the other things in the RunL() function.
+    iLatestResult.iExtension = NULL;
+    iLatestResult.iStoreContact = NULL;
+    iLatestResult.iOpCode = MVPbkContactObserver::EContactDelete;
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete(status, KErrNone);
+    SetActive();
     }
 
 // --------------------------------------------------------------------------
--- a/phonebookui/Phonebook2/UIControls/src/cpbk2contactviewcustomlistboxdata.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/cpbk2contactviewcustomlistboxdata.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -364,9 +364,7 @@
     
     iKineticScrolling = CAknPhysics::FeatureEnabled();
 
-#ifdef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     LoadMarkingIconsL();
-#endif // PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
 
     }
 
@@ -591,12 +589,10 @@
 //
 void CPbk2ContactViewCustomListBoxDataExtension::SkinChangedL()
     {
-#ifdef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     DeleteAnim();
     TryCreateAnimation();
     CreateColorBitmapsL();
     LoadMarkingIconsL();
-#endif // PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     }
 // -----------------------------------------------------------------------------
 // CPbk2ContactViewCustomListBoxDataExtension::SkinChanged
@@ -1188,7 +1184,6 @@
 //
 void CPbk2ContactViewCustomListBoxDataExtension::LoadMarkingIconsL()
     {
-#ifdef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     if ( !iMarkingIconArray )
         {
         iMarkingIconArray = new ( ELeave ) CAknIconArray( 2 );
@@ -1217,7 +1212,6 @@
     CleanupStack::PushL( icon );
     iMarkingIconArray->AppendL( icon );
     CleanupStack::Pop( icon );
-#endif // PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     }
 
 CCoeControl *CPbk2ContactViewCustomListBoxData::Control() const 
@@ -2041,7 +2035,6 @@
 
     TRgb aTextColor = aHighlight ? aColors.iHighlightedText : aColors.iText;
     
-#ifdef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     TBool markingMode = EFalse;
     TRect itemRect( aRect );
     
@@ -2057,7 +2050,6 @@
                     AknLayoutScalable_Avkon::list_single_graphic_pane_t1( 0 ).LayoutLine().il;
             }
         }
-#endif // PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
 
     MAknsSkinInstance *skin = AknsUtils::SkinInstance();
     MAknsControlContext *cc = AknsDrawUtils::ControlContext( Control() );
@@ -2073,13 +2065,8 @@
     
     if ( iExtension->iSubCellsMightIntersect )
         {
-#ifdef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
         CheckIfSubCellsIntersectL( &textLines[0], &rectClipped[0], *aText, itemRect );
         }
-#else
-        CheckIfSubCellsIntersectL( &textLines[0], &rectClipped[0], *aText, aRect );
-        }
-#endif // PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
 #ifdef RD_UI_TRANSITION_EFFECTS_LIST
     MAknListBoxTfxInternal *transApi = CAknListLoader::TfxApiInternal( &aGc );
 #endif // RD_UI_TRANSITION_EFFECTS_LIST
@@ -2120,7 +2107,6 @@
         }
     DrawHighLight( aGc, aRect, aHighlight, skin );
     
-#ifdef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     if ( markingMode && !aItemProperties.IsSelectionHidden() )
         {
         TAknLayoutRect layoutRect;
@@ -2154,7 +2140,6 @@
             }
         
         }
-#endif // PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     
     // The column draw loop
     column = 0;
@@ -2270,13 +2255,8 @@
                 }
             
             TAknLayoutText textLayout;
-#ifdef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
             textLayout.LayoutText( itemRect, textLineLayout, usedFont );
             TRect layoutedRect( itemRect);
-#else
-            textLayout.LayoutText( aRect, textLineLayout, usedFont );
-            TRect layoutedRect( aRect );
-#endif // PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
                           
             // *2 == leave some room for marquee
             const TInt maxlen( KMaxColumnDataLength * 2 ); 
@@ -2323,11 +2303,7 @@
                 {
                 iExtension->iMarquee->UseLogicalToVisualConversion( bidiConv );
                 
-#ifdef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
                 if ( iExtension->iMarquee->DrawText( aGc, itemRect, textLineLayout, convBuf, usedFont, textColor ) )
-#else
-                if ( iExtension->iMarquee->DrawText( aGc, aRect, textLineLayout, convBuf, usedFont, textColor ) )
-#endif // PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
                     {
                     // all the loops have been executed
                     textLayout.DrawText( aGc, convBuf, bidiConv, textColor );
@@ -2429,11 +2405,7 @@
             TAknWindowLineLayout graphicLayout = iExtension->AtSL(subCellIndex).iGraphicLayout;
             TAknLayoutRect graphicRect; 
             
-#ifdef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
             graphicRect.LayoutRect( itemRect,graphicLayout );
-#else
-            graphicRect.LayoutRect(aRect,graphicLayout);
-#endif // PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
             TSize graphicSize( graphicRect.Rect().Size() );
             
             if (index>=0 && IconArray())
@@ -2528,7 +2500,6 @@
         return;
         }
 
-#ifdef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     CEikListBox* listbox = static_cast<CEikListBox*>( iExtension->iControl );
     TBool markingMode = EFalse;
     TRect itemRect( aRect );
@@ -2545,19 +2516,12 @@
                 AknLayoutScalable_Avkon::list_single_graphic_pane_t1( 0 ).LayoutLine().il;
             }
         }
-#endif // PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     
     TInt extraVerticalSpace=(aRect.Height()-font->HeightInPixels());
     TInt baseLineOffset=extraVerticalSpace/2+font->AscentInPixels();
-#ifdef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     TRect textRect( itemRect );
     TRect textMRect; // textrect with margins.
     textRect.iBr.iX = itemRect.iTl.iX;
-#else
-    TRect textRect( aRect );
-    TRect textMRect; // textrect with margins.
-    textRect.iBr.iX=aRect.iTl.iX;
-#endif // PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     TInt column=0;
     TPtrC text;
 
@@ -2567,20 +2531,12 @@
     // be too difficult to do without - and this is cleaner solution.
     
     // pass 1, figures out x-coordinates for columns.
-#ifdef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     TInt x = itemRect.iTl.iX;
-#else
-    TInt x = aRect.iTl.iX;
-#endif // PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     
     TBool mirror = AknLayoutUtils::LayoutMirrored();
     if (mirror)
         {
-#ifdef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
         x = itemRect.iBr.iX;
-#else
-        x = aRect.iBr.iX;
-#endif // PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
         }
     TInt maxx = x;
     while(column <= lastColumn)
@@ -2653,15 +2609,6 @@
         cc = SkinBackgroundContext();
         }
 
-#ifndef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
-    // aRect is list item's rect, width of which is smaller than width of the list
-    // with a scroll bar. List needs to draw under scroll bar anyway, so we need to
-    // modify given rect here.
-    TRect r(aRect);
-    
-    CEikListBox* listbox = static_cast<CEikListBox*>( iExtension->iControl );
-#endif // !PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
-
 #ifdef RD_UI_TRANSITION_EFFECTS_LIST
 
     MAknListBoxTfxInternal *transApi = CAknListLoader::TfxApiInternal( &aGc );
@@ -2697,13 +2644,8 @@
 #endif // RD_UI_TRANSITION_EFFECTS_LIST
         }
     
-#ifdef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     if ( iExtension->iCurrentRow < listbox->BottomItemIndex() )
-#else
-    CEikListBox* list = static_cast<CEikListBox*>( iExtension->iControl );
-
-    if ( iExtension->iCurrentRow < list->BottomItemIndex() )
-#endif // PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
+
         {
         AknListUtils::DrawSeparator( aGc, aRect, aColors.iText, skin );
         }
@@ -2720,7 +2662,6 @@
         }
 #endif // RD_UI_TRANSITION_EFFECTS_LIST
 
-#ifdef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     if ( markingMode && !aItemProperties.IsSelectionHidden() )
         {
         TAknLayoutRect layoutRect;
@@ -2761,7 +2702,6 @@
                               EFalse );
             }
         }
-#endif // PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     
     // The column draw loop
     column = 0;
@@ -3382,11 +3322,8 @@
     // too.
     if( KAknsMessageSkinChange == aType )
         {
-#ifdef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
         TRAP_IGNORE( iExtension->SkinChangedL() );
-#else
-        iExtension->SkinChanged();
-#endif // PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
+
         }
     else if(aType == KEikDynamicLayoutVariantSwitch)
         {
--- a/phonebookui/Phonebook2/UIControls/src/cpbk2contactviewcustomlistboxitemdrawer.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIControls/src/cpbk2contactviewcustomlistboxitemdrawer.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -148,19 +148,6 @@
     data->SetItemCellSize( iItemCellSize );
     }
 
-#ifndef RD_TOUCH2
-void CPbk2ContactViewCustomListBoxItemDrawer::DrawCurrentItemRect(const TRect& aRect) const
-//
-//    Draw the item background
-//
-    {
-    iGc->SetClippingRect(iViewRect);
-    iGc->SetBrushStyle(CGraphicsContext::ENullBrush);
-    iGc->SetPenColor(iHighlightedBackColor);    // KDefaultLbxHighlightRectColor
-    iGc->DrawRect(aRect);
-    iGc->CancelClippingRect();
-    }
-#endif // !RD_TOUCH2
 
 /**
 * Returns a pointer to the column data. Does not imply transfer of ownership.
@@ -210,13 +197,11 @@
     TInt pos = -1;
     
     TBool removeicon = (!aItemIsSelected && !ItemMarkReverse()) || (aItemIsSelected && ItemMarkReverse()); 
-#ifdef PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     
     if ( Flags() & CListItemDrawer::EMarkingModeEnabled )
         {
         removeicon = EFalse;
         }
-#endif // PBK2_AVKON_TOUCH_MARKINGMODE_CHANGES
     if ( Flags() & EDrawMarkSelection && ItemMarkPosition() != -1 && removeicon)
         {
         repl.Set( ItemMarkReplacement() );
@@ -309,7 +294,18 @@
 
 TListItemProperties CPbk2ContactViewCustomListBoxItemDrawer::Properties(TInt aItemIndex) const
     {
-    if (!iPropertyArray) return CTextListItemDrawer::Properties(aItemIndex);
+    if ( !iPropertyArray )
+        {
+        TListItemProperties prop( 
+            CTextListItemDrawer::Properties( aItemIndex ) );       
+        // Do not allow marking other than contact items
+        if ( !ColumnData()->IsContactAtListboxIndex( aItemIndex ) )
+            {
+            prop.SetHiddenSelection( ETrue );
+            }      
+        return prop;
+        }
+    
     CAknListBoxFilterItems *filter = STATIC_CAST(CAknFilteredTextListBoxModel*,iModel)->Filter();
     if (filter)
         {
--- a/phonebookui/Phonebook2/UIPolicy/inc/CPbk2ContactViewSortPolicy.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIPolicy/inc/CPbk2ContactViewSortPolicy.h	Thu Aug 19 09:41:07 2010 +0300
@@ -73,6 +73,17 @@
                 TParam* aParam );
         TInt PostProcessResult(
                 TInt aSortUtilResult );
+        /**
+         * Get the index of top contact field in sort order list
+         */
+        TInt GetTopContactFieldIndex();
+        /** 
+         * Set sortkey array item from one field
+         */
+        void SetSortKey(
+        		CPbk2SortKeyArray* aSortKeyArray,
+        		const MVPbkBaseContactField* aField,
+        		TInt aIndex );
 
     private: // Data
         /// Own: Sort Util to forward sorting requests
@@ -90,6 +101,8 @@
         TPbk2SortOrderFieldMapper iFieldMapper;
         /// Own: Indicates succesfull initialization
         TBool iSortPolicyParameterReceived;
+        /// Index of top contact field in iSortOrder
+        TInt iTopContactId;
     };
 
 #endif // CPBK2CONTACTVIEWSORTPOLICY_H
--- a/phonebookui/Phonebook2/UIPolicy/src/CPbk2ContactViewSortPolicy.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/UIPolicy/src/CPbk2ContactViewSortPolicy.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -43,6 +43,12 @@
 // Debugging headers
 #include <Pbk2Profile.h>
 
+#include <vpbkeng.rsg>
+
+// Greater than any practical top contact number string
+// which is in form like '0000000001'.
+_LIT(KBigNumStr, "9999999999");
+
 
 /// Unnamed namespace for local definitions
 namespace {
@@ -172,6 +178,8 @@
         iSortOrder = CVPbkSortOrder::NewL(aParam->iSortOrder);
         iFieldMapper.SetSortOrder(*iSortOrder);
 
+        iTopContactId = GetTopContactFieldIndex();
+
         RPbk2LocalizedResourceFile resFile(aParam->iFs);
         resFile.OpenLC( KPbk2RomFileDrive, KDC_RESOURCE_FILES_DIR,
             KResourceFile );
@@ -205,6 +213,8 @@
     delete iSortOrder;
     iSortOrder = sortOrder;
     iFieldMapper.SetSortOrder( *iSortOrder );
+
+    iTopContactId = GetTopContactFieldIndex();
     }
 
 // --------------------------------------------------------------------------
@@ -275,34 +285,14 @@
         const TInt lhsCount = iFieldMapper.FieldCount();
         for ( i = 0; i < lhsCount; ++i )
             {
-            const MVPbkBaseContactField* lhsField =
-                iFieldMapper.FieldAt( i );
-            if ( lhsField )
-                {
-                iLeftSortKeyArray->SetText( MVPbkContactFieldTextData::Cast
-                    ( lhsField->FieldData() ).Text(), i );
-                }
-            else
-                {
-                iLeftSortKeyArray->SetText( KNullDesC, i );
-                }
+            SetSortKey( iLeftSortKeyArray, iFieldMapper.FieldAt(i), i );
             }
 
         iFieldMapper.SetContactFields( aRhs.Fields() );
         const TInt rhsCount = iFieldMapper.FieldCount();
         for ( i = 0; i < rhsCount; ++i )
             {
-            const MVPbkBaseContactField* rhsField =
-                iFieldMapper.FieldAt( i );
-            if ( rhsField )
-                {
-                iRightSortKeyArray->SetText( MVPbkContactFieldTextData::Cast
-                    ( rhsField->FieldData() ).Text(), i );
-                }
-            else
-                {
-                iRightSortKeyArray->SetText( KNullDesC, i );
-                }
+            SetSortKey( iRightSortKeyArray, iFieldMapper.FieldAt(i), i );
             }
 
 PBK2_PROFILE_END( Pbk2Profile::ESortPolicyCompareContacts );
@@ -392,4 +382,60 @@
     return result;
     }
 
+// --------------------------------------------------------------------------
+// CPbk2ContactViewSortPolicy::GetTopContactFieldIndex
+// --------------------------------------------------------------------------
+//
+TInt CPbk2ContactViewSortPolicy::GetTopContactFieldIndex()
+    {
+    TInt index = KErrNotFound;
+    for ( TInt i=0; i<iSortOrder->FieldTypeCount(); i++ )
+        {
+        // Resource id of top contact field is R_VPBK_FIELD_TYPE_TOPCONTACT.
+        if ( iSortOrder->FieldTypeAt( i ).FieldTypeResId() == 
+                R_VPBK_FIELD_TYPE_TOPCONTACT )
+            {
+            index = i;
+            break;
+            }
+        }
+    return index;
+    }
+
+// --------------------------------------------------------------------------
+// CPbk2ContactViewSortPolicy::SetSortKey
+// --------------------------------------------------------------------------
+//
+void CPbk2ContactViewSortPolicy::SetSortKey(
+        CPbk2SortKeyArray* aSortKeyArray,
+        const MVPbkBaseContactField* aField,
+        TInt aIndex )
+    {
+    TInt textLen = 0;
+    if ( aField )
+        {
+        TPtrC text = MVPbkContactFieldTextData::Cast
+            ( aField->FieldData() ).Text();
+        aSortKeyArray->SetText( text, aIndex );
+        textLen = text.Length();
+        }
+    if ( textLen == 0 )
+        {
+        if ( aIndex == iTopContactId )
+            {
+            // For some variants such as Chinese variant, 
+            // empty string is less than not empty string. 
+            // This will make topic contacts which have substantial top contact
+            // id strings after those with empty id strings.
+            // To prevent this, use a big number string instead of empty string 
+            // and make sure top contacts in front of other contacts.
+            aSortKeyArray->SetText( KBigNumStr, aIndex );
+            }
+        else
+            {
+            aSortKeyArray->SetText( KNullDesC, aIndex );
+            }
+        }
+    }
+
 //  End of File
--- a/phonebookui/Phonebook2/USIMExtension/inc/CPsu2CopyToSimFieldInfoArray.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/USIMExtension/inc/CPsu2CopyToSimFieldInfoArray.h	Thu Aug 19 09:41:07 2010 +0300
@@ -120,8 +120,16 @@
         * @return a reference to item in given index
         */
         inline const TPsu2CopyToSimFieldInfo& operator[](TInt aIndex) const;
-
-        
+                
+        /**
+        * Remove the fieldinfo which target type is not supported.
+        * Some target types defined in the rss file are not supported because of the limit
+        * of the sim card support. So the unsupported types must be removed from mapping 
+        * array.
+        * @param aSupportedTypes: the supported type list.
+        */
+        void RemoveUnSupportedFieldInfo( const MVPbkFieldTypeList& aSupportedTypes );
+               
         /**
         * @param aSourceType the source field type
         * @return the info that for the aSourceType or NULL
--- a/phonebookui/Phonebook2/USIMExtension/rss/Pbk2USimSimCopy.rss	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/USIMExtension/rss/Pbk2USimSimCopy.rss	Thu Aug 19 09:41:07 2010 +0300
@@ -218,6 +218,152 @@
         };
     }
 
+// -----------------------------------------------------------------------------
+//   
+// R_PSU2_COPY_TO_USIM_FIELDTYPE_MAPPINGS
+// A array that defines the rules for copying fields to the usim
+// with additional numbers
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE PSU2_COPY_TO_SIM_FIELDTYPE_MAPPINGS r_psu2_copy_to_usim_fieldtype_mappings
+    {
+    items =
+        {
+        PSU2_COPY_TO_SIM_FIELDTYPE_MAPPING
+            {
+            // Source: all email types
+            sourceTypeSelector = VPBK_FIELD_TYPE_SELECTOR
+                {
+                versitProperties = 
+                    {
+                    VBK_FIELD_VERSIT_PROPERTY
+                        {
+                        name = EVPbkVersitNameEMAIL;
+                        }
+                    };
+                };
+            // Target: USIM supports only general email
+            targetSimType = R_VPBK_FIELD_TYPE_EMAILGEN;
+            iBlockingError = KPsu2EMailFullError;
+            },
+        //To handle the situation of USIM supports more than one additional number.
+        PSU2_COPY_TO_SIM_FIELDTYPE_MAPPING
+            {
+            sourceTypeSelector = VPBK_FIELD_TYPE_SELECTOR
+                {
+                versitProperties = 
+                    {
+                        VBK_FIELD_VERSIT_PROPERTY
+                        {
+                        name = EVPbkVersitNameTEL;
+                        parameters = { EVPbkVersitParamHOME };
+                        }
+                    };
+                excludedParameters ={ EVPbkVersitParamFAX, EVPbkVersitParamWORK, 
+                        EVPbkVersitParamCELL, EVPbkVersitParamVIDEO };
+                };
+            // Target: USIM supports telephone( home )
+            targetSimType = R_VPBK_FIELD_TYPE_LANDPHONEHOME;
+            flags = 0;
+            },
+        PSU2_COPY_TO_SIM_FIELDTYPE_MAPPING
+            {
+            sourceTypeSelector = VPBK_FIELD_TYPE_SELECTOR
+                {
+                versitProperties = 
+                    {
+                    VBK_FIELD_VERSIT_PROPERTY
+                        {
+                        name = EVPbkVersitNameTEL;
+                        parameters = { EVPbkVersitParamWORK };
+                        }
+                    };
+                excludedParameters ={ EVPbkVersitParamFAX, EVPbkVersitParamHOME, 
+                        EVPbkVersitParamCELL, EVPbkVersitParamVIDEO };
+                };
+
+            // Target: USIM supports telephone( work )
+            targetSimType = R_VPBK_FIELD_TYPE_LANDPHONEWORK;
+            flags = 0;
+            },
+        PSU2_COPY_TO_SIM_FIELDTYPE_MAPPING
+            {
+            sourceTypeSelector = VPBK_FIELD_TYPE_SELECTOR
+                {
+                versitProperties = 
+                    {
+                    VBK_FIELD_VERSIT_PROPERTY
+                        {
+                        name = EVPbkVersitNameTEL;
+                        parameters = { EVPbkVersitParamFAX };
+                        },
+                    VBK_FIELD_VERSIT_PROPERTY
+                        {
+                        name = EVPbkVersitNameTEL;
+                        parameters = { EVPbkVersitParamFAX, EVPbkVersitParamHOME };
+                        },
+                    VBK_FIELD_VERSIT_PROPERTY
+                        {
+                        name = EVPbkVersitNameTEL;
+                        parameters = { EVPbkVersitParamFAX,EVPbkVersitParamWORK};
+                        }
+                    };
+                excludedParameters ={ EVPbkVersitParamCELL, EVPbkVersitParamVIDEO };
+                };
+            // Target: USIM supports only fax general
+            targetSimType = R_VPBK_FIELD_TYPE_FAXNUMBERGEN;
+            flags = 0;
+            },
+        PSU2_COPY_TO_SIM_FIELDTYPE_MAPPING
+            {
+            // Source: all number types
+            sourceTypeSelector = VPBK_FIELD_TYPE_SELECTOR
+                {
+                versitProperties = 
+                    {
+                    VBK_FIELD_VERSIT_PROPERTY
+                        {
+                        name = EVPbkVersitNameTEL;
+                        },
+                    VBK_FIELD_VERSIT_PROPERTY
+                        {            
+                        name = EVPbkVersitNameX;
+                        extensionName = "X-ASSISTANT-TEL";            
+                        }
+                    };
+                nonVersitType =
+                    {
+                    EVPbkNonVersitTypeDTMF
+                    };
+                };
+            // Target: SIM supports only mobile general
+            targetSimType = R_VPBK_FIELD_TYPE_MOBILEPHONEGEN;
+            flags = 0;
+            },
+        PSU2_COPY_TO_SIM_FIELDTYPE_MAPPING
+            {
+            // Source: nick name
+            sourceTypeSelector = VPBK_FIELD_TYPE_SELECTOR
+                {
+                versitProperties =
+                    {
+                    VBK_FIELD_VERSIT_PROPERTY
+                        {
+                        name = EVPbkVersitNameX;
+                        extensionName = "X-NICKNAME";
+                        }
+                    };
+                };
+            // Target: nick name
+            targetSimType = R_VPBK_FIELD_TYPE_SECONDNAME;
+            // Nick name can be truncated.
+            flags = KPsu2AllowedToTruncate;
+            iBlockingError = KPsu2SecondNameFullError;
+            }
+        };
+    }
+
 // End of File
 
 
--- a/phonebookui/Phonebook2/USIMExtension/src/CPsu2CopyToSimCmd.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/USIMExtension/src/CPsu2CopyToSimCmd.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -299,6 +299,13 @@
     PBK2_DEBUG_PRINT( PBK2_DEBUG_STRING
         ( "CPsu2CopyToSimCmd::RunError %d" ), aError );
     CCoeEnv::Static()->HandleError(aError);
+    
+    // If the copy operation is cancelled due to error occurred, update the 
+    // ui control and reset the command pointer before it is destructed.
+    if ( iNameListUiControl )
+        {
+        iNameListUiControl->UpdateAfterCommandExecution();
+        }
     if ( iCommandObserver )
         {
         iCommandObserver->CommandFinished(*this);
--- a/phonebookui/Phonebook2/USIMExtension/src/CPsu2CopyToSimFieldInfoArray.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/USIMExtension/src/CPsu2CopyToSimFieldInfoArray.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -33,7 +33,7 @@
 #include <coemain.h>
 #include <barsread.h>
 #include <gsmerror.h>
-
+#include <featmgr.h>
 #include <VPbkEng.rsg>
 
 namespace
@@ -239,10 +239,19 @@
     RPbk2LocalizedResourceFile resFile( &aFs );
     resFile.OpenLC(KPbk2RomFileDrive,
         KDC_RESOURCE_FILES_DIR, KPsu2USimExtensionResFile);
-    
+    FeatureManager::InitializeLibL();
     TResourceReader reader;
-    reader.SetBuffer( 
-        resFile.AllocReadLC( R_PSU2_COPY_TO_SIM_FIELDTYPE_MAPPINGS ) );
+    if( !FeatureManager::FeatureSupported( 
+                    KFeatureIdFfTdClmcontactreplicationfromphonebooktousimcard ) )
+        {
+        reader.SetBuffer( 
+               resFile.AllocReadLC( R_PSU2_COPY_TO_SIM_FIELDTYPE_MAPPINGS ) );
+        }
+    else
+        {
+        reader.SetBuffer( 
+               resFile.AllocReadLC( R_PSU2_COPY_TO_USIM_FIELDTYPE_MAPPINGS ) );
+        }
     
     // Go through all mappings in resource and create a mapping array
     const TInt count = reader.ReadInt16();
@@ -299,6 +308,7 @@
     iInfoArray.Close();
     iMatchedTypes.Close();
     delete iNumberKeyMap;
+    FeatureManager::UnInitializeLib();
     }
 
 // -----------------------------------------------------------------------------
@@ -320,6 +330,25 @@
         }
     return result;
     }
+
+// -----------------------------------------------------------------------------
+// CPsu2CopyToSimFieldInfoArray::RemoveUnSupportedTargetTypeFieldInfo
+// -----------------------------------------------------------------------------
+//
+void CPsu2CopyToSimFieldInfoArray::RemoveUnSupportedFieldInfo( const MVPbkFieldTypeList& aSupportedTypes )
+    {
+    // Check all the field info in the iInfoArray, if the target of the fieldinfo 
+    // is not contained in the supportedTypes, Remove it from iInfoArray.
+    TInt i = iInfoArray.Count() - 1;
+    while( i >= 0 )
+        {
+        if( !aSupportedTypes.ContainsSame( iInfoArray[i].SimType()))
+            {
+            iInfoArray.Remove( i );
+            }
+        i --;
+        }
+    }
     
 // -----------------------------------------------------------------------------
 // CPsu2CopyToSimFieldInfoArray::SimNameType
--- a/phonebookui/Phonebook2/USIMExtension/src/CPsu2SimContactProcessor.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/USIMExtension/src/CPsu2SimContactProcessor.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -253,6 +253,11 @@
 //
 void CPsu2SimContactProcessor::ConstructL( RFs& aFs )
     {
+    const MVPbkFieldTypeList& supportedTypes =
+            iTargetStore.StoreProperties().SupportedFields();
+    // Remove the unsupported fieldInfo from array first.
+    iCopyToSimFieldInfoArray.RemoveUnSupportedFieldInfo( supportedTypes );
+        
     const TInt count = iCopyToSimFieldInfoArray.Count();
     for ( TInt i = 0; i < count; ++i )
         {
--- a/phonebookui/Phonebook2/ccapplication/ccacommlauncherplugin/inc/ccappcommlaunchercontainer.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ccapplication/ccacommlauncherplugin/inc/ccappcommlaunchercontainer.h	Thu Aug 19 09:41:07 2010 +0300
@@ -23,6 +23,7 @@
 #include <Pbk2Commands.hrh>
 #include "ccappstatuscontrol.h"
 #include <aknlongtapdetector.h>
+#include <akninputblock.h>
 
 class CAknsBasicBackgroundControlContext;
 class CAknPreviewPopUpController;
@@ -36,6 +37,7 @@
 class CCCAExtensionFactory;
 class CCCAppCommLauncherCustomListBox;
 class CCCaFactoryExtensionNotifier;
+class CAknInputBlock;
 
 /**
  * Class implementing CCAppCommLauncher -container for controls
@@ -52,7 +54,8 @@
     public MEikListBoxObserver,
     public MCCAppContactHandlerNotifier,
     public MCCAStatusControlObserver,
-    public MAknLongTapDetectorCallBack
+    public MAknLongTapDetectorCallBack,
+    public MAknInputBlockCancelHandler
     {
 public: // constructor and destructor
 
@@ -227,7 +230,8 @@
      * @return the amount of the list box.
      * @since S60 v5.0
     */
-    const TInt GetListBoxItemAmount() const;
+    const TInt GetListBoxItemAmount() const;    
+    
 
 private: // New
 
@@ -280,6 +284,105 @@
     */
     void DoCheckExtensionFactoryL();
 
+    /*
+    * Launches find on map contact action
+    */
+    void HandleFindOnMapContactActionL();
+
+    /*
+    * Launches generic contact action 
+    * @param aActionType - Contact Action
+    */
+    void HandleGenericContactActionL(
+        VPbkFieldTypeSelectorFactory::TVPbkContactActionTypeSelector aActionType );
+       
+    /*
+    * Used to check whether a Contact has only one number for initiating VoiceCall.  
+    * Fills selection to aSelectedField if only one field is possible
+    * Only works with VoiceCall Contact Action Type
+    * 
+    * @param aActionType - Contact ActionType. Here it should be EVoiceCallSelector
+    * @param aSelectedField - Data of the selected field. (Phonenumber)
+    * @return - returns ETrue, if more than one field is present for the contact which is capable 
+    *       of VoiceCall.   
+    *       In this case we need to show the field selection dialog
+    *       wherein the user will choose the number for which he wants to start VoiceCall.
+    *       
+    *       returns EFalse - Straight Forward. Voice call can be made directly, 
+    *       since we have only once number for this contact.
+    *       The number to which VoiceCall needs to be made is filled in the aSelectedField.
+    *            
+    */
+    TBool IsVoiceCallFieldSelectionAmbiguous(
+        VPbkFieldTypeSelectorFactory::TVPbkContactActionTypeSelector aActionType,
+        TPtrC& aSelectedField );
+
+    /*
+    * Returns true if field has only one item
+    * @param CCmsContactField
+    */
+    TBool HasFieldOnlyOneItem( const CCmsContactField& field ) const;
+
+    /*
+    * Returns true if field is voice call type
+    * @param CCmsContactField
+    */
+    TBool IsVoiceCallType( const CCmsContactField& field ) const;
+    
+    /*
+    * Returns true if contact has single address
+    * @param aActionType - Contact ActionType.
+    * @param aHandler - Contact Handler 
+    */
+    TBool HasContactSingleAddress(
+        VPbkFieldTypeSelectorFactory::TVPbkContactActionTypeSelector aActionType,
+        CCCAppCommLauncherContactHandler& aHandler );
+    
+    
+    /*
+    * Executes contact action service with field selection
+    * 
+    * @param aActionType - Contact ActionType.
+    * @param aContactIdentifier - Contact Link
+    * @param aFullName - Contact's Name
+    */
+    void ExecuteContactActionServiceWithFieldSelectionL( 
+        VPbkFieldTypeSelectorFactory::TVPbkContactActionTypeSelector aActionType,
+        TDesC8& aContactIdentifier,
+        TDesC& aFullName );
+    
+    /*
+    * Executes contact actions service without field selections
+    * 
+    * @param aActionType - Contact ActionType.
+    * @param aContactIdentifier - Contact Link
+    * @param aFullName - Contact's Name
+    * @param aSelectedField - Contains the number to which 
+    *                   VoiceCall needs to be established.
+    */
+    void ExecuteContactActionServiceWithoutFieldSelectionL( 
+        VPbkFieldTypeSelectorFactory::TVPbkContactActionTypeSelector aActionType,
+        TDesC8& aContactIdentifier,
+        TDesC& aFullName,
+        TDesC& aSelectedField );
+    
+    /*
+    * From MAknInputBlockCancelHandler
+    */    
+    void AknInputBlockCancel();
+    
+    /**
+    * Removes the Input Blocker and makes the contianer regain 
+    * user input, key and pen
+    */    
+    void RemoveInputBlocker();
+    
+    /**
+    * Blocks user input, key and pen, from reaching
+    * container untill the issue of communication is complete 
+    */    
+    void SetInputBlockerL();
+
 private: // Constructors
 
     /**
@@ -371,6 +474,11 @@
 	
 	
 	TBool iLongTap;
+	
+	/**
+	 * Owns - Input Blocker
+	 */
+	CAknInputBlock* iInputBlocker;
     };
 
 #endif // __CCAPPCOMMALAUNCHERCONTAINER_H
--- a/phonebookui/Phonebook2/ccapplication/ccacommlauncherplugin/src/ccappcommlaunchercontainer.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ccapplication/ccacommlauncherplugin/src/ccappcommlaunchercontainer.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -576,57 +576,233 @@
         iHasBeenDragged = EFalse;
         }
 
-    if ( executeContactAction && iPlugin.CommandState().IsRunning() )
+    if ( executeContactAction && iPlugin.CommandState().IsRunning()  )
         {
         executeContactAction = EFalse;
         }
 
-    if (executeContactAction)
+    if ( executeContactAction )
         {
+        SetInputBlockerL();
+        
         VPbkFieldTypeSelectorFactory::TVPbkContactActionTypeSelector
             contactActionType = iPlugin.Container().SelectedCommunicationMethod();
         
         if ( contactActionType
         		== VPbkFieldTypeSelectorFactory::EFindOnMapSelector )
         	{
-            if ( !iLongTap )
-                {
-                DoShowMapCmdL( (TPbk2CommandId)EPbk2ExtensionShowOnMap );
-                }
-            else
-                {
-                iLongTap = EFalse;
-                }
+            HandleFindOnMapContactActionL();           
         	}
         else
         	{
-            TPtrC fullName;
-
-            iPlugin.ContactHandler().ContactFieldItemDataL(
-                CCmsContactFieldItem::ECmsFullName, fullName);
-
-            TUint paramFlag = CCAContactorService::TCSParameter::EEnableDefaults;
-
-            CCAContactorService::TCSParameter param(
-                contactActionType,
-                *iPlugin.ContactHandler().ContactIdentifierLC(),//contactlinkarray
-                paramFlag,
-                fullName);
+            HandleGenericContactActionL( contactActionType );
+            }
         
-            iPlugin.ExecuteServiceL(param);
+        RemoveInputBlocker();
+        }
+    }
+
+// ----------------------------------------------------------------------------
+// CCCAppCommLauncherContainer::HandleFindOnMapContactActionL()
+// ----------------------------------------------------------------------------
+//
+void CCCAppCommLauncherContainer::HandleFindOnMapContactActionL()
+    {
+    if ( !iLongTap )
+        {
+        DoShowMapCmdL( (TPbk2CommandId)EPbk2ExtensionShowOnMap );
+        }
+    else
+        {
+        iLongTap = EFalse;
+        }
+    }
+
+// ----------------------------------------------------------------------------
+// CCCAppCommLauncherContainer::HandleGenericContactActionL()
+// ----------------------------------------------------------------------------
+//
+void CCCAppCommLauncherContainer::HandleGenericContactActionL(
+    VPbkFieldTypeSelectorFactory::TVPbkContactActionTypeSelector aActionType )
+    {
+    TPtrC fullName;
+    iPlugin.ContactHandler().ContactFieldItemDataL(
+        CCmsContactFieldItem::ECmsFullName, fullName );  
+    
+    //contactlinkarray
+    HBufC8* contactIdentifier = iPlugin.ContactHandler().ContactIdentifierLC();
+    
+    TBool fieldSelectionReq(ETrue);
+    TPtrC selectedField;
+    if ( VPbkFieldTypeSelectorFactory::EVoiceCallSelector == aActionType )
+        {
+        fieldSelectionReq = IsVoiceCallFieldSelectionAmbiguous( aActionType, selectedField );        
+        }   
+    
+    
+    if( fieldSelectionReq ) 
+        {
+        ExecuteContactActionServiceWithFieldSelectionL( 
+            aActionType, 
+            *contactIdentifier,
+            fullName );
+        }
+    else
+        {
+        // Speed up contact action by skipping slow field selection operation
+        ExecuteContactActionServiceWithoutFieldSelectionL(
+            aActionType,
+            *contactIdentifier,
+            fullName,
+            selectedField );          
+        }
+    
+    //The Timer can be started after user selected any call item
+    if ( iPlugin.ContactorService()->IsSelected() && 
+        ( aActionType == VPbkFieldTypeSelectorFactory::EVoiceCallSelector ||
+          aActionType == VPbkFieldTypeSelectorFactory::EVideoCallSelector ||
+          aActionType == VPbkFieldTypeSelectorFactory::EVOIPCallSelector) )
+        {
+        iPlugin.StartTimerL();
+        }
+    
+    CleanupStack::PopAndDestroy(1);// contactlinkarray
+    }
+
+// ----------------------------------------------------------------------------
+// CCCAppCommLauncherContainer::IsVoiceCallFieldSelectionAmbiguous()
+// ----------------------------------------------------------------------------
+//
+TBool CCCAppCommLauncherContainer::IsVoiceCallFieldSelectionAmbiguous(
+    VPbkFieldTypeSelectorFactory::TVPbkContactActionTypeSelector aActionType,
+    TPtrC& aSelectedField )
+    {
+    CCCAppCommLauncherContactHandler& handler = iPlugin.ContactHandler();
+    
+    if ( HasContactSingleAddress( aActionType, handler ) )
+        {
+        RPointerArray<CCmsContactField>& fields = handler.ContactFieldDataArray();
+        
+        for( TInt i=0; i < fields.Count(); i++ ) 
+            {
+            CCmsContactField* field = fields[i];
             
-            //The Timer can be started after user selected any call item
-            if ( iPlugin.ContactorService()->IsSelected() && 
-                (contactActionType == VPbkFieldTypeSelectorFactory::EVoiceCallSelector ||
-                 contactActionType == VPbkFieldTypeSelectorFactory::EVideoCallSelector ||
-                 contactActionType == VPbkFieldTypeSelectorFactory::EVOIPCallSelector) )
+            if ( HasFieldOnlyOneItem( *field ) &&
+                 IsVoiceCallType( *field ) ) 
                 {
-                iPlugin.StartTimerL();
-                }
-            
-            CleanupStack::PopAndDestroy(1);// contactlinkarray
+                const CCmsContactFieldItem* fieldItem = NULL;
+                
+                TInt error = KErrNone;
+                TRAP( error, fieldItem = &field->ItemL( 0 ) );
+                
+                if( error == KErrNone ) 
+                    {
+                    aSelectedField.Set(fieldItem->Data());
+                    //Its safe to exit here
+                    //Making of Voice Call is not tedious
+                    //we have only one number
+                    return EFalse;
+                    }                   
+                }           
             }
         }
+    
+    return ETrue;
+    }
+
+// ----------------------------------------------------------------------------
+// CCCAppCommLauncherContainer::HasContactSingleAddress()
+// ----------------------------------------------------------------------------
+//
+TBool CCCAppCommLauncherContainer::HasContactSingleAddress(
+    VPbkFieldTypeSelectorFactory::TVPbkContactActionTypeSelector aActionType,
+    CCCAppCommLauncherContactHandler& aHandler )
+    {
+    TInt amount = aHandler.AddressAmount( aActionType );
+    if( 1 == amount )
+        {
+        return ETrue;
+        }
+    
+    return EFalse;
+    }
+
+// ----------------------------------------------------------------------------
+// CCCAppCommLauncherContainer::HasFieldOnlyOneItem()
+// ----------------------------------------------------------------------------
+//
+TBool CCCAppCommLauncherContainer::HasFieldOnlyOneItem( const CCmsContactField& field ) const
+    {
+    const RPointerArray<CCmsContactFieldItem>& items = field.Items();
+    
+    if ( 1 == items.Count() )
+        {
+        return ETrue;
+        }
+    
+    return EFalse;
+    }
+
+// ----------------------------------------------------------------------------
+// CCCAppCommLauncherContainer::IsVoiceCallType()
+// ----------------------------------------------------------------------------
+//
+TBool CCCAppCommLauncherContainer::IsVoiceCallType( const CCmsContactField& field ) const
+    {
+    CCmsContactFieldItem::TCmsContactField fieldType = field.Type();
+    
+    if( fieldType == CCmsContactFieldItem::ECmsLandPhoneGeneric ||
+        fieldType == CCmsContactFieldItem::ECmsLandPhoneHome ||
+        fieldType == CCmsContactFieldItem::ECmsLandPhoneWork ||
+        fieldType == CCmsContactFieldItem::ECmsMobilePhoneGeneric ||
+        fieldType == CCmsContactFieldItem::ECmsMobilePhoneHome ||
+        fieldType == CCmsContactFieldItem::ECmsMobilePhoneWork  )
+        {    
+        return ETrue;
+        }
+    
+    return EFalse;
+    }
+
+
+// ----------------------------------------------------------------------------
+// CCCAppCommLauncherContainer::ExecuteContactActionServiceWithFieldSelectionL()
+// ----------------------------------------------------------------------------
+//
+void CCCAppCommLauncherContainer::ExecuteContactActionServiceWithFieldSelectionL( 
+    VPbkFieldTypeSelectorFactory::TVPbkContactActionTypeSelector aActionType,
+    TDesC8& aContactIdentifier,
+    TDesC& aFullName )
+    {
+    TUint paramFlag = CCAContactorService::TCSParameter::EEnableDefaults;
+
+    CCAContactorService::TCSParameter param(
+        aActionType,
+        aContactIdentifier,
+        paramFlag,
+        aFullName );
+    
+    iPlugin.ExecuteServiceL(param);    
+    }
+
+// ----------------------------------------------------------------------------
+// CCCAppCommLauncherContainer::ExecuteContactActionServiceWithoutFieldSelectionL()
+// ----------------------------------------------------------------------------
+//
+void CCCAppCommLauncherContainer::ExecuteContactActionServiceWithoutFieldSelectionL( 
+    VPbkFieldTypeSelectorFactory::TVPbkContactActionTypeSelector aActionType,
+    TDesC8& aContactIdentifier,
+    TDesC& aFullName,
+    TDesC& aSelectedField )
+    {
+    CCAContactorService::TCSParameter param(
+        aActionType,
+        aContactIdentifier,
+        CCAContactorService::TCSParameter::EUseFieldParam,
+        aFullName,
+        aSelectedField );
+    
+    iPlugin.ExecuteServiceL(param);
     }
 
 // ----------------------------------------------------------------------------
@@ -915,4 +1091,39 @@
 	{
 	return iModel->MdcaCount();
 	}
+
+//-----------------------------------------------------------------------------
+// CCCAppCommLauncherContainer::SetInputBlockerL()
+//-----------------------------------------------------------------------------
+//
+void CCCAppCommLauncherContainer::SetInputBlockerL()
+     {
+     if (!iInputBlocker)
+         {
+         iInputBlocker = CAknInputBlock::NewCancelHandlerLC( this );
+         CleanupStack::Pop( iInputBlocker );   
+         iInputBlocker->SetCancelDelete( iInputBlocker );
+         }
+     } 
+
+// --------------------------------------------------------------------------
+// CCCAppCommLauncherContainer::RemoveInputBlockerL
+// --------------------------------------------------------------------------
+//
+void CCCAppCommLauncherContainer::RemoveInputBlocker()
+    {
+    if (iInputBlocker)
+        {
+        iInputBlocker->Cancel();
+        }
+    }
+
+// --------------------------------------------------------------------------
+// CCCAppCommLauncherContainer::AknInputBlockCancel
+// --------------------------------------------------------------------------
+//
+void CCCAppCommLauncherContainer::AknInputBlockCancel()
+     {
+     iInputBlocker = NULL;
+     }
 // End of File
--- a/phonebookui/Phonebook2/ccapplication/ccacommlauncherplugin/src/ccappcommlaunchermenuhandler.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ccapplication/ccacommlauncherplugin/src/ccappcommlaunchermenuhandler.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -544,23 +544,27 @@
         TPtrC8 contactLink = param->Value().AsData();
 
         // Update the CCA parameter contact data
-        HBufC16* link16 = HBufC16::NewLC( contactLink.Length() );
-        link16->Des().Copy( contactLink );
-        iPlugin.AppEngine()->Parameter().SetContactDataL( link16->Des() );
-        // Set contact data flag to EContactLink, because the parameters returned from 
-        // phonebook AIW provider have conatct link but not contact id.
-        iPlugin.AppEngine()->Parameter().SetContactDataFlag( MCCAParameter::EContactLink );
-        CleanupStack::PopAndDestroy(1); // link16
+        TInt length = contactLink.Length();
+        if ( length > 0 )
+            {
+            HBufC16* link16 = HBufC16::NewLC( length );
+            link16->Des().Copy( contactLink );
+            iPlugin.AppEngine()->Parameter().SetContactDataL( link16->Des() );
+            // Set contact data flag to EContactLink, because the parameters returned from 
+            // phonebook AIW provider have conatct link but not contact id.
+            iPlugin.AppEngine()->Parameter().SetContactDataFlag( MCCAParameter::EContactLink );
+            CleanupStack::PopAndDestroy(1); // link16
 
-        // Inform the app engine of the contact event
-        iPlugin.AppEngine()->CCAppContactEventL();
+            // Inform the app engine of the contact event
+            iPlugin.AppEngine()->CCAppContactEventL();
 
-        // Update the commlauncher the UI contact data
-        iPlugin.ContactHandler().RefetchContactL();
-        iPlugin.Container().ContactsChangedL();
-        
-        //Update the Store
-        SetContactStore(iPlugin.ContactHandler().ContactStore());
+            // Update the commlauncher the UI contact data
+            iPlugin.ContactHandler().RefetchContactL();
+            iPlugin.Container().ContactsChangedL();
+            
+            //Update the Store
+            SetContactStore(iPlugin.ContactHandler().ContactStore());
+            }
         }
 
     if (errParam)
--- a/phonebookui/Phonebook2/ccapplication/ccacommlauncherplugin/tsrc/ut_commlaunchercontacthandler/inc/ccappcommlauncherheaders.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ccapplication/ccacommlauncherplugin/tsrc/ut_commlaunchercontacthandler/inc/ccappcommlauncherheaders.h	Thu Aug 19 09:41:07 2010 +0300
@@ -30,7 +30,7 @@
 #include "t_ccappcmscontactfetcher.h"
 #include "t_testsingleton.h"
 #include "phonebookPrivateCRKeys.h"
-
+#include <e32hashtab.h>
 class CCmsContactFieldInfo;
 class MCCAppContactFieldDataObserver;
 
--- a/phonebookui/Phonebook2/ccapplication/ccadetailsviewplugin/src/ccappdetailsviewlistboxmodel.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ccapplication/ccadetailsviewplugin/src/ccappdetailsviewlistboxmodel.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -698,7 +698,12 @@
                 UpdateMSKinCbaL();
         );
 
-    SetFocusedListIndex(iInitialFocusIndex);
+    // check if any item highlighted
+    TBool highLightEnabled = iListBox.IsHighlightEnabled();
+    if ( !highLightEnabled )
+        {
+        SetFocusedListIndex(iInitialFocusIndex);
+        }
 
     /*if (!iXspIdModifyState)
      {
--- a/phonebookui/Phonebook2/ccapplication/inc/ccalogger.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/ccapplication/inc/ccalogger.h	Thu Aug 19 09:41:07 2010 +0300
@@ -134,19 +134,20 @@
 
 /**
  * PERFORMANCE LOGGINS
- * 
+ * Logging is down only in debug, to get the log files,
+ * need to enable the _DEBUG marco first.
+ *   
  * OPTIONS: 
  * PERF_LOGGING -> 12 different points where performance is measured. (c:\logs\perflogger.txt) 
- * http://presenceprojects/trac/wiki/PerfLogging
- * 
+ *                 http://presenceprojects/trac/wiki/PerfLogging
  * PERF_LAUNCH -> For test guys (c:\logs\perflaunch.txt)
  * 
  */
 
-#undef PERF_LOGGING
+#ifdef _DEBUG   
+#define PERF_LOGGING
 #define PERF_LAUNCH 
-
-
+#endif //_DEBUG
 
 
 #ifdef PERF_LOGGING
Binary file phonebookui/Phonebook2/conf/phonebook2.confml has changed
Binary file phonebookui/Phonebook2/conf/phonebook2_101f8794.crml has changed
--- a/phonebookui/Phonebook2/group/Pbk2CommandsExtension.mmp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/group/Pbk2CommandsExtension.mmp	Thu Aug 19 09:41:07 2010 +0300
@@ -87,7 +87,7 @@
 END
 
 // Include paths
-USERINCLUDE     ../CommandsExtension/inc
+USERINCLUDE     ../CommandsExtension/inc ../Commands/inc
 SYSTEMINCLUDE   ../inc
 SYSTEMINCLUDE     /epoc32/include/ecom  //RCL_ADD
 
Binary file phonebookui/Phonebook2/help/data/xhtml.zip has changed
--- a/phonebookui/Phonebook2/inc/CPbk2FetchDlg.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/inc/CPbk2FetchDlg.h	Thu Aug 19 09:41:07 2010 +0300
@@ -159,6 +159,14 @@
          */
         IMPORT_C void AcceptDelayedFetchL(
                 const TDesC8& aContactLink );
+        
+        /**
+         * Unmarks the given contact as selected.
+         *
+         * @param aContactLink  Link to a contact to select.
+         */
+        IMPORT_C void DenyDelayedFetchL(
+                const TDesC8& aContactLink );
 
     public: // From CEikDialog
         IMPORT_C TInt ExecuteLD();
@@ -204,6 +212,7 @@
         void SelectContactL(
                 const MVPbkContactLink& aLink,
                 TBool aSelected );
+        TBool IsSelectPermitted();
         
     private: // From MPbk2StoreConfigurationObserver
     	void ConfigurationChanged();
@@ -312,6 +321,8 @@
         CPbk2NamesListControl* iNamesListControl;
         /// Not own: Group list control
         CPbk2NamesListControl* iGroupListControl;
+        /// Is selection permitted
+        TBool iSelectPermitted;
     };
 
 #endif // CPBK2FETCHDLG_H
--- a/phonebookui/Phonebook2/inc/CPbk2NamesListControl.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/inc/CPbk2NamesListControl.h	Thu Aug 19 09:41:07 2010 +0300
@@ -32,6 +32,7 @@
 #include <aknsfld.h>
 #include <eiklbo.h>
 #include "CPbk2ControlContainer.h"
+#include <aknmarkingmodeobserver.h>
 
 // FORWARD DECLARATIONS
 class MPbk2NamesListState;
@@ -78,7 +79,8 @@
                               public MEikListBoxObserver,
                               public MPbk2ControlContainerForegroundEventObserver,
                               public MPbk2CommandItemUpdater,
-                              public MVPbkContactViewObserverExtension 
+                              public MVPbkContactViewObserverExtension, 
+                              public MAknMarkingModeObserver
     {
     public: // Enumerations
 
@@ -129,27 +131,27 @@
                 CPbk2StorePropertyArray& aStoreProperties );
         
         /**
-		* Creates a new instance of this class.
-		*
-		* @param aResourceId       Id of the resource where the control
-		*                          is defined in.
-		* @param aContainer        This control's container.
-		* @param aManager          Virtual Phonebook contact manager.
-		* @param aView             The contact view.
-		* @param aNameFormatter    Name formatter.
-		* @param aStoreProperties  An array containg properties
-		*                          for the stores that are shown.
-		* @param aThumbManager	   Thumbnail manager for social phonebook	//TODO
-		* @return A new instance of this class.
-		*/
-	   IMPORT_C static CPbk2NamesListControl* NewL(
-			   TInt aResourceId,
-			   const CCoeControl* aContainer,
-			   CVPbkContactManager& aManager,
-			   MVPbkContactViewBase& aView,
-			   MPbk2ContactNameFormatter& aNameFormatter,
-			   CPbk2StorePropertyArray& aStoreProperties,
-			   CPbk2ThumbnailManager* aThumbManager );
+        * Creates a new instance of this class.
+        *
+        * @param aResourceId       Id of the resource where the control
+        *                          is defined in.
+        * @param aContainer        This control's container.
+        * @param aManager          Virtual Phonebook contact manager.
+        * @param aView             The contact view.
+        * @param aNameFormatter    Name formatter.
+        * @param aStoreProperties  An array containg properties
+        *                          for the stores that are shown.
+        * @param aThumbManager       Thumbnail manager for social phonebook    //TODO
+        * @return A new instance of this class.
+        */
+       IMPORT_C static CPbk2NamesListControl* NewL(
+               TInt aResourceId,
+               const CCoeControl* aContainer,
+               CVPbkContactManager& aManager,
+               MVPbkContactViewBase& aView,
+               MPbk2ContactNameFormatter& aNameFormatter,
+               CPbk2StorePropertyArray& aStoreProperties,
+               CPbk2ThumbnailManager* aThumbManager );
 
         /**
          * Constructor. Defined as public for custom control needs.
@@ -245,8 +247,8 @@
         /**
          * For special case: Call this function to skip showing the 
          * blocking progress note when mass update is going on in nameslistview.
-		 * When done, MassUpdateSkipProgressNote(EFalse) must always be
-		 * called to reset back to original state (even if a Leave would happen in between) 
+         * When done, MassUpdateSkipProgressNote(EFalse) must always be
+         * called to reset back to original state (even if a Leave would happen in between) 
          * @param aSkip - ETrue if progress note should not be displayed. EFalse reset to normal.
          */
         IMPORT_C void MassUpdateSkipProgressNote( TBool aSkip );
@@ -390,6 +392,25 @@
     public: // from MAdaptiveSearchTextObserver
 
         void AdaptiveSearchTextChanged( CAknSearchField* aSearchField );
+
+    public: // From MAknMarkingModeObserver 
+            
+        /**
+         * This method is called when marking mode is activated or deactivated.
+         * 
+         * @param aActivated @c ETrue if marking mode was activate, @c EFalse
+         *                   if marking mode was deactivated.
+         */
+        void MarkingModeStatusChanged( TBool aActivated );
+
+        /**
+         * This method is called just before marking mode is closed. Client can 
+         * either accept or decline closing.
+         * 
+         * @return @c ETrue if marking mode should be closed, otherwise @c EFalse.
+         */
+        TBool ExitMarkingMode() const;
+        
     private: // Implementation
         
         /**
@@ -443,7 +464,16 @@
         void RestoreMarkedContactsL();
         void ClearMarkedContactsInfo();
         
+    public:
+        inline void SetMarkingMode( TBool aActived )
+            {
+            iMarkingModeOn = aActived;
+            }
         
+        inline TBool GetMarkingMode() const
+            {
+            return iMarkingModeOn;
+            }
         
     private: // Data
         /// Ref: Current state
@@ -500,17 +530,19 @@
         // Wheter this control owns the thumbnail manager (iThumbManager) or not 
         TBool iOwnThumbManager;
         //OWN: double list box "handle"
-        CPbk2ContactViewDoubleListBox* 	iDoubleListBox;
+        CPbk2ContactViewDoubleListBox* iDoubleListBox;
         
         //Own: Selected/Marked Contacts
-        MVPbkContactLinkArray* iSelectedLinkArray;      
+        MVPbkContactLinkArray* iSelectedLinkArray;
            
         //Own: Background Task Handler     
         CPbk2NamesListControlBgTask* iBgTask;
         //Own: Mass update checker/handler
         CPbk2HandleMassUpdate* iCheckMassUpdate;
         //Own: Open Cca is in progress
-        TBool iOpeningCca;        
+        TBool iOpeningCca;
+        // Flag to indicate marking mode is active
+        TBool iMarkingModeOn;
     };
 
 #endif // CPBK2NAMESLISTCONTROL_H
--- a/phonebookui/Phonebook2/inc/MPbk2FetchDlg.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/inc/MPbk2FetchDlg.h	Thu Aug 19 09:41:07 2010 +0300
@@ -118,6 +118,13 @@
         virtual void SelectContactL(
                 const MVPbkContactLink& aLink,
                 TBool aSelected ) = 0;
+        /**
+         * Check whether selection is permitted
+         * 
+         * @return              Check result
+         */
+        virtual TBool IsSelectPermitted() = 0;
+
 
     protected: // Protected functions
 
--- a/phonebookui/Phonebook2/inc/cpbk2commandactivator.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/inc/cpbk2commandactivator.h	Thu Aug 19 09:41:07 2010 +0300
@@ -52,7 +52,7 @@
         void ExecuteLD();
         void ResetUiControl(MPbk2ContactUiControl& aUiControl);
         void AddObserver( MPbk2CommandObserver& aObserver );
-                     
+        TAny* CommandExtension(TUid /*aExtensionUid*/);                     
     private: // MPbk2CommandObserver
         void CommandFinished( const MPbk2Command& aCommand );
 
--- a/phonebookui/Phonebook2/xSPExtensionManager/src/CxSPViewActivator.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/phonebookui/Phonebook2/xSPExtensionManager/src/CxSPViewActivator.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -21,6 +21,7 @@
 #include "CxSPViewActivator.h"
 #include <CxSPViewData.h>
 #include "CxSPViewInfo.h"
+#include <Pbk2ViewId.hrh>
 
 
 // System includes
@@ -137,17 +138,34 @@
             newViewId = viewID;
             }
     
-        aMessage.Complete(err);
+        // If err is KErrNone or KErrNotFound, complete client's request with KErrNone. 
+        // The reason is even if client passed an invalid view id to xsp server, 
+        // the server will launch phonebook namelist view instead. 
+        if ( KErrNone == err || KErrNotFound == err )
+        	{
+            aMessage.Complete( KErrNone );
+        	}
+        else
+        	{
+            aMessage.Complete( err );
+        	}
     
-        if(err == KErrNone)
+        if( err == KErrNone )
             {
             // Make view id
-            const TVwsViewId viewId(TUid::Uid(KUid), TUid::Uid(newViewId));
+            const TVwsViewId viewId( TUid::Uid( KUid ), TUid::Uid( newViewId ) );
             // Activate the view
             static_cast<CAknViewAppUi*>(CCoeEnv::Static()->AppUi())->ActivateViewL(
                                                         viewId, CPbk2ViewState::Uid(), *paramBuf);
             }
-    
+        else if ( err == KErrNotFound )
+        	{
+            // Activate phonebook namelist view if valid view id can't be found
+            const TVwsViewId viewId( TUid::Uid( KUid ), TUid::Uid( EPbk2NamesListViewId ) );
+            static_cast<CAknViewAppUi*>( CCoeEnv::Static()->AppUi() )->ActivateViewL(
+                                                        viewId, CPbk2ViewState::Uid(), *paramBuf );        
+        	}
+        
         CleanupStack::PopAndDestroy();  // paramBuf;
         }
     }
Binary file phonebookui/Speeddial/help/data/xhtml.zip has changed
--- a/predictivesearch/PcsAlgorithm/Algorithm1/inc/CPcsAlgorithm1.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm1/inc/CPcsAlgorithm1.h	Thu Aug 19 09:41:07 2010 +0300
@@ -308,12 +308,19 @@
         /**
         * launch plugins by idle
         */
-         void DoLaunchPluginsL();
+        void DoLaunchPluginsL();
         
         /**
         * launch plugins
         */
-         static TInt DoLaunchPluginsL(TAny* aPtr);
+        static TInt DoLaunchPluginsL(TAny* aPtr);
+
+        /**
+        * Get the Adaptive Grid data for one or more URIs
+        */
+        void GetAdaptiveGridFromCacheL( const MDesCArray& aURIs,
+                                        const TBool aCompanyName,
+                                        TDes& aAdaptiveGrid );
 
     private:
     
--- a/predictivesearch/PcsAlgorithm/Algorithm1/src/CPcsAlgorithm1.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm1/src/CPcsAlgorithm1.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -908,68 +908,115 @@
 // ----------------------------------------------------------------------------
 void CPcsAlgorithm1::UpdateCachingStatus(TDesC& aDataStore, TInt aStatus)
 {
-	PRINT ( _L("Enter CPcsAlgorithm1::UpdateCachingStatus") );
-	
-	// Handle data store update events
-	if ( aStatus == ECacheUpdateContactRemoved ||
-	     aStatus == ECacheUpdateContactModified ||
-	     aStatus == ECacheUpdateContactAdded )
-	    {
+    PRINT ( _L("Enter CPcsAlgorithm1::UpdateCachingStatus") );
+    PRINT2 ( _L("CPcsAlgorithm1::UpdateCachingStatus: Request received for URI=%S with status=%d"),
+             &aDataStore, aStatus );
+
+    // Handle data store update events
+    if ( aStatus == ECacheUpdateContactRemoved ||
+         aStatus == ECacheUpdateContactModified ||
+         aStatus == ECacheUpdateContactAdded )
+        {
         HandleCacheUpdated( static_cast<TCachingStatus>(aStatus) );
         return;
-	    }
-	
-	// If not a cache update event, then this event is related to the initial
-	// cache construction.
-	TInt index = FindStoreUri(aDataStore);
-	
-	iPcsCache[index]->UpdateCacheStatus(aStatus);
-	
-	// Check if any error occurred
-	// If so, update the cache status, Set the property and return
-	if ( aStatus < 0 )
-	{
-		SetCachingError(aDataStore, aStatus);
-		//return;
-	}
-	
-	// No error occurred
-	TCachingStatus status = ECachingComplete;
-	TBool atLeastOneStoreCachingCompleteWithErrors(EFalse);
-	for ( TInt i = 0; i < iPcsCache.Count(); i++ )
-	{
-		if ( iPcsCache[i]->GetCacheStatus() == ECachingComplete )
-		{
-	        continue;
-	    }
-		else if ( iPcsCache[i]->GetCacheStatus() == ECachingCompleteWithErrors )
-		{
-            atLeastOneStoreCachingCompleteWithErrors = ETrue;
-            continue;
-		}
-		else
-		{
-			status = ECachingInProgress;
-			break;
-		}
-	}
-	
-	if ( status == ECachingComplete )
-	{
-		// See if any error occurred while caching
-		// If so, change the status to ECachingCompleteWithErrors
-		if (( iCacheError != KErrNone ) || (atLeastOneStoreCachingCompleteWithErrors))
-			status = ECachingCompleteWithErrors;
-	}
-	
-	// Check if status changed
-	if ( status != iCacheStatus )
-	{
-		iCacheStatus = status;
-		RProperty::Set(KPcsInternalUidCacheStatus, EPsKeyCacheStatus, iCacheStatus );
-	}
-	
-	PRINT ( _L("End CPcsAlgorithm1::UpdateCachingStatus") );
+        }
+
+    // If not a cache update event, then this event is related to the initial
+    // cache construction.
+
+    // Check if any error occurred and update the cache error
+    if ( aStatus < 0 )
+    {
+        SetCachingError(aDataStore, aStatus);
+    }
+    else
+    {
+        TInt index = FindStoreUri(aDataStore);
+        iPcsCache[index]->UpdateCacheStatus(aStatus);
+    }
+
+    TCachingStatus status = ECachingNotStarted;
+    TUint countNotStarted = 0;
+    TUint countInProgress = 0;
+    TUint countCompleted = 0;
+    TUint countCompletedWithErrors = 0;
+    TInt cacheCount = iPcsCache.Count();
+    for ( TInt i = 0; i < cacheCount; i++ )
+    {
+        PRINT3 ( _L("CPcsAlgorithm1::UpdateCachingStatus: URI[%d]=%S, cache status=%d"),
+                 i, &iPcsCache[i]->GetURI(), iPcsCache[i]->GetCacheStatus() );
+
+        switch ( iPcsCache[i]->GetCacheStatus() )
+        {
+            case ECachingNotStarted:         
+            {
+                countNotStarted++;          
+                break;
+            }
+            case ECachingInProgress:         
+            {
+                countInProgress++;         
+                break;
+            }
+            case ECachingComplete:           
+            {
+                countCompleted++;           
+                break;
+            }
+            case ECachingCompleteWithErrors: 
+            {
+                countCompletedWithErrors++; 
+                break;
+            }
+            default:                         
+            { 
+                // Default completed state
+                countCompleted++;           
+                break;
+            }
+        }
+    }
+
+    // Calculate cumulative status according to single caches statuses
+    if ( countCompleted > 0 && ( countCompleted + countNotStarted ) == cacheCount )
+    {
+        // If at least one caching is finished
+        // set status to ECachingComplete or ECachingCompleteWithErrors
+        // according to iCacheError
+        status = ( iCacheError == KErrNone ) ? ECachingComplete : ECachingCompleteWithErrors;
+    }
+    else if ( countInProgress > 0 )
+    {
+        // Else if at least one caching is in progress,
+        // set status to ECachingInProgress
+        status = ECachingInProgress;
+    }
+    else if ( countCompletedWithErrors > 0 )
+    {
+        // Else if at least one caching is completed with errors, 
+        //set status to ECachingCompleteWithErrors
+        status = ECachingCompleteWithErrors;
+    }
+    else
+    {
+        // countNotStarted == cacheCount
+        // status is set to default ECachingNotStarted
+    }
+
+    PRINT1 ( _L("CPcsAlgorithm1::UpdateCachingStatus: Cumulative caching status is %d"),
+             status );
+
+    // Check if status changed
+    if ( status != iCacheStatus )
+    {
+        PRINT2 ( _L("CPcsAlgorithm1::UpdateCachingStatus: Cumulative caching changed: %d -> %d"),
+                 iCacheStatus, status );
+
+        iCacheStatus = status;
+        RProperty::Set(KPcsInternalUidCacheStatus, EPsKeyCacheStatus, iCacheStatus );
+    }
+
+    PRINT( _L("End CPcsAlgorithm1::UpdateCachingStatus") );
 }
 
 // ----------------------------------------------------------------------------
@@ -978,7 +1025,7 @@
 // ----------------------------------------------------------------------------
 void CPcsAlgorithm1::SetCachingError(const TDesC& aDataStore, TInt aError)
 {
-    PRINT2 ( _L("SetCachingError::URI %S ERROR %d"), &aDataStore, aError );
+    PRINT2 ( _L("CPcsAlgorithm1::SetCachingError: URI=%S, ERROR=%d"), &aDataStore, aError );
 
     iCacheError = aError;
     RProperty::Set( KPcsInternalUidCacheStatus, EPsKeyCacheError, iCacheError );
@@ -1326,9 +1373,35 @@
     PRINT1 ( _L("CPcsAlgorithm1::GetAdaptiveGridL. Request of Adaptive Grid for %d URI(s)"),
              aURIs.MdcaCount() );
 
+    if ( iCacheStatus != ECachingComplete )
+        {
+        PRINT ( _L("CPcsAlgorithm1::GetAdaptiveGridL: PCS Caching is not ready, returning empty Adaptive Grid") );
+        aAdaptiveGrid.Zero();
+        }
+    else
+        {
+        GetAdaptiveGridFromCacheL( aURIs, aCompanyName, aAdaptiveGrid );
+        }
+
+    PRINT ( _L("End CPcsAlgorithm1::GetAdaptiveGridL") );
+}
+
+// ----------------------------------------------------------------------------
+// CPcsAlgorithm1::GetAdaptiveGridFromCacheL
+// 
+// ----------------------------------------------------------------------------
+void CPcsAlgorithm1::GetAdaptiveGridFromCacheL( const MDesCArray& aURIs,
+                                                const TBool aCompanyName,
+                                                TDes& aAdaptiveGrid )
+{
+    PRINT ( _L("Enter CPcsAlgorithm1::GetAdaptiveGridFromCacheL") );
+
+    PRINT1 ( _L("CPcsAlgorithm1::GetAdaptiveGridFromCacheL. Request of Adaptive Grid for %d URI(s)"),
+             aURIs.MdcaCount() );
+
     RArray<TInt> cacheIds;
     CleanupClosePushL( cacheIds );
-
+    
     // Create the list of the cache indexes that will form the Adaptive Grid
     for ( TInt i=0; i < aURIs.MdcaCount(); i++ )
     {
@@ -1337,7 +1410,7 @@
         // If URI is a group URI skip it
         if ( CPcsAlgorithm1Utils::IsGroupUri( uri ) )
         {
-            PRINT1 ( _L("CPcsAlgorithm1::GetAdaptiveGridL. Adaptive Grid for URI \"%S\" is not supported. Skipping"),
+            PRINT1 ( _L("CPcsAlgorithm1::GetAdaptiveGridFromCacheL. Adaptive Grid for URI \"%S\" is not supported. Skipping"),
                      &uri );
             continue;
         }
@@ -1345,18 +1418,18 @@
         TInt cacheIndex = GetCacheIndex( uri );
         if ( cacheIndex == KErrNotFound )
         {
-            PRINT1 ( _L("CPcsAlgorithm1::GetAdaptiveGridL. Cache for URI \"%S\" doesn't exist"),
+            PRINT1 ( _L("CPcsAlgorithm1::GetAdaptiveGridFromCacheL. Cache for URI \"%S\" doesn't exist"),
                      &uri );
             continue;
         }
 
-        PRINT1 ( _L("CPcsAlgorithm1::GetAdaptiveGridL. Cache for URI \"%S\" will be used to form the Adaptive Grid"),
+        PRINT1 ( _L("CPcsAlgorithm1::GetAdaptiveGridFromCacheL. Cache for URI \"%S\" will be used to form the Adaptive Grid"),
                  &uri );
 
         cacheIds.AppendL( cacheIndex );
     }
 
-    PRINT1 ( _L("CPcsAlgorithm1::GetAdaptiveGridL. Number of caches that will be used to form the grid is %d"),
+    PRINT1 ( _L("CPcsAlgorithm1::GetAdaptiveGridFromCacheL. Number of caches that will be used to form the grid is %d"),
              cacheIds.Count( ) );
 
     // Create the Adaptive Grid from the cache(s)
@@ -1368,7 +1441,7 @@
         // Get the Adaptive Grid    
         cache->GetAdaptiveGridL( aCompanyName, aAdaptiveGrid );
 
-        PRINT1 ( _L("CPcsAlgorithm1::GetAdaptiveGridL. Adaptive Grid: \"%S\" (No merge was needed)"),
+        PRINT1 ( _L("CPcsAlgorithm1::GetAdaptiveGridFromCacheL. Adaptive Grid: \"%S\" (No merge was needed)"),
                  &aAdaptiveGrid );
         }
     else if ( cacheIds.Count() > 1 ) // Merge if we have more than one cache
@@ -1394,7 +1467,7 @@
             gridOnePtr.Zero();
             cache->GetAdaptiveGridL( aCompanyName, gridOnePtr );
 
-            PRINT2 ( _L("CPcsAlgorithm1::GetAdaptiveGridL. Adaptive Grid for cache \"%S\" is \"%S\""),
+            PRINT2 ( _L("CPcsAlgorithm1::GetAdaptiveGridFromCacheL. Adaptive Grid for cache \"%S\" is \"%S\""),
                      &cache->GetURI(), &gridOnePtr );
 
             // Loop through the characters of the Adaptive Grid for the cache
@@ -1421,7 +1494,7 @@
             aAdaptiveGrid.Append( gridAll[i] );
             }
 
-        PRINT1 ( _L("CPcsAlgorithm1::GetAdaptiveGridL. Adaptive Grid: \"%S\" (Merge was done)"),
+        PRINT1 ( _L("CPcsAlgorithm1::GetAdaptiveGridFromCacheL. Adaptive Grid: \"%S\" (Merge was done)"),
                  &aAdaptiveGrid );
         
         CleanupStack::PopAndDestroy( gridOne );
@@ -1430,7 +1503,7 @@
 
     CleanupStack::PopAndDestroy( &cacheIds ); // Close
     
-    PRINT ( _L("End CPcsAlgorithm1::GetAdaptiveGridL") );
+    PRINT ( _L("End CPcsAlgorithm1::GetAdaptiveGridFromCacheL") );
 }
 
 // ---------------------------------------------------------------------------------
--- a/predictivesearch/PcsAlgorithm/Algorithm2/group/PcsAlgorithm2.mmp	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/group/PcsAlgorithm2.mmp	Thu Aug 19 09:41:07 2010 +0300
@@ -40,8 +40,8 @@
 SOURCE          CPcsPoolElement.cpp
 SOURCE          CPcsKeyMap.cpp
 SOURCE          CPsDataPluginInterface.cpp
-SOURCE          FindUtilChineseECE.cpp 
-SOURCE          chinesefindutils.cpp
+SOURCE          chinesefindutils.cpp 
+SOURCE          FindUtilChineseECE.cpp
 
 USERINCLUDE     ../inc
 USERINCLUDE     ../../inc
@@ -65,3 +65,4 @@
 LIBRARY         fepbase.lib 
 LIBRARY         centralrepository.lib
 LIBRARY         findutil.lib
+LIBRARY         pbkeng.lib
--- a/predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsAlgorithm2.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsAlgorithm2.h	Thu Aug 19 09:41:07 2010 +0300
@@ -54,8 +54,7 @@
 // CLASS DECLARATION
 class CPcsAlgorithm2 : public CPcsPlugin,
 public MDataStoreObserver,
-public MStoreListObserver,
-public MFindStringConverter
+public MStoreListObserver
     {
 public: 
 
@@ -80,7 +79,7 @@
     void PerformSearchL(const CPsSettings& aPcsSettings,
         CPsQuery& aCondition,
         RPointerArray<CPsClientData>& aData,
-        RPointerArray<CPsPattern>& aPattern);							
+        RPointerArray<CPsPattern>& aPattern);
 
     /**
      * Search Function for input string
@@ -88,15 +87,15 @@
     void SearchInputL(CPsQuery& aSearchQuery,
         TDesC& aSearchData,
         RPointerArray<TDesC>& aMatchSet,
-        RArray<TPsMatchLocation>& aMatchLocation );  
+        RArray<TPsMatchLocation>& aMatchLocation );
 
     
     /**
     * Performs search on a input string, and return result also as a string 
     */
     void  SearchMatchStringL( CPsQuery& aSearchQuery,
-                              TDesC& aSearchData,
-                              TDes& aMatch );     
+                                TDesC& aSearchData,
+                                TDes& aMatch );
     
     /**
      * Returns ETrue if this language is supported
@@ -118,12 +117,6 @@
      */
     void ChangeSortOrderL(TDesC& aURI, RArray<TInt>& aSortOrder);
 
-    /**
-     * Get the Adaptive Grid for one or more URIs
-     */
-    void GetAdaptiveGridL( const MDesCArray& aURIs,
-                           const TBool aCompanyName,
-                           TDes& aAdaptiveGrid );
 
     // --------------------------------------------------------------------
 
@@ -134,22 +127,29 @@
     /** 
      * Add a contact to the cache
      */
-    void AddData ( TDesC& aDataStore, CPsData* aData);
+    void AddData( TDesC& aDataStore, CPsData* aData );
 
     /** 
-     * Remove a contact from the cache based on contact id		
+     * Remove a contact from the cache based on contact id
      */
-    void RemoveData ( TDesC& aDataStore, TInt aItemId );
+    void RemoveData( TDesC& aDataStore, TInt aItemId );
 
     /**
      *  Removes all the contacts from a particular datastore
      */
-    void RemoveAll ( TDesC& aDataStore);
+    void RemoveAll( TDesC& aDataStore );
 
     /**
      * Updates the caching status for a particular datastore
      */
     void UpdateCachingStatus(TDesC& aDataStore, TInt aStatus);
+    
+    /**
+    * Get the Adaptive Grid for one or more URIs
+    */
+    void GetAdaptiveGridL( const MDesCArray& aURIs,
+                           const TBool aCompanyName,
+                           TDes& aAdaptiveGrid );
 
     // --------------------------------------------------------------------
 
@@ -160,12 +160,12 @@
     /**
      * This method is called whenever any new store has been added
      */
-    void AddDataStore ( TDesC& aDataStore);
+    void AddDataStore( TDesC& aDataStore );
 
     /**
      * This method is called whenever a data store is removed
      */
-    void RemoveDataStore ( TDesC& aDataStore);
+    void RemoveDataStore( TDesC& aDataStore );
 
     // --------------------------------------------------------------------
 
@@ -174,7 +174,7 @@
     /**
      * Returns the array index of cache (in iPcsCache) for a datastore
      */
-    TInt GetCacheIndex(TDesC& aDataStore);	
+    TInt GetCacheIndex(const TDesC& aDataStore);
 
     /** 
      * Return the cache instance at a specific array index
@@ -190,8 +190,14 @@
     inline CPcsKeyMap* GetKeyMap() 
         { 
         return iKeyMap; 
-        };
+        }
 
+    inline CFindUtilChineseECE* FindUtilECE()
+        {
+        return iFindUtilECE;
+        }
+
+    void ReconstructCacheDataL();
 
 private:
 
@@ -215,48 +221,54 @@
     void DefinePropertyL( TPcsInternalKeyCacheStatus aPsKey );
 
     /**
-     * Replace occurance of "0" in ITU-T mode with space
+     * Remove leading and trailing spaces of search query
      */
-    TBool  ReplaceZeroWithSpaceL(CPsQuery& aQuery);
+    void RemoveSpacesL( CPsQuery& aQuery );
+
+    /**
+     * Replace occurances of "0" in predictive mode with space
+     * if those are on the same button
+     */
+    TBool  ReplaceZeroWithSpaceL( CPsQuery& aQuery );
 
     /**
      * Search function helper
      */
-    void  DoSearchL(const CPsSettings& aPcsSettings,
-        CPsQuery& aCondition,
-        RPointerArray<CPsData>& searchResults,
-        RPointerArray<CPsPattern>& searchSeqs );		                       
+    void  DoSearchL( const CPsSettings& aPcsSettings,
+                     CPsQuery& aCondition,
+                     RPointerArray<CPsData>& aSearchResults,
+                     RPointerArray<CPsPattern>& aSearchSeqs );
 
     /**                
      * Search function helper
      */
-    void  DoSearchInputL(CPsQuery& aQuery,
-        TDesC& aData,
-        RPointerArray<TDesC>& searchSeqs,
-        RArray<TPsMatchLocation>& aMatchLocation );	 
+    void  DoSearchInputL( CPsQuery& aQuery,
+                          const TDesC& aData,
+                          RPointerArray<TDesC>& aSearchSeqs,
+                          RArray<TPsMatchLocation>& aMatchLocation );
 
     /**
      * Returns the index corresponding a URI in iDataStoreUri
      */
-    TInt FindStoreUri ( TDesC& aDataStoreUri );
+    TInt FindStoreUri( const TDesC& aDataStoreUri );
 
     /**
      * Function to return all cached content
      */
-    void GetAllContentsL(const CPsSettings& aPcsSettings,	                    
-        RPointerArray<CPsData>& searchResults );
+    void GetAllContentsL( const CPsSettings& aPcsSettings,
+                          RPointerArray<CPsData>& aSearchResults );
 
     /**
      * Checks if search is on groups
-     * Return ETrue if there is a valid group URI        
+     * Return ETrue if there is a valid group URI
      */
-    TBool IsGroupSearchL ( CPsSettings& aSettings,
-        RArray<TInt>& aGroupIdArray );						 
+    TBool IsGroupSearchL( CPsSettings& aSettings,
+        RArray<TInt>& aGroupIdArray );
 
     /**
      * Utility function to replace groups uri with that of contacts uri
      */
-    void ReplaceGroupsUriL ( CPsSettings& aSettings );							 
+    void ReplaceGroupsUriL( CPsSettings& aSettings );
 
     /**
      * Filters the search results array for groups
@@ -266,8 +278,8 @@
 
     /**
      * Get the list of contact ids that belong to a group.
-     */							 	           
-    void GetContactsInGroupL ( TInt aGroupId, 
+     */
+    void GetContactsInGroupL( TInt aGroupId, 
         RArray<TInt>& aGroupContactIds );
 
     /**
@@ -275,31 +287,30 @@
      * @param aURI - The data store URI for which sort order is required
      * @param aSortOrder - The persisted sort order from the cenrep
      */
-    void ReadSortOrderFromCenRepL ( TDesC& aURI, 
+    void ReadSortOrderFromCenRepL( const TDesC& aURI, 
         RArray<TInt>& aSortOrder );
 
     /** Write sort order for a data store to the central repository
      * @param aURI - The data store URI for which sort order is to be persisted
      * @param aSortOrder - The sort order to be persisted	
      */
-    void WriteSortOrderToCenRepL ( TDesC& aURI, 
-        RArray<TInt>& aSortOrder );	
+    void WriteSortOrderToCenRepL( const TDesC& aURI, 
+        RArray<TInt>& aSortOrder );
 
     /**
      * Utility function that sets the caching error value
-     */                             
-    void SetCachingError ( TDesC& aDataStore, 
-        TInt aError );	
+     */
+    void SetCachingError( const TDesC& aDataStore, TInt aError );
 
     /**
-     * Write the content required by client 
+     * Write the content required by client
      */
-    CPsClientData* WriteClientDataL ( CPsData& aPsData );	
+    CPsClientData* WriteClientDataL( CPsData& aPsData );
 
     /**
      * Function to return data base URI for an internal identifier
-     */		                     
-    TDesC& GetUriForIdL( TUint8 aUriId );	
+     */
+    const TDesC& GetUriForIdL( TUint8 aUriId );
 
     /**
      * Inform clients about update happened on the cache
@@ -316,45 +327,18 @@
     */
      static TInt DoLaunchPluginsL(TAny* aPtr);
 
-public:    
-
-    inline TInt GetFirstNameIndex() 
-        { 
-        return iFirstNameIndex; 
-        }
-
-    inline TInt GetLastNameIndex()
-        { 
-        return iLastNameIndex; 
-        }
-
-    inline CFindUtilChineseECE* FindUtilECE()
-        {
-        return iFindUtilECE;
-        }
-
-    inline CFindUtil* FindUtil()
-        {
-        return iFindUtil;
-        }
-
-    void ReconstructCacheDataL();
-
-public: // From MFindStringConverter
-    void Converter(const TDesC& aSourStr, TDes& aDestStr);
-
 private:
 
     /**
      * Instance of contacts cache
      * Own
      */
-    RPointerArray<CPcsCache>   iPcsCache; 
+    RPointerArray<CPcsCache> iPcsCache;
 
     /**
      * Keeps the count of caches
      */
-    TUint8 iCacheCount; 
+    TUint8 iCacheCount;
 
     /**
      * Instance of key map
@@ -387,13 +371,6 @@
     // Own: Find util used to match contacts and construct character grid
     CFindUtilChineseECE* iFindUtilECE;
 
-    // Own: Find util used to match contacts and construct character grid
-    CFindUtil* iFindUtil;
-
-    // keep the index for Firstname and Lastname
-    TInt iFirstNameIndex;
-    TInt iLastNameIndex;
-    
     /**
     * plugin laucher, make the plugin instantiation async
     */
--- a/predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsAlgorithm2FilterHelper.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsAlgorithm2FilterHelper.h	Thu Aug 19 09:41:07 2010 +0300
@@ -91,7 +91,7 @@
 		/**
 		 * 2nd phase construtor
 		 */
-		void ConstructL(TSortType aSortType);   
+		void ConstructL(TSortType aSortType);
 		
 		/**
 		* Adds each result into respective pool based on match pattern
@@ -102,7 +102,7 @@
 		* Searches for for aSeq in iMatchPatternDetails and returns index 
         * where input sequence is found. Returns -1 if not found
 		*/
-		TInt FindSequence(TDesC* aSeq);
+		TInt FindSequence(const TDesC& aSeq);
 		
 		
 		/**
@@ -110,19 +110,19 @@
         * and returns index where input sequence is found. 
         * Returns -1 if not found
 		*/
-		TInt FindSubSequence(TDesC* aSeq,TInt aPatternIndex);
+		TInt FindSubSequence(const TDesC& aSeq, TInt aPatternIndex);
 		
 		/**
 		* Creates the Matchpattern aSeq in  iMatchPatternDetails.
         * Returns the index of the sequence in iMatchPatternDetails
         */
-		TInt CreateMatchPatternDetailsAndPoolsL(TDesC* aSeq);
+		TInt CreateMatchPatternDetailsAndPoolsL(const TDesC& aSeq);
 		
 		/**
 		* Searches for all the subsequences of aSeq and updates the 
 		* aFirstOccrVal in iMatchPatternDetails.
         */
-		void UpdateForSubSequencesL(TDesC& aSeq,TInt aFirstOccrVal);
+		void UpdateForSubSequencesL(const TDesC& aSeq, TInt aFirstOccrVal);
 
 	private:
 		
--- a/predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsAlgorithm2Helper.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsAlgorithm2Helper.h	Thu Aug 19 09:41:07 2010 +0300
@@ -22,6 +22,7 @@
 #include <e32cmn.h>
 #include <e32math.h>
 #include <e32hashtab.h>
+#include <MPbkGlobalSetting.h> // For name order setting
 
 #include "CPcsPlugin.h"
 #include "CPsData.h"
@@ -36,7 +37,7 @@
 class CPsDataPluginInterface;
 
 // CLASS DECLARATION
-class CPcsAlgorithm2Helper : public CBase
+class CPcsAlgorithm2Helper : public CBase, private MPbkGlobalSettingObserver
     {
 public:
 
@@ -53,78 +54,52 @@
 private:
 
     /**
-     * Filter subset results for ITU-T Mode. Entire search query is 
-     * entered in ITU-T mode.
-     */
-    void FilterResultsL(CPcsAlgorithm2FilterHelper* aAlgorithmFilterHelper,
-                        RPointerArray<CPcsPoolElement>& searchSet,
-                        const TDesC& searchQuery, TBool isSearchInGroup,
-                        RArray<TInt>& aContactsInGroup);
-    /**
-     * Filter subset results for Qwerty Mode. Entire search query is 
-     * entered in Qwerty mode.
+     * Filter subset results for Mixed mode. Some portion of query can be in 
+     * ITU-T mode and some portion in Qwerty mode.
      */
-    void FilterResultsQwertyL(CPcsAlgorithm2FilterHelper* aAlgorithmFilterHelper,
-                              RPointerArray<CPcsPoolElement>& searchSet,
-                              const TDesC& searchQuery, TBool isSearchInGroup,
-                              RArray<TInt>& aContactsInGroup);
-
-    /**
-     * Filter subset results for Mixed mode. Some portion of query is in 
-     * ITU-T mode and some portion in Qwert mode.
-     */
-    void FilterResultsMixedL(CPcsAlgorithm2FilterHelper* aAlgorithmFilterHelper,
-                             RPointerArray<CPcsPoolElement>& searchSet, 
-                             CPsQuery& searchQuery, TBool isSearchInGroup, 
-                             RArray<TInt>& aContactsInGroup);
-
+    void FilterResultsSingleL(CPcsAlgorithm2FilterHelper* aAlgorithmFilterHelper,
+                              RPointerArray<CPcsPoolElement>& aSearchSet,
+                              CPsQuery& aSearchQuery,
+                              TUint8 aFilteredDataMatch,
+                              TBool aIsSearchInGroup,
+                              const RArray<TInt>& aContactsInGroup);
+    
     /**
-     * Convert the search query to a string.
-     * If the mode is ITU-T, character is converted to numeric.
-     * If the mode is Qwerty, character is retained as is.
+     * Create a buffer containing the first name and last name of a contact in the
+     * order specified in Phonebook settings.
      */
-    void ExtractQueryL(CPsQuery& aPsQuery, TDes& aOutput);
-
+    HBufC* CreateNameBufLC( const CPsData& aContactData, TInt aFirstNameIndex, TInt aLastNameIndex ) const;
+    
     /**
-     * Convert the input search query to a string.
-     * Mode is referred in the CPsQuery.
-     * If the mode is ITU-T, character is converted to numeric.
-     * If the mode is Qwerty, character is retained as is.
+     * Get and store the order of first and last name.
      */
-    void ExtractQueryL(TDesC& aInput, CPsQuery& aPsQuery, TDes& aOutput);
-
-public:
+    void UpdateNameOrderL();
 
+private: // from MPbkGlobalSettingObserver
     /**
-     * Search Function for ITU-T style
+     * React to change in Phonebook settings.
      */
-    void SearchITUL(const CPsSettings& aSettings, CPsQuery& aQuery,
-                    TBool isGroupSearch, RArray<TInt>& aContactsInGroup,
-                    RPointerArray<CPsData>& searchResults,
-                    RPointerArray<CPsPattern>& searchSeqs);
-
-    /**
-     * Search Function for QWERTY style
-     */
-    void SearchQWERTYL(const CPsSettings& aSettings, CPsQuery& aQuery,
-                       TBool isGroupSearch, RArray<TInt>& aContactsInGroup,
-                       RPointerArray<CPsData>& searchResults,
-                       RPointerArray<CPsPattern>& searchSeqs);
+    void SettingChangedL( MPbkGlobalSetting::TPbkGlobalSetting aKey );
+    
+public:
 
     /**
      * Search Function for mixed style
      * Some chars are entered in ITU-T and some in QWERTY
      */
-    void SearchMixedL(const CPsSettings& aSettings, CPsQuery& aQuery,
-                      TBool isGroupSearch, RArray<TInt>& aContactsInGroup,
-                      RPointerArray<CPsData>& searchResults,
-                      RPointerArray<CPsPattern>& searchSeqs);
+    void SearchSingleL(const CPsSettings& aSettings, 
+                       CPsQuery& aQuery,
+                       TBool aIsGroupSearch, 
+                       const RArray<TInt>& aContactsInGroup,
+                       RPointerArray<CPsData>& aSearchResults,
+                       RPointerArray<CPsPattern>& aSearchSeqs);
 
     /**
      * Funciton to search matching sequences in the input text
      */
-    void SearchMatchSeqL(HBufC* aQuery, TDesC& aData,
-                         RPointerArray<TDesC>& aMatchSet, CPsQuery& aPsQuery, 
+    void SearchMatchSeqL(CPsQuery& aPsQuery,
+                         const TDesC& aData,
+                         RPointerArray<TDesC>& aMatchSet,
                          RArray<TPsMatchLocation>& aMatchLocation);
 
     /**
@@ -135,16 +110,6 @@
 private:
 
     /**
-     * Constructs a bit pattern using the required/supported data fields
-     * For example, 6, 4 and 27 are supported fields <-- 00000111
-     *              6 and 4 are required fields      <-- 00000011
-     * Bit pattern returned is 00000011.
-     */
-    TUint8 FilterDataFieldsL(RArray<TInt>& aRequiredDataFields,
-                             RArray<TInt>& aSupportedDataFields);
-private:
-
-    /**
      * Constructor
      */
     CPcsAlgorithm2Helper();
@@ -164,13 +129,33 @@
     /**
      * Pointer to key map instance. Not owned.
      */
-    CPcsKeyMap* keyMap;
+    CPcsKeyMap* iKeyMap;
 
     /**
      * Array of result sets from different data stores.
      */
     typedef RPointerArray<CPsData> CPSDATA_R_PTR_ARRAY;
     RPointerArray<CPSDATA_R_PTR_ARRAY> iSearchResultsArr;
+    
+    /**
+     * Phonebook settings store for reading name order.
+     */
+    MPbkGlobalSetting* iPbkSettings;
+    
+    /**
+     * Contact name display order 
+     */
+    enum TNameOrder
+        {
+        EFirstnameLastname,
+        ELastnameFirstname
+        };
+    TNameOrder iNameOrder;
+    
+    /**
+     * Counter of the matched contacts requested by PCS client
+     */
+    TInt iMaxCount;
     };
 
 #endif // C_PCS_ALGORITHM_2_HELPER
--- a/predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsAlgorithm2MultiSearchHelper.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsAlgorithm2MultiSearchHelper.h	Thu Aug 19 09:41:07 2010 +0300
@@ -64,33 +64,11 @@
      * Filter subset results for multi query mode. 
      */
     void FilterResultsMultiL(CPcsAlgorithm2FilterHelper* aAlgorithmFilterHelper,
-                             RPointerArray<CPcsPoolElement>& searchSet,
-                             RPointerArray<CPsQuery>& searchQuery, TUint8 aFilteredDataMatch,
-                             TBool isGroupSearch, RArray<TInt>& aContactsInGroup, 
-                             TInt keyboardMode);
-
-    /**
-     * Convert the search query to a string.
-     * If the mode is ITU-T, character is converted to numeric.
-     * If the mode is Qwerty, character is retained as is.
-     */
-    void ExtractQueryL(CPsQuery& aPsQuery, TDes& aOutput);
-
-    /**
-     * Convert the input search query to a string.
-     * Mode is referred in the CPsQuery.
-     * If the mode is ITU-T, character is converted to numeric.
-     * If the mode is Qwerty, character is retained as is.
-     */
-    void ExtractQueryL(TDesC& aInput, CPsQuery& aPsQuery, TDes& aOutput);
-    /**
-     * Converts the input data to the key board mode specified by the query.
-     * Mode is referred in the CPsQuery.
-     * If the mode is ITU-T, data is converted to numeric.
-     * If the mode is Qwerty, data is retained as is.
-     */
-    void ConvertdDataToKeyBoardModeL(CPsQuery* aQuery, TPtrC aInputData,
-                                     TBuf<KPsQueryMaxLen>& aOutputData);
+                             RPointerArray<CPcsPoolElement>& aSearchSet,
+                             RPointerArray<CPsQuery>& aSearchQuery, 
+                             TUint8 aFilteredDataMatch,
+                             TBool aIsGroupSearch, 
+                             const RArray<TInt>& aContactsInGroup);
 
 public:
 
@@ -98,29 +76,24 @@
      * Search Function for multi query
      * Initials search feature
      */
-    void SearchMultiL(const CPsSettings& aSettings, RPointerArray<CPsQuery>& aQuery, 
-                      TBool isGroupSearch, RArray<TInt>& aContactsInGroup,
-                      RPointerArray<CPsData>& searchResults,
-                      RPointerArray<CPsPattern>& searchSeqs, TInt keyboardMode);
+    void SearchMultiL(const CPsSettings& aSettings, 
+                      RPointerArray<CPsQuery>& aQuery, 
+                      TBool aIsGroupSearch, 
+                      const RArray<TInt>& aContactsInGroup,
+                      RPointerArray<CPsData>& aSearchResults,
+                      RPointerArray<CPsPattern>& aSearchSeqs);
 
     /**
      * Funtion to Search matching sequences for multi query
      */
     void SearchMatchSeqMultiL(RPointerArray<CPsQuery>& aPsQuery,
-                              TDesC& aData, RPointerArray<TDesC>& aMatchSet, 
+                              const TDesC& aData, 
+                              RPointerArray<TDesC>& aMatchSet, 
                               RArray<TPsMatchLocation>& aMatchLocation);
 
 private:
 
     /**
-     * Constructs a bit pattern using the required/supported data fields
-     * For example, 6, 4 and 27 are supported fields <-- 00000111
-     *              6 and 4 are required fields      <-- 00000011
-     * Bit pattern returned is 00000011.
-     */
-    TUint8 FilterDataFieldsL(RArray<TInt>& aRequiredDataFields,
-                             RArray<TInt>& aSupportedDataFields);
-    /**
      * Set the bits corresponding to word matches
      *
      * @param aIndex Index of data element
@@ -155,12 +128,6 @@
      */
     RPointerArray<CPsQuery> MultiQueryL(CPsQuery& aQuery);
 
-    /**
-     * Convert the search query (multiple) to a list
-     */
-    void ConvertQueryToListL(RPointerArray<CPsQuery>& aSearchQuery,
-                             RPointerArray<HBufC>& aQueryList);
-
 private:
 
     /**
@@ -183,7 +150,7 @@
     /**
      * Pointer to key map instance. Not owned.
      */
-    CPcsKeyMap* keyMap;
+    CPcsKeyMap* iKeyMap;
 
     /**
      * Array of result sets from different data stores.
@@ -195,6 +162,11 @@
      * Array of word macthes.
      */
     TUint8 iWordMatches[MAX_DATA_FIELDS];
+	
+    /**
+     * Counter of the matched contacts 
+     */
+    TInt iMaxCount;
     };
 
 #endif // C_PCS_ALGORITHM_2_MULTI_SEARCH_HELPER
--- a/predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsAlgorithm2Utils.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsAlgorithm2Utils.h	Thu Aug 19 09:41:07 2010 +0300
@@ -20,11 +20,12 @@
 
 // INCLUDE FILES
 
-#include <e32hashtab.h>
-
-#include "CPsData.h"
+#include <e32base.h>
 
 // FORWARD DECLARATION
+class CPsData;
+class CPsQuery;
+struct TPsMatchLocation;
 
 typedef RPointerArray<CPsData> CPSDATA_R_PTR_ARRAY;
 
@@ -41,10 +42,10 @@
      * works for all type of key board modes
      */
     static void FormCompleteSearchResultsL(RPointerArray<CPSDATA_R_PTR_ARRAY>& aSearchResultsArr,
-                                           RPointerArray<CPsData>& SearchResults);
+                                           RPointerArray<CPsData>& aSearchResults);
 
     /**
-     * Customized CompareC         
+     * Customized CompareC
      */
     static TInt MyCompareC(const TDesC& aLeft, const TDesC& aRight);
 
@@ -54,6 +55,16 @@
     static TInt CompareDataBySortOrder(const CPsData& aObject1, const CPsData& aObject2);
 
     /**
+     * TIdentityRelation rule for comparing descriptors case-sensitively.
+     */
+    static TBool CompareExact(const TDesC& aFirst, const TDesC& aSecond);
+
+    /**
+     * TLinearOrder rule for comparing queries by length
+     */
+    static TInt CompareLength(const CPsQuery& aFirst, const CPsQuery& aSecond);
+
+    /**
      * Trim off all white spaces and special chars
      */
     static void MyTrim(TDes& aString);
@@ -62,8 +73,28 @@
      * Check if the input URI is of contact search in a group template form
      */
     static TBool IsGroupUri(TDesC& aURI);
+    
+    /**
+     * Constructs a bit pattern using the required/supported data fields
+     * For example, 6, 4 and 27 are supported fields <-- 00000111
+     *              6 and 4 are required fields      <-- 00000011
+     * Bit pattern returned is 00000011.
+     */
+    static TUint8 FilterDataFieldsL(const RArray<TInt>& aRequiredDataFields,
+                                    const RArray<TInt>& aSupportedDataFields);
+    
+    /**
+     * Create upper-case match sequence buffer from matching part and append it to
+     * array unless there's equal sequence already present.
+     */
+    static void AppendMatchToSeqL( RPointerArray<TDesC>& aMatchSeq, const TDesC& aMatch );
+    
+    /**
+     * Check if two match location items have overlapping indices.
+     */
+    static TBool MatchesOverlap( const TPsMatchLocation& aFirst, const TPsMatchLocation& aSecond );
+    };
 
-    };
 
 // CleanupStack helpers for item owning RPointerArrays
 template <class T>
--- a/predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsCache.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsCache.h	Thu Aug 19 09:41:07 2010 +0300
@@ -38,7 +38,7 @@
     /**
      * Two phase construction
      */
-    static CPcsCache* NewL(CPcsAlgorithm2* aAlgorithm, TDesC& aURI, 
+    static CPcsCache* NewL(CPcsAlgorithm2* aAlgorithm, const TDesC& aURI, 
                            CPcsKeyMap& aKeyMap, TUint8 aUriId);
 
     /**
@@ -74,7 +74,7 @@
     /**
      * Removes all data elements from the cache
      */
-    void RemoveAllFromCacheL();
+    void RemoveAllFromCache();
 
     /**
      * Sets data fields to the cache
@@ -125,6 +125,16 @@
      */
     void ResortdataInPoolsL();
 
+    /**
+     * Get data index of the first name field
+     */
+    TInt GetFirstNameIndex() const;
+
+    /**
+     * Get data index of the last name field
+     */
+    TInt GetLastNameIndex() const;
+
 private:
 
     /**
@@ -135,24 +145,36 @@
     /**
      * Second phase constructor
      */
-    void ConstructL(CPcsAlgorithm2* aAlgorithm, TDesC& aURI,
+    void ConstructL(CPcsAlgorithm2* aAlgorithm, const TDesC& aURI,
                     CPcsKeyMap& aKeyMap, TUint8 aUriId);
 
     /**
      * Utility function to add a contact to the pool
      */
-    void AddToPoolL(TInt& aInfo, CPsData& data);
+    void AddToPoolL(TUint64& aPoolMap, CPsData& aData);
+
+    /**
+     * Utility function 
+     */
+    void SetPoolMap(TUint64& aPoolMap, TInt aArrayIndex);
 
     /**
      * Utility function 
      */
-    void SetPoolMap(TInt& aPoolMap, TInt aPoolId);
+    TBool GetPoolMap(TUint64& aPoolMap, TInt aArrayIndex);
 
     /**
-     * Utility function 
+     * Gets all the first characters of the words in the data field according
+     * to which the contact should be inserted into cache.
      */
-    TBool GetPoolMap(TInt& aPoolMap, TInt arrayIndex);
-
+    void GetFirstCharsForDataL( const TDesC& aData, RArray<TChar>& aFirstChars ) const;
+    
+    /**
+     * Gets all the pool IDs matching the given characters. If there are two predictive
+     * keyboards available, then pool IDs are given according to both keyboards.
+     */
+    void GetPoolIdsForCharsL( const RArray<TChar>& aChars, RArray<TInt>& aPoolIds ) const;
+    
     /**
      * Utility function
      */
@@ -165,27 +187,27 @@
      * Array of key maps
      */
     typedef RPointerArray<CPcsPoolElement> R_PTR_ARRAY;
-    RPointerArray<R_PTR_ARRAY> keyArr;
+    RPointerArray<R_PTR_ARRAY> iKeyArr;
 
     /*
      * Hashmaps to remember the location of a contact in the pools
      */
-    RHashMap<TInt, TInt> cacheInfo;
+    RHashMap<TInt, TUint64> iCacheInfo;
 
     /*
      * Master pool of all contacts in this cache
      */
-    RPointerArray<CPsData> masterPool;
+    RPointerArray<CPsData> iMasterPool;
     
     /*
     * Master pool backup of all contacts in this cache when sortorder changed
     */
-    RPointerArray<CPsData> masterPoolBackup;  
+    RPointerArray<CPsData> iMasterPoolBackup;
 
     /*
      * Not owned
      */
-    CPcsKeyMap* keyMap;
+    CPcsKeyMap* iKeyMap;
 
     /**
      * Owned. Refer to the database URI this cache is for.
--- a/predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsKeyMap.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsKeyMap.h	Thu Aug 19 09:41:07 2010 +0300
@@ -18,24 +18,22 @@
 #ifndef __CPCS_KEY_MAP_ALGORITHM_2_H__
 #define __CPCS_KEY_MAP_ALGORITHM_2_H__
 
-// The macro is used for a hack which fix a problem of PtiEngine with Sonja keyboard.
-// The problem is that J/# key can't returned character code ('J', 'j', '#') 
-#define HACK_FOR_E72_J_KEY
 
 // INCLUDES
 #include <e32base.h>
-#include <PtiEngine.h>
-#include <PtiKeyMappings.h>
-#include <AvkonInternalCRKeys.h>
 #include <e32property.h>
+#include <PtiDefs.h>
+#include "CPcsDefs.h"
 
 class CPcsAlgorithm2;
-class     CPtiEngine;
+class CPsQuery;
+class CPtiEngine;
+class CPtiKeyMapData;
 
 class TKeyMappingData
     {
 public:
-    TPtiKey key; // key
+    TPtiKey iKey; // key
     RArray<TInt> iKeyMappingArray; // All the characters mapped to the key
     };
 
@@ -56,14 +54,15 @@
     virtual ~CPcsKeyMap();
 
     /**
-     * Converts the alphanumeric string to numeric string
+     * Convert functions to get the key string from query and/or chars string
      */
-    void GetNumericKeyString(const TDesC& alphaNumericStr, TDes& numericStr);
+    void GetMixedKeyStringForQueryL(CPsQuery& aSrcQuery, TDes& aDestStr) const;
+    void GetMixedKeyStringForDataL(CPsQuery& aSrcQuery, const TDesC& aSrcData, TDes& aDestStr) const;
 
     /**
-     * Returns the numeric key id corresponding to a specific character		                          
+     * Returns the numeric key id corresponding to a specific character
      */
-    TInt KeyForCharacter(const TChar& aChar);
+    TPtiKey KeyForCharacter(TText aChar, TKeyboardModes aKbMode) const;
 
     /**
      * Returns ETrue if this language is supported
@@ -73,15 +72,20 @@
     void ReconstructKeymapL();
     
     /**
-     * Returns the pool Id for a Character                               
+     * Returns the pool Id for a key
      */
-    TInt PoolIdForCharacter(TChar aChar);
+    TInt PoolIdForCharacter(TChar aChar, TKeyboardModes aKbMode );
     
     /**
-     * Returns total number of pools                                
+     * Returns total number of pools
      */
     TInt PoolCount();
 
+    /**
+     * Returns true if the characters "0" and " " are on the same key
+     */
+    TBool GetSpaceAndZeroOnSameKey( TKeyboardModes aMode );
+
 private:
 
     /**
@@ -95,41 +99,42 @@
     void ConstructL(CPcsAlgorithm2* aAlgorithm);
 
     /**
+     * Set flags to indicate if space and zero are on same key.
+     * Keymappings must be constructed before calling this.
+     */
+    void SetSpaceAndZeroOnSameKey();
+    
+    /**
      * Helper function to construct keyboard specific mappings
      */
-    void ContructForItutKeyboardL(TLanguage aLanguage);
-    void ContructForHalfQwertyKeyboardL(TLanguage aLanguage);
-    void ContructFor4x10QwertyKeyboardL(TLanguage aLanguage);
+    void ConstructForItutKeyboardL();
+    void ConstructForQwertyKeyboardL(TPtiKeyboardType aKbType);
 
     /**
      * Helper function to populate Itut key mappings
      */
     void AddKeyMapforItutL(TLanguage aLanguage);
 
-    void AddDataForItutKeyboardL(CPtiKeyMappings* aPtiKeyMappings,
+    void AddDataForItutKeyboardL(CPtiKeyMapData* aPtiKeyMapData,
             TPtiKey aKey, TKeyMappingData& aKeyDataList);
     /**
      * Helper function to populate 4x10 Qwerty Keyboard  key mappings
      */
-    void AddKeyMapfor4x10QwertyKeyboardL(TLanguage aLanguage);
+    void AddKeyMapForQwertyKeyboardL(TLanguage aLanguage, TPtiKeyboardType aKbType);
 
-    void AddDataFor4x10QwertyKeyboardL(
-            CPtiQwertyKeyMappings* aPtiKeyMappings, TPtiKey aKey,
+    void AddDataForQwertyKeyboardL(
+            CPtiKeyMapData* aPtiKeyMapData, 
+            TPtiKeyboardType aKbType, 
+            TPtiKey aKey,
             TKeyMappingData& aKeyDataList);
     
-#ifdef HACK_FOR_E72_J_KEY
-    void AddDataFor4x10QwertyKeyboardE72HackL(); // Hack for E72 (J/# key)
-#endif  // HACK_FOR_E72_J_KEY
-    
     /**
-     * Helper function to populate alfQwerty Keyboard key mappings
+     * Create list of PTI keys for the given keyboard type
      */
-    void AddKeyMapforHalfQwertyKeyboardL(TLanguage aLanguage);
-
-    void AddDataForHalfQwertyKeyboardL(CPtiHalfQwertyKeyMappings* aPtiKeyMappings,
-            TPtiKey aKey, TKeyMappingData& aKeyDataList);
+    void CreateKeyListFromKeyBindingTable( RArray<TPtiKey>& aKeyArray, TPtiKeyboardType aKbType );
 
     void ResetKeyMap();
+    
     /**
      * Function to construct key mappings for a particula language
      * 
@@ -137,18 +142,15 @@
     void ConstructKeymapL();
     
     /**
-     * Get the current keyboard type.
-     * @return current keyboard type.
+     * Select keyboard types according to available physical keyboard(s)
      */
-    TInt CurrentKeyBoardTypeL();
+    void SetupKeyboardTypesL();
     
     /**
      * 
-     * Construct keymap by type and language
-     * @ aKeyboardType, the current keyboard type.
-     * @ aLanguage, the keymap construct language.
+     * Construct keymaps
      */
-    void ConstructConcreteKeyMapL( TInt aKeyboardType, TLanguage aLanguage );
+    void ConstructConcreteKeyMapL();
     
     /**
      * 
@@ -156,35 +158,104 @@
      * @ aKeyboardType, the current keyboard type.
      * @ aLanguage, the keymap construct language.
      */
-    void AddKeyMapforConcreteKeyboardL( TInt aKeyboardType, TLanguage aLanguage );
-    
+    void AddKeyMapforConcreteKeyboardL( TLanguage aLanguage );
+
     /**
      * In case the given character is a Chinese characer, give the first
      * character of it's first spelling using the current spelling mode.
      * Otherwise, the character is returned unmodified.
      */
     TChar FirstCharFromSpellingL( TChar aChar ) const;
+    
+    TInt PoolIdForKey(TPtiKey aKey, TKeyboardModes aKbMode) const;
+    
+    /**
+     * Gets predictive keyboard mapping data for given match mode.
+     * @param   aMode      Matching mode for which keymappings are asked. 
+     * @return  Mapping table for the given mode. NULL if asked for non-predictive mode.
+     */
+    const RPointerArray<TKeyMappingData>* KeyMappings( TKeyboardModes aMode ) const;
 
+    /**
+     * Resolve any ambiguity from the given keyboard mode.
+     * Keyboard mode "predictive default keyboard" will be replaced by 
+     * "ITU-T predictive" or "QWERTY predictive", depending on the configuration
+     * of the device. Predictive keyboard modes, which can't be supported
+     * in this device, are replaced with "non-predictive" mode.
+     */
+    TKeyboardModes ResolveKeyboardMode( TKeyboardModes aKbMode ) const;
+    
+    /**
+     * Get the default charcter for the given key in given keyboard.
+     * The default character is used to construct the compare string for
+     * predictive mode.
+     */
+    TText DefaultCharForKey( TPtiKey aKey, TKeyboardModes aKbMode ) const;
+    
 private:
+    /**
+     * PTI engine istance. Owned.
+     */
     CPtiEngine* iPtiEngine;
 
+    /**
+     * Algorithm instacne pointer. NOT owned.
+     */
     CPcsAlgorithm2* iAlgorithm;
+    
     /**
      * Array to hold the list of languages not supported
      */
     RArray<TLanguage> iLanguageNotSupported;
 
     /**
-     * Flag to indicate if Phone is Chinese variant 
+     * Type of keyboard used in ITU-T search mode. Typically this is standard ITU-T
+     * 12-key keypad.
      */
-    RArray<TPtiKey> iKeysForPoolFormation;
+    TPtiKeyboardType iItutKeyboardType;
+
+    /**
+     * PTI keys of the ITU-T keyboard.
+     */
+    RArray<TPtiKey> iItutKeys;
+
+    /**
+     * Contains all the ITU-T keys and the characters mapped to each key. Owned.
+     */
+    RPointerArray<TKeyMappingData> iItutKeyMappings;
 
     /**
-     * Contains all the keys and the characters mapped to each key
-     * own
+     * True if "0" and " " are on the same key in the ITU-T mode
+     */
+    TBool iSpaceAndZeroOnSameKeyOnItut;
+    
+    /**
+     * Type of keyboard used in QWERTY search mode. Typically this is either 3x11 or 4x10 QWERTY
+     * or EPtiKeyboardNone if there's no any kind of QWERTY available. This may also be
+     * half-QWERTY.
+     */
+    TPtiKeyboardType iQwertyKeyboardType;
+
+    /**
+     * PTI keys of the QWERTY keyboard.
      */
-    RPointerArray<TKeyMappingData> iAllKeyMappingsPtrArr;
+    RArray<TPtiKey> iQwertyKeys;
+
+    /**
+     * Contains all the QWERTY keys and the characters mapped to each key. Owned.
+     */
+    RPointerArray<TKeyMappingData> iQwertyKeyMappings;
     
+    /**
+     * True if "0" and " " are on the same key in the QWERTY mode
+     */
+    TBool iSpaceAndZeroOnSameKeyOnQwerty;
+    
+    /**
+     * Flag to indicate if the default multi-matching mode is ITU-T or QWERTY mode.
+     * ETrue, if ITU-T is defualt and EFalse if QWERTY is default.
+     */
+    TBool iItutIsDefault;
     };
 
 #endif // __CPCS_KEY_MAP_ALGORITHM_2_H__
--- a/predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsPoolElement.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/inc/CPcsPoolElement.h	Thu Aug 19 09:41:07 2010 +0300
@@ -100,7 +100,7 @@
      * Bit 6 = Not used
      * Bit 7 = Not used
      */
-    TInt8 iDataMatchAttribute;
+    TUint8 iDataMatchAttribute;
     };
 
 #endif // __CPCS_POOL_ELEMENT_ALGORITHM_2_H__
--- a/predictivesearch/PcsAlgorithm/Algorithm2/inc/FindUtilChineseECE.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/inc/FindUtilChineseECE.h	Thu Aug 19 09:41:07 2010 +0300
@@ -36,7 +36,7 @@
 Defines flags that can be used to indicate what is the default search method for each language.
 */
 
-enum TDefaultAdaptiveSearchMethod
+enum TChineseSearchMethod
     {
     EAdptSearchPinyin =0,
     EAdptSearchStroke,
@@ -48,7 +48,7 @@
 /**
  *  STRINGINFO struct
  *
- *  This data struct is for splited taxt in find pane. 
+ *  This data struct is for splited text in find pane. 
  *  It includes two type word, which is Chinese or no-Chinese 
  *
  *  @lib FindUtil.dll
@@ -58,6 +58,7 @@
     {
     TBuf<KMaxWordLength> segmentString;
     TBool isChinese;
+    TInt segmentPos;
     };
 
 /**
@@ -88,12 +89,26 @@
      *
      * @since S60 v3.2
      * @param aItemString Reference to the searching target
-     * @param aWord Reference to text in find pane
+     * @param aPsQuery Reference to the search query
      * @return ETrue for the text are matched; otherwise EFalse
      */
     virtual TBool MatchRefineL(const TDesC& aItemString, CPsQuery& aPsQuery);
 
     /**
+     * Match arithmetic for accurate search 
+     *
+     * @since S60 v5.2
+     * @param aItemString Reference to the searching target
+     * @param aPsQuery Reference to the search query
+     * @param aMatchPos On return, contain positions of matching parts within aItemString
+     * @param aMatchLength On return, contains lenghts of matching parts within aItemString
+     * @param aHighLight  If highlight or underline position of matched contact is enabled
+     * @return ETrue for the text are matched; otherwise EFalse
+     */
+    TBool MatchRefineL(const TDesC& aItemString, CPsQuery& aPsQuery, 
+        RArray<TInt>& aMatchPos, RArray<TInt>& aMatchLength, TBool aHighLight );
+
+    /**
      * Current input text is handled by this model 
      *
      * @since S60 v3.2
@@ -170,30 +185,6 @@
 public:
 
     /**
-     * Do translate for Chinese word
-     *
-     * @since S60 v3.2
-     * @param aHZUnicode For translate word
-     * @param aSpellList Reference to spelling list for polyphonic word
-     * @return ETrue for it can be translated; otherwise EFalse
-     */
-    TBool T9ChineseTranslationL(TInt16 aHZUnicode, RPointerArray<HBufC>& aSpellList);
-
-    /**
-     * Find pane text is including Chinese word
-     *
-     * @since S60 v3.2
-     * @param aWord Reference to text for analyse
-     * @return ETrue it includes Chinese; otherwise EFalse
-     */
-    TBool IsChineseWord(const TDesC& aWord);
-
-    /*
-     * 
-     */
-    void SetKeyboardMode(TInt aMode);
-    
-    /**
      * Translate Chinese word to its spelling
      *
      * @since S60 v3.2
@@ -203,6 +194,15 @@
      */
     TBool DoTranslationL(TInt16 aHZUnicode, RPointerArray<HBufC>& aSpellList);
 
+    /**
+     * Find pane text is including Chinese word
+     *
+     * @since S60 v3.2
+     * @param aWord Reference to text for analyse
+     * @return ETrue it includes Chinese; otherwise EFalse
+     */
+    TBool IsChineseWordIncluded(const TDesC& aWord);
+
     /*
      * 
      */
@@ -211,6 +211,11 @@
         return iLanguage;
         }
 
+    inline TChineseSearchMethod CurrentSearchMethod()
+        {
+        return iSearchMethod;
+        }
+    
 private:
 
     /**
@@ -238,9 +243,6 @@
      */
     void CloseT9InterfaceL();
 
-    TInt CategoryOfLang(TLanguage aLanguage);
-
-
     /**
      * This letter is stroke symbol
      *
@@ -248,12 +250,18 @@
      * @param aFindWord For analyse
      * @return ETrue for it is stroke symbol; otherwise EFalse
      */
-    TInt IsStrokeSymbol(const TInt aFindWord);
+    TInt IsStrokeSymbol(const TUint16 aFindWord);
     
-    // The below code is commented out because current CFindUtilChineseECE is used
-    // on 3.2.3 which is not supported adaptive search. It will be easy to keep these code 
-    // for the further merging work (merge from FindUtil 5.0)
-#if 0
+    /**
+     * Do translate for Chinese word
+     *
+     * @since S60 v3.2
+     * @param aHZUnicode For translate word
+     * @param aSpellList Reference to spelling list for polyphonic word
+     * @return ETrue for it can be translated; otherwise EFalse
+     */
+    TBool T9ChineseTranslationL(TInt16 aHZUnicode, RPointerArray<HBufC>& aSpellList);
+
     /**
      * Do translate for Chinese word
      *
@@ -263,7 +271,6 @@
      * @return ETrue for it can be translated; otherwise EFalse
      */
     TBool T9ChineseTranslationAdaptiveL(TInt16 aHZUnicode, RPointerArray<HBufC>& aSpellList);
-#endif
     
     /**
      * Find pane text is including separator
@@ -284,6 +291,14 @@
     TBool IsStrokeSymbolInString(const TDesC& aWord);
 
     /**
+     * Find pane text is just Chinese word
+     * 
+     * @param aWord Reference to text for analyse
+     * @return ETrue it is all Chinese word(s); otherwise EFalse
+     */
+    TBool IsAllChineseWord(const TDesC& aWord);
+    
+    /**
      * Find pane text is including zhuyin symbol
      *
      * @since S60 v3.2
@@ -327,10 +342,13 @@
      * @param aStringInfoArr Reference to segment list
      * @param aSegmentStr Reference to segment text
      * @param aChinese The segment is Chinese
+     * @param aIndexAfterStr The first index in the source string after the aSegmentStr.
+     *                       The indices of characters of aSegmentStr are 
+     *                       [aIndexAfterStr-aSegmementStr.Length(), aIndexAfterStr-1]
      * @return none
      */
     void InsertStrInforArrayL(RPointerArray<STRINGINFO>& aStringInfoArr,
-                              TDes &aSegmentStr, const TBool aChinese);
+                              TDes &aSegmentStr, TBool aChinese, TInt aIndexAfterStr);
 
     /**
      * This segment is matched by search text
@@ -338,9 +356,13 @@
      * @since S60 v3.2
      * @param aStringInfoArr Reference to segment list
      * @param aSearchText Reference to searching text
+     * @param aMatchPos On return, contain positions of matching parts within the original searcg target text
+     * @param aMatchLength On return, contains lenghts of matching parts within the original search target text
+     * @param aHighLight  If highlight or underline position of matched contact is enabled
      * @return ETrue it is matched; otherwise EFalse
      */
-    TBool MatchSegmentL(RPointerArray<STRINGINFO>& aStringInfoArr, CPsQuery& aQuery);
+    TBool MatchSegmentL(RPointerArray<STRINGINFO>& aStringInfoArr, 
+        CPsQuery& aQuery, RArray<TInt>& aMatchPos, RArray<TInt>& aMatchLength, TBool aHighLight );
 
     /**
      * Search text by reverse
@@ -348,9 +370,10 @@
      * @since S60 v3.2
      * @param aFirst Reference to matched text
      * @param aSecond Reference to matched text
+	 * @param aFullQuery Reference to the FullQuery
      * @return Matched count
      */
-    TInt ReverseMatchString(const TDesC& aFirst, const TDesC& aSecond);
+    TInt ReverseMatchStringL(const TDesC& aFirst, const TDesC& aSecond, CPsQuery& aFullQuery );
 
     /**
      * Search text in other text 
@@ -358,29 +381,34 @@
      * @since S60 v3.2
      * @param aFirst Reference to matched text
      * @param aSecond Reference to matched text
+	 * @param aFullQuery Reference to the FullQuery
      * @return Matched count
      */
-    TInt MatchString(const TDesC& aFirst, const TDesC& aSecond);
+    TInt MatchStringL(const TDesC& aFirst, const TDesC& aSecond, CPsQuery& aFullQuery);
     
     /**
      * Search text in other text 
      *
      * @since S60 v3.2
-     * @param aSearhTargetStr Reference to the target text to be queried
-     * @param CPsQuery maintain the matched text from user 
-     * @return Matched count
+     * @param aSearchTargetString Data to be searched through
+     * @param aQuery Text to be searched from aSearchTargetString
+     * @return Number of matched characters from the begining of aQuery
      */
-    TInt MatchString(const TDesC& aSearhTargetStr, CPsQuery& aQuery);
+    TInt MatchStringL(const TDesC& aSearhTargetString, CPsQuery& aQuery);
 
     /**
      * Search Chinese word in input text 
      *
      * @since S60 v3.2
-     * @param aFirst Reference to matched text
-     * @param aSecond Reference to matched text
-     * @return Matched count
+     * @param aSearchTargetString Data to be searched through
+     * @param aQuery Text to be searched from aSearchTargetString
+     * @param aMatchStrtIdx On return, will contain the start index 
+     *                      of the matching part within aSearchTargetString
+     * @param aMatchEndIdx On return, will contain the end index 
+     *                     of the matching part within aSearchTargetString
+     * @return Number of matched characters from the begining of aQuery
      */
-    TInt MatchChineseStringL(const TDesC& aSearchTargetString, CPsQuery& aQuery, TInt& aIndex);
+    TInt MatchChineseStringL(const TDesC& aSearchTargetString, CPsQuery& aQuery, TInt& aMatchStartIdx, TInt& aMatchEndIdx);
 
     /**
      * Initial character search 
@@ -397,18 +425,19 @@
      * Maximal matched count in spelling list  
      *
      * @since S60 v3.2
-     * @param spellList Reference to spelling list
+     * @param aSpellList Reference to spelling list
      * @param aSearchStr Reference to search text
      * @param aPreviouStr Reference to previous matched word
      * @param aMatchIndex Reference to match index in Search text
      * @param aFullMatched Previous word is fully matched
      * @param aMatchedCount Previous word matched count
      * @param aAgain Search again
+	 * @param aFullQuery Reference to the FullQuery
      * @return Matched count
      */
-    TInt MaxMatchInList(RPointerArray<HBufC> &spellList, CPsQuery& aQuery,
+    TInt MaxMatchInListL(RPointerArray<HBufC>& aSpellList, CPsQuery& aQuery,
                         TDesC& aPreviouStr, TInt& aMatchIndex, const TBool aFullMatched,
-                        const TInt aMatchedCount, TBool& aAgain);
+                        const TInt aMatchedCount, TBool& aAgain, TBool& aPrevReplaced, CPsQuery& aFullQuery);
 
     /**
      * Search the taxt is include the input text 
@@ -527,18 +556,6 @@
                 const TDes& aCurrentBuf,HBufC*& aNextChars );
 #endif
 
-    /**
-     * Converts the input data to the key board mode specified by the query.
-     * Mode is referred in the CPsQuery.
-     * If the mode is ITU-T, data is converted to numeric.
-     * If the mode is Qwerty, data is retained as is.
-     * If the mode is Mix, data is conerted according to the keyboard mode 
-     * of the corresponding query chararter 
-     */
-    void ConvertdDataToKeyBoardModeL(CPsQuery& aQuery, 
-                                     const TDesC& aSearchTargetStr,
-                                     TBuf<KMaxWordInterpretationLen>& aOutputNumInterpretationStr);
-    
     // help function for using CPsQuery
 public:
     void GetPartOfQueryL(CPsQuery& aSrcQuery, TInt aStartIndex, 
@@ -555,21 +572,11 @@
     CPtiEngine* iPtiEngine;
 
     /**
-     * Ptiengine for Chinese translation in English language (Own)
-     */
-    CPtiEngine* iPtiEnginePrc;
-
-    /**
      * Current text input language 
      */
     TLanguage iLanguage;
 
     /**
-     * It is support Chinese Language
-     */
-    TBool iSupportPRCChinese;
-
-    /**
      * Current input mode
      */
     TInt iCurInputMode;
@@ -584,14 +591,10 @@
      */
     CFindRepositoryWatcher* iWatcher;
    
-    // The below code is commented out because current CFindUtilChineseECE is used
-    // on 3.2.3 which is not supported adaptive search. It will be easy to keep these code 
-    // for the further merging work (merge from FindUtil 5.0)
-#if 0
     /**
      * Repository for input mode (Own)
      */     
-    CRepository* iRepositoryFindAdaptive;	 
+    CRepository* iRepositoryFindAdaptive;
 
     /**
      * The repository watcher(Own);
@@ -602,31 +605,15 @@
     /**
      * The default adaptive search method;
      */
-    TDefaultAdaptiveSearchMethod iSearchMethodPRC;
-    
-    /**
-     * The default adaptive search method;
-     */
-    TDefaultAdaptiveSearchMethod iSearchMethodTaiWan;
-    
-    /**
-     * The default adaptive search method;
-     */
-    TDefaultAdaptiveSearchMethod iSearchMethodHongKong;
+    TChineseSearchMethod iSearchMethod;
     
     /**
      * The search method;
      */
     TBool iSearchMethodAdaptive;
-#endif
 
     CPcsAlgorithm2* iAlgorithm;
 
-    /*
-     * The keyboard Mode
-     */
-    TInt iKeyboardMode;
-
     };
 
 #endif // __FINDUTILCHINESE_ECE__
--- a/predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsAlgorithm2.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsAlgorithm2.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -79,7 +79,6 @@
     iCacheCount = 0; // No data
 
     iFindUtilECE = CFindUtilChineseECE::NewL(this);
-    iFindUtil = CFindUtil::NewL();
     
     iPluginLauncher = CIdle::NewL( CActive::EPriorityStandard );
 
@@ -96,13 +95,14 @@
 
     // Initialize key map and pti engine
     TInt keyMapErr = KErrNone;
-    TRAP( keyMapErr, iKeyMap = CPcsKeyMap::NewL( this ));
+    TRAP( keyMapErr, iKeyMap = CPcsKeyMap::NewL( this ) );
     if (keyMapErr != KErrNone)
         {
         PRINT ( _L("**********************************************."));
         PRINT1 ( _L("CPcsAlgorithm2::ConstructL() KeyMap construction error. The keymap crashed with error code %d."), keyMapErr );
         PRINT ( _L("Please check the keypad/language for which keymap got crashed.") );
         PRINT ( _L("**********************************************."));
+        User::Leave( keyMapErr ); // we can't go on without a key map; constructing cache needs it
         }
     
     // Initialize helpers
@@ -140,7 +140,6 @@
     delete iMultiSearchHelper;
 
     delete iFindUtilECE;
-    delete iFindUtil;
     
     delete iPluginLauncher;
 
@@ -165,105 +164,152 @@
     }
 
 // ----------------------------------------------------------------------------
+// CPcsAlgorithm2::RemoveSpacesL
+// Remove leading and trailing spaces of search query
+// ----------------------------------------------------------------------------
+void  CPcsAlgorithm2::RemoveSpacesL(CPsQuery& aQuery)
+    {
+    PRINT ( _L("Enter CPcsAlgorithm2::RemoveSpacesL") );
+
+    // Remove all leading " "
+    while ( aQuery.Count() > 0 )
+        {
+        CPsQueryItem& item = aQuery.GetItemAtL(0); // First
+        if ( !item.Character().IsSpace() )
+            {
+            break;
+            }
+        aQuery.Remove(0);
+        }
+
+    // Remove all trailing " "
+    while ( aQuery.Count() > 0 )
+        {
+        CPsQueryItem& item = aQuery.GetItemAtL(aQuery.Count()-1); // Last
+        if ( !item.Character().IsSpace() )
+            {
+            break;
+            }
+        aQuery.Remove(aQuery.Count()-1);
+        }
+    
+    PRINT ( _L("End CPcsAlgorithm2::RemoveSpacesL") );
+    }    
+
+// ----------------------------------------------------------------------------
 // CPcsAlgorithm2::ReplaceZeroWithSpaceL
 // Replace first occurance of '0' in a sequence of '0's in ITU-T with space
 // ----------------------------------------------------------------------------
 TBool CPcsAlgorithm2::ReplaceZeroWithSpaceL(CPsQuery& aQuery)
     {
-    TChar space(KSpace); // ascii value for space
+    PRINT ( _L("Enter CPcsAlgorithm1::ReplaceZeroWithSpaceL") );
 
-    TBool queryModified = EFalse;
+       //PRINTQUERY ( _L("CPcsAlgorithm1::ReplaceZeroWithSpaceL (BEFORE): "), aQuery );
+
+       TBool queryModified = EFalse;    
 
-    // Skip initial zeros in query
-    TInt index = 0;
-    for (index = 0; index < aQuery.Count()
-            && aQuery.GetItemAtL(index).Character().GetNumericValue() == 0; ++index)
-        {
-        }
-
-    if (aQuery.KeyboardModeL() != EQwerty)
-        {
-        for (TInt beg = index; beg < aQuery.Count(); ++beg)
-            {
-            CPsQueryItem& item = aQuery.GetItemAtL(beg);
+       /* In phones like E52 and E55, where the "0" and the " " characters are on
+        * the same key, the "0"s have to be considered as possible separators.
+        *
+        * In phones like N97 and E72, where the "0" and the " " characters are on
+        * different keys, the "0"s must not be considered as possible separators.
+        */
 
-            if (item.Character().GetNumericValue() == 0 && item.Mode()== EItut)
-                {
-                if (beg != 0)
-                    {
-                    CPsQueryItem& item1 = aQuery.GetItemAtL(beg - 1);
-                    if (item1.Character().GetNumericValue() != 0
-                            && !item1.Character().IsSpace())
-                        {
-                        item.SetCharacter(space);
-                        queryModified = ETrue;
-                        }
-                    }
-                else
-                    {
-                    item.SetCharacter(space);
-                    queryModified = ETrue;
-                    }
-                }
-            }
-        }
+       // Skip initial "0"s, they are not replaced into spaces
+       TInt skipIndex = 0;
+       while ( (skipIndex < aQuery.Count()) && 
+               (aQuery.GetItemAtL(skipIndex).Character().GetNumericValue() == 0) )
+       {
+           skipIndex++;
+       }
+       
+       // Replace remaining "0"s into spaces in case they are entered with a keyboard
+       // that has "0" and " " on the same key.
+       const TInt queryCount = aQuery.Count();
+       for ( TInt index = skipIndex; index < queryCount; index++ )
+       {
+           CPsQueryItem& item = aQuery.GetItemAtL(index);
 
-    return queryModified;
+           if ( iKeyMap->GetSpaceAndZeroOnSameKey( item.Mode() ) &&
+                item.Character().GetNumericValue() == 0 )
+           {
+               item.SetCharacter(KSpace);
+               queryModified = ETrue;
+           }
+       }
+       
+       //PRINTQUERY ( _L("CPcsAlgorithm1::ReplaceZeroWithSpaceL (AFTER): "), aQuery );
+
+       PRINT1 ( _L("CPcsAlgorithm1::ReplaceZeroWithSpaceL: Query modified (0=not, 1=yes): %d"), queryModified );
+
+       PRINT ( _L("End CPcsAlgorithm1::ReplaceZeroWithSpaceL") );
+
+       return  queryModified;
     }
 
 // ----------------------------------------------------------------------------
 // CPcsAlgorithm2::PerformSearchL
 // Search function for cache
 // ----------------------------------------------------------------------------
-void CPcsAlgorithm2::PerformSearchL(const CPsSettings& aSettings, CPsQuery& aQuery, 
+void CPcsAlgorithm2::PerformSearchL(const CPsSettings& aSettings, 
+                                    CPsQuery& aQuery, 
                                     RPointerArray<CPsClientData>& aSearchResults,
                                     RPointerArray<CPsPattern>& aSearchSeqs)
     {
     PRINT ( _L("Enter CPcsAlgorithm2::PerformSearchL") );
 
-    __LATENCY_MARK ( _L("CPcsAlgorithm2::PerformSearchL") );
-
-    // Get the current language
-    TLanguage lang = User::Language();
-
-    // Check if the language is supported and the keyboard mode is not qwerty.
+    //__LATENCY_MARK ( _L("CPcsAlgorithm2::PerformSearchL") );
+    
+    // Check aSettings   
+    RPointerArray<TDesC> searchUris;
+    CleanupResetAndDestroyPushL( searchUris );
+    aSettings.SearchUrisL(searchUris);
+         
+    if ( searchUris.Count() <= 0)
+    {
+        PRINT ( _L("searchUris.Count() <= 0, Leave from CPcsAlgorithm1::PerformSearchL") );
+        User::Leave(KErrArgument); 
+    }
+    CleanupStack::PopAndDestroy( &searchUris ); // ResetAndDestroy
 
     // Local arrays to hold the search results 
     RPointerArray<CPsData> tempSearchResults;
+    CleanupClosePushL( tempSearchResults );
     RPointerArray<CPsData> tempSearchResults1;
+    CleanupClosePushL( tempSearchResults1 );
 
     // -------------------- Perform the basic search --------------------------
 
+    RemoveSpacesL(aQuery);
+    PRINTQUERY ( _L("CPcsAlgorithm2::PerformSearchL: 1st search query: "), aQuery );
     DoSearchL(aSettings, aQuery, tempSearchResults, aSearchSeqs);
 
     // ------------------------------------------------------------------------
 
-    // ------------------- Perform advanced search if needed ------------------
-    // Substitute "0" with space
+    // ---- Perform new search after "0" replacement if query is not empty ----
+    /* Examples:
+     * - If the original search string is "Abc0" then we will search again with "Abc".
+     * - If the original search string is "00" then we will not search again.
+     */
     TBool queryModified = ReplaceZeroWithSpaceL(aQuery);
-
-    // If query got modified and the search query translated to more than 1 query
-    // perform a multi search again
+    RemoveSpacesL(aQuery);
+    // Perform query again if query got modified. 
     if (queryModified)
         {
-        // Split query
-        RPointerArray<CPsQuery> queryList = iMultiSearchHelper->MultiQueryL(aQuery);
+        PRINTQUERY ( _L("CPcsAlgorithm2::PerformSearchL: 2nd search query: "), aQuery );
+        DoSearchL(aSettings, aQuery, tempSearchResults1, aSearchSeqs);
 
-        //  Perform seach again
-        if (queryList.Count() > 1)
-            {
-            DoSearchL(aSettings, aQuery, tempSearchResults1, aSearchSeqs);
-            }
 
         // Sort rule        
         TLinearOrder<CPsData> rule(CPcsAlgorithm2Utils::CompareDataBySortOrder);
 
         // Avoid duplicates and add new results
         TIdentityRelation<CPsData> identityRule(CPsData::CompareById);
+        const TInt tempSearchResults1Count = tempSearchResults1.Count();
         if (aSettings.GetSortType() != EAlphabetical)
             {
             TInt insertPos = 0;
-            for (int i = 0; i < tempSearchResults1.Count(); i++)
+            for (TInt i = 0; i < tempSearchResults1Count; i++)
                 {
                 if (tempSearchResults.Find(tempSearchResults1[i],
                                            identityRule) == KErrNotFound)
@@ -271,14 +317,11 @@
                     tempSearchResults.Insert(tempSearchResults1[i], insertPos);
                     insertPos++;
                     }
-
                 }
-
             }
         else
             {
-
-            for (int i = 0; i < tempSearchResults1.Count(); i++)
+            for (TInt i = 0; i < tempSearchResults1Count; i++)
                 {
                 if (tempSearchResults.Find(tempSearchResults1[i],
                                            identityRule) == KErrNotFound)
@@ -288,40 +331,35 @@
                     }
                 }
             }
-
-        queryList.ResetAndDestroy();
         }
     // ------------------------------------------------------------------------
 
     // ---------------------- Write result objects to the stream --------------
     // Truncate the result set if required
-    TInt numToDisplay = aSettings.MaxResults();
-    TInt resultSet = tempSearchResults.Count();
-
-    if (resultSet > numToDisplay && numToDisplay != -1)
+    TInt maxNumToDisplay = aSettings.MaxResults();
+    TInt resultSetCount = tempSearchResults.Count();
+    TInt numToDisplay = 0;
+    if ( maxNumToDisplay == -1 )
         {
-        // Copy the top N contents from tempSearchResults to the results stream
-        for (int i = 0; i < numToDisplay; i++)
-            {
-            aSearchResults.Append(WriteClientDataL(*(tempSearchResults[i])));
-            }
-
+        numToDisplay = resultSetCount;
         }
     else
         {
-        // Copy all the contents from tempSearchResults to the results stream
-        for (int i = 0; i < resultSet; i++)
-            {
-            aSearchResults.Append(WriteClientDataL(*(tempSearchResults[i])));
-            }
+        numToDisplay = Min( maxNumToDisplay, resultSetCount );
+        }
+
+    // Copy desired number of results from tempSearchResults to the results stream
+    for (TInt i = 0; i < numToDisplay; i++)
+        {
+        aSearchResults.Append(WriteClientDataL(*(tempSearchResults[i])));
         }
     // ------------------------------------------------------------------------
 
     // Cleanup local results array
-    tempSearchResults.Reset(); // Don't destroy
-    tempSearchResults1.Reset(); // Don't destroy
+    CleanupStack::PopAndDestroy( &tempSearchResults1 ); // Close, don't destroy
+    CleanupStack::PopAndDestroy( &tempSearchResults );  // Close, don't destroy
 
-    __LATENCY_MARKEND ( _L("CPcsAlgorithm2::PerformSearchL") );
+    // __LATENCY_MARKEND ( _L("CPcsAlgorithm2::PerformSearchL") );
 
     PRINT ( _L("End CPcsAlgorithm2::PerformSearchL") );
     }
@@ -330,52 +368,121 @@
 // CPcsAlgorithm2::SearchInputL
 // Search function for input string
 // ----------------------------------------------------------------------------
-void CPcsAlgorithm2::SearchInputL(CPsQuery& aQuery, TDesC& aData,
+void CPcsAlgorithm2::SearchInputL(CPsQuery& aQuery, 
+                                  TDesC& aData,
                                   RPointerArray<TDesC>& aMatchSet,
                                   RArray<TPsMatchLocation>& aMatchLocation)
     {
+    // __LATENCY_MARK ( _L("CPcsAlgorithm2::SearchInputL: ") );
     PRINT ( _L("Enter CPcsAlgorithm2::SearchInputL") );
 
-    // Get the current language
-    TLanguage lang = User::Language();
-
-    // Check if the language is supported and the keyboard mode is not qwerty.
-
     // Print input query for debug
-    aQuery.PrintQuery();
+    PRINTQUERY ( _L("CPcsAlgorithm2::SearchInputL: Search query: "), aQuery );
 
     // Print received search data
     PRINT1 ( _L("Search data received = %S"), &aData);
 
+
     // -------------------- Perform the basic search --------------------------
 
+    RemoveSpacesL(aQuery);
     DoSearchInputL(aQuery, aData, aMatchSet, aMatchLocation);
 
     // ------------------------------------------------------------------------   
 
-    // ------------------- Perform advanced search if needed ------------------
-    // Substitute "0" with space
+    // ---- Perform new search after "0" replacement if query is not empty ----
+    /* Examples:
+     * - If the original search string is "Abc0" then we will search again with "Abc".
+     * - If the original search string is "00" then we will not search again.
+     */
     TBool queryModified = ReplaceZeroWithSpaceL(aQuery);
-
-    // If query got modified and the search query translated to more than 1 query
+    RemoveSpacesL(aQuery);
+    // If query got modified and the search query still contains something
     // perform a multi search again
-    if (queryModified)
+    if (queryModified && aQuery.Count() > 0 && aMatchSet.Count() == 0  && aMatchLocation.Count() == 0 )
         {
-        RPointerArray<CPsQuery> queryList = iMultiSearchHelper->MultiQueryL(aQuery);
+        DoSearchInputL(aQuery, aData, aMatchSet, aMatchLocation);
+        }
+    // ------------------------------------------------------------------------
 
-        if (queryList.Count() > 1)
+    // --- Remove overlapping items from aMatchLocation ---
+    TInt i = 0;
+    TBool incrementFirstCursor;
+    while ( i < aMatchLocation.Count() )
+        {
+        incrementFirstCursor = ETrue;
+        TInt j = i+1;
+        while ( j < aMatchLocation.Count() )
+            {
+            if ( CPcsAlgorithm2Utils::MatchesOverlap( aMatchLocation[j], aMatchLocation[i] ) )
+                {
+                // Remove match location item with smallest length if 2 items have same index
+                if ( aMatchLocation[j].length <= aMatchLocation[i].length )
+                    {
+                    aMatchLocation.Remove(j);
+                    continue; // Do not increment j
+                    }
+                else
+                    {
+                    aMatchLocation.Remove(i);
+                    incrementFirstCursor = EFalse; // Do not increment i
+                    break;
+                    }
+                }
+            j++;
+            }
+        if ( incrementFirstCursor )
             {
-            DoSearchInputL(aQuery, aData, aMatchSet, aMatchLocation);
+            i++;
+            }
+        }
+
+    // --- Remove from aMatchSet items which no longer have corresponding item in aMatchLocation ---
+    HBufC* dataUpper = HBufC::NewLC(aData.Length());
+    dataUpper->Des().Copy(aData);
+    dataUpper->Des().UpperCase(); // Get uppercase, as aMatchSet is in upper case
+
+    TInt k = 0;
+    while ( k < aMatchSet.Count() )
+        {
+        TBool keepMatch = EFalse;
+        TInt startCursor = -1;
+
+        TInt offsetCursor;
+        while ( KErrNotFound != (offsetCursor = dataUpper->Mid(startCursor + 1).Find(*aMatchSet[k])) )
+            {
+            // startCursor = index of match item *aMatchSet[k] into search string aData
+            startCursor = offsetCursor + startCursor + 1;
+            const TInt matchLocationCount = aMatchLocation.Count();
+            for ( TInt i = 0; i < matchLocationCount; i++ )
+                {
+                // If match item was found in the location list, then keep it
+                if ( (aMatchLocation[i].index == startCursor) &&
+                     (aMatchLocation[i].length == aMatchSet[k]->Length()) )
+                    {
+                    keepMatch = ETrue;
+                    break;
+                    }
+                }
             }
 
-        queryList.ResetAndDestroy();
+        if ( keepMatch )
+            {
+            k++;
+            }
+        else
+            {
+            aMatchSet.Remove(k); // Do not increment k
+            }
         }
-    // ------------------------------------------------------------------------
+    CleanupStack::PopAndDestroy( dataUpper );
+    // --- Remove items End ---
 
     // Sort match set
     iHelper->SortSearchSeqsL(aMatchSet);
 
     PRINT ( _L("End CPcsAlgorithm2::SearchInputL") );
+    //__LATENCY_MARKEND ( _L("CPcsAlgorithm2::SearchInputL") );
     }
 
 // ----------------------------------------------------------------------------
@@ -386,28 +493,39 @@
                                          TDesC& /*aSearchData*/,
                                          TDes& /*aMatch*/ )
     {
-    //NOT IMPLEMENTED YET
+    PRINT ( _L("Enter CPcsAlgorithm2::SearchMatchStringL") );
+
+    //__LATENCY_MARK ( _L("CPcsAlgorithm2::SearchMatchStringL") ); 
+    
+    // TODO: Implementation missing
+    
+    //__LATENCY_MARKEND ( _L("CPcsAlgorithm2::SearchMatchStringL") );
+
+    PRINT ( _L("End CPcsAlgorithm2::SearchMatchStringL") );
     }
 
 // ----------------------------------------------------------------------------
 // CPcsAlgorithm2::DoSearchL
 // Search function helper
 // ----------------------------------------------------------------------------
-void CPcsAlgorithm2::DoSearchL(const CPsSettings& aSettings, CPsQuery& aQuery, 
-                               RPointerArray<CPsData>& searchResults,
-                               RPointerArray<CPsPattern>& searchSeqs)
+void CPcsAlgorithm2::DoSearchL( const CPsSettings& aSettings, 
+                                CPsQuery& aQuery, 
+                                RPointerArray<CPsData>& aSearchResults,
+                                RPointerArray<CPsPattern>& aSearchSeqs )
     {
     PRINT ( _L("Enter CPcsAlgorithm2::DoSearchL") );
 
-    // Print query for debug
-    aQuery.PrintQuery();
-
+    //__LATENCY_MARK ( _L("CPcsAlgorithm2::DoSearchL") ); 
+    
     // -(0)----------------- Check if group search is required ---------------    
     RArray<TInt> contactsInGroup;
+    CleanupClosePushL( contactsInGroup );
     RArray<TInt> groupIdArray;
+    CleanupClosePushL( groupIdArray );
 
     // Create a new settings instance
-    CPsSettings *tempSettings = aSettings.CloneL();
+    CPsSettings* tempSettings = aSettings.CloneL();
+    CleanupStack::PushL( tempSettings );
 
     TBool isGroupSearch = IsGroupSearchL(*tempSettings, groupIdArray);
 
@@ -420,102 +538,55 @@
         GetContactsInGroupL(groupIdArray[0], contactsInGroup);
         }
 
-    groupIdArray.Close();
-
     // -----------------------------------------------------------------------
 
 
     // Extract query list. 
     RPointerArray<CPsQuery> queryList = iMultiSearchHelper->MultiQueryL(aQuery);
+    CleanupResetAndDestroyPushL( queryList );
 
-    // -(1)--------------------- No query return all contacts ----------------    
+    // (1)-------------------- No query return all contacts -------------------
     if (queryList.Count() == 0)
         {
-        GetAllContentsL(*tempSettings, searchResults);
+        GetAllContentsL(*tempSettings, aSearchResults);
 
         if (isGroupSearch)
             {
-            FilterSearchResultsForGroupsL(contactsInGroup, searchResults);
+            FilterSearchResultsForGroupsL(contactsInGroup, aSearchResults);
             }
         }
     // ------------------------------------------------------------------------
 
-
-    // -(2)------------------------ Perform a single query search -------------
-    if (queryList.Count() == 1)
+    // (2)-------------------- Perform a single query search ------------------
+    else if (queryList.Count() == 1)
         {
-        TInt mode = aQuery.KeyboardModeL();
-
         CPsQuery* query = queryList[0];
 
-        iFindUtilECE->SetKeyboardMode(mode);
-
-        switch (mode)
-            {
-            case EItut:
-
-                PRINT ( _L("Query received is in ITU-T mode") );
-
-                // Search results
-                iHelper->SearchITUL(*tempSettings, *query, isGroupSearch,
-                                    contactsInGroup, searchResults, searchSeqs);
-
-                break;
-
-            case EQwerty:
-
-                PRINT ( _L("Query received is in QWERTY mode") );
-
-                // Search results
-                iHelper->SearchQWERTYL(*tempSettings, *query, isGroupSearch,
-                                       contactsInGroup, searchResults, searchSeqs);
-
-                break;
-
-            case EModeUndefined:
-
-                PRINT ( _L("Query received is in Mixed mode. Keyboard swap happened.") );
-
-                // Search results
-                iHelper->SearchMixedL(*tempSettings, *query, isGroupSearch,
-                                      contactsInGroup, searchResults, searchSeqs);
-
-                break;
-            }
-
+        // Search results
+        iHelper->SearchSingleL(*tempSettings, *query, isGroupSearch,
+                               contactsInGroup, aSearchResults, aSearchSeqs);
         }
     // ------------------------------------------------------------------------
 
-
-    // -(3)---------------------------- Perform a multi query search ----------
-    if (queryList.Count() > 1) // multiple query
+    // (3)-------------------- Perform a multi query search -------------------
+    else // multiple query
         {
         PRINT ( _L("Query received is in multiple. Performing a multi search.") );
 
-        TInt mode = aQuery.KeyboardModeL();
-        iFindUtilECE->SetKeyboardMode(mode);
-
-        for (int i = 0; i < queryList.Count(); i++)
-            {
-            TPtrC queryPtr = queryList[i]->QueryAsStringLC();
-            PRINT2 ( _L("Received Query, index = %d; value = %S"), i, &queryPtr );
-            CleanupStack::PopAndDestroy();
-            }
-
         // Search results
         iMultiSearchHelper->SearchMultiL(*tempSettings, queryList, isGroupSearch, 
-                                         contactsInGroup, searchResults, searchSeqs, 
-                                         mode);
+                                         contactsInGroup, aSearchResults, aSearchSeqs);
         }
     // -------------------------------------------------------------------------	
 
     // Cleanup
-    delete tempSettings;
-    tempSettings = NULL;
+    
+    CleanupStack::PopAndDestroy( &queryList ); // ResetAndDestroy
+    CleanupStack::PopAndDestroy( tempSettings );
+    CleanupStack::PopAndDestroy( &groupIdArray ); // Close
+    CleanupStack::PopAndDestroy( &contactsInGroup ); // Close
 
-    groupIdArray.Close();
-    contactsInGroup.Close();
-    queryList.ResetAndDestroy();
+	//__LATENCY_MARKEND ( _L("CPcsAlgorithm2::DoSearchL") );
 
     PRINT ( _L("End CPcsAlgorithm2::DoSearchL") );
     }
@@ -524,56 +595,49 @@
 // CPcsAlgorithm2::DoSearchInputL
 // Search function helper
 // ----------------------------------------------------------------------------
-void CPcsAlgorithm2::DoSearchInputL(CPsQuery& aQuery, TDesC& aData,
+void CPcsAlgorithm2::DoSearchInputL(CPsQuery& aQuery, 
+                                    const TDesC& aData,
                                     RPointerArray<TDesC>& aMatchSet,
                                     RArray<TPsMatchLocation>& aMatchLocation)
     {
 
+    //__LATENCY_MARK ( _L("CPcsAlgorithm2::SearchInputL: ") );
     PRINT ( _L("Enter CPcsAlgorithm2::DoSearchInputL") );
 
     // Check if any seperator is there in the query
     RPointerArray<CPsQuery> queryList = iMultiSearchHelper->MultiQueryL(aQuery);
+    CleanupResetAndDestroyPushL( queryList );
 
     // No query    
     if (queryList.Count() == 0)
         {
         PRINT ( _L("Query received is empty") );
+        CleanupStack::PopAndDestroy( &queryList ); // ResetAndDestroy
         return;
         }
 
-    RPointerArray<HBufC> convertedQuery;
-    iMultiSearchHelper->ConvertQueryToListL(queryList, convertedQuery);
-
     // Single query
     if (queryList.Count() == 1)
         {
-        iHelper->SearchMatchSeqL(convertedQuery[0], aData, aMatchSet, aQuery,
-                                 aMatchLocation);
-
+        iHelper->SearchMatchSeqL(aQuery, aData, aMatchSet, aMatchLocation);
         }
 
     if (queryList.Count() > 1) // multiple query
         {
         PRINT ( _L("Query received is in multiple. Performing a multi search.") );
 
-        for (int i = 0; i < queryList.Count(); i++)
-            {
-            TPtrC queryPtr = queryList[i]->QueryAsStringLC();
-            PRINT2 ( _L("Rceived Query, index = %d; value = %S"), i, &queryPtr );
-            CleanupStack::PopAndDestroy();
-            }
-
         // Search results
-        iMultiSearchHelper->SearchMatchSeqMultiL(queryList, aData, aMatchSet,
+        iMultiSearchHelper->SearchMatchSeqMultiL(queryList, 
+                                                 aData, 
+                                                 aMatchSet,
                                                  aMatchLocation);
-
         }
 
     // Delete all the query elements
-    queryList.ResetAndDestroy();
-    convertedQuery.ResetAndDestroy();
+    CleanupStack::PopAndDestroy( &queryList ); // ResetAndDestroy
+    PRINT ( _L("End CPcsAlgorithm2::DoSearchInputL") );
+    //__LATENCY_MARKEND ( _L("CPcsAlgorithm2::SearchInputL") );
 
-    PRINT ( _L("End CPcsAlgorithm2::DoSearchInputL") );
     }
 
 // ----------------------------------------------------------------------------
@@ -640,21 +704,17 @@
         return;
 
     CPcsCache* cache = iPcsCache[dataStoreIndex];
-    TRAPD(err, cache->RemoveAllFromCacheL());
-
-    if (err != KErrNone)
-        {
-        SetCachingError(aDataStore, err);
-        }
+    cache->RemoveAllFromCache();
     }
 
 // ----------------------------------------------------------------------------
 // CPcsAlgorithm2::GetCacheIndex
 // Return the cache index for a data store
 // ----------------------------------------------------------------------------
-TInt CPcsAlgorithm2::GetCacheIndex(TDesC& aDataStore)
+TInt CPcsAlgorithm2::GetCacheIndex(const TDesC& aDataStore)
     {
-    for (int i = 0; i < iPcsCache.Count(); i++)
+    const TInt pcsCacheCount = iPcsCache.Count();
+    for (int i = 0; i <pcsCacheCount; i++)
         {
         CPcsCache* cache = iPcsCache[i];
 
@@ -738,6 +798,7 @@
 // ----------------------------------------------------------------------------
 void CPcsAlgorithm2::RemoveDataStore(TDesC& aDataStore)
     {
+
     for (int i = 0; i < iPcsCache.Count(); i++)
         {
         CPcsCache* cache = iPcsCache[i];
@@ -764,12 +825,12 @@
 // CPcsAlgorithm2::GetUriForIdL
 // Get the URI string for this internal id
 // ----------------------------------------------------------------------------
-TDesC& CPcsAlgorithm2::GetUriForIdL(TUint8 aUriId)
+const TDesC& CPcsAlgorithm2::GetUriForIdL(TUint8 aUriId)
     {
     TBool found = EFalse;
     TInt i = 0;
-
-    for (i = 0; i < iPcsCache.Count(); i++)
+    const TInt pcsCacheCount = iPcsCache.Count();
+    for (i = 0; i < pcsCacheCount; i++)
         {
         if (iPcsCache[i]->GetUriId() == aUriId)
             {
@@ -790,17 +851,18 @@
 // CPcsAlgorithm2::FindStoreUri
 // Checks if this store exists
 // ----------------------------------------------------------------------------
-TInt CPcsAlgorithm2::FindStoreUri(TDesC& aDataStore)
+TInt CPcsAlgorithm2::FindStoreUri(const TDesC& aDataStore)
     {
-    for (int i = 0; i < iPcsCache.Count(); i++)
+    const TInt pcsCacheCount = iPcsCache.Count();
+    for ( TInt i = 0; i < pcsCacheCount; i++ )
         {
-        if (aDataStore.CompareC(*(iPcsCache[i]->GetUri())) == 0)
+        if ( aDataStore.CompareC(*(iPcsCache[i]->GetUri())) == 0 )
             {
             return i;
             }
         }
 
-    return -1;
+    return KErrNotFound;
     }
 
 // ----------------------------------------------------------------------------
@@ -808,8 +870,10 @@
 // Update caching status
 // ----------------------------------------------------------------------------
 void CPcsAlgorithm2::UpdateCachingStatus(TDesC& aDataStore, TInt aStatus)
-    {
+{
     PRINT ( _L("Enter CPcsAlgorithm2::UpdateCachingStatus") );
+    PRINT2 ( _L("CPcsAlgorithm2::UpdateCachingStatus: Request received for URI=%S with status=%d"),
+             &aDataStore, aStatus );
 
     // Handle data store update events
     if ( aStatus == ECacheUpdateContactRemoved ||
@@ -822,82 +886,108 @@
 
     // If not a cache update event, then this event is related to the initial
     // cache construction.
-    TInt index = FindStoreUri(aDataStore);
-    iPcsCache[index]->UpdateCacheStatus(aStatus);
+
+    // Check if any error occurred and update the cache error
+    if ( aStatus < 0 )
+    {
+        SetCachingError(aDataStore, aStatus);
+    }
+    else
+    {
+        TInt index = FindStoreUri(aDataStore);
+        iPcsCache[index]->UpdateCacheStatus(aStatus);
+    }
 
-    // Check if any error occurred
-    // If so, update the cache status, Set the property and return
-    if (aStatus < 0)
-        {
-        SetCachingError(aDataStore, aStatus);
-        //return;
-        }
+    TCachingStatus status = ECachingNotStarted;
+    TUint countNotStarted = 0;
+    TUint countInProgress = 0;
+    TUint countCompleted = 0;
+    TUint countCompletedWithErrors = 0;
+    TInt cacheCount = iPcsCache.Count();
+    for ( TInt i = 0; i < cacheCount; i++ )
+    {
+        PRINT3 ( _L("CPcsAlgorithm2::UpdateCachingStatus: URI[%d]=%S, cache status=%d"),
+                 i, &iPcsCache[i]->GetURI(), iPcsCache[i]->GetCacheStatus() );
 
-    //store the index for firstname and lastname
-    if (aStatus == ECachingComplete)
+        switch ( iPcsCache[i]->GetCacheStatus() )
         {
-        RArray<TInt> dataFields;
-        iPcsCache[index]->GetDataFields(dataFields);
-
-        for (int i = 0; i < dataFields.Count(); i++)
+            case ECachingNotStarted:         
+            {
+                countNotStarted++;          
+                break;
+            }
+            case ECachingInProgress:         
+            {
+                countInProgress++;         
+                break;
+            }
+            case ECachingComplete:           
             {
-            if (dataFields[i] == R_VPBK_FIELD_TYPE_FIRSTNAME)
-                {
-                iFirstNameIndex = i;
-                }
-            else if (dataFields[i] == R_VPBK_FIELD_TYPE_LASTNAME)
-                {
-                iLastNameIndex = i;
-                }
+                countCompleted++;           
+                break;
+            }
+            case ECachingCompleteWithErrors: 
+            {
+                countCompletedWithErrors++; 
+                break;
+            }
+            default:                         
+            { 
+                // Default completed state
+                countCompleted++;           
+                break;
             }
         }
+    }
 
-    // No error occurred
-    TCachingStatus status = ECachingComplete;
-    TBool atLeastOneStoreCachingCompleteWithErrors(EFalse);
-    for (TInt i = 0; i < iPcsCache.Count(); i++)
-        {
-        if (iPcsCache[i]->GetCacheStatus() == ECachingComplete)
-            {
-            continue;
-            }
-        else if (iPcsCache[i]->GetCacheStatus() == ECachingCompleteWithErrors)
-            {
-            atLeastOneStoreCachingCompleteWithErrors = ETrue;
-            continue;
-            }
-        else
-            {
-            status = ECachingInProgress;
-            break;
-            }
-        }
+    // Calculate cumulative status according to single caches statuses
+    if ( countCompleted > 0 && ( countCompleted + countNotStarted ) == cacheCount )
+    {
+        // If at least one caching is finished
+        // set status to ECachingComplete or ECachingCompleteWithErrors
+        // according to iCacheError
+        status = ( iCacheError == KErrNone ) ? ECachingComplete : ECachingCompleteWithErrors;
+    }
+    else if ( countInProgress > 0 )
+    {
+        // Else if at least one caching is in progress,
+        // set status to ECachingInProgress
+        status = ECachingInProgress;
+    }
+    else if ( countCompletedWithErrors > 0 )
+    {
+        // Else if at least one caching is completed with errors, 
+        //set status to ECachingCompleteWithErrors
+        status = ECachingCompleteWithErrors;
+    }
+    else
+    {
+        // countNotStarted == cacheCount
+        // status is set to default ECachingNotStarted
+    }
 
-    if (status == ECachingComplete)
-        {
-        // See if any error occurred while caching
-        // If so, change the status to ECachingCompleteWithErrors
-        if ((iCacheError != KErrNone) || (atLeastOneStoreCachingCompleteWithErrors))
-            {
-            status = ECachingCompleteWithErrors;
-            }
-        }
+    PRINT1 ( _L("CPcsAlgorithm2::UpdateCachingStatus: Cumulative caching status is %d"),
+             status );
 
     // Check if status changed
-    if (status != iCacheStatus)
-        {
+    if ( status != iCacheStatus )
+    {
+        PRINT2 ( _L("CPcsAlgorithm2::UpdateCachingStatus: Cumulative caching changed: %d -> %d"),
+                 iCacheStatus, status );
+
         iCacheStatus = status;
         RProperty::Set(KPcsInternalUidCacheStatus, EPsKeyCacheStatus, iCacheStatus );
-        }
+    }
 
-    PRINT ( _L("End CPcsAlgorithm2::UpdateCachingStatus") );
-    }
+    PRINT( _L("End CPcsAlgorithm2::UpdateCachingStatus") );
+}
+
 
 // ----------------------------------------------------------------------------
 // CPcsAlgorithm2::SetCachingError
 // Updates cachinge error
 // ----------------------------------------------------------------------------
-void CPcsAlgorithm2::SetCachingError(TDesC& aDataStore, TInt aError)
+void CPcsAlgorithm2::SetCachingError(const TDesC& aDataStore, TInt aError)
     {
     PRINT2 ( _L("SetCachingError::URI %S ERROR %d"), &aDataStore, aError );
 
@@ -912,25 +1002,33 @@
 void CPcsAlgorithm2::GetAllContentsL(const CPsSettings& aSettings,
                                      RPointerArray<CPsData>& aResults)
     {
-    __LATENCY_MARK ( _L("CPcsAlgorithm2::GetAllContentsL") );
+    //__LATENCY_MARK ( _L("CPcsAlgorithm2::GetAllContentsL") );
 
     PRINT ( _L("Enter CPcsAlgorithm2::GetAllContentsL") );
 
-    // Get the data stores
-    RPointerArray<TDesC> aDataStores;
-    aSettings.SearchUrisL(aDataStores);
-
     // To hold array of results from different data stores
     typedef RPointerArray<CPsData> CPSDATA_R_PTR_ARRAY;
-    RPointerArray<CPSDATA_R_PTR_ARRAY> iSearchResultsArr;
+    RPointerArray<CPSDATA_R_PTR_ARRAY> searchResultsArr;
+    CleanupResetAndDestroyPushL( searchResultsArr );
+    // TODO: Here's still a potential memory leak if a leave happens. The child
+    // arrays of searchResultsArr are not Reset in that case. The CPsData objects
+    // may leak as well. Handling this safely is somewhat complicated because some of
+    // the CPsData objects may already be transferred to ownership of aResults array
+    // at the time the leave happens, and those items must not be deleted.
+    
+    // Get the data stores
+    RPointerArray<TDesC> dataStores;
+    CleanupResetAndDestroyPushL( dataStores );
+    aSettings.SearchUrisL(dataStores);
 
     // Get all contacts for each data store
-    for (int dsIndex = 0; dsIndex < aDataStores.Count(); dsIndex++)
+    const TInt dataStoresCount = dataStores.Count(); 
+    for (TInt dsIndex = 0; dsIndex < dataStoresCount; dsIndex++)
         {
         RPointerArray<CPsData> *temp = new (ELeave) RPointerArray<CPsData> ();
-        iSearchResultsArr.Append(temp);
+        searchResultsArr.Append(temp);
 
-        TInt arrayIndex = GetCacheIndex(*(aDataStores[dsIndex]));
+        TInt arrayIndex = GetCacheIndex(*(dataStores[dsIndex]));
         if (arrayIndex < 0)
             {
             continue;
@@ -938,29 +1036,28 @@
 
         CPcsCache* cache = GetCache(arrayIndex);
 
-        cache->GetAllContentsL(*(iSearchResultsArr[dsIndex]));
+        cache->GetAllContentsL(*(searchResultsArr[dsIndex]));
         }
 
-    aDataStores.ResetAndDestroy();
+    CleanupStack::PopAndDestroy( &dataStores ); // ResetAndDestroy
 
     // Merge the results from different data stores
-    CPcsAlgorithm2Utils::FormCompleteSearchResultsL(iSearchResultsArr, aResults);
+    CPcsAlgorithm2Utils::FormCompleteSearchResultsL(searchResultsArr, aResults);
 
     // Cleanup the local arrays
-    for (TInt i = 0; i < iSearchResultsArr.Count(); i++)
+    const TInt seaerchResultsArrCount = searchResultsArr.Count(); 
+    for (TInt i = 0; i < seaerchResultsArrCount; i++)
         {
-        iSearchResultsArr[i]->Reset();
-        delete iSearchResultsArr[i];
-        iSearchResultsArr[i] = NULL;
+        searchResultsArr[i]->Reset();
         }
 
-    iSearchResultsArr.Reset();
+    CleanupStack::PopAndDestroy( &searchResultsArr ); // ResetAndDestroy
 
     PRINT1 ( _L("Number of results = %d"), aResults.Count() );
 
     PRINT ( _L("End CPcsAlgorithm2::GetAllContentsL") );
 
-    __LATENCY_MARKEND ( _L("CPcsAlgorithm2::GetAllContentsL") );
+    //__LATENCY_MARKEND ( _L("CPcsAlgorithm2::GetAllContentsL") );
     }
 
 // ----------------------------------------------------------------------------
@@ -977,18 +1074,18 @@
 
     // Get the current URIs defined in settings    
     RPointerArray<TDesC> searchUris;
+    CleanupResetAndDestroyPushL( searchUris );
     aSettings.SearchUrisL(searchUris);
 
     if (aGroupIdArray.Count() && (searchUris.Count() > aGroupIdArray.Count()))
         {
         // There is an error, either there are more than one groups
         // or the settings contain a combination of group/non-group Uris
-        searchUris.ResetAndDestroy();
         aGroupIdArray.Close();
         User::Leave(KErrArgument);
         }
 
-    searchUris.ResetAndDestroy();
+    CleanupStack::PopAndDestroy( &searchUris ); // ResetAndDestroy
 
     PRINT ( _L("End CPcsAlgorithm2::IsGroupSearchL") );
 
@@ -1005,15 +1102,16 @@
 void CPcsAlgorithm2::ReplaceGroupsUriL(CPsSettings& aSettings)
     {
     RPointerArray<TDesC> uri;
+    CleanupResetAndDestroyPushL( uri );
 
     // Set contacts db uri
-    HBufC* cntdb = HBufC::NewL(KBufferMaxLen);
-    cntdb->Des().Copy(KVPbkDefaultCntDbURI);
-    uri.Append(cntdb);
+    HBufC* cntdb = KVPbkDefaultCntDbURI().AllocLC();
+    uri.AppendL(cntdb);
+    CleanupStack::Pop( cntdb ); // ownership transferred
     aSettings.SetSearchUrisL(uri);
 
     // Cleanup
-    uri.ResetAndDestroy();
+    CleanupStack::PopAndDestroy( &uri ); // ResetAndDestroy
     }
 
 // ----------------------------------------------------------------------------
@@ -1055,28 +1153,22 @@
     {
     // Clear results array
     aGroupContactIds.Reset();
-
-    // Groups URI
-    HBufC* groupURI = HBufC::NewL(50);
-    groupURI->Des().Copy(KVPbkDefaultGrpDbURI);
-
-    // Cache Index   
-    TInt cacheIndex = GetCacheIndex(*groupURI);
-
-    // Cleanup
-    delete groupURI;
-    groupURI = NULL;
-
+    
+    // Cache Index for group database
+    TInt cacheIndex = GetCacheIndex(KVPbkDefaultGrpDbURI);
+    
     // Get the groups contact ids 
     if (cacheIndex != -1)
         {
         RPointerArray<CPsData> groups;
+        CleanupClosePushL( groups );
 
         // Get all groups
         iPcsCache[cacheIndex]->GetAllContentsL(groups);
 
         // Get all contacts in group
-        for (TInt i = 0; i < groups.Count(); i++)
+        const TInt groupsCount = groups.Count(); 
+        for (TInt i = 0; i < groupsCount; i++)
             {
             if (groups[i]->Id() == aGroupId)
                 {
@@ -1085,7 +1177,7 @@
                 }
             }
 
-        groups.Reset();
+        CleanupStack::PopAndDestroy( &groups ); // Close
         }
     }
 
@@ -1102,8 +1194,7 @@
     if (CPcsAlgorithm2Utils::IsGroupUri(aURI))
         {
         // If search in a group uri, use contacts db
-        TBuf<255> cntdb(KVPbkDefaultCntDbURI);
-        arrayIndex = GetCacheIndex(cntdb);
+        arrayIndex = GetCacheIndex(KVPbkDefaultCntDbURI);
         }
     else
         {
@@ -1138,8 +1229,7 @@
     if (CPcsAlgorithm2Utils::IsGroupUri(aURI))
         {
         // If search in a group uri, use contacts db
-        TBuf<255> cntdb(KVPbkDefaultCntDbURI);
-        arrayIndex = GetCacheIndex(cntdb);
+        arrayIndex = GetCacheIndex(KVPbkDefaultCntDbURI);
         }
     else
         {
@@ -1197,7 +1287,8 @@
     if (aSortOrder.Count() == mySortOrder.Count())
         {
         TBool same = ETrue;
-        for (int i = 0; i < mySortOrder.Count(); i++)
+        const TInt mySourtOrderCount = mySortOrder.Count(); 
+        for ( TInt i = 0; i < mySourtOrderCount ; i++ )
             {
             if (mySortOrder[i] != aSortOrder[i])
                 {
@@ -1239,22 +1330,11 @@
     PRINT ( _L("End CPcsAlgorithm2::ChangeSortOrderL.") );
     }
 
-// ----------------------------------------------------------------------------
-// CPcsAlgorithm2::GetAdaptiveGridL
-// 
-// ----------------------------------------------------------------------------
-void CPcsAlgorithm2::GetAdaptiveGridL( const MDesCArray& /*aURIs*/,
-                                       const TBool /*aCompanyName*/,
-                                       TDes& /*aAdaptiveGrid*/ )
-    {
-    //NOT IMPLEMENTED YET
-    }
-
 // ---------------------------------------------------------------------------------
 // Read the persisted sort order from the central repository
 // Persisted sort order is of form URI Field1 Field2 Field3 .. FieldN (space delimited)
 // ---------------------------------------------------------------------------------
-void CPcsAlgorithm2::ReadSortOrderFromCenRepL(TDesC& aURI, RArray<TInt>& aSortOrder)
+void CPcsAlgorithm2::ReadSortOrderFromCenRepL(const TDesC& aURI, RArray<TInt>& aSortOrder)
     {
     PRINT ( _L("Enter CPcsAlgorithm2::ReadSortOrderFromCenRepL.") );
 
@@ -1265,8 +1345,9 @@
     // Read the sort order from cenrep
     TBuf<KCRMaxLen> str;
 
-    for (TInt i(KCenrepFieldsStartKey); i < KCenrepFieldsStartKey
-            + KCenrepNumberOfFieldsCount; i++)
+    for ( TInt i(KCenrepFieldsStartKey); 
+          i < KCenrepFieldsStartKey + KCenrepNumberOfFieldsCount; 
+          i++ )
         {
         TInt err = repository->Get(i, str);
 
@@ -1318,18 +1399,19 @@
 // Write the sort order into the central repository
 // Persisted sort order is of form URI Field1 Field2 Field3 .. FieldN (space delimited)
 // ---------------------------------------------------------------------------------
-void CPcsAlgorithm2::WriteSortOrderToCenRepL(TDesC& aURI, RArray<TInt>& aSortOrder)
+void CPcsAlgorithm2::WriteSortOrderToCenRepL(const TDesC& aURI, RArray<TInt>& aSortOrder)
     {
     PRINT ( _L("Enter CPcsAlgorithm2::WriteSortOrderToCenRepL.") );
 
-    CRepository *repository = CRepository::NewL(KCRUidPSSortOrder);
+    CRepository* repository = CRepository::NewLC(KCRUidPSSortOrder);
 
     // Check if there an entry for this URI in cenrep
     TBuf<KCRMaxLen> str;
     TInt keyIndex = -1;
 
-    for (TInt i(KCenrepFieldsStartKey); i < KCenrepFieldsStartKey
-            + KCenrepNumberOfFieldsCount; i++)
+    for ( TInt i(KCenrepFieldsStartKey); 
+          i < KCenrepFieldsStartKey + KCenrepNumberOfFieldsCount; 
+          i++ )
         {
         TInt err = repository->Get(i, str);
 
@@ -1359,8 +1441,9 @@
     if (keyIndex == -1)
         {
         // Find the next free key index
-        for (TInt i(KCenrepFieldsStartKey); i < KCenrepFieldsStartKey
-                + KCenrepNumberOfFieldsCount; i++)
+        for ( TInt i(KCenrepFieldsStartKey); 
+              i < KCenrepFieldsStartKey + KCenrepNumberOfFieldsCount; 
+              i++ )
             {
             TInt err = repository->Get(i, str);
 
@@ -1385,7 +1468,7 @@
         }
 
     // Persist the sort order
-    HBufC* str1 = HBufC::NewL(KCRMaxLen);
+    HBufC* str1 = HBufC::NewLC(KCRMaxLen);
     TPtr ptr(str1->Des());
 
     // Append the URI
@@ -1393,7 +1476,8 @@
     ptr.Append(KSpace);
 
     // Append the sort order fields
-    for (int j = 0; j < aSortOrder.Count(); j++)
+    const TInt sortOrderCount =  aSortOrder.Count();
+    for (TInt j = 0; j < sortOrderCount; j++)
         {
         ptr.AppendNum(aSortOrder[j]);
         ptr.Append(KSpace);
@@ -1404,9 +1488,9 @@
 
     User::LeaveIfError(err);
 
-    delete str1;
+    CleanupStack::PopAndDestroy( str1 );
 
-    delete repository;
+    CleanupStack::PopAndDestroy( repository );
 
     PRINT ( _L("End CPcsAlgorithm2::WriteSortOrderToCenRepL.") );
     }
@@ -1427,7 +1511,8 @@
     clientData->SetUriL(GetUriForIdL(aPsData.UriId()));
 
     // set pointer to the each data element
-    for (TInt i = 0; i < aPsData.DataElementCount(); i++)
+    const TInt dataElementCount = aPsData.DataElementCount(); 
+    for (TInt i = 0; i <dataElementCount; i++)
         {
         clientData->SetDataL(i, *(aPsData.Data(i)));
         }
@@ -1466,11 +1551,11 @@
         default:
             break;
         }
-
-    if ( psKey != KErrNotFound )
+    
+    // Increment the relevant counter in P&S by one to signal the clients about
+    // the cache update.
+    if( psKey != KErrNotFound )
         {
-        // Increment the relevant counter in P&S by one to signal the clients about
-        // the cache update.
         TInt counter( KErrNotFound );
         TInt err = RProperty::Get( KPcsInternalUidCacheStatus, psKey, counter );
         if ( !err )
@@ -1495,25 +1580,24 @@
         PRINT1 ( _L("keyMap ReconstructKeymapL, err =%d"),err );
         }
     
-    for (int index = 0; index < iCacheCount; index++)
+    for (TInt index = 0; index < iCacheCount; index++)
         {
         CPcsCache* cache = iPcsCache[index];
 
-        HBufC * uri = cache->GetUri();
+        HBufC* uri = cache->GetUri();
         // Clear the cache
-        TRAP(err, cache->RemoveAllFromCacheL());   
-        PRINT1 ( _L("cache RemoveAllFromCacheL, err =%d"),err );
+        cache->RemoveAllFromCache();
 
         if (err != KErrNone)
             {
             SetCachingError(*uri, err);
             }
         //Update the caching status as ECachingInProgress, since now the caching
-        // would be strated again
+        // would be started again
         UpdateCachingStatus(*uri, ECachingInProgress);
 
         // Request for data again
-        TRAP(err, iPsDataPluginInterface->RequestForDataL(*uri));        
+        TRAP(err, iPsDataPluginInterface->RequestForDataL(*uri));
         PRINT1 ( _L("iPsDataPluginInterface->RequestForDataL, err =%d"),err );
 
         if (err != KErrNone)
@@ -1523,14 +1607,6 @@
         }
     }
 
-void CPcsAlgorithm2::Converter(const TDesC& aSourStr, TDes& aDestStr)
-    {
-    if (iKeyMap)
-        {
-        iKeyMap->GetNumericKeyString(aSourStr, aDestStr);
-        }
-    }
-
 // ---------------------------------------------------------------------------------
 // DoLaunchPluginsL.
 // launch plugins by idle
@@ -1561,15 +1637,32 @@
 
     // Initialize cache
     RPointerArray<TDesC> dataStores;
+    CleanupClosePushL( dataStores );
 
     iPsDataPluginInterface->GetAllSupportedDataStoresL(dataStores);
 
-    for (int dIndex = 0; dIndex < dataStores.Count(); dIndex++)
+    const TInt dataStoresCount = dataStores.Count();
+    for (TInt dIndex = 0; dIndex < dataStoresCount; dIndex++)
         {
         AddDataStore(*(dataStores[dIndex]));
         }
 
-    dataStores.Reset();
+    CleanupStack::PopAndDestroy( &dataStores ); // Close
+    }
+
+/**
+* Returns the Adaptive Grid for one or more URI
+* 
+*/
+ void CPcsAlgorithm2::GetAdaptiveGridL( const MDesCArray& /*aURIs*/,
+                               const TBool /*aCompanyName*/,
+                               TDes& /*aAdaptiveGrid*/ )
+    {
+     PRINT ( _L("Enter CPcsAlgorithm2::GetAdaptiveGridL") );
+
+
+     PRINT ( _L("End CPcsAlgorithm2::GetAdaptiveGridL") );
+
     }
 // End of file
 
--- a/predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsAlgorithm2FilterHelper.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsAlgorithm2FilterHelper.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -20,8 +20,8 @@
 #include "CPcsDebug.h"
 
 // Compare functions
-TBool ComparePsPattern(const TPsPatternDetails& aFirst,
-                       const TPsPatternDetails& aSecond)
+TInt ComparePsPattern(const TPsPatternDetails& aFirst,
+                      const TPsPatternDetails& aSecond)
     {
     return (CPcsAlgorithm2Utils::MyCompareC(*(aFirst.matchPattern),
                                             *(aSecond.matchPattern)));
@@ -109,7 +109,7 @@
 // CPcsAlgorithm2FilterHelper::AddL
 // 
 // ----------------------------------------------------------------------------
-void CPcsAlgorithm2FilterHelper::AddL(CPsData* psData, RPointerArray<TDesC>& aPatternSequence)
+void CPcsAlgorithm2FilterHelper::AddL(CPsData* aPsData, RPointerArray<TDesC>& aPatternSequence)
     {
     if (iSortType == EAlphabetical)
         {
@@ -117,44 +117,46 @@
         if (iMatchPatternPools.Count() == 0)
             {
             RPointerArray<CPsData> *tempPsDataArray = new (ELeave) RPointerArray<CPsData> ();
-            iMatchPatternPools.Append(tempPsDataArray);
+            CleanupStack::PushL( tempPsDataArray );
+            iMatchPatternPools.AppendL(tempPsDataArray);
+            CleanupStack::Pop( tempPsDataArray );
             }
         // Add result to the result set
-        iMatchPatternPools[0]->Append(psData);
+        iMatchPatternPools[0]->AppendL(aPsData);
 
         // Update the count
         iResultCount++;
 
         // Update sequence list
-        for (TInt i = 0; i < aPatternSequence.Count(); i++)
+        const TInt patternSequenceCount = aPatternSequence.Count();
+        for (TInt i = 0; i < patternSequenceCount; i++)
             {
-            TInt index = FindSequence(aPatternSequence[i]);
+            TInt index = FindSequence(*aPatternSequence[i]);
             if (index == KErrNotFound)
                 {
                 // sequence not found, add it to array
                 TPsPatternDetails* temp = new (ELeave) TPsPatternDetails;
-
-                TInt len = aPatternSequence[i]->Length();
-                temp->matchPattern = HBufC::NewL(len);
-                temp->matchPattern->Des().Copy(*(aPatternSequence[i]));
+                CleanupStack::PushL( temp );
+                
+                temp->matchPattern = aPatternSequence[i]->AllocL();
 
                 // First occurence should be -1 for alphabetical sort
                 // and pool index will be 0 as only one pool will be created
                 temp->firstOccurence = -1;
                 temp->poolIndex = 0;
 
-                iMatchPatternDetails.Append(temp);
+                iMatchPatternDetails.AppendL(temp);
+                CleanupStack::Pop( temp );
                 }
             }
         }
     else
         {
         // PatternBased sort
-        TInt index = AddToPoolL(psData, aPatternSequence);
+        TInt index = AddToPoolL(aPsData, aPatternSequence);
 
         // Increment the total count
         iResultCount++;
-
         }
     }
 
@@ -163,7 +165,7 @@
 // 
 // ----------------------------------------------------------------------------
 
-TInt CPcsAlgorithm2FilterHelper::AddToPoolL(CPsData* psData, RPointerArray<TDesC>& aPatternSequence)
+TInt CPcsAlgorithm2FilterHelper::AddToPoolL(CPsData* aPsData, RPointerArray<TDesC>& aPatternSequence)
     {
 
     // Sort the pattern sequence
@@ -179,12 +181,13 @@
     TInt poolItemCount = -1;
     TInt matchpatterpoolIndexToAppend = -1;
 
-    for (TInt cnt = 0; cnt < aPatternSequence.Count(); cnt++)
+    const TInt patternSequenceCount = aPatternSequence.Count();
+    for (TInt cnt = 0; cnt < patternSequenceCount; cnt++)
         {
 
         // Create the pattern for aPatternSequence[cnt] in  iMatchPatternDetails
         // and return the index
-        TInt indexInMatchPatternDetails = CreateMatchPatternDetailsAndPoolsL(aPatternSequence[cnt]);
+        TInt indexInMatchPatternDetails = CreateMatchPatternDetailsAndPoolsL(*aPatternSequence[cnt]);
 
         //Add the data to the pool the first pattern pool.
         // The data should be added only once
@@ -192,8 +195,8 @@
             {
             TInt poolIndex = iMatchPatternDetails[indexInMatchPatternDetails]->poolIndex;
             matchpatterpoolIndexToAppend = indexInMatchPatternDetails;
-            iMatchPatternPools[poolIndex]->InsertInOrderAllowRepeats(psData, psDataRule);
-            TInt findposition = iMatchPatternPools[poolIndex]->Find(psData, identitySearchRule);
+            iMatchPatternPools[poolIndex]->InsertInOrderAllowRepeats(aPsData, psDataRule);
+            TInt findposition = iMatchPatternPools[poolIndex]->Find(aPsData, identitySearchRule);
             if (findposition != KErrNotFound)
                 {
                 poolItemCount = findposition;
@@ -208,7 +211,7 @@
             {
             // Check if aPatternSequence[cnt] is listed in subpatterns of aPatternSequence[0]
             // If not, then create a sub pattern and apped it to  iMatchPatternDetails for aPatternSequence[0]
-            TInt subSeq = FindSubSequence(aPatternSequence[cnt], matchpatterpoolIndexToAppend);
+            TInt subSeq = FindSubSequence(*aPatternSequence[cnt], matchpatterpoolIndexToAppend);
             if (subSeq == KErrNotFound)
                 {
                 //Create the subpattern and append it.
@@ -230,7 +233,7 @@
 // Returns the index of the sequence in iMatchPatternDetails
 // ----------------------------------------------------------------------------
 
-TInt CPcsAlgorithm2FilterHelper::CreateMatchPatternDetailsAndPoolsL(TDesC* aSeq)
+TInt CPcsAlgorithm2FilterHelper::CreateMatchPatternDetailsAndPoolsL(const TDesC& aSeq)
     {
 
     TInt indexInMatchPatternDetails = FindSequence(aSeq);
@@ -240,8 +243,7 @@
         TPsPatternDetails* tempPatternDetailsInstance = new (ELeave) TPsPatternDetails;
 
         //TInt len = aPatternSequence[cnt]->Length();
-        tempPatternDetailsInstance->matchPattern = HBufC::NewL(aSeq->Length());
-        tempPatternDetailsInstance->matchPattern->Des().Copy(*(aSeq));
+        tempPatternDetailsInstance->matchPattern = aSeq.Alloc();
         tempPatternDetailsInstance->firstOccurence = -1; //RAVIKIRAN
 
         // Pools doesn't exist for this sequence..
@@ -282,7 +284,8 @@
     if (iSortType == EAlphabetical)
         {
         // Return the results stored in single array
-        for (TInt i = 0; i < iMatchPatternPools[0]->Count(); i++)
+        const TInt cnt = iMatchPatternPools[0]->Count();
+        for (TInt i = 0; i < cnt; i++)
             {
             aSearchResults.Append((*(iMatchPatternPools[0]))[i]);
             }
@@ -293,18 +296,21 @@
     else
         {
         TInt firstOccurenceTracker = 0;
-        for (TInt i = 0; i < iMatchPatternDetails.Count(); i++)
+        const TInt matchPatternDetailsCount = iMatchPatternDetails.Count();
+        for (TInt i = 0; i < matchPatternDetailsCount; i++)
             {
             // Get the mapping pool index for this sequence
             TInt index = iMatchPatternDetails[i]->poolIndex;
             TInt j = 0;
-            for (; j < iMatchPatternPools[index]->Count(); j++)
+            const TInt poolCount = iMatchPatternPools[index]->Count();
+            for (; j < poolCount; j++)
                 {
                 aSearchResults.Append((*(iMatchPatternPools[index]))[j]);
                 }
 
             // Check the sub patterns
-            for (TInt k = 0; k < iMatchPatternDetails[i]->subPatternArray.Count(); k++)
+            const TInt subPatternArrayCount =  iMatchPatternDetails[i]->subPatternArray.Count();
+            for (TInt k = 0; k < subPatternArrayCount; k++)
                 {
                 HBufC* temporseq = iMatchPatternDetails[i]->subPatternArray[k]->matchPattern;
                 TRAP_IGNORE( UpdateForSubSequencesL( *temporseq, 
@@ -334,7 +340,8 @@
     TLinearOrder<TPsPatternDetails> rule(ComparePsPattern);
     iMatchPatternDetails.Sort(rule);
 
-    for (TInt i = 0; i < iMatchPatternDetails.Count(); i++)
+    const TInt matchPatternDetailsCount = iMatchPatternDetails.Count(); 
+    for (TInt i = 0; i < matchPatternDetailsCount; i++)
         {
         CPsPattern *tempPattern = CPsPattern::NewL();
 
@@ -351,17 +358,14 @@
 // Searches for for aSeq in iMatchPatternDetails and returns index 
 //  where input sequence is found. Returns -1 if not found
 // ----------------------------------------------------------------------------
-TInt CPcsAlgorithm2FilterHelper::FindSequence(TDesC* aSeq)
+TInt CPcsAlgorithm2FilterHelper::FindSequence(const TDesC& aSeq)
     {
-    TBuf<50> seqBuf;
-    seqBuf.Append(*aSeq);
-
     TInt j = 0;
-    for (; j < iMatchPatternDetails.Count(); j++)
+    const TInt matchPatternDetailsCount =  iMatchPatternDetails.Count();
+    for (; j < matchPatternDetailsCount; j++)
         {
-        TBuf<50> matchPatternBuf;
-        matchPatternBuf.Copy((iMatchPatternDetails[j]->matchPattern->Des()));
-        if (seqBuf == matchPatternBuf)
+        const TDesC& matchPattern = *(iMatchPatternDetails[j]->matchPattern);
+        if ( CPcsAlgorithm2Utils::MyCompareC(aSeq, matchPattern) == 0 )
             break;
         }
 
@@ -377,17 +381,14 @@
 // and returns index where input sequence is found. 
 // Returns -1 if not found
 // ----------------------------------------------------------------------------
-TInt CPcsAlgorithm2FilterHelper::FindSubSequence(TDesC* aSeq, TInt aPatternIndex)
+TInt CPcsAlgorithm2FilterHelper::FindSubSequence(const TDesC& aSeq, TInt aPatternIndex)
     {
-    TBuf<50> seqBuf;
-    seqBuf.Append(*aSeq);
-
     TInt j = 0;
-    for (; j < iMatchPatternDetails[aPatternIndex]->subPatternArray.Count(); j++)
+    const TInt subPatternArraycount =  iMatchPatternDetails[aPatternIndex]->subPatternArray.Count();
+    for (; j < subPatternArraycount; j++)
         {
-        TBuf<50> matchPatternBuf;
-        matchPatternBuf.Copy((iMatchPatternDetails[aPatternIndex]->subPatternArray[j]->matchPattern->Des()));
-        if (seqBuf == matchPatternBuf)
+        const TDesC& matchPattern = *(iMatchPatternDetails[aPatternIndex]->subPatternArray[j]->matchPattern);
+	    if ( CPcsAlgorithm2Utils::MyCompareC(aSeq, matchPattern) == 0 ) 
             break;
         }
 
@@ -410,13 +411,13 @@
 // then, firstOccurence of all substring sequences ("A", "AB", "ABC") 
 //       in iMatchPatternDetails will be set to 2
 // ----------------------------------------------------------------------------
-void CPcsAlgorithm2FilterHelper::UpdateForSubSequencesL(TDesC& aSeq, TInt aFirstOccrVal)
+void CPcsAlgorithm2FilterHelper::UpdateForSubSequencesL(const TDesC& aSeq, TInt aFirstOccrVal)
     {
-    HBufC* tempSequence = HBufC::NewL(aSeq.Length() + 1);
-    for (TInt i = 0; i < aSeq.Length(); i++)
+    TPtrC tempSequence;
+    for ( TInt i = 1; i <= aSeq.Length(); i++ )
         {
         // Get the next substring in tempSequence
-        tempSequence->Des().Append(aSeq[i]);
+        tempSequence.Set( aSeq.Left(i) );
 
         // Find if this sequence exist in iMatchPatternDetails
         TInt patternIndex = FindSequence(tempSequence);
@@ -428,11 +429,6 @@
             }
 
         }
-    delete tempSequence;
-    tempSequence = NULL;
-
-    return;
-
     }
 // END OF FILE
 
--- a/predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsAlgorithm2Helper.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsAlgorithm2Helper.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -16,7 +16,7 @@
 */
 
 // INCLUDES
-#include <FindUtil.h>
+#include <PbkGlobalSettingFactory.h>
 #include "FindUtilChineseECE.h"
 #include "CPcsAlgorithm2.h"
 #include "CPcsAlgorithm2Helper.h"
@@ -25,22 +25,11 @@
 #include "CPcsCache.h"
 #include "CPcsKeyMap.h"
 #include "CPsData.h"
-#include "CWords.h"
 #include "CPsQuery.h"
 #include "CPsQueryItem.h"
 #include "CPsDataPluginInterface.h"
 #include "CPcsPoolElement.h"
 
-// Compare functions
-TBool Compare1(const TDesC& aFirst, const TDesC& aSecond)
-    {
-    return aFirst == aSecond;
-    }
-
-TBool Compare2(const TDesC& aFirst, const TDesC& aSecond)
-    {
-    return CPcsAlgorithm2Utils::MyCompareC(aFirst, aSecond);
-    }
 
 // ============================== MEMBER FUNCTIONS ============================
 
@@ -70,6 +59,7 @@
     {
     PRINT ( _L("Enter CPcsAlgorithm2Helper::CPcsAlgorithm2") );
     PRINT ( _L("End CPcsAlgorithm2Helper::CPcsAlgorithm2") );
+    iMaxCount = 0;
     }
 
 // ----------------------------------------------------------------------------
@@ -81,13 +71,18 @@
     PRINT ( _L("Enter CPcsAlgorithm2Helper::ConstructL") );
 
     iAlgorithm = aAlgorithm;
-    keyMap = iAlgorithm->GetKeyMap();
+    iKeyMap = iAlgorithm->GetKeyMap();
 
+    iPbkSettings = PbkGlobalSettingFactory::CreatePersistentSettingL();
+    iPbkSettings->ConnectL( MPbkGlobalSetting::EGeneralSettingCategory );
+    iPbkSettings->RegisterObserverL( this );
+    UpdateNameOrderL();
+    
     PRINT ( _L("End CPcsAlgorithm2Helper::ConstructL") );
     }
 
 // ----------------------------------------------------------------------------
-// CPcsAlgorithm2Helper::CPcsAlgorithm2Helper
+// CPcsAlgorithm2Helper::~CPcsAlgorithm2Helper
 // Destructor
 // ----------------------------------------------------------------------------
 CPcsAlgorithm2Helper::~CPcsAlgorithm2Helper()
@@ -98,798 +93,323 @@
     }
 
 // ----------------------------------------------------------------------------
-// CPcsAlgorithm2Helper::SearchMixedL
+// CPcsAlgorithm2Helper::SearchSingleL
 // Search function for input with both ITU-T and QWERTY mode
 // ----------------------------------------------------------------------------
-void CPcsAlgorithm2Helper::SearchMixedL(const CPsSettings& aSettings,
-                                        CPsQuery& aPsQuery, TBool isSearchInGroup,
-                                        RArray<TInt>& aContactsInGroup,
-                                        RPointerArray<CPsData>& searchResults,
-                                        RPointerArray<CPsPattern>& searchSeqs)
+void CPcsAlgorithm2Helper::SearchSingleL(const CPsSettings& aSettings,
+                                         CPsQuery& aPsQuery, 
+                                         TBool aIsSearchInGroup,
+                                         const RArray<TInt>& aContactsInGroup,
+                                         RPointerArray<CPsData>& aSearchResults,
+                                         RPointerArray<CPsPattern>& aSearchSeqs)
     {
-    __LATENCY_MARK ( _L("CPcsAlgorithm2Helper::SearchMixedL") );
+    PRINT ( _L("Enter CPcsAlgorithm2Helper::SearchSingleL") );
 
-    PRINT ( _L("Enter CPcsAlgorithm2Helper::SearchMixedL") );
+    //__LATENCY_MARK ( _L("CPcsAlgorithm2Helper::SearchSingleL") );
 
+    iMaxCount = aSettings.MaxResults();
+    
     // Create filtering helper for the required sort type
     TSortType sortType = aSettings.GetSortType();
     CPcsAlgorithm2FilterHelper* filterHelper =
             CPcsAlgorithm2FilterHelper::NewL(sortType);
+    CleanupStack::PushL( filterHelper );
+    
+    // Search from cache based on first character
+    const CPsQueryItem& firstCharItem = aPsQuery.GetItemAtL(0);
+    TInt cachePoolId = iKeyMap->PoolIdForCharacter( firstCharItem.Character(), firstCharItem.Mode() );
 
     // Reset the result set array for new search
     iSearchResultsArr.ResetAndDestroy();
 
     // Get the data stores
-    RPointerArray<TDesC> aDataStores;
-    aSettings.SearchUrisL(aDataStores);
+    RPointerArray<TDesC> dataStores;
+    CleanupResetAndDestroyPushL( dataStores );
+    aSettings.SearchUrisL(dataStores);
 
     // Get the required display fields from the client
     RArray<TInt> requiredDataFields;
+    CleanupClosePushL( requiredDataFields );
     aSettings.DisplayFieldsL(requiredDataFields);
-    
-    // Search from cache based on first character
-     const CPsQueryItem& firstCharItem = aPsQuery.GetItemAtL(0);
-     TInt numValue  = keyMap->PoolIdForCharacter( firstCharItem.Character() );
 
     // Perform search for each required data store
     RPointerArray<CPcsPoolElement> elements;
+    CleanupClosePushL( elements );
+    const TInt dataStoresCount = dataStores.Count();
 
-    for (int dsIndex = 0; dsIndex < aDataStores.Count(); dsIndex++)
+    for (TInt dsIndex = 0; dsIndex < dataStoresCount; dsIndex++)
         {
-
-        RPointerArray<CPsData> *temp = new (ELeave) RPointerArray<CPsData> ();
-        iSearchResultsArr.Append(temp);
+        RPointerArray<CPsData>* temp = new (ELeave) RPointerArray<CPsData> ();
+        CleanupStack::PushL( temp );
+        iSearchResultsArr.AppendL( temp );
+        CleanupStack::Pop( temp );
 
         // Get the contents for this data store
-        TInt arrayIndex = iAlgorithm->GetCacheIndex(*(aDataStores[dsIndex]));
+        TInt arrayIndex = iAlgorithm->GetCacheIndex(*(dataStores[dsIndex]));
         if (arrayIndex < 0)
             {
             continue;
             }
         CPcsCache* cache = iAlgorithm->GetCache(arrayIndex);
-        cache->GetContactsForKeyL(numValue, elements);
+        cache->GetContactsForKeyL(cachePoolId, elements);
+
+        // Get the supported data fields for this data store
+        RArray<TInt> supportedDataFields;
+        CleanupClosePushL( supportedDataFields );
+        cache->GetDataFields(supportedDataFields);
+
+        // Get the filtered data fields for this data store
+        TUint8 filteredDataMatch = CPcsAlgorithm2Utils::FilterDataFieldsL(requiredDataFields,
+                                                                          supportedDataFields);
 
         // Perform filtering
-        FilterResultsMixedL(filterHelper, elements, aPsQuery,
-                            isSearchInGroup, aContactsInGroup);
+        FilterResultsSingleL(filterHelper,
+                             elements,
+                             aPsQuery,
+                             filteredDataMatch,
+                             aIsSearchInGroup,
+                             aContactsInGroup);
 
-        // If alphabetical sorting, get the results for this datastore               
+        // If alphabetical sorting, get the results for this datastore
         if (sortType == EAlphabetical)
             {
             filterHelper->GetResults(*(iSearchResultsArr[dsIndex]));
             }
 
         elements.Reset();
-        }
-
-    aDataStores.ResetAndDestroy();
-    requiredDataFields.Reset();
-
-    // If alphabetical sorting, merge the result sets of all datastores
-    if (sortType == EAlphabetical)
-        {
-        // Form the complete searchResults array
-        CPcsAlgorithm2Utils::FormCompleteSearchResultsL(iSearchResultsArr,
-                                                        searchResults);
-        }
-    else
-        {
-        // Results are already sorted pattern based
-        filterHelper->GetResults(searchResults);
-        }
-
-    // Get the sorted match sequence list
-    filterHelper->GetPatternsL(searchSeqs);
-
-    PRINT1 ( _L("Number of search results = %d"), searchResults.Count() );
-
-    // Cleanup         
-    for (TInt i = 0; i < iSearchResultsArr.Count(); i++)
-        {
-        iSearchResultsArr[i]->Reset();
-        delete iSearchResultsArr[i];
-        iSearchResultsArr[i] = NULL;
+        CleanupStack::PopAndDestroy( &supportedDataFields ); // Close
         }
 
-    iSearchResultsArr.Reset();
-
-    CleanupStack::PopAndDestroy(); // query
-    delete filterHelper;
-
-    PRINT ( _L("End CPcsAlgorithm2Helper::SearchMixedL") );
-
-    __LATENCY_MARKEND ( _L("CPcsAlgorithm2Helper::SearchMixedL") );
-    }
-
-// ----------------------------------------------------------------------------
-// CPcsAlgorithm2Helper::SearchITUL
-// Search function for ITU-T style
-// ----------------------------------------------------------------------------
-void CPcsAlgorithm2Helper::SearchITUL(const CPsSettings& aSettings,
-                                      CPsQuery& aPsQuery, TBool isSearchInGroup,
-                                      RArray<TInt>& aContactsInGroup,
-                                      RPointerArray<CPsData>& searchResults,
-                                      RPointerArray<CPsPattern>& searchSeqs)
-    {
-    __LATENCY_MARK ( _L("CPcsAlgorithm2Helper::SearchITUL") );
-
-    PRINT ( _L("Enter CPcsAlgorithm2Helper::SearchITUL") );
-
-    // Create filtering helper for the required sort type
-    TSortType sortType = aSettings.GetSortType();
-    CPcsAlgorithm2FilterHelper* filterHelper =
-            CPcsAlgorithm2FilterHelper::NewL(sortType);
-
-    // Convert the query to string
-    TPtrC queryPtr = aPsQuery.QueryAsStringLC();
-
-    // Search from cache based on first character
-    const CPsQueryItem& firstCharItem = aPsQuery.GetItemAtL(0);
-    TInt numValue  = keyMap->PoolIdForCharacter( firstCharItem.Character() );
-
-    // Reset the result set array for new search
-    iSearchResultsArr.ResetAndDestroy();
-
-    // Get the data stores
-    RPointerArray<TDesC> aDataStores;
-    aSettings.SearchUrisL(aDataStores);
-
-    // Get the required display fields from the client
-    RArray<TInt> requiredDataFields;
-    aSettings.DisplayFieldsL(requiredDataFields);
-
-    // Perform search for each required data store
-    RPointerArray<CPcsPoolElement> elements;
-
-    for (int dsIndex = 0; dsIndex < aDataStores.Count(); dsIndex++)
-        {
-        RPointerArray<CPsData> *temp = new (ELeave) RPointerArray<CPsData> ();
-        iSearchResultsArr.Append(temp);
-
-        // Get the contents for this data store
-        TInt arrayIndex = iAlgorithm->GetCacheIndex(*(aDataStores[dsIndex]));
-        if (arrayIndex < 0)
-            {
-            continue;
-            }
-        CPcsCache* cache = iAlgorithm->GetCache(arrayIndex);
-        cache->GetContactsForKeyL(numValue, elements);
-
-        // Perform filtering
-        FilterResultsL(filterHelper, elements, queryPtr,
-                       isSearchInGroup, aContactsInGroup);
-
-        // If alphabetical sorting, get the results for this datastore               
-        if (sortType == EAlphabetical)
-            {
-            filterHelper->GetResults(*(iSearchResultsArr[dsIndex]));
-            }
-
-        elements.Reset();
-        }
-
-    aDataStores.ResetAndDestroy();
-    requiredDataFields.Reset();
-
-    // If alphabetical sorting, merge the result sets of all datastores
-    if (sortType == EAlphabetical)
-        {
-        // Merge the result sets of individual datastores alphabetically
-        CPcsAlgorithm2Utils::FormCompleteSearchResultsL(iSearchResultsArr,
-                                                        searchResults);
-        }
-    else
-        {
-        // Results are already sorted pattern based 
-        filterHelper->GetResults(searchResults);
-        }
-
-    // Get the sorted match sequence list
-    filterHelper->GetPatternsL(searchSeqs);
-
-    PRINT1 ( _L("Number of search results = %d"), searchResults.Count() );
-
-    // Cleanup
-    for (TInt i = 0; i < iSearchResultsArr.Count(); i++)
-        {
-        iSearchResultsArr[i]->Reset();
-        delete iSearchResultsArr[i];
-        iSearchResultsArr[i] = NULL;
-        }
-    iSearchResultsArr.Reset();
-
-    CleanupStack::PopAndDestroy(); // query
-    delete filterHelper;
-
-    PRINT ( _L("End CPcsAlgorithm2Helper::SearchITUL") );
-    __LATENCY_MARKEND ( _L("CPcsAlgorithm2Helper::SearchITUL") );
-    }
-
-// ----------------------------------------------------------------------------
-// CPcsAlgorithm2Helper::SearchQWERTYL
-// Search function for QWERTY style
-// ----------------------------------------------------------------------------
-void CPcsAlgorithm2Helper::SearchQWERTYL(const CPsSettings& aSettings,
-                                         CPsQuery& aPsQuery, TBool isSearchInGroup,
-                                         RArray<TInt>& aContactsInGroup,
-                                         RPointerArray<CPsData>& searchResults,
-                                         RPointerArray<CPsPattern>& searchSeqs)
-    {
-    __LATENCY_MARK ( _L("CPcsAlgorithm2Helper::SearchQWERTYL") );
-    PRINT ( _L("Enter CPcsAlgorithm2Helper::SearchQWERTYL") );
-
-    // te filtering helper for the required sort type
-    TSortType sortType = aSettings.GetSortType();
-    CPcsAlgorithm2FilterHelper* filterHelper =
-            CPcsAlgorithm2FilterHelper::NewL(sortType);
-
-    // Convert the query to string
-    TPtrC queryPtr = aPsQuery.QueryAsStringLC();
-
-    // Search from cache based on first character
-    const CPsQueryItem& firstCharItem = aPsQuery.GetItemAtL(0);
-    TInt numValue  = keyMap->PoolIdForCharacter( firstCharItem.Character() );
-    
-    // Reset the result set array for new search
-    iSearchResultsArr.ResetAndDestroy();
-
-    // Get the data stores  
-    RPointerArray<TDesC> aDataStores;
-    aSettings.SearchUrisL(aDataStores);
-
-    // Get the required display fields from the client
-    RArray<TInt> requiredDataFields;
-    aSettings.DisplayFieldsL(requiredDataFields);
-
-    // Perform search for each of the required data stores
-    RPointerArray<CPcsPoolElement> elements;
-
-    for (int dsIndex = 0; dsIndex < aDataStores.Count(); dsIndex++)
-        {
-
-        RPointerArray<CPsData> *temp = new (ELeave) RPointerArray<CPsData> ();
-        iSearchResultsArr.Append(temp);
-
-        // Get the contents for this data store
-        TInt arrayIndex = iAlgorithm->GetCacheIndex(*(aDataStores[dsIndex]));
-        if (arrayIndex < 0)
-            {
-            continue;
-            }
-        CPcsCache* cache = iAlgorithm->GetCache(arrayIndex);
-        cache->GetContactsForKeyL(numValue, elements);
-
-        // Perform filtering
-        FilterResultsQwertyL(filterHelper, elements, queryPtr,
-                             isSearchInGroup, aContactsInGroup);
-
-        // If alphabetical sorting, get the results for this datastore               
-        if (sortType == EAlphabetical)
-            {
-            filterHelper->GetResults(*(iSearchResultsArr[dsIndex]));
-            }
-
-        elements.Reset();
-        }
-    aDataStores.ResetAndDestroy();
-    requiredDataFields.Reset();
+    CleanupStack::PopAndDestroy( &elements );           // Close
+    CleanupStack::PopAndDestroy( &requiredDataFields ); // Close
+    CleanupStack::PopAndDestroy( &dataStores );         // ResetAndDestroy
 
     // If alphabetical sorting, merge the result sets of all datastores
     if (sortType == EAlphabetical)
         {
         // Form the complete searchResults array
         CPcsAlgorithm2Utils::FormCompleteSearchResultsL(iSearchResultsArr,
-                                                        searchResults);
+                                                        aSearchResults);
         }
     else
         {
         // Results are already sorted pattern based
-        filterHelper->GetResults(searchResults);
+        filterHelper->GetResults(aSearchResults);
         }
 
     // Get the sorted match sequence list
-    filterHelper->GetPatternsL(searchSeqs);
+    filterHelper->GetPatternsL(aSearchSeqs);
+
+    PRINT1 ( _L("Number of search results = %d"), aSearchResults.Count() );
 
-    PRINT1 ( _L("Number of search results = %d"), searchResults.Count() );
-
-    // Cleanup             
-    for (TInt i = 0; i < iSearchResultsArr.Count(); i++)
+    // Cleanup
+    const TInt searchResultsArrCount = iSearchResultsArr.Count();
+    for (TInt i = 0; i < searchResultsArrCount; i++)
         {
         iSearchResultsArr[i]->Reset();
-        delete iSearchResultsArr[i];
-        iSearchResultsArr[i] = NULL;
         }
-    iSearchResultsArr.Reset();
+    iSearchResultsArr.ResetAndDestroy();
 
-    CleanupStack::PopAndDestroy(); // query
-    delete filterHelper;
+    CleanupStack::PopAndDestroy( filterHelper );
 
-    PRINT ( _L("End CPcsAlgorithm2Helper::SearchQWERTYL") );
-    __LATENCY_MARKEND ( _L("CPcsAlgorithm2Helper::SearchQWERTYL") );
+    //__LATENCY_MARKEND ( _L("CPcsAlgorithm2Helper::SearchSingleL") );
+
+    PRINT ( _L("End CPcsAlgorithm2Helper::SearchSingleL") );
     }
 
 // ----------------------------------------------------------------------------
 // CPcsAlgorithm2Helper::SearchMatchSeqL
-// Funciton to search matching sequences in the input text
+// Function to search matching sequences in the input text
 // ----------------------------------------------------------------------------
-void CPcsAlgorithm2Helper::SearchMatchSeqL(HBufC* /*aQuery*/, TDesC& aData,
-                                           RPointerArray<TDesC>& /*aMatchSet*/, 
-                                           CPsQuery& /*aPsQuery*/,
-                                           RArray<TPsMatchLocation>& aMatchLocation)
+void CPcsAlgorithm2Helper::SearchMatchSeqL(CPsQuery& aPsQuery,
+                                           const TDesC& aData,
+                                           RPointerArray<TDesC>& aMatchSet,
+                                           RArray<TPsMatchLocation>& aMatchLocation )
     {
     PRINT ( _L("Enter CPcsAlgorithm2Helper::SearchMatchSeqL") );
 
-    // Convert the data into words		     
-    TLex lex(aData);
-
-    // First word
-    TPtrC token = lex.NextToken();
-
-    TInt beg = lex.Offset() - token.Length(); // start index of match sequence
-
-    // Search thru multiple words
-    while (token.Length() != 0)
+    RArray<TInt> matchPos;
+    CleanupClosePushL( matchPos );
+    RArray<TInt> matchLen;
+    CleanupClosePushL( matchLen );
+    if ( iAlgorithm->FindUtilECE()->MatchRefineL( aData, aPsQuery, matchPos, matchLen, ETrue ) )
         {
-        TPsMatchLocation tempLocation;
-
-        // check for directionality of the text
-        TBool found(EFalse);
-        TBidiText::TDirectionality dir = TBidiText::TextDirectionality(token, &found);
-
-        tempLocation.index = beg;
-        tempLocation.length = 0;
-        tempLocation.direction = dir;
-
-        // Add the match location to the data structure array
-        aMatchLocation.Append(tempLocation);
-
-        // Next word
-        token.Set(lex.NextToken());
-        beg = lex.Offset() - token.Length(); // start index of next word
+        ASSERT( matchPos.Count() == matchLen.Count() );
+        const TInt matchPosCount = matchPos.Count();
+        for ( TInt i = 0 ; i < matchPosCount ; ++i )
+            {
+            TPsMatchLocation tempLocation;
+    
+            // check for directionality of the text
+            TBool found(EFalse);
+            TPtrC matchingPart = aData.Mid( matchPos[i], matchLen[i] );
+            TBidiText::TDirectionality dir = TBidiText::TextDirectionality(matchingPart, &found);
+    
+            tempLocation.index = matchPos[i];
+            tempLocation.length = matchLen[i];
+            tempLocation.direction = dir;
+    
+            // Add the match location to the data structure array
+            aMatchLocation.Append(tempLocation);
+            
+            // Add the matched sequence to set, not allowing duplicates
+            CPcsAlgorithm2Utils::AppendMatchToSeqL( aMatchSet, matchingPart );
+            }
         }
+    CleanupStack::PopAndDestroy( &matchLen );
+    CleanupStack::PopAndDestroy( &matchPos );
 
     PRINT ( _L("End CPcsAlgorithm2Helper::SearchMatchSeqL") );
     }
 
 // ----------------------------------------------------------------------------
-// CPcsAlgorithm2::FilterResultsL
+// CPcsAlgorithm2Helper::FilterResultsSingleL
 // Subset search function
 // ----------------------------------------------------------------------------
-void CPcsAlgorithm2Helper::FilterResultsL(CPcsAlgorithm2FilterHelper* aAlgorithmFilterHelper, 
-                                          RPointerArray<CPcsPoolElement>& searchSet, 
-                                          const TDesC& searchQuery,
-                                          TBool isSearchInGroup, 
-                                          RArray<TInt>& aContactsInGroup)
+void CPcsAlgorithm2Helper::FilterResultsSingleL(CPcsAlgorithm2FilterHelper* aAlgorithmFilterHelper,
+                                                RPointerArray<CPcsPoolElement>& aSearchSet,
+                                                CPsQuery& aSearchQuery,
+                                                TUint8 aFilteredDataMatch,
+                                                TBool aIsSearchInGroup,
+                                                const RArray<TInt>& aContactsInGroup)
     {
-    __LATENCY_MARK ( _L("CPcsAlgorithm2Helper::FilterResultsL") );
-    PRINT ( _L("Enter CPcsAlgorithm2Helper::FilterResultsL") );
+    PRINT ( _L("Enter CPcsAlgorithm2::FilterResultsSingleL") );
+
+    TInt maxcount = 0;
+    CFindUtilChineseECE* pFindUtilEce = iAlgorithm->FindUtilECE();
 
-    // Convert the search condition to numeric key string
-    TBuf<KPsQueryMaxLen> tmpSearchQuery;
-    keyMap->GetNumericKeyString(searchQuery, tmpSearchQuery);
-    
-    //Holds the first char of first name of a contact
-    TBuf<10> firstChar;   
+    // Assume that all the elements is aSearchSet are from the same database.
+    // Get firstname index and lastname index for that database.
+    // If both are found, then name fields are matched a bit differently compared
+    // to rest of the fields.
+    TInt fnIndex( KErrNotFound );
+    TInt lnIndex( KErrNotFound );
+    TBool fullNameSearch( EFalse );
+    if ( aSearchSet.Count() )
+        {
+        TInt dbUriId = aSearchSet[0]->GetPsData()->UriId();
+        CPcsCache* cache = iAlgorithm->GetCache( dbUriId );
+        fnIndex = cache->GetFirstNameIndex();
+        lnIndex = cache->GetLastNameIndex();
 
-    PRINT2 ( _L("Numeric Key String for %S = %S"), &searchQuery, &tmpSearchQuery );
-
+        // Ensure that firstname and lastname are among the fields to be searched
+        TUint8 fnBitmask = 1 << fnIndex;
+        TUint8 lnBitmask = 1 << lnIndex;
+        if ( (aFilteredDataMatch & fnBitmask) && 
+             (aFilteredDataMatch & lnBitmask) )
+            {
+            fullNameSearch = ETrue;
+            // Remove firstname and lastname from the set of fields to search
+            // so that they will not be searched twice.
+            aFilteredDataMatch &= ~fnBitmask;
+            aFilteredDataMatch &= ~lnBitmask;
+            }
+        }
+    
     // Parse thru each search set elements and filter the results
-    for (int index = 0; index < searchSet.Count(); index++)
+    const TInt searchSetCount = aSearchSet.Count();
+    for (TInt index = 0; index < searchSetCount; index++)
         {
-        CPcsPoolElement* poolElement = static_cast<CPcsPoolElement*> (searchSet[index]);
+        CPcsPoolElement* poolElement = static_cast<CPcsPoolElement*> (aSearchSet[index]);
         CPsData* psData = poolElement->GetPsData();
         psData->ClearDataMatches();
-        RPointerArray<TDesC> tempMatchSeq;
 
-        // Search thru multiple words
-        TBuf<KBufferMaxLen> token;
-        TBuf<KBufferMaxLen> firstName;
-        TBuf<KBufferMaxLen> lastName;
-        lastName.Append(psData->Data(iAlgorithm->GetLastNameIndex())->Des());
-        firstName.Append(psData->Data(iAlgorithm->GetFirstNameIndex())->Des());
+        // Skip the contact if we are doing a group search and contact doesn't belong to the group
+        if ( aIsSearchInGroup && 
+             aContactsInGroup.Find( psData->Id() ) == KErrNotFound )
+            {
+            continue;
+            }
+        
+        // Buffer for matched character sequence. Currently, we don't return
+        // accurate pattern but just first character from the matching point.
+        // Current clients don't actually use this data for anything.
+        TBuf<1> matchingData;
+        
+        TBool matched = EFalse;
 
-        CFindUtilChineseECE* pFindUtilEce = iAlgorithm->FindUtilECE();
-        TBool matched  = 0;
+        // Parse thru each data field and filter the results
+        // -------------------------------------------------
+        
+        // Name fields are handled separately to enable searching with query like
+        // "LastnameFirstname". Searching fullname by query string 
+        // only for the pool elements matching with the firstname or lastname
+        if ( fullNameSearch && ( poolElement->IsDataMatch(fnIndex) || 
+            poolElement->IsDataMatch(lnIndex) ))
+            {
+            HBufC* fullName = CreateNameBufLC( *psData, fnIndex, lnIndex );
 
-        // If has Chinese word and the first name doesn't start with Chinese character, then should add a space
-        // before the first name, otherwise intitial letter searching will not function
-        if( pFindUtilEce->IsChineseWord(lastName) || pFindUtilEce->IsChineseWord(firstName))
-            {
-            token.Append(lastName);
-            if (firstName.Length())
+            // FindUtil can take care of matching queries like "Firstname", "Lastname", 
+            // and "LastnameFirstname".
+            matched = pFindUtilEce->MatchRefineL( *fullName, aSearchQuery );
+            if (matched)
                 {
-                firstChar.Zero();
-                firstChar.Append(firstName[0]);
-                if (!pFindUtilEce->IsChineseWord(firstChar) )
-                    {
-                    token.Append(KSpace);
-                    }
-                token.Append(firstName);
+                matchingData = fullName->Left(1);
+                psData->SetDataMatch( fnIndex );
+                psData->SetDataMatch( lnIndex );
+                }
+            
+            CleanupStack::PopAndDestroy( fullName );
+            }
+
+        // Find from the rest of the fields if no match found so far. 
+        // Name fields are already removed from aFilteredDataMatch if we did separate full name search.
+        const TInt dataElementCount = psData->DataElementCount();
+        for ( TInt dataIndex = 0; dataIndex < dataElementCount && !matched ; dataIndex++ )
+            {
+            // Filter off data fields not required in search
+            TUint8 bitIndex = 1 << dataIndex;
+            TUint8 filter = bitIndex & aFilteredDataMatch;
+            if ( filter == 0x0 )
+                {
+                // Move to next data
+                continue;
                 }
 
-            if (token.Length() != 0)
+            if ( poolElement->IsDataMatch(dataIndex) )
                 {
-                matched = iAlgorithm->FindUtil()->Interface()->
-                    MatchRefineL(token, tmpSearchQuery, ECustomConverter, iAlgorithm);
-
+                TPtrC fieldData( *psData->Data(dataIndex) );
+                matched = pFindUtilEce->MatchRefineL( fieldData, aSearchQuery );
                 if (matched)
                     {
-                    psData->SetDataMatch(iAlgorithm->GetLastNameIndex());
-                    psData->SetDataMatch(iAlgorithm->GetFirstNameIndex());
-                    }
-                }
-            }
-        else
-            {
-            // If contact name only has western word, then should send 
-            // "first name","last name" and "last name + first name" to FindUtil to do the search
-            const TInt lastnameLen = lastName.Length();
-            const TInt firstnameLen = firstName.Length();
-            if(lastnameLen)
-                {
-                matched = iAlgorithm->FindUtil()->Interface()->
-                    MatchRefineL(lastName, tmpSearchQuery, ECustomConverter, iAlgorithm);
-
-                if (matched)
-                    {
-                    psData->SetDataMatch(iAlgorithm->GetLastNameIndex());
-                    }
-                }
-
-            if(!matched && firstnameLen)
-                {
-                matched = iAlgorithm->FindUtil()->Interface()->
-                    MatchRefineL(firstName, tmpSearchQuery, ECustomConverter, iAlgorithm);
-
-                if (matched)
-                    {
-                    psData->SetDataMatch(iAlgorithm->GetFirstNameIndex());
-                    }
-                }
-            
-            token.Append(lastName);
-            token.Append(firstName);
-            if (!matched && lastnameLen && firstnameLen)
-                {
-                matched = iAlgorithm->FindUtil()->Interface()->
-                    MatchRefineL(token, tmpSearchQuery, ECustomConverter, iAlgorithm);
-
-                if (matched)
-                    {
-                    psData->SetDataMatch(iAlgorithm->GetLastNameIndex());
-                    psData->SetDataMatch(iAlgorithm->GetFirstNameIndex());
+                    matchingData = fieldData.Left(1);
+                    psData->SetDataMatch( dataIndex );
                     }
                 }
             }
 
-        if (matched)
+
+        // Add to results if match is found
+        if ( matched )
             {
-            // Extract matched character sequence, don't need to be accurate for Chinese variant
-            const TInt len = 1;  
-            HBufC* seq = HBufC::NewLC(len);
-            *seq = token.Mid(0, len);
-            seq->Des().UpperCase();
-
-            TIdentityRelation<TDesC> rule(Compare1);
-            if (tempMatchSeq.Find(seq, rule) == KErrNotFound)
-                {
-                tempMatchSeq.Append(seq);
-                CleanupStack::Pop();
-                }
-            else
-                {
-                CleanupStack::PopAndDestroy();
-                }
-                
-
-            // Add the result        
-            if (isSearchInGroup)
-                {
-                if (aContactsInGroup.Find(psData->Id()) != KErrNotFound)
-                    {
-                    aAlgorithmFilterHelper->AddL(psData, tempMatchSeq);
-                    }
-                }
-            else
-                {
-                aAlgorithmFilterHelper->AddL(psData, tempMatchSeq);
-                }
-            }
-
-        // Cleanup the match sequence array as 
-        // they are stored in pattern details structure
-        tempMatchSeq.ResetAndDestroy();
-        }
-
-    PRINT ( _L("End CPcsAlgorithm2Helper::FilterResultsL") );
-    __LATENCY_MARKEND ( _L("CPcsAlgorithm2Helper::FilterResultsL") );
-    }
-
-// ----------------------------------------------------------------------------
-// CPcsAlgorithm2Helper::FilterResultsQwertyL
-// Subset search function 
-// ----------------------------------------------------------------------------
-void CPcsAlgorithm2Helper::FilterResultsQwertyL(CPcsAlgorithm2FilterHelper* aAlgorithmFilterHelper, 
-                                                RPointerArray<CPcsPoolElement>& searchSet, 
-                                                const TDesC& searchQuery,TBool isSearchInGroup, 
-                                                RArray<TInt>& aContactsInGroup)
-    {
-    PRINT ( _L("Enter CPcsAlgorithm2::FilterResultsQwertyL") );
-
-    TBuf<50> tmpSearchQuery = searchQuery;
-    tmpSearchQuery.LowerCase();
-    
-    //Holds the first char of first name of a contact
-    TBuf<10> firstChar;
-
-    // Parse thru each search set elements and filter the results    
-    for (int index = 0; index < searchSet.Count(); index++)
-        {
-        CPcsPoolElement* poolElement = static_cast<CPcsPoolElement*> (searchSet[index]);
-        CPsData* psData = poolElement->GetPsData();
-        psData->ClearDataMatches();
-        RPointerArray<TDesC> tempMatchSeq;
+            RPointerArray<TDesC> tempMatchSeq;
+            CleanupClosePushL( tempMatchSeq );
 
-        // Parse thru each data and filter the results
-        TBuf<KBufferMaxLen> token;
-        TBuf<KBufferMaxLen> firstName;
-        TBuf<KBufferMaxLen> lastName;
-        lastName.Append(psData->Data(iAlgorithm->GetLastNameIndex())->Des());
-        firstName.Append(psData->Data(iAlgorithm->GetFirstNameIndex())->Des());
-
-        CFindUtilChineseECE* pFindUtilEce = iAlgorithm->FindUtilECE();
-        TBool matched  = 0;
-
-        // If has Chinese word and the first name doesn't start with Chinese character, then should add a space
-        // before the first name, otherwise intitial letter searching will not function
-        if( pFindUtilEce->IsChineseWord(lastName) || pFindUtilEce->IsChineseWord(firstName))
-            {
-            token.Append(lastName);
-            if (firstName.Length())
-                {
-                firstChar.Zero();
-                firstChar.Append(firstName[0]);
-                if (!pFindUtilEce->IsChineseWord(firstChar) )
-                    {
-                    token.Append(KSpace);
-                    }
-                token.Append(firstName);
-                }
-
-            if (token.Length() != 0)
-                {
-                matched = iAlgorithm->FindUtil()->Interface()->MatchRefineL(token, tmpSearchQuery);
-
-                if (matched)
-                    {
-                    psData->SetDataMatch(iAlgorithm->GetLastNameIndex());
-                    psData->SetDataMatch(iAlgorithm->GetFirstNameIndex());
-                    }
-                }
-            }
-        else
-            {
-            // If contact name only has western word, then should send 
-            // "first name","last name" and "last name + first name" to FindUtil to do the search
-            const TInt lastnameLen = lastName.Length();
-            const TInt firstnameLen = firstName.Length();
-            if(lastnameLen)
-                {
-                matched = iAlgorithm->FindUtil()->Interface()->MatchRefineL(lastName, tmpSearchQuery);
-
-                if (matched)
-                    {
-                    psData->SetDataMatch(iAlgorithm->GetLastNameIndex());
-                    }
-                }
-
-            if(!matched && firstnameLen)
-                {
-                matched = iAlgorithm->FindUtil()->Interface()->MatchRefineL(firstName, tmpSearchQuery);
-
-                if (matched)
-                    {
-                    psData->SetDataMatch(iAlgorithm->GetFirstNameIndex());
-                    }
-                }
+            // Wrap matched character sequence to array.
+            matchingData.UpperCase();
+            tempMatchSeq.AppendL(&matchingData);
+            
+            // Add the result
+            aAlgorithmFilterHelper->AddL( psData, tempMatchSeq );
+            maxcount++;
             
-            token.Append(lastName);
-            token.Append(firstName);
-            if (!matched && lastnameLen && firstnameLen)
-                {
-                matched = iAlgorithm->FindUtil()->Interface()->MatchRefineL(token, tmpSearchQuery);
-
-                if (matched)
-                    {
-                    psData->SetDataMatch(iAlgorithm->GetLastNameIndex());
-                    psData->SetDataMatch(iAlgorithm->GetFirstNameIndex());
-                    }
-                }
+            // Cleanup the match sequence array as 
+            // they are stored in pattern details structure
+            CleanupStack::PopAndDestroy( &tempMatchSeq ); // Close
+            
+            // TODO: Match seqs could be extracted from actual
+            //       match locations by using the other overload of
+            //       CFindUtilChineseECE::MatchRefineL().
+            //       Currently, match seq data is not used by clients.
             }
         
-        if (matched)
-            {
-            // Extract matched character sequence, don't need to be accurate for Chinese variant
-            const TInt len = 1;
-            HBufC* seq = HBufC::NewLC(len);
-            *seq = token.Mid(0, len);
-            seq->Des().UpperCase();
-
-            TIdentityRelation<TDesC> rule(Compare1);
-            if (tempMatchSeq.Find(seq, rule) == KErrNotFound)
-                {
-                tempMatchSeq.Append(seq);
-                CleanupStack::Pop();
-                }
-            else
-                {
-                CleanupStack::PopAndDestroy();
-                }
-            
-            // Add the result
-            if (isSearchInGroup)
-                {
-                if (aContactsInGroup.Find(psData->Id()) != KErrNotFound)
-                    {
-                    aAlgorithmFilterHelper->AddL(psData, tempMatchSeq);
-                    }
-                }
-            else
-                {
-                aAlgorithmFilterHelper->AddL(psData, tempMatchSeq);
-                }
-            }
-
-        // Cleanup the match sequence array as 
-        // they are stored in pattern details structure
-        tempMatchSeq.ResetAndDestroy();
+          if ( iMaxCount != -1 && maxcount > iMaxCount )
+              {
+              return;
+              }
         }
 
-    PRINT ( _L("End CPcsAlgorithm2Helper::FilterResultsQwertyL") );
-    }
-
-// ----------------------------------------------------------------------------
-// CPcsAlgorithm2Helper::FilterResultsMixedL
-// Subset search function
-// ----------------------------------------------------------------------------
-void CPcsAlgorithm2Helper::FilterResultsMixedL(CPcsAlgorithm2FilterHelper* aAlgorithmFilterHelper, 
-                                               RPointerArray<CPcsPoolElement>& searchSet, 
-                                               CPsQuery& searchQuery, TBool isSearchInGroup,
-                                               RArray<TInt>& aContactsInGroup)
-    {
-    PRINT ( _L("Enter CPcsAlgorithm2::FilterResultsMixedL") );
-
-    // Convert the search query to alpha numeric string
-    TBuf<50> tmpSearchQuery;
-    ExtractQueryL(searchQuery, tmpSearchQuery);
-    tmpSearchQuery.LowerCase();
-    TBuf<10> firstChar;
-
-    // Parse thru each search set elements and filter the results    
-    for (int index = 0; index < searchSet.Count(); index++)
-        {
-        CPcsPoolElement* poolElement = static_cast<CPcsPoolElement*> (searchSet[index]);
-        CPsData* psData = poolElement->GetPsData();
-        psData->ClearDataMatches();
-        RPointerArray<TDesC> tempMatchSeq;
-
-        // Parse thru each data and filter the results
-        TBuf<255> token;
-        TBuf<KBufferMaxLen> firstName;
-        TBuf<KBufferMaxLen> lastName;
-        lastName.Append(psData->Data(iAlgorithm->GetLastNameIndex())->Des());
-        firstName.Append(psData->Data(iAlgorithm->GetFirstNameIndex())->Des());
-
-        CFindUtilChineseECE* pFindUtilEce = iAlgorithm->FindUtilECE();
-        TBool matched  = 0;
-
-        // If has Chinese word and the first name doesn't start with Chinese character, then should add a space
-        // before the first name, otherwise intitial letter searching will not function
-        if( pFindUtilEce->IsChineseWord(lastName) || pFindUtilEce->IsChineseWord(firstName))
-            {
-            token.Append(lastName);
-            if (firstName.Length())
-                {
-                firstChar.Zero();
-                firstChar.Append(firstName[0]);
-                if (!pFindUtilEce->IsChineseWord(firstChar) )
-                    {
-                    token.Append(KSpace);
-                    }
-                token.Append(firstName);
-                }
-
-            if (token.Length() != 0)
-                {
-                matched = pFindUtilEce->MatchRefineL(token, searchQuery);
-
-                if (matched)
-                    {
-                    psData->SetDataMatch(iAlgorithm->GetLastNameIndex());
-                    psData->SetDataMatch(iAlgorithm->GetFirstNameIndex());
-                    }
-                }
-            }
-        else
-            {
-            // If contact name only has western word, then should send 
-            // "first name","last name" and "last name + first name" to FindUtil to do the search
-            const TInt lastnameLen = lastName.Length();
-            const TInt firstnameLen = firstName.Length();
-            if(lastnameLen)
-                {
-                matched = pFindUtilEce->MatchRefineL(lastName, searchQuery);
-
-                if (matched)
-                    {
-                    psData->SetDataMatch(iAlgorithm->GetLastNameIndex());
-                    }
-                }
-
-            if(!matched && firstnameLen)
-                {
-                matched = pFindUtilEce->MatchRefineL(firstName, searchQuery);
-
-                if (matched)
-                    {
-                    psData->SetDataMatch(iAlgorithm->GetFirstNameIndex());
-                    }
-                }
-            
-            token.Append(lastName);
-            token.Append(firstName);
-            if (!matched && lastnameLen && firstnameLen)
-                {
-                matched = pFindUtilEce->MatchRefineL(token, searchQuery);
-
-                if (matched)
-                    {
-                    psData->SetDataMatch(iAlgorithm->GetLastNameIndex());
-                    psData->SetDataMatch(iAlgorithm->GetFirstNameIndex());
-                    }
-                }
-            }
-
-        if (matched)
-            {
-            // Extract matched character sequence, don't need to be accurate for Chinese variant
-            const TInt len = 1;       
-        
-            HBufC* seq = HBufC::NewLC(len);
-            *seq = token.Mid(0, len);
-            seq->Des().UpperCase();
-
-            TIdentityRelation<TDesC> rule(Compare1);
-            if (tempMatchSeq.Find(seq, rule) == KErrNotFound)
-                {
-                tempMatchSeq.Append(seq);
-                CleanupStack::Pop();
-                }
-            else
-                {
-                CleanupStack::PopAndDestroy();
-                }
-            
-            // Add the result
-            if (isSearchInGroup)
-                {
-                if (aContactsInGroup.Find(psData->Id()) != KErrNotFound)
-                    {
-                    aAlgorithmFilterHelper->AddL(psData, tempMatchSeq);
-                    }
-                }
-            else
-                {
-                aAlgorithmFilterHelper->AddL(psData, tempMatchSeq);
-                }
-            }
-
-        // Cleanup the match sequence array as 
-        // they are stored in pattern details structure
-        tempMatchSeq.ResetAndDestroy();
-        }
-
-    PRINT ( _L("End CPcsAlgorithm2Helper::FilterResultsMixedL") );
+    PRINT ( _L("End CPcsAlgorithm2Helper::FilterResultsSingleL") );
     }
 
 // ----------------------------------------------------------------------------
@@ -899,93 +419,156 @@
 void CPcsAlgorithm2Helper::SortSearchSeqsL(RPointerArray<TDesC>& aSearchSeqs)
     {
     // Sort the search seqs
-    TLinearOrder<TDesC> rule(Compare2);
+    TLinearOrder<TDesC> rule( CPcsAlgorithm2Utils::MyCompareC );
     aSearchSeqs.Sort(rule);
     }
 
-// ----------------------------------------------------------------------------
-// CPcsAlgorithm2Helper::ExtractQueryL()
-// Required for mixed mode search.
-// ----------------------------------------------------------------------------
-void CPcsAlgorithm2Helper::ExtractQueryL(CPsQuery& aQuery, TDes& aOutput)
+// ---------------------------------------------------------------------------
+// CPcsAlgorithm2Helper::CreteNameBufLC
+// Update name order according to Phonebook setting
+// ---------------------------------------------------------------------------
+HBufC* CPcsAlgorithm2Helper::CreateNameBufLC( const CPsData& aContactData, 
+        TInt aFirstNameIndex, TInt aLastNameIndex ) const
     {
-    for (int i = 0; i < aQuery.Count(); i++)
+    const TDesC& firstName( *aContactData.Data(aFirstNameIndex) );
+    const TDesC& lastName( *aContactData.Data(aLastNameIndex) );
+    CFindUtilChineseECE* pFindUtilEce = iAlgorithm->FindUtilECE();
+    HBufC* fullName = NULL;
+    
+    if ( pFindUtilEce->IsChineseWordIncluded( lastName ) || 
+        pFindUtilEce->IsChineseWordIncluded( firstName ) )
         {
-        if (aQuery.GetItemAtL(i).Mode() == EItut)
+        fullName = HBufC::NewLC( lastName.Length() + firstName.Length()  + 1 );
+        TPtr fullNamePtr = fullName->Des();
+    
+        // Form the full name according the Phonebook name order setting. Typically,
+        // the order is always lastname-firstname in Chinese variants. However, at least
+        // currently it is possible to change this from Contacts app if UI language has
+        // been set to English.
+        if ( iNameOrder == ELastnameFirstname )
             {
-            TBuf<KPsQueryMaxLen> outBuf;
-            keyMap->GetNumericKeyString(aQuery.QueryAsStringLC(), outBuf);
-            aOutput.Append(outBuf[i]);
-            CleanupStack::PopAndDestroy();
+            fullNamePtr.Append( lastName );
+            //Holds the first char of first name of a contact
+            TBuf<10> firstChar;   
+            firstChar.Zero();
+            
+            if(firstName.Length())
+                {
+                firstChar.Append(firstName[0]);   
+                // There is no space between LastName and FirstName in Chinese Name
+                // except that the firstChar of FirstName isn't Chinese character
+                if ( !pFindUtilEce->IsChineseWordIncluded( firstChar ) )
+                    {
+                    fullNamePtr.Append( KSpace );
+                    }
+                fullNamePtr.Append( firstName ); 
+                }
             }
         else
             {
-            aOutput.Append(aQuery.GetItemAtL(i).Character());
+            fullNamePtr.Append( firstName );
+            //Holds the first char of last name of a contact
+            TBuf<10> firstChar;   
+            firstChar.Zero();
+            
+            if(lastName.Length())
+                {
+                firstChar.Append(lastName[0]);
+                // There is no space between LastName and FirstName in Chinese Name
+                // except that the firstChar of Lastname isn't Chinese character  
+                if ( !pFindUtilEce->IsChineseWordIncluded( firstChar ) )
+                    {
+                    fullNamePtr.Append( KSpace );
+                    }
+                fullNamePtr.Append( lastName ); 
+                }
+            }
+        }
+    else
+        {
+        fullName = HBufC::NewLC( lastName.Length() + firstName.Length() + 1 );
+        TPtr fullNamePtr = fullName->Des();
+    
+        // Form the full name according the Phonebook name order setting. Typically,
+        // the order is always lastname-firstname in Chinese variants. However, at least
+        // currently it is possible to change this from Contacts app if UI language has
+        // been set to English.
+        if ( iNameOrder == ELastnameFirstname )
+            {
+            fullNamePtr.Append( lastName );
+            fullNamePtr.Append( KSpace );
+            fullNamePtr.Append( firstName );
+            }
+        else
+            {
+            fullNamePtr.Append( firstName );
+            fullNamePtr.Append( KSpace );
+            fullNamePtr.Append( lastName );
+            }
+        }
+    
+    return fullName;
+    }
+
+// ---------------------------------------------------------------------------
+// CPcsAlgorithm2Helper::UpdateNameOrderL
+// Update name order according to Phonebook setting
+// ---------------------------------------------------------------------------
+void CPcsAlgorithm2Helper::UpdateNameOrderL()
+    {
+    /*
+    * Phonebook name ordering flag, integer value, possible values:
+    * 0: name order Lastname Firstname
+    * 1: name order Firstname Lastname
+    * 2: name order undefined
+    */
+    TInt nameOrderSetting;
+    iPbkSettings->Get( MPbkGlobalSetting::ENameOrdering, nameOrderSetting );
+    
+    switch ( nameOrderSetting )
+        {
+        case 0:
+            {
+            iNameOrder = ELastnameFirstname;
+            break;
+            }
+        case 1:
+            {
+            iNameOrder = EFirstnameLastname;
+            break;
+            }
+        case 2:
+        default:
+            {
+            // Decide name order based on UI language: lastname-firstname
+            // for Chinese, firstname-lastname for the rest of languages.
+            TLanguage uiLang = User::Language();
+            if ( uiLang == ELangPrcChinese || 
+                 uiLang == ELangHongKongChinese ||
+                 uiLang == ELangTaiwanChinese )
+                {
+                iNameOrder = ELastnameFirstname;
+                }
+            else
+                {
+                iNameOrder = EFirstnameLastname;
+                }
             }
         }
     }
 
-// ----------------------------------------------------------------------------
-// CPcsAlgorithm2Helper::ExtractQueryL()
-// Required for mixed mode search.
-// ----------------------------------------------------------------------------
-void CPcsAlgorithm2Helper::ExtractQueryL(TDesC& aInput, CPsQuery& aQuery, TDes& aOutput)
+// ---------------------------------------------------------------------------
+// CPcsAlgorithm2Helper::SettingChangedL
+// From MPbkGlobalSettingObserver
+// ---------------------------------------------------------------------------
+void CPcsAlgorithm2Helper::SettingChangedL( MPbkGlobalSetting::TPbkGlobalSetting aKey )
     {
-    TInt len = -1;
-
-    if (aInput.Length() > aQuery.Count())
-        {
-        len = aQuery.Count();
-        }
-    else
+    if ( aKey == MPbkGlobalSetting::ENameOrdering )
         {
-        len = aInput.Length();
-        }
-
-    for (int i = 0; i < len; i++)
-        {
-        if (aQuery.GetItemAtL(i).Mode() == EItut)
-            {
-            TBuf<KPsQueryMaxLen> outBuf;
-            keyMap->GetNumericKeyString(aInput, outBuf);
-            aOutput.Append(outBuf[i]);
-            }
-        else
-            {
-            aOutput.Append(aInput[i]);
-            }
+        UpdateNameOrderL();
         }
     }
 
-// ----------------------------------------------------------------------------
-// CPcsAlgorithm2Helper::FilterDataFieldsL()
-// Constructs a bit pattern using the required/supported data fields
-// For example, 6, 4 and 27 are supported fields <-- 00000111
-//              6 and 4 are required fields      <-- 00000011
-// Bit pattern returned is 00000011.
-// ----------------------------------------------------------------------------
-TUint8 CPcsAlgorithm2Helper::FilterDataFieldsL(RArray<TInt>& aRequiredDataFields, 
-                                               RArray<TInt>& aSupportedDataFields)
-    {
-    TUint8 filteredMatch = 0x0;
-
-    for (int i = 0; i < aSupportedDataFields.Count(); i++)
-        {
-        for (int j = 0; j < aRequiredDataFields.Count(); j++)
-            {
-            if (aSupportedDataFields[i] == aRequiredDataFields[j])
-                {
-                TReal val;
-                Math::Pow(val, 2, i);
-
-                filteredMatch |= (TUint8) val;
-                }
-            }
-        }
-
-    return filteredMatch;
-    }
-
 // End of file
 
 
--- a/predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsAlgorithm2MultiSearchHelper.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsAlgorithm2MultiSearchHelper.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -23,26 +23,7 @@
 #include <collate.h>
 #include <biditext.h>
 
-// Compare functions
-TBool Compare2(const HBufC& aFirst, const HBufC& aSecond)
-    {
-    TPtrC t1(aFirst);
-    TPtrC t2(aSecond);
-    return (t1.Length() > t2.Length());
-    }
 
-TBool Compare3(const TDesC& aFirst, const TDesC& aSecond)
-    {
-    return aFirst == aSecond;
-    }
-
-TBool Compare4(const CPsQuery& aFirst, const CPsQuery& aSecond)
-    {
-    CPsQuery& first = const_cast<CPsQuery&> (aFirst);
-    CPsQuery& second = const_cast<CPsQuery&> (aSecond);
-    
-    return (first.Count() > second.Count());
-    }
 // ============================== MEMBER FUNCTIONS ============================
 
 // ----------------------------------------------------------------------------
@@ -82,13 +63,14 @@
     PRINT ( _L("Enter CPcsAlgorithm2MultiSearchHelper::ConstructL") );
 
     iAlgorithm = aAlgorithm;
-    keyMap = iAlgorithm->GetKeyMap();
-
+    iKeyMap = iAlgorithm->GetKeyMap();
+    iMaxCount = 0;
+    
     PRINT ( _L("End CPcsAlgorithm2MultiSearchHelper::ConstructL") );
     }
 
 // ----------------------------------------------------------------------------
-// CPcsAlgorithm2MultiSearchHelper::CPcsAlgorithm2MultiSearchHelper
+// CPcsAlgorithm2MultiSearchHelper::~CPcsAlgorithm2MultiSearchHelper
 // Destructor
 // ----------------------------------------------------------------------------
 CPcsAlgorithm2MultiSearchHelper::~CPcsAlgorithm2MultiSearchHelper()
@@ -116,90 +98,105 @@
 // ----------------------------------------------------------------------------
 void CPcsAlgorithm2MultiSearchHelper::SearchMultiL(const CPsSettings& aSettings, 
                                                    RPointerArray<CPsQuery>& aPsQuery,
-                                                   TBool isSearchInGroup, 
-                                                   RArray<TInt>& aContactsInGroup, 
-                                                   RPointerArray<CPsData>& searchResults,
-                                                   RPointerArray<CPsPattern>& searchSeqs,
-                                                   TInt keyboardMode)
+                                                   TBool aIsSearchInGroup, 
+                                                   const RArray<TInt>& aContactsInGroup, 
+                                                   RPointerArray<CPsData>& aSearchResults,
+                                                   RPointerArray<CPsPattern>& aSearchSeqs)
     {
-    __LATENCY_MARK ( _L("CPcsAlgorithm2MultiSearchHelper::SearchMultiL") );
     PRINT ( _L("Enter CPcsAlgorithm2MultiSearchHelper::SearchMultiL") );
 
+    //__LATENCY_MARK ( _L("CPcsAlgorithm2MultiSearchHelper::SearchMultiL") );
+
+    PRINTQUERYLIST ( _L("CPcsAlgorithm2MultiSearchHelper::SearchMultiL: "), aPsQuery );
+
+    iMaxCount = aSettings.MaxResults();
     // Create CPcsAlgorithm2FilterHelper object to be used for filtering the results
     TSortType sortType = aSettings.GetSortType();
     CPcsAlgorithm2FilterHelper* filterHelper = CPcsAlgorithm2FilterHelper::NewL(sortType);
+    CleanupStack::PushL( filterHelper );
     RPointerArray<CPcsPoolElement> elements;
+    CleanupClosePushL( elements );
 
     iMultiSearchResultsArr.ResetAndDestroy();
 
     // Get the data stores  
-    RPointerArray<TDesC> aDataStores;
-    aSettings.SearchUrisL(aDataStores);
+    RPointerArray<TDesC> dataStores;
+    CleanupResetAndDestroyPushL( dataStores );
+    aSettings.SearchUrisL(dataStores);
 
     // Get the required display fields from the client
     RArray<TInt> requiredDataFields;
+    CleanupClosePushL( requiredDataFields );
     aSettings.DisplayFieldsL(requiredDataFields);
 
-    // Search from cache based on first character
+    // Search from cache based on first character of 1st item in query list
     const CPsQueryItem& firstCharItem = aPsQuery[0]->GetItemAtL(0);
-    TInt numValue  = keyMap->PoolIdForCharacter( firstCharItem.Character() );
-    
+    TInt cachePoolId = iKeyMap->PoolIdForCharacter( firstCharItem.Character(), firstCharItem.Mode() );
+
     // Get the elements from all the databases
-    for (int dsIndex = 0; dsIndex < aDataStores.Count(); dsIndex++)
+    const TInt dataStoresCount = dataStores.Count(); 
+    for (TInt dsIndex = 0; dsIndex < dataStoresCount; dsIndex++)
         {
         RPointerArray<CPsData> *temp = new (ELeave) RPointerArray<CPsData> ();
         iMultiSearchResultsArr.Append(temp);
 
         // Get the contents for this data store
-        TInt arrayIndex = iAlgorithm->GetCacheIndex(*(aDataStores[dsIndex]));
+        TInt arrayIndex = iAlgorithm->GetCacheIndex(*(dataStores[dsIndex]));
         if (arrayIndex < 0)
             {
             continue;
             }
         CPcsCache* cache = iAlgorithm->GetCache(arrayIndex);
-        cache->GetContactsForKeyL(numValue, elements);
+        cache->GetContactsForKeyL(cachePoolId, elements);
 
         // Get the supported data fields for this data store
         RArray<TInt> supportedDataFields;
+        CleanupClosePushL( supportedDataFields );
         cache->GetDataFields(supportedDataFields);
 
-        // Get the filtered data fields for this data store    		
-        TUint8 filteredDataMatch = FilterDataFieldsL(requiredDataFields, supportedDataFields);
+        // Get the filtered data fields for this data store
+        TUint8 filteredDataMatch = CPcsAlgorithm2Utils::FilterDataFieldsL(
+                requiredDataFields, supportedDataFields);
 
         // Filter the results now
-        FilterResultsMultiL(filterHelper, elements, aPsQuery, filteredDataMatch, 
-                            isSearchInGroup, aContactsInGroup, keyboardMode);
+        FilterResultsMultiL(filterHelper, 
+                            elements, 
+                            aPsQuery, 
+                            filteredDataMatch, 
+                            aIsSearchInGroup, 
+                            aContactsInGroup);
 
-        // If alphabetical sorting, get the results for this datastore               
+        // If alphabetical sorting, get the results for this datastore
         if (sortType == EAlphabetical)
             {
             filterHelper->GetResults(*(iMultiSearchResultsArr[dsIndex]));
             }
 
         elements.Reset();
-        supportedDataFields.Reset();
+        CleanupStack::PopAndDestroy( &supportedDataFields ); // Close
         }
-    aDataStores.ResetAndDestroy();
-    requiredDataFields.Reset();
+    CleanupStack::PopAndDestroy( &requiredDataFields ); // Close
+    CleanupStack::PopAndDestroy( &dataStores );         // ResetAndDestroy
 
     // If alphabetical sorting, merge the result sets of all datastores
     if (sortType == EAlphabetical)
         {
         // Form the complete searchResults array
-        CPcsAlgorithm2Utils::FormCompleteSearchResultsL(iMultiSearchResultsArr, searchResults);
+        CPcsAlgorithm2Utils::FormCompleteSearchResultsL(iMultiSearchResultsArr, 
+                                                        aSearchResults);
         }
     else
         {
         // Results are already sorted patternbased
-        filterHelper->GetResults(searchResults);
+        filterHelper->GetResults(aSearchResults);
         }
 
     // Get the sorted match sequence list
-    filterHelper->GetPatternsL(searchSeqs);
+    filterHelper->GetPatternsL(aSearchSeqs);
 
-    PRINT1 ( _L("Number of search results = %d"), searchResults.Count() );
+    PRINT1 ( _L("Number of search results = %d"), aSearchResults.Count() );
 
-    // Cleanup             
+    // Cleanup
     for (TInt i = 0; i < iMultiSearchResultsArr.Count(); i++)
         {
         iMultiSearchResultsArr[i]->Reset();
@@ -208,278 +205,148 @@
         }
 
     iMultiSearchResultsArr.Reset();
-    delete filterHelper;
+    CleanupStack::PopAndDestroy( &elements ); // Close
+    CleanupStack::PopAndDestroy( filterHelper );
+
+    //__LATENCY_MARKEND ( _L("CPcsAlgorithm2MultiSearchHelper::SearchMultiL") );
 
     PRINT ( _L("End CPcsAlgorithm2MultiSearchHelper::SearchMultiL") );
-    __LATENCY_MARKEND ( _L("CPcsAlgorithm2MultiSearchHelper::SearchMultiL") );
     }
 
 // ----------------------------------------------------------------------------
-// CPcsAlgorithm2MultiSearchHelper::SearchInputMultiL
-// Function to search match sequences for multi query
+// CPcsAlgorithm1MultiSearchHelper::SearchMatchSeqMultiL
+// Function adds matches, and locations based on multi query, and data
+// Duplicate locations are allowed (as they are removed later anyway)
+// Post condition locations in index order
 // ----------------------------------------------------------------------------
-void CPcsAlgorithm2MultiSearchHelper::SearchMatchSeqMultiL(RPointerArray<CPsQuery>& aPsQuery, 
-                                                           TDesC& aData, 
-                                                           RPointerArray<TDesC>& aMatchSet,
-                                                           RArray<TPsMatchLocation>& aMatchLocation)
+void CPcsAlgorithm2MultiSearchHelper::SearchMatchSeqMultiL( RPointerArray<CPsQuery>& aPsQuery,
+                                                            const TDesC& aData,
+                                                            RPointerArray<TDesC>& aMatchSeq,
+                                                            RArray<TPsMatchLocation>& aMatchLocation )
     {
     PRINT ( _L("Enter CPcsAlgorithm2MultiSearchHelper::SearchMatchSeqMultiL") );
-    CleanupResetAndDestroyPushL( aMatchSet );
-    CleanupClosePushL( aMatchLocation );
-    
-    RPointerArray<HBufC> queryList;
-    ConvertQueryToListL(aPsQuery, queryList);
-
-    RPointerArray<HBufC> tempqueryList;
-    // Remember a temporary copy of query list
-    // since we sort the queries
-    for (TInt i = 0; i < queryList.Count(); i++)
-        {
-        tempqueryList.Append(queryList[i]);
-        }
-    // To hold the match results
-    RPointerArray<TDesC> tmpMatchSet;
-    TBool isMatch = ETrue;
-    TUint32 wordMatches = 0;
-
-    // Sort the query items before we search them
-    TLinearOrder<HBufC> rule(Compare2);
-    queryList.Sort(rule);
 
-    // Check for each query atleast one data element matches
-    // Loop from the last query so that longest match is seen first
-    for (TInt queryIndex = queryList.Count() - 1; queryIndex >= 0; queryIndex--)
+    TLex lex(aData);
+    while ( !lex.Eos() ) // Search thru all words
         {
-        TBool queryMatch = EFalse;
-        HBufC* tmpQuery = queryList[queryIndex];
-        // Get the original query mode corresponding to this query
-        TInt modeIndex = tempqueryList.Find(tmpQuery);
-
-        TLex lex(aData);
+        TPtrC currentWord = lex.NextToken(); // next word
 
-        // First word
-        TPtrC tmpData = lex.NextToken();
-
-        TInt beg = lex.Offset() - tmpData.Length(); // start index of match sequence
-
-        TInt wordIndex = -1;
-        // Search thru multiple words
-        while ((tmpData.Length() != 0) && (!queryMatch))
+        const TInt psQueryCount = aPsQuery.Count(); 
+        for ( TInt queryIndex = 0; queryIndex < psQueryCount; ++queryIndex )
             {
-            wordIndex++;
+            CPsQuery* currentQuery = aPsQuery[queryIndex];
 
-            TPtr ptr = tmpQuery->Des();
-
-            // Perform two checks.
-            // 1. Ensure that the word is not matched against any previous query
-            // 2. If it is the first match to the query
-            TBool isWordMatch = EFalse;
-            TReal val;
-            Math::Pow(val, 2, wordIndex);
-            isWordMatch = wordMatches & (TUint) val;
-
-            if (!isWordMatch)
+            RArray<TInt> matchPos;
+            CleanupClosePushL( matchPos );
+            RArray<TInt> matchLen;
+            CleanupClosePushL( matchLen );
+            
+            if ( iAlgorithm->FindUtilECE()->MatchRefineL( currentWord, *currentQuery, matchPos, matchLen, ETrue ) )
                 {
-                // Check if no word is matched till now for this query
-                if (!queryMatch)
+                // Some matches found. Add all of them to result array.
+                ASSERT( matchPos.Count() == matchLen.Count() );
+                
+                TInt wordStartPos = lex.Offset() - currentWord.Length();
+                const TInt matchPosCount =  matchPos.Count(); 
+                for ( TInt i = 0 ; i < matchPosCount; ++i )
                     {
-                    queryMatch = ETrue;
-                    //set the word match bit
-                    TReal val;
-                    Math::Pow(val, 2, wordIndex);
-                    wordMatches |= (TUint) val;
-                    }
+                    TPsMatchLocation newLocation = { wordStartPos + matchPos[i], matchLen[i], 
+                            TBidiText::TextDirectionality(currentWord) };
+                    aMatchLocation.AppendL( newLocation );
 
-                TPsMatchLocation tempLocation;
-                // check for directionality of the text
-                TBool found(EFalse);
-                TBidiText::TDirectionality dir = TBidiText::TextDirectionality(tmpData, &found);
-
-                tempLocation.index = beg;
-                tempLocation.length = 0;
-                tempLocation.direction = dir;
-
-                // Add the match location to the data structure array
-                aMatchLocation.Append(tempLocation);
+                    TPtrC matchPart = currentWord.Mid( matchPos[i], matchLen[i] );
+                    CPcsAlgorithm2Utils::AppendMatchToSeqL( aMatchSeq, matchPart );
+                    }
                 }
-            }
-        // Next word
-        tmpData.Set(lex.NextToken());
-        beg = lex.Offset() - tmpData.Length(); // start index of next word  
-
-
-        // No data element matches the query. Ignore this result.
-        if (queryMatch == EFalse)
-            {
-            isMatch = EFalse;
-            break;
+                
+            CleanupStack::PopAndDestroy( &matchLen );
+            CleanupStack::PopAndDestroy( &matchPos );
             }
         }
 
-    // Count the number of bits set
-    TInt matchCount = 0;
-    matchCount = BitsSet32(wordMatches);
-
-    // If match add the element to the result set
-    // Before adding to the result set, check if there is atleast one match per query
-    // Number of bits set in word matches is atleast equal to total number of queries.
-    if ((isMatch) && (matchCount >= queryList.Count()))
-        {
-
-        // Include the match sequences in the final results
-        for (int i = 0; i < tmpMatchSet.Count(); i++)
-            {
-            TIdentityRelation<TDesC> rule(Compare3);
-            CleanupStack::PushL(tmpMatchSet[i]);
-            if (aMatchSet.Find(tmpMatchSet[i], rule) == KErrNotFound)
-                {
-                aMatchSet.Append(tmpMatchSet[i]);
-                CleanupStack::Pop();
-                }
-            else
-                {
-                CleanupStack::PopAndDestroy();
-                }
-            }
-
-        // Reset tmp match set
-        tmpMatchSet.Reset();
-        }
-    else
-        {
-        tmpMatchSet.ResetAndDestroy();
-        }
-
-    // Free the query list
-    queryList.ResetAndDestroy();
-    tempqueryList.Reset();
-    
-    CleanupStack::Pop();
-    CleanupStack::Pop( &aMatchSet );
-
     PRINT ( _L("End CPcsAlgorithm2MultiSearchHelper::SearchMatchSeqMultiL") );
     }
 
 // ----------------------------------------------------------------------------
-// CPcsAlgorithm2MultiSearchHelper::ConvertQueryToList
-// Converts the multiple search queries to a list
-// ----------------------------------------------------------------------------
-void CPcsAlgorithm2MultiSearchHelper::ConvertQueryToListL(RPointerArray<CPsQuery>& aSearchQuery, 
-                                                          RPointerArray<HBufC>& aQueryList)
-    {
-    for (int queryIndex = 0; queryIndex < aSearchQuery.Count(); queryIndex++)
-        {
-        CPsQuery* query = aSearchQuery[queryIndex];
-
-        HBufC* tmpSearchQuery = HBufC::NewL(KPsQueryMaxLen);
-        TPtr ptr = tmpSearchQuery->Des();
-
-        if (query->KeyboardModeL() == EItut) // ITU
-            {
-            keyMap->GetNumericKeyString(query->QueryAsStringLC(), ptr);
-            CleanupStack::PopAndDestroy();
-            }
-        else if (query->KeyboardModeL() == EQwerty) // QWERTY
-            {
-            ptr = query->QueryAsStringLC();
-            ptr.LowerCase();
-            CleanupStack::PopAndDestroy();
-            }
-        else // UNDEFINED
-            {
-            ExtractQueryL(*query, ptr);
-            ptr.LowerCase();
-            }
-        aQueryList.Append(tmpSearchQuery);
-        }
-    }
-
-// ----------------------------------------------------------------------------
-// CPcsAlgorithm2MultiSearchHelper::ConvertdDataToKeyBoardModeL
-// Converts the input data to the key board mode specified by the query
-// ----------------------------------------------------------------------------
-void CPcsAlgorithm2MultiSearchHelper::ConvertdDataToKeyBoardModeL(CPsQuery* aQuery, 
-                                                                  TPtrC aInputData, 
-                                                                  TBuf<KPsQueryMaxLen>& aOutputData)
-    {
-    if (aQuery->KeyboardModeL() == EItut)
-        {
-        keyMap->GetNumericKeyString(aInputData, aOutputData);
-        }
-    else if (aQuery->KeyboardModeL() == EQwerty)
-        {
-        aOutputData = aInputData;
-        aOutputData.LowerCase();
-        }
-    else
-        {
-        ExtractQueryL(aInputData, *aQuery, aOutputData);
-        aOutputData.LowerCase();
-        }
-    }
-
-// ----------------------------------------------------------------------------
 // CPcsAlgorithm2MultiSearchHelper::FilterResultsMultiL
 // Subset search function. Refer the above function for more description.
 // ----------------------------------------------------------------------------
 void CPcsAlgorithm2MultiSearchHelper::FilterResultsMultiL(CPcsAlgorithm2FilterHelper* aAlgorithmFilterHelper, 
-                                                          RPointerArray<CPcsPoolElement>& searchSet,
-                                                          RPointerArray<CPsQuery>& searchQuery, 
+                                                          RPointerArray<CPcsPoolElement>& aSearchSet,
+                                                          RPointerArray<CPsQuery>& aSearchQuery, 
                                                           TUint8 aFilteredDataMatch,
-                                                          TBool isSearchInGroup, 
-                                                          RArray<TInt>& aContactsInGroup,
-                                                          TInt keyboardMode)
+                                                          TBool aIsSearchInGroup, 
+                                                          const RArray<TInt>& aContactsInGroup)
     {
     PRINT ( _L("Enter CPcsAlgorithm2MultiSearchHelper::FilterResultsMultiL") );
 
+    //__LATENCY_MARK ( _L("CPcsAlgorithm2MultiSearchHelper::FilterResultsMultiL") );
+
+    TInt maxcount = 0;
+    
     // Convert the individual queries to string form
     RPointerArray<CPsQuery> mySearchQuery;
+    CleanupResetAndDestroyPushL( mySearchQuery );
 
     // Remember a temporary copy of query list
     // Copy the content of searchQuery
-    for (TInt i=0; i<searchQuery.Count(); i++)
+    const TInt searchQueryCount = aSearchQuery.Count(); 
+    for (TInt i=0; i < searchQueryCount; i++)
         {
         CPsQuery* tempQuery = CPsQuery::NewL();
-        iAlgorithm->FindUtilECE()->GetPartOfQueryL(*(searchQuery[i]), 0, 
-                                                   searchQuery[i]->Count()-1, *tempQuery);
-        mySearchQuery.Append(tempQuery);
+        CleanupStack::PushL( tempQuery );
+        iAlgorithm->FindUtilECE()->GetPartOfQueryL(
+                *(aSearchQuery[i]), 0, aSearchQuery[i]->Count()-1, *tempQuery );
+        mySearchQuery.AppendL(tempQuery);
+        CleanupStack::Pop(tempQuery); // ownership transferred
         }
 
     // Sort the query items according to the length of each query 
-    TLinearOrder<CPsQuery> rule(Compare4);
+    TLinearOrder<CPsQuery> rule(CPcsAlgorithm2Utils::CompareLength);
     mySearchQuery.Sort(rule);
 
     // To hold the match results
     RPointerArray<TDesC> tmpMatchSet;
+    CleanupResetAndDestroyPushL( tmpMatchSet );
 
-    // Parse thru each search set elements and filter the results    
-    for (int index = 0; index < searchSet.Count(); index++)
+    // Parse thru each search set elements and filter the results
+    const TInt searchSetCount = aSearchSet.Count(); 
+    for (TInt index = 0; index < searchSetCount; index++)
         {
-        CPcsPoolElement* poolElement = static_cast<CPcsPoolElement*> (searchSet[index]);
+        CPcsPoolElement* poolElement = static_cast<CPcsPoolElement*> (aSearchSet[index]);
         CPsData* psData = poolElement->GetPsData();
         psData->ClearDataMatches();
 
+        // Skip the contact if we are doing a group search and contact doesn't belong to the group
+        if ( aIsSearchInGroup && 
+             aContactsInGroup.Find( psData->Id() ) == KErrNotFound )
+            {
+            continue;
+            }
+        
         TBool isMatch = ETrue;
-        TUint8 wordMatches = 0;
+        TInt wordMatches = 0;
 
         // Reset iWordMatches to zero 
         ClearWordMatches();
 
         // Check for each query atleast one data element matches
         // Loop from the last query so that longest match is seen first
-        for (TInt queryIndex = mySearchQuery.Count() - 1; queryIndex >= 0; queryIndex--)            
+        for (TInt queryIndex = mySearchQuery.Count() - 1; queryIndex >= 0; queryIndex--)
             {
             TBool queryMatch = EFalse;
             CPsQuery* tmpPsQuery = mySearchQuery[queryIndex];
 
-            for (TInt dataIndex = 0; dataIndex < psData->DataElementCount(); dataIndex++)
+            const TInt dataElementCount = psData->DataElementCount();
+            for (TInt dataIndex = 0; dataIndex < dataElementCount; dataIndex++)
                 {
                 // Filter off data fields not required in search
-                TReal bitIndex;
-                Math::Pow(bitIndex, 2, dataIndex);
-
-                TUint8 filter = (TUint8) bitIndex & aFilteredDataMatch;
-                if (filter == 0x0)
+                TUint8 bitIndex = 1 << dataIndex;
+                TUint8 filter = bitIndex & aFilteredDataMatch;
+                
+                // Omit the data fields which is not required in search
+                // or not matched with the pool element
+                if ( filter == 0x0 ) 
                     {
                     // Move to next data
                     continue;
@@ -497,27 +364,9 @@
                     {
                     wordIndex++;
                     
-                    TPtrC queryPtr = tmpPsQuery->QueryAsStringLC();
-                    TBool matched = EFalse;
+                    // Compare the data against query
+                    TBool matched = iAlgorithm->FindUtilECE()->MatchRefineL(tmpData, *tmpPsQuery);
                     
-                    if (keyboardMode == EModeUndefined)
-                        {
-                        matched = iAlgorithm->FindUtilECE()->MatchRefineL(tmpData, *tmpPsQuery);
-                        }
-                    else if (keyboardMode == EItut)
-                        {
-                        matched = iAlgorithm->FindUtil()->Interface()->
-                                  MatchRefineL(tmpData, queryPtr, ECustomConverter, iAlgorithm);
-                        }
-                    else // Qwerty
-                        {
-                        matched = iAlgorithm->FindUtil()->Interface()->MatchRefineL(tmpData, queryPtr);
-                        
-                        }
-                    
-                    CleanupStack::PopAndDestroy(); // queryPtr
-                    
-                    // Compare the data against query
                     if (matched)
                         {
                         psData->SetDataMatch(dataIndex);
@@ -540,25 +389,18 @@
 
                             // Extract matched character sequence and fill in temp array
                             TInt len = tmpPsQuery->Count();
-                            if (iAlgorithm->FindUtilECE()->IsChineseWord(tmpData))
+                            if (iAlgorithm->FindUtilECE()->IsChineseWordIncluded(tmpData))
                                 {
                                 len = 1;
                                 }
 
-                            HBufC* seq = HBufC::NewL(len);
-                            *seq = tmpData.Mid(0, len);
-
-                            seq->Des().UpperCase();
-                            TIdentityRelation<TDesC> searchRule(Compare3);
-                            if (tmpMatchSet.Find(seq, searchRule) == KErrNotFound)
-                                {
-                                tmpMatchSet.Append(seq);
-                                }
-                            else
-                                {
-                                delete seq;
-                                seq = NULL;
-                                }
+                            TPtrC seq = tmpData.Left(len);
+                            CPcsAlgorithm2Utils::AppendMatchToSeqL( tmpMatchSet, seq );
+                            
+                            // TODO: Match seqs could be extracted from actual
+                            //       match locations by using the other overload of
+                            //       CFindUtilChineseECE::MatchRefineL().
+                            //       Currently, match seq data is not used by clients.
                             }
                         }
 
@@ -574,112 +416,50 @@
                 break;
                 }
             }
+        
 
         // If match add the element to the result set
         //  And before adding to the result set, check if there is atleast one match per query
-        if ((isMatch) && (wordMatches >= mySearchQuery.Count()))
+        if ( isMatch && wordMatches >= mySearchQuery.Count() )
             {
-            if (isSearchInGroup)
-                {
-                if (aContactsInGroup.Find(psData->Id()) != KErrNotFound)
-                    {
-                    aAlgorithmFilterHelper->AddL(psData, tmpMatchSet);
-                    }
-                }
-            else
-                {
-                aAlgorithmFilterHelper->AddL(psData, tmpMatchSet);
-                }
+            aAlgorithmFilterHelper->AddL(psData, tmpMatchSet);
+            maxcount++;
             }
-
+        
+        if ( iMaxCount != -1 && maxcount > iMaxCount )
+            {
+            break;
+            }
+        
         // Cleanup the match sequence array as 
         // they are stored in pattern details structure
         tmpMatchSet.ResetAndDestroy();
         }
 
-    mySearchQuery.Reset();
+    CleanupStack::PopAndDestroy( &tmpMatchSet );   // ResetAndDestroy
+    CleanupStack::PopAndDestroy( &mySearchQuery ); // ResetAndDestroy
+
+    //__LATENCY_MARKEND ( _L("CPcsAlgorithm2MultiSearchHelper::FilterResultsMultiL") );
 
     PRINT ( _L("End CPcsAlgorithm2MultiSearchHelper::FilterResultsMultiL") );
     }
 
 // ----------------------------------------------------------------------------
-// CPcsAlgorithm2MultiSearchHelper::SetWordMap()
+// CPcsAlgorithm2MultiSearchHelper::SetWordMap
 // ----------------------------------------------------------------------------
 void CPcsAlgorithm2MultiSearchHelper::SetWordMap(TInt aIndex, TInt aPosition)
     {
-    TReal val;
-    Math::Pow(val, 2, aPosition);
-
-    iWordMatches[aIndex] |= (TUint8) val;
-    }
-
-// ----------------------------------------------------------------------------
-// CPcsAlgorithm2MultiSearchHelper::IsWordMatch()
-// ----------------------------------------------------------------------------
-TBool CPcsAlgorithm2MultiSearchHelper::IsWordMatch(TInt aDataIndex, TInt aWordIndex)
-    {
-    TReal val;
-    Math::Pow(val, 2, aWordIndex);
-
-    return (iWordMatches[aDataIndex] & (TUint8) val);
+    TUint8 val = 1 << aPosition;
+    iWordMatches[aIndex] |= val;
     }
 
 // ----------------------------------------------------------------------------
-// CPcsAlgorithm2MultiSearchHelper::ExtractQueryL()
-// Extracts the query as a string. If the mode of query item is ITU numeric
-// character is used. Else the character is used.
-// ----------------------------------------------------------------------------
-void CPcsAlgorithm2MultiSearchHelper::ExtractQueryL(CPsQuery& aQuery, TDes& aOutput)
-    {
-    for (int i = 0; i < aQuery.Count(); i++)
-        {
-        if (aQuery.GetItemAtL(i).Mode() == EItut)
-            {
-            TBuf<KPsQueryMaxLen> outBuf;
-            keyMap->GetNumericKeyString(aQuery.QueryAsStringLC(), outBuf);
-            aOutput.Append(outBuf[i]);
-            CleanupStack::PopAndDestroy();
-            }
-        else
-            {
-            aOutput.Append(aQuery.GetItemAtL(i).Character());
-            }
-        }
-    }
-
-// ----------------------------------------------------------------------------
-// CPcsAlgorithm2MultiSearchHelper::ExtractQueryL()
-// Converts the input data refering the modes in the query.
-// If the mode of query item is ITU numeric character is used. Else the character
-// is used.
+// CPcsAlgorithm2MultiSearchHelper::IsWordMatch
 // ----------------------------------------------------------------------------
-void CPcsAlgorithm2MultiSearchHelper::ExtractQueryL(TDesC& aInput, CPsQuery& aQuery, TDes& aOutput)
+TBool CPcsAlgorithm2MultiSearchHelper::IsWordMatch(TInt aDataIndex, TInt aWordIndex)
     {
-    TInt len = -1;
-
-    // Always loop thru the lowest length
-    if (aInput.Length() > aQuery.Count())
-        {
-        len = aQuery.Count();
-        }
-    else
-        {
-        len = aInput.Length();
-        }
-
-    for (int i = 0; i < len; i++)
-        {
-        if (aQuery.GetItemAtL(i).Mode() == EItut)
-            {
-            TBuf<KPsQueryMaxLen> outBuf;
-            keyMap->GetNumericKeyString(aInput, outBuf);
-            aOutput.Append(outBuf[i]);
-            }
-        else
-            {
-            aOutput.Append(aInput[i]);
-            }
-        }
+    TUint8 val = 1 << aWordIndex;
+    return (iWordMatches[aDataIndex] & val);
     }
 
 // ----------------------------------------------------------------------------
@@ -699,7 +479,7 @@
     }
 
 // ----------------------------------------------------------------------------
-// CPcsAlgorithm2MultiSearchHelper::BitsSet32
+// CPcsAlgorithm2MultiSearchHelper::ClearWordMatches
 // Function to reset the iWordMatches
 // ----------------------------------------------------------------------------
 void CPcsAlgorithm2MultiSearchHelper::ClearWordMatches()
@@ -729,13 +509,14 @@
             {
             // Scan the end of the word
             TInt end = beg;
-            for (; end < textLength && !aQuery.GetItemAtL(end).Character().IsSpace(); ++end)
+            while ( end < textLength && !aQuery.GetItemAtL(end).Character().IsSpace() )
                 {
+                end++;
                 }
 
             // Create a new query object and append
             CPsQuery* newQuery = CPsQuery::NewL();
-            for (int i = beg; i < end; i++)
+            for (TInt i = beg; i < end; i++)
                 {
                 CPsQueryItem* item = CPsQueryItem::NewL();
                 item->SetCharacter(aQuery.GetItemAtL(i).Character());
@@ -752,35 +533,6 @@
     return query;
     }
 
-// ----------------------------------------------------------------------------
-// CPcsAlgorithm2MultiSearchHelper::FilterDataFieldsL()
-// Constructs a bit pattern using the required/supported data fields
-// For example, 6, 4 and 27 are supported fields <-- 00000111
-//              6 and 4 are required fields      <-- 00000011
-// Bit pattern returned is 00000011.
-// ----------------------------------------------------------------------------
-TUint8 CPcsAlgorithm2MultiSearchHelper::FilterDataFieldsL(RArray<TInt>& aRequiredDataFields, 
-                                                          RArray<TInt>& aSupportedDataFields)
-    {
-    TUint8 filteredMatch = 0x0;
-
-    for (int i = 0; i < aSupportedDataFields.Count(); i++)
-        {
-        for (int j = 0; j < aRequiredDataFields.Count(); j++)
-            {
-            if (aSupportedDataFields[i] == aRequiredDataFields[j])
-                {
-                TReal val;
-                Math::Pow(val, 2, i);
-
-                filteredMatch |= (TUint8) val;
-                }
-            }
-        }
-
-    return filteredMatch;
-    }
-
 // End of file
 
 
--- a/predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsAlgorithm2Utils.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsAlgorithm2Utils.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -18,6 +18,7 @@
 // INCLUDES
 #include "CPcsAlgorithm2Utils.h"
 #include "CPsData.h"
+#include "CPsQuery.h"
 #include "CPcsDefs.h"
 #include "CPcsCache.h"
 #include <collate.h>
@@ -33,16 +34,15 @@
 // Merges all the respective data store result sets to single set in sorted order.
 // ----------------------------------------------------------------------------
 void CPcsAlgorithm2Utils::FormCompleteSearchResultsL(RPointerArray<CPSDATA_R_PTR_ARRAY>& aSearchResultsArr,
-                                                     RPointerArray<CPsData>& SearchResults)
+                                                     RPointerArray<CPsData>& aSearchResults)
     {
-    CleanupClosePushL( SearchResults );
-    
     TInt maxIndex = 0;
     TInt maxValue = aSearchResultsArr[maxIndex]->Count();
     TLinearOrder<CPsData> rule(CPcsAlgorithm2Utils::CompareDataBySortOrder);
 
     // Find the largest array in aSearchResultsArr
-    for (TInt i = 1; i < aSearchResultsArr.Count(); i++)
+    const TInt searchResultsArrCount = aSearchResultsArr.Count(); 
+    for (TInt i = 1; i < searchResultsArrCount; i++)
         {
         if (aSearchResultsArr[i]->Count() > maxValue)
             {
@@ -52,13 +52,15 @@
         }
 
     // Assign the largets array to searchresults 
-    for (TInt i = 0; i < aSearchResultsArr[maxIndex]->Count(); i++)
+    const TInt cnt = aSearchResultsArr[maxIndex]->Count();
+    for (TInt i = 0; i < cnt; i++)
         {
-        SearchResults.Append((*(aSearchResultsArr[maxIndex]))[i]);
+        aSearchResults.Append((*(aSearchResultsArr[maxIndex]))[i]);
         }
 
     // Merge the remaining result arrays to the largest array in sequential order
-    for (TInt i = 0; i < aSearchResultsArr.Count(); i++)
+
+    for (TInt i = 0; i < searchResultsArrCount; i++)
         {
         // Check if we are not copying again the largest array
         if ((i != maxIndex) && ((aSearchResultsArr[i])->Count() != 0))
@@ -66,11 +68,10 @@
             TInt numElements = (aSearchResultsArr[i])->Count();
             for (TInt j = 0; j < numElements; j++)
                 {
-                SearchResults.InsertInOrderAllowRepeatsL((*(aSearchResultsArr[i]))[j], rule);
+                aSearchResults.InsertInOrderAllowRepeatsL((*(aSearchResultsArr[i]))[j], rule);
                 }
             }
         }
-    CleanupStack::Pop();
     }
 
 // ----------------------------------------------------------------------------
@@ -121,7 +122,8 @@
     cache->GetIndexOrder(indexOrder);
 
     // Append sort order elements first
-    for (int i = 0; i < indexOrder.Count(); i++)
+    const TInt indexOrderCount1 = indexOrder.Count();
+    for (int i = 0; i < indexOrderCount1; i++)
         {
         TInt index = indexOrder[i];
         if (index < aObject1.DataElementCount() && aObject1.Data(index))
@@ -158,9 +160,10 @@
 
     // Get the index order based on sort order from the cache
     cache->GetIndexOrder(indexOrder);
+    const TInt indexOrderCount2 = indexOrder.Count();
 
     // Append sort order elements first
-    for (int i = 0; i < indexOrder.Count(); i++)
+    for (int i = 0; i < indexOrderCount2; i++)
         {
         TInt index = indexOrder[i];
         if (index < aObject2.DataElementCount() && aObject2.Data(index))
@@ -195,6 +198,27 @@
     }
 
 // ----------------------------------------------------------------------------
+// CPcsAlgorithm2Utils::CompareExact()
+// 
+// ----------------------------------------------------------------------------
+TBool CPcsAlgorithm2Utils::CompareExact(const TDesC& aFirst, const TDesC& aSecond)
+    {
+    return aFirst == aSecond;
+    }
+
+// ----------------------------------------------------------------------------
+// CPcsAlgorithm2Utils::CompareLength()
+// 
+// ----------------------------------------------------------------------------
+TInt CPcsAlgorithm2Utils::CompareLength(const CPsQuery& aFirst, const CPsQuery& aSecond)
+    {
+    CPsQuery& first = const_cast<CPsQuery&> (aFirst);
+    CPsQuery& second = const_cast<CPsQuery&> (aSecond);
+    
+    return (first.Count() - second.Count());
+    }
+
+// ----------------------------------------------------------------------------
 // CPcsAlgorithm2Utils::MyTrim()
 // Trim off all white spaces and special characters
 // This behavior is required to mimic the current phonebook sort sequence
@@ -233,5 +257,90 @@
     return ETrue;
     }
 
+// ----------------------------------------------------------------------------
+// CPcsAlgorithm1Helper::FilterDataFieldsL()
+// Constructs a bit pattern using the required/supported data fields
+// For example, 6, 4 and 27 are supported fields <-- 00000111
+//              6 and 4 are required fields      <-- 00000011
+// Bit pattern returned is 00000011.
+// ----------------------------------------------------------------------------
+TUint8 CPcsAlgorithm2Utils::FilterDataFieldsL(const RArray<TInt>& aRequiredDataFields,
+                                              const RArray<TInt>& aSupportedDataFields)
+{
+    TUint8 filteredMatch = 0x0;
+   const TInt supportedDataFieldsCount = aSupportedDataFields.Count();
+   const TInt requiredDataFieldsCount = aRequiredDataFields.Count(); 
+    for ( TInt i = 0; i < supportedDataFieldsCount; i++ )
+    {
+        for ( TInt j = 0; j < requiredDataFieldsCount; j++ )
+        {
+            if ( aSupportedDataFields[i] == aRequiredDataFields[j] )
+            {
+                TUint8 val = 1 << i;
+                filteredMatch |= val;
+            }
+        }
+    }
+
+    return filteredMatch;
+}
+
+// ----------------------------------------------------------------------------
+// CPcsAlgorithm2Utils::AppendMatchToSeqL
+// ----------------------------------------------------------------------------
+void CPcsAlgorithm2Utils::AppendMatchToSeqL( 
+        RPointerArray<TDesC>& aMatchSeq, const TDesC& aMatch )
+    {
+    HBufC* seq = aMatch.AllocLC();
+    seq->Des().UpperCase();
+    TIdentityRelation<TDesC> rule(CompareExact);
+    if ( aMatchSeq.Find(seq, rule) == KErrNotFound )
+        {
+        aMatchSeq.AppendL(seq);
+        CleanupStack::Pop( seq );
+        }
+    else 
+        {
+        CleanupStack::PopAndDestroy( seq );
+        }
+    }
+
+// ----------------------------------------------------------------------------
+// CPcsAlgorithm2Utils::MatchesOverlap
+// Check if two match location items have overlapping indices.
+// ----------------------------------------------------------------------------
+TBool CPcsAlgorithm2Utils::MatchesOverlap( const TPsMatchLocation& aFirst, 
+                                           const TPsMatchLocation& aSecond )
+    {
+    TBool overlap = EFalse;
+    
+    if ( aFirst.index == aSecond.index )
+        {
+        overlap = ETrue;
+        }
+    else
+        {
+        // give arguments alias names where first begins before the second
+        TInt firstPos( aFirst.index );
+        TInt firstLen( aFirst.length );
+        TInt secondPos( aSecond.index );
+        if ( firstPos > secondPos )
+            {
+            firstPos = aSecond.index;
+            firstLen = aSecond.length;
+            secondPos = aFirst.index;
+            }
+        
+        // there is an overlap if the end of the first comes after
+        // beginning of the second
+        if ( firstPos + firstLen > secondPos )
+            {
+            overlap = ETrue;
+            }
+        }
+    
+    return overlap;
+    }
+
 // End of File
 
--- a/predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsCache.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsCache.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -22,6 +22,7 @@
 
 // INCLUDE FILES
 #include <MVPbkContactLink.h>
+#include <VPbkEng.rsg>
 
 #include "FindUtilChineseECE.h"
 #include "CPsData.h"
@@ -37,7 +38,7 @@
 // CPcsCache::NewL
 // Two Phase Construction
 // ----------------------------------------------------------------------------
-CPcsCache* CPcsCache::NewL(CPcsAlgorithm2* aAlgorithm, TDesC& aURI, 
+CPcsCache* CPcsCache::NewL(CPcsAlgorithm2* aAlgorithm, const TDesC& aURI, 
                            CPcsKeyMap& aKeyMap, TUint8 aUriId)
     {
     PRINT ( _L("Enter CPcsCache::NewL") );
@@ -69,7 +70,7 @@
 // CPcsCache::ConstructL
 // 2nd Phase Constructor
 // ----------------------------------------------------------------------------
-void CPcsCache::ConstructL(CPcsAlgorithm2* aAlgorithm, TDesC& aURI, 
+void CPcsCache::ConstructL(CPcsAlgorithm2* aAlgorithm, const TDesC& aURI, 
                            CPcsKeyMap& aKeyMap, TUint8 aUriId)
     {
     PRINT ( _L("Enter CPcsCache::ConstructL") );
@@ -80,13 +81,14 @@
     //Update the caching status for this cache
     iCacheStatus = ECachingNotStarted;
 
-    keyMap = &aKeyMap;
+    iKeyMap = &aKeyMap;
 
-    // Populate keyArr
-    for (TInt i = 0; i < aKeyMap.PoolCount(); i++)
+    // Populate iKeyArr
+    const TInt keyMapPoolcount =  aKeyMap.PoolCount();
+    for (TInt i = 0; i < keyMapPoolcount; i++)
         {
-        RPointerArray<CPcsPoolElement> *keyMap = new (ELeave) RPointerArray<CPcsPoolElement> (1);
-        keyArr.InsertL(keyMap, i);
+        RPointerArray<CPcsPoolElement>* keyMap = new (ELeave) RPointerArray<CPcsPoolElement> (1);
+        iKeyArr.InsertL(keyMap, i);
         }
 
     PRINT ( _L("End CPcsCache::ConstructL") );
@@ -100,86 +102,15 @@
     {
     PRINT ( _L("Enter CPcsCache::~CPcsCache") );
 
-    if (iURI)
-        {
-        delete iURI;
-        }
-
-    // Loop thru cache info and free and the data elements
-    THashMapIter<TInt, TInt> iter(cacheInfo);
-
-    do
-        {
-        TInt* id = const_cast<TInt*> (iter.NextKey());
-
-        if (id == NULL)
-            break;
-
-        TInt* poolMap = iter.CurrentValue();
-
-        if (poolMap == NULL)
-            {
-            continue;
-            }
-
-        CPsData *data = NULL;
-        for (int keyIndex = 0; keyIndex <= keyArr.Count(); keyIndex++)
-            {
-            TBool present = GetPoolMap(*poolMap, keyIndex);
-
-            if (!present)
-                {
-                continue;
-                }
+    delete iURI;
 
-            RPointerArray<CPcsPoolElement> tmpKeyMap = *(keyArr[keyIndex]);
-            for (int arrayIndex = 0; arrayIndex < tmpKeyMap.Count(); arrayIndex++)
-                {
-                CPcsPoolElement *element = tmpKeyMap[arrayIndex];
-                TInt localId = element->GetPsData()->Id();
-                if (*id == localId)
-                    {
-                    data = element->GetPsData();
-                    delete element;
-                    keyArr[keyIndex]->Remove(arrayIndex);
-                    }
-                }
-            };
-
-        // Remove this element from master pool
-        for (int arrayIndex = 0; arrayIndex < masterPool.Count(); arrayIndex++)
-            {
-            CPsData *dataElement = masterPool[arrayIndex];
-            TInt localId = dataElement->Id();
-            if (*id == localId)
-                {
-                masterPool.Remove(arrayIndex);
-                }
-            }
-
-        if (data)
-            {
-            delete data;
-            }
-
-        }
-    while (1);
-
-    for (TInt i = 0; i < keyArr.Count(); i++)
-        {
-        keyArr[i]->ResetAndDestroy();
-        delete keyArr[i];
-        keyArr[i] = NULL;
-        }
-
-    masterPool.ResetAndDestroy();
-
-    cacheInfo.Close();
-
-    keyArr.Reset();
+    RemoveAllFromCache(); // cleans up iMasterPool and iCacheInfo
+   
+    iKeyArr.ResetAndDestroy();
     iDataFields.Reset();
     iSortOrder.Reset();
     iIndexOrder.Reset();
+    iMasterPoolBackup.Close();
 
     PRINT ( _L("End CPcsCache::~CPcsCache") );
     }
@@ -191,15 +122,18 @@
 void CPcsCache::GetContactsForKeyL(TInt aKeyId, RPointerArray<CPcsPoolElement>& aData)
     {
     PRINT ( _L("Enter CPcsCache::GetContactsForKeyL") );
-    CleanupClosePushL( aData );
-    RPointerArray<CPcsPoolElement> arr = *keyArr[aKeyId];
-    for (int i = 0; i < arr.Count(); i++)
+
+    if ( aKeyId >= 0 && aKeyId < iKeyArr.Count() )
         {
-        CPcsPoolElement* value = arr[i];
-        aData.AppendL(value);
+        const RPointerArray<CPcsPoolElement>& arr = *iKeyArr[aKeyId];
+        const TInt arrCount = arr.Count();
+        for (TInt i = 0; i < arrCount; i++)
+            {
+            CPcsPoolElement* value = arr[i];
+            aData.AppendL(value);
+            }
         }
 
-    CleanupStack::Pop();
     PRINT ( _L("End CPcsCache::GetContactsForKeyL") );
     }
 
@@ -210,13 +144,14 @@
 void CPcsCache::GetAllContentsL(RPointerArray<CPsData>& aData)
     {
     PRINT ( _L("Enter CPcsCache::GetAllContentsL") );
-    CleanupClosePushL( aData );
-    for (int i = 0; i < masterPool.Count(); i++)
+    
+    const TInt masterPoolCount =  iMasterPool.Count(); 
+    for (TInt i = 0; i < masterPoolCount; i++)
         {
-        CPsData* value = masterPool[i];
+        CPsData* value = iMasterPool[i];
         aData.AppendL(value);
         }
-    CleanupStack::Pop();
+
     PRINT ( _L("End CPcsCache::GetAllContentsL") );
     }
 
@@ -224,7 +159,7 @@
 // CPcsCache::AddToPool
 // Adds a contact to cache
 // ----------------------------------------------------------------------------
-void CPcsCache::AddToPoolL(TInt& aPoolMap, CPsData& aData)
+void CPcsCache::AddToPoolL(TUint64& aPoolMap, CPsData& aData)
     {
     // Temp hash to remember the location of pool elements
     // First TInt  = Pool 
@@ -232,68 +167,43 @@
     // Required for memory optimization so that more than one pool
     // element doesn't get added for the same data
     RHashMap<TInt, TInt> elementHash;
+    CleanupClosePushL( elementHash );
     TLinearOrder<CPcsPoolElement> rule(CPcsPoolElement::CompareByData);
 
-    // Parse thru each data element    
-    for (int dataIndex = 0; dataIndex < aData.DataElementCount(); dataIndex++)
+    // Parse thru each data element
+    const TInt dataElementCount = aData.DataElementCount();
+    for (TInt dataIndex = 0; dataIndex < dataElementCount; dataIndex++)
         {
         // Stores first key for each word
-        RArray<TChar> firstKey;
+        RArray<TChar> firstCharArr;
+        CleanupClosePushL( firstCharArr );
 
         // Recover the first character
-        if (aData.Data(dataIndex) && aData.Data(dataIndex)->Length() != 0)
+        if ( aData.Data(dataIndex) )
             {
-            // Split the data into words	
-            CWords* words = CWords::NewLC(*aData.Data(dataIndex));
+            GetFirstCharsForDataL( *aData.Data(dataIndex), firstCharArr );
+            }
+        
+        // Get the corresponding Pool IDs
+        RArray<TInt> poolIdArr;
+        CleanupClosePushL( poolIdArr );
+        GetPoolIdsForCharsL( firstCharArr, poolIdArr );
 
-            // Store the first numeric key for each word
-            for (int i = 0; i < words->MdcaCount(); i++)
-                {
-                TChar firstChar;
-                for (int j = 0; j < words->MdcaPoint(i).Length(); j++)
-                    {
-                    firstChar = (words->MdcaPoint(i))[j];
-                    TBuf<20> word;
-                    word.Append(firstChar);
-                    if (iAlgorithm->FindUtilECE()->IsChineseWord(word))
-                        {
-                        RPointerArray<HBufC> spellList;
-                        if (iAlgorithm->FindUtilECE()->T9ChineseTranslationL(firstChar, spellList))
-                            {
-                            for (int j = 0; j < spellList.Count(); j++)
-                                {
-                                firstKey.Append(keyMap->KeyForCharacter(*(spellList[j]->Ptr())));
-                                }
-                            }
-                        else
-                            {
-                            firstKey.Append( keyMap->KeyForCharacter(firstChar));
-                            }
-                        spellList.ResetAndDestroy();
-                        }
-                    else
-                        {
-                        firstKey.Append(keyMap->KeyForCharacter(firstChar));
-                        }
-                    }
-                }
-
-            CleanupStack::PopAndDestroy(words);
-            }
-
-        for (TInt wordIndex = 0; wordIndex < firstKey.Count(); wordIndex++)
+        const TInt poolIdArrCount = poolIdArr.Count();
+        for (TInt poolArrIndex = 0; poolArrIndex < poolIdArrCount ; poolArrIndex++)
             {
-            TInt arrayIndex = keyMap->PoolIdForCharacter(firstKey[wordIndex]);
+            
+            TInt poolId = poolIdArr[poolArrIndex];
 
             CPcsPoolElement* element = NULL;
 
             // Check if an element already exists in the pool for this data
             TInt* loc = NULL;
-            loc = elementHash.Find(arrayIndex);
+            loc = elementHash.Find(poolId);
             if (loc != NULL)
                 {
                 // Exists. Then recover ...
-                RPointerArray<CPcsPoolElement> tmpKeyMap = *(keyArr[arrayIndex]);
+                RPointerArray<CPcsPoolElement> tmpKeyMap = *(iKeyArr[poolId]);
                 element = tmpKeyMap[*loc];
                 }
 
@@ -304,30 +214,31 @@
                 element->SetDataMatch(dataIndex);
 
                 // Insert to pool
-                keyArr[arrayIndex]->InsertInOrderAllowRepeatsL(element, rule);
-                TInt index = keyArr[arrayIndex]->FindInOrderL(element, rule);
+                iKeyArr[poolId]->InsertInOrderAllowRepeatsL(element, rule);
+                TInt index = iKeyArr[poolId]->FindInOrderL(element, rule);
 
-                // Set the bit for this pool					
-                SetPoolMap(aPoolMap, arrayIndex);
+                // Set the bit for this pool
+                SetPoolMap(aPoolMap, poolId);
 
                 // Store the array index in the temp hash
-                elementHash.InsertL(arrayIndex, index);
+                elementHash.InsertL(poolId, index);
                 }
             else // Pool element exists. Just alter the data match attribute
                 {
                 element->SetDataMatch(dataIndex);
 
-                // Set the bit for this pool					
-                SetPoolMap(aPoolMap, arrayIndex);
+                // Set the bit for this pool
+                SetPoolMap(aPoolMap, poolId);
                 }
 
             } // for 2 loop
 
-        firstKey.Reset();
+        CleanupStack::PopAndDestroy( &poolIdArr );    // Close
+        CleanupStack::PopAndDestroy( &firstCharArr ); // Close
 
         } // for 1 loop
 
-    elementHash.Close();
+    CleanupStack::PopAndDestroy( &elementHash );  // Close
     }
 
 // ---------------------------------------------------------------------
@@ -337,19 +248,19 @@
 void CPcsCache::AddToCacheL(CPsData& aData)
     {
     // Protect against duplicate items getting added
-    if (cacheInfo.Find(aData.Id()) != NULL)
+    if (iCacheInfo.Find(aData.Id()) != NULL)
         {
         return;
         }
 
     // Include this element in the pool     
-    TInt poolMap = 0;
+    TUint64 poolMap = 0;
     AddToPoolL(poolMap, aData);
-    cacheInfo.InsertL(aData.Id(), poolMap);
+    iCacheInfo.InsertL(aData.Id(), poolMap);
 
     // Include this element in master pool        
     TLinearOrder<CPsData> rule(CPcsAlgorithm2Utils::CompareDataBySortOrder);
-    masterPool.InsertInOrderAllowRepeatsL(&aData, rule);
+    iMasterPool.InsertInOrderAllowRepeatsL(&aData, rule);
     }
 
 // ---------------------------------------------------------------------
@@ -360,7 +271,7 @@
     {
     CPsData *data = NULL;
 
-    TInt* poolMap = cacheInfo.Find(aItemId);
+    TUint64* poolMap = iCacheInfo.Find(aItemId);
 
     if (poolMap == NULL)
         {
@@ -368,7 +279,8 @@
         }
 
     // Remove this element from pools
-    for (int keyIndex = 0; keyIndex <= keyArr.Count(); keyIndex++)
+    const TInt keyArrCount = iKeyArr.Count();
+    for (TInt keyIndex = 0; keyIndex < keyArrCount; keyIndex++)
         {
         TBool present = GetPoolMap(*poolMap, keyIndex);
 
@@ -377,8 +289,9 @@
             continue;
             }
 
-        RPointerArray<CPcsPoolElement> tmpKeyMap = *(keyArr[keyIndex]);
-        for (int arrayIndex = 0; arrayIndex < tmpKeyMap.Count(); arrayIndex++)
+        const RPointerArray<CPcsPoolElement>& tmpKeyMap = *(iKeyArr[keyIndex]);
+        
+        for (TInt arrayIndex = 0; arrayIndex < tmpKeyMap.Count(); arrayIndex++)
             {
             CPcsPoolElement *element = tmpKeyMap[arrayIndex];
             TInt id = element->GetPsData()->Id();
@@ -386,19 +299,19 @@
                 {
                 data = element->GetPsData();
                 delete element;
-                keyArr[keyIndex]->Remove(arrayIndex);
+                iKeyArr[keyIndex]->Remove(arrayIndex);
                 }
             }
         }
 
     // Remove this element from master pool
-    for (int arrayIndex = 0; arrayIndex < masterPool.Count(); arrayIndex++)
+    for (TInt arrayIndex = 0; arrayIndex < iMasterPool.Count(); arrayIndex++)
         {
-        CPsData *dataElement = masterPool[arrayIndex];
+        CPsData *dataElement = iMasterPool[arrayIndex];
         TInt id = dataElement->Id();
         if (id == aItemId)
             {
-            masterPool.Remove(arrayIndex);
+            iMasterPool.Remove(arrayIndex);
             }
         }
 
@@ -410,51 +323,178 @@
         }
 
     // Clear up cache information
-    cacheInfo.Remove(aItemId);
+    iCacheInfo.Remove(aItemId);
     }
 
 // ---------------------------------------------------------------------
 // CPcsCache::RemoveAllFromCacheL
 // 
 // ---------------------------------------------------------------------
-void CPcsCache::RemoveAllFromCacheL()
+void CPcsCache::RemoveAllFromCache()
     {
-    PRINT ( _L("Enter CPcsCache::RemoveAllFromCacheL") );
+    PRINT ( _L("Enter CPcsCache::RemoveAllFromCache") );
 
-    for (TInt i = 0; i < keyArr.Count(); i++)
+    const TInt keyArrCount = iKeyArr.Count();
+    for ( TInt i = 0 ; i < keyArrCount ; i++ )
         {
-        keyArr[i]->ResetAndDestroy();
-
+        iKeyArr[i]->ResetAndDestroy();
         }
 
-    masterPool.ResetAndDestroy();
-    cacheInfo.Close();
+    iMasterPool.ResetAndDestroy();
+    iCacheInfo.Close();
 
-    PRINT ( _L("End CPcsCache::RemoveAllFromCacheL") );
+    PRINT ( _L("End CPcsCache::RemoveAllFromCache") );
     }
 
 // ---------------------------------------------------------------------
 // CPcsCache::SetPoolMap
 // 
 // ---------------------------------------------------------------------
-void CPcsCache::SetPoolMap(TInt& aPoolMap, TInt arrayIndex)
+void CPcsCache::SetPoolMap(TUint64& aPoolMap, TInt aArrayIndex)
     {
-    TReal val;
-    Math::Pow(val, 2, arrayIndex);
+    __ASSERT_DEBUG( aArrayIndex < 64, User::Panic(_L("CPcsCache"), KErrOverflow ) );
 
-    aPoolMap |= (TInt) val;
+    /* Some platforms do not support 64 bits shift operations.
+     * Split to two 32 bits operations.
+     */
+    
+    TUint32 poolMapH = I64HIGH(aPoolMap);
+    TUint32 poolMapL = I64LOW(aPoolMap);
+    
+    TUint32 valH = 0;
+    TUint32 valL = 0;
+    if (aArrayIndex < 32)
+        {
+        valL = 1 << aArrayIndex;
+        }
+    else
+        {
+        valH = 1 << (aArrayIndex-32);
+        }
+
+    poolMapH |= valH;
+    poolMapL |= valL;
+    
+    aPoolMap = MAKE_TUINT64(poolMapH, poolMapL);
     }
 
 // ---------------------------------------------------------------------
 // CPcsCache::GetPoolMap
 // 
 // ---------------------------------------------------------------------
-TBool CPcsCache::GetPoolMap(TInt& aPoolMap, TInt arrayIndex)
+TBool CPcsCache::GetPoolMap(TUint64& aPoolMap, TInt aArrayIndex)
+    {
+    __ASSERT_DEBUG( aArrayIndex < 64, User::Panic(_L("CPcsCache"), KErrOverflow ) );
+
+    /* Some platforms do not support 64 bits shift operations.
+     * Split to two 32 bits operations.
+     */
+
+    TUint32 poolMapH = I64HIGH(aPoolMap);
+    TUint32 poolMapL = I64LOW(aPoolMap);
+    
+    TUint32 valH = 0;
+    TUint32 valL = 0;
+    if (aArrayIndex < 32)
+        {
+        valL = 1 << aArrayIndex;
+        }
+    else
+        {
+        valH = 1 << (aArrayIndex-32);
+        }
+
+    TBool ret = (poolMapH & valH) || (poolMapL & valL);
+
+    return (ret);
+    }
+
+// ---------------------------------------------------------------------
+// CPcsCache::GetFirstCharsForDataL
+// 
+// ---------------------------------------------------------------------
+void CPcsCache::GetFirstCharsForDataL( const TDesC& aData, RArray<TChar>& aFirstChars ) const
     {
-    TReal val;
-    Math::Pow(val, 2, arrayIndex);
+    // Split the data into words
+    CWords* words = CWords::NewLC(aData);
 
-    return (aPoolMap & (TInt) val);
+    // Find indexing characters for each word
+    for (TInt i = 0; i < words->MdcaCount(); i++)
+        {
+        TPtrC16 word = words->MdcaPoint(i);
+        TBool lastCharIsChinese = EFalse;
+        
+        // If the word contains any Chinese characters, then it is
+        // stored to cache according all the available spellings of
+        // all the Chinese characters
+        if ( iAlgorithm->FindUtilECE()->IsChineseWordIncluded(word) )
+            {
+            const TInt wordLength = word.Length();
+            for (TInt j = 0; j < wordLength; j++)
+                {
+                TText curChar = word[j];
+                RPointerArray<HBufC> spellList;
+                CleanupResetAndDestroyPushL( spellList );
+                if ( iAlgorithm->FindUtilECE()->DoTranslationL(curChar, spellList) )
+                    {
+                    lastCharIsChinese = ETrue;
+                    // Append first char of each spelling
+                    const TInt spellListCount = spellList.Count();
+                    for (TInt k = 0; k < spellListCount; k++)
+                        {
+                        const HBufC* spelling = spellList[k];
+                        aFirstChars.AppendL( (*spelling)[0] );
+                        }
+                    }
+                else
+                    {
+                    if ( lastCharIsChinese )
+                        {
+                        aFirstChars.AppendL( word[j] );
+                        lastCharIsChinese = EFalse;
+                        }
+                    }
+                CleanupStack::PopAndDestroy( &spellList ); // ResetAndDestroy
+                }
+            }
+        
+        // If the first charcter of the word is non-Chinese, then it's stored to the
+        // cache according this first character. Other characters of the word may or
+        // may not be Chinese.
+        if ( !iAlgorithm->FindUtilECE()->IsChineseWordIncluded( word.Left(1) ) )
+            {
+            aFirstChars.AppendL( word[0] );
+            }
+        }
+    CleanupStack::PopAndDestroy(words);
+    }
+
+// ---------------------------------------------------------------------
+// CPcsCache::GetPoolIdsForCharsL
+// 
+// ---------------------------------------------------------------------
+void CPcsCache::GetPoolIdsForCharsL( const RArray<TChar>& aChars, RArray<TInt>& aPoolIds ) const
+    {
+    // There can potentially be two pool IDs for each character. 
+    // Reserve memory for this upfront to prevent unnecessary reallocations.
+    aPoolIds.ReserveL( aChars.Count() * 2 );
+    
+    const TInt charsCount = aChars.Count() ;
+    for ( TInt i = 0 ; i < charsCount ; ++i )
+        {
+        TChar character = aChars[i];
+        TInt itutPoolId = iKeyMap->PoolIdForCharacter( character, EPredictiveItuT );
+        if ( itutPoolId != KErrNotFound )
+            {
+            aPoolIds.AppendL( itutPoolId );
+            }
+        
+        TInt qwertyPoolId = iKeyMap->PoolIdForCharacter( character, EPredictiveQwerty );
+        if ( qwertyPoolId != KErrNotFound )
+            {
+            aPoolIds.AppendL( qwertyPoolId );
+            }
+        }
     }
 
 // ---------------------------------------------------------------------
@@ -472,7 +512,8 @@
 // ---------------------------------------------------------------------
 void CPcsCache::SetDataFields(RArray<TInt>& aDataFields)
     {
-    for (TInt i(0); i < aDataFields.Count(); i++)
+    const TInt dataFieldsCount = aDataFields.Count();
+    for (TInt i(0); i < dataFieldsCount; i++)
         {
         iDataFields.Append(aDataFields[i]);
         }
@@ -484,7 +525,8 @@
 // ---------------------------------------------------------------------
 void CPcsCache::GetDataFields(RArray<TInt>& aDataFields)
     {
-    for (TInt i(0); i < iDataFields.Count(); i++)
+    const TInt dataFieldsCount = iDataFields.Count();
+    for (TInt i(0); i < dataFieldsCount; i++)
         {
         aDataFields.Append(iDataFields[i]);
         }
@@ -535,8 +577,8 @@
     PRINT ( _L("Enter CPcsCache::SetSortOrder") );
 
     iSortOrder.Reset();
-
-    for (TInt i(0); i < aSortOrder.Count(); i++)
+    const TInt sortOrderCount = aSortOrder.Count();
+    for (TInt i(0); i < sortOrderCount; i++)
         {
         iSortOrder.Append(aSortOrder[i]);
         }
@@ -553,8 +595,8 @@
 void CPcsCache::GetSortOrder(RArray<TInt>& aSortOrder)
     {
     aSortOrder.Reset();
-
-    for (TInt i(0); i < iSortOrder.Count(); i++)
+    const TInt sortOrderCount =  iSortOrder.Count();
+    for (TInt i(0); i < sortOrderCount; i++)
         {
         aSortOrder.Append(iSortOrder[i]);
         }
@@ -567,8 +609,8 @@
 void CPcsCache::GetIndexOrder(RArray<TInt>& aIndexOrder)
     {
     aIndexOrder.Reset();
-
-    for (TInt i(0); i < iIndexOrder.Count(); i++)
+    const TInt indexOrderCount = iIndexOrder.Count();
+    for (TInt i(0); i < indexOrderCount; i++)
         {
         aIndexOrder.Append(iIndexOrder[i]);
         }
@@ -582,9 +624,11 @@
     {
     iIndexOrder.Reset();
 
-    for (int i = 0; i < iSortOrder.Count(); i++)
+    const TInt sortOrderCount = iSortOrder.Count();
+    const TInt dataFieldsCount = iDataFields.Count(); 
+    for (TInt i = 0; i < sortOrderCount; i++)
         {
-        for (int j = 0; j < iDataFields.Count(); j++)
+        for (TInt j = 0; j <dataFieldsCount; j++)
             {
             if (iSortOrder[i] == iDataFields[j])
                 {
@@ -601,24 +645,64 @@
 // ---------------------------------------------------------------------
 void CPcsCache::ResortdataInPoolsL()
     {
-    // copy masterPool data into masterPoolBackup
-    for (TInt i = 0; i < masterPool.Count(); i++ )
+    // copy iMasterPool data into iMasterPoolBackup
+    const TInt masterPoolCount = iMasterPool.Count();
+    for (TInt i = 0; i < masterPoolCount; i++ )
         {
-        masterPoolBackup.Append( masterPool[i] );
+        iMasterPoolBackup.Append( iMasterPool[i] );
         }
     //Now reset the key array
-    for (TInt i = 0; i < keyArr.Count(); i++ )
+    const TInt keyArrCount = iKeyArr.Count(); 
+    for (TInt i = 0; i <keyArrCount; i++ )
         {
-        keyArr[i]->ResetAndDestroy();
+        iKeyArr[i]->ResetAndDestroy();
         }
-    masterPool.Reset();
-    cacheInfo.Close();
-    //now add data again from the masterPoolBackup
-    for (TInt i = 0; i < masterPoolBackup.Count(); i++ )
+    iMasterPool.Reset();
+    iCacheInfo.Close();
+    //now add data again from the iMasterPoolBackup
+    const TInt masterPoolBackupCount = iMasterPoolBackup.Count();
+    for (TInt i = 0; i < masterPoolBackupCount; i++ )
         {
-        CPsData* temp = static_cast<CPsData*>(masterPoolBackup[i]);
+        CPsData* temp = iMasterPoolBackup[i];
         AddToCacheL( *temp );
         }
-    masterPoolBackup.Reset();
-    } 
+    iMasterPoolBackup.Reset();
+    }
+
+// ---------------------------------------------------------------------
+// CPcsCache::GetFirstNameIndex
+// 
+// ---------------------------------------------------------------------
+TInt CPcsCache::GetFirstNameIndex() const
+    {
+    TInt fnIndex = KErrNotFound;
+    const TInt dataFieldsCount = iDataFields.Count();
+    for ( TInt i = 0 ; i < dataFieldsCount && fnIndex == KErrNotFound ; ++i )
+        {
+        if ( iDataFields[i] == R_VPBK_FIELD_TYPE_FIRSTNAME )
+            {
+            fnIndex = i;
+            }
+        }
+    return fnIndex;
+    }
+
+// ---------------------------------------------------------------------
+// CPcsCache::GetLastNameIndex
+// 
+// ---------------------------------------------------------------------
+TInt CPcsCache::GetLastNameIndex() const
+    {
+    TInt lnIndex = KErrNotFound;
+    const TInt dataFieldsCount = iDataFields.Count();
+    for ( TInt i = 0 ; i < dataFieldsCount && lnIndex == KErrNotFound ; ++i )
+        {
+        if ( iDataFields[i] == R_VPBK_FIELD_TYPE_LASTNAME )
+            {
+            lnIndex = i;
+            }
+        }
+    return lnIndex;
+    }
+
 // End of file
--- a/predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsKeyMap.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsKeyMap.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -23,9 +23,37 @@
 #include "FindUtilChineseECE.h"
 #include "CPcsDebug.h"
 #include "CPcsKeyMap.h"
+#include "CPsQueryItem.h"
+#include <PtiEngine.h>
+#include <PtiKeyMapData.h>
 #include <bldvariant.hrh>
 #include <AknFepInternalCRKeys.h>
 
+
+// Unnamed namespace for local definitions
+namespace {
+
+#ifdef _DEBUG
+    enum TPanicCode
+    {
+        EPanicPreCond_MultipleSingleCharMatching = 1,
+        EPanicPreCond_MultipleUIPriorityMatching = 2,
+        EPanicPreCond_MultipleEnglishPriorityMatching = 3,
+        EPanicPreCond_MultipleOthersPriorityMatching = 4,
+        EPanic_OverflowInPoolIndex = 5,
+        EPanic_InvalidKeyboardType = 6
+   };
+
+    void Panic(TInt aReason)
+    {
+        _LIT(KPanicText, "CPcsKeyMap");
+        User::Panic(KPanicText, aReason);
+    }
+#endif // DEBUG
+
+} // namespace
+
+
 // ============================== MEMBER FUNCTIONS ============================
 
 // ----------------------------------------------------------------------------
@@ -61,11 +89,14 @@
 void CPcsKeyMap::ConstructL(CPcsAlgorithm2* aAlgorithm)
     {
     iLanguageNotSupported.Append(ELangJapanese);
+    iLanguageNotSupported.Append(ELangKorean);
 
     iAlgorithm = aAlgorithm;
     iPtiEngine = CPtiEngine::NewL();
-	
+
+    SetupKeyboardTypesL();
     ConstructKeymapL();
+    SetSpaceAndZeroOnSameKey();
     }
 
 // ----------------------------------------------------------------------------
@@ -74,17 +105,18 @@
 // ----------------------------------------------------------------------------
 void CPcsKeyMap::ReconstructKeymapL()
     {
-    TLanguage lang = iAlgorithm->FindUtilECE()->CurrentInputLanguage();
-        if (lang == ELangPrcChinese || !IsLanguageSupportedL(lang))
-            lang = ELangEnglish;
-
-    TInt keyboardType = CurrentKeyBoardTypeL();
-    
     // Clear the keymap data array first when reconstruct the keymap.
     ResetKeyMap();
     
-    // Add new keymap to the keymap data array according the current writing language.
-    AddKeyMapforConcreteKeyboardL( keyboardType, lang );
+    // Always add English mappings first
+    AddKeyMapforConcreteKeyboardL( ELangEnglish );
+    
+    // Then append the mappings of the current input language
+    TLanguage lang = iAlgorithm->FindUtilECE()->CurrentInputLanguage();
+    if ( lang != ELangEnglish && IsLanguageSupportedL(lang) )
+        {
+        AddKeyMapforConcreteKeyboardL( lang );
+        }
     }
 
 // ----------------------------------------------------------------------------
@@ -93,106 +125,107 @@
 // ----------------------------------------------------------------------------
 void CPcsKeyMap::ConstructKeymapL()
     {
+    ConstructConcreteKeyMapL();
+    
+    // Always add English mappings first
+    AddKeyMapforConcreteKeyboardL( ELangEnglish );
+    
+    // Then append the mappings of the current input language
     TLanguage lang = iAlgorithm->FindUtilECE()->CurrentInputLanguage();
-    if (lang == ELangPrcChinese || !IsLanguageSupportedL(lang))
-        lang = ELangEnglish;
-
-    TInt keyboardType = CurrentKeyBoardTypeL();
-    
-    ConstructConcreteKeyMapL( keyboardType, lang );
+    if ( lang != ELangEnglish && IsLanguageSupportedL(lang) )
+        {
+        AddKeyMapforConcreteKeyboardL( lang );
+        }
     
     PRINT ( _L("----------------------------------------"));
-    
     }
 
 // ----------------------------------------------------------------------------
-// CPcsKeyMap::CurrentKeyBoardTypeL
-// 
+// CPcsKeyMap::SetupKeyboardTypesL
+// Initialise the keyboard type variables
 // ----------------------------------------------------------------------------
-TInt CPcsKeyMap::CurrentKeyBoardTypeL()
+void CPcsKeyMap::SetupKeyboardTypesL()
     {
-    TInt keyBoardType = EPtiKeyboardNone;
-    
-#ifdef RD_INTELLIGENT_TEXT_INPUT
-    
     TInt physicalKeyboard = 0;
     CRepository* aknFepRepository = CRepository::NewL( KCRUidAknFep );
-    // Get all the physical keyboards which are connected to the phone currently.
     aknFepRepository->Get( KAknFepPhysicalKeyboards, physicalKeyboard );
     delete aknFepRepository;
-    
-    
-    PRINT1 ( _L("CPcsKeyMap::CurrentKeyBoardTypeL: Physical keyboard support flag = 0x%02X"), physicalKeyboard );
+
+    PRINT1 ( _L("CPcsKeyMap::ConstructL: Physical keyboard support flag = 0x%02X"), physicalKeyboard );
 
     // Constants follow the definition of KAknFepPhysicalKeyboards
-    const TInt ptiKeyboard12Key = 0x01;         // Default
-    // const TInt ptiKeyboardQwerty4x12 = 0x02;    // Not used at the moment
-    const TInt ptiKeyboardQwerty4x10 = 0x04;
-    // const TInt ptiKeyboardQwerty3x11 = 0x08;    // Not used at the moment
-    const TInt ptiKeyboardHalfQwerty = 0x10;
-    // const TInt ptiKeyboardCustomQwerty = 0x20;  // Not used at the moment
+    const TInt KPtiKeyboard12Key = 0x01;
+    const TInt KPtiKeyboardQwerty4x12 = 0x02;
+    const TInt KPtiKeyboardQwerty4x10 = 0x04;
+    const TInt KPtiKeyboardQwerty3x11 = 0x08;
+    const TInt KPtiKeyboardHalfQwerty = 0x10;
+    const TInt KPtiKeyboardCustomQwerty = 0x20; 
 
-    // If there are more than 1 keyboards on HW, The priority from high to low for 
-    // selecting keyboard is EPtiKeyboard12Key, EPtiKeyboardHalfQwerty, EPtiKeyboardQwerty4x10  
-    if ( physicalKeyboard & ptiKeyboard12Key )
+    // Setup ITU-T mode first.
+    // Use always 12-key mode since all the supported devices should have at least
+    // virtual ITU-T available.
+    iItutKeyboardType = EPtiKeyboard12Key;
+    // TODO: ITU-T type could be set to "none" if device does not have either
+    // virtual keypad or hardware ITU-T available. This could be decided according
+    // some cenrep value, feature flag, device model, or platform version.
+    
+    // Then setup QWERTY mode. On real-life devices there should never
+    // be more than one QWERTY keyboard available but on emulator there can be several.
+    // Use the first one found in the following precedence
+    if ( physicalKeyboard & KPtiKeyboardQwerty3x11 )
         {
-        keyBoardType = EPtiKeyboard12Key;
+        iQwertyKeyboardType = EPtiKeyboardQwerty3x11;
         }
-    else if ( physicalKeyboard & ptiKeyboardHalfQwerty )
+    else if ( physicalKeyboard & KPtiKeyboardQwerty4x10 )
         {
-        keyBoardType = EPtiKeyboardHalfQwerty;
+        iQwertyKeyboardType = EPtiKeyboardQwerty4x10;
+        }
+    else if ( physicalKeyboard & KPtiKeyboardQwerty4x12 )
+        {
+        iQwertyKeyboardType = EPtiKeyboardQwerty4x12;
         }
-    else if ( physicalKeyboard & ptiKeyboardQwerty4x10 )
+    else if ( physicalKeyboard & KPtiKeyboardCustomQwerty )
         {
-        keyBoardType = EPtiKeyboardQwerty4x10;
+        iQwertyKeyboardType = EPtiKeyboardCustomQwerty;
+        }
+    else if ( physicalKeyboard & KPtiKeyboardHalfQwerty )
+        {
+        iQwertyKeyboardType = EPtiKeyboardHalfQwerty;
         }
     else
-#endif
         {
-        keyBoardType = EPtiKeyboard12Key;
+        iQwertyKeyboardType = EPtiKeyboardNone;
         }
-    return keyBoardType;
+    
+    // Decide, which keyboard is used for the "default" matching mode.
+    // If there is physical ITU-T available, or there's no physical QWERTY,
+    // then ITU-T is default.
+    iItutIsDefault = (physicalKeyboard & KPtiKeyboard12Key) || 
+                     (iQwertyKeyboardType == EPtiKeyboardNone);
+    
+    PRINT1 ( _L("CPcsKeyMap::ConstructL: ITU-T Keyboard chosen for Predictive Search = %d"), iItutKeyboardType );
+    PRINT1 ( _L("CPcsKeyMap::ConstructL: QWERTY Keyboard chosen for Predictive Search = %d"), iQwertyKeyboardType );
     }
 
+
 // ----------------------------------------------------------------------------
 // CPcsKeyMap::ConstructConcreteKeyMapL
 // 
 // ----------------------------------------------------------------------------
-void CPcsKeyMap::ConstructConcreteKeyMapL( TInt aKeyboardType, TLanguage aLanguage )
+void CPcsKeyMap::ConstructConcreteKeyMapL()
     {
-    switch ( aKeyboardType )
+    if ( iItutKeyboardType != EPtiKeyboardNone )
         {
-        case EPtiKeyboard12Key:
-            {
-            // Construct for Itut keyboard by default
-            PRINT ( _L("CPcsKeyMap::ConstructConcreteKeyMapL: Construct keymap for ContructForItutKeyboardL"));
-            
-            ContructForItutKeyboardL( aLanguage );
-            break;
-            }
-        case EPtiKeyboardHalfQwerty:
-            {
-            // Construct for Half Qwerty keyboard
-            PRINT ( _L("CPcsKeyMap::ConstructConcreteKeyMapL: Construct keymap for ContructForHalfQwertyKeyboardL"));
-            
-            ContructForHalfQwertyKeyboardL( aLanguage );
-            break;
-            }
-        case EPtiKeyboardQwerty4x10:
-            {
-            // Construct for 4x10 Qwerty keyboard
-            PRINT ( _L("CPcsKeyMap::ConstructConcreteKeyMapL: Construct keymap for ContructFor4x10QwertyKeyboardL"));
-            
-            ContructFor4x10QwertyKeyboardL( aLanguage );
-            break;
-            }
-        default:
-            {
-            // Construct for Itut keyboard
-            PRINT ( _L("CPcsKeyMap::ConstructConcreteKeyMapL: Construct keymap for ContructForItutKeyboardL"));
-            
-            ContructForItutKeyboardL( aLanguage );
-            }
+        // Construct for Itut keyboard by default
+        PRINT ( _L("CPcsKeyMap::ConstructConcreteKeyMapL: Construct keymap for ITU-T"));
+        ConstructForItutKeyboardL();
+        }
+    if ( iQwertyKeyboardType != EPtiKeyboardNone )
+        {
+        // Construct for any QWERTY keyboard
+        PRINT1 ( _L("CPcsKeyMap::ConstructConcreteKeyMapL: Construct keymap for QWERTY keyboard type %d"), 
+                 iQwertyKeyboardType );
+        ConstructForQwertyKeyboardL( iQwertyKeyboardType );
         }
     }
 
@@ -200,49 +233,16 @@
 // CPcsKeyMap::AddKeyMapforConcreteKeyboardL
 // 
 // ----------------------------------------------------------------------------
-void CPcsKeyMap::AddKeyMapforConcreteKeyboardL( TInt aKeyboardType, TLanguage aLanguage )
+void CPcsKeyMap::AddKeyMapforConcreteKeyboardL( TLanguage aLanguage )
     {
-    // If it's TW or HK variant, the key map for English also needs add to current key map.
-    TBool needAddEnglishKeyMap = ( aLanguage == ELangTaiwanChinese || aLanguage == ELangHongKongChinese );
-    
-    // Add the keymap for current writing language.
-    switch ( aKeyboardType )
+    if ( iItutKeyboardType != EPtiKeyboardNone )
         {
-        case EPtiKeyboard12Key:
-            {
-            AddKeyMapforItutL( aLanguage );
-            if ( needAddEnglishKeyMap )
-                {
-                AddKeyMapforItutL( ELangEnglish );
-                }
-            break;
-            }
-        case EPtiKeyboardHalfQwerty:
-            {
-            AddKeyMapforHalfQwertyKeyboardL( aLanguage );
-            if ( needAddEnglishKeyMap )
-                {
-                AddKeyMapforHalfQwertyKeyboardL( ELangEnglish );
-                }
-            break;
-            }
-        case EPtiKeyboardQwerty4x10:
-            {
-            AddKeyMapfor4x10QwertyKeyboardL( aLanguage );
-            if ( needAddEnglishKeyMap )
-                {
-                AddKeyMapfor4x10QwertyKeyboardL( ELangEnglish );
-                }
-            break;
-            }
-        default:
-            {
-            AddKeyMapforItutL( aLanguage );
-            if ( needAddEnglishKeyMap )
-                {
-                AddKeyMapforItutL( ELangEnglish );
-                }
-            }
+        AddKeyMapforItutL( aLanguage );
+        }
+    
+    if ( iQwertyKeyboardType != EPtiKeyboardNone )
+        {
+        AddKeyMapForQwertyKeyboardL( aLanguage, iQwertyKeyboardType );
         }
     }
 
@@ -252,12 +252,18 @@
 // ----------------------------------------------------------------------------
 void CPcsKeyMap::ResetKeyMap()
     {
-    for (TInt i = 0; i < iAllKeyMappingsPtrArr.Count(); i++)
+    const TInt ItutKeyMappingsCount = iItutKeyMappings.Count();
+    const TInt qwertyKeyMappingsCount = iQwertyKeyMappings.Count();
+    for (TInt i = 0; i < ItutKeyMappingsCount; i++)
         {
-        iAllKeyMappingsPtrArr[i]->iKeyMappingArray.Close();
+        iItutKeyMappings[i]->iKeyMappingArray.Reset();
         }
+    for (TInt i = 0; i < qwertyKeyMappingsCount; i++)
+        {
+        iQwertyKeyMappings[i]->iKeyMappingArray.Reset();
+        }
+    }
 
-    }
 // ----------------------------------------------------------------------------
 // CPcsKeyMap::~CPcsKeyMap
 // Destructor
@@ -268,137 +274,162 @@
 
     // Cleanup local arrays
     iLanguageNotSupported.Reset();
-    iAllKeyMappingsPtrArr.ResetAndDestroy();
-    iKeysForPoolFormation.Close();
+    iItutKeyMappings.ResetAndDestroy();
+    iItutKeys.Close();
+    iQwertyKeyMappings.ResetAndDestroy();
+    iQwertyKeys.Close();
     delete iPtiEngine;
     }
 
 // ----------------------------------------------------------------------------
-// CPcsKeyMap::GetNumericKeyStringL
-// 
+// CPcsKeyMap::GetMixedKeyStringForQueryL
+// aDestStr will have the length as the number of items in aSrcQuery.
 // ----------------------------------------------------------------------------
-void CPcsKeyMap::GetNumericKeyString(const TDesC& aSrcStr, TDes& aDestStr)
-    {
-    for (int i = 0; i < aSrcStr.Length(); i++)
+void CPcsKeyMap::GetMixedKeyStringForQueryL(
+        CPsQuery& aSrcQuery, TDes& aDestStr) const
+{
+    PRINT ( _L("Enter CPcsKeyMap::GetMixedKeyStringForQueryL") ); 
+
+    GetMixedKeyStringForDataL( aSrcQuery, aSrcQuery.QueryAsStringLC(), aDestStr );
+    CleanupStack::PopAndDestroy(); //result of QueryAsStringLC
+
+    PRINT ( _L("End CPcsKeyMap::GetMixedKeyStringForQueryL") );
+}
+
+// ----------------------------------------------------------------------------
+// CPcsKeyMap::GetMixedKeyStringForDataL
+// aDestStr will have the same length as aSrcData. aSrcQuery can be shorter.
+// ----------------------------------------------------------------------------
+void CPcsKeyMap::GetMixedKeyStringForDataL(
+        CPsQuery& aSrcQuery, const TDesC& aSrcData, TDes& aDestStr) const
+{
+    PRINT ( _L("Enter CPcsKeyMap::GetMixedKeyStringForDataL") );
+
+    const TInt srcDataLength = aSrcData.Length(); 
+    for ( TInt i = 0; i < srcDataLength; ++i )
         {
-        TInt index = KeyForCharacter(aSrcStr[i]);
-
-        // If a character is not mapped to numeric key append the character
-        if (index == -1)
+        TChar character( aSrcData[i] );
+        character.LowerCase();
+        if ( i < aSrcQuery.Count() )
             {
-            aDestStr.Append(aSrcStr[i]);
+            CPsQueryItem& currentItem = aSrcQuery.GetItemAtL(i);
+            TKeyboardModes curMode = ResolveKeyboardMode( currentItem.Mode() );
+            TPtiKey key = KeyForCharacter( aSrcData[i], curMode );
+            // If a character is not mapped to any key or it's entered in non-predictive mode,
+            // then append the character as exact.
+            if ( EPtiKeyNone == key )
+                {
+                aDestStr.Append( character );
+                }
+            else
+                {
+                aDestStr.Append( DefaultCharForKey(key, curMode) );
+                }
             }
         else
             {
-            aDestStr.Append(index);
+            // characters over query length are taken as exact
+            aDestStr.Append( character );
             }
         }
-    }
+
+    PRINT1 ( _L("CPcsKeyMap::GetMixedKeyStringForDataL: Return string: \"%S\""),
+             &aDestStr );
+
+    PRINT ( _L("End CPcsKeyMap::GetMixedKeyStringForDataL") );
+}
 
 // ----------------------------------------------------------------------------
 // CPcsKeyMap::KeyForCharacter
 // 
 // ----------------------------------------------------------------------------
-TInt CPcsKeyMap::KeyForCharacter(const TChar& aChar)
+TPtiKey CPcsKeyMap::KeyForCharacter(TText aChar, TKeyboardModes aKbMode) const
     {
+    const RPointerArray<TKeyMappingData>* keyMappings = KeyMappings( aKbMode );
+    
+    // Don't return any key in the exact mode
+    if ( !keyMappings )
+        {
+        return EPtiKeyNone;
+        }
+    
     TInt index = KErrNotFound;
 
-    TChar lChar = User::LowerCase(aChar);
+    TText lChar = User::LowerCase(aChar);
 
-    TInt count = iAllKeyMappingsPtrArr.Count() - 1;
+    const TInt count = keyMappings->Count() - 1;
 
     for (TInt i = 0; i < count; i++)
         {
-        index = iAllKeyMappingsPtrArr[i]->iKeyMappingArray.Find(lChar);
+        index = (*keyMappings)[i]->iKeyMappingArray.Find(lChar);
         if (index != KErrNotFound)
             {
-            return (TInt) iAllKeyMappingsPtrArr[i]->key;
+            return (*keyMappings)[i]->iKey;
             }
         }
 
-    return index;
+    return EPtiKeyNone;
     }
+
 // ----------------------------------------------------------------------------
-// CPcsKeyMap::ContructForHalfQwertyKeyboardL
+// CPcsKeyMap::AddKeyMapForQwertyKeyboardL
 // 
 // ----------------------------------------------------------------------------
-void CPcsKeyMap::ContructForHalfQwertyKeyboardL(TLanguage aLanguage)
+void CPcsKeyMap::AddKeyMapForQwertyKeyboardL(TLanguage aLanguage, TPtiKeyboardType aKbType)
     {
-#ifdef RD_INTELLIGENT_TEXT_INPUT    
-
-    iKeysForPoolFormation.Append(EPtiKeyQwertyQ);
-    iKeysForPoolFormation.Append(EPtiKeyQwertyE);
-    iKeysForPoolFormation.Append(EPtiKeyQwertyT);
-    iKeysForPoolFormation.Append(EPtiKeyQwertyU);
-    iKeysForPoolFormation.Append(EPtiKeyQwertyO);
-    iKeysForPoolFormation.Append(EPtiKeyQwertyA);
-    iKeysForPoolFormation.Append(EPtiKeyQwertyD);
-    iKeysForPoolFormation.Append(EPtiKeyQwertyG);
-    iKeysForPoolFormation.Append(EPtiKeyQwertyJ);
-    iKeysForPoolFormation.Append(EPtiKeyQwertyL);
-    iKeysForPoolFormation.Append(EPtiKeyQwertyZ);
-    iKeysForPoolFormation.Append(EPtiKeyQwertyC);
-    iKeysForPoolFormation.Append(EPtiKeyQwertyB);
-    iKeysForPoolFormation.Append(EPtiKeyQwertyM);
-    iKeysForPoolFormation.Append(EPtiKeyQwerty0);
-    // one additional pool for special characters not mapped too any keys. 
-    // This should always be the last one in the arrary
-    iKeysForPoolFormation.Append(EPtiKeyNone);
+#ifdef RD_INTELLIGENT_TEXT_INPUT
+    iPtiEngine->ActivateLanguageL(aLanguage);
+    iPtiEngine->SetKeyboardType(aKbType);
 
-    // Now add the keymap arrays to hold the keymap data
-    for (TInt i = 0; i < iKeysForPoolFormation.Count(); i++)
-        {
-        TKeyMappingData *keyData = new (ELeave) TKeyMappingData;
-        keyData->key = iKeysForPoolFormation[i];
-        iAllKeyMappingsPtrArr.Append(keyData);
-        }
-    //  Add the keymap for current language
-    AddKeyMapforHalfQwertyKeyboardL(aLanguage);
-
-    // If it's TW or HK variant, add the keymap for English language
-    if (aLanguage == ELangTaiwanChinese || aLanguage == ELangHongKongChinese)
-        {
-        AddKeyMapforHalfQwertyKeyboardL(ELangEnglish);
-        }
-
-    PRINT ( _L("----------------------------------------"));
-#endif // RD_INTELLIGENT_TEXT_INPUT
-    }
-// ----------------------------------------------------------------------------
-// CPcsKeyMap::AddKeyMapforHalfQwertyKeyboardL
-// 
-// ----------------------------------------------------------------------------
-void CPcsKeyMap::AddKeyMapforHalfQwertyKeyboardL(TLanguage aLanguage)
-    {
-#ifdef RD_INTELLIGENT_TEXT_INPUT     	
     // Make a language object based on current language
-    CPtiCoreLanguage* iCoreLanguage = static_cast<CPtiCoreLanguage*>(iPtiEngine->GetLanguage(  aLanguage));
+    CPtiCoreLanguage* coreLanguage = static_cast<CPtiCoreLanguage*>(iPtiEngine->GetLanguage( aLanguage ));
 
     //Perfrom the key mappings only if the corelanguage is available
-    if (iCoreLanguage)
+    if (coreLanguage)
         {
         // Get the keyboard mappings for the language
-        CPtiHalfQwertyKeyMappings* ptiKeyMappings = static_cast<CPtiHalfQwertyKeyMappings*> 
-                (iCoreLanguage->GetHalfQwertyKeymappings());
+        CPtiKeyMapData* ptiKeyMapData = coreLanguage->RawKeyMapData();
 
-        iPtiEngine->ActivateLanguageL(aLanguage, EPtiEngineHalfQwerty);
-        iPtiEngine->SetKeyboardType(EPtiKeyboardHalfQwerty);
-
-        for (TInt i = 0; i < iAllKeyMappingsPtrArr.Count() - 1; i++)
+        const TInt qwertyKeyMappingsCount = iQwertyKeyMappings.Count() - 1;
+        for (TInt i = 0; i < qwertyKeyMappingsCount; i++)
             {
-            AddDataForHalfQwertyKeyboardL( ptiKeyMappings, iKeysForPoolFormation[i], *(iAllKeyMappingsPtrArr[i]));
+            AddDataForQwertyKeyboardL( ptiKeyMapData, aKbType, 
+                    iQwertyKeys[i], *(iQwertyKeyMappings[i]) );
             }
         }
 #endif // RD_INTELLIGENT_TEXT_INPUT        
     }
 
 // ----------------------------------------------------------------------------
-// CPcsKeyMap::AddDataForHalfQwertyKeyboardL
+// CPcsKeyMap::ConstructForQwertyKeyboardL
+// Destructor
+// ----------------------------------------------------------------------------
+void CPcsKeyMap::ConstructForQwertyKeyboardL(TPtiKeyboardType aKbType)
+    {
+#ifdef RD_INTELLIGENT_TEXT_INPUT
+    CreateKeyListFromKeyBindingTable( iQwertyKeys, aKbType );
+
+    // Now add the keymap arrays to hold the keymap data
+    const TInt qwertyKeysCount = iQwertyKeys.Count();
+    for (TInt i = 0; i < qwertyKeysCount; i++)
+        {
+        TKeyMappingData* keyData = new (ELeave) TKeyMappingData;
+        keyData->iKey = iQwertyKeys[i];
+        iQwertyKeyMappings.Append(keyData);
+        }
+
+    PRINT ( _L("----------------------------------------"));
+#endif //RD_INTELLIGENT_TEXT_INPUT
+    }
+
+// ----------------------------------------------------------------------------
+// CPcsKeyMap::AddDataForQwertyKeyboardL
 // 
 // ----------------------------------------------------------------------------
-void CPcsKeyMap::AddDataForHalfQwertyKeyboardL( CPtiHalfQwertyKeyMappings* aPtiKeyMappings, 
-                                               TPtiKey aKey,  
-                                               TKeyMappingData& aKeyDataList)
+void CPcsKeyMap::AddDataForQwertyKeyboardL(CPtiKeyMapData* aPtiKeyMapData,
+                                           TPtiKeyboardType aKbType,
+                                           TPtiKey aKey,
+                                           TKeyMappingData& aKeyDataList)
     {
 #ifdef RD_INTELLIGENT_TEXT_INPUT     	
     TPtiTextCase caseArray[] =
@@ -411,171 +442,15 @@
         EPtiCaseChrUpper
         };
     
-    TBuf<50> iResult;
-    for (int i = 0; i < sizeof(caseArray) / sizeof(TPtiTextCase); i++)
+    for (TInt i = 0; i < sizeof(caseArray) / sizeof(TPtiTextCase); i++)
         {
-        iResult.Zero();
-        aPtiKeyMappings->GetDataForKey(aKey, iResult, caseArray[i]);
-
-        for (int j = 0; j < iResult.Length(); j++)
-            aKeyDataList.iKeyMappingArray.Append(iResult[j]);
-
-        PRINT2 ( _L("CPcsKeyMap: Mapping for Key %c = %S"), aKey,&iResult)
-        }
-#endif // RD_INTELLIGENT_TEXT_INPUT        
-    }
-
-// ----------------------------------------------------------------------------
-// CPcsKeyMap::ContructFor4x10QwertyKeyboardL
-// Destructor
-// ----------------------------------------------------------------------------
-void CPcsKeyMap::ContructFor4x10QwertyKeyboardL(TLanguage aLanguage)
-    {
-#ifdef RD_INTELLIGENT_TEXT_INPUT     
-// The special 4x10 Qwerty keyboard for Sonja.
-    iKeysForPoolFormation.Append( EPtiKeyQwertyA );
-    iKeysForPoolFormation.Append( EPtiKeyQwerty8 );
-    iKeysForPoolFormation.Append( EPtiKeyQwertyC );
-    iKeysForPoolFormation.Append( EPtiKeyQwertyD );
-    iKeysForPoolFormation.Append( EPtiKeyQwertyE );
-    iKeysForPoolFormation.Append( EPtiKeyQwerty4 );
-    iKeysForPoolFormation.Append( EPtiKeyQwerty5 );
-    iKeysForPoolFormation.Append( EPtiKeyQwerty6 );
-    iKeysForPoolFormation.Append( EPtiKeyQwertyI );
-    iKeysForPoolFormation.Append( EPtiKeyQwertyHash ); // Could have been EPtiKeyQwertyJ, EPtiKeyHash
-    iKeysForPoolFormation.Append( EPtiKeyQwertyK );
-    iKeysForPoolFormation.Append( EPtiKeyQwertyL );
-    iKeysForPoolFormation.Append( EPtiKeyQwerty0 );
-    iKeysForPoolFormation.Append( EPtiKeyQwerty9 );
-    iKeysForPoolFormation.Append( EPtiKeyQwertyO );
-    iKeysForPoolFormation.Append( EPtiKeyQwertyP );
-    iKeysForPoolFormation.Append( EPtiKeyQwertyQ );
-    iKeysForPoolFormation.Append( EPtiKeyQwerty1 );
-    iKeysForPoolFormation.Append( EPtiKeyQwertyS );
-    iKeysForPoolFormation.Append( EPtiKeyQwerty2 );
-    iKeysForPoolFormation.Append( EPtiKeyStar );    // Could have been EPtiKeyQwertyU
-    iKeysForPoolFormation.Append( EPtiKeyQwertyV );    // Could have been EPtiKeyQwerty7
-    iKeysForPoolFormation.Append( EPtiKeyQwertyW );
-    iKeysForPoolFormation.Append( EPtiKeyQwertyX );
-    iKeysForPoolFormation.Append( EPtiKeyQwerty3 );
-    iKeysForPoolFormation.Append( EPtiKeyQwertyZ );
-    
-    // one additional pool for special characters not mapped too any keys. 
-    // This should always be the last one in the arrary
-    iKeysForPoolFormation.Append(EPtiKeyNone);
-
-    // Now add the keymap arrays to hold the keymap data
-    for (TInt i = 0; i < iKeysForPoolFormation.Count(); i++)
-        {
-        TKeyMappingData *keyData = new (ELeave) TKeyMappingData;
-        keyData->key = iKeysForPoolFormation[i];
-        iAllKeyMappingsPtrArr.Append(keyData);
-        }
-
-    //  Add the keymap for current language
-    AddKeyMapfor4x10QwertyKeyboardL(aLanguage);
-
-    // If it's TW or HK variant, add the keymap for English language
-    if (aLanguage == ELangTaiwanChinese || aLanguage == ELangHongKongChinese)
-        {
-        AddKeyMapfor4x10QwertyKeyboardL(ELangEnglish);
-        }
-
-    PRINT ( _L("----------------------------------------"));
-#endif //RD_INTELLIGENT_TEXT_INPUT
-    }
+        TPtrC result = aPtiKeyMapData->DataForKey(aKbType, aKey, caseArray[i]);
 
-// ----------------------------------------------------------------------------
-// CPcsKeyMap::AddKeyMapfor4x10QwertyKeyboardL
-// 
-// ----------------------------------------------------------------------------
-void CPcsKeyMap::AddKeyMapfor4x10QwertyKeyboardL(TLanguage aLanguage)
-    {
-#ifdef RD_INTELLIGENT_TEXT_INPUT     	
-    // Make a language object based on current language
-    CPtiCoreLanguage* iCoreLanguage = static_cast<CPtiCoreLanguage*>(iPtiEngine->GetLanguage(aLanguage));
-
-    //Perfrom the key mappings only if the corelanguage is available
-    if (iCoreLanguage)
-        {
-        // Get the keyboard mappings for the language
-        CPtiQwertyKeyMappings* iPtiKeyMappings = static_cast<CPtiQwertyKeyMappings *> 
-                (iCoreLanguage->GetQwertyKeymappings());
-        iPtiEngine->SetKeyboardType(EPtiKeyboardQwerty4x10);
-
-        for (TInt i = 0; i < iAllKeyMappingsPtrArr.Count() - 1; i++)
-            {
-            AddDataFor4x10QwertyKeyboardL(iPtiKeyMappings, iKeysForPoolFormation[i], *(iAllKeyMappingsPtrArr[i]));
-            }
-
-#ifdef HACK_FOR_E72_J_KEY
-        AddDataFor4x10QwertyKeyboardE72HackL();
-#endif // HACK_FOR_E72_J_KEY
-        }
-#endif //RD_INTELLIGENT_TEXT_INPUT        
-
-    }
-
-#ifdef HACK_FOR_E72_J_KEY
-// ----------------------------------------------------------------------------
-// CPcsKeyMap::AddDataFor4x10QwertyKeyboardE72HackL
-//
-// Key code for J/# key in Sonja is EPtiKeyQwertyHash (127).
-// No returned character code ('J', 'j', '#') has 127 as ASCII value.
-// In this case we must add key to the list of characters for the pool.
-// ----------------------------------------------------------------------------
-void CPcsKeyMap::AddDataFor4x10QwertyKeyboardE72HackL()
-    {
-#ifdef RD_INTELLIGENT_TEXT_INPUT    
-    PRINT ( _L("Enter CPcsKeyMap::AddDataFor4x10QwertyKeyboardE72HackL") );
+        const TInt resultLength = result.Length(); 
+        for (TInt j = 0; j < resultLength; j++)
+            aKeyDataList.iKeyMappingArray.Append(result[j]);
 
-    TPtiKey keyValue = (TPtiKey) EPtiKeyQwertyHash;
-    TInt keyIndex = iKeysForPoolFormation.Find(keyValue);    
-
-    PRINT3 ( _L("CPcsKeyMap: ===== At index %d appending key to list: '%c' (#%d) -Hack-for-E72-"),
-             keyIndex, (TInt) keyValue, (TInt) keyValue);
-
-    if ( KErrNotFound != keyIndex )
-        {
-        iAllKeyMappingsPtrArr[keyIndex]->iKeyMappingArray.Append(keyValue);
-        }
-
-    PRINT ( _L("CPcsKeyMap: ===================================================") );  
-
-    PRINT ( _L("End CPcsKeyMap::AddDataFor4x10QwertyKeyboardE72HackL") );
-#endif // RD_INTELLIGENT_TEXT_INPUT    
-    }
-#endif // HACK_FOR_E72_J_KEY
-
-// ----------------------------------------------------------------------------
-// CPcsKeyMap::AddDataFor4x10QwertyKeyboardL
-// 
-// ----------------------------------------------------------------------------
-void CPcsKeyMap::AddDataFor4x10QwertyKeyboardL(CPtiQwertyKeyMappings* iPtiKeyMappings, 
-                                               TPtiKey aKey,  
-                                               TKeyMappingData& aKeyDataList)
-    {
-#ifdef RD_INTELLIGENT_TEXT_INPUT     	
-    TPtiTextCase caseArray[] =
-            {
-            EPtiCaseUpper,
-            EPtiCaseLower,
-            EPtiCaseFnLower,
-            EPtiCaseFnUpper,
-            EPtiCaseChrLower,
-            EPtiCaseChrUpper
-            };
-        
-    TBuf<50> iResult;
-    for (int i = 0; i < sizeof(caseArray) / sizeof(TPtiTextCase); i++)
-        {
-        iResult.Zero();
-        iPtiKeyMappings->GetDataForKey(aKey, iResult, caseArray[i]);
-
-        for (int j = 0; j < iResult.Length(); j++)
-            aKeyDataList.iKeyMappingArray.Append(iResult[j]);
-
-        PRINT2 ( _L("CPcsKeyMap: Mapping for Key %c = %S"), aKey, &iResult)
+        PRINT2 ( _L("CPcsKeyMap: Mapping for Key %c = %S"), aKey, &result)
         }
 #endif //RD_INTELLIGENT_TEXT_INPUT        
     }
@@ -584,42 +459,33 @@
 // CPcsKeyMap::ContructForItutKeyboardL
 // 
 // ----------------------------------------------------------------------------
-void CPcsKeyMap::ContructForItutKeyboardL(TLanguage aLanguage)
+void CPcsKeyMap::ConstructForItutKeyboardL()
     {
     // Add the keys for Pool formation
-    iKeysForPoolFormation.Append(EPtiKey0);
-    iKeysForPoolFormation.Append(EPtiKey1);
-    iKeysForPoolFormation.Append(EPtiKey2);
-    iKeysForPoolFormation.Append(EPtiKey3);
-    iKeysForPoolFormation.Append(EPtiKey4);
-    iKeysForPoolFormation.Append(EPtiKey5);
-    iKeysForPoolFormation.Append(EPtiKey6);
-    iKeysForPoolFormation.Append(EPtiKey7);
-    iKeysForPoolFormation.Append(EPtiKey8);
-    iKeysForPoolFormation.Append(EPtiKey9);
+    iItutKeys.Append(EPtiKey0);
+    iItutKeys.Append(EPtiKey1);
+    iItutKeys.Append(EPtiKey2);
+    iItutKeys.Append(EPtiKey3);
+    iItutKeys.Append(EPtiKey4);
+    iItutKeys.Append(EPtiKey5);
+    iItutKeys.Append(EPtiKey6);
+    iItutKeys.Append(EPtiKey7);
+    iItutKeys.Append(EPtiKey8);
+    iItutKeys.Append(EPtiKey9);
     // one additional pool for special characters not mapped too any keys. 
     // This should always be the last one in the arrary
-    iKeysForPoolFormation.Append(EPtiKeyNone);
+    iItutKeys.Append(EPtiKeyNone);
 
     // Now add the keymap arrays to hold the keymap data
-    for (TInt i = 0; i < iKeysForPoolFormation.Count(); i++)
+    const TInt ltutKeysCount = iItutKeys.Count();
+    for (TInt i = 0; i < ltutKeysCount; i++)
         {
         TKeyMappingData *keyData = new (ELeave) TKeyMappingData;
-        keyData->key = iKeysForPoolFormation[i];
-        iAllKeyMappingsPtrArr.Append(keyData);
-        }
-
-    //  Add the keymap for current language
-    AddKeyMapforItutL(aLanguage);
-
-    // If it's TW or HK variant, add the keymap for English language
-    if (aLanguage == ELangTaiwanChinese || aLanguage == ELangHongKongChinese)
-        {
-        AddKeyMapforItutL(ELangEnglish);
+        keyData->iKey = iItutKeys[i];
+        iItutKeyMappings.Append(keyData);
         }
 
     PRINT ( _L("----------------------------------------"));
-
     }
 
 // ----------------------------------------------------------------------------
@@ -628,29 +494,31 @@
 // ----------------------------------------------------------------------------
 void CPcsKeyMap::AddKeyMapforItutL(TLanguage aLanguage)
     {
-    // Make a language object based on current language
-    CPtiCoreLanguage* iCoreLanguage = static_cast<CPtiCoreLanguage*> (iPtiEngine->GetLanguage(aLanguage));
+    // Activate given language and get corresponding language object
+    iPtiEngine->ActivateLanguageL(aLanguage);
+    CPtiCoreLanguage* coreLanguage = static_cast<CPtiCoreLanguage*> (iPtiEngine->GetLanguage(aLanguage));
 
     //Perfrom the key mappings only if the corelanguage is available
-    if (iCoreLanguage)
+    if (coreLanguage)
         {
         // Get the keyboard mappings for the language
-        CPtiKeyMappings* iPtiKeyMappings =  static_cast<CPtiKeyMappings*> 
-                (iCoreLanguage->GetKeymappings());
+        CPtiKeyMapData* ptiKeyMapData = coreLanguage->RawKeyMapData();
 
-        for (TInt i = 0; i < iAllKeyMappingsPtrArr.Count() - 1; i++)
+        const TInt ltutKeyMappingsCount = iItutKeyMappings.Count() - 1;
+        for (TInt i = 0; i < ltutKeyMappingsCount; i++)
             {
-            AddDataForItutKeyboardL(iPtiKeyMappings, iKeysForPoolFormation[i], *(iAllKeyMappingsPtrArr[i]));
+            AddDataForItutKeyboardL(ptiKeyMapData, iItutKeys[i], *(iItutKeyMappings[i]));
             }
         }
 
-    if (iAlgorithm->FindUtilECE()->CurrentInputLanguage() == ELangHongKongChinese)
+    if ( (aLanguage == ELangPrcChinese || aLanguage == ELangTaiwanChinese || aLanguage == ELangHongKongChinese) && 
+         (iAlgorithm->FindUtilECE()->CurrentSearchMethod() == EAdptSearchStroke) )
         {
-        (*(iAllKeyMappingsPtrArr[1])).iKeyMappingArray.Append(0x4E00); //heng
-        (*(iAllKeyMappingsPtrArr[2])).iKeyMappingArray.Append(0x4E28); //shu
-        (*(iAllKeyMappingsPtrArr[3])).iKeyMappingArray.Append(0x4E3F); //pie
-        (*(iAllKeyMappingsPtrArr[4])).iKeyMappingArray.Append(0x4E36); //dian
-        (*(iAllKeyMappingsPtrArr[5])).iKeyMappingArray.Append(0x4E5B); //zhe
+        (*(iItutKeyMappings[1])).iKeyMappingArray.Append(0x4E00); //heng
+        (*(iItutKeyMappings[2])).iKeyMappingArray.Append(0x4E28); //shu
+        (*(iItutKeyMappings[3])).iKeyMappingArray.Append(0x4E3F); //pie
+        (*(iItutKeyMappings[4])).iKeyMappingArray.Append(0x4E36); //dian
+        (*(iItutKeyMappings[5])).iKeyMappingArray.Append(0x4E5B); //zhe
         }
 
     }
@@ -658,18 +526,80 @@
 // CPcsKeyMap::AddDataForItutKeyboardL
 // 
 // ----------------------------------------------------------------------------
-void CPcsKeyMap::AddDataForItutKeyboardL(CPtiKeyMappings* iPtiKeyMappings, TPtiKey aKey, TKeyMappingData& aKeyDataList)
+void CPcsKeyMap::AddDataForItutKeyboardL(CPtiKeyMapData* aPtiKeyMapData, TPtiKey aKey, TKeyMappingData& aKeyDataList)
     {
     TPtiTextCase caseArray[] = { EPtiCaseUpper, EPtiCaseLower };
-    TBuf<50> iResult;
-    for (int i = 0; i< sizeof(caseArray) / sizeof(TPtiTextCase); i++)
+    for (TInt i = 0; i< sizeof(caseArray) / sizeof(TPtiTextCase); i++)
+        {
+        TPtrC result = aPtiKeyMapData->DataForKey(EPtiKeyboard12Key, aKey, caseArray[i]);
+        const TInt resultLength =  result.Length();
+        for (TInt j = 0; j < resultLength; j++)
+            aKeyDataList.iKeyMappingArray.Append(result[j]);
+        PRINT2 ( _L("CPcsKeyMap: Mapping for Key %c = %S"), aKey,&result)
+        }
+    }
+
+// ----------------------------------------------------------------------------
+// CPcsKeyMap::CreateKeyMapFromKeyBindingTable
+//
+// ----------------------------------------------------------------------------
+void CPcsKeyMap::CreateKeyListFromKeyBindingTable( RArray<TPtiKey>& aKeyArray, 
+        TPtiKeyboardType aKbType )
+    {
+    PRINT ( _L("Enter CPcsKeyMap::CreateKeyListFromKeyBindingTable") );
+
+    // Use Eglish mappings to list the keys on the keyboard
+    TRAP_IGNORE( iPtiEngine->ActivateLanguageL( ELangEnglish ) );
+    CPtiCoreLanguage* ptiLang = 
+            static_cast<CPtiCoreLanguage*>(iPtiEngine->GetLanguage( ELangEnglish ));
+
+    if (ptiLang)
         {
-        iResult.Zero();
-        iPtiKeyMappings->GetDataForKey(aKey, iResult, caseArray[i]);
-        for (int j = 0; j < iResult.Length(); j++)
-            aKeyDataList.iKeyMappingArray.Append(iResult[j]);
-        PRINT2 ( _L("CPcsKeyMap: Mapping for Key %c = %S"), aKey,&iResult)
+        const CPtiKeyMapData* keyMapData = ptiLang->RawKeyMapData();
+        const TPtiKeyBinding* table = NULL;
+        TInt numItems = 0;
+        if ( keyMapData )
+            {
+            table = keyMapData->KeyBindingTable(aKbType, numItems);
+            }
+        else
+            {
+            PRINT( _L("CPcsKeyMap::CreateKeyListFromKeyBindingTable: #### Failed to get RawKeyMapData ####") );
+            }
+        
+        PRINT1 ( _L("CPcsKeyMap::CreateKeyListFromKeyBindingTable: Num of Items in KeyBindingTable is %d"), numItems );
+
+        // Get from the key table the keys for constructing the pools
+        if (table)
+            {
+            for (TInt i = 0; i < numItems; i++)
+                {
+                TPtiKey key = (TPtiKey) table[i].iScanCode;
+                // Get all keys with same EPtiCaseLower or EPtiCaseUpper case
+                // Only for one of the casing to avoid repetitions
+                if ( (EPtiKeyNone != key) && (EPtiCaseLower == table[i].iCase) )
+                    {
+                    PRINT3 ( _L("CPcsKeyMap::CreateKeyListFromKeyBindingTable: Adding pool %d with key '%c' (0x%02X)"),
+                            aKeyArray.Count(), key, key );
+                    aKeyArray.Append( key );
+                    }
+                }
+            }
+        else
+            {
+            PRINT ( _L("CPcsKeyMap::CreateKeyListFromKeyBindingTable: ##### Failed to create Key List (KeyBindingTable) #####") );
+            }
         }
+    else
+        {
+        PRINT ( _L("CPcsKeyMap::CreateKeyListFromKeyBindingTable: ##### Failed to create Key List (Language) #####") );
+        }
+
+    // one additional pool for special characters not mapped too any keys. 
+    // This should always be the last one in the arrary
+    aKeyArray.Append(EPtiKeyNone);
+
+    PRINT ( _L("End CPcsKeyMap::CreateKeyListFromKeyBindingTable") );
     }
 
 // ----------------------------------------------------------------------------
@@ -680,7 +610,8 @@
     {
 
     TBool flag = ETrue;
-    for (int i = 0; i < iLanguageNotSupported.Count(); i++)
+    const TInt languageNotSupportedCount = iLanguageNotSupported.Count();
+    for (TInt i = 0; i < languageNotSupportedCount; i++)
         {
         if (iLanguageNotSupported[i] == aLang)
             {
@@ -690,31 +621,131 @@
 
     return flag;
     }
+
+// ----------------------------------------------------------------------------
+// CPcsKeyMap::PoolIdForKey
+//
+// ----------------------------------------------------------------------------
+TInt CPcsKeyMap::PoolIdForKey(TPtiKey aKey, TKeyboardModes aKbMode) const
+    {
+    __ASSERT_DEBUG( (aKbMode==EPredictiveItuT || aKbMode==EPredictiveQwerty),
+                    Panic(EPanic_InvalidKeyboardType) );
+    
+    // From logical point of view, the Pool ID is an index of the key in
+    // an array which is formed by concatenating QWERTY keys array in the end
+    // of the ITU-T keys array.
+    TInt poolId = KErrNotFound;
+    if ( aKbMode == EPredictiveItuT && iItutKeys.Count() )
+        {
+        poolId = iItutKeys.Find(aKey);
+        // IF the key is not found, then it should go to the special pool,
+        // which is the pool of the dummy key in the ITU-T keys array
+        if (KErrNotFound == poolId)
+            {
+            poolId = iItutKeys.Count() - 1;
+            }
+        }
+    else if ( aKbMode == EPredictiveQwerty && iQwertyKeys.Count() )
+        {
+        poolId = iQwertyKeys.Find(aKey);
+        // IF the key is not found, then it should go to the special pool,
+        // which is the pool of the dummy key in the QWERTY keys array
+        if (KErrNotFound == poolId)
+            {
+            poolId = iQwertyKeys.Count() - 1;
+            }
+        // Pools of QWERTY keys come after pools of ITU-T keys
+        poolId += iItutKeys.Count();
+        }
+
+    // Pool ID must never exceed value 63, because CPcsCache class
+    // stores these values as bitmask into 64 bit variable.
+    __ASSERT_DEBUG( poolId < 64, Panic(EPanic_OverflowInPoolIndex) );
+    return poolId;
+    }
+
 // ----------------------------------------------------------------------------
 // CPcsKeyMap::PoolIdForCharacter
 // 
 // ----------------------------------------------------------------------------
-TInt CPcsKeyMap::PoolIdForCharacter(TChar aChar)
+TInt CPcsKeyMap::PoolIdForCharacter( TChar aChar, TKeyboardModes aKbMode )
     {
-    TInt numValue = KErrNotFound;
-    
+    // Pools are formed according the predictive keyboard mapping(s).
+    // When selecting pool for non-predictive mode, we use the pool of the
+    // default keyboard. The non-predictive matches should be a sub set of the
+    // predictive matches of the default keyboard, although strictly speaking,
+    // there' no guarantee for this.
+    if ( aKbMode == ENonPredictive || aKbMode == EPredictiveDefaultKeyboard )
+        {
+        aKbMode = ( iItutIsDefault ? EPredictiveItuT : EPredictiveQwerty );
+        }
+
     // If character is a Chinese word character, then we select the
     // pool ID according the first character of the first spelling of the word.
     TRAP_IGNORE( aChar = FirstCharFromSpellingL( aChar ) );
+
+    TPtiKey key = KeyForCharacter( aChar, aKbMode );
+    TInt poolId = PoolIdForKey( key, aKbMode );
+
+    return poolId;
+    }
+
+// ----------------------------------------------------------------------------
+// CPcsKeyMap::PoolCount
+// 
+// ----------------------------------------------------------------------------
+TInt CPcsKeyMap::PoolCount()
+    {
+    return iItutKeyMappings.Count() + iQwertyKeyMappings.Count();
+    }
+
+// ----------------------------------------------------------------------------
+// CPcsKeyMap::GetSpaceAndZeroOnSameKey
+// 
+// ----------------------------------------------------------------------------
+TBool CPcsKeyMap::GetSpaceAndZeroOnSameKey( TKeyboardModes aMode )
+    {
+    // Resolve ambiguous keyboard mode
+    aMode = ResolveKeyboardMode( aMode );
     
-    TInt key = KeyForCharacter(aChar);
-    if (key != KErrNotFound)
+    if ( aMode == EPredictiveItuT )
         {
-        numValue = iKeysForPoolFormation.Find((TPtiKey) key);
+        return iSpaceAndZeroOnSameKeyOnItut;
+        }
+    else if ( aMode == EPredictiveQwerty )
+        {
+        return iSpaceAndZeroOnSameKeyOnQwerty;
         }
     else
         {
-        // IF the key is not found, then it should go to the special pool,
-        // which is the last pool of iAllKeyMappingsPtrArr
-        numValue = iAllKeyMappingsPtrArr.Count() - 1;
+        return EFalse;
         }
+    }
 
-    return numValue;
+// ----------------------------------------------------------------------------
+// CPcsKeyMap::SetSpaceAndZeroOnSameKey
+// 
+// ----------------------------------------------------------------------------
+void CPcsKeyMap::SetSpaceAndZeroOnSameKey()
+    {
+    static const TInt KSpace = 0x20; // ASCII for " "
+    static const TInt KZero  = 0x30; // ASCII for "0"
+
+    TChar charSpace(KSpace);
+    TChar charZero(KZero);
+
+    TPtiKey keySpace;
+    TPtiKey keyZero;
+    
+    // ITU-T mode
+    keySpace = KeyForCharacter(charSpace, EPredictiveItuT);
+    keyZero = KeyForCharacter(charZero, EPredictiveItuT);
+    iSpaceAndZeroOnSameKeyOnItut = (keySpace == keyZero);
+    
+    // QWERTY mode
+    keySpace = KeyForCharacter(charSpace, EPredictiveQwerty);
+    keyZero = KeyForCharacter(charZero, EPredictiveQwerty);
+    iSpaceAndZeroOnSameKeyOnQwerty = (keySpace == keyZero);
     }
 
 // ----------------------------------------------------------------------------
@@ -726,7 +757,7 @@
     TChar translated( aChar );
     TBuf<1> temp;
     temp.Append( aChar );
-    if ( iAlgorithm->FindUtilECE()->IsChineseWord( temp ) )
+    if ( iAlgorithm->FindUtilECE()->IsChineseWordIncluded( temp ) )
         {
         RPointerArray<HBufC> spellList;
         CleanupResetAndDestroyPushL( spellList );
@@ -738,12 +769,91 @@
         }
     return translated;
     }
+
 // ----------------------------------------------------------------------------
-// CPcsKeyMap::PoolCount
+// CPcsKeyMap::KeyMappings
+//
+// ----------------------------------------------------------------------------
+const RPointerArray<TKeyMappingData>* CPcsKeyMap::KeyMappings( TKeyboardModes aMode ) const
+    {
+    const RPointerArray<TKeyMappingData>* mappings = NULL;
+    
+    if ( aMode == EPredictiveItuT )
+        {
+        mappings = &iItutKeyMappings;
+        }
+    else if ( aMode == EPredictiveQwerty )
+        {
+        mappings = &iQwertyKeyMappings;
+        }
+    else if ( aMode == ENonPredictive )
+        {
+        mappings = NULL;
+        }
+    else
+        {
+        mappings = NULL;
+        __ASSERT_DEBUG( EFalse, Panic( EPanic_InvalidKeyboardType ) );
+        }
+    
+    return mappings;
+    }
+
+// ----------------------------------------------------------------------------
+// CPcsKeyMap::ResolveKeyboardMode
 // 
 // ----------------------------------------------------------------------------
-TInt CPcsKeyMap::PoolCount()
+TKeyboardModes CPcsKeyMap::ResolveKeyboardMode( TKeyboardModes aKbMode ) const
     {
-    return iAllKeyMappingsPtrArr.Count();
+    TKeyboardModes resolvedMode = aKbMode;
+    
+    // Substitute "default predictive" mode with actual mode
+    if ( resolvedMode == EPredictiveDefaultKeyboard )
+        {
+        resolvedMode = ( iItutIsDefault ? EPredictiveItuT : EPredictiveQwerty );
+        }
+
+    // Substitute predictive mode with non-predictive mode if corresponding
+    // keyboard mappings are not available.
+    if ( ( resolvedMode == EPredictiveItuT && iItutKeyboardType == EPtiKeyboardNone ) ||
+         ( resolvedMode == EPredictiveQwerty && iQwertyKeyboardType == EPtiKeyboardNone ) )
+        {
+        PRINT1( _L("CPcsKeyMap::ResolveKeyboardMode: Mappings for requested mode %d unavailable. Falling back to non-predictive mode!"), aKbMode );
+        resolvedMode = ENonPredictive;
+        }
+    
+    return resolvedMode;
+    }
+
+// ----------------------------------------------------------------------------
+// CPcsKeyMap::DefaultCharForKey
+// 
+// ----------------------------------------------------------------------------
+TText CPcsKeyMap::DefaultCharForKey( TPtiKey aKey, TKeyboardModes aKbMode ) const
+    {
+    // On ITU-T, the Pti key code can be directly interpreted as unicode character.
+    // Thus, default characters for keys are 1,2,3,4,5,6,7,8,9,0,*,#.
+    TText defChar = aKey;
+    
+    // On QWERTY, using PtiKey values directly is not safe since all PtiKey values are
+    // not codepoints of printable Unicode characters.
+    // Treating these arbitrary numerical values as Unicode characters could break 
+    // the uniqueness of keys when collated comparison is used. Also, converting same
+    // data multiple times to "compare format" would then break the data.
+    if ( aKbMode == EPredictiveQwerty )
+        {
+        // Take first mapped character of the key and convert it to upper case.
+        TInt index = iQwertyKeys.Find( aKey );
+        if ( index != KErrNotFound )
+            {
+            const RArray<TInt>& mappings = iQwertyKeyMappings[index]->iKeyMappingArray;
+            if ( mappings.Count() )
+                {
+                defChar = User::UpperCase( mappings[0] );
+                }
+            }
+        }
+    
+    return defChar;
     }
 // End of file
--- a/predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsPoolElement.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/src/CPcsPoolElement.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -79,20 +79,19 @@
 // ----------------------------------------------------------------------------
 TInt CPcsPoolElement::CompareByData ( const CPcsPoolElement& aObject1,  const CPcsPoolElement& aObject2 )
 {
-  CPsData *data1 = const_cast<CPcsPoolElement&> (aObject1).GetPsData();
-  CPsData *data2 = const_cast<CPcsPoolElement&> (aObject2).GetPsData();  
-  return (CPcsAlgorithm2Utils::CompareDataBySortOrder(*(data1), *(data2)));
+    CPsData *data1 = const_cast<CPcsPoolElement&> (aObject1).GetPsData();
+    CPsData *data2 = const_cast<CPcsPoolElement&> (aObject2).GetPsData();  
+    return (CPcsAlgorithm2Utils::CompareDataBySortOrder(*(data1), *(data2)));
 }
 
 // CPcsPoolElement::IsDataMatch
 // 
 // ----------------------------------------------------------------------------		
-TBool CPcsPoolElement::IsDataMatch (TInt aIndex)
+TBool CPcsPoolElement::IsDataMatch(TInt aIndex)
 {
-	TReal val;
-	Math::Pow(val, 2, aIndex);
-
-	return(iDataMatchAttribute & (TUint8)val);	
+    __ASSERT_DEBUG( aIndex < 8, User::Panic( _L("CPcsPoolElement"), KErrOverflow ) );
+    TUint8 val = 1 << aIndex;
+    return (iDataMatchAttribute & val);
 }
 
 // ----------------------------------------------------------------------------
@@ -101,10 +100,9 @@
 // ----------------------------------------------------------------------------
 void CPcsPoolElement::SetDataMatch(TInt aIndex)
 {
-	TReal val;
-	Math::Pow(val, 2, aIndex);
-
-	iDataMatchAttribute |= (TUint8)val;	
+    __ASSERT_DEBUG( aIndex < 8, User::Panic( _L("CPcsPoolElement"), KErrOverflow ) );
+    TUint8 val = 1 << aIndex;
+    iDataMatchAttribute |= val;
 }
 
 // ----------------------------------------------------------------------------
--- a/predictivesearch/PcsAlgorithm/Algorithm2/src/CPsDataPluginInterface.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/src/CPsDataPluginInterface.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -15,6 +15,7 @@
 *
 */
 
+
 // INCLUDE FILES
 #include "CPsDataPluginInterface.h"
 #include "CPsDataPlugin.h"
@@ -109,7 +110,8 @@
     
     // Instantiate plugins for all impUIds by calling 
     // InstantiatePlugInFromImpUidL
-    for ( TInt i=0; i<infoArray.Count(); i++ )
+    const TInt infoArrayCount = infoArray.Count();
+    for ( TInt i=0; i < infoArrayCount; i++ )
     {
         // Get imp info
         CImplementationInformation& info( *infoArray[i] );
@@ -178,8 +180,8 @@
 {
 
     PRINT ( _L("Enter CPsDataPluginInterface::RequestForDataL") );
-   
-    for ( TInt idx = 0; idx < iPsDataPluginInstances.Count(); idx++ )
+   const TInt instancesCount = iPsDataPluginInstances.Count();
+    for ( TInt idx = 0; idx < instancesCount; idx++ )
     {
         if(iPsDataPluginInstances[idx]->IsDataStoresSupportedL(aDataStore))
         {
@@ -200,8 +202,8 @@
 {
 
     PRINT ( _L("Enter CPsDataPluginInterface::GetAllSupportedDataStoresL") );
-   
-    for ( TInt idx = 0; idx < iPsDataPluginInstances.Count(); idx++ )
+    const TInt instancesCount = iPsDataPluginInstances.Count();
+    for ( TInt idx = 0; idx < instancesCount; idx++ )
     {       
        iPsDataPluginInstances[idx]->GetSupportedDataStoresL(aDataStores);
     }
@@ -219,20 +221,23 @@
 
     PRINT ( _L("Enter CPsDataPluginInterface::GetAllSupportedDataStoresL") );
    
-    for ( TInt idx = 0; idx < iPsDataPluginInstances.Count(); idx++ )
-    {   
-       RPointerArray<TDesC> aDataStores;    
-       iPsDataPluginInstances[idx]->GetSupportedDataStoresL(aDataStores);
+    const TInt instancesCount = iPsDataPluginInstances.Count();
+    for ( TInt idx = 0; idx < instancesCount; idx++ )
+    {
+       RPointerArray<TDesC> dataStores;
+       CleanupClosePushL( dataStores );
+       iPsDataPluginInstances[idx]->GetSupportedDataStoresL(dataStores);
        
-       for( TInt i(0); i<aDataStores.Count(); i++)
-       {       	
-	       	if( aDataStores[i]->Compare(aUri) == 0)
+       const TInt dataStoresCount = dataStores.Count();
+       for ( TInt i(0); i < dataStoresCount; i++)
+       {
+	       	if ( dataStores[i]->Compare(aUri) == 0)
 	       	{
 	       		iPsDataPluginInstances[idx]->GetSupportedDataFieldsL(aDataFields);
 	       		break;
-	       	}    	
+	       	}
        }
-       aDataStores.Reset();
+       CleanupStack::PopAndDestroy( &dataStores ); // Close
     }
     
     PRINT ( _L("End CPsDataPluginInterface::GetAllSupportedDataStoresL") );
--- a/predictivesearch/PcsAlgorithm/Algorithm2/src/FindUtilChineseECE.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/src/FindUtilChineseECE.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -20,11 +20,12 @@
 #include <AknFepInternalCRKeys.h>
 #include <aknedsts.h>
 #include <coeaui.h>
+#include <AvkonInternalCRKeys.h>
+
 // The below code is commented out because current CFindUtilChineseECE is used
 // on 3.2.3 which is not supported adaptive search. It will be easy to keep these code 
 // for the further merging work (merge from FindUtil 5.0)
 #if 0
-#include <AvkonInternalCRKeys.h>
 #include <aknenv.h> //phonebook
 #include <aknappui.h>
 #include <aknapp.h>
@@ -45,12 +46,13 @@
 const TUint16 KZhuyinstart = 0x3105;
 const TInt KZhuyincount = 37;
 const TInt KSeperator = 2626;
-const TInt16 KMinUnicodeHz = 0x4e00;
-const TInt16 KStrokeHorizontalValue = 0x4e00;
-const TInt16 KStrokeVerticalValue = 0x4e28;
-const TInt16 KStrokeDownToLeftValue = 0x4e3f;
-const TInt16 KStrokeDownToRightValue = 0x4e36;
-const TInt16 KStrokeBendingValue = 0x4e5b;
+const TUint16 KMinUnicodeHz = 0x4e00;
+const TUint16 KMaxUnicodeHz = 0x9fa5;
+const TUint16 KStrokeHorizontalValue = 0x4e00;
+const TUint16 KStrokeVerticalValue = 0x4e28;
+const TUint16 KStrokeDownToLeftValue = 0x4e3f;
+const TUint16 KStrokeDownToRightValue = 0x4e36;
+const TUint16 KStrokeBendingValue = 0x4e5b;
 const TInt KSysInputMode = -1;
 const TInt KLeftToRightFlag =0x200e;
 const TInt KRightToLeftFlag =0x200f;
@@ -62,6 +64,7 @@
 const TUid KUidPhoneBookServer = {0x10207277};
 #endif
 
+
 _LIT(KWildChar, "*");
 _LIT(KUnderLine, "_");
 _LIT(KMiddleLine, "-");
@@ -70,28 +73,6 @@
 _LIT(KPanicReason, "Abnormal input parameters!");
 
 const TInt KLitLineFeed(8233);
-
-// CleanupStack helpers for item owning RPointerArrays
-template <class T>
-class CleanupResetAndDestroy
-    {
-public:
-    inline static void PushL( T& aRef )
-        { 
-        CleanupStack::PushL( TCleanupItem( &ResetAndDestroy, &aRef ) ); 
-        }
-private:
-    inline static void ResetAndDestroy( TAny *aPtr )
-        { 
-        static_cast<T*>( aPtr )->ResetAndDestroy();
-        }
-    };
-
-template <class T>
-inline void CleanupResetAndDestroyPushL( T& aRef )
-    { 
-    CleanupResetAndDestroy<T>::PushL( aRef );
-    }
 // ======== MEMBER FUNCTIONS ========
 
 // ---------------------------------------------------------
@@ -116,25 +97,16 @@
 void CFindUtilChineseECE::ConstructL(CPcsAlgorithm2* aAlgorithm)
     {
     iRepositoryFind = CRepository::NewL(KCRUidAknFep);
-    // The below code is commented out because current CFindUtilChineseECE is used
-    // on 3.2.3 which is not supported adaptive search. It will be easy to keep these code 
-    // for the further merging work (merge from FindUtil 5.0)
-#if 0   
     iRepositoryFindAdaptive = CRepository::NewL(KCRUidAvkon);
-#endif
 
     iWatcher = CFindRepositoryWatcher::NewL(KCRUidAknFep, 
         TCallBack(HandleFindRepositoryCallBack, this), 
         iRepositoryFind);
 
-    // The below code is commented out because current CFindUtilChineseECE is used
-    // on 3.2.3 which is not supported adaptive search. It will be easy to keep these code 
-    // for the further merging work (merge from FindUtil 5.0)
-#if 0
     iWatcherAdaptive = CFindRepositoryWatcher::NewL(KCRUidAvkon,
         TCallBack(HandleFindRepositoryCallBack, this),
-        iRepositoryFindAdaptive);                                        
-#endif
+        iRepositoryFindAdaptive);
+
     iAlgorithm = aAlgorithm;
     OpenL();
 
@@ -146,19 +118,11 @@
 //
 CFindUtilChineseECE::CFindUtilChineseECE() :
 iLanguage(ELangTest),
-iSupportPRCChinese(EFalse),
-iCurInputMode(KSysInputMode)
-// The below code is commented out because current CFindUtilChineseECE is used
-// on 3.2.3 which is not supported adaptive search. It will be easy to keep these code 
-// for the further merging work (merge from FindUtil 5.0)
-#if 0
-iSearchMethodPRC(EAdptSearchPinyin),
-iSearchMethodTaiWan(EAdptSearchZhuyin),
-iSearchMethodHongKong(EAdptSearchStroke),
+iCurInputMode(KSysInputMode),
+iSearchMethod(EAdptSearchPinyin),
 iSearchMethodAdaptive(EFalse)
-#endif
-    	    {
-    	    }
+    {
+    }
 
 // ---------------------------------------------------------
 // Destructor
@@ -168,15 +132,9 @@
     {
     delete iPtiEngine;
     delete iWatcher;
-    delete iPtiEnginePrc;
     delete iRepositoryFind;
-    // The below code is commented out because current CFindUtilChineseECE is used
-    // on 3.2.3 which is not supported adaptive search. It will be easy to keep these code 
-    // for the further merging work (merge from FindUtil 5.0)
-#if 0
     delete iWatcherAdaptive;
     delete iRepositoryFindAdaptive;
-#endif
     }
 
 // ---------------------------------------------------------
@@ -188,12 +146,36 @@
     if (!iPtiEngine)
         {
         iPtiEngine = CPtiEngine::NewL();
-        iSupportPRCChinese = IsSupportLanguage(ELangPrcChinese);
         }
 
     if (aLanguage != iLanguage)
         {
-        iLanguage = aLanguage;
+        // We only support Chinese languages. If input language is changed
+        // to non-Chinese, then first available Chinese language is used
+        // instead.
+        if ( aLanguage == ELangPrcChinese ||
+             aLanguage == ELangTaiwanChinese ||
+             aLanguage == ELangHongKongChinese )
+            {
+            iLanguage = aLanguage;
+            }
+        else if ( IsSupportLanguage(ELangPrcChinese) )
+            {
+            iLanguage = ELangPrcChinese;
+            }
+        else if ( IsSupportLanguage(ELangTaiwanChinese) )
+            {
+            iLanguage = ELangTaiwanChinese;
+            }
+        else if ( IsSupportLanguage(ELangHongKongChinese) )
+            {
+            iLanguage = ELangHongKongChinese;
+            }
+        else
+            {
+            iLanguage = aLanguage;
+            }
+        
         iPtiEngine->ActivateLanguageL(iLanguage);
         iPtiEngine->EnableToneMarks(EFalse);
         }
@@ -217,6 +199,10 @@
 //
 TBool CFindUtilChineseECE::DoTranslationL(TInt16 aHZUnicode, RPointerArray<HBufC>& aSpellList)
     {
+    // Always translate according the adaptive search method setting
+    return T9ChineseTranslationAdaptiveL(aHZUnicode, aSpellList);
+    
+#if 0
     // The below code is commented out because current CFindUtilChineseECE is used
     // on 3.2.3 which is not supported adaptive search. It will be easy to keep these code 
     // for the further merging work (merge from FindUtil 5.0)
@@ -264,13 +250,14 @@
 #endif
     return ETrue;
 
+#endif
     }
 
 // ---------------------------------------------------------
 // Find pane text is including stroke symbol
 // ---------------------------------------------------------
 //
-TInt CFindUtilChineseECE::IsStrokeSymbol(const TInt aFindWord)
+TInt CFindUtilChineseECE::IsStrokeSymbol(const TUint16 aFindWord)
     {
     TInt strokeValue = 0;
 
@@ -298,24 +285,7 @@
     return strokeValue;
     }
 
-TInt CFindUtilChineseECE::CategoryOfLang(TLanguage aLanguage)
-    {
-    TInt ret = 0;
-    if (iLanguage == ELangPrcChinese || ( aLanguage == ELangEnglish && iSupportPRCChinese ))
-        {
-        ret = 1;
-        }
-    else if (aLanguage == ELangTaiwanChinese)
-        {
-        ret = 2;
-        }
-    else if (aLanguage == ELangHongKongChinese)
-        {
-        ret = 3;
-        }
-    return ret;
-    }
-
+#if 0
 // ---------------------------------------------------------
 // Do translate for Chinese word
 // ---------------------------------------------------------
@@ -323,7 +293,6 @@
 TBool CFindUtilChineseECE::T9ChineseTranslationL(TInt16 aHZUnicode, RPointerArray<HBufC>& aSpellList)
     {
     TBuf<KMaxWordInterpretationLen> wordInterpretationBuf;
-    TBuf<KMaxWordInterpretationLen> numInterpretationBuf;
 
     if (iLanguage == ELangPrcChinese)
         {
@@ -389,11 +358,8 @@
 
     return ETrue;
     }
+#endif
 
-// The below code is commented out because current CFindUtilChineseECE is used
-// on 3.2.3 which is not supported adaptive search. It will be easy to keep these code 
-// for the further merging work (merge from FindUtil 5.0)
-#if 0    
 // ---------------------------------------------------------
 // Do translate for Chinese word
 // ---------------------------------------------------------
@@ -403,121 +369,59 @@
     {
     TBuf<KMaxWordInterpretationLen> wordInterpretationBuf;
 
-    if ( iLanguage == ELangPrcChinese )
+    switch(iSearchMethod)
         {
-        if(iSearchMethodPRC == EAdptSearchPinyin)
-            {
-            if (iPtiEngine->GetSpelling(aHZUnicode, wordInterpretationBuf, EPtiPinyin) 
-                != KErrNone)
-                {
-                return EFalse;
-                }	
-            }
-        else if(iSearchMethodPRC == EAdptSearchStroke)    
-            {
-            if (iPtiEngine->GetSpelling(aHZUnicode, wordInterpretationBuf, EPtiStrokes) 
+        case EAdptSearchPinyin:
+            if (iPtiEngine->GetSpelling(aHZUnicode, wordInterpretationBuf, EPtiPinyin)
                 != KErrNone)
                 {
                 return EFalse;
-                }	
-            }
-        else
-            {
-            return EFalse;	
-            }    
-
-        }
-    else if ( iLanguage == ELangTaiwanChinese )
-        {
-        if(iSearchMethodTaiWan == EAdptSearchZhuyin)
-            {
-            if (iPtiEngine->GetSpelling(aHZUnicode, wordInterpretationBuf, EPtiZhuyin) 
+                }
+             break;
+        case EAdptSearchStroke:
+            if (iPtiEngine->GetSpelling(aHZUnicode, wordInterpretationBuf, EPtiStrokes)
                 != KErrNone)
                 {
                 return EFalse;
-                }	
-            }
-        else if(iSearchMethodTaiWan == EAdptSearchStroke)    
-            {
-            if (iPtiEngine->GetSpelling(aHZUnicode, wordInterpretationBuf, EPtiStrokes) 
+                }
+            break;
+        case EAdptSearchZhuyin:
+            if (iPtiEngine->GetSpelling(aHZUnicode, wordInterpretationBuf, EPtiZhuyin)
                 != KErrNone)
                 {
                 return EFalse;
-                }	
-            }
-        else
-            {
-            return EFalse;	
-            }       
+                }   
+            break;
+        case EAdptSearchNormalCangjie:
+            if (iPtiEngine->GetSpelling(aHZUnicode, wordInterpretationBuf, EPtiCangJie)
+                != KErrNone)
+                {
+                return EFalse;
+                }
+            break;
+        case EAdptSearchEasyCangjie:
+            if (iPtiEngine->GetSpelling(aHZUnicode, wordInterpretationBuf, EPtiEasyCangjie) 
+                != KErrNone)
+                {
+                return EFalse;
+                }
+            break;
+        case EAdptSearchAdvCangjie:
+            if ((iPtiEngine->GetSpelling(aHZUnicode, wordInterpretationBuf, EPtiCangJie) != KErrNone)
+                &&(iPtiEngine->GetSpelling(aHZUnicode, wordInterpretationBuf, EPtiEasyCangjie) != KErrNone))
+                {
+                return EFalse;
+                }
+            break;
+        default:
+            return EFalse;
         }
-    else if ( iLanguage == ELangHongKongChinese )
-        {
-        switch(iSearchMethodHongKong)
-            {
-            case EAdptSearchNormalCangjie:
-                if (iPtiEngine->GetSpelling(aHZUnicode, wordInterpretationBuf, EPtiCangJie) 
-                    != KErrNone)
-                    {
-                    return EFalse;
-                    }
-                break;
-            case EAdptSearchEasyCangjie:
-                if (iPtiEngine->GetSpelling(aHZUnicode, wordInterpretationBuf, EPtiEasyCangjie) 
-                    != KErrNone)
-                    {
-                    return EFalse;
-                    }
-                break;
-            case EAdptSearchAdvCangjie:
-                if ((iPtiEngine->GetSpelling(aHZUnicode, wordInterpretationBuf, EPtiCangJie) != KErrNone)
-                    &&(iPtiEngine->GetSpelling(aHZUnicode, wordInterpretationBuf, EPtiEasyCangjie) != KErrNone))
-                    {
-                    return EFalse;
-                    }
-                break;
-            case EAdptSearchStroke:
-                if (iPtiEngine->GetSpelling(aHZUnicode, wordInterpretationBuf, EPtiStrokes) 
-                    != KErrNone)
-                    {
-                    return EFalse;
-                    }
-                break;
-            default:
-                return EFalse;        	
-            }
 
-        }
-    else if ( iLanguage == ELangEnglish )
-        {
-        if (!iSupportPRCChinese)
-            {
-            return EFalse;
-            }
-
-        TInt err = KErrNone;
-        if (!iPtiEnginePrc)
-            {
-            iPtiEnginePrc = CPtiEngine::NewL(EFalse);
-            TRAP(err, iPtiEnginePrc->ActivateLanguageL(ELangPrcChinese));
-            }   
-
-        if (err == KErrNone)
-            {
-            if (iPtiEnginePrc->GetSpelling(aHZUnicode, wordInterpretationBuf, EPtiPinyin) 
-                != KErrNone) 
-
-                return EFalse;
-            }
-        }
-    else
-        {
-        return EFalse;
-        }
 
     TInt len = wordInterpretationBuf.Length();
     TInt start = 0;
 
-    if( iSearchMethodHongKong != EAdptSearchAdvCangjie )
+    if( iSearchMethod != EAdptSearchAdvCangjie )
         {
         for (TInt i =0; i < len; i++)
             {
@@ -528,7 +432,7 @@
                 }
             }
 
-        aSpellList.Append((wordInterpretationBuf.MidTPtr(start, len-start)).Alloc());   	
+        aSpellList.Append((wordInterpretationBuf.MidTPtr(start, len-start)).Alloc());
         }
     //Could look advanced cangjie as normal and easy cangjie
     else 
@@ -564,8 +468,7 @@
         }
 
     return ETrue;
-    } 
-#endif
+    }
 
 // ---------------------------------------------------------
 // Find pane text is including separator
@@ -583,75 +486,71 @@
 void CFindUtilChineseECE::OpenL()
     {
     TInt inputLanguage = 0;
-    //TInt searchMode =0;
+    TInt searchMode = 0;
 
     if (iRepositoryFind != NULL)
         {
         iRepositoryFind->Get(KAknFepInputTxtLang, inputLanguage);
         }
 
+    // The following sets iLangueage to inputLanguage if inputLanguage
+    // is Chinese. If inputLanguage is non-Chinese, iLanguage will be
+    // set to first available Chinese language.
     OpenT9InterfaceL((TLanguage) inputLanguage);
 
-    // The below code is commented out because current CFindUtilChineseECE is used
-    // on 3.2.3 which is not supported adaptive search. It will be easy to keep these code 
-    // for the further merging work (merge from FindUtil 5.0)
-#if 0
     if (iRepositoryFindAdaptive != NULL)
         {
         iRepositoryFindAdaptive->Get(KAknAvkonAdaptiveSearchEnabled, iSearchMethodAdaptive);
         }
-    if( inputLanguage == ELangPrcChinese)
+    if (iLanguage == ELangPrcChinese)
         {
-        iRepositoryFindAdaptive->Get(KAknAdaptiveSearchChinesePRC , searchMode);	
-        if(searchMode ==0)
+        iRepositoryFindAdaptive->Get(KAknAdaptiveSearchChinesePRC , searchMode);
+        if (searchMode == 0)
             {
-            iSearchMethodPRC = EAdptSearchPinyin;	
+            iSearchMethod = EAdptSearchPinyin;
             }
-        else if(searchMode ==1)
+        else if (searchMode == 1)
             {
-            iSearchMethodPRC = EAdptSearchStroke;	
+            iSearchMethod = EAdptSearchStroke;
             }
         }
-    else if(inputLanguage == ELangTaiwanChinese)
+    else if (iLanguage == ELangTaiwanChinese)
         {
         iRepositoryFindAdaptive->Get(KAknAdaptiveSearchChineseTW , searchMode);
-        if(searchMode ==0)
+        if (searchMode == 0)
             {
-            iSearchMethodTaiWan = EAdptSearchZhuyin;	
+            iSearchMethod = EAdptSearchZhuyin;
             }
-        else if(searchMode ==1)
+        else if (searchMode == 1)
             {
-            iSearchMethodTaiWan = EAdptSearchStroke;	
-            }	
+            iSearchMethod = EAdptSearchStroke;
+            }
         }
-    else if(inputLanguage == ELangHongKongChinese)
+    else if (iLanguage == ELangHongKongChinese)
         {
         iRepositoryFindAdaptive->Get(KAknAdaptiveSearchChineseHongkong  , searchMode);
-        if(searchMode ==1)
-            {	    
+        if (searchMode == 1)
+            {
             iRepositoryFind->Get(KAknFepCangJieMode , searchMode);
 
             switch (searchMode)
                 {
                 case 0:
-                    iSearchMethodHongKong = EAdptSearchNormalCangjie;
+                    iSearchMethod = EAdptSearchNormalCangjie;
                     break;
                 case 1:
-                    iSearchMethodHongKong = EAdptSearchEasyCangjie;
+                    iSearchMethod = EAdptSearchEasyCangjie;
                     break;
                 case 2:
-                    iSearchMethodHongKong = EAdptSearchAdvCangjie;
+                    iSearchMethod = EAdptSearchAdvCangjie;
                     break;
                 }
-
             }
-        else if(searchMode ==0)
+        else if (searchMode == 0)
             {
-            iSearchMethodHongKong = EAdptSearchStroke;	
+            iSearchMethod = EAdptSearchStroke;
             }
-
         }
-#endif
     }
 
 // ---------------------------------------------------------
@@ -682,7 +581,7 @@
 
     TBool ret = EFalse;
     // Check Chinese word in find pane
-    TBool chineseWord = IsChineseWord(aWord);
+    TBool chineseWord = IsChineseWordIncluded(aWord);
 
     if (chineseWord)
         {
@@ -851,8 +750,25 @@
 //
 TBool CFindUtilChineseECE::MatchRefineL(const TDesC& aItemString, CPsQuery& aPsQuery)
     {
+    RArray<TInt> ignore1;
+    CleanupClosePushL( ignore1 );
+    RArray<TInt> ignore2;
+    CleanupClosePushL( ignore2 );
+    
+    TBool match = MatchRefineL( aItemString, aPsQuery, ignore1, ignore2, EFalse );
+    
+    CleanupStack::PopAndDestroy( &ignore2 );
+    CleanupStack::PopAndDestroy( &ignore1 );
+    
+    return match;
+    }
+
+TBool CFindUtilChineseECE::MatchRefineL(const TDesC& aItemString, CPsQuery& aPsQuery, 
+        RArray<TInt>& aMatchPos, RArray<TInt>& aMatchLength, TBool aHighLight )
+    {
     TBuf<KMaxWordLength> tempBuf;
     TBuf<KMaxWordLength> itemString;
+    TBool haschineseword = EFalse; 
 
     itemString.Zero();
     if ( KMaxWordLength > aItemString.Length() )
@@ -870,12 +786,10 @@
         if(itemString[0]== KLeftToRightFlag || itemString[0]== KRightToLeftFlag)
             {
             itemString.Delete(0,1);
-            itemString.Delete((itemString.Length()-1),1);    
+            itemString.Delete((itemString.Length()-1),1);
             }
         }
 
-    TBool haschineseword = EFalse; 
-
     // Check function parameter
     if (aPsQuery.Count() == 0)
         {
@@ -888,8 +802,8 @@
         }
 
     TBool ret = EFalse;
-
     CPsQuery* query = CPsQuery::NewL();
+    CleanupStack::PushL( query );
     GetPartOfQueryL(aPsQuery, 0, aPsQuery.Count()-1, *query);
     RemoveSeparatorL(*query);
     TPtrC queryStrPtr = query->QueryAsStringLC();
@@ -912,78 +826,63 @@
         {
         iCurInputMode = KSysInputMode;
         }
-
-    // Check Chinese word in find pane
-    if (IsChineseWord(tempBuf))
+    
+    TBool inputMethodStroke = EFalse;
+    if(iLanguage == ELangHongKongChinese && iCurInputMode == 0x0020)
+        {
+        inputMethodStroke = ETrue;
+        }
+      
+    // Check if any Chinese word in find pane
+    if ( IsChineseWordIncluded(tempBuf) )
         {
         haschineseword = ETrue;
         ret = IncludeString(aItemString, tempBuf);
-
-        if (ret)
+      
+        if( IsAllChineseWord( tempBuf ))
             {
+            CleanupStack::PopAndDestroy( query );
             return ret;
             }
-        /*    else
-            {
-            // if Stroke Symbol in HongKong
-            TBool strokeSymHK = (IsStrokeSymbolInString(tempBuf)) && 
-                                 (iLanguage == ELangHongKongChinese) &&
-                                 iCurInputMode == 0x0020;
-
-            if (!strokeSymHK)
-                {
-                return ret;
-                }
-            }*/
         }
 
-    //Find if search string has chinese word. 
-    //Compare with item string if find chinese word in item string then delete it from search and item string.
-    //if not then return EFalse.
-    TBool InputMethodStroke = EFalse;
-    if(iLanguage == ELangHongKongChinese && iCurInputMode == 0x0020)
-        {
-        InputMethodStroke = ETrue;
-        }
-    
+   
+    // There are two steps to do when searchstring includes Chinese character 
+    //
+    // step 1:  check whether itemstring includes the chinese charactor in the searchstring
+    //              If not, return EFalse. Otherwise, go to step2
+    //
+    // step2:  If itemstring includes the chinese charactor in the searchstring, translate 
+    //             the Chinese character in the searchstring to spellList and reconstruct the query.
     if (haschineseword)
         {
         TInt ii=0;
-        TBool leftDifferentChinese = EFalse; //Fixed for ESSG-7PJ6GF, flag the different Chinese character at the left of aSearchText.
+        
+        // Step 1: 
+        // E.g: itemstring = "0x4E00,0x4E8C,0x4E09,0x56DB,0x4E94" 
+        // (Unicode of Chinese number "1 2 3 4 5")
+        // searchstring1 = "0x4E00,x,y,z,0x4E09"
+        // searchstring2 = "0x4E8C,0x4E00"
+        // searchstring3 = "0x4E00,0x4E5D" 
+        // In this case, searchstring2 and searchstring3 will return EFalse, 
+        // only searchstring1 will be translated to spellList in step 2
         while (ii< tempBuf.Length())
             {
-            if ((TInt)tempBuf[ii]>= KMinUnicodeHz && (!InputMethodStroke
-                    ||(InputMethodStroke && !IsStrokeSymbol(tempBuf[ii]))))
+            TInt lastFindCursor = -1;
+            if( (TUint16)tempBuf[ii] <= KMaxUnicodeHz 
+                && (TUint16)tempBuf[ii]>= KMinUnicodeHz
+                && ( !inputMethodStroke ||(inputMethodStroke &&
+                    !IsStrokeSymbol(tempBuf[ii])) ) )
                 {
                 TInt Findcursor = itemString.Locate(tempBuf[ii]);
-                if (Findcursor != KErrNotFound)
+                if( KErrNotFound == Findcursor || Findcursor < lastFindCursor )
                     {
-                    if ((Findcursor == itemString.Length()-1)&& (ii
-                            ==tempBuf.Length()-1))
-                        {
-                        //Start:Fixed for ESSG-7PJ6GF
-                        if ( leftDifferentChinese || IsChineseWord(
-                            itemString.Left( Findcursor ) ) )
-                            {
-                            //if the different Chinese character at the left or middle, return false.
-                            return EFalse;
-                            }
-                        //End:Fixed for ESSG-7PJ6GF
-                        return ETrue;
-                        }
-                    itemString.Delete(0, Findcursor+1);
-                    tempBuf.Delete(0, ii+1);
-                    ii=0;
+                    CleanupStack::PopAndDestroy( query );
+                    return EFalse;
                     }
                 else
                     {
-                    //Start:Fixed for ESSG-7PJ6GF
-                    if ( IsChineseWord( tempBuf.Left( ii + 1 ) ) )
-                        {
-                        //flag the different Chinese character at the left.
-                        leftDifferentChinese = ETrue;
-                        }
-                    //End:Fixed for ESSG-7PJ6GF
+                    lastFindCursor = Findcursor;
                     ii++;
                     }
                 }
@@ -992,9 +891,70 @@
                 ii++;
                 }
             }
+            
+        ii = 0;
+        // Counter of queryItem
+        TInt queryItemCount = 0;
+        
+        //Step 2: 
+        // Translating searchstring to spellList and reconstruct query
+         while ( ii< tempBuf.Length() )
+             {            
+             // If it is a valid chinese character
+             if ( (TUint16)tempBuf[ii] <= KMaxUnicodeHz 
+                 && (TUint16)tempBuf[ii]>= KMinUnicodeHz
+                 && ( !inputMethodStroke ||(inputMethodStroke &&
+                     !IsStrokeSymbol(tempBuf[ii])) ) )
+                 {
+                 RPointerArray<HBufC> spellList;
+                 
+                 // If successfully translating the chinese character to spellList( Pinyin,Zhuyin or stroke )
+                 // then reconstruct the query, replace the Chinese character with its spellList in the query.
+                 // Otherwise, just increase the counter of queryItem.
+                 if( DoTranslationL(TInt16(tempBuf[ii]), spellList) )
+                     {                    
+                     // Replace the queryItem by the translated spelling
+                     CPsQueryItem& tempItem = query->GetItemAtL(queryItemCount);
+                     const TKeyboardModes tempMode = tempItem.Mode();
+                     
+                     // Remove the Chinese character queryItem
+                     query->Remove(queryItemCount);
+                     
+                     // Reconstruct the query, replace Chinese character with its spellList
+                     for(TInt cnt = 0; cnt < spellList[0]->Length(); cnt++)
+                         {
+                         // Add a new query item to query
+                         CPsQueryItem* newItem = CPsQueryItem::NewL();   
+                         CleanupStack::PushL(newItem);
+                         newItem->SetCharacter(  (*spellList[0])[cnt] );
+                         newItem->SetMode(tempMode);
+   
+                         query->InsertL(*newItem, queryItemCount + cnt );
+                         CleanupStack::Pop(newItem);  
+                         }
+                    
+                     queryItemCount += spellList[0]->Length();
+                     }
+                 else
+                     {
+                     queryItemCount++;
+                     }
+                     
+                 ii++;
+                 spellList.ResetAndDestroy();
+                 spellList.Close();
+
+                 }
+             //if not, just pass it by     
+             else
+                 {
+                 ii++;
+                 queryItemCount++;
+                 }
+             }
 
         }
-
+    
     // Array for item string
     RPointerArray<STRINGINFO> stringInfoArr;
     // Split item string
@@ -1002,13 +962,13 @@
 
     if (stringInfoArr.Count() > 0)
         {
-        ret = MatchSegmentL(stringInfoArr, *query);
+        ret = MatchSegmentL(stringInfoArr, *query, aMatchPos, aMatchLength, aHighLight);
         }
 
     stringInfoArr.ResetAndDestroy();
     stringInfoArr.Close();
 
-    delete query;
+    CleanupStack::PopAndDestroy( query );
 
     return ret;
     }
@@ -1018,7 +978,7 @@
 // ---------------------------------------------------------
 //
 void CFindUtilChineseECE::SplitItemStringL(RPointerArray<STRINGINFO>& aStringInfoArr, 
-    const TDesC &aItemString)
+    const TDesC& aItemString)
     {
     TBuf<KMaxWordLength> tempBuf;
     TBuf<KMaxWordLength> englishBuf;
@@ -1029,8 +989,7 @@
     chineseBuf.Zero();
 
     TInt index = 0;
-    TUint32 temp = 0;
-    TInt32 distance = 0;
+    TBool isChinese = EFalse;
     const TInt strLength = aItemString.Length();
 
     for (; index < strLength; index++)
@@ -1039,35 +998,35 @@
             {
             // Check Chinese and English Buf. If it is not empty, 
             // add buf to Array
-            InsertStrInforArrayL(aStringInfoArr, chineseBuf, ETrue);
-            InsertStrInforArrayL(aStringInfoArr, englishBuf, EFalse);
+            InsertStrInforArrayL(aStringInfoArr, chineseBuf, ETrue, index);
+            InsertStrInforArrayL(aStringInfoArr, englishBuf, EFalse, index);
             continue;
             }
 
-        temp = aItemString[index];
-        distance = (TInt32)(temp - KMinUnicodeHz);
-
-        if (distance < 0)// English word
+        isChinese = ((TUint16)aItemString[index] >= KMinUnicodeHz && 
+                               (TUint16)aItemString[index] <= KMaxUnicodeHz);
+        
+        if ( !isChinese )// English word
             {
             // Chinese word is end and add to array
-            InsertStrInforArrayL(aStringInfoArr, chineseBuf, ETrue);
+            InsertStrInforArrayL(aStringInfoArr, chineseBuf, ETrue, index);
 
             // Add English word to array
-            englishBuf.Append((TChar) aItemString[index]);
+            englishBuf.Append(aItemString[index]);
             }
         else // Chinese word
             {
             // English word is end and add to array
-            InsertStrInforArrayL(aStringInfoArr, englishBuf, EFalse);
+            InsertStrInforArrayL(aStringInfoArr, englishBuf, EFalse, index);
 
             // Add Chinese word to array
-            chineseBuf.Append((TChar) aItemString[index]);
+            chineseBuf.Append(aItemString[index]);
             }
         }
 
     // Finish loop check buffer is empty
-    InsertStrInforArrayL(aStringInfoArr, chineseBuf, ETrue);
-    InsertStrInforArrayL(aStringInfoArr, englishBuf, EFalse);
+    InsertStrInforArrayL(aStringInfoArr, chineseBuf, ETrue, index);
+    InsertStrInforArrayL(aStringInfoArr, englishBuf, EFalse, index);
     }
 
 // ---------------------------------------------------------
@@ -1075,9 +1034,8 @@
 // ---------------------------------------------------------
 //
 void CFindUtilChineseECE::InsertStrInforArrayL(RPointerArray<STRINGINFO>& aStringInfoArr, 
-    TDes &aSegmentStr, const TBool aChinese)
+    TDes &aSegmentStr, TBool aChinese, TInt aIndexAfterStr)
     {
-    CleanupResetAndDestroyPushL( aStringInfoArr );
     if (aSegmentStr.Length() <= 0)
         {
         return;
@@ -1089,10 +1047,10 @@
     strInfo->segmentString.Copy(aSegmentStr);
     strInfo->segmentString.LowerCase();
     strInfo->isChinese = aChinese;
+    strInfo->segmentPos = aIndexAfterStr - aSegmentStr.Length();
 
     aStringInfoArr.AppendL(strInfo);
     aSegmentStr.Zero();
-    CleanupStack::Pop( &aStringInfoArr );
     }
 
 // ---------------------------------------------------------
@@ -1100,107 +1058,133 @@
 // ---------------------------------------------------------
 //
 TBool CFindUtilChineseECE::MatchSegmentL(RPointerArray<STRINGINFO>& aStringInfoArr, 
-    CPsQuery& aQuery)
+    CPsQuery& aQuery, RArray<TInt>& aMatchPos, RArray<TInt>& aMatchLength, TBool aHighLight )
     {
     const TInt arrayLength = aStringInfoArr.Count();
     const TInt searchStrLength = aQuery.Count();
-    TInt searchStrIndex = 0;
     STRINGINFO* pStringInfo;
     TInt index = 0;
+    TBool ret = EFalse;
+    TBool hasChinese = EFalse;
 
-    // First only check English
+    // First check if there is a full match in non-Chinese in any one segment
     for (; index < arrayLength; index++)
         {
+        pStringInfo = aStringInfoArr[index];
+        TPtrC currentSeg( pStringInfo->segmentString );
+        TInt matchLen( 0 );
+
+        // Compare word
+        if (pStringInfo->isChinese)
+            {
+            hasChinese = ETrue;
+            }
+        else
+            {
+            matchLen = MatchStringL( currentSeg, aQuery );
+            }
+        
+        // If full match is found
+        if ( matchLen == searchStrLength  )
+            {
+            //Only append postion of non-Chinese character
+            if(  !pStringInfo->isChinese )
+                {
+                aMatchPos.Append( pStringInfo->segmentPos );
+                aMatchLength.Append( matchLen );
+                }
+            ret =   ETrue;
+            
+            // If there is no need to HighLight the matched part, return immediately
+            // Otherwise, continue to find all the matched positions
+            if( !aHighLight ) 
+                return ret;
+            }
+        }
+    
+    // Then search through segments again, this time considering
+    // also cases where matching part continues over several segments.
+    // This algorithm is greedy and heuristic and can't necesarily find
+    // all the matches in the segments after the first one.
+    TPtrC segCurrent;
+    TInt searchStrIndextemp = 0;
+    TInt searchStrIndexMax = 0;
+    TInt searchStrIndex = 0;
+    index = 0;
+
+    // Loop through seqments until whole query is matched
+    for (; index < arrayLength && !ret ; index++)
+        {
         // Create an empty CPsQuery
         CPsQuery* tempQuery = CPsQuery::NewL();
-        pStringInfo = aStringInfoArr[index];
-
-        GetPartOfQueryL( aQuery, searchStrIndex, searchStrLength - 1,
-            *tempQuery );
+        CleanupStack::PushL( tempQuery );
 
-        // Compare word
-        if (!pStringInfo->isChinese)
-            {
-            searchStrIndex += MatchString(pStringInfo->segmentString, *tempQuery);
-            }
+        GetPartOfQueryL( aQuery, searchStrIndex, searchStrLength - 1, *tempQuery );
 
-        delete tempQuery;
-        tempQuery = NULL;
-
-        if (searchStrIndex >= searchStrLength)
-            {
-            return ETrue;
-            }
-        }
+        pStringInfo = aStringInfoArr[index];
+        segCurrent.Set( pStringInfo->segmentString );
 
-    TBuf<KMaxWordLength> bufcurrent;
-    TBuf<KMaxWordLength> tempbufcurrent;
-    TInt searchStrIndextemp = 0;
-    TInt searchStrIndexMax = 0;
-    // Find Chinese and English
-    searchStrIndex = 0;
-    index = 0;
-
-    for (; index < arrayLength; index++)
-        {
-        // Create an empty CPsQuery
-        CPsQuery* tempQuery = CPsQuery::NewL();
-        pStringInfo = aStringInfoArr[index];
-
-        GetPartOfQueryL( aQuery, searchStrIndex, searchStrLength - 1,
-            *tempQuery );
-        searchStrIndexMax = 0;
-
-        bufcurrent = pStringInfo->segmentString;
-
-        for(TInt i =0;i< pStringInfo->segmentString.Length();i++)
+        if (pStringInfo->isChinese)
             {
-            tempbufcurrent = bufcurrent.Mid(i);
-            if (pStringInfo->isChinese)
+            // find the longest substring matching the query
+            searchStrIndexMax = 0;
+            for (TInt i = 0; i< segCurrent.Length(); i++)
                 {
-                TInt temp=0;
-                searchStrIndextemp = MatchChineseStringL(tempbufcurrent, *tempQuery, temp);  
-                if(searchStrIndextemp > searchStrIndexMax)
+                TPtrC tempSeg( segCurrent.Mid(i) );
+                TInt startIdx( KErrNotFound );
+                TInt endIdx( KErrNotFound );
+                searchStrIndextemp = MatchChineseStringL(tempSeg, *tempQuery, startIdx, endIdx);
+                if (searchStrIndextemp > searchStrIndexMax)
                     {
                     searchStrIndex -= searchStrIndexMax;
                     searchStrIndexMax = searchStrIndextemp;
                     searchStrIndex += searchStrIndexMax;
                     }
+                
+                if (searchStrIndex >= searchStrLength)
+                    {
+                    // found substring which consumes whole query, no need to find any longer
+                    break;
+                    }
                 }
-            else
-                {
-                searchStrIndex += MatchString(pStringInfo->segmentString, *tempQuery);
-                }
-
-            if (searchStrIndex >= searchStrLength)
+            }
+        else // not chinese
+            {
+            TInt matchLen = MatchStringL(segCurrent, *tempQuery);
+            searchStrIndex += matchLen;
+            if ( matchLen )
                 {
-                delete tempQuery;
-                tempQuery = NULL;
-                return ETrue;
-                }
-            else if(!pStringInfo->isChinese)
-                {
-                break;
+                aMatchPos.Append( pStringInfo->segmentPos );
+                aMatchLength.Append( matchLen );
                 }
             }
 
-        delete tempQuery;
-        tempQuery = NULL;
+        if (searchStrIndex >= searchStrLength)
+            {
+             ret = ETrue; // also breaks us out from the loop
+            }
+        else if ( !pStringInfo->isChinese && !hasChinese )
+            {
+           CleanupStack::PopAndDestroy( tempQuery );
+            break;
+            }
+        
+        CleanupStack::PopAndDestroy( tempQuery );
         }
 
-    return EFalse;
+    return ret;
     }
 
 // ---------------------------------------------------------
 // Search Chinese word in input text 
 // ---------------------------------------------------------
 //
-TInt CFindUtilChineseECE::MatchChineseStringL(const TDesC& aSearhTargetString, CPsQuery& aQuery, TInt& aIndex)
+TInt CFindUtilChineseECE::MatchChineseStringL(const TDesC& aSearhTargetString, CPsQuery& aQuery, 
+        TInt& aMatchStartIdx, TInt& aMatchEndIdx)
     {
     const TInt stringLength = aSearhTargetString.Length();
     const TInt searchLength = aQuery.Count();
     TInt index = 0;
-    //TBuf<KMaxWordLength> tempBuf;
     TBuf<KMaxWordLength> previousBuf;
     TInt curMatchCount = 0;
     TInt preMatchCount = 0;
@@ -1208,6 +1192,13 @@
     TInt curSearchIndex = 0;
     TBool bFullMatched = EFalse;
     TBool bContinue = EFalse;
+    TBool bPrevReplaced = EFalse;
+    aMatchStartIdx = KErrNotFound;
+    aMatchEndIdx = KErrNotFound;
+    
+    CPsQuery* tempFullQuery = CPsQuery::NewL();
+    CleanupStack::PushL( tempFullQuery );
+    GetPartOfQueryL( aQuery, 0, aQuery.Count() - 1, *tempFullQuery );
 
     for (; index < stringLength; index++)
         {
@@ -1226,17 +1217,17 @@
 
         // Get left string
         CPsQuery* tempQuery = CPsQuery::NewL();
-        GetPartOfQueryL( aQuery, curSearchIndex, searchLength - 1,
-            *tempQuery );
+        CleanupStack::PushL( tempQuery );
+        GetPartOfQueryL( aQuery, curSearchIndex, searchLength - 1, *tempQuery );
 
-        // Get Matched count and the matched index in list     
-        curMatchCount = MaxMatchInList(spellList, *tempQuery, previousBuf, matchIndex, 
-            bFullMatched, preMatchCount, bContinue);
+        // Get Matched count and the matched index in list
+        curMatchCount = MaxMatchInListL(spellList, *tempQuery, previousBuf, matchIndex, 
+            bFullMatched, preMatchCount, bContinue, bPrevReplaced, *tempFullQuery);
 
         // There is a string matched in list 
         if (curMatchCount != 0)
             {
-            previousBuf.Copy(spellList[matchIndex]->Des());
+            previousBuf.Copy(*spellList[matchIndex]);
 
             if (curMatchCount == previousBuf.Length())
                 {
@@ -1247,7 +1238,7 @@
                 bFullMatched = EFalse;
                 }
 
-            // If it is repeat match, continue     
+            // If it is repeat match, continue
             if (!bContinue)
                 {
                 curSearchIndex += curMatchCount;
@@ -1258,6 +1249,14 @@
                 previousBuf.Zero();
                 curMatchCount = 0;
                 }
+
+            // Store the index of first matched Han character
+            if ( bPrevReplaced || aMatchStartIdx == KErrNotFound )
+                {
+                aMatchStartIdx = index;
+                }
+            // Store the index of last matched Han character
+            aMatchEndIdx = index;
             }
         else
             {
@@ -1269,13 +1268,17 @@
                 }
 
             curSearchIndex = 0;
+            
+            // Any earlier partial match is discarded, reset the matching part indices
+            aMatchStartIdx = KErrNotFound;
+            aMatchEndIdx = KErrNotFound;
             }
 
         spellList.ResetAndDestroy();//destroy spellList
         spellList.Close();
         preMatchCount = curMatchCount;
 
-        delete tempQuery;
+        CleanupStack::PopAndDestroy( tempQuery );
         tempQuery = NULL;
 
         // Search to End and return
@@ -1284,8 +1287,9 @@
             break;
             }
         }
+    CleanupStack::PopAndDestroy( tempFullQuery );
+    tempFullQuery = NULL;
 
-    aIndex = index;
     return curSearchIndex;
     }
 
@@ -1293,11 +1297,11 @@
 // Maximal matched count in spelling list  
 // ---------------------------------------------------------
 //
-TInt CFindUtilChineseECE::MaxMatchInList(RPointerArray<HBufC> &spellList, CPsQuery& aQuery,
+TInt CFindUtilChineseECE::MaxMatchInListL(RPointerArray<HBufC> &aSpellList, CPsQuery& aQuery,
     TDesC& aPreviouStr, TInt& aMatchIndex, const TBool aFullMatched, 
-    const TInt aMatchedCount, TBool& aAgain)
+    const TInt aMatchedCount, TBool& aAgain, TBool& aPrevReplaced, CPsQuery& aFullQuery)
     {
-    const TInt itemCount = spellList.Count();
+    const TInt itemCount = aSpellList.Count();
     TInt matchCount = 0;
     TBool selfMatch = EFalse;
     aMatchIndex = 0;
@@ -1320,9 +1324,9 @@
         repeatCount = 0;
         loopFlag = EFalse;
         tempBuf.Zero();
-        tempBuf.Copy(spellList[index]->Des());
+        tempBuf.Copy( *aSpellList[index] );
 
-        temp = MatchString(tempBuf, aQuery);
+        temp = MatchStringL(tempBuf, aQuery);
         if(temp != 0)
             {
             selfMatch = ETrue;
@@ -1337,11 +1341,11 @@
             // Previous word is fully matched
             if (aFullMatched)
                 {
-                repeatCount = ReverseMatchString(aPreviouStr, tempBuf);
+                repeatCount = ReverseMatchStringL(aPreviouStr, tempBuf, aFullQuery );
                 // Find repeat and remove it, search again
                 if (repeatCount != 0)
                     {
-                    temp = MatchString(tempBuf.Right(tempBuf.Length() - repeatCount), aQuery);
+                    temp = MatchStringL(tempBuf.Right(tempBuf.Length() - repeatCount), aQuery);
 
                     if (temp == 0)
                         {
@@ -1352,14 +1356,14 @@
                 }
             else
                 {
-                repeatCount = MatchString(aPreviouStr, tempBuf);
+                repeatCount = MatchStringL(aPreviouStr, tempBuf, aFullQuery);
 
                 // Find repeat and remove it, search again
                 if (repeatCount != 0)
                     {
                     if (aMatchedCount <= repeatCount)
                         {
-                        temp = MatchString(tempBuf.Right(tempBuf.Length() - aMatchedCount), aQuery);
+                        temp = MatchStringL(tempBuf.Right(tempBuf.Length() - aMatchedCount), aQuery);
 
                         if (temp == 0)
                             {
@@ -1371,11 +1375,11 @@
 
                 if (temp == 0)
                     {
-                    repeatCount = ReverseMatchString(aPreviouStr.Left(aMatchedCount), tempBuf);
+                    repeatCount = ReverseMatchStringL(aPreviouStr.Left(aMatchedCount), tempBuf, aFullQuery);
 
                     if (repeatCount != 0)
                         {
-                        temp = MatchString(tempBuf.Right(tempBuf.Length() - repeatCount), aQuery);
+                        temp = MatchStringL(tempBuf.Right(tempBuf.Length() - repeatCount), aQuery);
 
                         if (temp == 0)
                             {
@@ -1414,16 +1418,20 @@
             aMatchIndex = index;
             aAgain = loopFlag;
             }
-        if(matchCount == aQuery.Count() && selfMatch)
+        if (matchCount == aQuery.Count() && selfMatch)
             {
             break;
             }
         }
+    
+    // Was the previous match replaced with a longer match from this spell list
+    aPrevReplaced = ( matchCount && repeatCount );
+    
     return matchCount;
     }
 
 // ---------------------------------------------------------
-// Search the taxt is include the input text  
+// Search the text is include the input text  
 // ---------------------------------------------------------
 //
 TBool CFindUtilChineseECE::IncludeString(const TDesC& aFirst, const TDesC& aSecond)
@@ -1455,29 +1463,22 @@
 // Search text in other text  
 // ---------------------------------------------------------
 //
-TInt CFindUtilChineseECE::MatchString(const TDesC& aFirst, const TDesC& aSecond)
+TInt CFindUtilChineseECE::MatchStringL(const TDesC& aFirst, const TDesC& aSecond, CPsQuery& aFullQuery)
     {
     const TInt secondStrLength = aSecond.Length();
     const TInt firstStrLength = aFirst.Length();
 
-    const TInt compareCount = firstStrLength > secondStrLength ? secondStrLength
-        : firstStrLength;
+    const TInt compareCount = Min( firstStrLength, secondStrLength );
     TInt index = 0;
-
-    TBuf<KMaxWordLength> tempStr;
-    // translate search target string into numeric string before match
-    if (iAlgorithm)
-        {
-        iAlgorithm->Converter( aFirst, tempStr );
-        }
-    else
-        {
-        tempStr.Copy(aFirst);
-        }
+    TBuf<KMaxWordInterpretationLen> firstNumInterpretationBuf;
+    TBuf<KMaxWordInterpretationLen> secondNumInterpretationBuf;
+    
+    iAlgorithm->GetKeyMap()->GetMixedKeyStringForDataL(aFullQuery, aFirst, firstNumInterpretationBuf);
+    iAlgorithm->GetKeyMap()->GetMixedKeyStringForDataL(aFullQuery, aSecond, secondNumInterpretationBuf);
 
     for (; index < compareCount; index++)
         {
-        if (tempStr.Left(index + 1).FindC(aSecond.Left(index + 1)) == KErrNotFound)
+        if (firstNumInterpretationBuf.Left(index + 1).FindC(secondNumInterpretationBuf.Left(index + 1)) == KErrNotFound)
             {
             break;
             }
@@ -1485,32 +1486,32 @@
     // Match count
     return index;
     }
+
 // ---------------------------------------------------------
 // Search CPsQuery in aSearhTargetStr
 // ---------------------------------------------------------
 //
-TInt CFindUtilChineseECE::MatchString(const TDesC& aSearhTargetStr, CPsQuery& aQuery)
+TInt CFindUtilChineseECE::MatchStringL(const TDesC& aSearhTargetStr, CPsQuery& aQuery)
     {
     const TInt secondStrLength = aQuery.Count();
     const TInt firstStrLength = aSearhTargetStr.Length();
     TBuf<KMaxWordInterpretationLen> numInterpretationBuf;
+    TBuf<KMaxWordInterpretationLen> queryStr;
 
-    const TInt compareCount = firstStrLength > secondStrLength ? secondStrLength
-        : firstStrLength;
+    const TInt compareCount = Min( firstStrLength, secondStrLength );
+
     TInt index = 0;
 
-    ConvertdDataToKeyBoardModeL(aQuery, aSearhTargetStr, numInterpretationBuf);
+    iAlgorithm->GetKeyMap()->GetMixedKeyStringForDataL(aQuery, aSearhTargetStr, numInterpretationBuf);
+    iAlgorithm->GetKeyMap()->GetMixedKeyStringForQueryL(aQuery, queryStr);
 
-    TPtrC queryStr = aQuery.QueryAsStringLC();
     for (; index < compareCount; index++)
         {
-
         if (numInterpretationBuf.Left(index + 1).FindC(queryStr.Left(index + 1)) == KErrNotFound)
             {
             break;
             }
         }
-    CleanupStack::PopAndDestroy();
 
     // Match count
     return index;
@@ -1520,32 +1521,22 @@
 // Search text by reverse  
 // ---------------------------------------------------------
 //
-TInt CFindUtilChineseECE::ReverseMatchString(const TDesC& aFirst, const TDesC& aSecond)
+TInt CFindUtilChineseECE::ReverseMatchStringL(const TDesC& aFirst, const TDesC& aSecond, CPsQuery& aFullQuery)
     {
     const TInt secondStrLength = aSecond.Length();
     const TInt firstStrLength = aFirst.Length();
     TInt compareCount = firstStrLength > secondStrLength ? secondStrLength : firstStrLength;
     TInt index = 0;
     TInt matchCount = 0;
-
+    TBuf<KMaxWordInterpretationLen> firstNumInterpretationBuf;
+    TBuf<KMaxWordInterpretationLen> secondNumInterpretationBuf;
+    
+    iAlgorithm->GetKeyMap()->GetMixedKeyStringForDataL(aFullQuery, aFirst, firstNumInterpretationBuf);
+    iAlgorithm->GetKeyMap()->GetMixedKeyStringForDataL(aFullQuery, aSecond, secondNumInterpretationBuf);
+    
     for (; index < compareCount; index++)
         {
-        TBuf<KMaxWordLength> firstConvStr;
-        TBuf<KMaxWordLength> secondConvStr;
-
-        // translate compared target string into numeric string before match
-        if ( iAlgorithm )
-            {
-            iAlgorithm->Converter( aFirst, firstConvStr );
-            iAlgorithm->Converter( aSecond, secondConvStr );
-            }
-        else
-            {
-            firstConvStr.Copy( aFirst );
-            secondConvStr.Copy( aSecond );
-            }
-
-        if( firstConvStr.Right( index + 1 ).FindC( secondConvStr.Left( index + 1 ) ) != KErrNotFound )
+        if( firstNumInterpretationBuf.Right( index + 1 ).FindC( secondNumInterpretationBuf.Left( index + 1 ) ) != KErrNotFound )
             {
             matchCount = index + 1;
             }
@@ -1567,14 +1558,16 @@
 // Find pane text is including Chinese word  
 // ---------------------------------------------------------
 //
-TBool CFindUtilChineseECE::IsChineseWord(const TDesC& aWord)
+TBool CFindUtilChineseECE::IsChineseWordIncluded(const TDesC& aWord)
     {
     TBool IsChineseSearchStr = EFalse;
     const TInt len = aWord.Length();
 
     for (TInt ii = 0; ii < len; ii++)
         {
-        if ((TInt) aWord[ii] >= KMinUnicodeHz)
+
+        if ( ((TUint16) aWord[ii] >= KMinUnicodeHz) &&
+            ((TUint16) aWord[ii] <= KMaxUnicodeHz) )
             {
             IsChineseSearchStr = ETrue;
             break;
@@ -1594,7 +1587,7 @@
 
     for (TInt index = 0; index < len; index++)
         {
-        if (IsStrokeSymbol(TInt(aWord[index])) != 0)
+        if (IsStrokeSymbol(TUint16(aWord[index])) != 0)
             {
             return ETrue;
             }
@@ -1602,6 +1595,33 @@
     return EFalse;
     }
 
+// --------------------------------------------------------
+// Find pane text is all Chinese word(s)
+// --------------------------------------------------------
+//
+TBool CFindUtilChineseECE::IsAllChineseWord(const TDesC& aWord)
+    {
+    TBool isChineseWord = ETrue;
+    const TInt len = aWord.Length();
+    
+    TBool InputMethodStroke = EFalse;
+    if(iLanguage == ELangHongKongChinese && iCurInputMode == 0x0020)
+        {
+        InputMethodStroke = ETrue;
+        }
+    
+    for( TInt i = 0; i < len; i++ )
+        {
+        if( (( TUint16 )aWord[i] > KMaxUnicodeHz ) ||  (( TUint16 )aWord[i] < KMinUnicodeHz )
+            || ( InputMethodStroke && IsStrokeSymbol(aWord[i]) ) )
+            {
+            isChineseWord = EFalse;
+            break;
+            }
+        }
+    return isChineseWord;
+    }
+
 // ---------------------------------------------------------
 // Find pane text is including zhuyin symbol  
 // ---------------------------------------------------------
@@ -1643,108 +1663,37 @@
 TInt CFindUtilChineseECE::HandleFindRepositoryCallBack(TAny* aPtr)
     {
     TInt ret = KErrNone;
-    CFindUtilChineseECE *self = static_cast<CFindUtilChineseECE*> (aPtr);
-    TInt searchMode = 0;
+    CFindUtilChineseECE* self = static_cast<CFindUtilChineseECE*> (aPtr);
 
-    if (self->iWatcher->ChangedKey() == KAknFepInputTxtLang)
+    // Get changed key either from language repository (AknFepRepository)
+    // or from adaptive repository (AvkonRepository).
+    TUint32 changedKey = self->iWatcher->ChangedKey();
+    if ( changedKey == NCentralRepositoryConstants::KInvalidNotificationId )
         {
-        TInt inputLanguage = 0;
-        self->iRepositoryFind->Get(KAknFepInputTxtLang, inputLanguage);
+        changedKey = self->iWatcherAdaptive->ChangedKey();
+        }
+
 
-        TInt prevCategory = self->CategoryOfLang(self->iLanguage);
-        TRAP(ret, self->OpenT9InterfaceL(TLanguage(inputLanguage)));
+    // Update the search method if input language or any search method variable
+    // changed
+    if ( changedKey == KAknFepInputTxtLang ||
+         changedKey == KAknAdaptiveSearchChinesePRC ||
+         changedKey == KAknAdaptiveSearchChineseTW ||
+         changedKey == KAknAdaptiveSearchChineseHongkong ||
+         changedKey == KAknFepCangJieMode ||
+         changedKey == KAknAvkonAdaptiveSearchEnabled )
+        {
+        TChineseSearchMethod prevSearchMethods = self->iSearchMethod;
 
-        TInt category = self->CategoryOfLang(TLanguage(inputLanguage));
-        if (prevCategory != category && category != 0)
+        TRAP( ret, self->OpenL() );
+        
+        // Reconstruct cache if search method got changed
+        if ( ret == KErrNone && prevSearchMethods != self->iSearchMethod )
             {
             TRAP(ret, self->iAlgorithm->ReconstructCacheDataL());
             }
         }
-
-    // The below code is commented out because current CFindUtilChineseECE is used
-    // on 3.2.3 which is not supported adaptive search. It will be easy to keep these code 
-    // for the further merging work (merge from FindUtil 5.0)
-#if 0    
-    if(self->iWatcherAdaptive->ChangedKey() == KAknAvkonAdaptiveSearchEnabled)
-        {
-        self->iRepositoryFindAdaptive->Get(KAknAvkonAdaptiveSearchEnabled, self->iSearchMethodAdaptive);
-        }
-
-    if (self->iWatcherAdaptive->ChangedKey() == KAknAdaptiveSearchChinesePRC)
-        {
-        self->iRepositoryFindAdaptive->Get(KAknAdaptiveSearchChinesePRC, searchMode);
-
-        if(searchMode ==0)
-            {
-            self->iSearchMethodPRC = EAdptSearchPinyin;	
-            }
-        else if(searchMode ==1)
-            {
-            self->iSearchMethodPRC = EAdptSearchStroke;	
-            }
-        }
-
-    if (self->iWatcherAdaptive->ChangedKey() == KAknAdaptiveSearchChineseTW )
-        {
-        self->iRepositoryFindAdaptive->Get(KAknAdaptiveSearchChineseTW , searchMode);
-
-        if(searchMode ==0)
-            {
-            self->iSearchMethodTaiWan = EAdptSearchZhuyin;	
-            }
-        else if(searchMode ==1)
-            {
-            self->iSearchMethodTaiWan = EAdptSearchStroke;	
-            }
-        }
-
-    if (self->iWatcherAdaptive->ChangedKey() == KAknAdaptiveSearchChineseHongkong )
-        {
-        self->iRepositoryFindAdaptive->Get(KAknAdaptiveSearchChineseHongkong , searchMode);
-
-        if(searchMode ==1)
-            {
-            self->iRepositoryFind->Get(KAknFepCangJieMode , searchMode);
-
-            switch (searchMode)
-                {
-                case 0:
-                    self->iSearchMethodHongKong = EAdptSearchNormalCangjie;
-                    break;
-                case 1:
-                    self->iSearchMethodHongKong = EAdptSearchEasyCangjie;
-                    break;
-                case 2:
-                    self->iSearchMethodHongKong = EAdptSearchAdvCangjie;
-                    break;	
-                }
-
-            }
-        else if(searchMode ==0)
-            {
-            self->iSearchMethodHongKong = EAdptSearchStroke;	
-            }
-        }
-
-    if (self->iWatcher->ChangedKey() == KAknFepCangJieMode )
-        {
-        self->iRepositoryFind->Get(KAknFepCangJieMode , searchMode);
-
-        switch (searchMode)
-            {
-            case 0:
-                self->iSearchMethodHongKong = EAdptSearchNormalCangjie;
-                break;
-            case 1:
-                self->iSearchMethodHongKong = EAdptSearchEasyCangjie;
-                break;
-            case 2:
-                self->iSearchMethodHongKong = EAdptSearchAdvCangjie;
-                break;	
-            }
-
-        }
-#endif
+    
     return ret;
     }
 
@@ -1777,11 +1726,6 @@
         }
     }
 
-void CFindUtilChineseECE::SetKeyboardMode(TInt aMode)
-    {
-    iKeyboardMode = aMode;
-    }
-
 // The below code is commented out because current CFindUtilChineseECE is used
 // on 3.2.3 which is not supported adaptive search. It will be easy to keep these code 
 // for the further merging work (merge from FindUtil 5.0)
@@ -1798,7 +1742,7 @@
             {
             aNextChars = aNextChars->ReAllocL( aNextChars->Des().MaxLength()+10 );
             }		
-        aNextChars->Des().Append(aCh);								
+        aNextChars->Des().Append(aCh);
         }
     }    
 
@@ -1990,7 +1934,7 @@
             // Compare word
             if (!pStringInfo->isChinese)
                 {
-                searchStrIndex += MatchString(pStringInfo->segmentString,
+                searchStrIndex += MatchStringL(pStringInfo->segmentString,
                     transSearchBuf);
                 }
 
@@ -2070,7 +2014,7 @@
 
         }
     tempSpellList.ResetAndDestroy();
-    if(ReverseMatchString(aCurrentBuf,temp)>0)
+    if(ReverseMatchStringL(aCurrentBuf,temp)>0)
         {
         if (pStringInfo->isChinese)
             {
@@ -2320,7 +2264,7 @@
     //Find if search string has chinese word. 
     //Compare with item string if find chinese word in item string then delete it from search and item string.
 
-    if(IsChineseWord(tempBuf))
+    if(IsChineseWordIncluded(tempBuf))
         {
         if(TrimChineseCharacterL(itemString,tempBuf,aNextChars))
             {
@@ -2405,7 +2349,7 @@
                 }
             else
                 {//english words and chinese words don't coexist in same segment
-                matchLength = MatchString(bufcurrent, transSearchBuf);
+                matchLength = MatchStringL(bufcurrent, transSearchBuf);
                 searchStrIndex +=matchLength;
                 if (searchStrIndex >= searchStrLength)
                     {
@@ -2554,58 +2498,6 @@
     }
 #endif
 
-// ----------------------------------------------------------------------------
-// CFindUtilChineseECE::ConvertdDataToKeyBoardModeL
-// Converts the input data to the key board mode specified by the query
-// ----------------------------------------------------------------------------
-void CFindUtilChineseECE::ConvertdDataToKeyBoardModeL(CPsQuery& aQuery, 
-    const TDesC& aSearchTargetStr, 
-    TBuf<KMaxWordInterpretationLen>& aOutputNumInterpretationStr)
-    {    
-    if (iKeyboardMode == EItut)
-        {
-        iAlgorithm->GetKeyMap()->GetNumericKeyString(aSearchTargetStr, aOutputNumInterpretationStr);
-        }
-    else if (iKeyboardMode == EQwerty)
-        {
-        aOutputNumInterpretationStr = aSearchTargetStr;
-        aOutputNumInterpretationStr.LowerCase();
-        }
-    else
-        {
-
-        TInt len = -1;
-        TBuf<KPsQueryMaxLen> outBuf;
-
-        iAlgorithm->GetKeyMap()->GetNumericKeyString(aSearchTargetStr, outBuf);
-
-        // Always loop thru the lowest length
-        if (aSearchTargetStr.Length() > aQuery.Count() )
-            {
-            len = aQuery.Count();
-            }
-        else
-            {
-            len = aSearchTargetStr.Length();
-            }
-
-        // Interprete search target str according to the query char mode
-        for (TInt i = 0; i < len; i++)
-            {
-            if (aQuery.GetItemAtL(i).Mode() == EItut)
-                {
-                aOutputNumInterpretationStr.Append(outBuf[i]);
-                }
-            else
-                {
-                aOutputNumInterpretationStr.Append(aSearchTargetStr[i]);
-                }
-            }
-
-        aOutputNumInterpretationStr.LowerCase();
-        }
-    }
-
 void CFindUtilChineseECE::GetPartOfQueryL(CPsQuery& aSrcQuery, TInt aStartIndex, 
     TInt aEndIndex, CPsQuery& aDestQuery)
     {
@@ -2624,7 +2516,6 @@
 
             aDestQuery.AppendL(*newItem);
             }
-
         }
     else 
         {
@@ -2651,6 +2542,7 @@
                 // ajust index after remove
                 index--; 
                 }
+                break;
             default:
                 continue;
             } // switch
--- a/predictivesearch/PcsAlgorithm/Algorithm2/src/chinesefindutils.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsAlgorithm/Algorithm2/src/chinesefindutils.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -66,7 +66,11 @@
     TCallBack aCallBack,
     CRepository* aRepository)
     :
-    iUid(aUid), iKey(aKey), iCallBack(aCallBack), iRepository(aRepository)
+    iUid(aUid), 
+    iKey(aKey), 
+    iChangedKey(NCentralRepositoryConstants::KInvalidNotificationId), 
+    iCallBack(aCallBack), 
+    iRepository(aRepository)
     {
     }
 
--- a/predictivesearch/PcsServer/inc/CPcsServer.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsServer/inc/CPcsServer.h	Thu Aug 19 09:41:07 2010 +0300
@@ -58,11 +58,6 @@
          */			                  
 	    CPcsPluginInterface* PluginInterface();
 	    
-	    /**
-         * Returns ETrue if there is Chinese variant feature in phone
-         */	
-	    TBool  IsChineseVariant() const;
-	    
     private:
     
         /**
@@ -85,11 +80,6 @@
          * A PCS algorithm instance (owned)
          */
     	CPcsPluginInterface* iPcs;
-		
-		/**
-         * Flag for whether there is Chinese in phone
-         */	
-    	TBool iIsChineseVariant;
 };
 
 #endif // End of file
--- a/predictivesearch/PcsServer/src/CPcsServer.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsServer/src/CPcsServer.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -44,7 +44,7 @@
     self->StartL(KPcsServerName);
     CleanupStack::Pop(); 
     
-    PRINT ( _L("End CPcsServer::NewL") );
+     PRINT ( _L("End CPcsServer::NewL") );
     
     return self;
 }
@@ -70,18 +70,17 @@
 	iPcs = CPcsPluginInterface::NewL();
     
 	// Check if the phone is chinese feature id installed
-	iIsChineseVariant = IsChineseFeatureInitilizedL();
+	TBool isChineseVariant = IsChineseFeatureInitilizedL();
     // Create the plugin for the required algorithm
     // Matches the ECOM Plugin's display name definition in rss file
     // Check for the chinese feature id flag.
-	if(iIsChineseVariant) 
+	if(isChineseVariant) 
 	    {
 	    // Chinese variant phones. Use Algorithm 2
 	    PRINT ( _L("Enter CPcsServer::ConstructL() - Chinese Variant Phone Algorithm Instantiated") );
 	    TBuf<KAlgorithmNameMaxLen> algorithmName(KPcsAlgorithm_Chinese);
 	    iPcs->InstantiateAlgorithmL(algorithmName);
-	    
-	    
+	      
 	    }
 	else 
 	    {
@@ -151,12 +150,3 @@
     
     return chineseFeatureInitialized;
 }
-
-// ----------------------------------------------------------------------------
-// CPcsServer::IsChineseVariant() const
-// Returns ETrue if there is Chinese variant feature in phone
-// ---------------------------------------------------------------------------- 
-TBool CPcsServer::IsChineseVariant() const
-    {
-    return iIsChineseVariant;
-    }
--- a/predictivesearch/PcsServer/src/CPcsSession.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/PcsServer/src/CPcsSession.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -240,10 +240,11 @@
 void CPcsSession::GetAsyncPcsResultsL(const RMessage2& aMessage)
 {
     __LATENCY_MARK ( _L("CPcsSession::GetAsyncPcsResultsL") );
-    PRINT ( _L("Enter CPcsSession::GetAsyncPcsResultsL") );
+    PRINT( _L("Enter CPcsSession::GetAsyncPcsResultsL") );
 
     if ( iBufferOverFlow == EFalse )
     {
+
         // -------------------------------------------------------------
 
 	    // Read search query from the message
@@ -254,20 +255,10 @@
         RPointerArray<CPsClientData> searchResults;
         RPointerArray<CPsPattern> searchSeqs;
 
-
-        if( !iServer->IsChineseVariant() )
-             {
-             PRINT ( _L("----Algorithm1 search----") );
-             iServer->PluginInterface()->PerformSearchL(*iSettings,
-                                                        *psQuery,
-                                                        searchResults,
-                                                        searchSeqs);
-             }
-         else
-             {
-             PRINT ( _L("----Algorithm2 fake search----") );
-             }       
-
+        iServer->PluginInterface()->PerformSearchL(*iSettings,
+                                                   *psQuery,
+                                                   searchResults,
+                                                   searchSeqs);
         CleanupStack::PopAndDestroy( psQuery );
 
 		// Dynamic data buffer
@@ -393,18 +384,11 @@
     // To hold matched location
     RArray<TPsMatchLocation> sequenceLoc;
 
-    if( !iServer->IsChineseVariant() )
-         {
-         PRINT ( _L("----Algorithm1 searchinput----") );
-         iServer->PluginInterface()->SearchInputL(*psQuery,
-                                                  *data,
-                                                  searchSeqs,
-                                                  sequenceLoc);
-         }
-     else
-         {
-         PRINT ( _L("----Algorithm2 fake searchinput----") );
-         }       
+	iServer->PluginInterface()->SearchInputL(*psQuery,
+	                                         *data,
+	                                         searchSeqs,
+	                                         sequenceLoc);
+
 
     // Delete the search query and search data
 	CleanupStack::PopAndDestroy( data );
@@ -478,7 +462,7 @@
 void CPcsSession::SearchMatchStringL(const RMessage2& aMessage)
 {
     PRINT ( _L("Enter CPcsSession::SearchMatchStringL") );
-    __LATENCY_MARK ( _L("CPcsSession::SearchMatchStringL") );
+    //__LATENCY_MARK ( _L("CPcsSession::SearchMatchStringL") );
 
     // -------------------------------------------------------------
 
@@ -525,7 +509,8 @@
     CleanupStack::PopAndDestroy(des);
     
     PRINT ( _L("End CPcsSession::SearchMatchStringL") );
-    __LATENCY_MARKEND ( _L("CPcsSession::SearchMatchStringL") );
+    //__LATENCY_MARKEND ( _L("CPcsSession::SearchMatchStringL") );
+
 }
 
 // ----------------------------------------------------------------------------
--- a/predictivesearch/adapters/contacts/inc/cpcscontactstore.h	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/adapters/contacts/inc/cpcscontactstore.h	Thu Aug 19 09:41:07 2010 +0300
@@ -50,6 +50,7 @@
 enum
 {
     ECreateView,
+    EFetchAllLinks,
     EFetchContactBlock,
     EComplete
 };
@@ -216,6 +217,11 @@
         void ConstructL(CVPbkContactManager& aContactManager, MDataStoreObserver& aObserver,const TDesC& aUri);
 
         /**
+         * Check next state of state machine for contacts retrieval and perform transition 
+         */
+        void CheckNextState();
+
+        /**
          * Handles the operations for a single contact after it is fetched
          * @param aContact - The contact from database
          */
@@ -239,7 +245,8 @@
         /**
          * Fetches the  data from contact links from the view
          */
-        void FetchlinksL();
+        void FetchAllInitialContactLinksL();
+        void FetchContactsBlockL();
 
         /**
          * Reads the fields to cache from the central repository
@@ -260,7 +267,7 @@
         /**
          * Issues request to active object to call RunL method
          */
-        void IssueRequest();
+        void IssueRequest( TInt aTimeDelay );
 
         /**
          * Creates a sort order depending on the fields specified in the cenrep
@@ -275,12 +282,15 @@
 
     private:
 
+        RPointerArray<MVPbkContactLink> iInitialContactLinks;
 
         /**
          * Flags for store operations
          */
-        TInt  iAllContactLinksCount;
-        TInt  iFetchedContactCount;
+        TInt iInitialContactCount; // Initial contact count in a view
+        TInt iFetchBlockLowerNumber;
+        TInt iFetchBlockUpperNumber;
+        TInt iVPbkCallbackCount;
         TBool iContactViewReady;
         TCachingStatus iOngoingCacheUpdate;
 
--- a/predictivesearch/adapters/contacts/src/cpcscontactstore.cpp	Thu Jul 15 18:22:55 2010 +0300
+++ b/predictivesearch/adapters/contacts/src/cpcscontactstore.cpp	Thu Aug 19 09:41:07 2010 +0300
@@ -95,16 +95,17 @@
 // ---------------------------------------------------------------------------------
 CPcsContactStore::CPcsContactStore():
     CActive( CActive::EPriorityLow ),
-    iAllContactLinksCount(0),
-    iFetchedContactCount(0),
-    iContactViewReady(EFalse)
+    iInitialContactCount( 0 ),
+    iFetchBlockLowerNumber( 0 ),
+    iFetchBlockUpperNumber( 0 ),
+    iVPbkCallbackCount( 0 ),
+    iContactViewReady( EFalse )
 {
     PRINT ( _L("Enter CPcsContactStore::CPcsContactStore") );
     CActiveScheduler::Add( this );
     PRINT ( _L("End CPcsContactStore::CPcsContactStore") );
 }
 
-
 // ---------------------------------------------------------------------------------
 // CPcsContactStore::ConstructL() 
 // 2nd phase constructor
@@ -135,7 +136,7 @@
     
     // Initial state
 	iNextState = ECreateView;
-	IssueRequest();
+	IssueRequest( 0 );
 	
     FeatureManager::InitializeLibL();
     if( FeatureManager::FeatureSupported( KFeatureIdffContactsMycard ) )
@@ -155,26 +156,19 @@
 	PRINT ( _L("Enter CPcsContactStore::~CPcsContactStore") );
 	
 	delete iContactViewBase;
-	iContactViewBase = NULL;
-	
 	delete iSortOrder;
-	iSortOrder = NULL;
-	
-    delete iSimContactItems;
-    iSimContactItems = NULL ;
-     
+    delete iSimContactItems;   
 	delete iWait;
-	iWait = NULL;
-	
 	delete iUri;
-	iUri = NULL;
 	
 	iTimer.Cancel();
     iTimer.Close();
 	iFieldsToCache.Close();	
 	
 	iFs.Close();
-	
+
+	iInitialContactLinks.ResetAndDestroy();
+    
 	if(IsActive())
 	{
 		Deque();
@@ -185,7 +179,6 @@
 	PRINT ( _L("End CPcsContactStore::~CPcsContactStore") );
 }
 
-
 // ---------------------------------------------------------------------------------
 // Handles addition/deletion/modification of contacts
 // ---------------------------------------------------------------------------------
@@ -193,43 +186,36 @@
                 TVPbkContactStoreEvent aStoreEvent)
 {
    	PRINT ( _L("Enter CPcsContactStore::HandleStoreEventL") );
-
-	switch (aStoreEvent.iEventType) 
-	{
+   	
+    PRINT2 ( _L("CPcsContactStore::HandleStoreEventL: URI=%S, event TVPbkContactStoreEventType::%d received"),
+             &*iUri, aStoreEvent.iEventType);
+   	        
+    switch (aStoreEvent.iEventType) 
+    {
 		case TVPbkContactStoreEvent::EContactAdded:
+        case TVPbkContactStoreEvent::EGroupAdded:
 		{
-		    PRINT ( _L("Add contact/group event received") );
-		    
 		    // Observer will be notified once the cache update is complete
 		    iOngoingCacheUpdate = ECacheUpdateContactAdded;
 		                    
 		    iContactManager->RetrieveContactL( *(aStoreEvent.iContactLink), *this );
 			break;
 		}
-		
+
         case TVPbkContactStoreEvent::EUnknownChanges:
-            {
-            iObserver->RemoveAll( *iUri );
+        {
+            iObserver->RemoveAll( *iUri );      
+            // To indicate that contact view is not ready when unknown changes happens 
             iContactViewReady = EFalse;
             iContactViewBase->AddObserverL(*this);
-            }
             break;
+        }
 
 		case TVPbkContactStoreEvent::EContactDeleted:
+        case TVPbkContactStoreEvent::EGroupDeleted:
 		case TVPbkContactStoreEvent::EContactChanged:
-		case TVPbkContactStoreEvent::EGroupDeleted:
 		case TVPbkContactStoreEvent::EGroupChanged:
 		{
-		    if ( aStoreEvent.iEventType == TVPbkContactStoreEvent::EContactChanged ||
-		         aStoreEvent.iEventType == TVPbkContactStoreEvent::EGroupChanged ) 
-		    {
-		    	PRINT ( _L("Change contact/group event received") );
-		    }
-		    else 
-		    {
-		    	PRINT ( _L("Delete contact/group event received") );
-		    }
-			
 			CVPbkContactIdConverter* converter = NULL;
 			
 		    TRAPD ( err, converter = CVPbkContactIdConverter::NewL( aContactStore ) );
@@ -295,83 +281,97 @@
 }
 
 // ---------------------------------------------------------------------------
+//  Check next state of state machine for contacts retrieval and perform
+//  transition
+// --------------------------------------------------------------------------- 
+void CPcsContactStore::CheckNextState()
+{
+    PRINT5 ( _L("CPcsContactStore::CheckNextState(state %d) %d:(%d..%d)/%d"),
+             iNextState, iVPbkCallbackCount,
+             iFetchBlockLowerNumber, iFetchBlockUpperNumber, iInitialContactCount );
+
+    if ( iNextState == EComplete )
+    {
+        return;
+    }
+
+    // If during the caching of the contacts initially in the view we get some
+    // contact events for other contact operations from the user, then it can
+    // happen at the end of the caching process that iCallbackCount > iAllContactLinksCount.
+    // We assume that it can never be that at the end of the caching it results
+    // iCallbackCount < iAllContactLinksCount.
+
+    // Check if caching is complete
+    if( iFetchBlockUpperNumber == iInitialContactCount       // All contacts initially in the view were fetched
+        && iVPbkCallbackCount >= iInitialContactCount )        // We got at least the same amount of callbacks
+    {
+        iObserver->UpdateCachingStatus(*iUri, ECachingComplete);
+        iNextState = EComplete;
+        IssueRequest( 0 );
+    }
+    // We could have a number of callbacks that is the same of the fetched contacts
+    // from the view even before we get the all the callbacks for the fetched contacts.
+    // This can happen for instance if a contact is added by the user.
+    // With the following condition it will happen just that the fetching of more
+    // contacts from the initial view is happening before all the callbacks for
+    // those are received.
+    else if ( iVPbkCallbackCount >= iFetchBlockUpperNumber ) // Fetch next block
+    {
+        iObserver->UpdateCachingStatus(*iUri, ECachingInProgress);
+        iNextState = EFetchContactBlock;
+        // Delay the next fetch since contact fetch is CPU intensive,
+        // this will give other threads a chance to use CPU
+        IssueRequest( KTimerInterval ); // 100 milliseconds
+    }
+    else
+    {
+    // Otherwise, just pass through.
+    }
+
+}
+
+// ---------------------------------------------------------------------------
 //  Callback Method. Called when one Retrieve operation is complete
 // --------------------------------------------------------------------------- 
 void CPcsContactStore::VPbkSingleContactOperationComplete(
         MVPbkContactOperationBase& aOperation, MVPbkStoreContact* aContact)
-{    
-    iFetchedContactCount++;
+{
+    PRINT ( _L("Enter CPcsContactStore::VPbkSingleContactOperationComplete") );
 
-			       
+    // We get this incremented even during add/del of contacts during caching
+    iVPbkCallbackCount++;
+    
 	// Handle the fetched contact....
 	TRAPD(err, HandleRetrievedContactL(aContact) );
 	if( err != KErrNone)
 	{
 		iObserver->UpdateCachingStatus(*iUri, err);
 	}
-	
+
 	MVPbkContactOperationBase* Opr = &aOperation;
 	if ( Opr )
 	{
 		delete Opr;
 		Opr = NULL;
 	}
-	
-	// Update the iNextState variable to proper state
-	if( iFetchedContactCount == iAllContactLinksCount )
-	{
-	    // Fetch complete
-	    // Update the caching status
-		iObserver->UpdateCachingStatus(*iUri, ECachingComplete);
-		iNextState = EComplete;
-		IssueRequest();
-	}
-	else if ( (iFetchedContactCount % KLinksToFetchInOneGo) == 0 )
-	{
-	    // Fetch next block
-		iNextState = EFetchContactBlock;
-        // Delay the next fetch since contact fetch is CPU intensive,
-        // this will give other threads a chance to use CPU
-	    if(!IsActive())
-	        {
-            iTimer.After( iStatus, KTimerInterval); // 100 milliseconds
-            SetActive();
-	        }
 
-	}
-	
+	CheckNextState();
+
+    PRINT ( _L("End CPcsContactStore::VPbkSingleContactOperationComplete") );
 }
     
 // ---------------------------------------------------------------------------
-//  Callback Method.Called when one Retrieve operation fails.
+//  Callback Method. Called when one Retrieve operation fails.
 // ---------------------------------------------------------------------------
 void CPcsContactStore::VPbkSingleContactOperationFailed(
         MVPbkContactOperationBase& /*aOperation*/, TInt /*aError*/ )
 {
   	PRINT ( _L("Enter CPcsContactStore::VPbkSingleContactOperationFailed") );
-	iFetchedContactCount++;
+
+  	iVPbkCallbackCount++;
 
-	// Update the iNextState variable to proper state
-	if( iFetchedContactCount == iAllContactLinksCount )
-	{
-		// Fetch complete
-		iObserver->UpdateCachingStatus(*iUri, ECachingComplete);
-		iNextState = EComplete;
-		IssueRequest();
-	}
-	else if ( (iFetchedContactCount % KLinksToFetchInOneGo) == 0 ) 
-	{
-		// Fetch next block
-		iNextState = EFetchContactBlock;
-        // Delay the next fetch since contact fetch is CPU intensive,
-        // this will give other threads a chance to use CPU
-        if(!IsActive())
-            {
-            iTimer.After( iStatus, KTimerInterval); // 100 milliseconds
-            SetActive();
-            }
-	}
-	
+	CheckNextState();
+
 	PRINT ( _L("End CPcsContactStore::VPbkSingleContactOperationFailed") );
 }
 
@@ -399,10 +399,9 @@
         CleanupStack::PopAndDestroy( aContact );
         return;
     }
-   
+
 	CPsData* phoneContact = CPsData::NewL();
 
-	
 	// Fill the contact id
 	CVPbkContactIdConverter* converter = NULL;
 	TRAPD ( err, converter = CVPbkContactIdConverter::NewL( aContact->ParentStore() ) );
@@ -410,7 +409,7 @@
 	if ( err == KErrNotSupported )
 	{
 		// simdb domain
-		PRINT ( _L("SIM domain data received") );
+		PRINT ( _L("CPcsContactStore::HandleRetrievedContactL: SIM domain data received") );
 		
         // Set the contact link 
         HBufC8* extnInfo = tmpLink->PackLC();
@@ -519,13 +518,11 @@
 void CPcsContactStore::GetDataForSingleContactL( MVPbkBaseContact& aContact,
                                                  CPsData* aPhoneData )
 {      
-
     for(TInt i =0; i < iFieldsToCache.Count(); i++)
     {
 	    aPhoneData->SetDataL(i, KNullDesC);
 		AddContactFieldsL( aContact, iFieldsToCache[i], aPhoneData);			
     }
-	
 }
 
 // ---------------------------------------------------------------------------
@@ -587,27 +584,58 @@
 }
 
 // ---------------------------------------------------------------------------
+// Fetches all the initial contact links from vpbk 
+// --------------------------------------------------------------------------- 
+void CPcsContactStore::FetchAllInitialContactLinksL()
+{
+    PRINT2 ( _L("CPcsContactStore::FetchAllInitialContactLinksL: URI=%S. Fetching %d contact links"),
+             &*iUri, iInitialContactCount );
+
+    __LATENCY_MARK ( _L("CPcsContactStore::FetchAllInitialContactLinksL ==== fetch contact links start") );
+    
+    for(TInt cnt = 0; cnt < iInitialContactCount; cnt++)
+    {
+        // Get the contact link
+        MVPbkContactLink* tempLink = iContactViewBase->CreateLinkLC(cnt);
+        iInitialContactLinks.AppendL( tempLink );
+        CleanupStack::Pop();
+    }
+
+    __LATENCY_MARKEND ( _L("CPcsContactStore::FetchAllInitialContactLinksL ==== fetch contact links end") );                          
+
+    // No callback to wait for next state
+    iObserver->UpdateCachingStatus(*iUri, ECachingInProgress);
+    iNextState = EFetchContactBlock;
+    IssueRequest( 0 );
+}
+
+// ---------------------------------------------------------------------------
 // Fetches the data from the vpbk using the contact links 
 // --------------------------------------------------------------------------- 
-void CPcsContactStore::FetchlinksL()
-{		
-
-	PRINT1 ( _L("CPcsContactStore::Total contacts downloaded = %d"),
-	          iFetchedContactCount );
-	
-    TInt blockCount = iFetchedContactCount + KLinksToFetchInOneGo;
+void CPcsContactStore::FetchContactsBlockL()
+{
+    iFetchBlockLowerNumber = iFetchBlockUpperNumber;
+    iFetchBlockUpperNumber += KLinksToFetchInOneGo;
+    if ( iFetchBlockUpperNumber > iInitialContactCount )
+    {
+        iFetchBlockUpperNumber = iInitialContactCount;
+    }
     
-    if( blockCount >= iAllContactLinksCount)
-    	blockCount = iAllContactLinksCount;
-    
-	for(TInt cnt = iFetchedContactCount; cnt < blockCount; cnt++)
-	{	
-		// Retrieve the contact 
-		MVPbkContactLink* tempLink =iContactViewBase->CreateLinkLC(cnt);
-		iContactManager->RetrieveContactL( *tempLink, *this );
-		CleanupStack::PopAndDestroy(); // tempLink
-	}
+    PRINT2 ( _L("CPcsContactStore::FetchContactsBlockL: Fetched %d contacts, fetching more until %d"),
+             iFetchBlockLowerNumber, iFetchBlockUpperNumber );
 
+    for(TInt cnt = iFetchBlockLowerNumber; cnt < iFetchBlockUpperNumber; cnt++)
+    {
+        // Retrieve the contact
+        iContactManager->RetrieveContactL( *iInitialContactLinks[cnt], *this );
+    }
+
+    // Destroy the array of temporary contact links when all
+    // contacts from the initial view are retrieved
+    if (iFetchBlockUpperNumber == iInitialContactCount)
+    {
+        iInitialContactLinks.ResetAndDestroy();
+    }
 }
 
 // ---------------------------------------------------------------------------
@@ -617,37 +645,42 @@
                 MVPbkContactViewBase& aView ) 
 {
     PRINT ( _L("Enter CPcsContactStore::ContactViewReady") );
+
     iFs.Close();
     aView.RemoveObserver(*this);
     // Get the total number of contacts for this view
-    TRAPD(err,iAllContactLinksCount = aView.ContactCountL());
+    TRAPD(err, iInitialContactCount = aView.ContactCountL());
     
     if(err != KErrNone)
     {
-    	PRINT( _L("CPcsContactStore::ContactViewReady - Unable to obtain contact count"));
+    	PRINT( _L("CPcsContactStore::ContactViewReady: Unable to obtain Contacts count"));
+        iObserver->UpdateCachingStatus(*iUri, ECachingCompleteWithErrors);
     	iNextState = EComplete;
-   		IssueRequest();
+   		IssueRequest( 0 );
    		return;
     }
     
-    PRINT1 ( _L("Total number of contacts for this view: %d"), iAllContactLinksCount);
-    if( iAllContactLinksCount == 0)
+    PRINT1 ( _L("CPcsContactStore::ContactViewReady: Total number of contacts for this view: %d"),
+            iInitialContactCount );
+    if(iInitialContactCount == 0)
     {
-        // No Contactsb to cache, hence update the status accordingly
+        // No Contacts to cache, hence update the status accordingly
     	iObserver->UpdateCachingStatus(*iUri, ECachingComplete);
     	iNextState = EComplete;
-   		IssueRequest();
+   		IssueRequest( 0 );
    		return;
     }
-    iFetchedContactCount = 0;
+    iFetchBlockLowerNumber = 0;
+    iFetchBlockUpperNumber = 0;
+    iVPbkCallbackCount = 0;
     
     // Change the iNextState to fetch the contacts 
-    if( iContactViewReady == EFalse)
+    if(iContactViewReady == EFalse)
     {
     	iObserver->UpdateCachingStatus(*iUri, ECachingInProgress);
     	iContactViewReady = ETrue;
-    	iNextState = EFetchContactBlock;
-   		IssueRequest();
+    	iNextState = EFetchAllLinks;
+   		IssueRequest( 0 );
     }
 	
 	PRINT ( _L("End CPcsContactStore::ContactViewReady") );
@@ -657,22 +690,28 @@
 // Implements the view unavailable function of MVPbkContactViewObserver
 // --------------------------------------------------------------------------- 
 void CPcsContactStore::ContactViewUnavailable(
-                MVPbkContactViewBase& /*aView*/ )  
+         MVPbkContactViewBase& /*aView*/ )  
 {
     PRINT ( _L("Enter CPcsContactStore::ContactViewUnavailable") );
-    // Update the caching status to complete
+    PRINT1 ( _L("CPcsContactStore::ContactViewUnavailable: URI=%S"),
+             &*iUri );
+
+    // Update the caching status to cachingComplete, the client of PCS--Cmail can
+    // perform searching even when contactview of somestore is unavailable.
+    // For Contacts and Group view we get one of this event brfore ContactViewReady
 	iObserver->UpdateCachingStatus(*iUri, ECachingComplete);
     iFs.Close();
-	PRINT ( _L("End CPcsContactStore::ContactViewUnavailable") );
+
+    PRINT ( _L("End CPcsContactStore::ContactViewUnavailable") );
 }
 
 // ---------------------------------------------------------------------------
 // Implements the add contact function of MVPbkContactViewObserver
 // --------------------------------------------------------------------------- 
 void CPcsContactStore::ContactAddedToView(
-            MVPbkContactViewBase& /*aView*/, 
-            TInt /*aIndex*/, 
-            const MVPbkContactLink& /*aContactLink*/ ) 
+         MVPbkContactViewBase& /*aView*/, 
+         TInt /*aIndex*/, 
+         const MVPbkContactLink& /*aContactLink*/ ) 
 {
 }
 
@@ -680,9 +719,9 @@
 // Implements the remove contact function of MVPbkContactViewObserver
 // --------------------------------------------------------------------------- 
 void CPcsContactStore::ContactRemovedFromView(
-                MVPbkContactViewBase& /*aView*/, 
-                TInt /*aIndex*/, 
-                const MVPbkContactLink& /*aContactLink*/ )  
+         MVPbkContactViewBase& /*aView*/, 
+         TInt /*aIndex*/, 
+         const MVPbkContactLink& /*aContactLink*/ )  
 {
 }
 
@@ -690,10 +729,12 @@
 // Implements the view error function of MVPbkContactViewObserver
 // --------------------------------------------------------------------------- 
 void CPcsContactStore::ContactViewError(
-            MVPbkContactViewBase& /*aView*/, 
-            TInt /*aError*/, 
-            TBool /*aErrorNotified*/ )  
+         MVPbkContactViewBase& /*aView*/, 
+         TInt aError, 
+         TBool /*aErrorNotified*/ )  
 {
+    PRINT2 ( _L("CPcsContactStore::ContactViewError: URI=%S, Error=%d"),
+             &*iUri, aError );
 }
 
 // ---------------------------------------------------------------------------
@@ -702,13 +743,15 @@
 void CPcsContactStore::CreateContactFetchViewL()
 {
 	PRINT ( _L("Enter CPcsContactStore::CreateContactFetchViewL") );
+    PRINT1 ( _L("CPcsContactStore::CreateContactFetchViewL: URI=%S"),
+             &*iUri );
 	
 	// Create the view definition
     CVPbkContactViewDefinition* viewDef = CVPbkContactViewDefinition::NewL();
 	CleanupStack::PushL( viewDef );
 
-  // Create the View Name for the view
-  // The views are named as PCSView_<uri>		
+    // Create the View Name for the view
+    // The views are named as PCSView_<uri>		
 	HBufC* viewName = HBufC::NewL(KBufferMaxLen);
 	viewName->Des().Append(KPcsViewPrefix);
 	viewName->Des().Append(iUri->Des());
@@ -767,10 +810,9 @@
         CleanupStack::Pop(); // iContactViewBase
         CleanupStack::PopAndDestroy(sortOrder);	
         CleanupStack::PopAndDestroy(textbuffer);
-    
+
     	// Close the resouce File
-        iResourceFile.Close();                        
-	
+        iResourceFile.Close();
 	}
 	else if ( iUri->CompareC(KVPbkDefaultCntDbURI) == 0)
     {       
@@ -807,7 +849,7 @@
 			
 		// Set name for the view
 		viewDef->SetNameL( *viewName );	
-		__LATENCY_MARK ( _L("CPcsContactStore::CreateContactFetchViewL===== create view start") );
+		__LATENCY_MARK ( _L("CPcsContactStore::CreateContactFetchViewL ==== create view start") );
     	iContactViewBase = iContactManager->CreateContactViewLC( 
 		                         *this, 
 		                         *viewDef, 
@@ -841,18 +883,29 @@
 	
     switch( iNextState)
     {
-	   	case ECreateView :
-			CreateContactFetchViewL();
-		    break;
+        case ECreateView:
+            PRINT1 ( _L("CPcsContactStore::RunL(ECreateView): URI=%S. Create contact view to fetch data from store"),
+                     &*iUri );
+            CreateContactFetchViewL();
+            break;
+
+        case EFetchAllLinks:
+            PRINT1 ( _L("CPcsContactStore::RunL(EFetchAllLinks): URI=%S. Get all contact links in initial view"),
+                     &*iUri );
+            FetchAllInitialContactLinksL();
+            break;
    		
 	   	case EFetchContactBlock:
-	   		PRINT ( _L("Issuing the fetch request for next block") );
-			FetchlinksL();
+            PRINT4 ( _L("CPcsContactStore::RunL(EFetchContactBlock): URI=%S. Issuing fetch request for next block of max %d contacts (%d/%d fetched)"),
+                     &*iUri, KLinksToFetchInOneGo, iFetchBlockUpperNumber, iInitialContactCount);
+            FetchContactsBlockL();
 			break;
 	   	
 	   	case EComplete:
-		    PRINT ( _L("Contacts Caching FINISHED") );
-		    PRINT_BOOT_PERFORMANCE ( _L("Contacts Caching FINISHED") );
+		    PRINT3 ( _L("CPcsContactStore::RunL(EComplete): URI=%S. Contacts Caching FINISHED, (%d/%d contacts fetched)"),
+		             &*iUri, iFetchBlockUpperNumber, iInitialContactCount );
+		    PRINT1_BOOT_PERFORMANCE ( _L("CPcsContactStore::RunL(EComplete): URI=%S. Contacts Caching FINISHED"),
+		                              &*iUri );
 		    break;
     }
 }
@@ -862,11 +915,13 @@
 // ---------------------------------------------------------------------------------
 TInt CPcsContactStore::RunError(TInt /*aError*/) 
 {
-	PRINT ( _L(" Enter CPcsContactStore:: CPcsContactStore::RunError()") );
+	PRINT ( _L("Enter CPcsContactStore::RunError") );
 
-	PRINT1 ( _L(" CPcsContactStore:: RunError().  Completing caching in contacts store %S with status ECachingCompleteWithErrors "), &(iUri->Des()));
+	PRINT1 ( _L("CPcsContactStore::RunError(): URI=%S. Completing caching with status ECachingCompleteWithErrors"),
+	         &*iUri );
     iObserver->UpdateCachingStatus(*iUri, ECachingCompleteWithErrors);
- 	PRINT ( _L(" End CPcsContactStore:: CPcsContactStore::RunError()") );
+
+    PRINT ( _L("End CPcsContactStore::RunError") );
 	return KErrNone;
 }
 
@@ -908,15 +963,31 @@
 // ---------------------------------------------------------------------------------
 // Issues request to active object to call RunL method
 // ---------------------------------------------------------------------------------
-void CPcsContactStore::IssueRequest()
+void CPcsContactStore::IssueRequest( TInt aTimeDelay )
 {
-	TRequestStatus* status = &iStatus;
-	User::RequestComplete( status, KErrNone );
-	SetActive();
+    if( IsActive() ) // cannot activate allready active object
+        return;
+
+    if ( 0 == aTimeDelay )
+    {
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+    }
+    else
+    {
+        PRINT1 ( _L("CPcsContactStore::IssueRequest: Applying delay of %d milliseconds"),
+                 aTimeDelay );
+
+        iTimer.After( iStatus, aTimeDelay);
+    }
+
+    SetActive();
 }
-// Creates a sort order depending on the fields specified in the cenrep
-// when calling this function pass the masterList (i.e list containing all the
-// vpbk fields)
+
+// ---------------------------------------------------------------------------------
+// Creates a sort order depending on the fields specified 
+// in the cenrep when calling this function pass the 
+// masterList (i.e list containing all the vpbk fields)
 // ---------------------------------------------------------------------------------
 void CPcsContactStore::CreateSortOrderL(const MVPbkFieldTypeList& aMasterList)
 {