// -----------------------------------------------------------------------------
// CSIPMessage::ReplaceHeadersL
// -----------------------------------------------------------------------------
//
EXPORT_C void 
CSIPMessage::ReplaceHeadersL (RPointerArray<CSIPHeaderBase>& aNewHeaders)
    {
    __ASSERT_ALWAYS (aNewHeaders.Count() > 0, User::Leave(KErrArgument));
    __ASSERT_ALWAYS (aNewHeaders[0] != 0, User::Leave(KErrArgument));
    
    RStringF name = aNewHeaders[0]->Name();
    for (TInt i=1; i < aNewHeaders.Count(); i++)
        {
        __ASSERT_ALWAYS (aNewHeaders[i] != 0, User::Leave(KErrArgument));
        __ASSERT_ALWAYS (name == aNewHeaders[i]->Name(),
                         User::Leave(KErrArgument));
        }

    TInt headerListIndex = FindHeaderListIndex (name);
    __ASSERT_ALWAYS (headerListIndex >= 0, User::Leave(KErrArgument));

    // Remove old headers
    TSglQueIter<CSIPHeaderBase> iter(iSIPHeaderListArray[headerListIndex]);
	while (iter)
		{
		CSIPHeaderBase* header = iter++;
		delete header;
		}
    iSIPHeaderListArray[headerListIndex].Reset();

    // Add new headers
    for (TInt j=0; j < aNewHeaders.Count(); j++)
        {
        iSIPHeaderListArray[headerListIndex].AddLast(*aNewHeaders[j]);
        }
    aNewHeaders.Reset();
    }
// -----------------------------------------------------------------------------
// CMCETestUIEngineProfileContainer::ConstructL
// -----------------------------------------------------------------------------
//
void CMCETestUIEngineProfileContainer::ConstructL()
	{
	iProfileRegistry = CSIPProfileRegistry::NewL( iSip, *this ); 

    // Instantiate and store all profiles
    RPointerArray<CSIPProfile> profiles;
    iProfileRegistry->ProfilesL( profiles );

    for ( TInt i = 0; i < profiles.Count(); ++i )
        {
        CMCETestUIEngineProfile* item = 
            CMCETestUIEngineProfile::NewL( profiles[i], iEngine );
        CleanupStack::PushL( item );
        User::LeaveIfError( iProfiles.Append( item ) );
        CleanupStack::Pop( item );
        }
     
    profiles.Reset();
    
    if ( MCETestUIEngineDefaultValues::TakeDefaultProfileIntoUse() )
        {
        TakeProfileIntoUseL( GetDefaultProfileL() );
        }
    
	}
// -----------------------------------------------------------------------------
// CCLFDefaultOperation::SortItemsL
// -----------------------------------------------------------------------------
//
void CCLFDefaultOperation::SortItemsL( RPointerArray<MCLFItem>& aItemArray )
{
    if( iSortingStyle )
    {
        RPointerArray<MCLFItem> array;
        CleanupClosePushL( array );
        RPointerArray<MCLFItem> array1;
        CleanupClosePushL( array1 );
        RPointerArray<MCLFItem>* undefinedItemArray = &array;
        RPointerArray<MCLFItem>* newUndefinedItemArray = &array1;

        SortItemsBySortingStyleL( aItemArray,
                                  *iSortingStyle,
                                  *undefinedItemArray );
        TInt lastAddedItemCount( aItemArray.Count() );
        TInt nextItemIndex( lastAddedItemCount );
        TCLFUndefinedItemPosition position(
            iSortingStyle->UndefinedItemPosition() );

        const TInt secondarySorterCount( iSortingStyleArray.Count() );
        for( TInt i = 0 ; i < secondarySorterCount ; ++i )
        {
            MCLFSortingStyle& sortingStyle = *iSortingStyleArray[i];

            newUndefinedItemArray->Reset();
            // sort undefined items
            SortItemsBySortingStyleL( *undefinedItemArray,
                                      sortingStyle,
                                      *newUndefinedItemArray );

            // append sorted items to aItemArray
            AppendItemsToArrayL( undefinedItemArray->Array(),
                                 aItemArray,
                                 position,
                                 nextItemIndex,
                                 lastAddedItemCount );


            position = sortingStyle.UndefinedItemPosition();

            // change pointers
            RPointerArray<MCLFItem>* tmp = undefinedItemArray;
            undefinedItemArray = newUndefinedItemArray;
            newUndefinedItemArray = tmp;
        }


        // copy rest undefined items to correct position
        AppendItemsToArrayL( undefinedItemArray->Array(),
                             aItemArray,
                             position,
                             nextItemIndex,
                             lastAddedItemCount );

        // close undefined arrays
        CleanupStack::PopAndDestroy( 2, &array );
    }
    // else no sorting
}
// ----------------------------------------------------------
// CSimplePresenceList::GetDocuments
// ----------------------------------------------------------
//
void CSimplePresenceList::GetDocuments( RPointerArray<MSimpleDocument>& aDocs )
    {
    aDocs.Reset();
    TInt size = iDocuments.Count();
    for ( TInt i = 0; i<size ; i++ )
        {
        (void)aDocs.Append( iDocuments[i] );
        }    
    }
// ----------------------------------------------------------
// CSimplePresenceList::GetSubLists
// ----------------------------------------------------------
//
void CSimplePresenceList::GetSubLists( RPointerArray<MSimplePresenceList>& aLists )
    {
    aLists.Reset();
    TInt size = iPresList.Count();
    for ( TInt i = 0; i<size ; i++ )
        {
        (void)aLists.Append( iPresList[i] );
        }     
    }
// -----------------------------------------------------------------------------
// CSvgTimeContainer::UserPlay
// Called to handle user/client generated play event
// -----------------------------------------------------------------------------
//
void CSvgTimeContainer::UserPlay()
    {

    
    if ( !iTimer )
        {
        // Check whether this time container has a parent
        // then we do not have to create the timer
        if ( !iIsParentTcPresent )
            {
            // Obtain the post order list of media elements 
             RPointerArray<CSvgElementImpl> lMediaEleList;
            lMediaEleList.Reset(); 
            
            CSvgElementImpl *handle = (CSvgElementImpl *)(iOwnerDoc->RootElement());
            
            //Parse postorderr only if there are media elements
            if(iTcTimedEntities.Count() > 1 )
            {
              iOwnerDoc->ParsePostOrderMediaElements( handle, lMediaEleList );    
            }
            
            
            // Rearrange as per Post order
            RearrangeTimedEntityList( lMediaEleList );
            
            // Done with the list
            lMediaEleList.Close();  
            
            TRAPD( lTimerCreateErr, iTimer = CSvgTimer::NewL( this ) );
            
            if ( lTimerCreateErr != KErrNone )
                {
                // Error Processing
                return;
                }
            
            iTimer->SetStartTime();
            
            // the current home time needs to be updated.
            if ( iOwnerDoc && iCurrentTime != 0 )
                {
                iCurrentTime = 0;
                iCurrentTick.iParentTcTick = 0;
                iCurrentTick.iRealTimeTick = 0;
                TSvgTimerEvent timeEvent( iCurrentTime );
                iOwnerDoc->Reset( &timeEvent );
                }            

            if ( !iTimer->IsActive() )
                {
                iTimer->After( 1000 );
                }           
            }
        }
    }
void CRecognizerContainer::StopDisplay()
{
	CALLSTACKITEM_N(_CL("CRecognizerContainer"), _CL("StopDisplay"));

	if (owns_bitmap) delete iBitmap; iBitmap=0;
	delete iVCS; iVCS=0;
	delete iCurrentCodeInfo; iCurrentCodeInfo=0;
	iCurrentCodeArray->Reset();
	iStandByLabel->MakeVisible(ETrue);
	DrawDeferred();
}
// -----------------------------------------------------------------------------
// CSIPProfileRegistryBase::StoreProfileL
// -----------------------------------------------------------------------------
//
void CSIPProfileRegistryBase::StoreArrayL(
	RPointerArray<CSIPConcreteProfile>& aProfiles,
	RPointerArray<CSIPProfile>& aRetProfiles)
	{
	int count = aProfiles.Count();

	for (TInt i = 0; i < count; i++)
		{
		TUint profileId = (aProfiles[0])->Id();
		TInt index = ProfileIndex(profileId);
		
		CSIPProfileCleanupItem* cleanupItem = new (ELeave) CSIPProfileCleanupItem(iITC);
		CleanupStack::PushL(cleanupItem);

		if(index == KErrNotFound) 
			{
			CleanupStack::PushL(TCleanupItem(CrashRevert, cleanupItem));

			cleanupItem->iProfileId = (aProfiles[0])->Id();
			cleanupItem->iConcreteProfile = aProfiles[0];
			aProfiles.Remove(0);

			StoreProfileL(cleanupItem);
			User::LeaveIfError(aRetProfiles.Append(cleanupItem->iManagedProfile));
			}
		else
			{
			CleanupStack::PushL(TCleanupItem(LocalCrashRevert, cleanupItem));

			CSIPProfileItem* item = ProfileItemL(profileId);
			CSIPProfile* managed = NewInstanceL();
			cleanupItem->iManagedProfile = managed;
			managed->SetConcreteProfile(&(item->ConcreteProfile()));
			managed->SetEnabled(item->IsEnabled());
			item->IncrementReferenceCountL(*managed);
			User::LeaveIfError(aRetProfiles.Append(managed));
			CSIPConcreteProfile* profileNotUsed = aProfiles[0];
			aProfiles.Remove(0);
			delete profileNotUsed;
			}
		}
	aProfiles.Reset();

	for (TInt j = 0; j < count; j++)
		{
		CleanupStack::Pop(); //TCleanupItem
		CleanupStack::PopAndDestroy(); //cleanupItem
		}
	}
/**
Returns an array containing the MetaDataEntry for the given audio clip

@param  aMetaArray
        The meta data Array

@leave	Leaves with KErrNotFound if the meta data entry does not exist or
		KErrNotSupported if the controller does not support meta data 
		information for this format. Other errors indicate more general system
		failure.
*/
EXPORT_C void CMVSAudioPlayAgent::GetMetaArrayL(RPointerArray<CMMFMetaDataEntry>& aMetaArray)
	{
	//Reset the meta array
    aMetaArray.Reset();
	//Find how many elements there are to obtain
	TInt noMetaEntries = 0;
    TInt err = iPlayer->GetNumberOfMetaDataEntries(noMetaEntries);
    if(err == KErrNone)
	    {
	    //Add the elements, one at a time.
	    for(TInt counter = 0; counter < noMetaEntries; ++counter)
	         {
	         aMetaArray.Append(iPlayer->GetMetaDataEntryL(counter));
	         }	
	    }
	User::LeaveIfError(err);	
	}
void CDummyCalendarApp::ExtractNonExistentEntryL()
	{
	RPointerArray<CCalEntry> entryArray;
	CleanupStack::PushL(TCleanupItem(ResetAndDestroyCalEntryArray, &entryArray));
	
	// Passing string type UID parameter and expecting entryArray to be empty
	iEntryView->FetchL( _L8("myuid"), entryArray);
	test(entryArray.Count() == 0);
	entryArray.Reset();
	
	// Passing integer type UID parameter and expecting entryArray to be empty
	iEntryView->FetchL( _L8("10"), entryArray);
	test(entryArray.Count() == 0);
	
	CleanupStack::Pop(); // TCleanupItem(ResetAndDestroyCalEntryArray, &entryArray)
	entryArray.ResetAndDestroy();
	}
// -----------------------------------------------------------------------------
// CSvgTimeContainer::AddTimedEntityL
// Add a timed entity to the time container.
// -----------------------------------------------------------------------------
//
void CSvgTimeContainer::AddTimedEntityL( 
    MSvgTimedEntityInterface* aTimedEntity )
    {
    if ( !aTimedEntity )
        {
        User::Leave( KErrArgument );
        }
    
    // check to see if entity is already in list and simply return
    TInt lTimedEntityListCnt = iTcTimedEntities.Count();
    for ( TInt lItemIndex = lTimedEntityListCnt - 1; lItemIndex >= 0 ; lItemIndex-- )
        {
        if ( (iTcTimedEntities[ lItemIndex ]).iTimedEntity == aTimedEntity )
            {
            return;
            }
        }
   
    TSvgTimedEntityListItem lListItem;
    lListItem.iTimedEntity = aTimedEntity;

    //Media State initially Idle
    lListItem.iMediaState = ESvgMediaIdle;
    
    //User state initially is running
    lListItem.iUserState =ESvgUserRunning ;
    
    // Sync State is Playing
    lListItem.iIsSyncPaused = EFalse;

    // Append to Timed Entity List
    iTcTimedEntities.AppendL( lListItem );
    
    // Obtain the post order list of media elements 
     RPointerArray<CSvgElementImpl> lMediaEleList;
    lMediaEleList.Reset(); 
    
    CSvgElementImpl *handle = (CSvgElementImpl *)(iOwnerDoc->RootElement());
    iOwnerDoc->ParsePostOrderMediaElements( handle, lMediaEleList );
    
    // Rearrange as per Post order
    RearrangeTimedEntityList( lMediaEleList );
    
    // Done with the list
    lMediaEleList.Close();  
    }
/**
 * Parse a file with base64 encoding.
 * 
 * @param aFile filename to be read in.
 * @param aUrl  ???  //DEBUG
 * @param aOutput name out output file.
 */ 
void CMultipartTestContainer::ParseFileL( const TDesC& aFile,
                                          const TDesC& aUrl,
                                          const TDesC& aOutput )
    {
    // body
    HBufC8* data = ReadFileLC( aFile );
    // content type
    _LIT8(KMultipartMixed, "multipart/mixed");
    // boundary
    _LIT8(KBoundary1, "KBoundary");
    // body part array
    RPointerArray<CBodyPart> bodyPartArray;  

    // parse
		TInt err;
    if( aUrl.Ptr() )
        {
        TRAP( err, MultipartParser::ParseL( *data, KMultipartMixed, KBoundary1, aUrl, bodyPartArray ) );
        }
    else
        {
        TRAP( err, MultipartParser::ParseL( *data, KMultipartMixed, KBoundary1, aFile, bodyPartArray ) );
        }
	if (err != KErrNone)
		{
		INFO_PRINTF1(_L("Error parsing file."));
		}			

    // output
    WriteFileL( aOutput, bodyPartArray);

    // clean up memory
    CleanupStack::PopAndDestroy(); // data
    // clean up body part array and its content
    TInt size = bodyPartArray.Count();
    TInt i;
    for (i = 0; i < size; i++)
        {
        delete bodyPartArray[i];
        }
    bodyPartArray.Reset();
    }
/**
* Update entries 
* Care is taken to ensure that updateL is not performed on the Child Entries
*/
void CTestCalInterimApiModifier::UpdateEntriesL()
	{
	RPointerArray<CCalEntry> updatedEntries;
	CleanupStack::PushL(TCleanupItem(ResetAndDestroyEntryArray, &updatedEntries));
	const TInt KUidCount(iModifier->iEntryArray.Count());

	for (TInt j(0) ; j < KUidCount ; ++j)
		{
		RPointerArray<CCalEntry> calEntries;
		CleanupStack::PushL(TCleanupItem(ResetAndDestroyEntryArray, &calEntries));
		TCalTime recurrenceId = iModifier->iEntryArray[j]->RecurrenceIdL();
		TTime recurrenceIdInTTime = recurrenceId.TimeUtcL();
		TTime recurNullTime = Time::NullTTime();

		if(recurrenceIdInTTime != recurNullTime)
			{
			continue;
			}

		TPtrC8 desiredGuid(iModifier->iEntryArray[j]->UidL());
		iEntryView->FetchL(desiredGuid, calEntries);

		// update of entries can be performed only on the parent entry
		calEntries[0]->SetLastModifiedDateL();
		updatedEntries.Append(calEntries[0]);
		calEntries.Reset();
		CleanupStack::Pop(&calEntries);
		}
		
	TInt numSuccessful(0);
	iTestStep->INFO_PRINTF1(KModifyOperation);
	TRAPD(err, iEntryView->UpdateL(updatedEntries, numSuccessful));
	TESTL( numSuccessful == updatedEntries.Count() );
	if(err != KErrNone)
		{
		iTestStep->ERR_PRINTF2(KErrUpdateOperation,err);
		iTestStep->SetTestStepResult(EFail);
		}
	
	CleanupStack::PopAndDestroy(); //UpdateEntries
	}
void CSCOMOAdapterDb::GetEntryForServerIDL(RPointerArray<CAMDbItem>& aItemArray,
        TDesC8& aValue)
    {

    aItemArray.Reset();// first reset the array

    _LIT(KEqualToString,"='%S'");
    _LIT(KQuery, "SELECT * FROM %S WHERE %S");

    TBuf<256> serverid;
    serverid.Copy(aValue);

    TBuf<100> bufsql;
    bufsql.Append(KQuery);
    bufsql.Append(KEqualToString);
    TBuf<100> bufsql1;
    bufsql1.Format(bufsql, &KTableAMMgmtObject, &NCol4, &serverid);

    ReadItemsL(aItemArray, bufsql1);

    }
// ==========================================================================
// FUNCTION: InitializeL
// ==========================================================================
void CContainerStoreSearchHandler::InitializeL( TMsgStoreSearchCmdParams& aCmdParams, 
                                                RArray<TContainerId>&     aFolderIds, 
                                                RPointerArray<HBufC8>&    aPropertyNames )
    {
    iSearchParams = aCmdParams;
    
    iFolderIds.Reset();
    for( TInt i = 0 ; i < aFolderIds.Count() ; i++ )
        {
        iFolderIds.AppendL( aFolderIds[i] );
        }

    iPropertyNames.ResetAndDestroy();
    for ( TInt i = 0 ; i < aPropertyNames.Count() ; i++ )
        {
        iPropertyNames.AppendL( aPropertyNames[i] );
        }
    aPropertyNames.Reset();
    
    delete iSortResultSet;
    iSortResultSet = NULL;
    }
// -----------------------------------------------------------------------------
// SortItemsBySortingStyleL
// sort aItemArray with aSortingStyle
// add undefined items to aUndefinedItemArray
// -----------------------------------------------------------------------------
//
void SortItemsBySortingStyleL( RPointerArray<MCLFItem>& aItemArray,
                               MCLFSortingStyle& aSortingStyle,
                               RPointerArray<MCLFItem>& aUndefinedItemArray )
{
    RArray<TCLFFieldId> sortingFields;
    CleanupClosePushL( sortingFields );
    aSortingStyle.GetFieldsL( sortingFields );
    const TInt sortingFieldsCount( sortingFields.Count() );
    if( sortingFieldsCount )  // sort only if there are sorting fields
    {
        TCLFItemDataType sortingDataType( aSortingStyle.SortingDataType() );

        RArray<TCLFSortingItem> sortingArray;
        CleanupClosePushL( sortingArray );
        MakeSortingItemsL( sortingArray,
                           aUndefinedItemArray,
                           aItemArray.Array(),
                           sortingFields.Array(),
                           sortingDataType );

        SortSortingItemsL( sortingArray, sortingDataType );

        aItemArray.Reset();
        if( aSortingStyle.Ordering() == ECLFOrderingAscending )
        {
            AppendSortingItemsToArrayL( sortingArray.Array(),
                                        aItemArray );
        }
        else
        {
            AppendSortingItemsToArrayReverseL( sortingArray.Array(),
                                               aItemArray );
        }

        CleanupStack::PopAndDestroy( &sortingArray ); // sortingArray.Close
    }
    CleanupStack::PopAndDestroy( &sortingFields ); // sortingFields.Close
}
//----------------------------------------------------------------
// CLbsLocMonitorConversionHandler::CacheLookupL
// (other items were commented in a header).
//----------------------------------------------------------------
TBool CLbsLocMonitorConversionHandler::CacheLookupL()
    {
    iCachePartialResults.Reset();
    // Does NOT own contents
    iSubsetLocationInfoArray.Reset();
    TInt infoCount = iLocationInfoArray.Count();
    // We only do lookups if the client wants a position
    if(iRequestedInfo != ELbsConversionOutputPosition)
        {
        // copy all into subset array, the cache has solved nothing
        for(TInt i = 0; i < infoCount; i++)
            {
            iSubsetLocationInfoArray.AppendL(iLocationInfoArray[i]);
            }
        return EFalse;
        }
    
    TInt cacheLoads = 0;
    TBool resolved = EFalse;
    

    for(TInt i=0; i < infoCount; i++)
        {
        CLbsLocationInfo* locationInfo = static_cast<CLbsLocationInfo*>(iLocationInfoArray[i]);
        RLbsAreaInfoBaseArray areaArray;
        CleanupStack::PushL(TCleanupItem(*CleanUpResetAndDestroy, &areaArray));
        // NOTE! When locmonitor is expanded to cache wlan etc. this call must be changed! 
		// Currently we know about GSM and 3g (WCDMA).
        locationInfo->GetAreaInfoL(areaArray, CLbsLocationInfo::ELbsGsmInfo|CLbsLocationInfo::ELbsWcdmaInfo);
        
        TInt areaCount = areaArray.Count();
        TBool saved = EFalse;
        
        TRealX nan;
        nan.SetNaN();
        TLocality partialLocality;
        partialLocality.SetCoordinate(nan, nan, nan);
        partialLocality.SetAccuracy(nan, nan);
        
        for (TInt j = 0; j < areaCount; j++)
            {   
            resolved = EFalse;
            TLbsAreaInfoClassType type = areaArray[j]->Type();
            TLbsLocMonitorAreaInfoGci areaInfoGci;
            switch(type)
                {
                case ELbsAreaGsmCellInfoClass:
                    {
                    CLbsGsmCellInfo* area = static_cast<CLbsGsmCellInfo*>(areaArray[j]);
                    areaInfoGci.iMcc = area->MobileCountryCode();
                    areaInfoGci.iMnc = area->MobileNetworkCode();
                    areaInfoGci.iLac = area->LocationAreaCode();
                    areaInfoGci.iCid = area->CellId();
                    areaInfoGci.iValidity = ETrue;
                    areaInfoGci.iIs3gNetworkMode = EFalse;
                    
                    resolved = ETrue;
                    break;
                    }

                case ELbsAreaWcmdaCellInfoClass :
                    {
                    CLbsWcdmaCellInfo* area = static_cast<CLbsWcdmaCellInfo*>(areaArray[j]);
                    areaInfoGci.iMcc = area->MobileCountryCode();
                    areaInfoGci.iMnc = area->MobileNetworkCode();
                    areaInfoGci.iLac = area->LocalAreaCode();
                    areaInfoGci.iCid = area->UniqueCellId();
                    areaInfoGci.iValidity = ETrue;
                    areaInfoGci.iIs3gNetworkMode = ETrue;
                    
                    resolved = ETrue;
                    break;
                    }

                default:
                    {
                    resolved = EFalse;
                    break;
                    }
                }
            
            if(resolved && !saved)
                {
                TPosition position;
                RPointerArray<TLbsLocMonitorAreaInfoBase> outArray;
                outArray.Append(&areaInfoGci);
                TPositionAreaExtendedInfo matchLevel; 
                matchLevel.SetArea(TPositionAreaInfo::EAreaUnknown);
                TRequestStatus status; 
                // Cache gets are fast and not really asynch, so no harm in blocking here
                TInt ret = iCache.GetPosition(position,outArray,matchLevel,status);
                if((ret == KErrNone) || (ret == KErrNotFound))
                    {
                    User::WaitForRequest(status);
                    }
                outArray.Reset();
                
                if((ret == KErrNone) && (matchLevel.Area()  >= TPositionAreaExtendedInfo::EAreaCity))
                    {
                    TLocality locality;
                    locality.SetCoordinate(position.Latitude(), position.Longitude(),
								position.Altitude());
                	TRealX nan;
                	nan.SetNaN();
                    locality.SetAccuracy(AccuracyFromMatchLevel(matchLevel.Area()), nan);
                    
                    CLbsPositionInfo* positionInfo = CLbsPositionInfo::NewL(locality);
                    CleanupStack::PushL(positionInfo);
                    iLocationInfoArray[i]->AddAreaInfoL(positionInfo);
                    CleanupStack::Pop(positionInfo);
                    saved = ETrue;
                    cacheLoads++;
                    }
                else if ((ret == KErrNone) && (matchLevel.Area()  > TPositionAreaExtendedInfo::EAreaUnknown))
                    {
                    // we also store partial matches in case they are better than the plugin response
                    partialLocality.SetCoordinate(position.Latitude(), position.Longitude(),
                                position.Altitude());
                    TRealX nan;
                    nan.SetNaN();
                    partialLocality.SetAccuracy(AccuracyFromMatchLevel(matchLevel.Area()), nan);
                    }

                }
            }
        if(!saved)
            {
            //copy into subset array, we couldn't solve this from cache
            iSubsetLocationInfoArray.AppendL(iLocationInfoArray[i]);
            
            iCachePartialResults.AppendL(partialLocality);
            }
        CleanupStack::PopAndDestroy(&areaArray);
        }
    // If we've loaded as many results from the cache as there are requests 
    // then we have fully satisfied the query
    return cacheLoads == infoCount;
    }
//----------------------------------------------------------------
// CLbsLocMonitorConversionHandler::CacheSaveL
// (other items were commented in a header).
//----------------------------------------------------------------
TBool CLbsLocMonitorConversionHandler::CacheSaveL()
    {
    iState = EStateCacheSave;
    TBool saveRequested = EFalse;
    TInt infoCount = iSubsetLocationInfoArray.Count();
    while((iSavedToCacheCount < infoCount) && !saveRequested)
        {
        CLbsLocationInfo* locationInfo = static_cast<CLbsLocationInfo*>(iSubsetLocationInfoArray[iSavedToCacheCount]);
        
        RLbsAreaInfoBaseArray cellArray;
        CleanupStack::PushL(TCleanupItem(*CleanUpResetAndDestroy, &cellArray));
        locationInfo->GetAreaInfoL(cellArray, CLbsLocationInfo::ELbsGsmInfo | CLbsLocationInfo::ELbsWcdmaInfo);
        
        RLbsAreaInfoBaseArray locationArray;
        CleanupStack::PushL(TCleanupItem(*CleanUpResetAndDestroy, &locationArray));
        locationInfo->GetAreaInfoL(locationArray, CLbsLocationInfo::ELbsPosInfo);
        
        
        // We should get only 1 pos back but may have passed in multiple cells
        // We want to save that pos against all cells
        if((locationArray.Count() > 0) && (cellArray.Count() > 0))
            {
            CLbsPositionInfo* location = static_cast<CLbsPositionInfo*>(locationArray[0]);
            TLocality locality;
            location->GetLocality(locality);
            // Only locations that have an accuracy that is better than a cell
            // location code will be saved in the cache
            if(locality.HorizontalAccuracy() < KCellLocationAccuracy)
                {
                for(TInt i = 0; i < cellArray.Count(); i++)
                    {
					TLbsLocMonitorAreaInfoGci areaInfoGci;
					if (cellArray[i]->Type() == ELbsAreaGsmCellInfoClass)
						{
						CLbsGsmCellInfo* cell = static_cast<CLbsGsmCellInfo*>(cellArray[i]);
						areaInfoGci.iMcc = cell->MobileCountryCode();
						areaInfoGci.iMnc = cell->MobileNetworkCode();
						areaInfoGci.iLac = cell->LocationAreaCode();
						areaInfoGci.iCid = cell->CellId();
                        areaInfoGci.iValidity = ETrue;
						areaInfoGci.iIs3gNetworkMode = EFalse;
						}
					else 
						{ 
						// by elimination type must be ELbsAreaWcmdaCellInfoClass!
						CLbsWcdmaCellInfo* cell = static_cast<CLbsWcdmaCellInfo*>(cellArray[i]);

						// If we don't have a valid LAC (which may happen with WCDMA) then we cannot
						// save to the cache and we should go to the next cell immediately.
						if (cell->LocalAreaCode() == -1)
							continue;
						areaInfoGci.iMcc = cell->MobileCountryCode();
						areaInfoGci.iMnc = cell->MobileNetworkCode();
						areaInfoGci.iLac = cell->LocalAreaCode();
						areaInfoGci.iCid = cell->UniqueCellId();
						areaInfoGci.iValidity = ETrue;
						areaInfoGci.iIs3gNetworkMode = ETrue;
						}

                    RPointerArray<TLbsLocMonitorAreaInfoBase> areaArray;
                    areaArray.Append(&areaInfoGci);
                    TTime now;
                    now.HomeTime();
                    TPosition pos(locality, now);
                    TInt ret = iCache.SavePosition(pos, areaArray, EFalse, iStatus);
                    if(ret != KErrNone)
                        {
                        saveRequested = EFalse;
                        }
                    else
                        {
                        saveRequested = ETrue;
                        SetActive();
                        }
                    areaArray.Reset();
                    }            
                }
            }
        CleanupStack::PopAndDestroy(&locationArray);
        CleanupStack::PopAndDestroy(&cellArray);
        iSavedToCacheCount++;
        }
    if((iSavedToCacheCount >= infoCount) && !saveRequested)
        {
        return ETrue;
        }
    return EFalse;
    }
void CRecognizerContainer::ShowCodes(const TRect& aDrawRect, const TSize& aBmpSize) const
{
	CALLSTACKITEM_N(_CL("CRecognizerContainer"), _CL("ShowCodes"));

	RPointerArray<CCodeInfo>* Codes=0;
	TInt CurrentCode; bool draw_rect=true;
	if (!iVCS || iVCS->GetCodes() == NULL || iVCS->GetCodes()->Count()==0 || iInvalid) {
		if (!iCurrentCodeInfo) return;
		iCurrentCodeArray->Reset();
		User::LeaveIfError(iCurrentCodeArray->Append(iCurrentCodeInfo));
		Codes=iCurrentCodeArray;
		CurrentCode=0;
		if (iVCS || iInvalid) draw_rect=false;
	} else {
		Codes=iVCS->GetCodes();
		CurrentCode=iCurrentCode;
	}

	TInt xd = aDrawRect.iTl.iX;
	TInt yd = aDrawRect.iTl.iY;
	TInt hd = aDrawRect.Height();
	TInt wd = aDrawRect.Width();

	TInt hi = aBmpSize.iHeight;
	TInt wi = aBmpSize.iWidth;

	CWindowGc& gc = SystemGc();
	gc.SetPenStyle(CGraphicsContext::ESolidPen);

	TInt n = Codes->Count();

	// draw frames around the codes

	if (draw_rect) {
		for (TInt i = 0; i < n; i++) {
			CCodeInfo* ci = (*Codes)[i];

			gc.SetPenColor(ci->IsCodeValid() ? KRgbYellow : KRgbRed);
			gc.SetPenSize(i != CurrentCode ? TSize(1,1) : TSize(2,2));

			TPoint rb = ci->GetImageCoordinates(TPoint(10,10));

			gc.DrawLine(TPoint(xd + rb.iX*wd/wi, yd + rb.iY*hd/hi), 
						TPoint(xd + ci->x2*wd/wi, yd + ci->y2*hd/hi));
			gc.DrawLine(TPoint(xd + rb.iX*wd/wi, yd + rb.iY*hd/hi), 
						TPoint(xd + ci->x4*wd/wi, yd + ci->y4*hd/hi));
			gc.DrawLine(TPoint(xd + ci->x1*wd/wi, yd + ci->y1*hd/hi), 
						TPoint(xd + ci->x2*wd/wi, yd + ci->y2*hd/hi));
			gc.DrawLine(TPoint(xd + ci->x4*wd/wi, yd + ci->y4*hd/hi), 
						TPoint(xd + ci->x1*wd/wi, yd + ci->y1*hd/hi));
		}
	}

	gc.SetPenSize(TSize(1,1));

	// display value of current code

	if (CurrentCode >= 0 && CurrentCode < Codes->Count()) {
		CCodeInfo* ci = (*Codes)[CurrentCode];
		TBuf<64> info;

		// code value

		ci->code->AppendToString(info);
		gc.SetPenColor(KRgbYellow);
		gc.SetBrushStyle(CGraphicsContext::ENullBrush);
		const CFont* fontUsed = iEikonEnv->DenseFont();
		gc.UseFont(fontUsed);
		TInt baseline = aDrawRect.Height() - 2 * fontUsed->AscentInPixels();
		info.Copy(*iScreenMsgBuf);
		gc.DrawText(info, aDrawRect, baseline, CGraphicsContext::ECenter);

	}
}
void CTestCalIndexFileModifyEntryStep::ModifyEntryL()
	{
	TPtrC entryString;
	TBool readRes = EFalse;
	readRes = GetStringFromConfig(ConfigSection(), KModifyEntry, entryString);
	if (!readRes)
		{
		INFO_PRINTF1(_L("Error in CTestCalIndexFileModifyEntryStep::ModifyEntryL - entrytomodify not found in config file"));
		User::Leave(KErrNotFound);
		}
	CConfigTestEntryInfo* inf = new(ELeave)CConfigTestEntryInfo();
	CleanupStack::PushL(inf);
	ParseEntryStringL(*inf, entryString);
				
	//  see if we can find a match in the database using an instance view
		
		CCalProgress* progress = new(ELeave)CCalProgress;
		CleanupStack::PushL(progress);  
	
		CCalInstanceView* view = CCalInstanceView::NewL(*iSession, *progress);
		CleanupStack::PushL(view);
		
		CActiveScheduler::Start();
		
		CalCommon::TCalViewFilter filter = CalCommon::EIncludeAppts;
		switch (inf->iType)
			{
			case (CCalEntry::EAppt):
				filter = CalCommon::EIncludeAppts;
				break;
			case (CCalEntry::ETodo):
				filter = CalCommon::EIncludeCompletedTodos | CalCommon::EIncludeIncompletedTodos;
				break;
			case (CCalEntry::EEvent):
				filter = CalCommon::EIncludeEvents;
				break;
			case (CCalEntry::EReminder):
				filter = CalCommon::EIncludeReminder;
				break;
			case (CCalEntry::EAnniv):
				filter = CalCommon::EIncludeAnnivs;
				break;
			default:
				User::Leave(KErrCorrupt);
				break;
			}
		RPointerArray<CCalInstance> instances;
		CleanupClosePushL(instances);

		// look for instances between (startdate -1 day) and
		// (enddate + 1 day)
		TTimeIntervalDays oneDay(1);
		TTime beginTTime = (inf->iStartTime) - oneDay;
		TTime endTTime = (inf->iEndTime) + oneDay;
		TCalTime begin;
		begin.SetTimeUtcL(beginTTime);
		TCalTime end;
		end.SetTimeUtcL(endTTime);
		CalCommon::TCalTimeRange timerange(begin, end);	
		
		view->FindInstanceL(instances, filter, timerange);
		
		TInt counter = 0;
		TInt max = instances.Count();
		INFO_PRINTF2(_L("%d instances to compare against"),max);
		TBool found = EFalse;
		while ((found == EFalse) && (counter < max))
			{
			INFO_PRINTF2(_L("compare modify info to entry %d"), (counter+1));
			if (inf->CompareToEntryL((instances[counter])->Entry()))
				{
				INFO_PRINTF2(_L("Entry info matched instance %d"), (counter+1));
				found = ETrue;
				
				CCalProgress* progress1 = new(ELeave)CCalProgress;
				CleanupStack::PushL(progress1);  
				
				CCalEntryView* eView = CCalEntryView::NewL(*iSession, *progress);
				CleanupStack::PushL(eView);
				
				CActiveScheduler::Start();

				CCalEntry* eEntry = &((instances[counter])->Entry());
				eEntry->SetDescriptionL(KTCIModifiedText());
				RPointerArray<CCalEntry> eList;
				CleanupResetAndDestroyPushL(eList);
				eList.Reset();
				TInt numChanged = 0;
				eList.Append(eEntry);
				eView->UpdateL(eList, numChanged);
				if (numChanged != 1)
					{
					INFO_PRINTF1(_L("Error modifiying entry"));
					User::Leave(KErrGeneral);
					}
				CleanupStack::PopAndDestroy(&eList);
				CleanupStack::PopAndDestroy(2);
				}
			else
				{
				counter++;
				}
			}
		CleanupStack::PopAndDestroy(&instances);
		CleanupStack::PopAndDestroy(view);
		CleanupStack::PopAndDestroy(progress);
	
	CleanupStack::PopAndDestroy(inf);
	
	if (!found)
		{
		INFO_PRINTF1(_L("Could not find entrytomodify in database"));
		User::Leave(KErrNotFound);
		}
	}
TVerdict CTestCalInterimApiRichAlarmFormatStep::doTestStepL()
	{
	CActiveScheduler* scheduler = new(ELeave)CActiveScheduler;
	CleanupStack::PushL(scheduler);  
	CActiveScheduler::Install(scheduler);

	iSession  = CCalSession::NewL();
	
	CTestCalInterimApiCallbackForRichAlarms* alarmCallback = CTestCalInterimApiCallbackForRichAlarms::NewL(this);
	CleanupStack::PushL(alarmCallback); 

	OpenSessionFileL();
	iEntryView = CCalEntryView::NewL(*iSession,*alarmCallback);
	
	CActiveScheduler::Add(alarmCallback);
	CActiveScheduler::Start();
	
	//build the CCalDataExchange object and import
	CCalDataExchange* dataExchange = CCalDataExchange::NewL(*iSession);
	CleanupStack::PushL(dataExchange); 

	//IMPORT the calendar info from a known file
	RFs fs;
	fs.Connect();
	CleanupClosePushL(fs);
	RFile inFile;
	CleanupClosePushL(inFile);
	TInt errR = inFile.Open(fs, GetFullFileName(KEntryImportFile), EFileRead);
	RFileReadStream readStream(inFile);
	CleanupClosePushL(readStream);
	
	RPointerArray<CCalEntry> secondEntryArray;
	CleanupStack::PushL(TCleanupItem(CloseAndDeleteRPtrArrayEntries, &secondEntryArray));
	secondEntryArray.Reset();
	
	INFO_PRINTF1(KImporting);
	TInt index = 0;
	for (index = 0; index < KNumEntriesInFile; index++)
		{
		dataExchange->ImportL(KUidVCalendar, readStream, secondEntryArray);
		}
	
	CleanupStack::Pop(&secondEntryArray);
	CleanupStack::PopAndDestroy(&readStream);
	CleanupStack::PopAndDestroy(&inFile);
	CleanupStack::PushL(TCleanupItem(CloseAndDeleteRPtrArrayEntries, &secondEntryArray));

	SetTestStepResult(CompareAlarmDataL(&secondEntryArray));
	
	//Test for importing from a badly formatted file
	RFile badInFile;
	CleanupClosePushL(badInFile);
	TInt baddErr = badInFile.Open(fs, GetFullFileName(KEntryBadImportFile), EFileRead);
	RFileReadStream badStream(badInFile);
	CleanupClosePushL(badStream);
	
	RPointerArray<CCalEntry> badEntryArray;
	CleanupStack::PushL(TCleanupItem(CloseAndDeleteRPtrArrayEntries, &badEntryArray));
	badEntryArray.Reset();
	
	INFO_PRINTF1(KImporting);
	TInt i = 0;
	for (i = 0; i < 1; i++)
		{
		dataExchange->ImportL(KUidVCalendar, badStream, badEntryArray);
		}
	CCalEntry* pEntry = badEntryArray[0];
	CCalAlarm* pAlarm = pEntry->AlarmL();
	if (pAlarm)
		{
		CleanupStack::PushL(pAlarm);
		CCalContent* pContent = pAlarm->AlarmAction();
		if (pContent != NULL)
			{
			ERR_PRINTF1(KUnexpectedAlarmAction);
			SetTestStepResult(EFail);
			}
		delete pContent;
		CleanupStack::PopAndDestroy(pAlarm);
		}
	CleanupStack::PopAndDestroy(&badEntryArray);
	CleanupStack::PopAndDestroy(&badStream);
	CleanupStack::PopAndDestroy(&badInFile);

	
	CleanupStack::PopAndDestroy(5 , scheduler);

	return TestStepResult();
	}
EXPORT_C void T_LbsUtils::ResetAndDestroy_PosInfoArr(RPointerArray<TAny>& aPosInfoArr)
	{
		for (TInt i = 0; i < aPosInfoArr.Count(); ++i)
			delete aPosInfoArr[i];
		aPosInfoArr.Reset();	
	}