Add ..\dev\.. to path
authorjjkang
Tue, 29 Jun 2010 14:52:54 +0800
changeset 606 30b30f9da0b7
parent 605 122d2b873fd1
child 607 378360dbbdba
Add ..\dev\.. to path
bintools/checklib/group/checklib.mmp
bintools/checklib/group/checklib.mrp
bintools/checklib/group/release.txt
bintools/checklib/object/elf/elf_file_header.h
bintools/checklib/object/elf/elf_section_header.h
bintools/checklib/object/elf/elf_symbol.h
bintools/checklib/object/object.h
bintools/elftools/def2dll.pl
bintools/elftools/elftran/elf_dlld.cpp
bintools/elftools/elftran/elf_file.cpp
bintools/elftools/elftran/elf_imp.cpp
bintools/elftools/elftran/elf_tran.cpp
bintools/elftools/getexports/geninf.cpp
bintools/elftools/group/bld.inf
bintools/elftools/group/elftools.mrp
bintools/elftools/group/elftran.mmp
bintools/elftools/group/release.txt
bintools/elftools/inc/elfdll.h
bintools/elftools/inc/elffile.h
bintools/elftools/inc/elftran.h
bintools/evalid/dev_build_bintools_evalid.mrp
bintools/evalid/evalid.mrp
bintools/rcomp/group/BLD.INF
bintools/rcomp/group/RELEASE.TXT
bintools/rcomp/group/rcomp.mmp
bintools/rcomp/group/rcomp.mrp
bintools/rcomp/inc/VERSION.H
bintools/rcomp/inc/main.h
bintools/rcomp/src/NUMVAL.CPP
bintools/rcomp/src/RCBINSTR.CPP
bintools/rcomp/src/RCOMP.LEX
bintools/rcomp/src/RCOMP.YACC
bintools/rcomp/src/main.cpp
bintools/rcomp/src/rcomp.cpp
bintools/rcomp/src/rcompl.cpp
e32tools/e32lib/group/bld.inf
e32tools/e32lib/group/e32lib.mrp
e32tools/e32lib/group/release.txt
e32tools/e32lib/group/seclib.mmp
e32tools/e32lib/seclib/seclib.cpp
e32tools/e32lib/setcap/setcap.h
e32tools/elf2e32/group/elf2e32.mmp
e32tools/elf2e32/group/elf2e32.mrp
e32tools/elf2e32/group/release.txt
e32tools/elf2e32/include/h_ver.h
e32tools/elf2e32/source/deflatecompress.cpp
e32tools/elf2e32/source/e32imagefile.cpp
e32tools/elf2e32/source/e32imagefile.h
e32tools/elf2e32/source/elffilesupplied.cpp
e32tools/elf2e32/source/filedump.cpp
e32tools/elf2e32/source/imgdump.cpp
e32tools/elf2e32/source/parametermanager.cpp
imgtools/buildrom/group/BLD.INF
imgtools/buildrom/group/buildrom.mrp
imgtools/buildrom/group/release.txt
imgtools/buildrom/tools/CODESIZE.PL
imgtools/buildrom/tools/CONVERT.PL
imgtools/buildrom/tools/Dep_Lister.pm
imgtools/buildrom/tools/GenericParser.pm
imgtools/buildrom/tools/ImageContentHandler.pm
imgtools/buildrom/tools/buildrom.pl
imgtools/buildrom/tools/buildrom.pm
imgtools/buildrom/tools/cdfparser.pm
imgtools/buildrom/tools/datadriveimage.pm
imgtools/buildrom/tools/efficient_rom_paging.pm
imgtools/buildrom/tools/externaltools.pm
imgtools/buildrom/tools/featurefile.pm
imgtools/buildrom/tools/featuremanager.pm
imgtools/buildrom/tools/featureparser.pm
imgtools/buildrom/tools/features.pl
imgtools/buildrom/tools/features.pm
imgtools/buildrom/tools/featuresutil.pm
imgtools/buildrom/tools/spitool.pl
imgtools/buildrom/tools/spitool.pm
imgtools/imgcheck/group/bld.inf
imgtools/imgcheck/group/imgcheck.mmp
imgtools/imgcheck/group/imgcheck.mrp
imgtools/imgcheck/group/imgutils.mmp
imgtools/imgcheck/group/release.txt
imgtools/imgcheck/imagechekunittest/testcode/cmdlinehandletest.cpp
imgtools/imgcheck/inc/checker.h
imgtools/imgcheck/inc/cmdlinehandler.h
imgtools/imgcheck/inc/cmdlinewriter.h
imgtools/imgcheck/inc/common.h
imgtools/imgcheck/inc/dbgflagchecker.h
imgtools/imgcheck/inc/depchecker.h
imgtools/imgcheck/inc/exceptionimplementation.h
imgtools/imgcheck/inc/exceptionreporter.h
imgtools/imgcheck/inc/hash.h
imgtools/imgcheck/inc/imgcheckmanager.h
imgtools/imgcheck/inc/reporter.h
imgtools/imgcheck/inc/reportwriter.h
imgtools/imgcheck/inc/sidchecker.h
imgtools/imgcheck/inc/version.h
imgtools/imgcheck/inc/vidchecker.h
imgtools/imgcheck/inc/xmlwriter.h
imgtools/imgcheck/libimgutils/inc/dirreader.h
imgtools/imgcheck/libimgutils/inc/e32reader.h
imgtools/imgcheck/libimgutils/inc/imagereader.h
imgtools/imgcheck/libimgutils/inc/rofsreader.h
imgtools/imgcheck/libimgutils/inc/romfsentry.h
imgtools/imgcheck/libimgutils/inc/romreader.h
imgtools/imgcheck/libimgutils/inc/typedefs.h
imgtools/imgcheck/libimgutils/inc/utils.h
imgtools/imgcheck/libimgutils/src/dirreader.cpp
imgtools/imgcheck/libimgutils/src/e32reader.cpp
imgtools/imgcheck/libimgutils/src/imagereader.cpp
imgtools/imgcheck/libimgutils/src/rofsimage.cpp
imgtools/imgcheck/libimgutils/src/rofsreader.cpp
imgtools/imgcheck/libimgutils/src/romimageheader.cpp
imgtools/imgcheck/libimgutils/src/romreader.cpp
imgtools/imgcheck/libimgutils/src/utils.cpp
imgtools/imgcheck/src/checker.cpp
imgtools/imgcheck/src/cmdlinehandler.cpp
imgtools/imgcheck/src/cmdlinewriter.cpp
imgtools/imgcheck/src/common.cpp
imgtools/imgcheck/src/dbgflagchecker.cpp
imgtools/imgcheck/src/depchecker.cpp
imgtools/imgcheck/src/exceptionimplementation.cpp
imgtools/imgcheck/src/exceptionreporter.cpp
imgtools/imgcheck/src/hash.cpp
imgtools/imgcheck/src/imgcheckmanager.cpp
imgtools/imgcheck/src/main.cpp
imgtools/imgcheck/src/reporter.cpp
imgtools/imgcheck/src/sidchecker.cpp
imgtools/imgcheck/src/vidchecker.cpp
imgtools/imgcheck/src/xmlwriter.cpp
imgtools/imglib/compress/byte_pair.cpp
imgtools/imglib/compress/byte_pair.h
imgtools/imglib/compress/pagedcompress.cpp
imgtools/imglib/e32image/deflate/deflate.cpp
imgtools/imglib/e32image/e32image.cpp
imgtools/imglib/e32image/imgdump.cpp
imgtools/imglib/e32image/tr_main.cpp
imgtools/imglib/e32uid/e32uid.cpp
imgtools/imglib/e32uid/uidcrc.cpp
imgtools/imglib/group/bld.inf
imgtools/imglib/group/imglib.mrp
imgtools/imglib/host/h_file.cpp
imgtools/imglib/host/h_utl.cpp
imgtools/imglib/host/utf16string.cpp
imgtools/imglib/inc/e32image.h
imgtools/imglib/inc/h_utl.h
imgtools/imglib/inc/h_ver.h
imgtools/imglib/inc/pe_file.h
imgtools/imglib/memmap/include/memmap.h
imgtools/imglib/memmap/include/memmaputils.h
imgtools/imglib/memmap/source/memmap.cpp
imgtools/imglib/memmap/source/memmaputils.cpp
imgtools/imglib/parameterfileprocessor/include/parameterfileprocessor.h
imgtools/imglib/parameterfileprocessor/source/parameterfileprocessor.cpp
imgtools/imglib/patchdataprocessor/include/patchdataprocessor.h
imgtools/imglib/patchdataprocessor/source/patchdataprocessor.cpp
imgtools/romtools/group/BLD.INF
imgtools/romtools/group/readimage.mmp
imgtools/romtools/group/release.txt
imgtools/romtools/group/romtools.mrp
imgtools/romtools/maksym/fixupsym.pl
imgtools/romtools/maksym/hpsym.pl
imgtools/romtools/maksym/maksym.pl
imgtools/romtools/maksym/maksymrofs.pl
imgtools/romtools/readimage/inc/common.h
imgtools/romtools/readimage/inc/e32_image_reader.h
imgtools/romtools/readimage/inc/image_handler.h
imgtools/romtools/readimage/inc/image_reader.h
imgtools/romtools/readimage/inc/rofs_image_reader.h
imgtools/romtools/readimage/inc/rom_image_reader.h
imgtools/romtools/readimage/src/common.cpp
imgtools/romtools/readimage/src/e32_image_reader.cpp
imgtools/romtools/readimage/src/image_handler.cpp
imgtools/romtools/readimage/src/image_reader.cpp
imgtools/romtools/readimage/src/rofs_image_reader.cpp
imgtools/romtools/readimage/src/rom_image_reader.cpp
imgtools/romtools/rofsbuild/r_build.cpp
imgtools/romtools/rofsbuild/r_coreimage.cpp
imgtools/romtools/rofsbuild/r_coreimage.h
imgtools/romtools/rofsbuild/r_driveimage.cpp
imgtools/romtools/rofsbuild/r_driveimage.h
imgtools/romtools/rofsbuild/r_driveutl.cpp
imgtools/romtools/rofsbuild/r_driveutl.h
imgtools/romtools/rofsbuild/r_obey.cpp
imgtools/romtools/rofsbuild/r_obey.h
imgtools/romtools/rofsbuild/r_rofs.cpp
imgtools/romtools/rofsbuild/r_rofs.h
imgtools/romtools/rofsbuild/r_romnode.h
imgtools/romtools/rofsbuild/r_smrimage.cpp
imgtools/romtools/rofsbuild/r_smrimage.h
imgtools/romtools/rofsbuild/rofsbuild.cpp
imgtools/romtools/rofsbuild/rofsbuild.mmp
imgtools/romtools/rombuild/r_areaset.cpp
imgtools/romtools/rombuild/r_areaset.h
imgtools/romtools/rombuild/r_build.cpp
imgtools/romtools/rombuild/r_coreimage.cpp
imgtools/romtools/rombuild/r_coreimage.h
imgtools/romtools/rombuild/r_coreimagereader.cpp
imgtools/romtools/rombuild/r_coreimagereader.h
imgtools/romtools/rombuild/r_dir.cpp
imgtools/romtools/rombuild/r_dir.h
imgtools/romtools/rombuild/r_global.cpp
imgtools/romtools/rombuild/r_global.h
imgtools/romtools/rombuild/r_mromimage.h
imgtools/romtools/rombuild/r_obey.cpp
imgtools/romtools/rombuild/r_obey.h
imgtools/romtools/rombuild/r_rom.cpp
imgtools/romtools/rombuild/r_rom.h
imgtools/romtools/rombuild/r_srec.cpp
imgtools/romtools/rombuild/r_t_areaset.cpp
imgtools/romtools/rombuild/rombuild.cpp
imgtools/romtools/rombuild/rombuild.mmp
imgtools/romtools/rombuild/rombuild_mingw.mk
imgtools/sisutils/group/sisutils.mmp
imgtools/sisutils/group/sisutils.mrp
imgtools/sisutils/inc/pkgfileparser.h
imgtools/sisutils/inc/pkglanguage.h
imgtools/sisutils/inc/sis2iby.h
imgtools/sisutils/inc/sisutils.h
imgtools/sisutils/src/pkgfileparser.cpp
imgtools/sisutils/src/pkglanguage.cpp
imgtools/sisutils/src/sis2iby.cpp
imgtools/sisutils/src/sisutils.cpp
package_definition.xml
sbsv1/abld/e32util/createrfifile.pl
sbsv1/abld/e32util/efreeze.pl
sbsv1/abld/e32util/gendef.pl
sbsv1/abld/e32util/h2inc.pl
sbsv1/abld/e32util/makedef.pl
sbsv1/abld/e32util/omapsig.pl
sbsv1/abld/e32util/prepdef.pl
sbsv1/abld/genutil/listzip.pl
sbsv1/abld/group/bld.inf
sbsv1/abld/group/release.txt
sbsv1/abld/platform/sym_lkup_util.pl
srctools/tranasm/group/bld.inf
srctools/tranasm/group/tranasm.mrp
--- a/bintools/checklib/group/checklib.mmp	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/checklib/group/checklib.mmp	Tue Jun 29 14:52:54 2010 +0800
@@ -20,6 +20,7 @@
 userinclude     ..
 userinclude     ../object/coff
 userinclude 	../..
+systeminclude   ../../elftools/inc
 
 sourcepath      ..
 
--- a/bintools/checklib/group/checklib.mrp	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/checklib/group/checklib.mrp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,8 +1,8 @@
 component       dev_build_bintools_checklib
 
-source          /src/tools/dev/build/bintools/checklib
-exports         /src/tools/dev/build/bintools/checklib/group
-binary          /src/tools/dev/build/bintools/checklib/group all
+source          /src/tools/build/bintools/checklib
+exports         /src/tools/build/bintools/checklib/group
+binary          /src/tools/build/bintools/checklib/group all
 
 notes_source    release.txt
 
--- a/bintools/checklib/group/release.txt	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/checklib/group/release.txt	Tue Jun 29 14:52:54 2010 +0800
@@ -3,3 +3,8 @@
 
 NOTESRC_RELEASE_REASON
 Checklib Release
+
+version ??
+===============
+Released by Zheng Shen, 22/02/2010
+	1) DPDEF144562	Build Tools cannot be built in Linux
--- a/bintools/checklib/object/elf/elf_file_header.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/checklib/object/elf/elf_file_header.h	Tue Jun 29 14:52:54 2010 +0800
@@ -16,7 +16,7 @@
 #ifndef ELF_FILE_HEADER_H
 #define ELF_FILE_HEADER_H
 
-#include "elftools/inc/elfdefs.h"
+#include <elfdefs.h>
 #include <stdint.h>
 
 
--- a/bintools/checklib/object/elf/elf_section_header.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/checklib/object/elf/elf_section_header.h	Tue Jun 29 14:52:54 2010 +0800
@@ -16,7 +16,7 @@
 #ifndef ELF_SECTION_HEADER_H
 #define ELF_SECTION_HEADER_H
 
-#include "elftools/inc/elfdefs.h"
+#include <elfdefs.h>
 #include <stdint.h>
 
 namespace elf
--- a/bintools/checklib/object/elf/elf_symbol.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/checklib/object/elf/elf_symbol.h	Tue Jun 29 14:52:54 2010 +0800
@@ -16,7 +16,7 @@
 #ifndef ELF_SYMBOL_H
 #define ELF_SYMBOL_H
 
-#include "elftools/inc/elfdefs.h"
+#include <elfdefs.h>
 #include <stdint.h>
 
 
--- a/bintools/checklib/object/object.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/checklib/object/object.h	Tue Jun 29 14:52:54 2010 +0800
@@ -12,15 +12,10 @@
 //
 // Description:
 // Classes for interpreting a memory area as an ELF or COFF object.
-//
-//                    <creates>
+// <creates>
 // Object_factory -----------------> Object
-//                                     ^
-//                                     |
-//                              +------+------+
-//                              |             |
-//
-//                         Elf_object      Coff_object
+// Elf_object      Coff_object
+// 
 //
 
 #ifndef OBJECT_H
--- a/bintools/elftools/def2dll.pl	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/elftools/def2dll.pl	Tue Jun 29 14:52:54 2010 +0800
@@ -33,6 +33,11 @@
 	}	
 }
 
+# Version
+my $MajorVersion = 1;
+my $MinorVersion = 1;
+my $PatchVersion = 0;
+
 use lib $PerlLibPath;
 use Defutl;
 
@@ -66,6 +71,14 @@
 my $interworking = "${oP}apcs /nointer";
 $interworking = "${oP}apcs /inter" if ($interworkingp);
 
+my $gDelim;
+if ($^O eq "MSWin32") {
+	$gDelim = '\\';
+}
+else {
+	$gDelim = '/';
+}
+
 my @objectFiles;
 
 &main;
@@ -91,7 +104,7 @@
 sub usage( )
 {
         print "\n";
-        print "DEF2DLL -Creates binary objects used to implement the Symbian OS DLL model\n";
+        print "DEF2DLL -Creates binary objects used to implement the Symbian OS DLL model v$MajorVersion.$MinorVersion.$PatchVersion\n";
         print "\n";
         print "Usage: def2dll --deffile=<file> [--path=<dir>] [--bldpath=<dir>] [--import=<file>]  [--linkas=<file>] [--inter] [--export=<file>] [--sym_name_lkup]\n";
 
@@ -103,7 +116,7 @@
         print "\t--linkas=<file>     		: linkas to file name specified\n";
         print "\t--inter                 	: enables interworking on ARM and THUMB\n";
         print "\t--export=<file>			: export to filename\n";
-        print "\t--sym_name_lkup         	: symbol name ordinal number lookupç\n";
+        print "\t--sym_name_lkup         	: symbol name ordinal number lookup\n";
         print "\n";
         exit 1;
 }
@@ -148,8 +161,8 @@
     my $numkeys = keys %symbolIndexMap;
     my $failed = 0;
 
-    open EXPFILE, ">$path\\$expFile.s" or
-		die "Error: can't create $path\\$expFile.s\n";
+    open EXPFILE, ">$path$gDelim$expFile.s" or
+		die "Error: can't create $path$gDelim$expFile.s\n";
 
     print EXPFILE "\tEXPORT __DLL_Export_Table__\n\n";
     print EXPFILE "\tEXPORT |DLL\#\#ExportTable|\n\n";
@@ -204,9 +217,9 @@
     print EXPFILE "\tEND";
     close EXPFILE;
 
-    $failed = system "armasm $floatingpointmodel $interworking -o $path\\$expFile.exp $path\\$expFile.s";
-    unlink ("$path\\$expFile.s") unless $failed;
-    die "Error: cant create $path\\$expFile.exp\n" if $failed;
+    $failed = system "armasm $floatingpointmodel $interworking -o $path$gDelim$expFile.exp $path$gDelim$expFile.s";
+    unlink ("$path$gDelim$expFile.s") unless $failed;
+    die "Error: cant create $path$gDelim$expFile.exp\n" if $failed;
 }
 
 my %DataSymbols = ();
@@ -216,8 +229,8 @@
     my ($bldpath, $dllName) = @_;
     my $FileName = "VtblExports";
 
-    open VTBLFILE, ">$bldpath\\$FileName.s" or
-		die "Error: can't create $bldpath\\$FileName.s\n";
+    open VTBLFILE, ">$bldpath$gDelim$FileName.s" or
+		die "Error: can't create $bldpath$gDelim$FileName.s\n";
 
     print VTBLFILE "\tAREA |.directive|, NOALLOC, READONLY, ALIGN=2\n";
     printf VTBLFILE "\tDCB \"\#\<SYMEDIT\>\#\\n\"\n";
@@ -233,23 +246,23 @@
     print VTBLFILE "\tEND";
     close VTBLFILE;
 
-    my $failed = system "armasm $floatingpointmodel $interworking -o $bldpath\\$FileName.o $bldpath\\$FileName.s";
-    unlink ("$bldpath\\$FileName.s");
-    die "Error: cant create $bldpath\\$FileName.o\n" if $failed;
-    push @objectFiles, "$bldpath\\$FileName.o";
+    my $failed = system "armasm $floatingpointmodel $interworking -o $bldpath$gDelim$FileName.o $bldpath$gDelim$FileName.s";
+    unlink ("$bldpath$gDelim$FileName.s");
+    die "Error: cant create $bldpath$gDelim$FileName.o\n" if $failed;
+    push @objectFiles, "$bldpath$gDelim$FileName.o";
 }
 
 sub genLibFile ($$$$)
 {
     my ($path, $bldpath, $libFile, $dllName) = @_;
-    my $tempFileName = "$bldpath\\$compName";
-    my $viaFileName = sprintf("$bldpath\\_t%x_via_.txt", time);
+    my $tempFileName = "$bldpath$gDelim$compName";
+    my $viaFileName = sprintf("$bldpath${gDelim}_t%x_via_.txt", time);
     my $keyz = keys %symbolIndexMap;
     my $failed = 0;
     my $key;
 
     if ($keyz > 0) {
-		open STUBGEN, "|$ENV{'EPOCROOT'}/epoc32/tools/genstubs" if $exports;
+		open STUBGEN, "|genstubs" if $exports;
 		foreach $key (sort keys %symbolIndexMap) {
 			my $symbol = $symbolIndexMap{$key};
 			my $stubFileName = "$tempFileName-$key";
@@ -263,7 +276,7 @@
 		genVtblExportFile($bldpath, $dllName);
     } else {
 		# create dummy stub so armar creates a .lib for us
-		open STUBGEN, "|$ENV{'EPOCROOT'}/epoc32/tools/genstubs";
+		open STUBGEN, "|genstubs";
 		print STUBGEN "$tempFileName-stub.o $tempFileName##stub $dllName##dummy\n";
 		push @objectFiles, "$tempFileName-stub.o";
     }
@@ -272,7 +285,7 @@
     open VIAFILE, ">$viaFileName" or
 		die "Error: can't create VIA fie $viaFileName\n";
 
-    print VIAFILE "${oP}create \"$path\\$libFile\"\n";
+    print VIAFILE "${oP}create \"$path$gDelim$libFile\"\n";
     my $objectFile;
     foreach $objectFile (@objectFiles) {
 		print VIAFILE "\"$objectFile\"\n";
@@ -282,7 +295,7 @@
     $failed = system( "armar ${oP}via $viaFileName");
     push @objectFiles, $viaFileName;
     unlink @objectFiles;
-    die "Error: can't create $path\\$libFile\n" if $failed;
+    die "Error: can't create $path$gDelim$libFile\n" if $failed;
 }
 
 __END__
--- a/bintools/elftools/elftran/elf_dlld.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/elftools/elftran/elf_dlld.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,954 +1,928 @@
-/*
-* Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-
-#include <string.h>
-#include <stdlib.h>
-#include <e32std.h>
-#include <elfdefs.h>
-#include "elfdll.h"
-#include "elffile.h"
-#include <h_utl.h>
-#include <e32ldr.h>
-
-ELFFile::ELFDllData::ELFDllData(ELFFile * f)
-    :
-        iElfFile(f),
-
-        iDynStrTab(0),
-        iDynStrTabSize(0),
-        iDynSymTab(0),
-
-        iSymSize(0),
-        iRela(0),
-        iRelaSz(0),
-        iRelaEnt(0),
-
-        iRel(0),
-        iRelSz(0),
-        iRelEnt(0),
-
-        iHashTable(0),
-
-        iNamedExportSymbolHead(0),
-        iNamedExportCount(0),
-
-        iSymStringTableSize(0),
-        iStringNameOffset(0),
-
-        iDepRecords(0),
-        iDepRecordsTail(0),
-
-        iNeededDllNames(0),
-        iNeededDllNamesTail(0),
-
-        iOrdZeroRec(0),
-
-        iNamedLookupEnabled(0),
-
-        iDllHead(0),
-        iDllTail(0),
-
-        iNumberOfImports(0),
-        iNumberOfExports(0),
-        iNumberOfImportDlls(0),
-
-        iStringTableSize(0),
-
-        iNumberOfRelocs(0),
-        iNumberOfCodeRelocs(0),
-        iNumberOfDataRelocs(0)
-		{
-		}
-
-ELFFile::ELFDllData::~ELFDllData()
-	{
-		delete iOrdZeroRec;
-		delete iDepRecords;
-		delete iNeededDllNames;
-	}
-
-TBool ELFFile::ELFDllData::Init()
-	{
-	// process imported symbols
-	// There will be at least one relocation (assumed to be Elf32_Rel) for each such symbol.
-	// S iterate over relocations looking for DLL symbols and add them to the record of
-	// of import info.
-	TInt nrelocs = iRelSz/iRelEnt;
-	TInt SrcSegIdx = -1;
-	TInt errors = 0;
-
-	for (TInt idx = 0; idx < nrelocs; idx++)
-			{
-			Elf32_Rel * rel = &iRel[idx];
-			TUint relType = ELF32_R_TYPE(rel->r_info);
-
-			if (relType == R_ARM_ABS32)      
-					{	
-					TInt symIdx = ELF32_R_SYM(rel->r_info);
-					Elf32_Sym * sym = &iDynSymTab[symIdx];
-					DllSymbol * dllSym = DllSymbolP(sym);
-					if (dllSym) 
-							{
-							dllSym->iRel = rel;
-							dllSym->iSegment = iElfFile->GetSegment(SrcSegIdx);
-							if (!AddSymbol(dllSym)) return EFalse;
-							}
-					else errors++;
-					}
-			else if (relType == R_ARM_RABS32)
-					{
-					iNumberOfRelocs++;
-					if (iElfFile->CodeSegmentP(SrcSegIdx)) iNumberOfCodeRelocs++;
-					else iNumberOfDataRelocs++;
-					}
-			else if (relType == R_ARM_RBASE)
-				    {
-					SrcSegIdx = ELF32_R_SYM(rel->r_info);
-					if (SrcSegIdx) SrcSegIdx--;
-					}
-			else 
-				    {
-					// Gives error with all other Relocation types..
-					TInt symIdx = ELF32_R_SYM(rel->r_info);
-					Elf32_Sym * s = &iDynSymTab[symIdx];
-					char * symName = ELFADDR(char,iDynStrTab,s->st_name);
-					Print(EPeError, "Unresolved symbol: %s\n", symName);
-					errors++;
-					}
-			}
-	// Set up export info
-	if (InitExportInfo())
-	       {
-	       TText * sym = (TText *)"_E32Startup";
-	       // If _E32Startup is defined then this is not a DLL
-	       iImageIsDll = !iElfFile->SymbolPresent(sym);
-	       }
-	if (errors > 0) return EFalse;
-	return ETrue;
-	}
-
-TBool ELFFile::ELFDllData::ParseDllSymbol(Elf32_Sym * s, char *& dll, TUint& len, TInt& ord)
-    {
-	char * sym = ELFADDR(char,iDynStrTab,s->st_name);
-	if (!strncmp(sym, DLLSYMPREFIX, strlen(DLLSYMPREFIX)))
-			{
-			dll = sym + strlen(DLLSYMPREFIX);
-			TUint lim = strlen(dll);
-			TUint index = strcspn(dll, DLLSYMPREFIX0);
-			if ((index + strlen(DLLSYMSUFFIX)) < lim)
-					{
-					len = index;
-					char * dllSuffix = dll+index;
-					char * match = DLLSYMSUFFIX;
-					int suflen = strlen(DLLSYMSUFFIX);
-					if (!strncmp(dllSuffix, match, suflen))
-							{
-							char * ordString = dll+index+suflen;
-							char * final;
-							TUint X = strtoul(ordString, &final, ORDBASE);
-							if (ordString != final)
-									{
-									ord = (TInt)X;
-									return ETrue;
-									}
-			     
-							}
-					}
-			}
-	dll = 0;
-	len = 0;
-	ord = -1;
-	return EFalse;
-	}
-
-ELFFile::ELFDllData::DllSymbol * ELFFile::ELFDllData::DllSymbolP(Elf32_Sym * s)
-    {
-	char * dllName;
-	TUint nameLen;
-	TInt symOrd;
-	if (ParseDllSymbol(s, dllName, nameLen, symOrd))
-	       {
-	       DllSymbol * ds = new DllSymbol(dllName, nameLen, symOrd);
-	       if (ds) return ds;
-	       Print(EPeError, "Out of memory.\n");
-	       return NULL;
-	       }
-	// If we get here its not a valid 'dll symbol' and so it is an unresolved symbol
-	char * sym = ELFADDR(char,iDynStrTab,s->st_name);
-	Print(EPeError, "Unresolved symbol: %s\n", sym);
-    return NULL;
-	}
-
-TBool ELFFile::ELFDllData::AddSymbol(ELFFile::ELFDllData::DllSymbol * s)
-    {
-	DllRec * aDll = NULL;
-     
-	for (DllRec * r = iDllHead; r != NULL; r = r->iNext)
-			{
-			if (!strncmp(s->iDll, r->iName, s->iLen))
-					{
-					aDll = r;
-					break;
-					}
-			}
-	if (aDll)
-			{
-		    iNumberOfImports++;
-		    aDll->AddSymbol(s);
-			return ETrue;
-			}
-	else
-			{
-			aDll = new DllRec(s->iDll, s->iLen, s);
-			if (aDll)
-					{
-					if (!iDllHead) 
-							{
-							iDllHead = iDllTail = aDll;
-							}
-					else
-							{
-							iDllTail->iNext = aDll;
-							iDllTail = aDll;
-							}
-					iStringTableSize += (s->iLen + 1);
-	      			iNumberOfImportDlls++;
-					iNumberOfImports++;
-					return ETrue;
-					}
-			else
-					{
-					Print(EPeError, "Out of memory.\n");
-					return EFalse;
-					}
-			}
-	}
-
-void ELFFile::ELFDllData::DllRec::AddSymbol(ELFFile::ELFDllData::DllSymbol * s)
-	{
-	nImports++;
-    iTail->iNext = s;
-    iTail = s;
-    }
-
-static unsigned long elf_hash(const unsigned char *name)
-    {
-    unsigned long h, g;
-    for (h = 0; *name != 0; ++name)
-	        {
-			h = (h << 4) + *name;
-			g = h & 0xf0000000;
-			if (g != 0) h ^= g >> 24;
-			h &= ~g;
-			}
-	return h;
-    }
-
-Elf32_Word ELFFile::ELFDllData::FindSymbolIndex(TText * s)
-    {
-	TUint h = elf_hash(s);
-	TUint nb = iHashTable[0].nBuckets;
-	TUint probe = h%nb;
-	Elf32_Sword * bucket = ELFADDR(Elf32_Sword, iHashTable, sizeof(Elf32_HashTable));
-	Elf32_Sword * chain = ELFADDR(Elf32_Sword, bucket, nb * sizeof(Elf32_Sword));
-	Elf32_Sword idx = bucket[probe];
-
-	do 	
-			{
-			if (!strcmp(ELFADDR(char, iDynStrTab, iDynSymTab[idx].st_name), (char *)s)) return idx;
-			idx = chain[idx];
-			} while (idx > 0);
-	if (idx == 0) idx = -1;
-	return idx;
-	}
-
-TBool ELFFile::ELFDllData::InitExportInfo()
-	{
-	memset(&iSymInfoHdr, 0, sizeof(iSymInfoHdr));
-	TText * exp = (TText *)EXPORTTABLENAME;
-	if ( int(iExportTableSymIdx = FindSymbolIndex(exp)) != -1 )
-			{
-			TText * exps = (TText *)EXPORTTABLESIZENAME;
-			iExportTableSizeSymIdx = FindSymbolIndex(exps);
-			//TUint offset = iDynSymTab[iExportTableSizeSymIdx].st_value - (TUint)code;
-			Elf32_Word * pNumberOfExports = iElfFile->CodePtrFromAddr(iDynSymTab[iExportTableSizeSymIdx].st_value);
-			iNumberOfExports = * pNumberOfExports;
-			iImageIsDll = ETrue;
-			return ETrue;
-			}
-	else iImageIsDll = EFalse;
-	return EFalse;
-	}
-
-TInt ELFFile::ELFDllData::NumberOfImports(void)
-    {
-	return iNumberOfImports;
-	}
-
-TInt ELFFile::ELFDllData::NumberOfExports(void)
-    {
-	return iNumberOfExports;
-	}
-
-TInt ELFFile::ELFDllData::NumberOfImportDlls(void)
-    {
-	return iNumberOfImportDlls;
-	}
-
-TInt ELFFile::ELFDllData::NumberOfRelocs()
-	{
-	return iNumberOfRelocs;
-	}
-
-char * ELFFile::ELFDllData::CreateImportSection(TInt &aSize)
-	{
-	if (!iNumberOfImports)
-			{
-			aSize = 0;
-			return 0;
-			}
-
-	TInt byteSize = sizeof(E32ImportSection) + 
-	                (sizeof(E32ImportBlock) * iNumberOfImportDlls) +
-					(sizeof(TUint) * iNumberOfImports) +
-					iStringTableSize;
-	if(iNamedLookupEnabled)
-	{
-		// 0th ordinal of each DLL imported from.
-		byteSize += (sizeof(TUint) * iNumberOfImportDlls);
-	}
-	char * newSection = new char[byteSize];
-
-	if (!newSection)
-	       {
-	       Print(EPeError, "Failed to allocate new import section.\n");
-	       aSize = 0;
-	       return 0;
-	       }
-
-	((E32ImportSection *)newSection)->iSize = byteSize;
-
-	// used to point to current ImportBlock
-	E32ImportBlock * bp = ELFADDR(E32ImportBlock, newSection, sizeof(E32ImportSection));
-	// used to point to current import relocation entry
-	TUint * rp;
-	// used to point to current location in string table
-	char * sp = ELFADDR(char, newSection, (byteSize - iStringTableSize));
-	OrdZeroRecord *aDep = iDepRecords;
-
-	for (DllRec * dll = iDllHead; dll != NULL ; dll = dll->iNext, bp = (E32ImportBlock *)rp )
-	        {
-			// set up the offset from E32ImportBlock.iOffsetOfDllName to the
-			// corresponding  string table location
-			bp->iOffsetOfDllName = (sp - (char *)newSection);
-			bp->iNumberOfImports = dll->nImports;
-			if(iNamedLookupEnabled)
-			{
-				bp->iNumberOfImports++;
-			}
-
-			// copy the DLL name to the string table
-			memcpy(sp , dll->iName, dll->iLen);
-			sp[dll->iLen] = 0;
-			sp = sp + dll->iLen + 1;
-
-			// sort out the import 'relocs'
-			rp = ELFADDR(TUint, bp, sizeof(E32ImportBlock));
-		
-			for (DllSymbol * sym = dll->iHead; sym != NULL; sym = sym->iNext, rp++)
-				    {
-					Elf32_Phdr * segment = sym->iSegment;
-					Elf32_Addr segBase = segment->p_vaddr;
-
-					// sanity check: segment should be the code segment
-					if (!iElfFile->CodeSegmentP(segment))
-							{
-							Print(EPeError, "Import relocation does not refer to code segment.\n");
-							aSize = 0;
-							return 0;
-							}
-
-					// This field is misnamed because it is actually given as a virtual address in 
-					// dynamic relocations
-					Elf32_Addr dynOffset = sym->iRel->r_offset;
-					//So this is the 'real' offset of the reloc in  the segment in which it occurs
-					Elf32_Addr segOffset = dynOffset - segBase;
-					TUint * relocAddr = ELFADDR(TUint, iElfFile->ELFFileBase(), (segment->p_offset + segOffset));
-					// The only non-zero reloc vals we expect are for vtables.
-					// We store there reloc offset in the top 16 bits of the 'reloc info'.
-					// NB the ELF reloc values should only ever be multiples of 4. So we could optimize here,
-					// but we won't.
-					TUint relocVal = *relocAddr;
-					TUint importOrdinal = sym->iOrd;
-					if (relocVal > 0xFFFF)
-							Print(EPeError, "ELF relocation exceeds E32Image limit of 64K.\n");
-					if (importOrdinal > 0xFFFF)
-							Print(EPeError, "Import ordinal exceeds E32Image limit of 64K.\n");
-   
-   					*rp = segOffset;
-   			
-   					// eek !! surgery on the code segment....
-					*relocAddr = (relocVal<<16) | importOrdinal;
-					}
-			
-				if(iNamedLookupEnabled)
-				{
-					aDep = FindDependency(dll->iName, dll->iLen);
-					if( aDep )
-					{
-						*rp = aDep->iOffset;
-						rp++;
-					}
-				}
-			}
-	
-	aSize = byteSize;
-	return newSection;
-	}
-
-TUint ELFFile::ELFDllData::GetExportTableOffset(void)
-    {
-	Elf32_Sym * et = &iDynSymTab[iExportTableSymIdx];
-	Elf32_Phdr * segment = iElfFile->GetSegment(et->st_shndx - 1);
-	
-	return et->st_value - segment->p_vaddr;
-	}
-
-TBool ELFFile::ELFDllData::GetRelocs(Elf32_Rel **aCodeRelocs, Elf32_Rel **aDataRelocs)
-	//	
-	// load the relocs from the reloc section into relocation and relocsection arrays
-	//
-	{
-	TInt nrelocs = iRelSz/iRelEnt;
-
-	TInt SrcSegIdx = -1;
-
-	TInt cidx = 0;
-	TInt didx = 0;
-
-	for (TInt idx = 0; idx < nrelocs; idx++)
-	        {
-			Elf32_Rel * rel = &iRel[idx];
-
-			if (ELF32_R_TYPE(rel->r_info) == R_ARM_RABS32)
-					{
-					if (iElfFile->CodeSegmentP(SrcSegIdx))
-							aCodeRelocs[cidx++]=rel;
-					else if (iElfFile->DataSegmentP(SrcSegIdx))
-							aDataRelocs[didx++]=rel;
-					}
-			else if (ELF32_R_TYPE(rel->r_info) == R_ARM_RBASE)
-					{
-					SrcSegIdx = ELF32_R_SYM(rel->r_info);
-					if (!(iElfFile->CodeSegmentP(SrcSegIdx-1) || iElfFile->DataSegmentP(SrcSegIdx-1)))
-							{
-							Print(EPeError, "Source segment for relocations is neither Code or Data.\n");
-							return EFalse;
-							}
-					SrcSegIdx--;
-					}
-			}
-
-	if(!iNamedLookupEnabled)
-		return ETrue;
-
-	// Add the 0th ordinal of this binary - The relocation info is already setup.
-	aCodeRelocs[cidx++] = &iOrdZeroRec->iReloc;
-
-	// add relocation entries for each of the symbols
-	NamedExportSymbol *aSym = iNamedExportSymbolHead;
-	while(aSym)
-	{
-		// The symbol name info is part of the code section hence all relocations
-		// are collected as part of Code relocations.
-		aCodeRelocs[cidx++] = &aSym->iReloc;
-		aSym = aSym->Next();
-	}
-
-	// Since we have added a few relocations, lets make sure
-	// they are still sorted on addresses they refer to.
-	
-	//Sorting the code relocs
-	TInt aIdx1, aIdx2;
-	Elf32_Rel *aTmp;
-	for (aIdx1 = 0; aIdx1 < cidx; aIdx1++) {
-		for (aIdx2 = aIdx1; aIdx2 < cidx; aIdx2++) {
-			if(aCodeRelocs[aIdx1]->r_offset > aCodeRelocs[aIdx2]->r_offset) {
-				aTmp = aCodeRelocs[aIdx2];
-				aCodeRelocs[aIdx2] = aCodeRelocs[aIdx1];
-				aCodeRelocs[aIdx1] = aTmp;
-			}
-		}
-	}
-	
-	//Sorting the data relocs
-	for (aIdx1 = 0; aIdx1 < didx; aIdx1++) {
-		for (aIdx2 = aIdx1; aIdx2 < didx; aIdx2++) {
-			if(aDataRelocs[aIdx1]->r_offset > aDataRelocs[aIdx2]->r_offset) {
-				aTmp = aDataRelocs[aIdx2];
-				aDataRelocs[aIdx2] = aDataRelocs[aIdx1];
-				aDataRelocs[aIdx1] = aTmp;
-			}
-		}
-	}
-
-	return ETrue;
-	}
-
-NamedExportSymbol::NamedExportSymbol(char* aName, Elf32_Addr aValue) : \
-	iSymbolName(aName), iValue(aValue), iNext(NULL)
-{
-}
-
-TBool ELFFile::ELFDllData::CreateSymLookupTable()
-{
-	if( !SetupSymbolValues() )
-		return FALSE;
-
-	if( !SetupSymbolNames() )
-		return FALSE;
-
-	return TRUE;
-}
-
-TBool ELFFile::ELFDllData::SetupSymbolValues()
-{
-	NamedExportSymbol *aSym, *aPrevSym;
-
-	if( int(iExportTableSymIdx) == -1 || int(iExportTableSizeSymIdx) == -1)
-		return FALSE;
-
-	// Fetch the 'export table' symbol from the dynamic symbol table.
-	Elf32_Sym *aElfExpTbl = &iDynSymTab[iExportTableSymIdx];
-
-	// Fetch the 'export table size' symbol from the dynamic symbol table.
-	Elf32_Sym *aElfExpTblSz = &iDynSymTab[iExportTableSizeSymIdx];
-
-	if((aElfExpTbl->st_value - aElfExpTblSz->st_value) != 4)
-	{
-		// Check that the word prior to the export table is not the export table size
-		// This is to make sure that there is space for the 0th ordinal and
-		// we dont overwrite the 'export table size' entry.
-		iNamedLookupEnabled = 1;
-	}
-	else 
-		return FALSE;
-
-	// Fetch the export table contents
-	Elf32_Word * aExpEntries = iElfFile->CodePtrFromAddr(aElfExpTbl->st_value);
-
-	if(!aExpEntries)
-		return FALSE;
-
-	aSym = aPrevSym = NULL;
-	TInt idx;
-	// Create symbols corresponding to export table entries.
-	for(idx = 0;  idx < iNumberOfExports; idx++)
-	{
-		//Symbols marked Absent are ignored.
-		if( aExpEntries[idx] == iElfFile->iEntryPoint)
-			continue;
-
-		aSym = new NamedExportSymbol(0, aExpEntries[idx]);
-		iNamedExportCount++;
-		if(aPrevSym)
-		{
-			aPrevSym->Next(aSym);
-		}
-		else
-		{
-			iNamedExportSymbolHead = aSym;
-		}
-
-		aPrevSym = aSym;
-	}
-
-	return TRUE;
-}
-
-TBool ELFFile::ELFDllData::SetupSymbolNames()
-{
-	char *aSymName = NULL;
-	NamedExportSymbol *aSym;
-	TUint aDynSymbolTblCount = iHashTable->nChains;
-	TInt aCount = 0;
-	TInt aCodeSegIdx = iElfFile->CodeSegmentIndex() + 1;
-	TInt aDataSegIdx = iElfFile->DataSegmentIndex() + 1;
-
-	// Traverse the dynamic symbol table
-	for(TUint idx = 0; idx < aDynSymbolTblCount; idx++)
-	{
-		//Consider only the the defined symbols
-		if( ELF32_ST_TYPE(iDynSymTab[idx].st_info) == STT_OBJECT || 
-			ELF32_ST_TYPE(iDynSymTab[idx].st_info) == STT_FUNC )
-		{
-			aSym = iNamedExportSymbolHead;
-			while(aSym)
-			{
-				// Name already set
-				if(aSym->Name())
-				{
-					aSym = aSym->Next();
-					continue;
-				}
-				Elf32_Addr aAddr = aSym->Value();
-
-				// If the exported symbol and the dynamic symbol table entry have the 
-				// same values, setup the name
-				if(iDynSymTab[idx].st_value == aAddr)
-				{
-					aSymName = ELFADDR(char, iDynStrTab, iDynSymTab[idx].st_name);
-					aSym->Name(aSymName);
-					
-					if(iElfFile->CodeSegmentP (iElfFile->GetSegmentFromAddr(aAddr)) ) {
-						aSym->iReloc.r_info = aCodeSegIdx << 8 | R_ARM_RABS32;
-						aSym->iSymRelocType = KTextRelocType;
-					}
-					else {
-						aSym->iReloc.r_info = aDataSegIdx << 8 | R_ARM_RABS32;
-						aSym->iSymRelocType = KDataRelocType;
-					}
-					
-					iNumberOfCodeRelocs++;
-					iNumberOfRelocs++;
-
-					// The offset to the name is always 4 byte aligned.
-					iStringNameOffset = iSymStringTableSize >> 2;
-					aSym->NameOffset( iSymStringTableSize );
-					// These are NULL-terminated strings
-					iSymStringTableSize += (strlen(aSymName) + 1);
-					iSymStringTableSize = ALIGN4(iSymStringTableSize);
-
-					aCount++;
-					break;
-				}
-				aSym = aSym->Next();
-			}
-		}
-	}
-
-	if(aCount != iNamedExportCount)
-		return FALSE;
-
-	// Sort symbols on their names...
-	if(iNamedExportCount > 1)
-	{
-		NamedExportSymbol **aTmpStart = &iNamedExportSymbolHead;
-		Sort(aTmpStart, iNamedExportSymbolHead);
-	}
-
-	return TRUE;
-}
-
-void ELFFile::ELFDllData::SetLookupTblBase(TInt aBaseOffset)
-{
-	Elf32_Addr	aBaseAddr = iElfFile->iLinkedBase + iElfFile->GetCodeSize();
-
-	Elf32_Addr	aAddr;
-
-	// setup relocations of each of the exported symbols.
-	aAddr = aBaseAddr + iSymInfoHdr.iSymbolTblOffset;
-	NamedExportSymbol *aSym = iNamedExportSymbolHead;
-	while(aSym)
-	{
-		aSym->iReloc.r_offset = aAddr;
-		aAddr += sizeof(Elf32_Addr);
-		aSym = aSym->Next();
-	}
-
-	// setup relocations for the 0th ordinal of this binary. 
-
-	iOrdZeroRec = new OrdZeroRecord(0);
-	Elf32_Sym * et = &iDynSymTab[iExportTableSymIdx];
-	iOrdZeroRec->iReloc.r_offset = et->st_value - 4; // The word prior ro the first entry
-											// of the export table is the 0th ordinal entry.
-
-	//At the 0th ordinal, write the address of the start of symbol info	
-	TUint32 aZeroOrdOff = et->st_value - 4 - iElfFile->iLinkedBase;
-	aZeroOrdOff += (iElfFile->GetSegment(et->st_shndx - 1))->p_offset;
-	TUint32 *aZeroOrdLocation = ELFADDR(TUint32, iElfFile->ELFFileBase(), aZeroOrdOff);
-	*aZeroOrdLocation = aBaseAddr;
-
-	iOrdZeroRec->iReloc.r_info = ELF32_R_INFO(et->st_shndx, R_ARM_RABS32);
-	iNumberOfCodeRelocs++;
-	iNumberOfRelocs++;
-
-	TInt aOffset = aBaseOffset + iSymInfoHdr.iDepDllZeroOrdTableOffset;
-
-	OrdZeroRecord *aDepRecord = iDepRecords;
-
-	while( aDepRecord )
-	{
-		// Setup the offset - This offset (relative code segment) is filled in the 
-		// import table to point to this dependency record.
-		aDepRecord->iOffset = aOffset;
-
-		aOffset += 4;
-		aDepRecord = aDepRecord->iNext;
-	}
-}
-
-TBool ELFFile::ELFDllData::AddToDependency(TUint aOff)
-{
-	// Add the name found in DT_NEEDED into a list.
-	// The dynamic string table might not have been found in dynamic table yet.
-	// So store the offset (wrt base of dynamic string table) for now.
-	NeededDLLsList *aNeeded = new NeededDLLsList(aOff);
-	if(!aNeeded)
-		return FALSE;
-
-	if ( iNeededDllNames ) {
-	 iNeededDllNamesTail->iNext= aNeeded;
-	 iNeededDllNamesTail = aNeeded; 
-	}
-	else {
-		iNeededDllNames = iNeededDllNamesTail = aNeeded;
-	}
-	
-	return TRUE;
-}
-
-TBool ELFFile::ELFDllData::CreateDependency()
-{
-	OrdZeroRecord *aDep;
-	NeededDLLsList *aNeeded = iNeededDllNames;
-	char *aDllName = NULL;
-	DllRec *aRec;
-	TInt aNeededFound;
-
-	for(aNeededFound = 0; (aNeededFound < iNumberOfImportDlls) && aNeeded;)
-	{
-		aRec = 0;
-		while(aNeeded) {
-			aDllName = iDynStrTab + aNeeded->iOffset;
-			// aNeeded is just a guess that this binary might be dependent on aDllName
-			// Search through the import table to find if the guess was correct.
-			aRec = SearchImports(aDllName);
-			if(aRec && FindDependency(aRec->iName, aRec->iLen) == NULL) {
-				// Check if aDllName is listed in import table and it
-				// not added already in the depedency records.
-				aNeededFound++;
-				break;
-			}
-			// Bad guess...go to the next aNeeded
-			aNeeded = aNeeded->iNext;
-		}
-
-		if( !aRec )
-			return FALSE;
-
-		aDep = new OrdZeroRecord(aDllName);
-		if(!iDepRecords)
-		{
-			iDepRecords = iDepRecordsTail = aDep;
-		}
-		else
-		{
-			iDepRecordsTail->iNext = aDep;
-			iDepRecordsTail = aDep;
-		}
-		aNeeded = aNeeded->iNext;
-	}
-
-	return (aNeededFound == iNumberOfImportDlls);
-}
-
-ELFFile::ELFDllData::DllRec* ELFFile::ELFDllData::SearchImports(char *aName)
-{
-	DllRec *aRec = iDllHead;
-	while (aRec)
-	{
-		if(strncmp(aRec->iName, aName, aRec->iLen) == 0)
-			return aRec;
-		aRec = aRec->iNext;
-	}
-	return NULL;
-}
-
-OrdZeroRecord* ELFFile::ELFDllData::FindDependency(char* aName, TUint aLen)
-{
-	OrdZeroRecord* aDep = iDepRecords;
-	while(aDep)
-	{
-		if(strncmp(aName, aDep->iName, aLen) == 0)
-			return aDep;
-		aDep = aDep->iNext;
-	}
-	return NULL;
-}
-
-void ELFFile::ELFDllData::GetExportSymInfoHeader(E32EpocExpSymInfoHdr& aSymInfoHdr)
-{
-	memcpy(&aSymInfoHdr, &iSymInfoHdr, sizeof(E32EpocExpSymInfoHdr));
-}
-
-void ELFFile::ELFDllData::SetExportSymInfo()
-{
-	iSymInfoHdr.iSymCount = (TUint16)iNamedExportCount;
-	iSymInfoHdr.iSymbolTblOffset = sizeof(E32EpocExpSymInfoHdr);
-	iSymInfoHdr.iStringTableSz = iSymStringTableSize;
-	TInt aSymTabSz;
-	if( iStringNameOffset > 0xffff){
-		iSymInfoHdr.iFlags = KNameLookupOffsetFlag32;  // Flag indicating 32 bit offsets 
-													   // for symbol names
-		aSymTabSz = iNamedExportCount* sizeof(TUint32);// symbol addresses
-		aSymTabSz += iNamedExportCount* sizeof(TUint32);// symbol name 32-bit offsets
-	}
-	else
-	{
-		iSymInfoHdr.iFlags &= ~KNameLookupOffsetFlag32;// Flag indicating 16-bit offsets 
-													   // for symbol names
-		aSymTabSz = iNamedExportCount* sizeof(TUint32);	// symbol addresses
-		aSymTabSz += iNamedExportCount* sizeof(TUint16);// symbol name 16-bit offsets
-		aSymTabSz = ALIGN4(aSymTabSz);
-	}
-	iSymInfoHdr.iStringTableOffset = iSymInfoHdr.iSymbolTblOffset + aSymTabSz;
-	iSymInfoHdr.iDllCount = iNumberOfImportDlls;
-	iSymInfoHdr.iDepDllZeroOrdTableOffset = iSymInfoHdr.iStringTableOffset + \
-								iSymInfoHdr.iStringTableSz;
-
-	iSymInfoHdr.iSize = iSymInfoHdr.iDepDllZeroOrdTableOffset + \
-						iSymInfoHdr.iDllCount * sizeof(Elf32_Addr);
-}
-
-TUint ELFFile::ELFDllData::GetSymLookupSection(char* aBuff)
-{
-	if( !iNamedLookupEnabled)
-		return 0;
-
-	memcpy(aBuff, &iSymInfoHdr, sizeof(iSymInfoHdr));
-	
-	// Name offsets start after the end of symbol addresses.
-	TUint32 aNameOffsetStart = iSymInfoHdr.iSymbolTblOffset + \
-								iNamedExportCount* sizeof(TUint32);
-																
-	TUint32 *aAddrPtr = (TUint32*)(aBuff + iSymInfoHdr.iSymbolTblOffset);
-	TUint32 aStringTabOff = 0;
-	char *aStringTab = aBuff + iSymInfoHdr.iStringTableOffset;//Start of the string table.
-	NamedExportSymbol *aSym = iNamedExportSymbolHead;
-	while(aSym)
-	{
-		*aAddrPtr = aSym->Value();
-		aStringTabOff = aSym->NameOffset(); // Get the offset of symbol name (which is wrt 
-											// string table base).
-		if( iSymInfoHdr.iFlags & KNameLookupOffsetFlag32 )
-		{
-			TUint32 *aNameOffPtr = (TUint32*)(aBuff + aNameOffsetStart);
-			*aNameOffPtr = (aStringTabOff >> 2);//write the offset of the name
-			strcpy(aStringTab + aStringTabOff, aSym->Name());//write the symbol name
-			aNameOffsetStart +=4;
-		}
-		else
-		{
-			TUint16 *aNameOffPtr = (TUint16*)(aBuff + aNameOffsetStart);
-			*aNameOffPtr = (TUint16)(aStringTabOff >> 2);//write the offset of the name
-			strcpy(aStringTab + aStringTabOff, aSym->Name());//write the symbol name
-			aNameOffsetStart +=2;
-		}
-		aAddrPtr++;
-		aSym = aSym->Next();
-	}
-
-	OrdZeroRecord *aRec = iDepRecords;
-	TUint32* aDepsTable = (TUint32*)(aBuff + iSymInfoHdr.iDepDllZeroOrdTableOffset);
-	while(aRec)
-	{
-		*aDepsTable++ = 0;
-		aRec = aRec->iNext;
-	}
-	return iSymInfoHdr.iSize;
-}
-
-void ELFFile::ELFDllData::Sort(NamedExportSymbol** aDstList, NamedExportSymbol* aSrcList)
-{
-	NamedExportSymbol *aSym = aSrcList;
-	NamedExportSymbol **aSymbols = new NamedExportSymbol*[iNamedExportCount];
-	
-	TInt pos;
-	for (pos = 0; pos < iNamedExportCount; pos++) {
-		aSymbols[pos] = aSym;
-		aSym = aSym->Next();
-	}
-	
-	NamedExportSymbol **aResult = new NamedExportSymbol*[iNamedExportCount];
-	MergeSort(aResult, aSymbols);
-	iNamedExportSymbolHead = aResult[0];
-	for (pos = 0; pos < iNamedExportCount; pos++) {
-		aSym = aResult[pos];
-		if( pos == iNamedExportCount-1)
-			aSym->Next(NULL);
-		else
-			aSym->Next(aResult[pos+1]);
-	}
-	*aDstList = aResult[0];
-	delete [] aResult;
-	delete [] aSymbols;
-}
-
-void ELFFile::ELFDllData::MergeSort(NamedExportSymbol** aDstList, NamedExportSymbol** aSrcList)
-{
-	MergeSort(aDstList, aSrcList, 0, iNamedExportCount);
-}
-
-void ELFFile::ELFDllData::MergeSort(NamedExportSymbol** aDstList, NamedExportSymbol** aSrcList, \
-									TUint aLeft, TUint aRight)
-{
-	if( (aRight - aLeft) <= 1)
-		return;
-
-	TUint aSize = aRight - aLeft;
-	TUint aCenter = aLeft + aSize/2;
-
-	MergeSort(aDstList, aSrcList, aLeft, aCenter);
-	MergeSort(aDstList, aSrcList, aCenter, aRight);
-
-	TUint aLPos, aRPos, aCnt;
-	aLPos = aLeft;
-	aRPos = aCenter;
-	for(aCnt = 0; aCnt < aSize; aCnt++)
-	{
-		if( (aLPos < aCenter) &&
-			(aRPos == aRight || (strcmp(aSrcList[aLPos]->Name(), aSrcList[aRPos]->Name()) < 0) )
-		  )
-		{
-			// Compare the left half with the right and add the lesser one.
-			// The comparision is done on the topmost element on each half.
-			// if aRPos is past the last element of the right half, the left element has 
-			// nothing to compare with. Just add it to the result list.
-			aDstList[aCnt] = aSrcList[aLPos];
-			aLPos++;
-		}
-		else
-		{
-			// Add the greater one into the list.
-			// if aLPos is past the element at the center, it anyway belongs to the
-			// right half. Add it to the result list.
-			aDstList[aCnt] = aSrcList[aRPos];
-			aRPos++;
-		}
-	}
-
-	// Once the sublist is sorted, put it back to the source list
-	// so that the parent has its left and right sublists are sorted.
-	for(aCnt = 0; aCnt < aSize; aCnt++)
-	{
-		aSrcList[aLeft+aCnt] = aDstList[aCnt];
-	}
-}
-
+/*
+* Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+
+#include <string.h>
+#include <stdlib.h>
+#include <e32std.h>
+#include "elfdefs.h"
+#include "elfdll.h"
+#include "elffile.h"
+#include "h_utl.h"
+#include <e32ldr.h>
+
+ELFFile::ELFDllData::ELFDllData(ELFFile * f) :
+         iElfFile(f), iDynStrTab(0), iDynStrTabSize(0), iDynSymTab(0),
+ 		iSymSize(0), iRela(0), iRelaSz(0), iRelaEnt(0), 
+ 		iRel(0), iRelSz(0), iRelEnt(0),
+ 		iHashTable(0), iNamedExportSymbolHead(0),  iNamedExportCount(0),
+		iSymStringTableSize(0),iStringNameOffset(0), 
+		iDepRecords(0), iDepRecordsTail(0),iNeededDllNames(0),iNeededDllNamesTail(0),
+		iOrdZeroRec(0), iNamedLookupEnabled(0), 
+		iDllHead(0), iDllTail(0), 
+ 		iNumberOfImports(0),  iNumberOfExports(0), iNumberOfImportDlls(0),
+ 		iStringTableSize(0), iNumberOfRelocs(0), iNumberOfCodeRelocs(0),
+ 		iNumberOfDataRelocs(0)
+ 		  		
+		{
+		}
+
+ELFFile::ELFDllData::~ELFDllData()
+	{
+		delete iOrdZeroRec;
+		delete iDepRecords;
+		delete iNeededDllNames;
+	}
+
+TBool ELFFile::ELFDllData::Init()
+	{
+	// process imported symbols
+	// There will be at least one relocation (assumed to be Elf32_Rel) for each such symbol.
+	// S iterate over relocations looking for DLL symbols and add them to the record of
+	// of import info.
+	TInt nrelocs = iRelSz/iRelEnt;
+	TInt SrcSegIdx = -1;
+	TInt errors = 0;
+
+	for (TInt idx = 0; idx < nrelocs; idx++)
+			{
+			Elf32_Rel * rel = &iRel[idx];
+			TUint relType = ELF32_R_TYPE(rel->r_info);
+
+			if (relType == R_ARM_ABS32)      
+					{	
+					TInt symIdx = ELF32_R_SYM(rel->r_info);
+					Elf32_Sym * sym = &iDynSymTab[symIdx];
+					DllSymbol * dllSym = DllSymbolP(sym);
+					if (dllSym) 
+							{
+							dllSym->iRel = rel;
+							dllSym->iSegment = iElfFile->GetSegment(SrcSegIdx);
+							if (!AddSymbol(dllSym)) return EFalse;
+							}
+					else errors++;
+					}
+			else if (relType == R_ARM_RABS32)
+					{
+					iNumberOfRelocs++;
+					if (iElfFile->CodeSegmentP(SrcSegIdx)) iNumberOfCodeRelocs++;
+					else iNumberOfDataRelocs++;
+					}
+			else if (relType == R_ARM_RBASE)
+				    {
+					SrcSegIdx = ELF32_R_SYM(rel->r_info);
+					if (SrcSegIdx) SrcSegIdx--;
+					}
+			else 
+				    {
+					// Gives error with all other Relocation types..
+					TInt symIdx = ELF32_R_SYM(rel->r_info);
+					Elf32_Sym * s = &iDynSymTab[symIdx];
+					char * symName = ELFADDR(char,iDynStrTab,s->st_name);
+					Print(EPeError, "Unresolved symbol: %s\n", symName);
+					errors++;
+					}
+			}
+	// Set up export info
+	if (InitExportInfo())
+	       { 
+	       // If _E32Startup is defined then this is not a DLL
+	       iImageIsDll = !iElfFile->SymbolPresent("_E32Startup");
+	       }
+	if (errors > 0) return EFalse;
+	return ETrue;
+	}
+
+TBool ELFFile::ELFDllData::ParseDllSymbol(Elf32_Sym * s, char *& dll, TUint& len, TInt& ord)
+    {
+	char * sym = ELFADDR(char,iDynStrTab,s->st_name);
+	if (!strncmp(sym, DLLSYMPREFIX, strlen(DLLSYMPREFIX)))
+			{
+			dll = sym + strlen(DLLSYMPREFIX);
+			TUint lim = strlen(dll);
+			TUint index = strcspn(dll, DLLSYMPREFIX0);
+			if ((index + strlen(DLLSYMSUFFIX)) < lim)
+					{
+					len = index;
+					char * dllSuffix = dll+index;
+					char * match = DLLSYMSUFFIX;
+					int suflen = strlen(DLLSYMSUFFIX);
+					if (!strncmp(dllSuffix, match, suflen))
+							{
+							char * ordString = dll+index+suflen;
+							char * final;
+							TUint X = strtoul(ordString, &final, ORDBASE);
+							if (ordString != final)
+									{
+									ord = (TInt)X;
+									return ETrue;
+									}
+			     
+							}
+					}
+			}
+	dll = 0;
+	len = 0;
+	ord = -1;
+	return EFalse;
+	}
+
+ELFFile::ELFDllData::DllSymbol * ELFFile::ELFDllData::DllSymbolP(Elf32_Sym * s)
+    {
+	char * dllName;
+	TUint nameLen;
+	TInt symOrd;
+	if (ParseDllSymbol(s, dllName, nameLen, symOrd))
+	       {
+	       DllSymbol * ds = new DllSymbol(dllName, nameLen, symOrd);
+	       if (ds) return ds;
+	       Print(EPeError, "Out of memory.\n");
+	       return NULL;
+	       }
+	// If we get here its not a valid 'dll symbol' and so it is an unresolved symbol
+	char * sym = ELFADDR(char,iDynStrTab,s->st_name);
+	Print(EPeError, "Unresolved symbol: %s\n", sym);
+    return NULL;
+	}
+
+TBool ELFFile::ELFDllData::AddSymbol(ELFFile::ELFDllData::DllSymbol * s)
+    {
+	DllRec * aDll = NULL;
+     
+	for (DllRec * r = iDllHead; r != NULL; r = r->iNext)
+			{
+			if (!strncmp(s->iDll, r->iName, s->iLen))
+					{
+					aDll = r;
+					break;
+					}
+			}
+	if (aDll)
+			{
+		    iNumberOfImports++;
+		    aDll->AddSymbol(s);
+			return ETrue;
+			}
+	else
+			{
+			aDll = new DllRec(s->iDll, s->iLen, s);
+			if (aDll)
+					{
+					if (!iDllHead) 
+							{
+							iDllHead = iDllTail = aDll;
+							}
+					else
+							{
+							iDllTail->iNext = aDll;
+							iDllTail = aDll;
+							}
+					iStringTableSize += (s->iLen + 1);
+	      			iNumberOfImportDlls++;
+					iNumberOfImports++;
+					return ETrue;
+					}
+			else
+					{
+					Print(EPeError, "Out of memory.\n");
+					return EFalse;
+					}
+			}
+	}
+
+void ELFFile::ELFDllData::DllRec::AddSymbol(ELFFile::ELFDllData::DllSymbol * s)
+	{
+	nImports++;
+    iTail->iNext = s;
+    iTail = s;
+    }
+
+static unsigned long elf_hash(const unsigned char* name)
+    {
+    unsigned long h, g;
+    for (h = 0; *name != 0; ++name)
+	        {
+			h = (h << 4) + *name;
+			g = h & 0xf0000000;
+			if (g != 0) h ^= g >> 24;
+			h &= ~g;
+			}
+	return h;
+    }
+
+Elf32_Word ELFFile::ELFDllData::FindSymbolIndex(const char* s)
+    {
+	TUint h = elf_hash((const unsigned char*)s);
+	TUint nb = iHashTable[0].nBuckets;
+	TUint probe = h%nb;
+	Elf32_Sword * bucket = ELFADDR(Elf32_Sword, iHashTable, sizeof(Elf32_HashTable));
+	Elf32_Sword * chain = ELFADDR(Elf32_Sword, bucket, nb * sizeof(Elf32_Sword));
+	Elf32_Sword idx = bucket[probe];
+
+	do 	
+			{
+			if (!strcmp(ELFADDR(char, iDynStrTab, iDynSymTab[idx].st_name), s)) return idx;
+			idx = chain[idx];
+			} while (idx > 0);
+	if (idx == 0) idx = -1;
+	return idx;
+	}
+
+TBool ELFFile::ELFDllData::InitExportInfo()
+	{
+	memset(&iSymInfoHdr, 0, sizeof(iSymInfoHdr)); 
+	if ((iExportTableSymIdx = FindSymbolIndex(EXPORTTABLENAME)) != (Elf32_Word)-1)
+			{ 
+			iExportTableSizeSymIdx = FindSymbolIndex(EXPORTTABLESIZENAME);
+			//TUint offset = iDynSymTab[iExportTableSizeSymIdx].st_value - (TUint)code;
+			Elf32_Word * pNumberOfExports = iElfFile->CodePtrFromAddr(iDynSymTab[iExportTableSizeSymIdx].st_value);
+			iNumberOfExports = * pNumberOfExports;
+			iImageIsDll = ETrue;
+			return ETrue;
+			}
+	else iImageIsDll = EFalse;
+	return EFalse;
+	}
+
+TInt ELFFile::ELFDllData::NumberOfImports(void)
+    {
+	return iNumberOfImports;
+	}
+
+TInt ELFFile::ELFDllData::NumberOfExports(void)
+    {
+	return iNumberOfExports;
+	}
+
+TInt ELFFile::ELFDllData::NumberOfImportDlls(void)
+    {
+	return iNumberOfImportDlls;
+	}
+
+TInt ELFFile::ELFDllData::NumberOfRelocs()
+	{
+	return iNumberOfRelocs;
+	}
+
+char * ELFFile::ELFDllData::CreateImportSection(TInt &aSize)
+	{
+	if (!iNumberOfImports)
+			{
+			aSize = 0;
+			return 0;
+			}
+
+	TInt byteSize = sizeof(E32ImportSection) + 
+	                (sizeof(E32ImportBlock) * iNumberOfImportDlls) +
+					(sizeof(TUint) * iNumberOfImports) +
+					iStringTableSize;
+	if(iNamedLookupEnabled)
+	{
+		// 0th ordinal of each DLL imported from.
+		byteSize += (sizeof(TUint) * iNumberOfImportDlls);
+	}
+	char * newSection = new char[byteSize];
+
+	if (!newSection)
+	       {
+	       Print(EPeError, "Failed to allocate new import section.\n");
+	       aSize = 0;
+	       return 0;
+	       }
+
+	((E32ImportSection *)newSection)->iSize = byteSize;
+
+	// used to point to current ImportBlock
+	E32ImportBlock * bp = ELFADDR(E32ImportBlock, newSection, sizeof(E32ImportSection));
+	// used to point to current import relocation entry
+	TUint * rp;
+	// used to point to current location in string table
+	char * sp = ELFADDR(char, newSection, (byteSize - iStringTableSize));
+	OrdZeroRecord *aDep = iDepRecords;
+
+	for (DllRec * dll = iDllHead; dll != NULL ; dll = dll->iNext, bp = (E32ImportBlock *)rp )
+	        {
+			// set up the offset from E32ImportBlock.iOffsetOfDllName to the
+			// corresponding  string table location
+			bp->iOffsetOfDllName = (sp - (char *)newSection);
+			bp->iNumberOfImports = dll->nImports;
+			if(iNamedLookupEnabled)
+			{
+				bp->iNumberOfImports++;
+			}
+
+			// copy the DLL name to the string table
+			memcpy(sp , dll->iName, dll->iLen);
+			sp[dll->iLen] = 0;
+			sp = sp + dll->iLen + 1;
+
+			// sort out the import 'relocs'
+			rp = ELFADDR(TUint, bp, sizeof(E32ImportBlock));
+		
+			for (DllSymbol * sym = dll->iHead; sym != NULL; sym = sym->iNext, rp++)
+				    {
+					Elf32_Phdr * segment = sym->iSegment;
+					Elf32_Addr segBase = segment->p_vaddr;
+
+					// sanity check: segment should be the code segment
+					if (!iElfFile->CodeSegmentP(segment))
+							{
+							Print(EPeError, "Import relocation does not refer to code segment.\n");
+							Print(EPeError, "Dll: %s\n", sym->iDll);
+							Print(EPeError, "Ordinal: %d\n", sym->iOrd);
+							Print(EPeError, "DLL name: %s\n", dll->iName);
+							aSize = 0;
+							return 0;
+							}
+
+					// This field is misnamed because it is actually given as a virtual address in 
+					// dynamic relocations
+					Elf32_Addr dynOffset = sym->iRel->r_offset;
+					//So this is the 'real' offset of the reloc in  the segment in which it occurs
+					Elf32_Addr segOffset = dynOffset - segBase;
+					TUint * relocAddr = ELFADDR(TUint, iElfFile->ELFFileBase(), (segment->p_offset + segOffset));
+					// The only non-zero reloc vals we expect are for vtables.
+					// We store there reloc offset in the top 16 bits of the 'reloc info'.
+					// NB the ELF reloc values should only ever be multiples of 4. So we could optimize here,
+					// but we won't.
+					TUint relocVal = *relocAddr;
+					TUint importOrdinal = sym->iOrd;
+					if (relocVal > 0xFFFF) {
+							Print(EPeError, "ELF relocation exceeds E32Image limit of 64K.\n");
+							Print(EPeError, "Dll: %s\n", sym->iDll);
+							Print(EPeError, "Ordinal: %d\n", sym->iOrd);
+							Print(EPeError, "DLL name: %s\n", dll->iName);
+					}
+					if (importOrdinal > 0xFFFF) {
+							Print(EPeError, "Import ordinal exceeds E32Image limit of 64K.\n");
+							Print(EPeError, "Dll: %s\n", sym->iDll);
+							Print(EPeError, "Ordinal: %d\n", sym->iOrd);
+							Print(EPeError, "DLL name: %s\n", dll->iName);
+					}   
+   					*rp = segOffset;
+   			
+   					// eek !! surgery on the code segment....
+					*relocAddr = (relocVal<<16) | importOrdinal;
+					}
+			
+				if(iNamedLookupEnabled)
+				{
+					aDep = FindDependency(dll->iName, dll->iLen);
+					if( aDep )
+					{
+						*rp = aDep->iOffset;
+						rp++;
+					}
+				}
+			}
+	
+	aSize = byteSize;
+	return newSection;
+	}
+
+TUint ELFFile::ELFDllData::GetExportTableOffset(void)
+    {
+	Elf32_Sym * et = &iDynSymTab[iExportTableSymIdx];
+	Elf32_Phdr * segment = iElfFile->GetSegment(et->st_shndx - 1);
+	
+	return et->st_value - segment->p_vaddr;
+	}
+
+TBool ELFFile::ELFDllData::GetRelocs(Elf32_Rel **aCodeRelocs, Elf32_Rel **aDataRelocs)
+	//	
+	// load the relocs from the reloc section into relocation and relocsection arrays
+	//
+	{
+	TInt nrelocs = iRelSz/iRelEnt;
+
+	TInt SrcSegIdx = -1;
+	
+	TInt idx = 0;
+	TInt cidx = 0;
+	TInt didx = 0;
+
+	for (idx = 0, cidx = 0, didx = 0; idx < nrelocs; idx++)
+	        {
+			Elf32_Rel * rel = &iRel[idx];
+
+			if (ELF32_R_TYPE(rel->r_info) == R_ARM_RABS32)
+					{
+					if (iElfFile->CodeSegmentP(SrcSegIdx))
+							aCodeRelocs[cidx++]=rel;
+					else if (iElfFile->DataSegmentP(SrcSegIdx))
+							aDataRelocs[didx++]=rel;
+					}
+			else if (ELF32_R_TYPE(rel->r_info) == R_ARM_RBASE)
+					{
+					SrcSegIdx = ELF32_R_SYM(rel->r_info);
+					if (!(iElfFile->CodeSegmentP(SrcSegIdx-1) || iElfFile->DataSegmentP(SrcSegIdx-1)))
+							{
+							Print(EPeError, "Source segment for relocations is neither Code or Data.\n");
+							return EFalse;
+							}
+					SrcSegIdx--;
+					}
+			}
+
+	if(!iNamedLookupEnabled)
+		return ETrue;
+
+	// Add the 0th ordinal of this binary - The relocation info is already setup.
+	aCodeRelocs[cidx++] = &iOrdZeroRec->iReloc;
+
+	// add relocation entries for each of the symbols
+	NamedExportSymbol *aSym = iNamedExportSymbolHead;
+	while(aSym)
+	{
+		// The symbol name info is part of the code section hence all relocations
+		// are collected as part of Code relocations.
+		aCodeRelocs[cidx++] = &aSym->iReloc;
+		aSym = aSym->Next();
+	}
+
+	// Since we have added a few relocations, lets make sure
+	// they are still sorted on addresses they refer to.
+	
+	//Sorting the code relocs
+	TInt aIdx1, aIdx2;
+	Elf32_Rel *aTmp;
+	for (aIdx1 = 0; aIdx1 < cidx; aIdx1++) {
+		for (aIdx2 = aIdx1; aIdx2 < cidx; aIdx2++) {
+			if(aCodeRelocs[aIdx1]->r_offset > aCodeRelocs[aIdx2]->r_offset) {
+				aTmp = aCodeRelocs[aIdx2];
+				aCodeRelocs[aIdx2] = aCodeRelocs[aIdx1];
+				aCodeRelocs[aIdx1] = aTmp;
+			}
+		}
+	}
+	
+	//Sorting the data relocs
+	for (aIdx1 = 0; aIdx1 < didx; aIdx1++) {
+		for (aIdx2 = aIdx1; aIdx2 < didx; aIdx2++) {
+			if(aDataRelocs[aIdx1]->r_offset > aDataRelocs[aIdx2]->r_offset) {
+				aTmp = aDataRelocs[aIdx2];
+				aDataRelocs[aIdx2] = aDataRelocs[aIdx1];
+				aDataRelocs[aIdx1] = aTmp;
+			}
+		}
+	}
+
+	return ETrue;
+	}
+
+NamedExportSymbol::NamedExportSymbol(char* aName, Elf32_Addr aValue) : \
+	iSymbolName(aName), iValue(aValue), iNext(NULL)
+{
+}
+
+TBool ELFFile::ELFDllData::CreateSymLookupTable()
+{
+	if( !SetupSymbolValues() )
+		return FALSE;
+
+	if( !SetupSymbolNames() )
+		return FALSE;
+
+	return TRUE;
+}
+
+TBool ELFFile::ELFDllData::SetupSymbolValues()
+{
+	NamedExportSymbol *aSym, *aPrevSym;
+
+	if( iExportTableSymIdx == (Elf32_Word)-1 || iExportTableSizeSymIdx == (Elf32_Word)-1)
+		return FALSE;
+
+	// Fetch the 'export table' symbol from the dynamic symbol table.
+	Elf32_Sym *aElfExpTbl = &iDynSymTab[iExportTableSymIdx];
+
+	// Fetch the 'export table size' symbol from the dynamic symbol table.
+	Elf32_Sym *aElfExpTblSz = &iDynSymTab[iExportTableSizeSymIdx];
+
+	if((aElfExpTbl->st_value - aElfExpTblSz->st_value) != 4)
+	{
+		// Check that the word prior to the export table is not the export table size
+		// This is to make sure that there is space for the 0th ordinal and
+		// we dont overwrite the 'export table size' entry.
+		iNamedLookupEnabled = 1;
+	}
+	else 
+		return FALSE;
+
+	// Fetch the export table contents
+	Elf32_Word * aExpEntries = iElfFile->CodePtrFromAddr(aElfExpTbl->st_value);
+
+	if(!aExpEntries)
+		return FALSE;
+
+	aSym = aPrevSym = NULL;
+	TInt idx;
+	// Create symbols corresponding to export table entries.
+	for(idx = 0;  idx < iNumberOfExports; idx++)
+	{
+		//Symbols marked Absent are ignored.
+		if( aExpEntries[idx] == iElfFile->iEntryPoint)
+			continue;
+
+		aSym = new NamedExportSymbol(0, aExpEntries[idx]);
+		iNamedExportCount++;
+		if(aPrevSym)
+		{
+			aPrevSym->Next(aSym);
+		}
+		else
+		{
+			iNamedExportSymbolHead = aSym;
+		}
+
+		aPrevSym = aSym;
+	}
+
+	return TRUE;
+}
+
+TBool ELFFile::ELFDllData::SetupSymbolNames()
+{
+	char *aSymName = NULL;
+	NamedExportSymbol *aSym;
+	TUint aDynSymbolTblCount = iHashTable->nChains;
+	TInt aCount = 0;
+	TInt aCodeSegIdx = iElfFile->CodeSegmentIndex() + 1;
+	TInt aDataSegIdx = iElfFile->DataSegmentIndex() + 1;
+
+	// Traverse the dynamic symbol table
+	for(TUint idx = 0; idx < aDynSymbolTblCount; idx++)
+	{
+		//Consider only the the defined symbols
+		if( ELF32_ST_TYPE(iDynSymTab[idx].st_info) == STT_OBJECT || 
+			ELF32_ST_TYPE(iDynSymTab[idx].st_info) == STT_FUNC )
+		{
+			aSym = iNamedExportSymbolHead;
+			while(aSym)
+			{
+				// Name already set
+				if(aSym->Name())
+				{
+					aSym = aSym->Next();
+					continue;
+				}
+				Elf32_Addr aAddr = aSym->Value();
+
+				// If the exported symbol and the dynamic symbol table entry have the 
+				// same values, setup the name
+				if(iDynSymTab[idx].st_value == aAddr)
+				{
+					aSymName = ELFADDR(char, iDynStrTab, iDynSymTab[idx].st_name);
+					aSym->Name(aSymName);
+					
+					if(iElfFile->CodeSegmentP (iElfFile->GetSegmentFromAddr(aAddr)) ) {
+						aSym->iReloc.r_info = aCodeSegIdx << 8 | R_ARM_RABS32;
+						aSym->iSymRelocType = KTextRelocType;
+					}
+					else {
+						aSym->iReloc.r_info = aDataSegIdx << 8 | R_ARM_RABS32;
+						aSym->iSymRelocType = KDataRelocType;
+					}
+					
+					iNumberOfCodeRelocs++;
+					iNumberOfRelocs++;
+
+					// The offset to the name is always 4 byte aligned.
+					iStringNameOffset = iSymStringTableSize >> 2;
+					aSym->NameOffset( iSymStringTableSize );
+					// These are NULL-terminated strings
+					iSymStringTableSize += (strlen(aSymName) + 1);
+					iSymStringTableSize = ALIGN4(iSymStringTableSize);
+
+					aCount++;
+					break;
+				}
+				aSym = aSym->Next();
+			}
+		}
+	}
+
+	if(aCount != iNamedExportCount)
+		return FALSE;
+
+	// Sort symbols on their names...
+	if(iNamedExportCount > 1)
+	{
+		NamedExportSymbol **aTmpStart = &iNamedExportSymbolHead;
+		Sort(aTmpStart, iNamedExportSymbolHead);
+	}
+
+	return TRUE;
+}
+
+void ELFFile::ELFDllData::SetLookupTblBase(TInt aBaseOffset)
+{
+	Elf32_Addr	aBaseAddr = iElfFile->iLinkedBase + iElfFile->GetCodeSize();
+
+	Elf32_Addr	aAddr;
+
+	// setup relocations of each of the exported symbols.
+	aAddr = aBaseAddr + iSymInfoHdr.iSymbolTblOffset;
+	NamedExportSymbol *aSym = iNamedExportSymbolHead;
+	while(aSym)
+	{
+		aSym->iReloc.r_offset = aAddr;
+		aAddr += sizeof(Elf32_Addr);
+		aSym = aSym->Next();
+	}
+
+	// setup relocations for the 0th ordinal of this binary. 
+
+	iOrdZeroRec = new OrdZeroRecord(0);
+	Elf32_Sym * et = &iDynSymTab[iExportTableSymIdx];
+	iOrdZeroRec->iReloc.r_offset = et->st_value - 4; // The word prior ro the first entry
+											// of the export table is the 0th ordinal entry.
+
+	//At the 0th ordinal, write the address of the start of symbol info	
+	TUint32 aZeroOrdOff = et->st_value - 4 - iElfFile->iLinkedBase;
+	aZeroOrdOff += (iElfFile->GetSegment(et->st_shndx - 1))->p_offset;
+	TUint32 *aZeroOrdLocation = ELFADDR(TUint32, iElfFile->ELFFileBase(), aZeroOrdOff);
+	*aZeroOrdLocation = aBaseAddr;
+
+	iOrdZeroRec->iReloc.r_info = ELF32_R_INFO(et->st_shndx, R_ARM_RABS32);
+	iNumberOfCodeRelocs++;
+	iNumberOfRelocs++;
+
+	TInt aOffset = aBaseOffset + iSymInfoHdr.iDepDllZeroOrdTableOffset;
+
+	OrdZeroRecord *aDepRecord = iDepRecords;
+
+	while( aDepRecord )
+	{
+		// Setup the offset - This offset (relative code segment) is filled in the 
+		// import table to point to this dependency record.
+		aDepRecord->iOffset = aOffset;
+
+		aOffset += 4;
+		aDepRecord = aDepRecord->iNext;
+	}
+}
+
+TBool ELFFile::ELFDllData::AddToDependency(TUint aOff)
+{
+	// Add the name found in DT_NEEDED into a list.
+	// The dynamic string table might not have been found in dynamic table yet.
+	// So store the offset (wrt base of dynamic string table) for now.
+	NeededDLLsList *aNeeded = new NeededDLLsList(aOff);
+	if(!aNeeded)
+		return FALSE;
+
+	if ( iNeededDllNames ) {
+	 iNeededDllNamesTail->iNext= aNeeded;
+	 iNeededDllNamesTail = aNeeded; 
+	}
+	else {
+		iNeededDllNames = iNeededDllNamesTail = aNeeded;
+	}
+	
+	return TRUE;
+}
+
+TBool ELFFile::ELFDllData::CreateDependency()
+{
+	OrdZeroRecord *aDep;
+	NeededDLLsList *aNeeded = iNeededDllNames;
+	char *aDllName = NULL;
+	DllRec *aRec;
+	TInt aNeededFound;
+
+	for(aNeededFound = 0; (aNeededFound < iNumberOfImportDlls) && aNeeded;)
+	{
+		aRec = 0;
+		while(aNeeded) {
+			aDllName = iDynStrTab + aNeeded->iOffset;
+			// aNeeded is just a guess that this binary might be dependent on aDllName
+			// Search through the import table to find if the guess was correct.
+			aRec = SearchImports(aDllName);
+			if(aRec && FindDependency(aRec->iName, aRec->iLen) == NULL) {
+				// Check if aDllName is listed in import table and it
+				// not added already in the depedency records.
+				aNeededFound++;
+				break;
+			}
+			// Bad guess...go to the next aNeeded
+			aNeeded = aNeeded->iNext;
+		}
+
+		if( !aRec )
+			return FALSE;
+
+		aDep = new OrdZeroRecord(aDllName);
+		if(!iDepRecords)
+		{
+			iDepRecords = iDepRecordsTail = aDep;
+		}
+		else
+		{
+			iDepRecordsTail->iNext = aDep;
+			iDepRecordsTail = aDep;
+		}
+		aNeeded = aNeeded->iNext;
+	}
+
+	return (aNeededFound == iNumberOfImportDlls);
+}
+
+ELFFile::ELFDllData::DllRec* ELFFile::ELFDllData::SearchImports(char *aName)
+{
+	DllRec *aRec = iDllHead;
+	while (aRec)
+	{
+		if(strncmp(aRec->iName, aName, aRec->iLen) == 0)
+			return aRec;
+		aRec = aRec->iNext;
+	}
+	return NULL;
+}
+
+OrdZeroRecord* ELFFile::ELFDllData::FindDependency(char* aName, TUint aLen)
+{
+	OrdZeroRecord* aDep = iDepRecords;
+	while(aDep)
+	{
+		if(strncmp(aName, aDep->iName, aLen) == 0)
+			return aDep;
+		aDep = aDep->iNext;
+	}
+	return NULL;
+}
+
+void ELFFile::ELFDllData::GetExportSymInfoHeader(E32EpocExpSymInfoHdr& aSymInfoHdr)
+{
+	memcpy(&aSymInfoHdr, &iSymInfoHdr, sizeof(E32EpocExpSymInfoHdr));
+}
+
+void ELFFile::ELFDllData::SetExportSymInfo()
+{
+	iSymInfoHdr.iSymCount = (TUint16)iNamedExportCount;
+	iSymInfoHdr.iSymbolTblOffset = sizeof(E32EpocExpSymInfoHdr);
+	iSymInfoHdr.iStringTableSz = iSymStringTableSize;
+	TInt aSymTabSz;
+	if( iStringNameOffset > 0xffff){
+		iSymInfoHdr.iFlags = KNameLookupOffsetFlag32;  // Flag indicating 32 bit offsets 
+													   // for symbol names
+		aSymTabSz = iNamedExportCount* sizeof(TUint32);// symbol addresses
+		aSymTabSz += iNamedExportCount* sizeof(TUint32);// symbol name 32-bit offsets
+	}
+	else
+	{
+		iSymInfoHdr.iFlags &= ~KNameLookupOffsetFlag32;// Flag indicating 16-bit offsets 
+													   // for symbol names
+		aSymTabSz = iNamedExportCount* sizeof(TUint32);	// symbol addresses
+		aSymTabSz += iNamedExportCount* sizeof(TUint16);// symbol name 16-bit offsets
+		aSymTabSz = ALIGN4(aSymTabSz);
+	}
+	iSymInfoHdr.iStringTableOffset = iSymInfoHdr.iSymbolTblOffset + aSymTabSz;
+	iSymInfoHdr.iDllCount = iNumberOfImportDlls;
+	iSymInfoHdr.iDepDllZeroOrdTableOffset = iSymInfoHdr.iStringTableOffset + \
+								iSymInfoHdr.iStringTableSz;
+
+	iSymInfoHdr.iSize = iSymInfoHdr.iDepDllZeroOrdTableOffset + \
+						iSymInfoHdr.iDllCount * sizeof(Elf32_Addr);
+}
+
+TUint ELFFile::ELFDllData::GetSymLookupSection(char* aBuff)
+{
+	if( !iNamedLookupEnabled)
+		return 0;
+
+	memcpy(aBuff, &iSymInfoHdr, sizeof(iSymInfoHdr));
+	
+	// Name offsets start after the end of symbol addresses.
+	TUint32 aNameOffsetStart = iSymInfoHdr.iSymbolTblOffset + \
+								iNamedExportCount* sizeof(TUint32);
+																
+	TUint32 *aAddrPtr = (TUint32*)(aBuff + iSymInfoHdr.iSymbolTblOffset);
+	TUint32 aStringTabOff = 0;
+	char *aStringTab = aBuff + iSymInfoHdr.iStringTableOffset;//Start of the string table.
+	NamedExportSymbol *aSym = iNamedExportSymbolHead;
+	while(aSym)
+	{
+		*aAddrPtr = aSym->Value();
+		aStringTabOff = aSym->NameOffset(); // Get the offset of symbol name (which is wrt 
+											// string table base).
+		if( iSymInfoHdr.iFlags & KNameLookupOffsetFlag32 )
+		{
+			TUint32 *aNameOffPtr = (TUint32*)(aBuff + aNameOffsetStart);
+			*aNameOffPtr = (aStringTabOff >> 2);//write the offset of the name
+			strcpy(aStringTab + aStringTabOff, aSym->Name());//write the symbol name
+			aNameOffsetStart +=4;
+		}
+		else
+		{
+			TUint16 *aNameOffPtr = (TUint16*)(aBuff + aNameOffsetStart);
+			*aNameOffPtr = (TUint16)(aStringTabOff >> 2);//write the offset of the name
+			strcpy(aStringTab + aStringTabOff, aSym->Name());//write the symbol name
+			aNameOffsetStart +=2;
+		}
+		aAddrPtr++;
+		aSym = aSym->Next();
+	}
+
+	OrdZeroRecord *aRec = iDepRecords;
+	TUint32* aDepsTable = (TUint32*)(aBuff + iSymInfoHdr.iDepDllZeroOrdTableOffset);
+	while(aRec)
+	{
+		*aDepsTable++ = 0;
+		aRec = aRec->iNext;
+	}
+	return iSymInfoHdr.iSize;
+}
+
+void ELFFile::ELFDllData::Sort(NamedExportSymbol** aDstList, NamedExportSymbol* aSrcList)
+{
+	NamedExportSymbol *aSym = aSrcList;
+	NamedExportSymbol **aSymbols = new NamedExportSymbol*[iNamedExportCount];
+	
+	TInt pos;
+	for (pos = 0; pos < iNamedExportCount; pos++) {
+		aSymbols[pos] = aSym;
+		aSym = aSym->Next();
+	}
+	
+	NamedExportSymbol **aResult = new NamedExportSymbol*[iNamedExportCount];
+	MergeSort(aResult, aSymbols);
+	iNamedExportSymbolHead = aResult[0];
+	for (pos = 0; pos < iNamedExportCount; pos++) {
+		aSym = aResult[pos];
+		if( pos == iNamedExportCount-1)
+			aSym->Next(NULL);
+		else
+			aSym->Next(aResult[pos+1]);
+	}
+	*aDstList = aResult[0];
+	delete [] aResult;
+	delete [] aSymbols;
+}
+
+void ELFFile::ELFDllData::MergeSort(NamedExportSymbol** aDstList, NamedExportSymbol** aSrcList)
+{
+	MergeSort(aDstList, aSrcList, 0, iNamedExportCount);
+}
+
+void ELFFile::ELFDllData::MergeSort(NamedExportSymbol** aDstList, NamedExportSymbol** aSrcList, \
+									TUint aLeft, TUint aRight)
+{
+	if( (aRight - aLeft) <= 1)
+		return;
+
+	TUint aSize = aRight - aLeft;
+	TUint aCenter = aLeft + aSize/2;
+
+	MergeSort(aDstList, aSrcList, aLeft, aCenter);
+	MergeSort(aDstList, aSrcList, aCenter, aRight);
+
+	TUint aLPos, aRPos, aCnt;
+	aLPos = aLeft;
+	aRPos = aCenter;
+	for(aCnt = 0; aCnt < aSize; aCnt++)
+	{
+		if( (aLPos < aCenter) &&
+			(aRPos == aRight || (strcmp(aSrcList[aLPos]->Name(), aSrcList[aRPos]->Name()) < 0) )
+		  )
+		{
+			// Compare the left half with the right and add the lesser one.
+			// The comparision is done on the topmost element on each half.
+			// if aRPos is past the last element of the right half, the left element has 
+			// nothing to compare with. Just add it to the result list.
+			aDstList[aCnt] = aSrcList[aLPos];
+			aLPos++;
+		}
+		else
+		{
+			// Add the greater one into the list.
+			// if aLPos is past the element at the center, it anyway belongs to the
+			// right half. Add it to the result list.
+			aDstList[aCnt] = aSrcList[aRPos];
+			aRPos++;
+		}
+	}
+
+	// Once the sublist is sorted, put it back to the source list
+	// so that the parent has its left and right sublists are sorted.
+	for(aCnt = 0; aCnt < aSize; aCnt++)
+	{
+		aSrcList[aLeft+aCnt] = aDstList[aCnt];
+	}
+}
+
--- a/bintools/elftools/elftran/elf_file.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/elftools/elftran/elf_file.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,540 +1,527 @@
-/*
-* Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-
-#include <e32def.h>
-#include <e32std.h>
-#include "elftran.h"
-#include <elfdefs.h>
-#include "elffile.h"
-#include "elfdll.h"
-#include <h_utl.h>
-#include <string.h>
-#include <stdlib.h>
-
-TBool hadText, hadReloc = EFalse;
-
-ELFFile::ELFFile() 
-    :
-    iHeapCommittedSize(0x1000),
-    iHeapReservedSize(0x100000),
-    iStackCommittedSize(0),
-
-    iFileName(0),
-    iFileHandle(-1),
-    iElfFile(0),
-
-    iDynamicSegmentHdr(0),
-    iDynamicSegmentIdx(0),
-
-    iCodeSegmentHdr(0),
-    iCodeSegmentIdx(0),
-
-    iDataSegmentHdr(0),
-    iDataSegmentIdx(0),
-
-    iDllData(0),
-    iCpu(ECpuUnknown)
-    {}
-
-
-
-
-ELFFile::~ELFFile()
-	{
-	delete [] iFileName;
-	delete iElfFile;
-	delete iDllData;
-	}
-
-
-TBool ELFFile::Init(const TText * const aFileName)
-//
-// Read the ELF file into memory
-//
- 	{
-
- 	delete [] iFileName;	
-	iFileName = new TText[strlen((const char *)aFileName)+1];
-	strcpy ((char *)iFileName, (const char *)aFileName);
-
-	TInt error = HFile::Open(iFileName, &iFileHandle);
-	if (error!=0)
-		return EFalse;
-
-	TInt flength = HFile::GetLength(iFileHandle);
-
-	iElfFile = (Elf32_Ehdr *)HMem::Alloc(0,flength);
-	if (!iElfFile)
-		{
-		Print(EPeError,"Failed to allocate memory to read in file.\n");
-		Close();
-		return EFalse;
-		}
-
-	if (!HFile::Read(iFileHandle,iElfFile,flength))
-		{
-		Print(EPeError,"Unable to read file %s.\n",iFileName);
-		Close();
-		return EFalse;
-		}
-
-        Close();
-
-	if (!IsValidFileHeader(iElfFile))
-		{
-		Print(EPeError,"Invalid file header.\n");
-		return EFalse;
-		}
-	// we only support this....for the moment
-	iCpu = ECpuArmV4;
-
-	if (!InitHeaders()) return EFalse;
-	
-	if (!InitDllData()) return EFalse;
-
-	iEntryPoint = iElfFile->e_entry;
-
-	iCodeSize = GetCodeSize();
-	iDataSize = GetDataSize();
-	iBssSize = GetBssSize();
-
-	iStackReservedSize = 0x2000;
-	iStackCommittedSize = 0x2000;
-
- 	iLinkedBase = iCodeSegmentHdr->p_vaddr;
-	
-	iImageIsDll = iDllData->ImageIsDll();
-
-	return ETrue;
-	}
-
-char * ELFFile::CreateImportSection(TInt &aSize)
-//
-// get ELFDLLData to do it
-//
-	{
-	TInt size;
-	char * newSection = iDllData->CreateImportSection(size);
-	aSize = size;
-	return newSection;
-	}
-
-TUint ELFFile::GetExportTableOffset(void)
-        {
-	return iDllData->GetExportTableOffset();
-	}
-
-TBool ELFFile::InitHeaders(void)
-        {
-	TInt nphdrs = iElfFile->e_phnum;
-	if (nphdrs)
-	       {
-	       // Find the dynamic segment
-	       Elf32_Phdr * aPhdr = ELFADDR(Elf32_Phdr, iElfFile, iElfFile->e_phoff);
-	       iPhdr = aPhdr;
-	       for (TInt idx = 0; idx < nphdrs; idx++)
-					{
-					Elf32_Word ptype = aPhdr[idx].p_type;
-					if (ptype == PT_DYNAMIC)
-							{
-							iDynamicSegmentHdr = &aPhdr[idx];
-							iDynamicSegmentIdx = idx;
-							}
-      				else if (ptype == PT_LOAD && 
-							 (aPhdr[idx].p_flags & (PF_X + PF_ARM_ENTRY)))
-							{
-							iCodeSegmentHdr = &aPhdr[idx];
-							iCodeSegmentIdx = idx;
-							}
-      				else if (ptype == PT_LOAD && 
-							 (aPhdr[idx].p_flags & (PF_W + PF_R)))
-							{
-							iDataSegmentHdr = &aPhdr[idx];
-							iDataSegmentIdx = idx;
-							}
-					}
-	       }
-	
-	// cache pointer to symbol table
-
-	// Get section header table
-	Elf32_Shdr * s = ELFADDR(Elf32_Shdr, iElfFile, iElfFile->e_shoff);
-	// Index of section header for section header string table
-	TInt stIdx = iElfFile->e_shstrndx;
-	TInt symIdx = -1;
-	// Section name string table
-	char * stringtable = ELFADDR(char, iElfFile, s[stIdx].sh_offset);
-	// the index at which we find '.symtab' is the index of the symtab section
-	for (TInt idx = 0; idx < iElfFile->e_shnum; idx++)
-	    {
-		if (idx != stIdx)
-		       {
-		       if (!strcmp(&stringtable[s[idx].sh_name], ".symtab"))
-			      {
-			      symIdx = idx;
-			      break;
-			      }
-		       }
-		}
-	if (symIdx == -1) return EFalse;
-
-	// save section header table
-	iSectionHeaderTable = s;
-	// save the index
-	iSymIdx = symIdx;	
-	// here's the symbol table
-	iSymTab = ELFADDR(Elf32_Sym, iElfFile, s[symIdx].sh_offset);
-	return ETrue;
-	}
-
-TBool ELFFile::InitDllData(void)
-	{
-	if (!iDynamicSegmentHdr)
-	       {
-#if defined(_DEBUG)
-	       Print(EWarning, "Image '%s' has no import/export data.\n", iFileName);
-#endif
-	       return ETrue;
-	       }
-	iDllData = new ELFDllData(this);
-	if (!iDllData)
-	       {
-	       Print(EPeError, "Out of memory allocating DLL data\n");
-	       return EFalse;
-	       }
-
-	Elf32_Dyn * dyn = ELFADDR(Elf32_Dyn, iElfFile, iDynamicSegmentHdr->p_offset);
-	TInt idx = 0;
-	TInt soNameOffset = 0;
-	while(dyn[idx].d_tag != DT_NULL) // best to make it explicit
-	       {
-	       switch (dyn[idx].d_tag)
-		      {
-		      case DT_HASH:
-			   iDllData->iHashTable = ELFADDR(Elf32_HashTable, dyn, dyn[idx].d_val);
-			   break;
-		      case DT_STRTAB:
-			   iDllData->iDynStrTab = ELFADDR(char, dyn, dyn[idx].d_val);
-			   break;
-		      case DT_SYMTAB:
-			   iDllData->iDynSymTab = ELFADDR(Elf32_Sym, dyn, dyn[idx].d_val);
-			   break;
-		      case DT_RELA:
-			   iDllData->iRela = ELFADDR(Elf32_Rela, dyn, dyn[idx].d_val);
-			   break;
-		      case DT_RELASZ:
-			   iDllData->iRelaSz = dyn[idx].d_val;
-			   break;
-		      case DT_RELAENT:
-			   iDllData->iRelaSz = dyn[idx].d_val;
-			   break;
-		      case DT_STRSZ:
-			   iDllData->iDynStrTabSize = dyn[idx].d_val;
-			   break;
-		      case DT_ARM_SYMTABSZ_21: //For RVCT2.1
-			   //iDllData->iDynSymTabSize = dyn[idx].d_val;
-		      case DT_ARM_SYMTABSZ:
-			  /* This is same as DT_ARM_SYMTABSZ_21, but for RVCT 2.2
-			   * The tag value has been changed for RVC2.2 from RVCT2.1.
-			   * We just ignore this. i.e., we get the symbol table size
-			   * from the nchain field of the hash table as noted in section
-			   * 3.2.2.2 of the BPABI.
-			   */
-			   break;
-		      case DT_SYMENT:
-			   iDllData->iSymSize = dyn[idx].d_val;
-			   break;
-		      case DT_SONAME:
-			   soNameOffset = dyn[idx].d_val;
-			   break;
-		      case DT_REL:
-			   iDllData->iRel = ELFADDR(Elf32_Rel, dyn, dyn[idx].d_val);
-			   break;
-		      case DT_RELSZ:
-			   iDllData->iRelSz = dyn[idx].d_val;
-			   break;
-		      case DT_RELENT:
-			   iDllData->iRelEnt = dyn[idx].d_val;
-			   break;
-		      case DT_NEEDED:
-			   iDllData->AddToDependency(dyn[idx].d_val);
-			   break;
-		      case DT_PLTRELSZ:
-		      case DT_PLTGOT:
-		      case DT_INIT:
-		      case DT_FINI:
-		      case DT_RPATH:
-		      case DT_SYMBOLIC:
-		      case DT_PLTREL:
-		      case DT_DEBUG:
-		      case DT_TEXTREL:
-		      case DT_JMPREL:
-		      case DT_BIND_NOW:
-			   break;
-		      default:
-		           Print(EPeError,"Unrecognized Dyn Array tag in image '%s'.\n", iFileName);
-			   return EFalse;
-		      }
-		      idx++;
-	       }
-	return iDllData->Init();
-	}
-
-
-void ELFFile::Close()
-//
-// close the ELF file
-//
-	{
-	HFile::Close(iFileHandle);
-	}
-
-
-
-TInt ELFFile::NumberOfImports() const
-//
-// Count the total number of imports for this image
-//
-	{
-	return iDllData->NumberOfImports();
-	}
-
-TInt ELFFile::NumberOfImportDlls() const
-//
-// Count the number of referenced Dlls
-//
-	{
-	return iDllData->NumberOfImportDlls();
-	}
-
-TInt ELFFile::NumberOfExports() const
-//
-// Count the number of exported symbols
-//
-	{
-	return iDllData->NumberOfExports();
-	}
-
-TInt ELFFile::NumberOfCodeRelocs() 
-	{ 
-	return iDllData->NumberOfCodeRelocs(); 
-	}
-
-TInt ELFFile::NumberOfDataRelocs() 
-	{ 
-	return iDllData->NumberOfDataRelocs(); 
-	}
-
-Elf32_Phdr * ELFFile::GetSegmentFromAddr(Elf32_Addr addr)
-	{
-	TInt nphdrs = iElfFile->e_phnum;
-	for (TInt idx = 0; idx < nphdrs; idx++)
-	        {
-		// take advantage of unsignedness 
-		if ((addr - iPhdr[idx].p_vaddr) < iPhdr[idx].p_memsz) return &iPhdr[idx];
-		}
-	return NULL;
-	}
-
-
-TInt ELFFile::NumberOfRelocs()
-	{
-	return iDllData->NumberOfRelocs();
-	}
-
-TUint16 ELFFile::GetRelocType(Elf32_Rel *aReloc)
-    {
-	// We work out the type by figuring out the segment of the reloc
-	TInt segmentIdx = ELF32_R_SYM(aReloc->r_info);
-	
-	// check to see if its a reserved or special index.
-	if ((!segmentIdx) || ((segmentIdx >= SHN_LORESERVE) && (segmentIdx <= SHN_HIRESERVE)))
-		// up until now these have been treated as KInferredRelocType, so lets continue...
-		return KInferredRelocType;
-			
-	// need to see if this section is executable or writable
-	if (iPhdr[segmentIdx-1].p_flags & PF_X) 
-		return KTextRelocType;
-	if (iPhdr[segmentIdx-1].p_flags & PF_W) 
-		return KDataRelocType;
-	// perhaps we should error here.
-	return KInferredRelocType;
-	}
-
-TBool ELFFile::GetRelocs(Elf32_Rel **aCodeRelocs, Elf32_Rel **aDataRelocs)
-        {
-	return iDllData->GetRelocs(aCodeRelocs, aDataRelocs);
-	}
-
-TUint ELFFile::GetCodeSize()
-    {
-	return iCodeSegmentHdr->p_filesz;
-	}
-
-TBool ELFFile::HasInitialisedData()
-	{
-	return iDataSegmentHdr != NULL && iDataSegmentHdr->p_filesz != 0;
-	}
-
-TUint ELFFile::GetDataSize()
-    {
-	return iDataSegmentHdr != NULL ? iDataSegmentHdr->p_filesz : 0;
-	}
-
-TBool ELFFile::HasBssData()
-	{
-	return iDataSegmentHdr != NULL && (iDataSegmentHdr->p_memsz - iDataSegmentHdr->p_filesz) != 0;
-	}
-
-TUint ELFFile::GetBssSize()
-    {
-	return iDataSegmentHdr != NULL ? iDataSegmentHdr->p_memsz - iDataSegmentHdr->p_filesz: 0;
-	}
-
-
-
-
-
-
-TBool ELFFile::IsValidFileHeader(Elf32_Ehdr * iElfFile)
- 	{
-        if (!(iElfFile->e_ident[EI_MAG0] == ELFMAG0 &&
-	      iElfFile->e_ident[EI_MAG1] == ELFMAG1 &&
-	      iElfFile->e_ident[EI_MAG2] == ELFMAG2 &&
-	      iElfFile->e_ident[EI_MAG3] == ELFMAG3))
-		{
-                Print(EPeError,"Invalid ELF magic.\n");
-		return EFalse;
-		}
-
-        if (iElfFile->e_ident[EI_CLASS] != ELFCLASS32)
-		{
-                Print(EPeError,"File is not a 32 bit object file.\n");
-		return EFalse;
-		}
-        if (iElfFile->e_ident[EI_DATA] != ELFDATA2LSB)
-		{
-                Print(EPeError,"File data encoding is not Little Endian.\n");
-		return EFalse;
-		}
-
-  	if (iElfFile->e_machine != EM_ARM)
-		{
-		Print(EPeError,"File does not target ARM/THUMB processors.\n");
-		return EFalse;
-		}
-
-  	if (!(iElfFile->e_type == ET_EXEC || iElfFile->e_type == ET_DYN))
-		{
-		Print(EPeError,"File is neither an executable nor a shared object\n");
-		return EFalse;
-		}
-
-	return ETrue;
-	}
-
-
-// Get details of the next import to fix-up in the current file. Fill in the name of the dll 
-//it is imported from, the ordinal number and the address to write back to.
-#define ORDINAL_DONE 0x40000000
-
-
-// The following static functions are passed an array of PE files to operate on
-
-Elf32_Sym * ELFFile::FindSymbol(const TText *aName)
-    {
-	Elf32_Shdr * s = ELFADDR(Elf32_Shdr, iElfFile, iElfFile->e_shoff);	
-	TInt symIdx = iSymIdx;
-	Elf32_Sym * sym = iSymTab;
-	TInt nSyms = s[symIdx].sh_size / s[symIdx].sh_entsize;
-	char * symStringtable = ELFADDR(char, iElfFile, s[s[symIdx].sh_link].sh_offset);
-	for (TInt jdx = 0; jdx < nSyms; jdx++)
-	    {
-		if (!strcmp(&symStringtable[sym[jdx].st_name], (char *)aName)) 
-			return &sym[jdx];
-		}
-	return (Elf32_Sym *)0;
-    }
-
-TBool ELFFile::SymbolPresent(TText *aName)
-    {
-	return (FindSymbol(aName) != 0);
-    }
-
-TBool ELFFile::GetExceptionIndexInfo(TUint32 &aOffset)
-    {
-    const TText * aBase = (TText *)".ARM.exidx$$Base";
-    const TText * aLimit = (TText *)".ARM.exidx$$Limit";
-	Elf32_Sym * exidxBase = FindSymbol(aBase);
-	Elf32_Sym * exidxLimit = FindSymbol(aLimit);
-	if (exidxBase && exidxLimit && (exidxLimit->st_value - exidxBase->st_value)) 
-	    {
-		const TText * aExceptionDescriptor = (TText *)"Symbian$$CPP$$Exception$$Descriptor";
-		Elf32_Sym * aED = FindSymbol(aExceptionDescriptor);
-		if (aED) 
-			{
-			// Set bottom bit so 0 in header slot means an old binary.
-			// The decriptor is always aligned on a 4 byte boundary.
-			aOffset = (aED->st_value - iLinkedBase) | 0x00000001;
-			return ETrue;
-			}
-		else
-			{
-			Print(EPeError,"Executable has exception table but no exception descriptor\n");
-			exit(666);
-			}
-		}
-	return EFalse;
-    }
-
-TBool ELFFile::SetUpLookupTable()
-{
-	if(!iDllData->CreateSymLookupTable() ) {
-		Print(EPeError,"Failed to create named symbol lookup information\n");
-		return FALSE;
-	}
-	if(!iDllData->CreateDependency()){
-		Print(EPeError,"Failed to create dependency ordering for named symbol lookup\n");
-		return FALSE;
-	}
-
-	iDllData->SetExportSymInfo();
-	return TRUE;
-}
-
-void ELFFile::GetExportSymInfoHeader(E32EpocExpSymInfoHdr& aSymInfoHdr)
-{
-	iDllData->GetExportSymInfoHeader(aSymInfoHdr);
-}
-
-void ELFFile::SetLookupTblBase(TInt aBaseOffset)
-{
-	iDllData->SetLookupTblBase(aBaseOffset);
-}
-
-TInt ELFFile::GetLookupTblSize()
-{
-	return iDllData->GetLookupTblSize();
-}
-
-TUint ELFFile::GetSymLookupSection(char* aBuff)
-{
-	return iDllData->GetSymLookupSection(aBuff);
-}
-
+/*
+* Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+
+#include <e32def.h>
+#include <e32std.h>
+#include "elftran.h"
+#include "elfdefs.h"
+#include "elffile.h"
+#include "elfdll.h"
+#include "h_utl.h"
+#include <string.h>
+#include <stdlib.h>
+
+TBool hadText, hadReloc = EFalse;
+
+ELFFile::ELFFile() 
+    :	iHeapCommittedSize(0x1000), iHeapReservedSize(0x100000), iStackCommittedSize(0),
+		iFileName(0), iFileHandle(-1) , iElfFile(0), 
+  	iDynamicSegmentHdr(0), iDynamicSegmentIdx(0),
+		iCodeSegmentHdr(0), iCodeSegmentIdx(0), 
+		iDataSegmentHdr(0), iDataSegmentIdx(0),
+  	iDllData(0), iCpu(ECpuUnknown)
+  	{}
+
+ELFFile::~ELFFile()
+  //
+  // Destructor
+  //
+	{
+	if(iFileName)
+		delete [] iFileName;
+	delete iElfFile;
+	delete iDllData;
+	}
+
+
+TBool ELFFile::Init(const char* aFileName)
+//
+// Read the ELF file into memory
+//
+ 	{
+	if(iFileName){
+		delete [] iFileName;	
+		iFileName = 0;
+	}
+	size_t length = strlen(aFileName) + 1 ;
+	iFileName = new char[length];
+	memcpy (iFileName, aFileName,length);
+
+	TInt error = HFile::Open(iFileName, &iFileHandle);
+	if (error!=0)
+		return EFalse;
+
+	TInt flength = HFile::GetLength(iFileHandle);
+
+	iElfFile = (Elf32_Ehdr *)HMem::Alloc(0,flength);
+	if (!iElfFile)
+		{
+		Print(EPeError,"Failed to allocate memory to read in file.\n");
+		Close();
+		return EFalse;
+		}
+
+	if (!HFile::Read(iFileHandle,iElfFile,flength))
+		{
+		Print(EPeError,"Unable to read file %s.\n",iFileName);
+		Close();
+		return EFalse;
+		}
+
+        Close();
+
+	if (!IsValidFileHeader(iElfFile))
+		{
+		Print(EPeError,"Invalid file header.\n");
+		return EFalse;
+		}
+	// we only support this....for the moment
+	iCpu = ECpuArmV4;
+
+	if (!InitHeaders()) return EFalse;
+	
+	if (!InitDllData()) return EFalse;
+
+	iEntryPoint = iElfFile->e_entry;
+
+	iCodeSize = GetCodeSize();
+	iDataSize = GetDataSize();
+	iBssSize = GetBssSize();
+
+	iStackReservedSize = 0x2000;
+	iStackCommittedSize = 0x2000;
+
+ 	iLinkedBase = iCodeSegmentHdr->p_vaddr;
+	
+	iImageIsDll = iDllData->ImageIsDll();
+
+	return ETrue;
+	}
+
+char * ELFFile::CreateImportSection(TInt &aSize)
+//
+// get ELFDLLData to do it
+//
+	{
+	TInt size;
+	char * newSection = iDllData->CreateImportSection(size);
+	aSize = size;
+	return newSection;
+	}
+
+TUint ELFFile::GetExportTableOffset(void)
+        {
+	return iDllData->GetExportTableOffset();
+	}
+
+TBool ELFFile::InitHeaders(void)
+        {
+	TInt nphdrs = iElfFile->e_phnum;
+	if (nphdrs)
+	       {
+	       // Find the dynamic segment
+	       Elf32_Phdr * aPhdr = ELFADDR(Elf32_Phdr, iElfFile, iElfFile->e_phoff);
+	       iPhdr = aPhdr;
+	       for (TInt idx = 0; idx < nphdrs; idx++)
+					{
+					Elf32_Word ptype = aPhdr[idx].p_type;
+					if (ptype == PT_DYNAMIC)
+							{
+							iDynamicSegmentHdr = &aPhdr[idx];
+							iDynamicSegmentIdx = idx;
+							}
+      				else if (ptype == PT_LOAD && 
+							 (aPhdr[idx].p_flags & (PF_X + PF_ARM_ENTRY)))
+							{
+							iCodeSegmentHdr = &aPhdr[idx];
+							iCodeSegmentIdx = idx;
+							}
+      				else if (ptype == PT_LOAD && 
+							 (aPhdr[idx].p_flags & (PF_W + PF_R)))
+							{
+							iDataSegmentHdr = &aPhdr[idx];
+							iDataSegmentIdx = idx;
+							}
+					}
+	       }
+	
+	// cache pointer to symbol table
+
+	// Get section header table
+	Elf32_Shdr * s = ELFADDR(Elf32_Shdr, iElfFile, iElfFile->e_shoff);
+	// Index of section header for section header string table
+	TInt stIdx = iElfFile->e_shstrndx;
+	TInt symIdx = -1;
+	// Section name string table
+	char * stringtable = ELFADDR(char, iElfFile, s[stIdx].sh_offset);
+	// the index at which we find '.symtab' is the index of the symtab section
+	for (TInt idx = 0; idx < iElfFile->e_shnum; idx++)
+	    {
+		if (idx != stIdx)
+		       {
+		       if (!strcmp(&stringtable[s[idx].sh_name], ".symtab"))
+			      {
+			      symIdx = idx;
+			      break;
+			      }
+		       }
+		}
+	if (symIdx == -1) return EFalse;
+
+	// save section header table
+	iSectionHeaderTable = s;
+	// save the index
+	iSymIdx = symIdx;	
+	// here's the symbol table
+	iSymTab = ELFADDR(Elf32_Sym, iElfFile, s[symIdx].sh_offset);
+	return ETrue;
+	}
+
+TBool ELFFile::InitDllData(void)
+	{
+	if (!iDynamicSegmentHdr)
+	       {
+#if defined(_DEBUG)
+	       Print(EWarning, "Image '%s' has no import/export data.\n", iFileName);
+#endif
+	       return ETrue;
+	       }
+	iDllData = new ELFDllData(this);
+	if (!iDllData)
+	       {
+	       Print(EPeError, "Out of memory allocating DLL data\n");
+	       return EFalse;
+	       }
+
+	Elf32_Dyn * dyn = ELFADDR(Elf32_Dyn, iElfFile, iDynamicSegmentHdr->p_offset);
+	TInt idx = 0;
+	TInt soNameOffset = 0;
+	while(dyn[idx].d_tag != DT_NULL) // best to make it explicit
+	       {
+	       switch (dyn[idx].d_tag)
+		      {
+		      case DT_HASH:
+			   iDllData->iHashTable = ELFADDR(Elf32_HashTable, dyn, dyn[idx].d_val);
+			   break;
+		      case DT_STRTAB:
+			   iDllData->iDynStrTab = ELFADDR(char, dyn, dyn[idx].d_val);
+			   break;
+		      case DT_SYMTAB:
+			   iDllData->iDynSymTab = ELFADDR(Elf32_Sym, dyn, dyn[idx].d_val);
+			   break;
+		      case DT_RELA:
+			   iDllData->iRela = ELFADDR(Elf32_Rela, dyn, dyn[idx].d_val);
+			   break;
+		      case DT_RELASZ:
+			   iDllData->iRelaSz = dyn[idx].d_val;
+			   break;
+		      case DT_RELAENT:
+			   iDllData->iRelaSz = dyn[idx].d_val;
+			   break;
+		      case DT_STRSZ:
+			   iDllData->iDynStrTabSize = dyn[idx].d_val;
+			   break;
+		      case DT_ARM_SYMTABSZ_21: //For RVCT2.1
+			   //iDllData->iDynSymTabSize = dyn[idx].d_val;
+		      case DT_ARM_SYMTABSZ:
+			  /* This is same as DT_ARM_SYMTABSZ_21, but for RVCT 2.2
+			   * The tag value has been changed for RVC2.2 from RVCT2.1.
+			   * We just ignore this. i.e., we get the symbol table size
+			   * from the nchain field of the hash table as noted in section
+			   * 3.2.2.2 of the BPABI.
+			   */
+			   break;
+		      case DT_SYMENT:
+			   iDllData->iSymSize = dyn[idx].d_val;
+			   break;
+		      case DT_SONAME:
+			   soNameOffset = dyn[idx].d_val;
+			   break;
+		      case DT_REL:
+			   iDllData->iRel = ELFADDR(Elf32_Rel, dyn, dyn[idx].d_val);
+			   break;
+		      case DT_RELSZ:
+			   iDllData->iRelSz = dyn[idx].d_val;
+			   break;
+		      case DT_RELENT:
+			   iDllData->iRelEnt = dyn[idx].d_val;
+			   break;
+		      case DT_NEEDED:
+			   iDllData->AddToDependency(dyn[idx].d_val);
+			   break;
+		      case DT_PLTRELSZ:
+		      case DT_PLTGOT:
+		      case DT_INIT:
+		      case DT_FINI:
+		      case DT_RPATH:
+		      case DT_SYMBOLIC:
+		      case DT_PLTREL:
+		      case DT_DEBUG:
+		      case DT_TEXTREL:
+		      case DT_JMPREL:
+		      case DT_BIND_NOW:
+			   break;
+		      default:
+		           Print(EPeError,"Unrecognized Dyn Array tag in image '%s'.\n", iFileName);
+			   return EFalse;
+		      }
+		      idx++;
+	       }
+	return iDllData->Init();
+	}
+
+
+void ELFFile::Close()
+//
+// close the ELF file
+//
+	{
+	HFile::Close(iFileHandle);
+	}
+
+
+
+TInt ELFFile::NumberOfImports() const
+//
+// Count the total number of imports for this image
+//
+	{
+	return iDllData->NumberOfImports();
+	}
+
+TInt ELFFile::NumberOfImportDlls() const
+//
+// Count the number of referenced Dlls
+//
+	{
+	return iDllData->NumberOfImportDlls();
+	}
+
+TInt ELFFile::NumberOfExports() const
+//
+// Count the number of exported symbols
+//
+	{
+	return iDllData->NumberOfExports();
+	}
+
+TInt ELFFile::NumberOfCodeRelocs() 
+	{ 
+	return iDllData->NumberOfCodeRelocs(); 
+	}
+
+TInt ELFFile::NumberOfDataRelocs() 
+	{ 
+	return iDllData->NumberOfDataRelocs(); 
+	}
+
+Elf32_Phdr * ELFFile::GetSegmentFromAddr(Elf32_Addr addr)
+	{
+	TInt nphdrs = iElfFile->e_phnum;
+	for (TInt idx = 0; idx < nphdrs; idx++)
+	        {
+		// take advantage of unsignedness 
+		if ((addr - iPhdr[idx].p_vaddr) < iPhdr[idx].p_memsz) return &iPhdr[idx];
+		}
+	return NULL;
+	}
+
+
+TInt ELFFile::NumberOfRelocs()
+	{
+	return iDllData->NumberOfRelocs();
+	}
+
+TUint16 ELFFile::GetRelocType(Elf32_Rel *aReloc)
+    {
+	// We work out the type by figuring out the segment of the reloc
+	TInt segmentIdx = ELF32_R_SYM(aReloc->r_info);
+	
+	// check to see if its a reserved or special index.
+	if ((!segmentIdx) || ((segmentIdx >= SHN_LORESERVE) && (segmentIdx <= SHN_HIRESERVE)))
+		// up until now these have been treated as KInferredRelocType, so lets continue...
+		return KInferredRelocType;
+			
+	// need to see if this section is executable or writable
+	if (iPhdr[segmentIdx-1].p_flags & PF_X) 
+		return KTextRelocType;
+	if (iPhdr[segmentIdx-1].p_flags & PF_W) 
+		return KDataRelocType;
+	// perhaps we should error here.
+	return KInferredRelocType;
+	}
+
+TBool ELFFile::GetRelocs(Elf32_Rel **aCodeRelocs, Elf32_Rel **aDataRelocs)
+        {
+	return iDllData->GetRelocs(aCodeRelocs, aDataRelocs);
+	}
+
+TUint ELFFile::GetCodeSize()
+    {
+	return iCodeSegmentHdr->p_filesz;
+	}
+
+TBool ELFFile::HasInitialisedData()
+	{
+	return iDataSegmentHdr != NULL && iDataSegmentHdr->p_filesz != 0;
+	}
+
+TUint ELFFile::GetDataSize()
+    {
+	return iDataSegmentHdr != NULL ? iDataSegmentHdr->p_filesz : 0;
+	}
+
+TBool ELFFile::HasBssData()
+	{
+	return iDataSegmentHdr != NULL && (iDataSegmentHdr->p_memsz - iDataSegmentHdr->p_filesz) != 0;
+	}
+
+TUint ELFFile::GetBssSize()
+    {
+	return iDataSegmentHdr != NULL ? iDataSegmentHdr->p_memsz - iDataSegmentHdr->p_filesz: 0;
+	}
+
+
+
+
+
+
+TBool ELFFile::IsValidFileHeader(Elf32_Ehdr * iElfFile)
+ 	{
+        if (!(iElfFile->e_ident[EI_MAG0] == ELFMAG0 &&
+	      iElfFile->e_ident[EI_MAG1] == ELFMAG1 &&
+	      iElfFile->e_ident[EI_MAG2] == ELFMAG2 &&
+	      iElfFile->e_ident[EI_MAG3] == ELFMAG3))
+		{
+                Print(EPeError,"Invalid ELF magic.\n");
+		return EFalse;
+		}
+
+        if (iElfFile->e_ident[EI_CLASS] != ELFCLASS32)
+		{
+                Print(EPeError,"File is not a 32 bit object file.\n");
+		return EFalse;
+		}
+        if (iElfFile->e_ident[EI_DATA] != ELFDATA2LSB)
+		{
+                Print(EPeError,"File data encoding is not Little Endian.\n");
+		return EFalse;
+		}
+
+  	if (iElfFile->e_machine != EM_ARM)
+		{
+		Print(EPeError,"File does not target ARM/THUMB processors.\n");
+		return EFalse;
+		}
+
+  	if (!(iElfFile->e_type == ET_EXEC || iElfFile->e_type == ET_DYN))
+		{
+		Print(EPeError,"File is neither an executable nor a shared object\n");
+		return EFalse;
+		}
+
+	return ETrue;
+	}
+
+
+// Get details of the next import to fix-up in the current file. Fill in the name of the dll 
+//it is imported from, the ordinal number and the address to write back to.
+#define ORDINAL_DONE 0x40000000
+
+
+// The following static functions are passed an array of PE files to operate on
+
+Elf32_Sym * ELFFile::FindSymbol(const char* aName)
+    {
+	Elf32_Shdr * s = ELFADDR(Elf32_Shdr, iElfFile, iElfFile->e_shoff);	
+	TInt symIdx = iSymIdx;
+	Elf32_Sym * sym = iSymTab;
+	TInt nSyms = s[symIdx].sh_size / s[symIdx].sh_entsize;
+	char * symStringtable = ELFADDR(char, iElfFile, s[s[symIdx].sh_link].sh_offset);
+	for (TInt jdx = 0; jdx < nSyms; jdx++)
+	    {
+		if (!strcmp(&symStringtable[sym[jdx].st_name], (char *)aName)) 
+			return &sym[jdx];
+		}
+	return (Elf32_Sym *)0;
+    }
+
+TBool ELFFile::SymbolPresent(const char* aName)
+    {
+	return (FindSymbol(aName) != 0);
+    }
+
+TBool ELFFile::GetExceptionIndexInfo(TUint32 &aOffset)
+    {
+	Elf32_Sym * exidxBase = FindSymbol(".ARM.exidx$$Base");
+	Elf32_Sym * exidxLimit = FindSymbol(".ARM.exidx$$Limit");
+	if (exidxBase && exidxLimit && (exidxLimit->st_value - exidxBase->st_value)) 
+	    {
+		Elf32_Sym * aED = FindSymbol("Symbian$$CPP$$Exception$$Descriptor");
+		if (aED) 
+			{
+			// Set bottom bit so 0 in header slot means an old binary.
+			// The decriptor is always aligned on a 4 byte boundary.
+			aOffset = (aED->st_value - iLinkedBase) | 0x00000001;
+			return ETrue;
+			}
+		else
+			{
+			Print(EPeError,"Executable has exception table but no exception descriptor\n");
+			exit(666);
+			}
+		}
+	return EFalse;
+    }
+
+TBool ELFFile::SetUpLookupTable()
+{
+	if(!iDllData->CreateSymLookupTable() ) {
+		Print(EPeError,"Failed to create named symbol lookup information\n");
+		return FALSE;
+	}
+	if(!iDllData->CreateDependency()){
+		Print(EPeError,"Failed to create dependency ordering for named symbol lookup\n");
+		return FALSE;
+	}
+
+	iDllData->SetExportSymInfo();
+	return TRUE;
+}
+
+void ELFFile::GetExportSymInfoHeader(E32EpocExpSymInfoHdr& aSymInfoHdr)
+{
+	iDllData->GetExportSymInfoHeader(aSymInfoHdr);
+}
+
+void ELFFile::SetLookupTblBase(TInt aBaseOffset)
+{
+	iDllData->SetLookupTblBase(aBaseOffset);
+}
+
+TInt ELFFile::GetLookupTblSize()
+{
+	return iDllData->GetLookupTblSize();
+}
+
+TUint ELFFile::GetSymLookupSection(char* aBuff)
+{
+	return iDllData->GetSymLookupSection(aBuff);
+}
+
--- a/bintools/elftools/elftran/elf_imp.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/elftools/elftran/elf_imp.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,39 +1,39 @@
-/*
-* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include <stdlib.h>
-#include <string.h>
-#include <e32std.h>
-#include <h_utl.h>
-#include "e32ldfmt.h"
-#include "elftran.h"
-#include "elffile.h"
-
-char* E32ImageFile_ELF::CreateImportSection(ELFFile& aElfFile, TInt& aSize)
-//
-// get the ELFFile to do it for us.
-//
-	{
-	TInt size;
-	char * newSection = aElfFile.CreateImportSection(size);
-	aSize = size;
-	return newSection;
-	}
-
-
-
+/*
+* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#include <stdlib.h>
+#include <string.h>
+#include <e32std.h>
+#include "h_utl.h"
+#include "e32ldfmt.h"
+#include "elftran.h"
+#include "elffile.h"
+
+char* E32ImageFile_ELF::CreateImportSection(ELFFile& aElfFile, TInt& aSize)
+//
+// get the ELFFile to do it for us.
+//
+	{
+	TInt size;
+	char * newSection = aElfFile.CreateImportSection(size);
+	aSize = size;
+	return newSection;
+	}
+
+
+
--- a/bintools/elftools/elftran/elf_tran.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/elftools/elftran/elf_tran.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,301 +1,301 @@
-/*
-* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include <time.h>
-#include <malloc.h>
-#include <string.h>
-#include "elftran.h"
-#include <e32std.h>
-#include <elfdefs.h>
-#include "elffile.h"
-#include <h_ver.h>
-#include <h_utl.h>
-
-extern TUid gUid1, gUid2, gUid3;
-extern int gSetUid1, gSetUid2, gSetUid3;
-
-int gAlignConstSection=FALSE;
-TUint gConstSectionAddressMask=0;
-
-E32ImageFile* E32ImageFile::New()
-	{
-	return new E32ImageFile_ELF;
-	}
-
-E32ImageFile_ELF::E32ImageFile_ELF()
-	{
-	}
-
-E32ImageFile_ELF::~E32ImageFile_ELF()
-	{
-	}
-
-TInt E32ImageFile_ELF::DoCodeHeader(ELFFile &aElfFile)
-//
-// Calculate the code parts of the ELFFile
-//
-	{
-
-	TInt size=ALIGN4(aElfFile.GetCodeSize());
-	iHdr->iCodeSize = iHdr->iTextSize = size;
-	// make it the offset from the beginning of the file.....
-	if(iHdr->iExportDirCount==0)
-		iHdr->iExportDirOffset = 0;
-	else
-		iHdr->iExportDirOffset = aElfFile.GetExportTableOffset() + iHdr->iCodeOffset;
-
-	return size;
-	}
-
-TInt E32ImageFile_ELF::DoDataHeader(ELFFile &aElfFile, TUint aDataBase)
-	{
-
-	if (aDataBase==0 && aElfFile.iDataSegmentHdr)
-		aDataBase=aElfFile.iDataSegmentHdr->p_vaddr;
-	TInt size=0;
-
-	iHdr->iDataBase=aDataBase;
-
-	if (aElfFile.HasInitialisedData())
-		{
-	        size=ALIGN4(aElfFile.GetDataSize());
-		iHdr->iDataOffset = iHdr->iCodeOffset + iHdr->iCodeSize;
-		iHdr->iDataSize = size;
-		}
-	if (aElfFile.HasBssData())
-		{
-		iHdr->iBssSize = ALIGN4(aElfFile.GetBssSize());
-		}
-	return size;
-	}
-
-TInt E32ImageFile_ELF::CopyCode(char *p, ELFFile &aElfFile)
-//
-// Copies the files code sections to p
-// returns the number of bytes copied or KErrGeneral
-//
-	{
-	TInt size=aElfFile.GetCodeSize();
-	memcpy(p, (char *)aElfFile.GetCode(), size);
-	p+=ALIGN4(size);
-	return iHdr->iCodeSize = size;
-	}
-
-TInt E32ImageFile_ELF::CopyData(char *p, ELFFile &aElfFile)
-	{
-	TInt size=aElfFile.GetDataSize();
-	if (size) memcpy(p, (char *)aElfFile.GetData(), size);
-	return size;
-	}
-
-TInt E32ImageFile_ELF::Translate(const char* aFileName, TUint aDataBase, TBool aAllowDllData, \
-								 TBool aSymLkupEnabled)
-//
-// Translate a ELF format file to a E32Image file
-//
-	
-{
-	iSource = EElfFile;
-	ELFFile elffile;
-	if (!elffile.Init((const TText * const)aFileName)) return KErrGeneral;
-		
-	iFileName = strdup(aFileName);
-
-	Adjust(ALIGN4(sizeof(E32ImageHeaderV)));	// fixed for now because holes not supported
-	SetDefaultHeader();
-	iHdr->iDllRefTableCount = elffile.NumberOfImportDlls();
-	iHdr->iExportDirCount = elffile.NumberOfExports();
-	iHdr->iCodeBase = elffile.iLinkedBase;
-
-	if(aSymLkupEnabled)
-	{
-		if( !SetUpLookupTable(elffile) )
-			return KErrGeneral;
-	}
-
-
-	TInt size = ALIGN4(sizeof(E32ImageHeaderV));	// fixed for now because holes not supported
-	iHdr->iCodeOffset = size;
-	TInt pos = size;
-	size+=DoCodeHeader(elffile);
-
-	size += DoSymbolLookupHeader(elffile, size - pos);
-
-	TInt nimports=elffile.NumberOfImports();
-	TInt importSectionSize;
-	char *newImportSection=CreateImportSection(elffile, importSectionSize);
-
-	TInt t=DoDataHeader(elffile, aDataBase);
-	if (t>0)
-		{
-		iHdr->iDataOffset = size;
-		size += t;
-		}
-	if (importSectionSize!=0)
-		{
-		iHdr->iImportOffset=size;
-		size+=ALIGN4(importSectionSize);
-		}
-
-	char *newCodeRelocs=NULL;
-	char *newDataRelocs=NULL;
-	TInt codeRelocSize=0, dataRelocSize=0;
-	TInt nCodeRelocs=elffile.NumberOfCodeRelocs();
-	TInt nDataRelocs=elffile.NumberOfDataRelocs();
-	if (nCodeRelocs + nDataRelocs)
-		{
-		Elf32_Rel **codeRelocs=new Elf32_Rel * [nCodeRelocs];
-		Elf32_Rel **dataRelocs=new Elf32_Rel * [nDataRelocs];
-		if (!elffile.GetRelocs(codeRelocs, dataRelocs)) return KErrGeneral;
-		       
-		FixRelocs(elffile, codeRelocs, dataRelocs);
-		if (elffile.iCodeSegmentHdr)
-			newCodeRelocs=CreateRelocs(elffile, codeRelocs, nCodeRelocs, codeRelocSize, elffile.iCodeSegmentHdr->p_vaddr);
-		if (elffile.iDataSegmentHdr)
-			newDataRelocs=CreateRelocs(elffile, dataRelocs, nDataRelocs, dataRelocSize, elffile.iDataSegmentHdr->p_vaddr);
-		if (codeRelocSize)
-			{
-			iHdr->iCodeRelocOffset = size;
-			size += codeRelocSize;
-			}
-		if (dataRelocSize)
-			{
-			iHdr->iDataRelocOffset = size;
-			size += dataRelocSize;
-			}
-		delete [] codeRelocs;
-		delete [] dataRelocs;
-		}
-
-	Adjust(size);
-	t=CopyCode(iData + pos, elffile);
-	if (t<0)
-		return KErrGeneral;
-	pos += t;
-	t = CopyExportSymInfo(iData+pos, elffile);
-	if (t<0)
-		return KErrGeneral;
-	pos += t;
-
-	pos += CopyData(iData + pos, elffile);
-	if (nimports)
-		{
-		memcpy(iData + pos, newImportSection, importSectionSize);
-		pos += ALIGN4(importSectionSize);
-		}
-	if (codeRelocSize)
-		{
-		memcpy(iData + pos, newCodeRelocs, codeRelocSize);
-		pos += codeRelocSize;
-		}
-	if (dataRelocSize)
-		{
-		memcpy(iData + pos, newDataRelocs, dataRelocSize);
-		pos += dataRelocSize;
-		}
-
-	// locate the entry point
-	TUint entryPointOffset=elffile.GetEntryPointOffset();
-
-	// Arrange a header for this E32 Image
-	iHdr->iCpuIdentifier = (TUint16)ECpuArmV4;
-	// Import format is ELF-derived
-	iHdr->iFlags |= KImageImpFmt_ELF;
-	// ABI is ARM EABI
-	iHdr->iFlags |= KImageABI_EABI;
-	if (ImageIsDll(elffile))
-		{
-		iHdr->iFlags |= KImageDll;
-		if (iHdr->iDataSize && !aAllowDllData)
-			return Print(EError, "Dll '%s' has initialised data.\n", iFileName);
-		if (iHdr->iBssSize  && !aAllowDllData)
-			return Print(EError, "Dll '%s' has uninitialised data.\n", iFileName);
-		}
-	iHdr->iHeapSizeMin = elffile.iHeapCommittedSize;
-	iHdr->iHeapSizeMax = elffile.iHeapReservedSize;
-	iHdr->iStackSize = elffile.iStackCommittedSize;
-	iHdr->iEntryPoint = entryPointOffset;
-	TInt r = DetermineEntryPointType();
-	if (r == KErrCorrupt)
-		return Print(EError, "File '%s': Bad Entry Point.\n", iFileName);
-	else if (r == KErrNotSupported)
-		return Print(EError, "File '%s': Bad Entry Point Type.\n", iFileName);
-
-	SetUpExceptions(elffile);
-
-	delete [] newImportSection;
-	delete [] newCodeRelocs;
-	delete [] newDataRelocs;
-
-	return KErrNone;
-	}
-
-TBool E32ImageFile_ELF::Translate(ELFFile &aElfFile)
-    {
-    // VT fix for warning
-    // fix warning in Linux
-    return Translate((const char*)aElfFile.iFileName, 0, EFalse);
-    }
-
-TBool E32ImageFile_ELF::ImageIsDll(ELFFile& aElfFile)
-    {
-    return aElfFile.ImageIsDll();
-    }
-
-void E32ImageFile_ELF::SetUpExceptions(ELFFile &aElfFile)
-    {
-    aElfFile.GetExceptionIndexInfo(iHdr->iExceptionDescriptor);
-    }
-
-void E32ImageFile_ELF::SetSymNameLookup(TInt aSymNameLkupEnabled)
-	{
-	if(aSymNameLkupEnabled)
-		iHdr->iFlags |= KImageNmdExpData;
-	else
-		iHdr->iFlags &= ~KImageNmdExpData;
-	}
-TBool E32ImageFile_ELF::IsNamedLookupEnabled()
-{
-	return (iHdr->iFlags & KImageNmdExpData);
-}
-
-TBool E32ImageFile_ELF::SetUpLookupTable(ELFFile &aElfFile)
-// Symbol lookup by name is enabled. Create the symbol table with names
-// and their values.
-{
-	if(!aElfFile.SetUpLookupTable() )
-		return FALSE;
-	SetSymNameLookup(TRUE);
-	return TRUE;
-}
-
-// Build the infrastructure for symbol lookup via name
-TInt E32ImageFile_ELF::DoSymbolLookupHeader(ELFFile &aElfFile, TInt aBaseOffset)
-	{
-	if(!IsNamedLookupEnabled())
-		return 0;
-	
-	aElfFile.SetLookupTblBase(aBaseOffset);
-	return aElfFile.GetLookupTblSize(); 
-	}
-TUint E32ImageFile_ELF::CopyExportSymInfo(char *p, ELFFile &aElfFile)
-	{
-	iHdr->iCodeSize += aElfFile.GetLookupTblSize();
-	iHdr->iTextSize = iHdr->iCodeSize ;
-	return aElfFile.GetSymLookupSection(p);
-	}
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#include <time.h>
+#include <malloc.h>
+#include <string.h>
+#include "elftran.h"
+#include <e32std.h>
+#include "elfdefs.h"
+#include "elffile.h"
+#include "h_ver.h"
+#include "h_utl.h"
+
+extern TUid gUid1, gUid2, gUid3;
+extern int gSetUid1, gSetUid2, gSetUid3;
+
+int gAlignConstSection=FALSE;
+TUint gConstSectionAddressMask=0;
+
+E32ImageFile* E32ImageFile::New()
+	{
+	return new E32ImageFile_ELF;
+	}
+
+E32ImageFile_ELF::E32ImageFile_ELF()
+	{
+	}
+
+E32ImageFile_ELF::~E32ImageFile_ELF()
+	{
+	}
+
+TInt E32ImageFile_ELF::DoCodeHeader(ELFFile &aElfFile)
+//
+// Calculate the code parts of the ELFFile
+//
+	{
+
+	TInt size=ALIGN4(aElfFile.GetCodeSize());
+	iHdr->iCodeSize = iHdr->iTextSize = size;
+	// make it the offset from the beginning of the file.....
+	if(iHdr->iExportDirCount==0)
+		iHdr->iExportDirOffset = 0;
+	else
+		iHdr->iExportDirOffset = aElfFile.GetExportTableOffset() + iHdr->iCodeOffset;
+
+	return size;
+	}
+
+TInt E32ImageFile_ELF::DoDataHeader(ELFFile &aElfFile, TUint aDataBase)
+	{
+
+	if (aDataBase==0 && aElfFile.iDataSegmentHdr)
+		aDataBase=aElfFile.iDataSegmentHdr->p_vaddr;
+	TInt size=0;
+
+	iHdr->iDataBase=aDataBase;
+
+	if (aElfFile.HasInitialisedData())
+		{
+	        size=ALIGN4(aElfFile.GetDataSize());
+		iHdr->iDataOffset = iHdr->iCodeOffset + iHdr->iCodeSize;
+		iHdr->iDataSize = size;
+		}
+	if (aElfFile.HasBssData())
+		{
+		iHdr->iBssSize = ALIGN4(aElfFile.GetBssSize());
+		}
+	return size;
+	}
+
+TInt E32ImageFile_ELF::CopyCode(char *p, ELFFile &aElfFile)
+//
+// Copies the files code sections to p
+// returns the number of bytes copied or KErrGeneral
+//
+	{
+	TInt size=aElfFile.GetCodeSize();
+	memcpy(p, (char *)aElfFile.GetCode(), size);
+	p+=ALIGN4(size);
+	return iHdr->iCodeSize = size;
+	}
+
+TInt E32ImageFile_ELF::CopyData(char *p, ELFFile &aElfFile)
+	{
+	TInt size=aElfFile.GetDataSize();
+	if (size) memcpy(p, (char *)aElfFile.GetData(), size);
+	return size;
+	}
+
+TInt E32ImageFile_ELF::Translate(const char* aFileName, TUint aDataBase, TBool aAllowDllData, \
+								 TBool aSymLkupEnabled)
+//
+// Translate a ELF format file to a E32Image file
+//
+	
+{
+	iSource = EElfFile;
+	ELFFile elffile;
+	if (!elffile.Init(aFileName)) return KErrGeneral;
+		
+	iFileName = strdup(aFileName);
+
+	Adjust(ALIGN4(sizeof(E32ImageHeaderV)));	// fixed for now because holes not supported
+	SetDefaultHeader();
+	iHdr->iDllRefTableCount = elffile.NumberOfImportDlls();
+	iHdr->iExportDirCount = elffile.NumberOfExports();
+	iHdr->iCodeBase = elffile.iLinkedBase;
+
+	if(aSymLkupEnabled)
+	{
+		if( !SetUpLookupTable(elffile) )
+			return KErrGeneral;
+	}
+
+
+	TInt size = ALIGN4(sizeof(E32ImageHeaderV));	// fixed for now because holes not supported
+	iHdr->iCodeOffset = size;
+	TInt pos = size;
+	size+=DoCodeHeader(elffile);
+
+	size += DoSymbolLookupHeader(elffile, size - pos);
+
+	TInt nimports=elffile.NumberOfImports();
+	TInt importSectionSize;
+	char *newImportSection=CreateImportSection(elffile, importSectionSize);
+
+	TInt t=DoDataHeader(elffile, aDataBase);
+	if (t>0)
+		{
+		iHdr->iDataOffset = size;
+		size += t;
+		}
+	if (importSectionSize!=0)
+		{
+		iHdr->iImportOffset=size;
+		size+=ALIGN4(importSectionSize);
+		}
+
+	char *newCodeRelocs=NULL;
+	char *newDataRelocs=NULL;
+	TInt codeRelocSize=0, dataRelocSize=0;
+	TInt nCodeRelocs=elffile.NumberOfCodeRelocs();
+	TInt nDataRelocs=elffile.NumberOfDataRelocs();
+	if (nCodeRelocs + nDataRelocs)
+		{
+		Elf32_Rel **codeRelocs=new Elf32_Rel * [nCodeRelocs];
+		Elf32_Rel **dataRelocs=new Elf32_Rel * [nDataRelocs];
+		if (!elffile.GetRelocs(codeRelocs, dataRelocs)) return KErrGeneral;
+		       
+		FixRelocs(elffile, codeRelocs, dataRelocs);
+		if (elffile.iCodeSegmentHdr)
+			newCodeRelocs=CreateRelocs(elffile, codeRelocs, nCodeRelocs, codeRelocSize, elffile.iCodeSegmentHdr->p_vaddr);
+		if (elffile.iDataSegmentHdr)
+			newDataRelocs=CreateRelocs(elffile, dataRelocs, nDataRelocs, dataRelocSize, elffile.iDataSegmentHdr->p_vaddr);
+		if (codeRelocSize)
+			{
+			iHdr->iCodeRelocOffset = size;
+			size += codeRelocSize;
+			}
+		if (dataRelocSize)
+			{
+			iHdr->iDataRelocOffset = size;
+			size += dataRelocSize;
+			}
+		delete [] codeRelocs;
+		delete [] dataRelocs;
+		}
+
+	Adjust(size);
+	t=CopyCode(iData + pos, elffile);
+	if (t<0)
+		return KErrGeneral;
+	pos += t;
+	t = CopyExportSymInfo(iData+pos, elffile);
+	if (t<0)
+		return KErrGeneral;
+	pos += t;
+
+	pos += CopyData(iData + pos, elffile);
+	if (nimports)
+		{
+		memcpy(iData + pos, newImportSection, importSectionSize);
+		pos += ALIGN4(importSectionSize);
+		}
+	if (codeRelocSize)
+		{
+		memcpy(iData + pos, newCodeRelocs, codeRelocSize);
+		pos += codeRelocSize;
+		}
+	if (dataRelocSize)
+		{
+		memcpy(iData + pos, newDataRelocs, dataRelocSize);
+		pos += dataRelocSize;
+		}
+
+	// locate the entry point
+	TUint entryPointOffset=elffile.GetEntryPointOffset();
+
+	// Arrange a header for this E32 Image
+	iHdr->iCpuIdentifier = (TUint16)ECpuArmV4;
+	// Import format is ELF-derived
+	iHdr->iFlags |= KImageImpFmt_ELF;
+	// ABI is ARM EABI
+	iHdr->iFlags |= KImageABI_EABI;
+	if (ImageIsDll(elffile))
+		{
+		iHdr->iFlags |= KImageDll;
+		if (iHdr->iDataSize && !aAllowDllData)
+			return Print(EError, "Dll '%s' has initialised data.\n", iFileName);
+		if (iHdr->iBssSize  && !aAllowDllData)
+			return Print(EError, "Dll '%s' has uninitialised data.\n", iFileName);
+		}
+	iHdr->iHeapSizeMin = elffile.iHeapCommittedSize;
+	iHdr->iHeapSizeMax = elffile.iHeapReservedSize;
+	iHdr->iStackSize = elffile.iStackCommittedSize;
+	iHdr->iEntryPoint = entryPointOffset;
+	TInt r = DetermineEntryPointType();
+	if (r == KErrCorrupt)
+		return Print(EError, "File '%s': Bad Entry Point.\n", iFileName);
+	else if (r == KErrNotSupported)
+		return Print(EError, "File '%s': Bad Entry Point Type.\n", iFileName);
+
+	SetUpExceptions(elffile);
+
+	delete [] newImportSection;
+	delete [] newCodeRelocs;
+	delete [] newDataRelocs;
+
+	return KErrNone;
+	}
+
+TBool E32ImageFile_ELF::Translate(ELFFile &aElfFile)
+    {
+    // VT fix for warning
+    // fix warning in Linux
+    return Translate((const char*)aElfFile.iFileName, 0, EFalse);
+    }
+
+TBool E32ImageFile_ELF::ImageIsDll(ELFFile& aElfFile)
+    {
+    return aElfFile.ImageIsDll();
+    }
+
+void E32ImageFile_ELF::SetUpExceptions(ELFFile &aElfFile)
+    {
+    aElfFile.GetExceptionIndexInfo(iHdr->iExceptionDescriptor);
+    }
+
+void E32ImageFile_ELF::SetSymNameLookup(TInt aSymNameLkupEnabled)
+	{
+	if(aSymNameLkupEnabled)
+		iHdr->iFlags |= KImageNmdExpData;
+	else
+		iHdr->iFlags &= ~KImageNmdExpData;
+	}
+TBool E32ImageFile_ELF::IsNamedLookupEnabled()
+{
+	return (iHdr->iFlags & KImageNmdExpData);
+}
+
+TBool E32ImageFile_ELF::SetUpLookupTable(ELFFile &aElfFile)
+// Symbol lookup by name is enabled. Create the symbol table with names
+// and their values.
+{
+	if(!aElfFile.SetUpLookupTable() )
+		return FALSE;
+	SetSymNameLookup(TRUE);
+	return TRUE;
+}
+
+// Build the infrastructure for symbol lookup via name
+TInt E32ImageFile_ELF::DoSymbolLookupHeader(ELFFile &aElfFile, TInt aBaseOffset)
+	{
+	if(!IsNamedLookupEnabled())
+		return 0;
+	
+	aElfFile.SetLookupTblBase(aBaseOffset);
+	return aElfFile.GetLookupTblSize(); 
+	}
+TUint E32ImageFile_ELF::CopyExportSymInfo(char *p, ELFFile &aElfFile)
+	{
+	iHdr->iCodeSize += aElfFile.GetLookupTblSize();
+	iHdr->iTextSize = iHdr->iCodeSize ;
+	return aElfFile.GetSymLookupSection(p);
+	}
--- a/bintools/elftools/getexports/geninf.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/elftools/getexports/geninf.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -159,8 +159,8 @@
 	Elf32_Sym * symtab = 0;
 	int nSyms = 0;
 	char * strtab = 0;
-	int i=0;
-
+	int i = 0;
+	
 	for (i = 0; (i < shnum); i++) {
 		if (shdr[i].sh_type == SHT_SYMTAB) {
 			symtab = ELFADDR(Elf32_Sym, eh, shdr[i].sh_offset);
@@ -283,7 +283,6 @@
 	int shoff = eh->e_shoff;                      // offset of section header table
 	if (shoff) {
 	Elf32_Shdr * shdr = ELFADDR(Elf32_Shdr, eh, shoff);
-	int i=0;
 
 	int shnum = eh->e_shnum;                    // number of section headers
 
@@ -307,7 +306,8 @@
 	Elf32_Sym * symtab = 0;
 	int nSyms = 0;
 	char * strtab = 0;
-
+	int i = 0;
+	
 	for (i = 0; (i < shnum); i++) {
 		if (shdr[i].sh_type == SHT_DYNSYM) {
 			symtab = ELFADDR(Elf32_Sym, eh, shdr[i].sh_offset);
@@ -350,7 +350,7 @@
 
 		int shstrndx = eh->e_shstrndx;
 		char *aSHdrStrTab = ELFADDR(char, eh, shdr[shstrndx].sh_offset);
-		int i=0;
+		int i;
 		Elf32_Verdef *aVerDef = 0;
 		char *aStringTab = 0;
 		for(i = 0; i < shnum; i++) {
--- a/bintools/elftools/group/bld.inf	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/elftools/group/bld.inf	Tue Jun 29 14:52:54 2010 +0800
@@ -1,44 +1,45 @@
-/*
-* Copyright (c) 1999-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Base tools (e.g. petran)
-*
-*/
-
-
-
-PRJ_PLATFORMS
-TOOLS TOOLS2
-
-PRJ_EXPORTS
-
-../elf2inf.pl		/epoc32/tools/elf2inf.pl
-../def2dll.bat		/epoc32/tools/def2dll.bat
-../def2dll.pl		/epoc32/tools/def2dll.pl
-../deputil.pl		/epoc32/tools/deputil.pl
-../deputil.pm		/epoc32/tools/deputil.pm
-../inc/elfdefs.h	/epoc32/include/tools/elfdefs.h
-
-
-PRJ_MMPFILES
-#ifdef TOOLS
-genstubs
-getexports
-elftran
-#else
-elfdump
-#endif
-
-
-
+/*
+* Copyright (c) 1999-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Base tools (e.g. petran)
+*
+*/
+
+
+
+PRJ_PLATFORMS
+TOOLS2
+
+PRJ_EXPORTS
+#ifndef TOOLS2_LINUX
+../elf2inf.pl		/epoc32/tools/elf2inf.pl
+../def2dll.bat		/epoc32/tools/def2dll.bat
+../deputil.pl		/epoc32/tools/deputil.pl
+../deputil.pm		/epoc32/tools/deputil.pm
+#endif
+../def2dll.pl		/epoc32/tools/def2dll.pl
+../inc/elfdefs.h	SYMBIAN_OS_LAYER_PLATFORM_EXPORT_PATH(tools/elfdefs.h)
+
+
+PRJ_MMPFILES
+#ifndef TOOLS2_LINUX
+getexports
+#endif
+elftran
+genstubs
+elfdump
+
+
+
+
--- a/bintools/elftools/group/elftools.mrp	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/elftools/group/elftools.mrp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,8 +1,8 @@
 component       dev_build_bintools_elftools
 
-source          /src/tools/dev/build/bintools/elftools
-exports         /src/tools/dev/build/bintools/elftools/group
-binary          /src/tools/dev/build/bintools/elftools/group all
+source          /src/tools/build/bintools/elftools
+exports         /src/tools/build/bintools/elftools/group
+binary          /src/tools/build/bintools/elftools/group all
 
 notes_source    release.txt
 
--- a/bintools/elftools/group/elftran.mmp	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/elftools/group/elftran.mmp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,49 +1,49 @@
-/*
-* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-macro           __SUPPORT_ELF_FILES__
-
-target          elftran.exe
-targettype      exe
-
-sourcepath      ../elftran
-source          elf_file.cpp elf_dlld.cpp elf_imp.cpp elf_reloc.cpp elf_tran.cpp
-
-sourcepath      ../../../imgtools/imglib/e32uid
-source          e32uid.cpp
-
-sourcepath      ../../../imgtools/imglib/host
-source          h_file.cpp h_mem.cpp h_utl.cpp
-
-userinclude     ../inc
-userinclude     ../../../e32tools/e32lib/e32image/inc
-
-systeminclude   ../../../e32tools/e32lib/e32image/inc
-
-sourcepath      ../../../e32tools/e32lib/e32image
-source          e32image.cpp tr_main.cpp imgdump.cpp
-
-sourcepath      ../../../e32tools/e32lib/e32image/deflate
-source          decode.cpp encode.cpp deflate.cpp inflate.cpp panic.cpp compress.cpp
-
-sourcepath      ../../../imgtools/imglib/compress
-source          byte_pair.cpp pagedCompress.cpp
-
-systeminclude   ../inc /epoc32/include ../../../imgtools/imglib/compress /epoc32/include/tools/
-
-VENDORID        0x70000001
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+macro           __SUPPORT_ELF_FILES__
+
+target          elftran.exe
+targettype      exe
+
+sourcepath      ../elftran
+source          elf_file.cpp elf_dlld.cpp elf_imp.cpp elf_reloc.cpp elf_tran.cpp
+
+sourcepath      ../../../imgtools/imglib/e32uid
+source          e32uid.cpp
+
+sourcepath      ../../../imgtools/imglib/host
+source          h_file.cpp h_mem.cpp h_utl.cpp
+
+userinclude     ../inc
+userinclude     ../../../imgtools/imglib/e32image
+userinclude     ../../../imgtools/imglib/compress
+userinclude     ../../../imgtools/imglib/inc
+
+sourcepath      ../../../imgtools/imglib/e32image
+source          e32image.cpp tr_main.cpp imgdump.cpp
+
+sourcepath      ../../../imgtools/imglib/e32image/deflate
+source          decode.cpp encode.cpp deflate.cpp inflate.cpp panic.cpp compress.cpp
+
+sourcepath      ../../../imgtools/imglib/compress
+source          byte_pair.cpp pagedCompress.cpp
+
+OS_LAYER_SYSTEMINCLUDE_SYMBIAN
+
+VENDORID        0x70000001
--- a/bintools/elftools/group/release.txt	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/elftools/group/release.txt	Tue Jun 29 14:52:54 2010 +0800
@@ -1,5 +1,20 @@
-NOTESRC_RELEASER
-Nokia Corporation
-
-NOTESRC_RELEASE_REASON
-ELFtools Release
+NOTESRC_RELEASER
+Nokia Corporation
+
+NOTESRC_RELEASE_REASON
+ELFtools Release
+
+Version v1.1.0 - def2dll.pl
+===============
+Released by Zheng Shen, 12/06/2010
+    Minor: port def2dll.pl to Linux
+
+Version V02.02 (Build 002)
+===============
+Released by Zheng Shen, 10/03/2010
+    1) DPDEF144887  [System build] : NE1 smoketest not booting up for TB92SF_1069 vtb92sf build
+
+Version V02.02 (Build 001)
+===============
+Released by Zheng Shen, 05/03/2010
+    1) DPDEF144558  ELFTRAN'd give info in the illegal import of data message to allow debugging
--- a/bintools/elftools/inc/elfdll.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/elftools/inc/elfdll.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,254 +1,254 @@
-/*
-* Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#if !defined(__ELFDLL_H__)
-#define __ELFDLL_H__
-//#include <e32rom.h>
-#include "e32ldfmt.h"
-#include <elfdefs.h>
-#include "elffile.h"
-
-#define DLLSYMPREFIX "#<DLL>"
-#define DLLSYMPREFIX0 "#"
-#define DLLSYMSUFFIX "#<\\DLL>"
-#define ORDBASE 16
-#define EXPORTTABLENAME "DLL##ExportTable"
-#define EXPORTTABLESIZENAME "DLL##ExportTableSize"
-
-class NamedExportSymbol;
-class OrdZeroRecord;
-struct NeededDLLsList;
-
-const TUint		KNameLookupOffsetFlag32 = 0x0001;
-
-class ELFFile::ELFDllData
-        {
-public:
-	ELFFile * iElfFile;
-
-	char * iDynStrTab;
-	// bytesize of the dynamic string table
-	TInt iDynStrTabSize; 
-	Elf32_Sym * iDynSymTab;
-	// size of an entry in the dynamic symbol table
-	TInt iSymSize;
-	// the rela relocation table
-	Elf32_Rela * iRela;
-	// size of rela relocation table in bytes
-	TInt iRelaSz;
-	// size of a rela entry in bytes
-	TInt iRelaEnt;
-	// the rel relocation table
-	Elf32_Rel * iRel;
-	// size of rel relocation table in bytes
-	TInt iRelSz;
-	// size of a rel entry in bytes
-	TInt iRelEnt;
-
-	Elf32_HashTable * iHashTable;
-
-	// Exported symbols required for lookup via names.
-	NamedExportSymbol			*iNamedExportSymbolHead;
-	// Number of exported symbols - this doesn't nclude the absent symbols.
-	TInt					iNamedExportCount;
-	// header of the export symbol info table
-	E32EpocExpSymInfoHdr	iSymInfoHdr;
-	// String table size for the symbol names.
-	TUint					iSymStringTableSize;
-	TUint					iStringNameOffset;
-	
-	// Dependency list
-	// Static Dependencies - An 'import relocation' entry is required to be created 
-	// for each such record.
-	OrdZeroRecord		*iDepRecords;
-	OrdZeroRecord		*iDepRecordsTail;
-
-	// List of names obtained from DT_NEEDED entries in ELF.
-	// The order in which they appear is the order in which symbol
-	// lookup shall be followed.
-	NeededDLLsList		*iNeededDllNames;
-	NeededDLLsList		*iNeededDllNamesTail;
-	// Ordinal 0 of this binary. - A local relocation needs to be created for this
-	// record.
-
-	OrdZeroRecord		*iOrdZeroRec;		
-	TInt			iNamedLookupEnabled;
-	
-	ELFDllData(ELFFile * f);
-	~ELFDllData();
-    TBool Init();
-
-	TBool ParseDllSymbol(Elf32_Sym * s, char*& dll, TUint& len, TInt& ord);
-	class DllSymbol
-		{
-	public:
-		char * iDll;
-		TUint iLen;
-		TInt iOrd;
-		Elf32_Phdr * iSegment;
-		Elf32_Rel * iRel;
-		DllSymbol * iNext;
-
-		DllSymbol(char * n, TUint l, TInt o) 
-		        : iDll(n), iLen(l), iOrd(o), iSegment(0),iRel(0),iNext(0) 
-			{}
-		~DllSymbol()
-			{ 
-			delete iNext; 
-			}
-		};
-	DllSymbol * DllSymbolP(Elf32_Sym * s);
-	TBool AddSymbol(DllSymbol * s);
-
-	class DllRec
-		{
-	public:
-	    char * iName;
-	    TUint iLen;
-	    TInt nImports;
-	    DllSymbol * iHead;
-	    DllSymbol * iTail;
-	    DllRec * iNext;
-
-		DllRec(char * n, TInt l, DllSymbol * s) :
-			iName(n), iLen(l), nImports(1), iHead(s), iTail(s), iNext(0)
-		    {}
-	    ~DllRec() 
-		    { 
-		    delete iHead; 
-		    delete iNext; 
-		    }
-	    void AddSymbol(DllSymbol * s);
-	    };
-
-	DllRec * iDllHead;
-	DllRec * iDllTail;
-
-	Elf32_Word iExportTableSymIdx;
-	Elf32_Word iExportTableSizeSymIdx;
-
-	TBool InitExportInfo();
-	TBool iImageIsDll;
-	TBool ImageIsDll() { return iImageIsDll; }
-
-	Elf32_Word FindSymbolIndex(TText * s);
-
-	TInt iNumberOfImports;
-	TInt iNumberOfExports;
-	TInt iNumberOfImportDlls;
-
-	TInt iStringTableSize;
-
-	TInt iNumberOfRelocs;
-	TInt iNumberOfCodeRelocs;
-	TInt iNumberOfDataRelocs;
-
-	TInt NumberOfImports(void);
-	TInt NumberOfExports(void);
-	TInt NumberOfImportDlls(void);
-
-	TInt NumberOfRelocs(void);
-
-	TInt NumberOfCodeRelocs() { return iNumberOfCodeRelocs; }
-	TInt NumberOfDataRelocs() { return iNumberOfDataRelocs; }
-	
-	TBool GetRelocs(Elf32_Rel **aCodeRelocs, Elf32_Rel **aDataRelocs);
-
-	TUint GetExportTableOffset(void);
-	char * CreateImportSection(TInt &aSize);
-	TBool CreateSymLookupTable();
-	TBool SetupSymbolValues();
-	TBool SetupSymbolNames();
-	void Sort(NamedExportSymbol** aDstList, NamedExportSymbol* aSrcList);
-	void MergeSort(NamedExportSymbol** aDstList, NamedExportSymbol** aSrcList);
-	void MergeSort(NamedExportSymbol** aDstList, NamedExportSymbol** aSrcList, \
-									TUint aLeft, TUint aRight);
-	TBool AddToDependency(TUint aOff);
-	TBool CreateDependency();
-	OrdZeroRecord* FindDependency(char* aName, TUint aLen);
-	DllRec * SearchImports(char *aName);
-	TInt GetLookupTblSize(){ return iSymInfoHdr.iSize;}
-	void SetLookupTblBase(TInt);
-	void GetExportSymInfoHeader(E32EpocExpSymInfoHdr& aSymInfoHdr);
-	void SetExportSymInfo();
-	TUint GetSymLookupSection(char* aBuff);
-	};
-
-// This class is used to create symbols to support named lookups.
-// 
-	class NamedExportSymbol
-	{
-	public:
-		NamedExportSymbol(char* aName, Elf32_Addr aValue);
-		~NamedExportSymbol()
-		{
-			delete iNext;
-		}
-		
-		char* Name() { return iSymbolName;}
-		void Name(char* aName) {iSymbolName = aName;}
-		
-		TUint NameOffset() {return iSymbolNameOffset;}
-		void  NameOffset(TUint aOffset) {iSymbolNameOffset = aOffset;}
-		
-		Elf32_Addr Value() { return iValue;}
-		void Value(Elf32_Addr aValue) { iValue = aValue;}
-	
-		NamedExportSymbol* Next() { return iNext;}
-		void Next(NamedExportSymbol* aNext) { iNext = aNext;}
-
-		Elf32_Rel	iReloc;	// relocation entry for the symbol address
-		TUint		iSymRelocType;  // Whether it is a code or data relocation for this symbol
-	private:
-		char*		iSymbolName;	// Symbol name
-		TInt		iSymIdx;
-		TUint		iSymbolNameOffset;// offset of name in string table.
-		Elf32_Addr	iValue;			// symbol value - this is the address of the symbol
-		NamedExportSymbol *iNext;		// next symbol
-	};
-
-// This class is used to support symbol lookup of the static dependencies by linking in their 
-// 0th ordinal.
-	class OrdZeroRecord
-	{
-	public:
-		OrdZeroRecord(char* aName): 
-			iName(aName), iNext(0){}
-		~OrdZeroRecord()
-		{
-			delete iNext;
-		}
-		char				*iName; // (linkas) name of the dependency
-		Elf32_Rel			iReloc;	// a relocation entry for the 0th ordinal of each dependency
-		OrdZeroRecord		*iNext; // next dependency
-		TUint				iOffset;
-	};
-	struct NeededDLLsList
-	{
-		NeededDLLsList(TUint aOff) : iOffset(aOff), iNext(0)
-		{}
-		~NeededDLLsList()
-		{
-			delete iNext;
-		}
-		TUint iOffset;
-		NeededDLLsList *iNext;
-	};
-
-#endif
-
+/*
+* Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#if !defined(__ELFDLL_H__)
+#define __ELFDLL_H__
+//#include <e32rom.h>
+#include "e32ldfmt.h"
+#include "elfdefs.h"
+#include "elffile.h"
+
+#define DLLSYMPREFIX "#<DLL>"
+#define DLLSYMPREFIX0 "#"
+#define DLLSYMSUFFIX "#<\\DLL>"
+#define ORDBASE 16
+#define EXPORTTABLENAME "DLL##ExportTable"
+#define EXPORTTABLESIZENAME "DLL##ExportTableSize"
+
+class NamedExportSymbol;
+class OrdZeroRecord;
+struct NeededDLLsList;
+
+const TUint		KNameLookupOffsetFlag32 = 0x0001;
+
+class ELFFile::ELFDllData
+        {
+public:
+	ELFFile * iElfFile;
+
+	char * iDynStrTab;
+	// bytesize of the dynamic string table
+	TInt iDynStrTabSize; 
+	Elf32_Sym * iDynSymTab;
+	// size of an entry in the dynamic symbol table
+	TInt iSymSize;
+	// the rela relocation table
+	Elf32_Rela * iRela;
+	// size of rela relocation table in bytes
+	TInt iRelaSz;
+	// size of a rela entry in bytes
+	TInt iRelaEnt;
+	// the rel relocation table
+	Elf32_Rel * iRel;
+	// size of rel relocation table in bytes
+	TInt iRelSz;
+	// size of a rel entry in bytes
+	TInt iRelEnt;
+
+	Elf32_HashTable * iHashTable;
+
+	// Exported symbols required for lookup via names.
+	NamedExportSymbol			*iNamedExportSymbolHead;
+	// Number of exported symbols - this doesn't nclude the absent symbols.
+	TInt					iNamedExportCount;
+	// header of the export symbol info table
+	E32EpocExpSymInfoHdr	iSymInfoHdr;
+	// String table size for the symbol names.
+	TUint					iSymStringTableSize;
+	TUint					iStringNameOffset;
+	
+	// Dependency list
+	// Static Dependencies - An 'import relocation' entry is required to be created 
+	// for each such record.
+	OrdZeroRecord		*iDepRecords;
+	OrdZeroRecord		*iDepRecordsTail;
+
+	// List of names obtained from DT_NEEDED entries in ELF.
+	// The order in which they appear is the order in which symbol
+	// lookup shall be followed.
+	NeededDLLsList		*iNeededDllNames;
+	NeededDLLsList		*iNeededDllNamesTail;
+	// Ordinal 0 of this binary. - A local relocation needs to be created for this
+	// record.
+
+	OrdZeroRecord		*iOrdZeroRec;		
+	TInt			iNamedLookupEnabled;
+	
+	ELFDllData(ELFFile * f);
+	~ELFDllData();
+    TBool Init();
+
+	TBool ParseDllSymbol(Elf32_Sym * s, char*& dll, TUint& len, TInt& ord);
+	class DllSymbol
+		{
+	public:
+		char * iDll;
+		TUint iLen;
+		TInt iOrd;
+		Elf32_Phdr * iSegment;
+		Elf32_Rel * iRel;
+		DllSymbol * iNext;
+
+		DllSymbol(char * n, TUint l, TInt o) 
+		        : iDll(n), iLen(l), iOrd(o), iSegment(0),iRel(0),iNext(0) 
+			{}
+		~DllSymbol()
+			{ 
+			delete iNext; 
+			}
+		};
+	DllSymbol * DllSymbolP(Elf32_Sym * s);
+	TBool AddSymbol(DllSymbol * s);
+
+	class DllRec
+		{
+	public:
+	    char * iName;
+	    TUint iLen;
+	    TInt nImports;
+	    DllSymbol * iHead;
+	    DllSymbol * iTail;
+	    DllRec * iNext;
+
+		DllRec(char * n, TInt l, DllSymbol * s) :
+			iName(n), iLen(l), nImports(1), iHead(s), iTail(s), iNext(0)
+		    {}
+	    ~DllRec() 
+		    { 
+		    delete iHead; 
+		    delete iNext; 
+		    }
+	    void AddSymbol(DllSymbol * s);
+	    };
+
+	DllRec * iDllHead;
+	DllRec * iDllTail;
+
+	Elf32_Word iExportTableSymIdx;
+	Elf32_Word iExportTableSizeSymIdx;
+
+	TBool InitExportInfo();
+	TBool iImageIsDll;
+	TBool ImageIsDll() { return iImageIsDll; }
+
+	Elf32_Word FindSymbolIndex(const char* s);
+
+	TInt iNumberOfImports;
+	TInt iNumberOfExports;
+	TInt iNumberOfImportDlls;
+
+	TInt iStringTableSize;
+
+	TInt iNumberOfRelocs;
+	TInt iNumberOfCodeRelocs;
+	TInt iNumberOfDataRelocs;
+
+	TInt NumberOfImports(void);
+	TInt NumberOfExports(void);
+	TInt NumberOfImportDlls(void);
+
+	TInt NumberOfRelocs(void);
+
+	TInt NumberOfCodeRelocs() { return iNumberOfCodeRelocs; }
+	TInt NumberOfDataRelocs() { return iNumberOfDataRelocs; }
+	
+	TBool GetRelocs(Elf32_Rel **aCodeRelocs, Elf32_Rel **aDataRelocs);
+
+	TUint GetExportTableOffset(void);
+	char * CreateImportSection(TInt &aSize);
+	TBool CreateSymLookupTable();
+	TBool SetupSymbolValues();
+	TBool SetupSymbolNames();
+	void Sort(NamedExportSymbol** aDstList, NamedExportSymbol* aSrcList);
+	void MergeSort(NamedExportSymbol** aDstList, NamedExportSymbol** aSrcList);
+	void MergeSort(NamedExportSymbol** aDstList, NamedExportSymbol** aSrcList, \
+									TUint aLeft, TUint aRight);
+	TBool AddToDependency(TUint aOff);
+	TBool CreateDependency();
+	OrdZeroRecord* FindDependency(char* aName, TUint aLen);
+	DllRec * SearchImports(char *aName);
+	TInt GetLookupTblSize(){ return iSymInfoHdr.iSize;}
+	void SetLookupTblBase(TInt);
+	void GetExportSymInfoHeader(E32EpocExpSymInfoHdr& aSymInfoHdr);
+	void SetExportSymInfo();
+	TUint GetSymLookupSection(char* aBuff);
+	};
+
+// This class is used to create symbols to support named lookups.
+// 
+	class NamedExportSymbol
+	{
+	public:
+		NamedExportSymbol(char* aName, Elf32_Addr aValue);
+		~NamedExportSymbol()
+		{
+			delete iNext;
+		}
+		
+		char* Name() { return iSymbolName;}
+		void Name(char* aName) {iSymbolName = aName;}
+		
+		TUint NameOffset() {return iSymbolNameOffset;}
+		void  NameOffset(TUint aOffset) {iSymbolNameOffset = aOffset;}
+		
+		Elf32_Addr Value() { return iValue;}
+		void Value(Elf32_Addr aValue) { iValue = aValue;}
+	
+		NamedExportSymbol* Next() { return iNext;}
+		void Next(NamedExportSymbol* aNext) { iNext = aNext;}
+
+		Elf32_Rel	iReloc;	// relocation entry for the symbol address
+		TUint		iSymRelocType;  // Whether it is a code or data relocation for this symbol
+	private:
+		char*		iSymbolName;	// Symbol name
+		TInt		iSymIdx;
+		TUint		iSymbolNameOffset;// offset of name in string table.
+		Elf32_Addr	iValue;			// symbol value - this is the address of the symbol
+		NamedExportSymbol *iNext;		// next symbol
+	};
+
+// This class is used to support symbol lookup of the static dependencies by linking in their 
+// 0th ordinal.
+	class OrdZeroRecord
+	{
+	public:
+		OrdZeroRecord(char* aName): 
+			iName(aName), iNext(0){}
+		~OrdZeroRecord()
+		{
+			delete iNext;
+		}
+		char				*iName; // (linkas) name of the dependency
+		Elf32_Rel			iReloc;	// a relocation entry for the 0th ordinal of each dependency
+		OrdZeroRecord		*iNext; // next dependency
+		TUint				iOffset;
+	};
+	struct NeededDLLsList
+	{
+		NeededDLLsList(TUint aOff) : iOffset(aOff), iNext(0)
+		{}
+		~NeededDLLsList()
+		{
+			delete iNext;
+		}
+		TUint iOffset;
+		NeededDLLsList *iNext;
+	};
+
+#endif
+
--- a/bintools/elftools/inc/elffile.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/elftools/inc/elffile.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,160 +1,160 @@
-/*
-* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#if !defined(__ELFFILE_H__)
-#define __ELFFILE_H__
-#include <e32rom.h>
-#include "e32ldfmt.h"
-#include <elfdefs.h>
-
-#define ELFADDR(rtype, p, o) (rtype *)(((char *)p) + o)
-
-//
-enum TImportStat {EImpError, EImpSuccess, EImpDone};
-//
-class ELFFile
-	{
-public:
-	ELFFile();
-	~ELFFile();
-	TBool Init(const TText * const aFileName);
-	void Close(void);
-
-	char *CreateImportSection(TInt &aSize);
-
-	TBool GetRelocs(Elf32_Rel **aCodeRelocs, Elf32_Rel **aDataRelocs);
-	TUint16 GetRelocType(Elf32_Rel* aReloc);
-
-	TInt NumberOfImports() const;
-	TInt NumberOfImportDlls() const;
-	TInt NumberOfExports() const;
-	TInt NumberOfRelocs();
-
-	
-
-	TInt NumberOfCodeRelocs();
-	TInt NumberOfDataRelocs();
-	
-public:
-	TUint iCodeSize;
-	TUint iDataSize;
-	TUint iBssSize;
-
-
-	TUint GetCodeSize();
-	TBool HasInitialisedData();
-	TUint GetDataSize();
-	TBool HasBssData();
-	TUint GetBssSize();
-	
-
-	Elf32_Phdr * GetSegment(TInt idx) {return &iPhdr[idx];}
-	Elf32_Phdr * GetSegmentFromAddr(Elf32_Addr addr);
-
-	char * GetCode() { return ELFADDR(char, iElfFile, iCodeSegmentHdr->p_offset); }
-	char * GetData() { return ELFADDR(char, iElfFile, iDataSegmentHdr->p_offset); }
-	TBool CodeSegmentP(Elf32_Phdr * s) { return (TBool)(s == iCodeSegmentHdr); }
-	TBool CodeSegmentP(TInt idx) { return (TBool)(idx == iCodeSegmentIdx); }
-	TInt CodeSegmentIndex() {return iCodeSegmentIdx;}
-	TBool DataSegmentP(Elf32_Phdr * s) { return (TBool)(s == iDataSegmentHdr); }
-	TBool DataSegmentP(TInt idx) { return (TBool)(idx == iDataSegmentIdx); }
-	TInt DataSegmentIndex() {return iDataSegmentIdx;}
-
-	TUint * CodePtrFromAddr(Elf32_Addr addr) { return PtrInSegment(iCodeSegmentHdr, addr); }
-	TUint * DataPtrFromAddr(Elf32_Addr addr) { return PtrInSegment(iDataSegmentHdr, addr); }
-
-
-	char * ELFFileBase() { return (char *) iElfFile; }
-
-	TUint GetExportTableOffset(void);
-	TUint GetEntryPointOffset(void) { return iElfFile->e_entry - iCodeSegmentHdr->p_vaddr; }
-
-	TBool SymbolPresent(TText *s);
-	Elf32_Sym * FindSymbol(const TText *);
-
-	TBool GetExceptionIndexInfo(TUint32 &aOffset);
-	TBool SetUpLookupTable();
-	void SetLookupTblBase(TInt);
-	TInt GetLookupTblSize();
-	void GetExportSymInfoHeader(E32EpocExpSymInfoHdr& aSymInfoHdr);
-	TUint GetSymLookupSection(char* aBuff);
-private:
-	TBool InitHeaders(void);
-	TBool InitDllData(void);
-
-	TUint * PtrInSegment(Elf32_Phdr * phdr, Elf32_Addr addr) 
-	        { 
-		return ELFADDR(TUint, ELFADDR(TUint, iElfFile, phdr->p_offset), (addr - phdr->p_vaddr));
-		}
-
-
-	TBool IsValidFileHeader(Elf32_Ehdr * aElfHdr);
-	void CopySectionData(TAny *source, TAny *dest, TUint32 fileLength, TUint32 memLength);
-	TBool ProcessRelocData(TAny *relocData,TInt dataSize);
-	ELFFile(const ELFFile&);
-	const ELFFile & operator = (const ELFFile&);
-public:
-	TBool	iImageIsDll;
-	TBool	ImageIsDll() { return iImageIsDll; }
-	Elf32_Addr iLinkedBase;
-
-	TUint iEntryPoint;
-	TUint iHeapCommittedSize;
-	TUint iHeapReservedSize;
-	TUint iStackCommittedSize;
-	TUint iStackReservedSize;
-private:
-	friend class E32ImageFile;
-	friend class E32ImageFile_ELF;
-
-	TText * iFileName;
-	TInt32 iFileHandle;
-	Elf32_Ehdr * iElfFile;
-	Elf32_Phdr * iPhdr;
-	Elf32_Phdr * iDynamicSegmentHdr;
-	TInt iDynamicSegmentIdx;
-	Elf32_Phdr * iCodeSegmentHdr;
-	TInt iCodeSegmentIdx;
-	Elf32_Phdr * iDataSegmentHdr;
-	TInt iDataSegmentIdx;
-
-	Elf32_Shdr * iSectionHeaderTable;
-	TInt iSymIdx;
-	Elf32_Sym * iSymTab;
-
-	class ELFDllData;
-	ELFDllData * iDllData;
-
-	TCpu iCpu;
-
-
-	};
-#endif
-
-
-
-
-
-
-
-
-
-
-
-
-
+/*
+* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#if !defined(__ELFFILE_H__)
+#define __ELFFILE_H__
+#include <e32rom.h>
+#include "e32ldfmt.h"
+#include "elfdefs.h"
+
+#define ELFADDR(rtype, p, o) (rtype *)(((char *)p) + o)
+
+//
+enum TImportStat {EImpError, EImpSuccess, EImpDone};
+//
+class ELFFile
+	{
+public:
+	ELFFile();
+	~ELFFile();
+	TBool Init(const char* aFileName);
+	void Close(void);
+
+	char *CreateImportSection(TInt &aSize);
+
+	TBool GetRelocs(Elf32_Rel **aCodeRelocs, Elf32_Rel **aDataRelocs);
+	TUint16 GetRelocType(Elf32_Rel* aReloc);
+
+	TInt NumberOfImports() const;
+	TInt NumberOfImportDlls() const;
+	TInt NumberOfExports() const;
+	TInt NumberOfRelocs();
+
+	
+
+	TInt NumberOfCodeRelocs();
+	TInt NumberOfDataRelocs();
+	
+public:
+	TUint iCodeSize;
+	TUint iDataSize;
+	TUint iBssSize;
+
+
+	TUint GetCodeSize();
+	TBool HasInitialisedData();
+	TUint GetDataSize();
+	TBool HasBssData();
+	TUint GetBssSize();
+	
+
+	Elf32_Phdr * GetSegment(TInt idx) {return &iPhdr[idx];}
+	Elf32_Phdr * GetSegmentFromAddr(Elf32_Addr addr);
+
+	char * GetCode() { return ELFADDR(char, iElfFile, iCodeSegmentHdr->p_offset); }
+	char * GetData() { return ELFADDR(char, iElfFile, iDataSegmentHdr->p_offset); }
+	TBool CodeSegmentP(Elf32_Phdr * s) { return (TBool)(s == iCodeSegmentHdr); }
+	TBool CodeSegmentP(TInt idx) { return (TBool)(idx == iCodeSegmentIdx); }
+	TInt CodeSegmentIndex() {return iCodeSegmentIdx;}
+	TBool DataSegmentP(Elf32_Phdr * s) { return (TBool)(s == iDataSegmentHdr); }
+	TBool DataSegmentP(TInt idx) { return (TBool)(idx == iDataSegmentIdx); }
+	TInt DataSegmentIndex() {return iDataSegmentIdx;}
+
+	TUint * CodePtrFromAddr(Elf32_Addr addr) { return PtrInSegment(iCodeSegmentHdr, addr); }
+	TUint * DataPtrFromAddr(Elf32_Addr addr) { return PtrInSegment(iDataSegmentHdr, addr); }
+
+
+	char * ELFFileBase() { return (char *) iElfFile; }
+
+	TUint GetExportTableOffset(void);
+	TUint GetEntryPointOffset(void) { return iElfFile->e_entry - iCodeSegmentHdr->p_vaddr; }
+
+	TBool SymbolPresent(const char* s);
+	Elf32_Sym * FindSymbol(const char* s);
+
+	TBool GetExceptionIndexInfo(TUint32 &aOffset);
+	TBool SetUpLookupTable();
+	void SetLookupTblBase(TInt);
+	TInt GetLookupTblSize();
+	void GetExportSymInfoHeader(E32EpocExpSymInfoHdr& aSymInfoHdr);
+	TUint GetSymLookupSection(char* aBuff);
+private:
+	TBool InitHeaders(void);
+	TBool InitDllData(void);
+
+	TUint * PtrInSegment(Elf32_Phdr * phdr, Elf32_Addr addr) 
+	        { 
+		return ELFADDR(TUint, ELFADDR(TUint, iElfFile, phdr->p_offset), (addr - phdr->p_vaddr));
+		}
+
+
+	TBool IsValidFileHeader(Elf32_Ehdr * aElfHdr);
+	void CopySectionData(TAny *source, TAny *dest, TUint32 fileLength, TUint32 memLength);
+	TBool ProcessRelocData(TAny *relocData,TInt dataSize);
+	ELFFile(const ELFFile&);
+	const ELFFile & operator = (const ELFFile&);
+public:
+	TBool	iImageIsDll;
+	TBool	ImageIsDll() { return iImageIsDll; }
+	Elf32_Addr iLinkedBase;
+
+	TUint iEntryPoint;
+	TUint iHeapCommittedSize;
+	TUint iHeapReservedSize;
+	TUint iStackCommittedSize;
+	TUint iStackReservedSize;
+private:
+	friend class E32ImageFile;
+	friend class E32ImageFile_ELF;
+
+	char* iFileName;
+	TInt32 iFileHandle;
+	Elf32_Ehdr * iElfFile;
+	Elf32_Phdr * iPhdr;
+	Elf32_Phdr * iDynamicSegmentHdr;
+	TInt iDynamicSegmentIdx;
+	Elf32_Phdr * iCodeSegmentHdr;
+	TInt iCodeSegmentIdx;
+	Elf32_Phdr * iDataSegmentHdr;
+	TInt iDataSegmentIdx;
+
+	Elf32_Shdr * iSectionHeaderTable;
+	TInt iSymIdx;
+	Elf32_Sym * iSymTab;
+
+	class ELFDllData;
+	ELFDllData * iDllData;
+
+	TCpu iCpu;
+
+
+	};
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
+
--- a/bintools/elftools/inc/elftran.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/elftools/inc/elftran.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,65 +1,65 @@
-/*
-* Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Derived in part from E32IMAGE.H
-*
-*/
-
-
-#ifndef __ELFTRAN_H__
-#define __ELFTRAN_H__
-
-#include <e32std.h>
-#include <e32image.h>
-#include "e32ldfmt.h"
-#include <elfdefs.h>
-
-class ELFFile;
-
-//
-class E32ImageFile_ELF : public E32ImageFile
-	{
-public:
-	E32ImageFile_ELF();
-	virtual ~E32ImageFile_ELF();
-	virtual TBool Translate(const char* aFileName, TUint aDataBase, TBool aAllowDllData, \
-		TBool aSymLkupEnabled = FALSE);
-	TBool Translate(ELFFile& aElfFile);
-	TBool ImageIsDll(ELFFile& aElfFile);
-private:
-	TInt DoCodeHeader(ELFFile &aElfFile);
-	TInt DoDataHeader(ELFFile &aElfFile, TUint aDataBase);
-	TInt CopyCode(char *aPtr, ELFFile &aElfFile);
-	TInt CopyData(char *aPtr, ELFFile &aElfFile);
-
-	char *CreateImportSection(ELFFile &aElfFile, TInt &aSize);
-	void CreateExportSection(char *aPtr, ELFFile &aElfFile);
-
-	void FixRelocs(ELFFile &aElfFile, Elf32_Rel **codeRelocs, Elf32_Rel **dataRelocs);
-	char *CreateRelocs(ELFFile& aElfFile, Elf32_Rel **relocs, TInt nrelocs, TInt &aSize, TUint aBase);
-
-	TUint FixAddress(ELFFile &aElfFile, TUint va, Elf32_Rel * rel);
-
-	void SetUpExceptions(ELFFile &aElfFile);
-	void SetSymNameLookup(TInt aSymNameLkupEnabled);
-	TBool IsNamedLookupEnabled();
-	TBool SetUpLookupTable(ELFFile &aElfFile);
-	TInt DoSymbolLookupHeader(ELFFile &aElfFile, TInt aBaseOffset);
-	TUint CopyExportSymInfo(char *aPtr, ELFFile &aElfFile);
-	};
-
-#endif
-
-
-
+/*
+* Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Derived in part from E32IMAGE.H
+*
+*/
+
+
+#ifndef __ELFTRAN_H__
+#define __ELFTRAN_H__
+
+#include <e32std.h>
+#include "e32image.h"
+#include "e32ldfmt.h"
+#include "elfdefs.h"
+
+class ELFFile;
+
+//
+class E32ImageFile_ELF : public E32ImageFile
+	{
+public:
+	E32ImageFile_ELF();
+	virtual ~E32ImageFile_ELF();
+	virtual TBool Translate(const char* aFileName, TUint aDataBase, TBool aAllowDllData, \
+		TBool aSymLkupEnabled = FALSE);
+	TBool Translate(ELFFile& aElfFile);
+	TBool ImageIsDll(ELFFile& aElfFile);
+private:
+	TInt DoCodeHeader(ELFFile &aElfFile);
+	TInt DoDataHeader(ELFFile &aElfFile, TUint aDataBase);
+	TInt CopyCode(char *aPtr, ELFFile &aElfFile);
+	TInt CopyData(char *aPtr, ELFFile &aElfFile);
+
+	char *CreateImportSection(ELFFile &aElfFile, TInt &aSize);
+	void CreateExportSection(char *aPtr, ELFFile &aElfFile);
+
+	void FixRelocs(ELFFile &aElfFile, Elf32_Rel **codeRelocs, Elf32_Rel **dataRelocs);
+	char *CreateRelocs(ELFFile& aElfFile, Elf32_Rel **relocs, TInt nrelocs, TInt &aSize, TUint aBase);
+
+	TUint FixAddress(ELFFile &aElfFile, TUint va, Elf32_Rel * rel);
+
+	void SetUpExceptions(ELFFile &aElfFile);
+	void SetSymNameLookup(TInt aSymNameLkupEnabled);
+	TBool IsNamedLookupEnabled();
+	TBool SetUpLookupTable(ELFFile &aElfFile);
+	TInt DoSymbolLookupHeader(ELFFile &aElfFile, TInt aBaseOffset);
+	TUint CopyExportSymInfo(char *aPtr, ELFFile &aElfFile);
+	};
+
+#endif
+
+
+
--- a/bintools/evalid/dev_build_bintools_evalid.mrp	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/evalid/dev_build_bintools_evalid.mrp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,7 +1,7 @@
 component	dev_build_bintools_evalid
 
-source	\src\dev\build\bintools\evalid
-exports	\src\dev\build\bintools\evalid
+source	\src\tools\build\bintools\evalid
+exports	\src\tools\build\bintools\evalid
 
 notes_source	\component_defs\release.src
 
--- a/bintools/evalid/evalid.mrp	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/evalid/evalid.mrp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,7 +1,7 @@
 component	dev_build_bintools_evalid
 
-source	\src\tools\dev\build\bintools\evalid
-exports	\src\tools\dev\build\bintools\evalid
+source	\src\tools\build\bintools\evalid
+exports	\src\tools\build\bintools\evalid
 
 notes_source	\component_defs\release.src
 
--- a/bintools/rcomp/group/BLD.INF	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/rcomp/group/BLD.INF	Tue Jun 29 14:52:54 2010 +0800
@@ -1,42 +1,43 @@
-/*
-* Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Resource compiler
-*
-*/
-
-
-/**
- @file
-*/
-
-PRJ_PLATFORMS
-
-TOOLS2
-
-PRJ_EXPORTS
-// Add the Symbian localisation header files to the epoc32\include directory.
-// These files are needed by epocrc.pl to provide context information for
-// localisation of resource files.
-
-../inc/loc/symbiantags.rh
-../inc/loc/symbianbasictags.rh
-../inc/loc/symbiancontexts.rh
-
-
-
-PRJ_MMPFILES
-
-// Additional extension makefile to process the lex and yacc source files
-rcomp.mmp
+/*
+* Copyright (c) 2001-2010 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Resource compiler
+*
+*/
+
+
+/**
+ @file
+*/
+
+PRJ_PLATFORMS
+
+TOOLS2
+
+PRJ_EXPORTS
+// Add the Symbian localisation header files to the epoc32\include directory.
+// These files are needed by epocrc.pl to provide context information for
+// localisation of resource files.
+
+../inc/loc/symbiantags.rh
+../inc/loc/symbianbasictags.rh
+../inc/loc/symbiancontexts.rh
+
+
+
+PRJ_MMPFILES
+
+// Additional extension makefile to process the lex and yacc source files
+rcomp.mmp
+ 
--- a/bintools/rcomp/group/RELEASE.TXT	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/rcomp/group/RELEASE.TXT	Tue Jun 29 14:52:54 2010 +0800
@@ -1,628 +1,663 @@
-Version 8.1.005
-===============
-Released by KunalM, 06/03/2007
-
-	1) RCOMP ported to the TOOLS2 platform, under PREQ1182, MS3.6.2
-
-
-Version 8.00.002
-================
-Released by AndrewR, 3/3/2005
-
-	1) DEFECT FIX: DEF055559 - Problems building rcomp in VC6 IDE
-
-Version 8.00.001
-================
-Released by AndrewR, 7/2/2005
-
-	1) DEFECT FIX: DEF054981 - tools_rcomp component is updated every day
-
-Version 8.00.000
-================
-Released by AndrewR, 4/2/2005
-	1) Fixed DEF054617 - rcomp doesn't build from source
-	2) Fixed INC049059 - incorrect line number for error reported by rcomp when building \s60\gs
-
-Version 7.01.009
-============
-Released by KuldipN, 22/07/2004
-	Add UID2 and UID3 keywords to RCOMP 
-	(CR HBRT-5YJJ9C Specifying UID2 and UID3 in RSS files)
-
-Version 7.01.008
-============
-Released by DuskoJ, 10/07/2003
-	1) Fixed DEF022269  Resource value is read incorrectly
-	2) Fixed INC036025  RCOMP chinese resource complation problem 
-
-Version 7.01.007
-============
-Released by Jon Chatten, 03/06/2003
-	1) Fixed "DEF025433 RComp core dumps on certain resource files"
-	2) Adjusted version number in release.txt to match binary.
-
-	
-Version 7.06
-============
-Released by Dusko Jahora, 03/06/2003
-	1) Reverted fix for DEF022269
-
-
-Version 7.05
-============
-Released by Dusko Jahora, 02/06/2003
-1)	DuskoJ
-	1)	Changes to RCOMP whihch are part of CR PCHY-5L3RDW 
-		"Typhoon must support 16bpp colour".
-	2)	Fixed DEF022269  Resource value is read incorrectly
-		(this fix was not submitted on 09/05/2003 because of 
-		 an integration error)
-
-
-Version 7.04
-============
-
-Released by Dusko Jahora, 09/05/2003
-1)	DuskoJ
-	1)	Fixed DEF022269  Resource value is read incorrectly
-
-
-Version 7.03
-============
-
-Released by Dusko Jahora, April 2003
-	1)	Fixed defect DEF017151 "RCOMP should be upgraded to support files with UTF8 
-		signature".
-
-
-1)	William
-	1)	Fixed defect ROS-58VCX8 "RCOMP doesn't allow + in filenames" by removing
-		the unnecessary validation of the filenames left by the C++ preprocessor.
-	2)	Fixed defect RED-5ACK5F "Resource compiler creates nothing for empty and bad 
-		counted byte arrays"
-2)	Dusko
-	1)	Fixed defect ROS-5B7MHW "RCOMP fails to handle boundary values correctly
-		for WORD data type"
-	
-NB. The handling of LABEL suggests that it would be pretty easy to add rls_string support
-into the compiler directly.
-
-Version 7.01
-============
-
-Released by Jon Chatten, February 2002
-
-Fixed defect ROS-56PHFA - Replaced system() call to uidcrc.exe with a call to _spawnlp -
-this addresses the IDE-hanging issue when epocrc.pl is integrated as a plug-in with the CW
-IDE on Windows 98.
-
-Removed attempt to absolutely identify uidcrc.exe - this is no longer required as the CW RCOMP/EPOCRC.PL
-plug-in now sets the PATH before invoking the command line tools.
-
-
-1)	William
-	1)	Fixed defect ROS-55KJ4U "RCOMP fails if epoc32\tools not on the path"
-
-
-Version 7.00
-============
-
-Released by David Batchelor (November/December 2001)
-
-The format of resource files changes as follows:
-
-- The initial 2 two-byte values are removed as they are completely redundant. (All the information
-  they provide can be derived from the last 2 bytes of the file combined with the size of the
-  file.)
-- Resource files now have a standard 4-byte checked-UID field at the start. The first UID is
-  0x101f4a6b, to indicate that the resource file potentially contains Unicode compressed according
-  to the "Standard Compression Scheme for Unicode" (see
-  http://www.unicode.org/unicode/reports/tr6/tr6-3.2.html). The second and third UIDs may be
-  specified on the command-line by using an optional parameter of the form
-  "-{0x12345678,0x9abcdef0}" (without the quotation marks). If "*" is used as the last UID, e.g.
-  "-{0x600ddea1,*}", then the resource file's "offset" (i.e. the 20-bit number generated from the
-  resource file's "NAME") is used as the last UID.
-- The UID field is immediately followed by a bit-array, one bit for each resource in the resource
-  file, where each bit indicates whether the corresponding resource contains compressed Unicode.
-  The bit field is padded up to a multiple of 8-bits (if necessary) with zero bits.
-- Each resource which contains compressed Unicode consists of a series of "runs" preceded by a 1
-  or 2-byte run-length (1 byte if the run is <128 bytes, else 2 bytes). The run-length value does
-  not include itself in the byte count that it holds. The first run, the third run, the fifth run
-  etc contain compressed Unicode. The second run, the fourth run, the sixth run etc contain other
-  stuff. As the protocol defines that the first run is compressed Unicode, this run may obviously
-  be of zero length - no subsequent run in that resource may be of zero length.
-- Rcomp only uses compressed Unicode for text fields if it yields any benefit (i.e. only if it
-  actually makes the output file smaller).
-- The changes are completely transparent for code that reads resources.
-
-
-Version 6.03
-============
-
-Released by William Roberts, 30-Jul-2001
-
-Fix defect EXT-4YSCUV "Resource compiler corrupts long strings"
-Handle very long C++ comments, which previously caused a "token buffer overflow" message from the
-lexical analyser. Avoid overruning the buffer for literals by using a CHECK_APPEND() macro which
-discards characters rather than run off the end, giving errors like
-
-<empty>(5) : string too long - 1 ignored
-<empty>(5) : string too long - 2 ignored
-
-Avoid overflowing the Value array in string expressions by checking the new length before
-agreeing to concatenate the strings. Ultimately it would be best to replace Value[] with 
-a char* which has been created with strdup() and can therefore be realloc'd to grow the string.
-
-Fix defect ARG-4TZF7J "RCOMP needs warning waivers registered with SI"
-Removed all warnings in tools rel build - some tools deb warnings will appear in rcomp.cpp 
-because of problems in the mks\etc\yyparse.cpp file, but I didn't want to hide related problems 
-in any new Symbian code we might add. 
-
-Improve the -v output to show the primitive types being emitted, and to dump the IndexTable as hex
-offsets followed by the resource name, e.g.
-
-    IndexTable
-    IndexTableItem 4	<empty>
-    IndexTableItem c	r_eikserv_panic_dialog
-    IndexTableItem b8	r_eiksrv_oom_event_top
-    IndexTableItem e4	r_eiksrv_oom_event_bot
-    IndexTableItem 144	r_eikserv_replace_main_batteries
-    IndexTableItem 170	r_eikserv_replace_backup_battery
-
-and 
-
-    ResourceHeader          r_eiksrv_tasklist_dialog
-    ++ResourceItemArray
-    SimpleResourceItem [Long flags]  9
-    SimpleResourceItem [LText16 title]  
-    SimpleResourceItem [LLink pages]  
-    SimpleResourceItem [LLink buttons]  
-    StructArrayResourceItem (Level 0) [items]  
-    ArrayLength [Word] 1
-    ----------------------
-    --ResourceItemArrayArray
-    ++ResourceItemArray
-    SimpleResourceItem [Word type]  1001
-    SimpleResourceItem [LText16 prompt]  
-    SimpleResourceItem [Word id]  1
-    SimpleResourceItem [Long itemflags]  0
-    StructTypeResourceItem (Level 0) [control]  
-    ----------------------
-    ++ResourceItemArray
-    SimpleResourceItem [Byte version]  0
-    SimpleResourceItem [Word flags]  0
-    SimpleResourceItem [Word height]  8
-    SimpleResourceItem [Word width]  20
-    SimpleResourceItem [LLink array_id]  
-    ----------------------
-    SimpleResourceItem [LText16 trailer]  
-    ----------------------
-
-Together these changes should make it significantly easier to step through the binary image of a
-resource and work out which element has changed unexpectedly.
-
-
-Version 6.02
-============
-
-Released by William Roberts, 15-Feb-2001
-
-Fix awful defect in version 6.01, which caused negative integer constants to be written to the file as -1.
-
-When testing with LOCKIT, RCOMP developer should be aware that the version of RCOMP.EXE used by lockit 
-is kept in \lockit\tools, not \epoc32\tools.
-
-
-Version 6.01
-============
-
-Released by William Roberts, 14-Feb-2001
-
-Redefined character literals ('x') to be effectively strings so that they can contain UTF8 encodings
-for interesting characters. This is handled using the same lexical rules as string literals, so
-the limited escape processing is also supported. The introduction of strings surrounded by single-quotes
-means that the sequence \' is now accepted as standing for '.
-
-If the character literal string decodes to more than one Unicode character, a warning is given and the
-rest of the string is ignored. The prevailing source character encoding is used, but there is no support
-narrow character literals in the difficult part of the CP1252 range: the interpretation of the literal
-is always "the Unicode encoding for the first character of the string". For example, even in a 
-CP1252 source file building a narrow resource, a literal containing the Euro symbol will be interpreted 
-as 0x20ac, not 0x80.
-
-LTEXT strings are now checked to ensure that they are less than 256 characters in length.
-
-The NAME statement can now take a string literal or a label, instead of the previous behaviour where the
-lexical analyser handled the following word differently. Any RSS file which used a keyword as a name,
-for example WORD.RSS, will need to be changed to specify the name as a literal: the preferred syntax
-is to use string literals in all cases.
-
-
-Version 3.18
-============
-
-Released by William Roberts, 05-Aug-1999.
-
-Requires BAFL 092.
-
-Changed the handling of Unicode string resources (TEXT16 and LTEXT16) to ensure that the
-Unicode characters are aligned to a multiple of 2 bytes when the resource is used.
- 
-Resources are never used in place: instead RResourceFile::AllocReadLC creates an HBufC8 to hold a
-copy of the data. This means that rather than aligning from the start of the entire resource file,
-instead we have to align to the start of the individual resource, because the data in an HBufC8 
-always starts at an aligned address.
-
-Added RCBinaryStream::Align(int nBytes) and RCBinaryStream::SetAlignBase() to support the 
-generation of the necessary padding, and call them from suitable places in RCOSTRM.CPP.
-
-Also added code to add 1 to the offset of the end of the table of resource offsets: this is tested
-in BAFL as a marker to indicate the new format of resource file.
-
-Added a /verbose flag to core.cmd which invokes RCOMP with -v.
-
-Added #pragma warning( disable : 4710 ) in a couple of places to cut down on the number of
-unnecessary and useless "warnings".
-
-Regenerated the test resources.
-
-
-Version 3.17
-============
-
-Released by William Roberts, 25-Jun-1999.
-
-Fixed defect where embedded Unicode characters could cause BUF<x> strings to fail a length check.
-Updated test code include a check for this.
-
-Added more stuff for the Engineering Automated Build.
-
-
-Version 3.16
-============
-
-Released by Pute, 9-Jun-1999.  Based on work by William Roberts,
-26-May-1999 described in the "William's notes" section below.
-
-
-Character sets
---------------
-
-We are moving towards a specific principle of character sets for RCOMP.
-
-Previously, the character set used by RCOMP was not well defined, later we
-added the CHARACTER_SET identifier.  This implied that any specific values
-inserted into strings in <n> format would be in the character set of the
-source.
-
-In this design RCOMP will have trouble handling multibyte encodings like
-Shift-JIS because the tools it relies upon, LEX and YACC, are based on
-single-octet encodings only. Sometimes a multibyte encoding will produce
-artefacts that appear to be syntax elements such as double quote marks.
-
-In future the intention is that RCOMP uses UTF-8 encoding internally,
-provided by a pre-processing phase.  This release is an interim step.
-
-In this release, when explicit values are inserted in text strings, they
-are interpreted as Unicode values and converted to UTF-8.  To retain
-backward compatibility with CP1252 source, values 80-9F are also permitted
-and these will be mapped to Unicode as before when the source character set
-is defined to be CP1252.  The use of explicit values 80-9F is deprecated
-however.
-
-The default input character set is CP1252.  Previously, the default
-character set was "unknown".  This possibility is no-longer supported.
-This was also contrary to documentation.
-
-
-Details:
-
-Test command procedure updated and enhanced.
-
-Test comparison files TUTEXT8.RSC and TUTEXT16.RSC have been updated to
-allow for the introduction of the extra characters in the CP1252 character
-set.  (128 used to be "not used" and is now the euro sign)
-
-Note that compilation warning messages about deprecated characters will
-appear durng this test.
-
-A new test source file TWTEXT.RSS and associated reference binaries have
-been added to the test suite to demonstrate explicit use of values >255.
-
-
-
-
-William's notes (edited by Pute):
----------------
-
-Defined a new "character set" called UTF8, which supports the UTF8
-encoding of Unicode strings. 
-This actually allows the whole resource source file to be entered as
-UTF8 if required.  However the default charset remains CP1252.
-
-Arranged to support embedded Unicode characters constructed using the
-<xxx> notation, to support the use of 0x07ED as the end-of-paragraph
-marker (see ETEXT 120). This exploits the UTF8 support by inserting the
-appropriate UTF8 sequence into the 8-bit data.
-
-The embedded Unicode characters are also supported in the CP1252
-character set, with internal use of 0x81 as an "escape" character
-indicating that the following bytes are a UTF8 encoded character. This
-allows existing CP1252 resource source files to be used with the new
-ETEXT.
-
-Added the Euro and the Z caron encodings to the cp1252_exceptions table.
-
-
-Only RCOMP.EXE has been rebuilt.  Judging from the timestamps, the other
-executables haven't been rebuilt for the last few releases.
-
-To build rcomp, first run ..\src\BLDEX, then MNT BLDREL
-
-Building is only possible from NT and makes use of lex and yacc from
-T:\mks - this should be updated to use the GNUPro tools which we use to
-build GCC, as the Cygnus toolchain is something we expect to have always
-available.
-
-
-
-Version 3.15
-============
-
-Released by SimonC, 01-Feb-1999
-
-Fixed defects
-	EDN484092 "RCOMP needs to be Symbianised"
-	EDN584421 "Need to rebuild RCOMP with boilerplated headers"
-
-Only RCOMP.EXE has been rebuilt.  Judging from the timestamps, the other executables
-haven't been rebuilt for the last few releases.
-
-To build rcomp, first run ..\src\BLDEX, then MNT BLDREL
-
-Building is only possible from the NT and makes use of executables on T: so this can't
-be rebuilt by licensees (which doesn't seem to have been a problem so far...)
-
-
-
-Version 3.14
-============
-
-Released by PNJ, 19-Mar-1997
-
-The CORE command and the test procedures rely on NT command extensions.
-
-
-Version 314 mods
-
-  1. In FILELINE.CPP, FileLineManager::ExtractFileName updated to add
-     filename information planted by the preprocessor. This is a rewrite of
-     the code that was removed in the previous release because it was
-     violating.
-  2. Test code now in a formalised framework accessed via MNT TEST. The
-     formalism isn't perfect because of the limitations imposed by the
-     legacy command language. See TEST.HTM in the TSRC directory for more
-     information. The test procedure relies on NT command extensions.
-  3. The CORE command procedure has been changed to allow preprocessor
-     symbols to be defined. See below.
-
-CORE syntax
-
-CORE filename [ object_directory [options] ]
-
-If options are being used the object directory parameter must be present,
-the default value is "." for the current directory.
-
-Options are:
-
-/UNICODE
-     Specifies that strings are emitted as Unicode in the resource binary.
-     Previously, this option was selected with "-u", which is the parameter
-     currently used by RCOMP itself.
-/DEFINE symbol [ symbol...]
-     Specifies one or more symbols to be defined for the preprocessor pass.
-     This must be the last option supplied because it is followed by an
-     arbitrary number of tokens and the command language is so primitive.
-
-
-
-
-
-
-
-
-Version 3.13
-============
-
-Released by PNJ, 13-Jan-1997
-
-Version number scheme is independent of product-specific E32 chain
-numbering.
-
-This is an interim release, to provide 16-bit character set functionality.
-Later releases are planned to provide other requested features.  Existing
-RSS files produce identical binaries to previous releases when compiled
-in the default non-Unicode mode.
-
-There are some serious defects in the source code which will take
-a long time to address properly, eg misuse of assert as a status check.
-
-1.  Minor changes to MNT and build settings.
-2.  Minor code changes to remove warnings.
-3.  Renamed STRING.CPP, .H to remove ambiguity with
-    standard header of the same name.
-4.  rcscan::yyerror function updated so that it actually
-    interprets formatted strings instead of ignoring the extra
-    parameters.
-5.  Fixed defect in String operator != which was doing the inverse
-    of what it is supposed to do!
-6.  Provide a qualifier for Unicode output.
-7.  Fix erroneous error message if source file not specified.
-8.  Fixed problem which caused run time fatal errors during
-    source context switching.
-9.  Introduce new tokens to differentiate between 8 and 16-bit
-    text strings.
-10. Introduce a CHARACTER_SET token to specify the source
-    character set.
-11. Introduce an extra test component directory.
-12. Introduce a command procedure wrapper for RCOMP (called CoRe)
-
-
-Language features
------------------
-
-CHARACTER_SET name
-
-Specifies the character set of the input file.  The implementation currently
-does not do much with this, but will do in the nexty release or 2.  Legal
-values for name are currently:
-
-ASCII, CP1252, CP850, ISOLatin1, ShiftJIS, Unicode
-
-Note that Unicode source text is not likely to be supported any time soon,
-largely because RCOMP relies on LEX and YACC which are not Unicode-aware.
-
-The default setting in this implementation is CP1252.
-
-
-TEXT, LTEXT and BUF
-
-Now have explicit 8 and 16-bit variants, eg TEXT8, BUF16.  The unadorned
-variants are internally converted to the 8 or 16-bit equivalents depending
-on the presence of the -u (for unicode) command line qualifier.
-
-The prefixed counter for an LTEXT16 is still an 8-bit field.
-
-The zero terminator for a TEXT16 is a 16-bit field.
-
-For text fields, it is recommended that you continue to use the unadorned
-keywords. For binary data, you should use the explicit 8-bit keywords. This
-is likely to apply most commonly to the BUF (BUF8) keyword.
-
-
-
-
-
-Version 0.03.12
-===============
-
-1) Reduced verbosity.
-2) Released a version compatible with NT4.
-
-Version 0.03.11
-===============
-
-1) PVCS'ed RCOMP and generally tidied it up.
-2) Fixed empty BUF crash.
-3) Fixed extra trailing comma crash.
-4) Cleaned up the build warnings.
-5) Added ...BUF<n>... where n is an integer giving max length of BUF.
-6) The .exe is now called rcomp.exe.
-
-Version 3.06, MartinW, 05 Jul 96
-================================
-1. Added enum handling.
-        e.g.
-        ENUM ExampleEnum { Elem1, Elem2}
-        STRUCT a { BYTE b;}
-        RESOURCE a c { b = ExampleEnum::Elem2;}
-This should set up b with the value 1.
-
-Version 3.05, MartinW, 30 May 96
-================================
-1.Deal with long (>42characters) resource names in output to header
-  file.
-2.Prevent assertion failure in case of missing comma after first item
-  in an array of struct's.
-
-Version 3.04, MartinW, 29 Apr 96
-================================
-Avoid using cin by reading from a specified file (-s<filename>). The 
-cin approach suffered from something to do with the source file being 
-left open even when the program ended. This was the case at least with 
-a test program built using C++ 1.51 and run under NT 3.51.
-e.g.    void main() { char a; cin << a; }
-        TestProgram < a.src
-        del a.src             <---- "file in use by another process".
-
-Version 3.03, MartinW, 18 Apr 96
-================================
-1.Handle syntax error with numbers more effectively so assert does not
-  fail.
-2.Accept 0 for double without warning.
-
-Version 3.02, MartinW, 11 Apr 96
-================================
-Corrected defect to do with line number in error message for text being
-converted to a number.
-
-Version 3.01, MartinW, 9 Apr 96
-===============================
-1.I added more error handling so that more proper error messages are
-  given.
-2.I altered the error message format so that it is suitable for VC++.
-  Brief seems to cope with this new format quite happily. VC++ didn't 
-  seem to like e.g. ".\t1.rss" at the start but "C:\rcomp\src\t1.rss" 
-  worked.
-3.The drive and directory for the file name specified with -i is used
-  to provide the full paths for all filenames given in error messages. 
-  If the -i file name is not a full path then the current directory and 
-  drive are used in combination with the partial path to create a full 
-  path.
-
-Version 3.00, MartinW, 19 Mar 96
-================================
-To use this resource compiler execute "mnt getrel". The egrs.bat file
-is an example of how the resource compiler may be run. The GNU
-preprocessor is used (t:\tools\gnucpp.exe) first and the output
-passed to rc3.exe. The fc4bat.exe file is used to avoid writing the
-header output file if it has in fact not changed.
-
-Details about this version
---------------------------
-This is a completely new version based on yacc and lex along with C++.
-
-Overview of system:
-        Source file (e.g.pic.rss) 
-                -> Preprocessing
-                -> Lexer
-                -> Parser
-                -> Data structures (using C++ classes)
-                -> Data file output (e.g. pic.rsg)
-                -> Header file output (e.g. pic.h)
-
-        The GNU C++ preprocessor was used. The output from this
-        includes directives giving line numbering following inclusion
-        of header files. The lexer uses this to store data which the 
-        parser then uses to output error messages in Brief format.
-    
-        The lexer and parser are generated by lex and yacc
-        respectively from rcomp.l and rcomp.y. These define the
-        tokens and the grammar for the resource script language.
-
-        Supporting C++ classes are compiled and linked along with the
-        output from lex and yacc.
-
-        The batch file rs.bat takes the file specified by the first
-        parameter and passes it to the GNU preprocessor. The output
-        is piped through to rcomp.exe. The names of the data output 
-        file and the header file are specified based on the name
-        given to rs.bat. The -i flag is used to give the original
-        name (as passed to the preprocessor) for error reporting.
-     
-        A program called fc4bat.exe is used to give an errorlevel if
-        the specified files do not match. This is used to avoid
-        changing the date on the header file if it has not changed.
-
-Issues for porting to other platforms:
-         1) atof has been used. The output of this is written to the
-            rsc file. The format must be that expected by the program
-            reading the rsc file rather than the format of the
-            machine used to generate the file.
-         2) The MKS versions of yacc and lex were used. These are PC
-            versions of the UNIX tools. The non-standard features
-            were avoided however only the PC versions have been used.
-         3) Stream handling has been used. Apparently there may be
-            differences in implementations of this extension to C++.
-
-
+version 8.4.001
+===============
+Released by Lorence Wang, 26/04/2010
+	1) DPDEF145375 RCOMP can not parse data passed to its STDIN correctly 
+
+version 8.3.001
+===============
+Released by Zheng Shen, 16/03/2010
+	1) DPDEF145001  RCOMP failed if uidcrc is not located in the same directory as it is
+
+version 8.3.000
+===============
+Released by Zheng Shen, 22/02/2010
+	1) DPDEF144562	Build Tools cannot be built in Linux
+
+version 8.2.008
+===============
+Released by Marvin Shi, 25/01/2010
+	1) DPDEF143586 Add -o2 optimization to rcomp 
+
+version 8.2.007
+===============
+Released by Marvin Shi, 15/01/2010
+	1) DPDEF143836 rcomp produces error messages which should be warning messages 
+
+Version 8.2.006
+===============
+Released by Zheng Shen, 10/12/2009
+	1) DPDEF143045 rcomp produces a warning 'Cannot convert "1.0" 
+
+Version 8.2.005
+===============
+Released by Jason Cui, 31/7/2009 (did not clear build number, should be done by next feature deliery)
+  1) SITK v1.4, GT0499, MS3.5.3, DS.1772 PREQ2471: RIT: Resource compiler (RComp) must support characters outside of the BMP 
+
+Version 8.1.005
+===============
+Released by KunalM, 06/03/2007
+
+	1) RCOMP ported to the TOOLS2 platform, under PREQ1182, MS3.6.2
+
+
+Version 8.00.002
+================
+Released by AndrewR, 3/3/2005
+
+	1) DEFECT FIX: DEF055559 - Problems building rcomp in VC6 IDE
+
+Version 8.00.001
+================
+Released by AndrewR, 7/2/2005
+
+	1) DEFECT FIX: DEF054981 - tools_rcomp component is updated every day
+
+Version 8.00.000
+================
+Released by AndrewR, 4/2/2005
+	1) Fixed DEF054617 - rcomp doesn't build from source
+	2) Fixed INC049059 - incorrect line number for error reported by rcomp when building \s60\gs
+
+Version 7.01.009
+============
+Released by KuldipN, 22/07/2004
+	Add UID2 and UID3 keywords to RCOMP 
+	(CR HBRT-5YJJ9C Specifying UID2 and UID3 in RSS files)
+
+Version 7.01.008
+============
+Released by DuskoJ, 10/07/2003
+	1) Fixed DEF022269  Resource value is read incorrectly
+	2) Fixed INC036025  RCOMP chinese resource complation problem 
+
+Version 7.01.007
+============
+Released by Jon Chatten, 03/06/2003
+	1) Fixed "DEF025433 RComp core dumps on certain resource files"
+	2) Adjusted version number in release.txt to match binary.
+
+	
+Version 7.06
+============
+Released by Dusko Jahora, 03/06/2003
+	1) Reverted fix for DEF022269
+
+
+Version 7.05
+============
+Released by Dusko Jahora, 02/06/2003
+1)	DuskoJ
+	1)	Changes to RCOMP whihch are part of CR PCHY-5L3RDW 
+		"Typhoon must support 16bpp colour".
+	2)	Fixed DEF022269  Resource value is read incorrectly
+		(this fix was not submitted on 09/05/2003 because of 
+		 an integration error)
+
+
+Version 7.04
+============
+
+Released by Dusko Jahora, 09/05/2003
+1)	DuskoJ
+	1)	Fixed DEF022269  Resource value is read incorrectly
+
+
+Version 7.03
+============
+
+Released by Dusko Jahora, April 2003
+	1)	Fixed defect DEF017151 "RCOMP should be upgraded to support files with UTF8 
+		signature".
+
+
+1)	William
+	1)	Fixed defect ROS-58VCX8 "RCOMP doesn't allow + in filenames" by removing
+		the unnecessary validation of the filenames left by the C++ preprocessor.
+	2)	Fixed defect RED-5ACK5F "Resource compiler creates nothing for empty and bad 
+		counted byte arrays"
+2)	Dusko
+	1)	Fixed defect ROS-5B7MHW "RCOMP fails to handle boundary values correctly
+		for WORD data type"
+	
+NB. The handling of LABEL suggests that it would be pretty easy to add rls_string support
+into the compiler directly.
+
+Version 7.01
+============
+
+Released by Jon Chatten, February 2002
+
+Fixed defect ROS-56PHFA - Replaced system() call to uidcrc.exe with a call to _spawnlp -
+this addresses the IDE-hanging issue when epocrc.pl is integrated as a plug-in with the CW
+IDE on Windows 98.
+
+Removed attempt to absolutely identify uidcrc.exe - this is no longer required as the CW RCOMP/EPOCRC.PL
+plug-in now sets the PATH before invoking the command line tools.
+
+
+1)	William
+	1)	Fixed defect ROS-55KJ4U "RCOMP fails if epoc32\tools not on the path"
+
+
+Version 7.00
+============
+
+Released by David Batchelor (November/December 2001)
+
+The format of resource files changes as follows:
+
+- The initial 2 two-byte values are removed as they are completely redundant. (All the information
+  they provide can be derived from the last 2 bytes of the file combined with the size of the
+  file.)
+- Resource files now have a standard 4-byte checked-UID field at the start. The first UID is
+  0x101f4a6b, to indicate that the resource file potentially contains Unicode compressed according
+  to the "Standard Compression Scheme for Unicode" (see
+  http://www.unicode.org/unicode/reports/tr6/tr6-3.2.html). The second and third UIDs may be
+  specified on the command-line by using an optional parameter of the form
+  "-{0x12345678,0x9abcdef0}" (without the quotation marks). If "*" is used as the last UID, e.g.
+  "-{0x600ddea1,*}", then the resource file's "offset" (i.e. the 20-bit number generated from the
+  resource file's "NAME") is used as the last UID.
+- The UID field is immediately followed by a bit-array, one bit for each resource in the resource
+  file, where each bit indicates whether the corresponding resource contains compressed Unicode.
+  The bit field is padded up to a multiple of 8-bits (if necessary) with zero bits.
+- Each resource which contains compressed Unicode consists of a series of "runs" preceded by a 1
+  or 2-byte run-length (1 byte if the run is <128 bytes, else 2 bytes). The run-length value does
+  not include itself in the byte count that it holds. The first run, the third run, the fifth run
+  etc contain compressed Unicode. The second run, the fourth run, the sixth run etc contain other
+  stuff. As the protocol defines that the first run is compressed Unicode, this run may obviously
+  be of zero length - no subsequent run in that resource may be of zero length.
+- Rcomp only uses compressed Unicode for text fields if it yields any benefit (i.e. only if it
+  actually makes the output file smaller).
+- The changes are completely transparent for code that reads resources.
+
+
+Version 6.03
+============
+
+Released by William Roberts, 30-Jul-2001
+
+Fix defect EXT-4YSCUV "Resource compiler corrupts long strings"
+Handle very long C++ comments, which previously caused a "token buffer overflow" message from the
+lexical analyser. Avoid overruning the buffer for literals by using a CHECK_APPEND() macro which
+discards characters rather than run off the end, giving errors like
+
+<empty>(5) : string too long - 1 ignored
+<empty>(5) : string too long - 2 ignored
+
+Avoid overflowing the Value array in string expressions by checking the new length before
+agreeing to concatenate the strings. Ultimately it would be best to replace Value[] with 
+a char* which has been created with strdup() and can therefore be realloc'd to grow the string.
+
+Fix defect ARG-4TZF7J "RCOMP needs warning waivers registered with SI"
+Removed all warnings in tools rel build - some tools deb warnings will appear in rcomp.cpp 
+because of problems in the mks\etc\yyparse.cpp file, but I didn't want to hide related problems 
+in any new Symbian code we might add. 
+
+Improve the -v output to show the primitive types being emitted, and to dump the IndexTable as hex
+offsets followed by the resource name, e.g.
+
+    IndexTable
+    IndexTableItem 4	<empty>
+    IndexTableItem c	r_eikserv_panic_dialog
+    IndexTableItem b8	r_eiksrv_oom_event_top
+    IndexTableItem e4	r_eiksrv_oom_event_bot
+    IndexTableItem 144	r_eikserv_replace_main_batteries
+    IndexTableItem 170	r_eikserv_replace_backup_battery
+
+and 
+
+    ResourceHeader          r_eiksrv_tasklist_dialog
+    ++ResourceItemArray
+    SimpleResourceItem [Long flags]  9
+    SimpleResourceItem [LText16 title]  
+    SimpleResourceItem [LLink pages]  
+    SimpleResourceItem [LLink buttons]  
+    StructArrayResourceItem (Level 0) [items]  
+    ArrayLength [Word] 1
+    ----------------------
+    --ResourceItemArrayArray
+    ++ResourceItemArray
+    SimpleResourceItem [Word type]  1001
+    SimpleResourceItem [LText16 prompt]  
+    SimpleResourceItem [Word id]  1
+    SimpleResourceItem [Long itemflags]  0
+    StructTypeResourceItem (Level 0) [control]  
+    ----------------------
+    ++ResourceItemArray
+    SimpleResourceItem [Byte version]  0
+    SimpleResourceItem [Word flags]  0
+    SimpleResourceItem [Word height]  8
+    SimpleResourceItem [Word width]  20
+    SimpleResourceItem [LLink array_id]  
+    ----------------------
+    SimpleResourceItem [LText16 trailer]  
+    ----------------------
+
+Together these changes should make it significantly easier to step through the binary image of a
+resource and work out which element has changed unexpectedly.
+
+
+Version 6.02
+============
+
+Released by William Roberts, 15-Feb-2001
+
+Fix awful defect in version 6.01, which caused negative integer constants to be written to the file as -1.
+
+When testing with LOCKIT, RCOMP developer should be aware that the version of RCOMP.EXE used by lockit 
+is kept in \lockit\tools, not \epoc32\tools.
+
+
+Version 6.01
+============
+
+Released by William Roberts, 14-Feb-2001
+
+Redefined character literals ('x') to be effectively strings so that they can contain UTF8 encodings
+for interesting characters. This is handled using the same lexical rules as string literals, so
+the limited escape processing is also supported. The introduction of strings surrounded by single-quotes
+means that the sequence \' is now accepted as standing for '.
+
+If the character literal string decodes to more than one Unicode character, a warning is given and the
+rest of the string is ignored. The prevailing source character encoding is used, but there is no support
+narrow character literals in the difficult part of the CP1252 range: the interpretation of the literal
+is always "the Unicode encoding for the first character of the string". For example, even in a 
+CP1252 source file building a narrow resource, a literal containing the Euro symbol will be interpreted 
+as 0x20ac, not 0x80.
+
+LTEXT strings are now checked to ensure that they are less than 256 characters in length.
+
+The NAME statement can now take a string literal or a label, instead of the previous behaviour where the
+lexical analyser handled the following word differently. Any RSS file which used a keyword as a name,
+for example WORD.RSS, will need to be changed to specify the name as a literal: the preferred syntax
+is to use string literals in all cases.
+
+
+Version 3.18
+============
+
+Released by William Roberts, 05-Aug-1999.
+
+Requires BAFL 092.
+
+Changed the handling of Unicode string resources (TEXT16 and LTEXT16) to ensure that the
+Unicode characters are aligned to a multiple of 2 bytes when the resource is used.
+ 
+Resources are never used in place: instead RResourceFile::AllocReadLC creates an HBufC8 to hold a
+copy of the data. This means that rather than aligning from the start of the entire resource file,
+instead we have to align to the start of the individual resource, because the data in an HBufC8 
+always starts at an aligned address.
+
+Added RCBinaryStream::Align(int nBytes) and RCBinaryStream::SetAlignBase() to support the 
+generation of the necessary padding, and call them from suitable places in RCOSTRM.CPP.
+
+Also added code to add 1 to the offset of the end of the table of resource offsets: this is tested
+in BAFL as a marker to indicate the new format of resource file.
+
+Added a /verbose flag to core.cmd which invokes RCOMP with -v.
+
+Added #pragma warning( disable : 4710 ) in a couple of places to cut down on the number of
+unnecessary and useless "warnings".
+
+Regenerated the test resources.
+
+
+Version 3.17
+============
+
+Released by William Roberts, 25-Jun-1999.
+
+Fixed defect where embedded Unicode characters could cause BUF<x> strings to fail a length check.
+Updated test code include a check for this.
+
+Added more stuff for the Engineering Automated Build.
+
+
+Version 3.16
+============
+
+Released by Pute, 9-Jun-1999.  Based on work by William Roberts,
+26-May-1999 described in the "William's notes" section below.
+
+
+Character sets
+--------------
+
+We are moving towards a specific principle of character sets for RCOMP.
+
+Previously, the character set used by RCOMP was not well defined, later we
+added the CHARACTER_SET identifier.  This implied that any specific values
+inserted into strings in <n> format would be in the character set of the
+source.
+
+In this design RCOMP will have trouble handling multibyte encodings like
+Shift-JIS because the tools it relies upon, LEX and YACC, are based on
+single-octet encodings only. Sometimes a multibyte encoding will produce
+artefacts that appear to be syntax elements such as double quote marks.
+
+In future the intention is that RCOMP uses UTF-8 encoding internally,
+provided by a pre-processing phase.  This release is an interim step.
+
+In this release, when explicit values are inserted in text strings, they
+are interpreted as Unicode values and converted to UTF-8.  To retain
+backward compatibility with CP1252 source, values 80-9F are also permitted
+and these will be mapped to Unicode as before when the source character set
+is defined to be CP1252.  The use of explicit values 80-9F is deprecated
+however.
+
+The default input character set is CP1252.  Previously, the default
+character set was "unknown".  This possibility is no-longer supported.
+This was also contrary to documentation.
+
+
+Details:
+
+Test command procedure updated and enhanced.
+
+Test comparison files TUTEXT8.RSC and TUTEXT16.RSC have been updated to
+allow for the introduction of the extra characters in the CP1252 character
+set.  (128 used to be "not used" and is now the euro sign)
+
+Note that compilation warning messages about deprecated characters will
+appear durng this test.
+
+A new test source file TWTEXT.RSS and associated reference binaries have
+been added to the test suite to demonstrate explicit use of values >255.
+
+
+
+
+William's notes (edited by Pute):
+---------------
+
+Defined a new "character set" called UTF8, which supports the UTF8
+encoding of Unicode strings. 
+This actually allows the whole resource source file to be entered as
+UTF8 if required.  However the default charset remains CP1252.
+
+Arranged to support embedded Unicode characters constructed using the
+<xxx> notation, to support the use of 0x07ED as the end-of-paragraph
+marker (see ETEXT 120). This exploits the UTF8 support by inserting the
+appropriate UTF8 sequence into the 8-bit data.
+
+The embedded Unicode characters are also supported in the CP1252
+character set, with internal use of 0x81 as an "escape" character
+indicating that the following bytes are a UTF8 encoded character. This
+allows existing CP1252 resource source files to be used with the new
+ETEXT.
+
+Added the Euro and the Z caron encodings to the cp1252_exceptions table.
+
+
+Only RCOMP.EXE has been rebuilt.  Judging from the timestamps, the other
+executables haven't been rebuilt for the last few releases.
+
+To build rcomp, first run ..\src\BLDEX, then MNT BLDREL
+
+Building is only possible from NT and makes use of lex and yacc from
+T:\mks - this should be updated to use the GNUPro tools which we use to
+build GCC, as the Cygnus toolchain is something we expect to have always
+available.
+
+
+
+Version 3.15
+============
+
+Released by SimonC, 01-Feb-1999
+
+Fixed defects
+	EDN484092 "RCOMP needs to be Symbianised"
+	EDN584421 "Need to rebuild RCOMP with boilerplated headers"
+
+Only RCOMP.EXE has been rebuilt.  Judging from the timestamps, the other executables
+haven't been rebuilt for the last few releases.
+
+To build rcomp, first run ..\src\BLDEX, then MNT BLDREL
+
+Building is only possible from the NT and makes use of executables on T: so this can't
+be rebuilt by licensees (which doesn't seem to have been a problem so far...)
+
+
+
+Version 3.14
+============
+
+Released by PNJ, 19-Mar-1997
+
+The CORE command and the test procedures rely on NT command extensions.
+
+
+Version 314 mods
+
+  1. In FILELINE.CPP, FileLineManager::ExtractFileName updated to add
+     filename information planted by the preprocessor. This is a rewrite of
+     the code that was removed in the previous release because it was
+     violating.
+  2. Test code now in a formalised framework accessed via MNT TEST. The
+     formalism isn't perfect because of the limitations imposed by the
+     legacy command language. See TEST.HTM in the TSRC directory for more
+     information. The test procedure relies on NT command extensions.
+  3. The CORE command procedure has been changed to allow preprocessor
+     symbols to be defined. See below.
+
+CORE syntax
+
+CORE filename [ object_directory [options] ]
+
+If options are being used the object directory parameter must be present,
+the default value is "." for the current directory.
+
+Options are:
+
+/UNICODE
+     Specifies that strings are emitted as Unicode in the resource binary.
+     Previously, this option was selected with "-u", which is the parameter
+     currently used by RCOMP itself.
+/DEFINE symbol [ symbol...]
+     Specifies one or more symbols to be defined for the preprocessor pass.
+     This must be the last option supplied because it is followed by an
+     arbitrary number of tokens and the command language is so primitive.
+
+
+
+
+
+
+
+
+Version 3.13
+============
+
+Released by PNJ, 13-Jan-1997
+
+Version number scheme is independent of product-specific E32 chain
+numbering.
+
+This is an interim release, to provide 16-bit character set functionality.
+Later releases are planned to provide other requested features.  Existing
+RSS files produce identical binaries to previous releases when compiled
+in the default non-Unicode mode.
+
+There are some serious defects in the source code which will take
+a long time to address properly, eg misuse of assert as a status check.
+
+1.  Minor changes to MNT and build settings.
+2.  Minor code changes to remove warnings.
+3.  Renamed STRING.CPP, .H to remove ambiguity with
+    standard header of the same name.
+4.  rcscan::yyerror function updated so that it actually
+    interprets formatted strings instead of ignoring the extra
+    parameters.
+5.  Fixed defect in String operator != which was doing the inverse
+    of what it is supposed to do!
+6.  Provide a qualifier for Unicode output.
+7.  Fix erroneous error message if source file not specified.
+8.  Fixed problem which caused run time fatal errors during
+    source context switching.
+9.  Introduce new tokens to differentiate between 8 and 16-bit
+    text strings.
+10. Introduce a CHARACTER_SET token to specify the source
+    character set.
+11. Introduce an extra test component directory.
+12. Introduce a command procedure wrapper for RCOMP (called CoRe)
+
+
+Language features
+-----------------
+
+CHARACTER_SET name
+
+Specifies the character set of the input file.  The implementation currently
+does not do much with this, but will do in the nexty release or 2.  Legal
+values for name are currently:
+
+ASCII, CP1252, CP850, ISOLatin1, ShiftJIS, Unicode
+
+Note that Unicode source text is not likely to be supported any time soon,
+largely because RCOMP relies on LEX and YACC which are not Unicode-aware.
+
+The default setting in this implementation is CP1252.
+
+
+TEXT, LTEXT and BUF
+
+Now have explicit 8 and 16-bit variants, eg TEXT8, BUF16.  The unadorned
+variants are internally converted to the 8 or 16-bit equivalents depending
+on the presence of the -u (for unicode) command line qualifier.
+
+The prefixed counter for an LTEXT16 is still an 8-bit field.
+
+The zero terminator for a TEXT16 is a 16-bit field.
+
+For text fields, it is recommended that you continue to use the unadorned
+keywords. For binary data, you should use the explicit 8-bit keywords. This
+is likely to apply most commonly to the BUF (BUF8) keyword.
+
+
+
+
+
+Version 0.03.12
+===============
+
+1) Reduced verbosity.
+2) Released a version compatible with NT4.
+
+Version 0.03.11
+===============
+
+1) PVCS'ed RCOMP and generally tidied it up.
+2) Fixed empty BUF crash.
+3) Fixed extra trailing comma crash.
+4) Cleaned up the build warnings.
+5) Added ...BUF<n>... where n is an integer giving max length of BUF.
+6) The .exe is now called rcomp.exe.
+
+Version 3.06, MartinW, 05 Jul 96
+================================
+1. Added enum handling.
+        e.g.
+        ENUM ExampleEnum { Elem1, Elem2}
+        STRUCT a { BYTE b;}
+        RESOURCE a c { b = ExampleEnum::Elem2;}
+This should set up b with the value 1.
+
+Version 3.05, MartinW, 30 May 96
+================================
+1.Deal with long (>42characters) resource names in output to header
+  file.
+2.Prevent assertion failure in case of missing comma after first item
+  in an array of struct's.
+
+Version 3.04, MartinW, 29 Apr 96
+================================
+Avoid using cin by reading from a specified file (-s<filename>). The 
+cin approach suffered from something to do with the source file being 
+left open even when the program ended. This was the case at least with 
+a test program built using C++ 1.51 and run under NT 3.51.
+e.g.    void main() { char a; cin << a; }
+        TestProgram < a.src
+        del a.src             <---- "file in use by another process".
+
+Version 3.03, MartinW, 18 Apr 96
+================================
+1.Handle syntax error with numbers more effectively so assert does not
+  fail.
+2.Accept 0 for double without warning.
+
+Version 3.02, MartinW, 11 Apr 96
+================================
+Corrected defect to do with line number in error message for text being
+converted to a number.
+
+Version 3.01, MartinW, 9 Apr 96
+===============================
+1.I added more error handling so that more proper error messages are
+  given.
+2.I altered the error message format so that it is suitable for VC++.
+  Brief seems to cope with this new format quite happily. VC++ didn't 
+  seem to like e.g. ".\t1.rss" at the start but "C:\rcomp\src\t1.rss" 
+  worked.
+3.The drive and directory for the file name specified with -i is used
+  to provide the full paths for all filenames given in error messages. 
+  If the -i file name is not a full path then the current directory and 
+  drive are used in combination with the partial path to create a full 
+  path.
+
+Version 3.00, MartinW, 19 Mar 96
+================================
+To use this resource compiler execute "mnt getrel". The egrs.bat file
+is an example of how the resource compiler may be run. The GNU
+preprocessor is used (t:\tools\gnucpp.exe) first and the output
+passed to rc3.exe. The fc4bat.exe file is used to avoid writing the
+header output file if it has in fact not changed.
+
+Details about this version
+--------------------------
+This is a completely new version based on yacc and lex along with C++.
+
+Overview of system:
+        Source file (e.g.pic.rss) 
+                -> Preprocessing
+                -> Lexer
+                -> Parser
+                -> Data structures (using C++ classes)
+                -> Data file output (e.g. pic.rsg)
+                -> Header file output (e.g. pic.h)
+
+        The GNU C++ preprocessor was used. The output from this
+        includes directives giving line numbering following inclusion
+        of header files. The lexer uses this to store data which the 
+        parser then uses to output error messages in Brief format.
+    
+        The lexer and parser are generated by lex and yacc
+        respectively from rcomp.l and rcomp.y. These define the
+        tokens and the grammar for the resource script language.
+
+        Supporting C++ classes are compiled and linked along with the
+        output from lex and yacc.
+
+        The batch file rs.bat takes the file specified by the first
+        parameter and passes it to the GNU preprocessor. The output
+        is piped through to rcomp.exe. The names of the data output 
+        file and the header file are specified based on the name
+        given to rs.bat. The -i flag is used to give the original
+        name (as passed to the preprocessor) for error reporting.
+     
+        A program called fc4bat.exe is used to give an errorlevel if
+        the specified files do not match. This is used to avoid
+        changing the date on the header file if it has not changed.
+
+Issues for porting to other platforms:
+         1) atof has been used. The output of this is written to the
+            rsc file. The format must be that expected by the program
+            reading the rsc file rather than the format of the
+            machine used to generate the file.
+         2) The MKS versions of yacc and lex were used. These are PC
+            versions of the UNIX tools. The non-standard features
+            were avoided however only the PC versions have been used.
+         3) Stream handling has been used. Apparently there may be
+            differences in implementations of this extension to C++.
+
+
--- a/bintools/rcomp/group/rcomp.mmp	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/rcomp/group/rcomp.mmp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,47 +1,47 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-TARGET			rcomp.exe
-
-TARGETTYPE		exe
-
-SOURCEPATH		.
-
-SOURCEPATH		../src
-SOURCE			 main.cpp                                          
-SOURCE			 ARRAY.CPP ASTRING.CPP CCODES.CPP CTABLE.CPP       
-SOURCE			 DATATYPE.CPP ERRORHAN.CPP FILEACC.CPP FILELINE.CPP
-SOURCE			 INDEXTAB.CPP LINKLIST.CPP MEM.CPP                 
-SOURCE			 NAMEIDMA.CPP NUMVAL.CPP RCBINSTR.CPP              
-SOURCE			 RCOSTRM.CPP                                       
-SOURCE			 RCSCAN.CPP RCSTACK.CPP RESOURCE.CPP               
-SOURCE			 STACK.CPP STRINGAR.CPP STRUCTST.CPP               
-SOURCE			 UNICODE_COMPRESSOR.CPP                            
-SOURCE			 localise.cpp QUALIFAR.CPP                         
-SOURCE			messages.cpp
-
-SOURCE			 rcompl.cpp rcomp.cpp
-
-userinclude	../inc
-SYSTEMINCLUDE	../src
-
-MACRO			_WIN32
-
-OPTION			GCC -w //Disabling warnings for TOOLS2 build, since GCC warns of code generated by bison
-
-VENDORID 0x70000001
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+TARGET			rcomp.exe
+
+TARGETTYPE		exe
+
+SOURCEPATH		.
+
+SOURCEPATH		../src
+SOURCE			 main.cpp                                          
+SOURCE			 ARRAY.CPP ASTRING.CPP CCODES.CPP CTABLE.CPP       
+SOURCE			 DATATYPE.CPP ERRORHAN.CPP FILEACC.CPP FILELINE.CPP
+SOURCE			 INDEXTAB.CPP LINKLIST.CPP MEM.CPP                 
+SOURCE			 NAMEIDMA.CPP NUMVAL.CPP RCBINSTR.CPP              
+SOURCE			 RCOSTRM.CPP                                       
+SOURCE			 RCSCAN.CPP RCSTACK.CPP RESOURCE.CPP               
+SOURCE			 STACK.CPP STRINGAR.CPP STRUCTST.CPP               
+SOURCE			 UNICODE_COMPRESSOR.CPP                            
+SOURCE			 localise.cpp QUALIFAR.CPP                         
+SOURCE			messages.cpp
+
+SOURCE			 rcompl.cpp rcomp.cpp
+
+userinclude	../inc
+SYSTEMINCLUDE	../src
+
+// MACRO			_WIN32
+
+OPTION	GCC -O2 -w
+
+VENDORID 0x70000001
--- a/bintools/rcomp/group/rcomp.mrp	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/rcomp/group/rcomp.mrp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,7 +1,7 @@
 component	dev_build_bintools_rcomp
-source	\src\tools\dev\build\bintools\rcomp
-binary	\src\tools\dev\build\bintools\rcomp\group	all
-exports	\src\tools\dev\build\bintools\rcomp\group
+source	\src\tools\build\bintools\rcomp
+binary	\src\tools\build\bintools\rcomp\group	all
+exports	\src\tools\build\bintools\rcomp\group
 
 binary	\epoc32\release\tools2\rel\rcomp.exe
 
--- a/bintools/rcomp/inc/VERSION.H	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/rcomp/inc/VERSION.H	Tue Jun 29 14:52:54 2010 +0800
@@ -1,23 +1,23 @@
-/*
-* Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-const char version[]="8.2";
-
-const char build[]="005";
-
-// end of version.h
+/*
+* Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+const char version[]="8.4";
+
+const char build[]="001";
+
+// end of version.h
--- a/bintools/rcomp/inc/main.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/rcomp/inc/main.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,103 +1,106 @@
-/*
-* Copyright (c) 2000-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* VT fix here
-*
-*/
-
-
-#ifndef __MAIN_H__
-#define __MAIN_H__
-
-#ifdef __VC32__ 
-#pragma warning( disable : 4786 )	// identifier truncated in debugging information.
-#pragma warning( push, 1 )	// MS STL libraries do not compile cleanly, temporarily set warning level to 1
-#pragma warning( disable : 4530 )	// and disable this one as well.
-#pragma warning(disable : 4710 )
-#endif
-#include <vector>
-#include <map>
-#ifdef __VC32__
-#pragma warning( pop )
-#endif
-
-// VT fix for Linux
-#ifdef __LINUX__
-   #include <stdio.h>
-#endif // LINUX
-// end VT
-
-#include "STRUCTST.H"
-#include "RCSTACK.H" 
-#include "INDEXTAB.H"
-#include "FILELINE.H"
-#include "Parser.h"
-#include "qualifar.h"
-#include "messages.h"
-
-struct RlsValue
-{
-	RlsValue(const String* aFileName, int aLineNo,
-		const char*a, TRlsType aType, TRlsCardinality aCard)
-		: iValue(a), iType(aType), iCardinality(aCard), iCitationCount(0),
-		iMaximumLength(0xFFFFFFF),
-		iLineNumber(aLineNo), iFileName(aFileName) { }
-	RlsValue(const String* aFileName, int aLineNo,
-		const char*a, TRlsType aType, TRlsCardinality aCard,
-		unsigned long aMaximumLength)
-		: iValue(a), iType(aType), iCardinality(aCard), iCitationCount(0),
-		iMaximumLength(aMaximumLength),
-		iLineNumber(aLineNo), iFileName(aFileName) { }
-
-	String iValue;
-	TRlsType iType;
-	TRlsCardinality iCardinality;
-	int iCitationCount;
-	unsigned long iMaximumLength;
-	int iLineNumber;
-	const String* iFileName;
-};
-
-typedef std::map<String, int, StringLess> TNameIndex;
-typedef TNameIndex::iterator TNameIndexIterator;
-
-
-// Global data is held in a structure allocated in main(). This is in order for the memory leakage
-// mechanism to be able see the allocation of this data.
-struct GlobalData
-{
-    StructHeaderArray          SHA;
-    ResourceItemArrayStack     RIAStack;
-    StructResourceItemStack    SRIStack;
-    IndexTable                 Index;
-    NameIdMap                  ResourceNameIds;
-    FileLineManager            FileLineHandler;
-    NameIdMap                  EnumValues;
-    std::vector<RlsValue>      RlsValues;
-    TNameIndex                 RlsNameIndex; // index from Label -> RlsValues[]
-    bool                       WarningMultiExplained;
-    StringArray                AllIdentifiers;
-    QualifiedStringArray       UsedIdentifiers;
-    MessageArray               Messages;
-};
-
-extern GlobalData *pG;
-extern int verbose;
-extern unsigned short logmemorysetting;		// remove this
-
-
-
-extern int ParseSourceFile(FILE* aFile, unsigned short aYYDebug);
-
-#endif // end VT __MAIN_H__
+/*
+* Copyright (c) 2000-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* VT fix here
+*
+*/
+
+
+#ifndef __MAIN_H__
+#define __MAIN_H__
+
+#ifdef __VC32__ 
+#pragma warning( disable : 4786 )	// identifier truncated in debugging information.
+#pragma warning( push, 1 )	// MS STL libraries do not compile cleanly, temporarily set warning level to 1
+#pragma warning( disable : 4530 )	// and disable this one as well.
+#pragma warning(disable : 4710 )
+#endif
+#include <vector>
+#include <map>
+#ifdef __VC32__
+#pragma warning( pop )
+#endif
+
+// VT fix for Linux
+#ifdef __LINUX__
+   #include <stdio.h>
+#endif // LINUX
+// end VT
+
+#include "STRUCTST.H"
+#include "RCSTACK.H" 
+#include "INDEXTAB.H"
+#include "FILELINE.H"
+#include "Parser.h"
+#include "qualifar.h"
+#include "messages.h"
+
+struct RlsValue
+{
+	RlsValue(const String* aFileName, int aLineNo,
+		const char*a, TRlsType aType, TRlsCardinality aCard)
+		: iValue(a), iType(aType), iCardinality(aCard), iCitationCount(0),
+		iMaximumLength(0xFFFFFFF),
+		iLineNumber(aLineNo), iFileName(aFileName) { }
+	RlsValue(const String* aFileName, int aLineNo,
+		const char*a, TRlsType aType, TRlsCardinality aCard,
+		unsigned long aMaximumLength)
+		: iValue(a), iType(aType), iCardinality(aCard), iCitationCount(0),
+		iMaximumLength(aMaximumLength),
+		iLineNumber(aLineNo), iFileName(aFileName) { }
+
+	String iValue;
+	TRlsType iType;
+	TRlsCardinality iCardinality;
+	int iCitationCount;
+	unsigned long iMaximumLength;
+	int iLineNumber;
+	const String* iFileName;
+};
+
+typedef std::map<String, int, StringLess> TNameIndex;
+typedef TNameIndex::iterator TNameIndexIterator;
+
+
+// Global data is held in a structure allocated in main(). This is in order for the memory leakage
+// mechanism to be able see the allocation of this data.
+struct GlobalData
+{
+    StructHeaderArray          SHA;
+    ResourceItemArrayStack     RIAStack;
+    StructResourceItemStack    SRIStack;
+    IndexTable                 Index;
+    NameIdMap                  ResourceNameIds;
+    FileLineManager            FileLineHandler;
+    NameIdMap                  EnumValues;
+    std::vector<RlsValue>      RlsValues;
+    TNameIndex                 RlsNameIndex; // index from Label -> RlsValues[]
+    bool                       WarningMultiExplained;
+    StringArray                AllIdentifiers;
+    QualifiedStringArray       UsedIdentifiers;
+    MessageArray               Messages;
+	char*					   StdInBuffer ;
+	unsigned long			   StdInBufLength ;
+	unsigned long			   StdInfBufPos ;
+};
+
+extern GlobalData *pG;
+extern int verbose;
+extern unsigned short logmemorysetting;		// remove this
+
+
+
+extern int ParseSourceFile(FILE* aFile, unsigned short aYYDebug);
+
+#endif // end VT __MAIN_H__
--- a/bintools/rcomp/src/NUMVAL.CPP	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/rcomp/src/NUMVAL.CPP	Tue Jun 29 14:52:54 2010 +0800
@@ -1,473 +1,473 @@
-/*
-* Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include <assert.h>
-#include <string.h>
-#include <ctype.h>
-#include <stdlib.h>
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-#include <sstream>
-#include <iostream>
-using std::cerr;
-using std::endl;
-#else //!__MSVCDOTNET__
-#ifndef __LINUX__
-#include <strstrea.h>
-#endif //!__LINUX__
-#endif //__MSVCDOTNET__
-
-#include "ASTRING.H"
-#include "NUMVAL.H"  
-#include "STRUCTST.H"
-#include "Parser.h"
-#include "rcomp.hpp"
-#include "MEM.H"     
-#include "ERRORHAN.H"
-#include "RCBINSTR.H"
-
-#if defined(__VC32__)
-#pragma warning( disable : 4702 )	// unreachable code
-#endif
-
-NumericValue::NumericValue( const String & Source, DataType NumericValueType):
-	iNumericValueType( NumericValueType),
-	iData( NULL),
-	iULongValue( 0),
-	iSignedValue( 0),
-	iDoubleValue( 0.0)
-	{
-	AllocateSpace();
-	ConvertToNumber( Source);
-	}
-
-NumericValue::NumericValue( DataType NumericValueType):
-	iNumericValueType( NumericValueType),
-	iData( NULL),
-	iULongValue( 0),
-	iSignedValue( 0),
-	iDoubleValue( 0.0)
-	{
-	AllocateSpace();
-	}
-
-NumericValue::NumericValue( unsigned long ValueToSet, DataType NumericValueType):
-	iNumericValueType( NumericValueType),
-	iData( NULL),
-	iULongValue( 0),
-	iSignedValue( 0),
-	iDoubleValue( 0.0)
-	{
-	AllocateSpace();
-	StoreValue( ValueToSet);
-	}
-
-NumericValue::~NumericValue()
-	{
-	delete [] iData;
-	}
-
-NumericValue::NumericValue( const NumericValue & Source):
-	iNumericValueType( Source.iNumericValueType),
-	iData( NULL),
-	iULongValue( 0),
-	iSignedValue( 0),
-	iDoubleValue( 0.0)	
-	{
-	AllocateSpace();
-	memcpy( iData, Source.iData, iSize);
-	}
-
-void NumericValue::AllocateSpace()
-	{
-	switch(iNumericValueType)
-		{
-		case L_BYTE:
-			iData = new unsigned char [1];
-			iSize = 1;
-			break;
-		case L_WORD:
-			iData = new unsigned char [2];
-			iSize = 2;
-			break;
-		case L_LONG:
-			iData = new unsigned char [4];
-			iSize = 4;
-			break;
-		default:
-			if ( iNumericValueType != L_DOUBLE)
-				assert(0);	// Cannot use NumericValue for specified data type.
-		}
-
-	if ( iNumericValueType != L_DOUBLE && iData == NULL)
-		{
-		ErrorHandler::OutputErrorLine( "Failed to allocate space for number.");
-		exit(1);
-		}
-	}
-
-const unsigned char * NumericValue::Data() const
-	{
-	return iData;
-	}
-
-unsigned long NumericValue::Size() const
-	{
-	return iSize;
-	}
-
-DataType NumericValue::NumericValueType() const
-	{
-	return iNumericValueType;
-	}
-
-void NumericValue::ConvertToNumber( const String & Source)
-	{
-	if ( iNumericValueType == L_DOUBLE)
-		ConvertToDouble( Source);
-	else
-		ConvertToNatural( Source);
-	}
-
-void NumericValue::ConvertToDouble( const String & Source)
-	{
-	assert( iNumericValueType == L_DOUBLE);
-	assert( Source.Length() > 0);
-	
-	double d = atof( Source.GetAssertedNonEmptyBuffer());
-	if ( d == 0.0 && !( Source == "0.0" || Source == "0") )
-		{ MOFF; cerr << "atof may have failed for " << Source << endl; MON;}
-		
-	iDoubleValue = d;
-	}
- 
-#if defined(__VC32__)
-#pragma warning( disable : 4706 ) // assignment within conditional expression
-#endif
-
-void NumericValue::ConvertToNatural( const String & Source)
-	{
-	unsigned long	LongValue = 0;
-	
-	assert( sizeof( unsigned long) >= 4);	// Assume that LongValue can hold at least 2^32 - 1.
-	
-	const char *	pSourceChar = Source.iRep;
-	int	bLeadingHyphen = 0;
-	int	bHexNumber = 0;
-
-	if ( pSourceChar[0] == '0' && pSourceChar[1] == 'x')
-		{
-		bHexNumber = 1;
-		pSourceChar++;
-		pSourceChar++;
-		}
-	
-	if ( pSourceChar[0] == '-')
-		{
-		bLeadingHyphen = 1;
-		pSourceChar++;
-		}
-
-	while ( * pSourceChar != '\0')
-		{
-		unsigned char DigitValue;
-		
-		if ( bHexNumber)
-			{
-			assert( isxdigit( * pSourceChar) );
-			if ( isdigit( * pSourceChar) )
-				DigitValue = (unsigned char)(* pSourceChar - '0');
-			else
-				DigitValue = (unsigned char)(toupper( * pSourceChar) - 'A' + 10);
-				if (LongValue >= 0x10000000)
-					{
-					String st("Number \"");	
-					st += Source;
-					st +=  "\" is too big ";
-					ErrorHandler::OutputErrorLine(st);	//prevents overflow if number is bigger than 2^32 - 1.
-					}
-			LongValue = LongValue * 16 + DigitValue;
-			}
-		else
-			{
-			if ( ! isdigit( * pSourceChar) )
-				{
-				String s( "Cannot convert \"");
-				s += Source;
-				s += "\" to a number.";
-				ErrorHandler::OutputErrorLine( s);
-				exit(1);
-				// unreachable code
-				}
-			DigitValue = (unsigned char)(* pSourceChar - '0');
-			if ((LongValue > 429496729) || ((LongValue == 429496729) && (DigitValue > 5)))
-				{
-				String st("Number \"");	
-				st += Source;
-				st +=  "\" is too big ";
-				ErrorHandler::OutputErrorLine(st);	//prevents overflow if number is bigger than 2^32 - 1.
-				}
-			LongValue = LongValue * 10 + DigitValue;
-			}	
-		pSourceChar++;		
-		assert( ( pSourceChar - Source.iRep) < 10000);	// Safety check!
-		}
-
-	int inrange=0;
-	
-	// Check value is within the allowed range for the type taking into account
-	// a leading hyphen (minus sign) if there was one.
-	switch( iNumericValueType)
-		{
-		case L_BYTE:							// L_BYTE is 8 bits long.
-			if ( bLeadingHyphen)
-				{
-				if ( ! ( inrange = (LongValue <= 128) ) )			// 2 ^ 7
-					ErrorHandler::OutputErrorLine( "Number too low for BYTE");
-				}
-			else
-				if ( ! ( inrange = (LongValue <= 0xFF) ) )
-					ErrorHandler::OutputErrorLine( "Number too big for BYTE");
-			break;
-		case L_WORD:							// L_WORD is 16-bits long.
-			if ( bLeadingHyphen)
-				{
-				if ( ! ( inrange = (LongValue <= 32768) ) )		// 2^15
-					ErrorHandler::OutputErrorLine( "Number too low for WORD");
-				}
-			else
-				if ( ! ( inrange = (LongValue <= 0xFFFF) ) )
-					ErrorHandler::OutputErrorLine( "Number too big for WORD");
-			break;
-		case L_LONG:							// L_LONG is 32-bits long
-			if ( bLeadingHyphen)
-				{
-				if ( ! ( inrange = (LongValue <= 0x80000000) ) )	// 2^31
-					ErrorHandler::OutputErrorLine( "Number too low for LONG");
-				}
-			else
-				if ( ! ( inrange = (LongValue <= 0xFFFFFFFF ) ) ) // This test is a bit pointless as long cannot be greater than 0xffffffff
-					ErrorHandler::OutputErrorLine( "Number too big for LONG");
-			break;
-		default:
-			assert(0);	// Other data types cannot be converted to natural numbers.
-		}
-
-	if(!inrange)
-		exit(1);
-	
-	StoreValue( LongValue);
-
-	// If there was a hyphen then make the stored number negative (using two's complement).
-	if ( bLeadingHyphen)
-		{
-		LongValue = (LongValue ^ 0xFFFFFFFFu)+1;
-
-		// Output file will be treated as little-endian.
-		switch ( iNumericValueType)
-			{
-			case L_LONG:
-				iData[3] = (unsigned char)((LongValue & 0xFF000000) >> 24);
-				iData[2] = (unsigned char)((LongValue & 0xFF0000) >> 16);
-			case L_WORD:
-				iData[1] = (unsigned char)((LongValue & 0xFF00) >> 8);
-			case L_BYTE:
-				iData[0] = (unsigned char)(LongValue & 0xFF);
-			}
-		}
-	}
-
-#if defined(__VC32__)
-#pragma warning( default : 4706 ) // assignment within conditional expression
-#endif
-
-void NumericValue::StoreValue( unsigned long LongValue)
-	{		
-	iULongValue = LongValue;
-	
-	if ( LongValue <= 0x80000000)
-		iSignedValue = (unsigned long) LongValue;
-
-	int inrange = 1;
-		
-	switch( iNumericValueType)
-		{
-		case L_BYTE:
-			inrange = ( LongValue <= 0xFF);
-			break;
-		case L_WORD:
-			inrange = ( LongValue <= 0xFFFF);
-			break;
-		case L_LONG:
-			inrange = ( LongValue <= 0xFFFFFFFF);
-		}
-
-	if ( ! inrange)	
-		{
-		ErrorHandler::OutputErrorLine( "Numeric value out of range for specified type");
-		exit(1);
-		}
-
-	// Output file will be treated as little-endian.
-	switch ( iNumericValueType)
-		{
-		case L_LONG:
-			iData[3] = (unsigned char)((LongValue & 0xFF000000) >> 24);
-			iData[2] = (unsigned char)((LongValue & 0xFF0000) >> 16);
-		case L_WORD:
-			iData[1] = (unsigned char)((LongValue & 0xFF00) >> 8);
-		case L_BYTE:
-			iData[0] = (unsigned char)(LongValue & 0xFF);
-		}
-	}
-
-template<bool> class __CompileTimeAssert {public: __CompileTimeAssert(...) {}};
-template<> class __CompileTimeAssert<false> {};
-struct COMPILE_TIME_ERROR {};
-#define COMPILE_TIME_ASSERT(aCondition) { __CompileTimeAssert<(aCondition)> __temp = __CompileTimeAssert<(aCondition)>(COMPILE_TIME_ERROR()); }
-
-RCBinaryStream & operator<< ( RCBinaryStream & os, NumericValue o)
-	{
-	switch( o.iNumericValueType)
-		{
-		case L_BYTE:
-			os.Write( o.iData, 1);
-			break;
-		case L_WORD:
-			os.Write( o.iData, 2);
-			break;
-		case L_LONG:
-			os.Write( o.iData, 4);
-			break;
-		case L_DOUBLE:
-			COMPILE_TIME_ASSERT(sizeof(double) == 8);
-			os.Write(reinterpret_cast<unsigned char*>(&o.iDoubleValue), 8);
-			break;
-		default:
-			assert(0);
-		}
-	
-	return os;
-	}
-
-void NumericValue::StreamOut(ResourceDataStream& aStream) const
-	{
-	switch (iNumericValueType)
-		{
-		case L_BYTE:
-			aStream.StreamIn(iData, 1);
-			break;
-		case L_WORD:
-			aStream.StreamIn(iData, 2);
-			break;
-		case L_LONG:
-			aStream.StreamIn(iData, 4);
-			break;
-		case L_DOUBLE:
-			COMPILE_TIME_ASSERT(sizeof(double) == 8);
-			aStream.StreamIn(reinterpret_cast<const unsigned char*>(&iDoubleValue), 8);
-			break;
-		default:
-			assert(0);
-		}
-	}
-
-NumericValue & NumericValue::operator= ( unsigned long ValueToSet)
-	{
-	StoreValue( ValueToSet);
-	
-	return * this;
-	}
-
-unsigned long NumericValue::GetULong() const
-	{
-	return iULongValue;
-	}
-
-long NumericValue::GetLong() const
-	{
-	assert( iULongValue <= 2147483647);	// Check that we are not holding a number that is really positive only.
-	return iSignedValue;
-	}
-
-bool NumericValue::CheckSigned(unsigned long aValue, DataType aNumericValueType)
-	{
-	switch (aNumericValueType)
-		{
-		case L_BYTE:
-			if (aValue > 0x7f) return false;
-			break;
-		case L_WORD:
-			if (aValue > 0x7fff) return false;
-			break;
-		case L_LONG:
-			if (aValue > 0x7fffffff) return false;
-			break;
-		default:
-			assert(0);
-		}
-	return true;
-	}
-
-String NumericValue::ltoa( long Source)
-	{
-	char	v[10];	// long can have no more than 10 digits in this implementation.
-	char *	pv = v;
-	long	x;
-	
-	if ( Source < 0)
-		x = - Source;
-	else
-		x = Source;
-
-	if ( x == 0)
-		* pv++ = '0';
-	else
-		{
-		while( x > 0)
-			{
-			assert( pv <= (v+9) );
-
-			* pv = char(x%10 + '0');
-			pv++;
-			x /= 10;
-			}
-		}
-
-	// Now reverse digits so they are in the correct order. Put in terminating null and hyphen
-	// if necessary.
-	
-	char	r[12];
-	char *	pr = r;
-
-	if ( Source < 0)
-		{
-		r[0] = '-';
-		pr++;
-		}
-
-	while( pv != v)
-		{
-		assert( pr < (r+11) );
-		* pr++ = * --pv;
-		}
-		
-	* pr = '\0';
-	
-	return r;
-	}
+/*
+* Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#include <assert.h>
+#include <string.h>
+#include <ctype.h>
+#include <stdlib.h>
+
+#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
+#include <sstream>
+#include <iostream>
+using std::cerr;
+using std::endl;
+#else //!__MSVCDOTNET__
+#ifndef __LINUX__
+#include <strstrea.h>
+#endif //!__LINUX__
+#endif //__MSVCDOTNET__
+
+#include "ASTRING.H"
+#include "NUMVAL.H"  
+#include "STRUCTST.H"
+#include "Parser.h"
+#include "rcomp.hpp"
+#include "MEM.H"     
+#include "ERRORHAN.H"
+#include "RCBINSTR.H"
+
+#if defined(__VC32__)
+#pragma warning( disable : 4702 )	// unreachable code
+#endif
+
+NumericValue::NumericValue( const String & Source, DataType NumericValueType):
+	iNumericValueType( NumericValueType),
+	iData( NULL),
+	iULongValue( 0),
+	iSignedValue( 0),
+	iDoubleValue( 0.0)
+	{
+	AllocateSpace();
+	ConvertToNumber( Source);
+	}
+
+NumericValue::NumericValue( DataType NumericValueType):
+	iNumericValueType( NumericValueType),
+	iData( NULL),
+	iULongValue( 0),
+	iSignedValue( 0),
+	iDoubleValue( 0.0)
+	{
+	AllocateSpace();
+	}
+
+NumericValue::NumericValue( unsigned long ValueToSet, DataType NumericValueType):
+	iNumericValueType( NumericValueType),
+	iData( NULL),
+	iULongValue( 0),
+	iSignedValue( 0),
+	iDoubleValue( 0.0)
+	{
+	AllocateSpace();
+	StoreValue( ValueToSet);
+	}
+
+NumericValue::~NumericValue()
+	{
+	delete [] iData;
+	}
+
+NumericValue::NumericValue( const NumericValue & Source):
+	iNumericValueType( Source.iNumericValueType),
+	iData( NULL),
+	iULongValue( 0),
+	iSignedValue( 0),
+	iDoubleValue( 0.0)	
+	{
+	AllocateSpace();
+	memcpy( iData, Source.iData, iSize);
+	}
+
+void NumericValue::AllocateSpace()
+	{
+	switch(iNumericValueType)
+		{
+		case L_BYTE:
+			iData = new unsigned char [1];
+			iSize = 1;
+			break;
+		case L_WORD:
+			iData = new unsigned char [2];
+			iSize = 2;
+			break;
+		case L_LONG:
+			iData = new unsigned char [4];
+			iSize = 4;
+			break;
+		default:
+			if ( iNumericValueType != L_DOUBLE)
+				assert(0);	// Cannot use NumericValue for specified data type.
+		}
+
+	if ( iNumericValueType != L_DOUBLE && iData == NULL)
+		{
+		ErrorHandler::OutputErrorLine( "Error: Failed to allocate space for number.");
+		exit(1);
+		}
+	}
+
+const unsigned char * NumericValue::Data() const
+	{
+	return iData;
+	}
+
+unsigned long NumericValue::Size() const
+	{
+	return iSize;
+	}
+
+DataType NumericValue::NumericValueType() const
+	{
+	return iNumericValueType;
+	}
+
+void NumericValue::ConvertToNumber( const String & Source)
+	{
+	if ( iNumericValueType == L_DOUBLE)
+		ConvertToDouble( Source);
+	else
+		ConvertToNatural( Source);
+	}
+
+void NumericValue::ConvertToDouble( const String & Source)
+	{
+	assert( iNumericValueType == L_DOUBLE);
+	assert( Source.Length() > 0);
+	
+	double d = atof( Source.GetAssertedNonEmptyBuffer());
+	if ( d == 0.0 && !( Source == "0.0" || Source == "0") )
+		{ MOFF; cerr << "atof may have failed for " << Source << endl; MON;}
+		
+	iDoubleValue = d;
+	}
+ 
+#if defined(__VC32__)
+#pragma warning( disable : 4706 ) // assignment within conditional expression
+#endif
+
+void NumericValue::ConvertToNatural( const String & Source)
+	{
+	unsigned long	LongValue = 0;
+	
+	assert( sizeof( unsigned long) >= 4);	// Assume that LongValue can hold at least 2^32 - 1.
+	
+	const char *	pSourceChar = Source.iRep;
+	int	bLeadingHyphen = 0;
+	int	bHexNumber = 0;
+
+	if ( pSourceChar[0] == '0' && pSourceChar[1] == 'x')
+		{
+		bHexNumber = 1;
+		pSourceChar++;
+		pSourceChar++;
+		}
+	
+	if ( pSourceChar[0] == '-')
+		{
+		bLeadingHyphen = 1;
+		pSourceChar++;
+		}
+
+	while ( * pSourceChar != '\0')
+		{
+		unsigned char DigitValue;
+		
+		if ( bHexNumber)
+			{
+			assert( isxdigit( * pSourceChar) );
+			if ( isdigit( * pSourceChar) )
+				DigitValue = (unsigned char)(* pSourceChar - '0');
+			else
+				DigitValue = (unsigned char)(toupper( * pSourceChar) - 'A' + 10);
+				if (LongValue >= 0x10000000)
+					{
+					String st("Number \"");	
+					st += Source;
+					st +=  "\" is too big ";
+					ErrorHandler::OutputErrorLine(st);	//prevents overflow if number is bigger than 2^32 - 1.
+					}
+			LongValue = LongValue * 16 + DigitValue;
+			}
+		else
+			{
+			if ( ! isdigit( * pSourceChar) )
+				{
+				String s( "Error: Cannot convert \"");
+				s += Source;
+				s += "\" to a number.";
+				ErrorHandler::OutputErrorLine( s);
+				exit(1);
+				// unreachable code
+				}
+			DigitValue = (unsigned char)(* pSourceChar - '0');
+			if ((LongValue > 429496729) || ((LongValue == 429496729) && (DigitValue > 5)))
+				{
+				String st("Number \"");	
+				st += Source;
+				st +=  "\" is too big ";
+				ErrorHandler::OutputErrorLine(st);	//prevents overflow if number is bigger than 2^32 - 1.
+				}
+			LongValue = LongValue * 10 + DigitValue;
+			}	
+		pSourceChar++;		
+		assert( ( pSourceChar - Source.iRep) < 10000);	// Safety check!
+		}
+
+	int inrange=0;
+	
+	// Check value is within the allowed range for the type taking into account
+	// a leading hyphen (minus sign) if there was one.
+	switch( iNumericValueType)
+		{
+		case L_BYTE:							// L_BYTE is 8 bits long.
+			if ( bLeadingHyphen)
+				{
+				if ( ! ( inrange = (LongValue <= 128) ) )			// 2 ^ 7
+					ErrorHandler::OutputErrorLine( "Error: Number too low for BYTE");
+				}
+			else
+				if ( ! ( inrange = (LongValue <= 0xFF) ) )
+					ErrorHandler::OutputErrorLine( "Error: Number too big for BYTE");
+			break;
+		case L_WORD:							// L_WORD is 16-bits long.
+			if ( bLeadingHyphen)
+				{
+				if ( ! ( inrange = (LongValue <= 32768) ) )		// 2^15
+					ErrorHandler::OutputErrorLine( "Error: Number too low for WORD");
+				}
+			else
+				if ( ! ( inrange = (LongValue <= 0xFFFF) ) )
+					ErrorHandler::OutputErrorLine( "Error: Number too big for WORD");
+			break;
+		case L_LONG:							// L_LONG is 32-bits long
+			if ( bLeadingHyphen)
+				{
+				if ( ! ( inrange = (LongValue <= 0x80000000) ) )	// 2^31
+					ErrorHandler::OutputErrorLine( "Error: Number too low for LONG");
+				}
+			else
+				if ( ! ( inrange = (LongValue <= 0xFFFFFFFF ) ) ) // This test is a bit pointless as long cannot be greater than 0xffffffff
+					ErrorHandler::OutputErrorLine( "Error: Number too big for LONG");
+			break;
+		default:
+			assert(0);	// Other data types cannot be converted to natural numbers.
+		}
+
+	if(!inrange)
+		exit(1);
+	
+	StoreValue( LongValue);
+
+	// If there was a hyphen then make the stored number negative (using two's complement).
+	if ( bLeadingHyphen)
+		{
+		LongValue = (LongValue ^ 0xFFFFFFFFu)+1;
+
+		// Output file will be treated as little-endian.
+		switch ( iNumericValueType)
+			{
+			case L_LONG:
+				iData[3] = (unsigned char)((LongValue & 0xFF000000) >> 24);
+				iData[2] = (unsigned char)((LongValue & 0xFF0000) >> 16);
+			case L_WORD:
+				iData[1] = (unsigned char)((LongValue & 0xFF00) >> 8);
+			case L_BYTE:
+				iData[0] = (unsigned char)(LongValue & 0xFF);
+			}
+		}
+	}
+
+#if defined(__VC32__)
+#pragma warning( default : 4706 ) // assignment within conditional expression
+#endif
+
+void NumericValue::StoreValue( unsigned long LongValue)
+	{		
+	iULongValue = LongValue;
+	
+	if ( LongValue <= 0x80000000)
+		iSignedValue = (unsigned long) LongValue;
+
+	int inrange = 1;
+		
+	switch( iNumericValueType)
+		{
+		case L_BYTE:
+			inrange = ( LongValue <= 0xFF);
+			break;
+		case L_WORD:
+			inrange = ( LongValue <= 0xFFFF);
+			break;
+		case L_LONG:
+			inrange = ( LongValue <= 0xFFFFFFFF);
+		}
+
+	if ( ! inrange)	
+		{
+		ErrorHandler::OutputErrorLine( "Error: Numeric value out of range for specified type");
+		exit(1);
+		}
+
+	// Output file will be treated as little-endian.
+	switch ( iNumericValueType)
+		{
+		case L_LONG:
+			iData[3] = (unsigned char)((LongValue & 0xFF000000) >> 24);
+			iData[2] = (unsigned char)((LongValue & 0xFF0000) >> 16);
+		case L_WORD:
+			iData[1] = (unsigned char)((LongValue & 0xFF00) >> 8);
+		case L_BYTE:
+			iData[0] = (unsigned char)(LongValue & 0xFF);
+		}
+	}
+
+template<bool> class __CompileTimeAssert {public: __CompileTimeAssert(...) {}};
+template<> class __CompileTimeAssert<false> {};
+struct COMPILE_TIME_ERROR {};
+#define COMPILE_TIME_ASSERT(aCondition) { __CompileTimeAssert<(aCondition)> __temp = __CompileTimeAssert<(aCondition)>(COMPILE_TIME_ERROR()); }
+
+RCBinaryStream & operator<< ( RCBinaryStream & os, NumericValue o)
+	{
+	switch( o.iNumericValueType)
+		{
+		case L_BYTE:
+			os.Write( o.iData, 1);
+			break;
+		case L_WORD:
+			os.Write( o.iData, 2);
+			break;
+		case L_LONG:
+			os.Write( o.iData, 4);
+			break;
+		case L_DOUBLE:
+			COMPILE_TIME_ASSERT(sizeof(double) == 8);
+			os.Write(reinterpret_cast<unsigned char*>(&o.iDoubleValue), 8);
+			break;
+		default:
+			assert(0);
+		}
+	
+	return os;
+	}
+
+void NumericValue::StreamOut(ResourceDataStream& aStream) const
+	{
+	switch (iNumericValueType)
+		{
+		case L_BYTE:
+			aStream.StreamIn(iData, 1);
+			break;
+		case L_WORD:
+			aStream.StreamIn(iData, 2);
+			break;
+		case L_LONG:
+			aStream.StreamIn(iData, 4);
+			break;
+		case L_DOUBLE:
+			COMPILE_TIME_ASSERT(sizeof(double) == 8);
+			aStream.StreamIn(reinterpret_cast<const unsigned char*>(&iDoubleValue), 8);
+			break;
+		default:
+			assert(0);
+		}
+	}
+
+NumericValue & NumericValue::operator= ( unsigned long ValueToSet)
+	{
+	StoreValue( ValueToSet);
+	
+	return * this;
+	}
+
+unsigned long NumericValue::GetULong() const
+	{
+	return iULongValue;
+	}
+
+long NumericValue::GetLong() const
+	{
+	assert( iULongValue <= 2147483647);	// Check that we are not holding a number that is really positive only.
+	return iSignedValue;
+	}
+
+bool NumericValue::CheckSigned(unsigned long aValue, DataType aNumericValueType)
+	{
+	switch (aNumericValueType)
+		{
+		case L_BYTE:
+			if (aValue > 0x7f) return false;
+			break;
+		case L_WORD:
+			if (aValue > 0x7fff) return false;
+			break;
+		case L_LONG:
+			if (aValue > 0x7fffffff) return false;
+			break;
+		default:
+			assert(0);
+		}
+	return true;
+	}
+
+String NumericValue::ltoa( long Source)
+	{
+	char	v[10];	// long can have no more than 10 digits in this implementation.
+	char *	pv = v;
+	long	x;
+	
+	if ( Source < 0)
+		x = - Source;
+	else
+		x = Source;
+
+	if ( x == 0)
+		* pv++ = '0';
+	else
+		{
+		while( x > 0)
+			{
+			assert( pv <= (v+9) );
+
+			* pv = char(x%10 + '0');
+			pv++;
+			x /= 10;
+			}
+		}
+
+	// Now reverse digits so they are in the correct order. Put in terminating null and hyphen
+	// if necessary.
+	
+	char	r[12];
+	char *	pr = r;
+
+	if ( Source < 0)
+		{
+		r[0] = '-';
+		pr++;
+		}
+
+	while( pv != v)
+		{
+		assert( pr < (r+11) );
+		* pr++ = * --pv;
+		}
+		
+	* pr = '\0';
+	
+	return r;
+	}
--- a/bintools/rcomp/src/RCBINSTR.CPP	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/rcomp/src/RCBINSTR.CPP	Tue Jun 29 14:52:54 2010 +0800
@@ -1,539 +1,539 @@
-/*
-* Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include <assert.h>
-#include <string.h>
-#include "ASTRING.H"
-#include <stdlib.h>
-#include <malloc.h>
-
-#include "RCBINSTR.H"
-#include "TOKENS.H"  
-#include "STACK.H"   
-#include "NUMVAL.H"  
-#include "DATATYPE.H"
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-using std::ofstream;
-using std::ios;
-#endif //__MSVCDOTNET__
-
-extern long CurrentId;
-extern RCTypeArray gTypes;
-
-RCBinaryStream::RCBinaryStream()
-	{}
-
-RCBinaryStream::~RCBinaryStream()
-	{
-	if (iOs.is_open())
-		{
-		iOs.flush();
-		iOs.close();
-		}
-	}
-
-void RCBinaryStream::OpenForAppend(const String& FileName)
-	{
-	assert( !IsOpen());
-	
-	iOs.open( FileName.GetAssertedNonEmptyBuffer(), ios::in | ios::out | ios::binary | ios::ate); // ios::in to prevent overwriting
-	}
-
-int RCBinaryStream::IsOpen()
-	{
-	return(iOs.is_open());
-	}
-		
-RCBinaryStream & RCBinaryStream::operator<< ( char o)
-	{
-	Write((const unsigned char*)&o, 1);
-	return * this;
-	}
-
-RCBinaryStream & RCBinaryStream::operator<< ( char * o)
-	{
-	Write((const unsigned char*)o, strlen(o));
-	return * this;
-	}
-
-int RCBinaryStream::SizeOfCompressedInteger(unsigned int aInteger)
-	{ // static
-	assert((aInteger&~0x7fff)==0);
-	return (aInteger&~0x7f)? 2: 1;
-	}
-
-void RCBinaryStream::WriteCompressedInteger(unsigned int aInteger)
-	{
-	assert((aInteger&~0x7fff)==0);
-	if (aInteger&~0x7f)
-		{
-		*this << char((aInteger>>8)|0x80);
-		}
-	*this << char(aInteger&0xff);
-	}
-
-void RCBinaryStream::Write( const unsigned char * p, unsigned long count)
-	{
-	iOs.write( (const char*)p, count);
-#if defined(_DEBUG)
-	iOs.flush();
-#endif
-	}
-
-unsigned long RCBinaryStream::GetPosition()
-	{
-	return iOs.tellp();
-	}
-
-void RCBinaryStream::SetPosition(unsigned long aNewPosition)
-	{
-	assert(aNewPosition<=GetPosition());
-	iOs.seekp(aNewPosition, ios::beg);
-	}
-
-// ResourceDataStream - this code makes the apparently valid assumption that the decompressing of compressed Unicode (done by BAFL) will yield exactly the same length of string as what you started with before it was compressed (by RCOMP)
-
-ResourceDataStream::ResourceDataStream()
-	:iBuffer(NULL),
-	 iNumberOfBytesAllocated(0),
-	 iNumberOfBytesUsed(0),
-	 iContainsCompressedUnicode(false)
-	{
-	}
-
-ResourceDataStream::~ResourceDataStream()
-	{
-	delete [] iBuffer;
-	}
-
-void ResourceDataStream::StartOfBlockWithSizePrefix(DataType aDataTypeOfSizePrefix)
-	{
-	NumericValue* const sizeOfBlockWhenUncompressed=new NumericValue(aDataTypeOfSizePrefix);
-	assert(sizeOfBlockWhenUncompressed!=NULL);
-	iArrayOfMarks.AppendMark(iNumberOfBytesUsed, EMarkType_StartOfBlockWithSizePrefix, (unsigned int)sizeOfBlockWhenUncompressed);
-	}
-
-void ResourceDataStream::EndOfBlockWithSizePrefix()
-	{
-	iArrayOfMarks.AppendMark(iNumberOfBytesUsed, EMarkType_EndOfBlockWithSizePrefix);
-	}
-
-void ResourceDataStream::StartOfCompressedUnicodeRun(int aUncompressedUnicodeSizeInBytes, const unsigned char* aUncompressedUnicodeBuffer)
-	{
-	if (!iContainsCompressedUnicode)
-		{
-		// the first run *must* be a compressed Unicode run, so if it isn't, insert a zero-length one at the start
-		bool insertZeroLengthCompressedUnicodeRunAtStart=(iNumberOfBytesUsed>0);
-		if (!insertZeroLengthCompressedUnicodeRunAtStart)
-			{
-			const int numberOfMarks=iArrayOfMarks.Size();
-			for (int i=0; i<numberOfMarks; ++i)
-				{
-				const Mark& mark=iArrayOfMarks.MarkAt(i);
-				assert(mark.iBufferPosition==0);
-				assert(mark.iMarkType!=EMarkType_TwoByteAlignmentPoint); // it is only possible to have a EMarkType_TwoByteAlignmentPoint mark if iNumberOfBytesUsed>0, and we only execute this code if !insertZeroLengthCompressedUnicodeRunAtStart, i.e. if iNumberOfBytesUsed==0 (well, strictly speaking, if iNumberOfBytesUsed<=0)
-				if (mark.iMarkType==EMarkType_StartOfBlockWithSizePrefix)
-					{
-					insertZeroLengthCompressedUnicodeRunAtStart=true;
-					break;
-					}
-				}
-			}
-		if (insertZeroLengthCompressedUnicodeRunAtStart)
-			{
-			iArrayOfMarks.InsertMark(0, 0, EMarkType_StartOfCompressedUnicodeRun, (unsigned int)BinaryBuffer::New(0, NULL)); // mark the insertion point for the initial zero-length compressed-Unicode run
-			iArrayOfMarks.InsertMark(1, 0, EMarkType_EndOfCompressedUnicodeRun); // mark the insertion point for the subsquent run of "other stuff"
-			}
-		}
-	iArrayOfMarks.AppendMark(iNumberOfBytesUsed, EMarkType_StartOfCompressedUnicodeRun, (unsigned int)BinaryBuffer::New(aUncompressedUnicodeSizeInBytes, aUncompressedUnicodeBuffer));
-	iContainsCompressedUnicode=true;
-	}
-
-void ResourceDataStream::EndOfCompressedUnicodeRun()
-	{
-#if !defined(NDEBUG)
-	const Mark& markAtStartOfCompressedUnicodeRun=iArrayOfMarks.MarkAt(iArrayOfMarks.Size()-1);
-	assert(markAtStartOfCompressedUnicodeRun.iMarkType==EMarkType_StartOfCompressedUnicodeRun);
-	const int numberOfBytesWhenCompressed=iNumberOfBytesUsed-markAtStartOfCompressedUnicodeRun.iBufferPosition;
-	const BinaryBuffer& runWhenUncompressed=*(const BinaryBuffer*)markAtStartOfCompressedUnicodeRun.iOtherData;
-	assert(numberOfBytesWhenCompressed<runWhenUncompressed.NumberOfBytes());
-#endif
-	iArrayOfMarks.AppendMark(iNumberOfBytesUsed, EMarkType_EndOfCompressedUnicodeRun);
-	}
-
-void ResourceDataStream::TwoByteAlignmentPoint()
-	{
-	iArrayOfMarks.AppendMark(iNumberOfBytesUsed, EMarkType_TwoByteAlignmentPoint);
-	}
-
-void ResourceDataStream::EnquireStreamPositionWhenKnown(unsigned long& aStreamPosition)
-	{
-	iArrayOfMarks.AppendMark(iNumberOfBytesUsed, EMarkType_EnquireStreamPositionWhenKnown, (unsigned int)&aStreamPosition);
-	}
-
-void ResourceDataStream::StreamIn(const unsigned char* aBuffer, int aNumberOfBytes)
-	{
-	EnsureEnoughSpareBytes(aNumberOfBytes);
-	memcpy(iBuffer+iNumberOfBytesUsed, aBuffer, aNumberOfBytes);
-	iNumberOfBytesUsed+=aNumberOfBytes;
-	}
-
-void ResourceDataStream::MakePlaceHolder(int aNumberOfBytes)
-	{
-	EnsureEnoughSpareBytes(aNumberOfBytes);
-	memset(iBuffer+iNumberOfBytesUsed, 0xeb, aNumberOfBytes);
-	iNumberOfBytesUsed+=aNumberOfBytes;
-	}
-
-class SizePrefix : public StackItem
-	{
-public:
-	inline SizePrefix(int aUncompressedSizeOfResourceUpToStartOfBlock, NumericValue& aSizeOfBlockWhenUncompressed) :iUncompressedSizeOfResourceUpToStartOfBlock(aUncompressedSizeOfResourceUpToStartOfBlock), iSizeOfBlockWhenUncompressed(aSizeOfBlockWhenUncompressed) {}
-	inline int UncompressedSizeOfResourceUpToStartOfBlock() const {return iUncompressedSizeOfResourceUpToStartOfBlock;}
-	inline NumericValue& SizeOfBlockWhenUncompressed() const {return iSizeOfBlockWhenUncompressed;}
-private:
-	inline void operator=(const SizePrefix&);
-private:
-	int iUncompressedSizeOfResourceUpToStartOfBlock;
-	NumericValue& iSizeOfBlockWhenUncompressed;
-	};
-
-class SizePrefixStack : public Stack
-	{
-public:
-	inline SizePrefixStack() {}
-	inline void Push(int aUncompressedSizeOfResourceUpToStartOfBlock, NumericValue& aSizeOfBlockWhenUncompressed) {Stack::Push(new SizePrefix(aUncompressedSizeOfResourceUpToStartOfBlock, aSizeOfBlockWhenUncompressed));}
-	inline SizePrefix* Pop() {return (SizePrefix*)Stack::Pop();}
-	};
-
-bool ResourceDataStream::StreamOutReturningWhetherContainsCompressedUnicode(RCBinaryStream& aStream, int& aSizeWhenUncompressed)
-	{
-startOfFirstPass:
-	bool encounteredCompressedUnicode[3];
-	encounteredCompressedUnicode[0]=false;
-	encounteredCompressedUnicode[1]=false;
-	encounteredCompressedUnicode[2]=false;
-	{
-	// do a first pass (i) to calculate run-lengths of the "other-stuff" runs (i.e. the second, fourth, sixth, etc), (ii) to calculate which EMarkType_TwoByteAlignmentPoint marks require a padding byte, and (iii) to calculate the size-prefixes
-	// do a second pass to see if there are any compressed-Unicode runs that don't actually make the resource smaller (taking into consideration the preceding run-length byte(s) and any trailing run-length byte(s)) - if so, replace the EMarkType_StartOfCompressedUnicodeRun/EMarkType_EndOfCompressedUnicodeRun mark-pair with a single EMarkType_TwoByteAlignmentPoint mark and go right back to the start of the first pass
-	// do a third and final pass to actually write out the resource data to aStream
-	const int numberOfMarks=iArrayOfMarks.Size(); // caching this is done *after* the "startOfFirstPass" as ConvertCompressedRunToUncompressed (which is called just before "goto startOfFirstPass") changes the number of items in iArrayOfMarks
-	const unsigned int* lengthOfLastRun=NULL;
-	for (int pass=0; pass<3; ++pass)
-		{
-		const int numberOfBytesBeforeFirstMark=NumberOfBytesToNextMark(-1);
-		int runLength=numberOfBytesBeforeFirstMark;
-		int uncompressedSize=numberOfBytesBeforeFirstMark;
-		unsigned int* addressToWriteSizeOfCompressedIntegerTo=NULL; // used on the first pass
-		SizePrefixStack sizePrefixStack; // used on the first pass
-		int bufferIndex=0; // used on the third pass
-		if (pass==2)
-			{
-			const int numberOfBytesToFirstMark=NumberOfBytesToNextMark(-1);
-			assert(bufferIndex==0);
-			aStream.Write(reinterpret_cast<unsigned char*>(iBuffer), numberOfBytesToFirstMark);
-			bufferIndex+=numberOfBytesToFirstMark;
-			}
-		for (int i=0; i<numberOfMarks; ++i) // must iterate forwards so that lengthOfLastRun is correctly assigned (after the end of this loop) to point to the iOtherData (i.e. run-length) of the last EMarkType_EndOfCompressedUnicodeRun mark
-			{
-			Mark& mark=iArrayOfMarks.MarkAt(i);
-			switch (mark.iMarkType)
-				{
-			case EMarkType_StartOfBlockWithSizePrefix:
-				{
-				NumericValue* const sizeOfBlockWhenUncompressed=(NumericValue*)mark.iOtherData;
-				assert(sizeOfBlockWhenUncompressed!=NULL);
-				const int sizeOfSizePrefix=gTypes.GetSize(sizeOfBlockWhenUncompressed->NumericValueType());
-				runLength+=sizeOfSizePrefix;
-				uncompressedSize+=sizeOfSizePrefix;
-				if (pass==0)
-					{
-					sizePrefixStack.Push(uncompressedSize, *(NumericValue*)mark.iOtherData);
-					}
-				else if (pass==2)
-					{
-					aStream << *sizeOfBlockWhenUncompressed;
-					delete sizeOfBlockWhenUncompressed;
-					mark.iOtherData=(unsigned int)(NumericValue*)NULL;
-					}
-				}
-				break;
-			case EMarkType_EndOfBlockWithSizePrefix:
-				if (pass==0)
-					{
-					SizePrefix* const sizePrefix=sizePrefixStack.Pop();
-					assert(sizePrefix!=NULL);
-					sizePrefix->SizeOfBlockWhenUncompressed()=uncompressedSize-sizePrefix->UncompressedSizeOfResourceUpToStartOfBlock();
-					delete sizePrefix;
-					}
-				break;
-			case EMarkType_StartOfCompressedUnicodeRun:
-				{
-				assert(runLength>=0);
-				if (addressToWriteSizeOfCompressedIntegerTo!=NULL)
-					{
-					*addressToWriteSizeOfCompressedIntegerTo=runLength;
-					addressToWriteSizeOfCompressedIntegerTo=NULL;
-					}
-				runLength=0;
-				BinaryBuffer& runWhenUncompressed=*(BinaryBuffer*)mark.iOtherData;
-				const int numberOfBytesWhenUncompressed=runWhenUncompressed.NumberOfBytes();
-				const int numberOfBytesWhenUncompressedIncludingAnyPrecedingPaddingByte=numberOfBytesWhenUncompressed+((uncompressedSize%2!=0)? 1: 0);
-				assert((numberOfBytesWhenUncompressed>0) || !encounteredCompressedUnicode[pass]); // compressed-Unicode runs are of non-zero size apart from the compulsory initial compressed-Unicode run if the resource does not actually start with compressed Unicode
-				uncompressedSize+=numberOfBytesWhenUncompressedIncludingAnyPrecedingPaddingByte;
-				assert(i+1<numberOfMarks);
-				++i; // skip a loop iteration - we know that EMarkType_StartOfCompressedUnicodeRun marks are always followed by a EMarkType_EndOfCompressedUnicodeRun mark
-				Mark& nextMark=iArrayOfMarks.MarkAt(i);
-				assert(nextMark.iMarkType==EMarkType_EndOfCompressedUnicodeRun);
-				const int numberOfBytesWhenCompressed=nextMark.iBufferPosition-mark.iBufferPosition;
-				assert((numberOfBytesWhenCompressed>0) || !encounteredCompressedUnicode[pass]); // compressed-Unicode runs are of non-zero size apart from the compulsory initial compressed-Unicode run if the resource does not actually start with compressed Unicode
-				assert((numberOfBytesWhenCompressed<numberOfBytesWhenUncompressed) || ((!encounteredCompressedUnicode[pass]) && (numberOfBytesWhenCompressed==0) && (numberOfBytesWhenUncompressed==0)));
-				if (pass==0)
-					{
-					addressToWriteSizeOfCompressedIntegerTo=&nextMark.iOtherData; // iOtherData in "other-stuff" runs (i.e. the second run, the fourth run, the sixth run, etc) stores the combined size of the run taking into account any extra bytes caused by other marks, e.g. a padding byte caused by a ETwoByteAlignmentPoint
-					}
-				else if (pass==1)
-					{
-					const unsigned int* const lengthOfOtherStuffRun=&nextMark.iOtherData;
-					const bool isTheFirstCompressedUnicodeRun=!encounteredCompressedUnicode[pass];
-					const bool isTheLastCompressedUnicodeRun=(lengthOfLastRun==lengthOfOtherStuffRun);
-					if (isTheLastCompressedUnicodeRun || !isTheFirstCompressedUnicodeRun) // if this is the first compressed-Unicode run and there are others, then we can't get rid of it, hence this check
-						{
-						int numberOfBytesWhenCompressedIncludingRunLengthsEitherSide=RCBinaryStream::SizeOfCompressedInteger(numberOfBytesWhenCompressed)+numberOfBytesWhenCompressed;
-						if ((lengthOfLastRun!=lengthOfOtherStuffRun) || (*lengthOfOtherStuffRun>0))
-							{
-							numberOfBytesWhenCompressedIncludingRunLengthsEitherSide+=RCBinaryStream::SizeOfCompressedInteger(*lengthOfOtherStuffRun);
-							}
-						if (numberOfBytesWhenCompressedIncludingRunLengthsEitherSide>=numberOfBytesWhenUncompressedIncludingAnyPrecedingPaddingByte) // use ">=" rather than just ">" as we want to get rid of any compressed-Unicode runs that don't actually give any benefit, so that if possible we can remove the initial compressed-Unicode run (if it's of zero length and it's the only compressed-Unicode run, in which case it's unnecessary overhead)
-							{
-							if (isTheFirstCompressedUnicodeRun && isTheLastCompressedUnicodeRun) // if this is the only compressed-Unicode run...
-								{
-								iContainsCompressedUnicode=false;
-								}
-							ConvertCompressedRunToUncompressed(i-1);
-							goto startOfFirstPass; // go back to the start of the first pass again as we need to calculate all the fiddly stuff again, e.g. whether two-byte alignment points need padding bytes, etc.
-							}
-						}
-					}
-				else
-					{
-					assert(pass==2);
-					runWhenUncompressed.Destroy();
-					mark.iOtherData=(unsigned int)(BinaryBuffer*)NULL;
-					aStream.WriteCompressedInteger(numberOfBytesWhenCompressed);
-					aStream.Write(reinterpret_cast<unsigned char*>(iBuffer+bufferIndex), numberOfBytesWhenCompressed);
-					bufferIndex+=numberOfBytesWhenCompressed;
-					const unsigned int* const lengthOfOtherStuffRun=&nextMark.iOtherData;
-					if ((lengthOfLastRun!=lengthOfOtherStuffRun) || (*lengthOfOtherStuffRun>0))
-						{
-						aStream.WriteCompressedInteger(*lengthOfOtherStuffRun);
-						}
-					}
-				encounteredCompressedUnicode[pass]=true;
-				}
-				break;
-			case EMarkType_TwoByteAlignmentPoint:
-				{
-				const bool needPaddingByte=(uncompressedSize%2!=0);
-				if (needPaddingByte)
-					{
-					++runLength;
-					++uncompressedSize;
-					if (pass==2)
-						{
-						aStream << (unsigned char)(0xab);
-						}
-					}
-				if (pass==0)
-					{
-					mark.iOtherData=needPaddingByte;
-					}
-				else
-					{
-					assert((mark.iOtherData!=0)==needPaddingByte);
-					}
-				}
-				break;
-			case EMarkType_EnquireStreamPositionWhenKnown:
-				if (pass==2)
-					{
-					unsigned long& streamPosition=*(unsigned long*)mark.iOtherData;
-					streamPosition=aStream.GetPosition();
-					}
-				break;
-			default:
-				assert(0);
-				break;
-				}
-			const int numberOfBytesToNextMark=NumberOfBytesToNextMark(i);
-			if (pass==2)
-				{
-				aStream.Write(reinterpret_cast<unsigned char*>(iBuffer+bufferIndex), numberOfBytesToNextMark);
-				}
-			runLength+=numberOfBytesToNextMark;
-			uncompressedSize+=numberOfBytesToNextMark;
-			bufferIndex+=numberOfBytesToNextMark;
-			}
-		if (pass>0)
-			{
-			assert(aSizeWhenUncompressed==uncompressedSize);
-			}
-		else
-			{
-			aSizeWhenUncompressed=uncompressedSize;
-			lengthOfLastRun=addressToWriteSizeOfCompressedIntegerTo;
-			}
-		assert(runLength>=0);
-		if (addressToWriteSizeOfCompressedIntegerTo!=NULL)
-			{
-			*addressToWriteSizeOfCompressedIntegerTo=runLength;
-			addressToWriteSizeOfCompressedIntegerTo=NULL;
-			}
-		runLength=0;
-		}
-	}
-
-	assert(encounteredCompressedUnicode[0]==iContainsCompressedUnicode);
-	assert(encounteredCompressedUnicode[1]==iContainsCompressedUnicode);
-	assert(encounteredCompressedUnicode[2]==iContainsCompressedUnicode);
-	return encounteredCompressedUnicode[0];
-	}
-
-void ResourceDataStream::Dump(const char* aDumpFile) const
-	{
-	ofstream fileStream;
-	fileStream.open(aDumpFile, ios::out | ios::binary | ios::trunc);
-	fileStream.write((const char*)iBuffer, iNumberOfBytesUsed);
-	fileStream.flush();
-	fileStream.close();
-	}
-
-void ResourceDataStream::EnsureEnoughSpareBytes(int aNumberOfBytes)
-	{
-	const int numberOfBytesSpare=iNumberOfBytesAllocated-iNumberOfBytesUsed;
-	assert(numberOfBytesSpare>=0);
-	if (aNumberOfBytes>numberOfBytesSpare)
-		{
-		const int newNumberOfBytesAllocated=iNumberOfBytesAllocated+aNumberOfBytes+16; // 16 is just some extra bytes to stop the heap being thrashed too much
-		unsigned char* const newBuffer = new unsigned char[newNumberOfBytesAllocated];
-		if (iNumberOfBytesUsed>0)
-			{
-			memcpy(newBuffer, iBuffer, iNumberOfBytesUsed);
-			}
-		delete [] iBuffer;
-		iNumberOfBytesAllocated=newNumberOfBytesAllocated;
-		iBuffer=newBuffer;
-		}
-	}
-
-int ResourceDataStream::NumberOfBytesToNextMark(int aMarkIndex) const
-	{
-	assert(aMarkIndex>=-1);
-	assert(aMarkIndex<iArrayOfMarks.Size());
-	int numberOfBytesToNextMark=(aMarkIndex+1<iArrayOfMarks.Size())? iArrayOfMarks.MarkAt(aMarkIndex+1).iBufferPosition: iNumberOfBytesUsed;
-	if (aMarkIndex>=0)
-		{
-		numberOfBytesToNextMark-=iArrayOfMarks.MarkAt(aMarkIndex).iBufferPosition;
-		}
-	return numberOfBytesToNextMark;
-	}
-
-void ResourceDataStream::ConvertCompressedRunToUncompressed(int aMarkIndexOfStartOfCompressedUnicodeRun)
-	{
-	// remove the EMarkType_StartOfCompressedUnicodeRun/EMarkType_EndOfCompressedUnicodeRun mark-pair
-	Mark* markForStartOfCompressedUnicodeRun=&iArrayOfMarks.MarkAt(aMarkIndexOfStartOfCompressedUnicodeRun);
-	assert(markForStartOfCompressedUnicodeRun->iMarkType==EMarkType_StartOfCompressedUnicodeRun);
-	BinaryBuffer& runWhenUncompressed=*(BinaryBuffer*)markForStartOfCompressedUnicodeRun->iOtherData;
-	markForStartOfCompressedUnicodeRun->iOtherData=(unsigned int)(BinaryBuffer*)NULL;
-	Mark* markForEndOfCompressedUnicodeRun=&iArrayOfMarks.MarkAt(aMarkIndexOfStartOfCompressedUnicodeRun+1);
-	assert(markForEndOfCompressedUnicodeRun->iMarkType==EMarkType_EndOfCompressedUnicodeRun);
-	const int bufferPositionOfStartOfCompressedUnicodeRun=markForStartOfCompressedUnicodeRun->iBufferPosition;
-	const int bufferPositionOfEndOfCompressedUnicodeRun=markForEndOfCompressedUnicodeRun->iBufferPosition;
-	const int numberOfBytesWhenCompressed=bufferPositionOfEndOfCompressedUnicodeRun-bufferPositionOfStartOfCompressedUnicodeRun;
-	iArrayOfMarks.RemoveMark(aMarkIndexOfStartOfCompressedUnicodeRun); // remove the EMarkType_StartOfCompressedUnicodeRun mark
-	iArrayOfMarks.RemoveMark(aMarkIndexOfStartOfCompressedUnicodeRun); // remove the EMarkType_EndOfCompressedUnicodeRun mark
-	markForStartOfCompressedUnicodeRun=NULL; // just in case we're tempted to use it again now that it's been removed
-	markForEndOfCompressedUnicodeRun=NULL; // just in case we're tempted to use it again now that it's been removed
-	const int numberOfBytesWhenUncompressed=runWhenUncompressed.NumberOfBytes();
-	const int numberOfExtraBytes=numberOfBytesWhenUncompressed-numberOfBytesWhenCompressed;
-
-	// insert a EMarkType_TwoByteAlignmentPoint mark if necessary
-	int startOfMarksToUpdate=aMarkIndexOfStartOfCompressedUnicodeRun;
-	if (numberOfBytesWhenCompressed==0)
-		{
-		assert(numberOfExtraBytes==0);
-		assert(numberOfBytesWhenUncompressed==0);
-		assert(aMarkIndexOfStartOfCompressedUnicodeRun==0);
-		}
-	else
-		{
-		assert(numberOfBytesWhenCompressed>0);
-		iArrayOfMarks.InsertMark(aMarkIndexOfStartOfCompressedUnicodeRun, bufferPositionOfStartOfCompressedUnicodeRun, EMarkType_TwoByteAlignmentPoint);
-		++startOfMarksToUpdate;
-		assert(startOfMarksToUpdate==aMarkIndexOfStartOfCompressedUnicodeRun+1);
-		}
-
-	// replace the compressed-Unicode bytes in the buffer with the uncompressed equivalent
-	if (numberOfExtraBytes==0)
-		{
-		assert(numberOfBytesWhenCompressed==0);
-		assert(numberOfBytesWhenUncompressed==0);
-		assert(aMarkIndexOfStartOfCompressedUnicodeRun==0);
-		}
-	else
-		{
-		assert(numberOfExtraBytes>0);
-
-		// make room in the buffer to insert the uncompressed Unicode (replacing the compressed-Unicode run)
-		const int numberOfBytesToMove=iNumberOfBytesUsed-bufferPositionOfEndOfCompressedUnicodeRun; // must be done before MakePlaceHolder is called as MakePlaceHolder will increment iNumberOfBytesUsed by numberOfExtraBytes
-		MakePlaceHolder(numberOfExtraBytes);
-		unsigned char* basePointer=iBuffer+bufferPositionOfEndOfCompressedUnicodeRun;
-		memmove(basePointer+numberOfExtraBytes, basePointer, numberOfBytesToMove); // memmove copes with overlapping source and target areas
-
-		// adjust all the subsequent mark's iBufferPositions
-		for (int i=iArrayOfMarks.Size()-1; i>=startOfMarksToUpdate; --i)
-			{
-			iArrayOfMarks.MarkAt(i).iBufferPosition+=numberOfExtraBytes;
-			}
-		}
-
-	// copy in the uncompressed Unicode and destroying the old copy
-	memcpy(iBuffer+bufferPositionOfStartOfCompressedUnicodeRun, runWhenUncompressed.Buffer(), numberOfBytesWhenUncompressed);
-	runWhenUncompressed.Destroy();
-	}
-
-ResourceDataStream::BinaryBuffer* ResourceDataStream::BinaryBuffer::New(int aNumberOfBytes, const unsigned char* aBuffer)
-	{ // static
-	BinaryBuffer* const binaryBuffer=(BinaryBuffer*)malloc((size_t)&((BinaryBuffer*)0)->iBuffer[aNumberOfBytes]);
-	assert(binaryBuffer!=NULL);
-	binaryBuffer->iNumberOfBytes=aNumberOfBytes;
-	assert(aNumberOfBytes>=0);
-	if (aNumberOfBytes>0)
-		{
-		assert(aBuffer!=NULL);
-		memcpy(binaryBuffer->iBuffer, aBuffer, aNumberOfBytes);
-		}
-	return binaryBuffer;
-	}
-
-void ResourceDataStream::BinaryBuffer::Destroy()
-	{
-	free(this);
-	}
-
+/*
+* Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#include <assert.h>
+#include <string.h>
+#include "ASTRING.H"
+#include <stdlib.h>
+#include <malloc.h>
+
+#include "RCBINSTR.H"
+#include "TOKENS.H"  
+#include "STACK.H"   
+#include "NUMVAL.H"  
+#include "DATATYPE.H"
+
+ 
+using namespace std ;
+
+extern long CurrentId;
+extern RCTypeArray gTypes;
+
+RCBinaryStream::RCBinaryStream()
+	{}
+
+RCBinaryStream::~RCBinaryStream()
+	{
+	if (iOs.is_open())
+		{
+		iOs.flush();
+		iOs.close();
+		}
+	}
+
+void RCBinaryStream::OpenForAppend(const String& FileName)
+	{
+	assert( !IsOpen());
+	
+	iOs.open( FileName.GetAssertedNonEmptyBuffer(), ios::in | ios::out | ios::binary | ios::ate); // ios::in to prevent overwriting
+	}
+
+int RCBinaryStream::IsOpen()
+	{
+	return(iOs.is_open());
+	}
+		
+RCBinaryStream & RCBinaryStream::operator<< ( char o)
+	{
+	Write((const unsigned char*)&o, 1);
+	return * this;
+	}
+
+RCBinaryStream & RCBinaryStream::operator<< ( char * o)
+	{
+	Write((const unsigned char*)o, strlen(o));
+	return * this;
+	}
+
+int RCBinaryStream::SizeOfCompressedInteger(unsigned int aInteger)
+	{ // static
+	assert((aInteger&~0x7fff)==0);
+	return (aInteger&~0x7f)? 2: 1;
+	}
+
+void RCBinaryStream::WriteCompressedInteger(unsigned int aInteger)
+	{
+	assert((aInteger&~0x7fff)==0);
+	if (aInteger&~0x7f)
+		{
+		*this << char((aInteger>>8)|0x80);
+		}
+	*this << char(aInteger&0xff);
+	}
+
+void RCBinaryStream::Write( const unsigned char * p, unsigned long count)
+	{
+	iOs.write( (const char*)p, count);
+#if defined(_DEBUG)
+	iOs.flush();
+#endif
+	}
+
+unsigned long RCBinaryStream::GetPosition()
+	{
+	return iOs.tellp();
+	}
+
+void RCBinaryStream::SetPosition(unsigned long aNewPosition)
+	{
+	assert(aNewPosition<=GetPosition());
+	iOs.seekp(aNewPosition, ios::beg);
+	}
+
+// ResourceDataStream - this code makes the apparently valid assumption that the decompressing of compressed Unicode (done by BAFL) will yield exactly the same length of string as what you started with before it was compressed (by RCOMP)
+
+ResourceDataStream::ResourceDataStream()
+	:iBuffer(NULL),
+	 iNumberOfBytesAllocated(0),
+	 iNumberOfBytesUsed(0),
+	 iContainsCompressedUnicode(false)
+	{
+	}
+
+ResourceDataStream::~ResourceDataStream()
+	{
+	delete [] iBuffer;
+	}
+
+void ResourceDataStream::StartOfBlockWithSizePrefix(DataType aDataTypeOfSizePrefix)
+	{
+	NumericValue* const sizeOfBlockWhenUncompressed=new NumericValue(aDataTypeOfSizePrefix);
+	assert(sizeOfBlockWhenUncompressed!=NULL);
+	iArrayOfMarks.AppendMark(iNumberOfBytesUsed, EMarkType_StartOfBlockWithSizePrefix, (unsigned int)sizeOfBlockWhenUncompressed);
+	}
+
+void ResourceDataStream::EndOfBlockWithSizePrefix()
+	{
+	iArrayOfMarks.AppendMark(iNumberOfBytesUsed, EMarkType_EndOfBlockWithSizePrefix);
+	}
+
+void ResourceDataStream::StartOfCompressedUnicodeRun(int aUncompressedUnicodeSizeInBytes, const unsigned char* aUncompressedUnicodeBuffer)
+	{
+	if (!iContainsCompressedUnicode)
+		{
+		// the first run *must* be a compressed Unicode run, so if it isn't, insert a zero-length one at the start
+		bool insertZeroLengthCompressedUnicodeRunAtStart=(iNumberOfBytesUsed>0);
+		if (!insertZeroLengthCompressedUnicodeRunAtStart)
+			{
+			const int numberOfMarks=iArrayOfMarks.Size();
+			for (int i=0; i<numberOfMarks; ++i)
+				{
+				const Mark& mark=iArrayOfMarks.MarkAt(i);
+				assert(mark.iBufferPosition==0);
+				assert(mark.iMarkType!=EMarkType_TwoByteAlignmentPoint); // it is only possible to have a EMarkType_TwoByteAlignmentPoint mark if iNumberOfBytesUsed>0, and we only execute this code if !insertZeroLengthCompressedUnicodeRunAtStart, i.e. if iNumberOfBytesUsed==0 (well, strictly speaking, if iNumberOfBytesUsed<=0)
+				if (mark.iMarkType==EMarkType_StartOfBlockWithSizePrefix)
+					{
+					insertZeroLengthCompressedUnicodeRunAtStart=true;
+					break;
+					}
+				}
+			}
+		if (insertZeroLengthCompressedUnicodeRunAtStart)
+			{
+			iArrayOfMarks.InsertMark(0, 0, EMarkType_StartOfCompressedUnicodeRun, (unsigned int)BinaryBuffer::New(0, NULL)); // mark the insertion point for the initial zero-length compressed-Unicode run
+			iArrayOfMarks.InsertMark(1, 0, EMarkType_EndOfCompressedUnicodeRun); // mark the insertion point for the subsquent run of "other stuff"
+			}
+		}
+	iArrayOfMarks.AppendMark(iNumberOfBytesUsed, EMarkType_StartOfCompressedUnicodeRun, (unsigned int)BinaryBuffer::New(aUncompressedUnicodeSizeInBytes, aUncompressedUnicodeBuffer));
+	iContainsCompressedUnicode=true;
+	}
+
+void ResourceDataStream::EndOfCompressedUnicodeRun()
+	{
+#if !defined(NDEBUG)
+	const Mark& markAtStartOfCompressedUnicodeRun=iArrayOfMarks.MarkAt(iArrayOfMarks.Size()-1);
+	assert(markAtStartOfCompressedUnicodeRun.iMarkType==EMarkType_StartOfCompressedUnicodeRun);
+	const int numberOfBytesWhenCompressed=iNumberOfBytesUsed-markAtStartOfCompressedUnicodeRun.iBufferPosition;
+	const BinaryBuffer& runWhenUncompressed=*(const BinaryBuffer*)markAtStartOfCompressedUnicodeRun.iOtherData;
+	assert(numberOfBytesWhenCompressed<runWhenUncompressed.NumberOfBytes());
+#endif
+	iArrayOfMarks.AppendMark(iNumberOfBytesUsed, EMarkType_EndOfCompressedUnicodeRun);
+	}
+
+void ResourceDataStream::TwoByteAlignmentPoint()
+	{
+	iArrayOfMarks.AppendMark(iNumberOfBytesUsed, EMarkType_TwoByteAlignmentPoint);
+	}
+
+void ResourceDataStream::EnquireStreamPositionWhenKnown(unsigned long& aStreamPosition)
+	{
+	iArrayOfMarks.AppendMark(iNumberOfBytesUsed, EMarkType_EnquireStreamPositionWhenKnown, (unsigned int)&aStreamPosition);
+	}
+
+void ResourceDataStream::StreamIn(const unsigned char* aBuffer, int aNumberOfBytes)
+	{
+	EnsureEnoughSpareBytes(aNumberOfBytes);
+	memcpy(iBuffer+iNumberOfBytesUsed, aBuffer, aNumberOfBytes);
+	iNumberOfBytesUsed+=aNumberOfBytes;
+	}
+
+void ResourceDataStream::MakePlaceHolder(int aNumberOfBytes)
+	{
+	EnsureEnoughSpareBytes(aNumberOfBytes);
+	memset(iBuffer+iNumberOfBytesUsed, 0xeb, aNumberOfBytes);
+	iNumberOfBytesUsed+=aNumberOfBytes;
+	}
+
+class SizePrefix : public StackItem
+	{
+public:
+	inline SizePrefix(int aUncompressedSizeOfResourceUpToStartOfBlock, NumericValue& aSizeOfBlockWhenUncompressed) :iUncompressedSizeOfResourceUpToStartOfBlock(aUncompressedSizeOfResourceUpToStartOfBlock), iSizeOfBlockWhenUncompressed(aSizeOfBlockWhenUncompressed) {}
+	inline int UncompressedSizeOfResourceUpToStartOfBlock() const {return iUncompressedSizeOfResourceUpToStartOfBlock;}
+	inline NumericValue& SizeOfBlockWhenUncompressed() const {return iSizeOfBlockWhenUncompressed;}
+private:
+	inline void operator=(const SizePrefix&);
+private:
+	int iUncompressedSizeOfResourceUpToStartOfBlock;
+	NumericValue& iSizeOfBlockWhenUncompressed;
+	};
+
+class SizePrefixStack : public Stack
+	{
+public:
+	inline SizePrefixStack() {}
+	inline void Push(int aUncompressedSizeOfResourceUpToStartOfBlock, NumericValue& aSizeOfBlockWhenUncompressed) {Stack::Push(new SizePrefix(aUncompressedSizeOfResourceUpToStartOfBlock, aSizeOfBlockWhenUncompressed));}
+	inline SizePrefix* Pop() {return (SizePrefix*)Stack::Pop();}
+	};
+
+bool ResourceDataStream::StreamOutReturningWhetherContainsCompressedUnicode(RCBinaryStream& aStream, int& aSizeWhenUncompressed)
+	{
+startOfFirstPass:
+	bool encounteredCompressedUnicode[3];
+	encounteredCompressedUnicode[0]=false;
+	encounteredCompressedUnicode[1]=false;
+	encounteredCompressedUnicode[2]=false;
+	{
+	// do a first pass (i) to calculate run-lengths of the "other-stuff" runs (i.e. the second, fourth, sixth, etc), (ii) to calculate which EMarkType_TwoByteAlignmentPoint marks require a padding byte, and (iii) to calculate the size-prefixes
+	// do a second pass to see if there are any compressed-Unicode runs that don't actually make the resource smaller (taking into consideration the preceding run-length byte(s) and any trailing run-length byte(s)) - if so, replace the EMarkType_StartOfCompressedUnicodeRun/EMarkType_EndOfCompressedUnicodeRun mark-pair with a single EMarkType_TwoByteAlignmentPoint mark and go right back to the start of the first pass
+	// do a third and final pass to actually write out the resource data to aStream
+	const int numberOfMarks=iArrayOfMarks.Size(); // caching this is done *after* the "startOfFirstPass" as ConvertCompressedRunToUncompressed (which is called just before "goto startOfFirstPass") changes the number of items in iArrayOfMarks
+	const unsigned int* lengthOfLastRun=NULL;
+	for (int pass=0; pass<3; ++pass)
+		{
+		const int numberOfBytesBeforeFirstMark=NumberOfBytesToNextMark(-1);
+		int runLength=numberOfBytesBeforeFirstMark;
+		int uncompressedSize=numberOfBytesBeforeFirstMark;
+		unsigned int* addressToWriteSizeOfCompressedIntegerTo=NULL; // used on the first pass
+		SizePrefixStack sizePrefixStack; // used on the first pass
+		int bufferIndex=0; // used on the third pass
+		if (pass==2)
+			{
+			const int numberOfBytesToFirstMark=NumberOfBytesToNextMark(-1);
+			assert(bufferIndex==0);
+			aStream.Write(reinterpret_cast<unsigned char*>(iBuffer), numberOfBytesToFirstMark);
+			bufferIndex+=numberOfBytesToFirstMark;
+			}
+		for (int i=0; i<numberOfMarks; ++i) // must iterate forwards so that lengthOfLastRun is correctly assigned (after the end of this loop) to point to the iOtherData (i.e. run-length) of the last EMarkType_EndOfCompressedUnicodeRun mark
+			{
+			Mark& mark=iArrayOfMarks.MarkAt(i);
+			switch (mark.iMarkType)
+				{
+			case EMarkType_StartOfBlockWithSizePrefix:
+				{
+				NumericValue* const sizeOfBlockWhenUncompressed=(NumericValue*)mark.iOtherData;
+				assert(sizeOfBlockWhenUncompressed!=NULL);
+				const int sizeOfSizePrefix=gTypes.GetSize(sizeOfBlockWhenUncompressed->NumericValueType());
+				runLength+=sizeOfSizePrefix;
+				uncompressedSize+=sizeOfSizePrefix;
+				if (pass==0)
+					{
+					sizePrefixStack.Push(uncompressedSize, *(NumericValue*)mark.iOtherData);
+					}
+				else if (pass==2)
+					{
+					aStream << *sizeOfBlockWhenUncompressed;
+					delete sizeOfBlockWhenUncompressed;
+					mark.iOtherData=(unsigned int)(NumericValue*)NULL;
+					}
+				}
+				break;
+			case EMarkType_EndOfBlockWithSizePrefix:
+				if (pass==0)
+					{
+					SizePrefix* const sizePrefix=sizePrefixStack.Pop();
+					assert(sizePrefix!=NULL);
+					sizePrefix->SizeOfBlockWhenUncompressed()=uncompressedSize-sizePrefix->UncompressedSizeOfResourceUpToStartOfBlock();
+					delete sizePrefix;
+					}
+				break;
+			case EMarkType_StartOfCompressedUnicodeRun:
+				{
+				assert(runLength>=0);
+				if (addressToWriteSizeOfCompressedIntegerTo!=NULL)
+					{
+					*addressToWriteSizeOfCompressedIntegerTo=runLength;
+					addressToWriteSizeOfCompressedIntegerTo=NULL;
+					}
+				runLength=0;
+				BinaryBuffer& runWhenUncompressed=*(BinaryBuffer*)mark.iOtherData;
+				const int numberOfBytesWhenUncompressed=runWhenUncompressed.NumberOfBytes();
+				const int numberOfBytesWhenUncompressedIncludingAnyPrecedingPaddingByte=numberOfBytesWhenUncompressed+((uncompressedSize%2!=0)? 1: 0);
+				assert((numberOfBytesWhenUncompressed>0) || !encounteredCompressedUnicode[pass]); // compressed-Unicode runs are of non-zero size apart from the compulsory initial compressed-Unicode run if the resource does not actually start with compressed Unicode
+				uncompressedSize+=numberOfBytesWhenUncompressedIncludingAnyPrecedingPaddingByte;
+				assert(i+1<numberOfMarks);
+				++i; // skip a loop iteration - we know that EMarkType_StartOfCompressedUnicodeRun marks are always followed by a EMarkType_EndOfCompressedUnicodeRun mark
+				Mark& nextMark=iArrayOfMarks.MarkAt(i);
+				assert(nextMark.iMarkType==EMarkType_EndOfCompressedUnicodeRun);
+				const int numberOfBytesWhenCompressed=nextMark.iBufferPosition-mark.iBufferPosition;
+				assert((numberOfBytesWhenCompressed>0) || !encounteredCompressedUnicode[pass]); // compressed-Unicode runs are of non-zero size apart from the compulsory initial compressed-Unicode run if the resource does not actually start with compressed Unicode
+				assert((numberOfBytesWhenCompressed<numberOfBytesWhenUncompressed) || ((!encounteredCompressedUnicode[pass]) && (numberOfBytesWhenCompressed==0) && (numberOfBytesWhenUncompressed==0)));
+				if (pass==0)
+					{
+					addressToWriteSizeOfCompressedIntegerTo=&nextMark.iOtherData; // iOtherData in "other-stuff" runs (i.e. the second run, the fourth run, the sixth run, etc) stores the combined size of the run taking into account any extra bytes caused by other marks, e.g. a padding byte caused by a ETwoByteAlignmentPoint
+					}
+				else if (pass==1)
+					{
+					const unsigned int* const lengthOfOtherStuffRun=&nextMark.iOtherData;
+					const bool isTheFirstCompressedUnicodeRun=!encounteredCompressedUnicode[pass];
+					const bool isTheLastCompressedUnicodeRun=(lengthOfLastRun==lengthOfOtherStuffRun);
+					if (isTheLastCompressedUnicodeRun || !isTheFirstCompressedUnicodeRun) // if this is the first compressed-Unicode run and there are others, then we can't get rid of it, hence this check
+						{
+						int numberOfBytesWhenCompressedIncludingRunLengthsEitherSide=RCBinaryStream::SizeOfCompressedInteger(numberOfBytesWhenCompressed)+numberOfBytesWhenCompressed;
+						if ((lengthOfLastRun!=lengthOfOtherStuffRun) || (*lengthOfOtherStuffRun>0))
+							{
+							numberOfBytesWhenCompressedIncludingRunLengthsEitherSide+=RCBinaryStream::SizeOfCompressedInteger(*lengthOfOtherStuffRun);
+							}
+						if (numberOfBytesWhenCompressedIncludingRunLengthsEitherSide>=numberOfBytesWhenUncompressedIncludingAnyPrecedingPaddingByte) // use ">=" rather than just ">" as we want to get rid of any compressed-Unicode runs that don't actually give any benefit, so that if possible we can remove the initial compressed-Unicode run (if it's of zero length and it's the only compressed-Unicode run, in which case it's unnecessary overhead)
+							{
+							if (isTheFirstCompressedUnicodeRun && isTheLastCompressedUnicodeRun) // if this is the only compressed-Unicode run...
+								{
+								iContainsCompressedUnicode=false;
+								}
+							ConvertCompressedRunToUncompressed(i-1);
+							goto startOfFirstPass; // go back to the start of the first pass again as we need to calculate all the fiddly stuff again, e.g. whether two-byte alignment points need padding bytes, etc.
+							}
+						}
+					}
+				else
+					{
+					assert(pass==2);
+					runWhenUncompressed.Destroy();
+					mark.iOtherData=(unsigned int)(BinaryBuffer*)NULL;
+					aStream.WriteCompressedInteger(numberOfBytesWhenCompressed);
+					aStream.Write(reinterpret_cast<unsigned char*>(iBuffer+bufferIndex), numberOfBytesWhenCompressed);
+					bufferIndex+=numberOfBytesWhenCompressed;
+					const unsigned int* const lengthOfOtherStuffRun=&nextMark.iOtherData;
+					if ((lengthOfLastRun!=lengthOfOtherStuffRun) || (*lengthOfOtherStuffRun>0))
+						{
+						aStream.WriteCompressedInteger(*lengthOfOtherStuffRun);
+						}
+					}
+				encounteredCompressedUnicode[pass]=true;
+				}
+				break;
+			case EMarkType_TwoByteAlignmentPoint:
+				{
+				const bool needPaddingByte=(uncompressedSize%2!=0);
+				if (needPaddingByte)
+					{
+					++runLength;
+					++uncompressedSize;
+					if (pass==2)
+						{
+						aStream << (unsigned char)(0xab);
+						}
+					}
+				if (pass==0)
+					{
+					mark.iOtherData=needPaddingByte;
+					}
+				else
+					{
+					assert((mark.iOtherData!=0)==needPaddingByte);
+					}
+				}
+				break;
+			case EMarkType_EnquireStreamPositionWhenKnown:
+				if (pass==2)
+					{
+					unsigned long& streamPosition=*(unsigned long*)mark.iOtherData;
+					streamPosition=aStream.GetPosition();
+					}
+				break;
+			default:
+				assert(0);
+				break;
+				}
+			const int numberOfBytesToNextMark=NumberOfBytesToNextMark(i);
+			if (pass==2)
+				{
+				aStream.Write(reinterpret_cast<unsigned char*>(iBuffer+bufferIndex), numberOfBytesToNextMark);
+				}
+			runLength+=numberOfBytesToNextMark;
+			uncompressedSize+=numberOfBytesToNextMark;
+			bufferIndex+=numberOfBytesToNextMark;
+			}
+		if (pass>0)
+			{
+			assert(aSizeWhenUncompressed==uncompressedSize);
+			}
+		else
+			{
+			aSizeWhenUncompressed=uncompressedSize;
+			lengthOfLastRun=addressToWriteSizeOfCompressedIntegerTo;
+			}
+		assert(runLength>=0);
+		if (addressToWriteSizeOfCompressedIntegerTo!=NULL)
+			{
+			*addressToWriteSizeOfCompressedIntegerTo=runLength;
+			addressToWriteSizeOfCompressedIntegerTo=NULL;
+			}
+		runLength=0;
+		}
+	}
+
+	assert(encounteredCompressedUnicode[0]==iContainsCompressedUnicode);
+	assert(encounteredCompressedUnicode[1]==iContainsCompressedUnicode);
+	assert(encounteredCompressedUnicode[2]==iContainsCompressedUnicode);
+	return encounteredCompressedUnicode[0];
+	}
+
+void ResourceDataStream::Dump(const char* aDumpFile) const
+	{
+	ofstream fileStream;
+	fileStream.open(aDumpFile, ios::out | ios::binary | ios::trunc);
+	fileStream.write((const char*)iBuffer, iNumberOfBytesUsed);
+	fileStream.flush();
+	fileStream.close();
+	}
+
+void ResourceDataStream::EnsureEnoughSpareBytes(int aNumberOfBytes)
+	{
+	const int numberOfBytesSpare=iNumberOfBytesAllocated-iNumberOfBytesUsed;
+	assert(numberOfBytesSpare>=0);
+	if (aNumberOfBytes>numberOfBytesSpare)
+		{
+		const int newNumberOfBytesAllocated=iNumberOfBytesAllocated+aNumberOfBytes+16; // 16 is just some extra bytes to stop the heap being thrashed too much
+		unsigned char* const newBuffer = new unsigned char[newNumberOfBytesAllocated];
+		if (iNumberOfBytesUsed>0)
+			{
+			memcpy(newBuffer, iBuffer, iNumberOfBytesUsed);
+			}
+		delete [] iBuffer;
+		iNumberOfBytesAllocated=newNumberOfBytesAllocated;
+		iBuffer=newBuffer;
+		}
+	}
+
+int ResourceDataStream::NumberOfBytesToNextMark(int aMarkIndex) const
+	{
+	assert(aMarkIndex>=-1);
+	assert(aMarkIndex<iArrayOfMarks.Size());
+	int numberOfBytesToNextMark=(aMarkIndex+1<iArrayOfMarks.Size())? iArrayOfMarks.MarkAt(aMarkIndex+1).iBufferPosition: iNumberOfBytesUsed;
+	if (aMarkIndex>=0)
+		{
+		numberOfBytesToNextMark-=iArrayOfMarks.MarkAt(aMarkIndex).iBufferPosition;
+		}
+	return numberOfBytesToNextMark;
+	}
+
+void ResourceDataStream::ConvertCompressedRunToUncompressed(int aMarkIndexOfStartOfCompressedUnicodeRun)
+	{
+	// remove the EMarkType_StartOfCompressedUnicodeRun/EMarkType_EndOfCompressedUnicodeRun mark-pair
+	Mark* markForStartOfCompressedUnicodeRun=&iArrayOfMarks.MarkAt(aMarkIndexOfStartOfCompressedUnicodeRun);
+	assert(markForStartOfCompressedUnicodeRun->iMarkType==EMarkType_StartOfCompressedUnicodeRun);
+	BinaryBuffer& runWhenUncompressed=*(BinaryBuffer*)markForStartOfCompressedUnicodeRun->iOtherData;
+	markForStartOfCompressedUnicodeRun->iOtherData=(unsigned int)(BinaryBuffer*)NULL;
+	Mark* markForEndOfCompressedUnicodeRun=&iArrayOfMarks.MarkAt(aMarkIndexOfStartOfCompressedUnicodeRun+1);
+	assert(markForEndOfCompressedUnicodeRun->iMarkType==EMarkType_EndOfCompressedUnicodeRun);
+	const int bufferPositionOfStartOfCompressedUnicodeRun=markForStartOfCompressedUnicodeRun->iBufferPosition;
+	const int bufferPositionOfEndOfCompressedUnicodeRun=markForEndOfCompressedUnicodeRun->iBufferPosition;
+	const int numberOfBytesWhenCompressed=bufferPositionOfEndOfCompressedUnicodeRun-bufferPositionOfStartOfCompressedUnicodeRun;
+	iArrayOfMarks.RemoveMark(aMarkIndexOfStartOfCompressedUnicodeRun); // remove the EMarkType_StartOfCompressedUnicodeRun mark
+	iArrayOfMarks.RemoveMark(aMarkIndexOfStartOfCompressedUnicodeRun); // remove the EMarkType_EndOfCompressedUnicodeRun mark
+	markForStartOfCompressedUnicodeRun=NULL; // just in case we're tempted to use it again now that it's been removed
+	markForEndOfCompressedUnicodeRun=NULL; // just in case we're tempted to use it again now that it's been removed
+	const int numberOfBytesWhenUncompressed=runWhenUncompressed.NumberOfBytes();
+	const int numberOfExtraBytes=numberOfBytesWhenUncompressed-numberOfBytesWhenCompressed;
+
+	// insert a EMarkType_TwoByteAlignmentPoint mark if necessary
+	int startOfMarksToUpdate=aMarkIndexOfStartOfCompressedUnicodeRun;
+	if (numberOfBytesWhenCompressed==0)
+		{
+		assert(numberOfExtraBytes==0);
+		assert(numberOfBytesWhenUncompressed==0);
+		assert(aMarkIndexOfStartOfCompressedUnicodeRun==0);
+		}
+	else
+		{
+		assert(numberOfBytesWhenCompressed>0);
+		iArrayOfMarks.InsertMark(aMarkIndexOfStartOfCompressedUnicodeRun, bufferPositionOfStartOfCompressedUnicodeRun, EMarkType_TwoByteAlignmentPoint);
+		++startOfMarksToUpdate;
+		assert(startOfMarksToUpdate==aMarkIndexOfStartOfCompressedUnicodeRun+1);
+		}
+
+	// replace the compressed-Unicode bytes in the buffer with the uncompressed equivalent
+	if (numberOfExtraBytes==0)
+		{
+		assert(numberOfBytesWhenCompressed==0);
+		assert(numberOfBytesWhenUncompressed==0);
+		assert(aMarkIndexOfStartOfCompressedUnicodeRun==0);
+		}
+	else
+		{
+		assert(numberOfExtraBytes>0);
+
+		// make room in the buffer to insert the uncompressed Unicode (replacing the compressed-Unicode run)
+		const int numberOfBytesToMove=iNumberOfBytesUsed-bufferPositionOfEndOfCompressedUnicodeRun; // must be done before MakePlaceHolder is called as MakePlaceHolder will increment iNumberOfBytesUsed by numberOfExtraBytes
+		MakePlaceHolder(numberOfExtraBytes);
+		unsigned char* basePointer=iBuffer+bufferPositionOfEndOfCompressedUnicodeRun;
+		memmove(basePointer+numberOfExtraBytes, basePointer, numberOfBytesToMove); // memmove copes with overlapping source and target areas
+
+		// adjust all the subsequent mark's iBufferPositions
+		for (int i=iArrayOfMarks.Size()-1; i>=startOfMarksToUpdate; --i)
+			{
+			iArrayOfMarks.MarkAt(i).iBufferPosition+=numberOfExtraBytes;
+			}
+		}
+
+	// copy in the uncompressed Unicode and destroying the old copy
+	memcpy(iBuffer+bufferPositionOfStartOfCompressedUnicodeRun, runWhenUncompressed.Buffer(), numberOfBytesWhenUncompressed);
+	runWhenUncompressed.Destroy();
+	}
+
+ResourceDataStream::BinaryBuffer* ResourceDataStream::BinaryBuffer::New(int aNumberOfBytes, const unsigned char* aBuffer)
+	{ // static
+		BinaryBuffer *dummy = reinterpret_cast<BinaryBuffer *>(0) ;
+		size_t offset = reinterpret_cast<size_t>(&(dummy->iBuffer[aNumberOfBytes])) ;
+	BinaryBuffer* const binaryBuffer=(BinaryBuffer*)malloc(offset);
+	assert(binaryBuffer!=NULL);
+	binaryBuffer->iNumberOfBytes=aNumberOfBytes;
+	assert(aNumberOfBytes>=0);
+	if (aNumberOfBytes>0)
+		{
+		assert(aBuffer!=NULL);
+		memcpy(binaryBuffer->iBuffer, aBuffer, aNumberOfBytes);
+		}
+	return binaryBuffer;
+	}
+
+void ResourceDataStream::BinaryBuffer::Destroy()
+	{
+	free(this);
+	}
+
--- a/bintools/rcomp/src/RCOMP.LEX	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/rcomp/src/RCOMP.LEX	Tue Jun 29 14:52:54 2010 +0800
@@ -1,317 +1,302 @@
-%option yylineno
-%{
-// Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies). 
-// All rights reserved.
-// This component and the accompanying materials are made available
-// under the terms of the License "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:
-// RCOMPL.INL
-// Generated from RCOMP.L
-
-
-#include <limits.h>
-#include <string.h>
-#include "main.h"
-#include "structst.h"
-#include "parser.h"
-#include "localise.h"
-
-#define YY_SKIP_YYWRAP 1
-#define YY_NEVER_INTERACTIVE 1
-int yywrap();
-void yyerror(const char* string, ...);
-
-// Redefine YY_INPUT so we can parse binary data.
-#undef YY_INPUT
-#define YY_INPUT(buf, result, max_size) (result = new_yy_input(buf, max_size))
-
-int new_yy_input(char *buf, int max_size)
-{
-   int result;
-   result = fread(buf, 1, max_size, yyin);
-   if (result == 0)
-      return YY_NULL;
-   
-   // check for utf8 (BOM) header in buf
-   for (int i = 0; i < result-3; i++)
-   {
-      if (buf[i] == 0xffffffef && buf[i+1] == 0xffffffbb && buf[i+2] == 0xffffffbf)
-      {
-		buf[i] = ' ';
-		buf[i+1] = ' ';
-		buf[i+2] = ' ';
-      }
-   }
-   return result;
-}
-
-#include "rcomp.hpp"
-#include "fileline.h"
-
-#define VALUE_LEN   (1024*8)	// must match sizeof(YYSTYPE.Value)
-char buf[VALUE_LEN];
-char * pCh;
-#define CHECK_APPEND(x)	\
-    if (pCh-buf==VALUE_LEN-1) { yyerror("string too long - %c ignored", (x)); } else {*pCh++ = (x); }
-
-int isCharLiteral;
-
-extern String		InputBaseName;
-extern FileLineManager* pFileLineHandler;
-extern int*		pCurrentLineNumber;
-char RealLineNumber[200];
-//
-// Disable MSVC warnings
-//
-#ifdef __VC32__
-#if 0
-..\src\RCOMP.L(95) : warning C4127: conditional expression is constant
-..\src\RCOMP.L(114) : warning C4244: 'initializing' : conversion from 'const int' to 'YY_CHAR', possible loss of data
-..\src\RCOMP.L(119) : warning C4244: '=' : conversion from 'const int' to 'YY_CHAR', possible loss of data
-..\src\RCOMP.L(130) : warning C4102: 'find_rule' : unreferenced label
-..\src\RCOMP.L(513) : warning C4244: 'initializing' : conversion from 'int' to 'YY_CHAR', possible loss of data
-..\src\RCOMP.L(518) : warning C4244: '=' : conversion from 'const int' to 'YY_CHAR', possible loss of data
-..\src\RCOMP.L(548) : warning C4244: '=' : conversion from 'const int' to 'YY_CHAR', possible loss of data
-..\src\RCOMP.L(63) : warning C4505: 'yyunput' : unreferenced local function has been removed
-\epoc32\BUILD\generatedcpp\rcomp\rcompl.cpp(243) : warning C4505: 'yy_flex_realloc' : unreferenced local function has been removed
-#endif
-
-#pragma warning( disable : 4100 )
-#pragma warning( disable : 4102 )
-#pragma warning( disable : 4127 )
-#pragma warning( disable : 4244 )
-#pragma warning( disable : 4245 )
-#pragma warning( disable : 4505 )
-#endif //__VC32__
-
-#include "errorhan.h"
-
-#define REGISTER_LINE	ErrorHandler::Register(pFileLineHandler->GetCurrentFile(), pFileLineHandler->GetErrorLine(* pCurrentLineNumber))
-
-
-%}
-    
-Digit [0-9]
-Lower [a-z]
-Upper [A-Z]
-Letter {Lower}|{Upper}
-Alphanumeric {Letter}|{Digit}
-LetterOrUnderscore {Letter}|_
-AlphanumUscore {Alphanumeric}|_
-HexChar [A-Fa-f0-9]
-ExpChar [eE]
-FileNameChar [^"]
-
-%s string_rules
-	/* Rule set for string literals.			        */
-	/* n.b. Exclusive rule sets i.e. %x are available in MKS only	*/
-	/* so they are not used here; hence all the <INITIAL>'s.        */
-				
-%s file_line_rules
-	/* Rule set for file_line_directive.*/
-
-%s cpp_comment
-	/* C++ comment to end of line */
-
-%s c_comment
-	/* C comment */
-
-%s comment_tag
-	/* Doxygen-style comment tag */
-
-%%
-
-
-	/* Translations section */
-	/* ==================== */
-
-	/*******************************************/
-	/* Main keywords                           */
-	/*******************************************/
-<INITIAL>STRUCT				return L_STRUCT;
-<INITIAL>RESOURCE				return L_RESOURCE;
-<INITIAL>NAME					return L_NAME;
-<INITIAL>CHARACTER_SET			return L_CHARACTER_SET;
-<INITIAL>OFFSET				return L_OFFSET;
-<INITIAL>SYSTEM				return L_SYSTEM;
-<INITIAL>GLOBAL				return L_GLOBAL;
-<INITIAL>LOCAL				return L_LOCAL;
-<INITIAL>ENUM					return L_ENUM;
-<INITIAL>enum					return L_ENUM;
-<INITIAL>UID2					return L_UID_TWO;
-<INITIAL>UID3					return L_UID_THREE;
-<INITIAL>rls_string		return L_RLS_STRING;
-<INITIAL>rls_string8		return L_RLS_STRING8;
-<INITIAL>rls_double		return L_RLS_DOUBLE;
-<INITIAL>rls_byte		return L_RLS_BYTE;
-<INITIAL>rls_word		return L_RLS_WORD;
-<INITIAL>rls_long		return L_RLS_LONG;
-<INITIAL>multi		return L_MULTI;
-
-	/*******************************************/
-	/* Types                                   */
-	/*******************************************/
-<INITIAL>BUF					return L_BUF;
-<INITIAL>BUF8					return L_BUF8;
-<INITIAL>BUF16				return L_BUF16;
-<INITIAL>WORD					return L_WORD;
-<INITIAL>BYTE					return L_BYTE;
-<INITIAL>LONG					return L_LONG;
-<INITIAL>DOUBLE				return L_DOUBLE;
-<INITIAL>TEXT					return L_TEXT;
-<INITIAL>LTEXT				return L_LTEXT;
-<INITIAL>TEXT8				return L_TEXT8;
-<INITIAL>LTEXT8				return L_LTEXT8;
-<INITIAL>TEXT16				return L_TEXT16;
-<INITIAL>LTEXT16				return L_LTEXT16;
-<INITIAL>LINK					return L_LINK;
-<INITIAL>LLINK				return L_LLINK;
-<INITIAL>SRLINK				return L_SRLINK;
-
-
-	/*******************************************/
-	/* Others                                  */
-	/*******************************************/
-<INITIAL>LEN					return L_LEN;
-
-
-	/*******************************************/
-	/* String & character literals             */
-	/*******************************************/
-<INITIAL>\"					{ BEGIN(string_rules); pCh = buf; isCharLiteral=0; }
-<INITIAL>'					{ BEGIN(string_rules); pCh = buf; isCharLiteral=1; }
-
-	/* Escaped single- and double-quotes.*/
-<string_rules>\\\"		{ CHECK_APPEND('"'); }
-<string_rules>\\'		{ CHECK_APPEND('\''); };
-
-	/* Convert escaped character into corresponding actual character e.g. \t to tab. */
-<string_rules>\\[rbfntv]	{ CHECK_APPEND( * ( strchr("\rr\bb\ff\nn\tt\vv\aa", yytext[1])-1));}
-
-	/* Escaped backslash */
-<string_rules>\\\\			{ CHECK_APPEND('\\'); }
-
-<string_rules>\\\n				/* Escaped newline ignored*/ ;
-
-	/* End of line before terminating double-quotes.*/
-<string_rules>(\r)?\n		{ yyerror( isCharLiteral?"Unterminated character literal":"Unterminated string"); BEGIN 0; }
-
-	/* End of string reached.*/
-<string_rules>\"	{ 
-    if (!isCharLiteral) 
-	    {
-	    *pCh = '\0'; BEGIN(0); strcpy( yylval.Value, buf); 
-		return L_STRING_LITERAL; 
-	    }
-    CHECK_APPEND(*yytext);
-    }
-
-<string_rules>'		{ 
-    if (isCharLiteral) 
-	    {
-	    *pCh = '\0'; BEGIN(0); strcpy( yylval.Value, buf); return L_CHAR_LITERAL;
-	    }
-    CHECK_APPEND(*yytext);
-    }
-
-	/* Anything other than \n is stored.*/
-<string_rules>.			{ CHECK_APPEND(*yytext); }
-
-
-	/*******************************************/
-	/* Labels                                  */
-	/*******************************************/
-<INITIAL>{LetterOrUnderscore}{AlphanumUscore}*    {	
-    BEGIN(0);
-    strcpy( yylval.Value, yytext);
-    return L_LABEL;
-    }
-
-	/*******************************************/
-	/* Numbers                                 */
-	/*******************************************/
-<INITIAL>{Digit}+					{	strcpy( yylval.Value, yytext); return L_NUM_NATURAL; }
-<INITIAL>0x{HexChar}+					{	strcpy( yylval.Value, yytext); return L_NUM_NATURAL; }
-<INITIAL>{Digit}+\.{Digit}+{ExpChar}{Digit}+		{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
-<INITIAL>-{Digit}+\.{Digit}+{ExpChar}{Digit}+		{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
-<INITIAL>{Digit}+\.{Digit}+				{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
-<INITIAL>-{Digit}+\.{Digit}+				{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
-<INITIAL>{Digit}+{ExpChar}{Digit}+			{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
-<INITIAL>-{Digit}+{ExpChar}{Digit}+			{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
-
-	/*******************************************/
-	/* file_line_directive                     */
-	/*******************************************/
-<INITIAL>[#][ ]{Digit}+[ ]\"					{	BEGIN(file_line_rules); strcpy( RealLineNumber, yytext+2); }
-
-<file_line_rules>\"(\r)?$					{	BEGIN(0); // # <line> "" means start of base file.
-											pFileLineHandler->SetBase( InputBaseName, * pCurrentLineNumber);
-										}
-										
-<file_line_rules>{FileNameChar}*\"(\r)?$		{	BEGIN(0); // # <line> <filename> means @ line <line> of named base file.
-											pFileLineHandler->PostInclude( yytext, RealLineNumber, * pCurrentLineNumber);
-										}
-
-<file_line_rules>{FileNameChar}*\"[ ]1([ ]3){0,1}(\r)?$	{
-											BEGIN(0); // # <line> <filename> 1 means start of an included file.
-											pFileLineHandler->SetInclude( yytext, * pCurrentLineNumber);
-										}
-
-<file_line_rules>{FileNameChar}*\"[ ]2([ ]3){0,1}(\r)?$	{
-											BEGIN(0); // # <line> <filename> 2 means end of an included file and now at <line> in <filename>.
-											pFileLineHandler->PostInclude( yytext, RealLineNumber, * pCurrentLineNumber);
-										}
-
-
-
-	/*******************************************/
-	/* White space                             */
-	/*******************************************/
-<INITIAL,file_line_rules>[ \t]			; // skipped
-<INITIAL>[\n\r]							; // skipped
-<file_line_rules>[\n\r]					; // skipped
-<INITIAL,file_line_rules>"//"			{ BEGIN(cpp_comment); }
-<cpp_comment>[\n\r]						{ BEGIN(0); }
-<cpp_comment>.			    ;			// skipped
-<INITIAL,file_line_rules>"/*"/[^&\n]	{ BEGIN(c_comment); }
-<INITIAL,file_line_rules>"/*"[\n\r]		{ BEGIN(c_comment); }
-<c_comment>"*/"							{ BEGIN(0); }
-<c_comment>[\n\r]						; // skipped
-<c_comment>.							; // skipped
-
-	/*******************************************/
-	/* Comment tags                            */
-	/*******************************************/
-
-<INITIAL,file_line_rules>[ \t]*"/*&"	{ 
-										BEGIN(comment_tag);
-										pGL->SetStart(*(pFileLineHandler->GetCurrentFile()), pFileLineHandler->GetErrorLine(* pCurrentLineNumber));
-										return L_TAG_START; 
-										}	// any comment beginning with a slash followed by a star followed by an ampersand
-<comment_tag>"*/"						{ 
-										BEGIN(0); 
-										return L_TAG_END; 
-										}
-<comment_tag>"@"[^* \t\r\n]+			{ strcpy( yylval.Value, yytext);	return L_TAG_COMMAND; }
-<comment_tag>[^*@ \t\n\r][^ *\t\r\n]*	{ strcpy( yylval.Value, yytext);	return L_TAG_WORD; }
-<comment_tag>[\n\r]						{ strcpy( yylval.Value, "\n");		return L_TAG_NEW_LINE; }
-<comment_tag>[* \t]						;
-
-	/*******************************************/
-	/* Special single characters               */
-	/*******************************************/
-<INITIAL>[.{};=\[\],()+\-*/|<>]		return * yytext;
-
-
-	/*******************************************/
-	/* Everything else cannot be recognised    */
-	/*******************************************/
-.                       { yyerror("*** Unknown character '%c' (value 0x%x) ", *yytext, *yytext);}
+%option yylineno
+%{
+// Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies). 
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of the License "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:
+// RCOMPL.INL
+// Generated from RCOMP.L
+
+
+#include <limits.h>
+#include <string.h>
+#include "main.h"
+#include "STRUCTST.H"
+#include "Parser.h"
+#include "localise.h"
+
+#define YY_SKIP_YYWRAP 1
+#define YY_NEVER_INTERACTIVE 1
+int yywrap();
+void yyerror(const char* string, ...);
+
+// Redefine YY_INPUT so we can parse binary data.
+#undef YY_INPUT
+#define YY_INPUT(buf, result, max_size) (result = new_yy_input(buf, max_size))
+
+int new_yy_input(char *buf, int max_size)
+{
+  int result;
+   if(yyin != NULL) {
+		result = fread(buf, 1, max_size, yyin);
+	}
+   else if((pG->StdInBuffer != NULL) && (pG->StdInBufLength > 0)) {
+		int left = pG->StdInBufLength - pG->StdInfBufPos ;
+		if(left == 0)
+			return YY_NULL ;
+		result = (max_size < left) ? max_size : left ; 
+		memcpy(buf,&(pG->StdInBuffer[pG->StdInfBufPos]),result); 
+		pG->StdInfBufPos += result ;
+   }
+
+   if (result == 0)
+      return YY_NULL;
+   
+   const unsigned char BOM[] = {0xef , 0xbb, 0xbf, 0x0 };
+   // check for utf8 (BOM) header in buf
+   for (int i = 0; i < result-3; i++) {
+      if (0 == memcmp(&buf[i],BOM,3)) {
+		memset(&buf[i],0x20,3);
+      }
+   }
+   return result;
+}
+
+#include "rcomp.hpp"
+#include "FILELINE.H"
+
+#define VALUE_LEN   (1024*8)	// must match sizeof(YYSTYPE.Value)
+char buf[VALUE_LEN];
+char * pCh;
+#define CHECK_APPEND(x)	\
+    if (pCh-buf==VALUE_LEN-1) { yyerror("string too long - %c ignored", (x)); } else {*pCh++ = (x); }
+
+int isCharLiteral;
+
+extern String		InputBaseName;
+extern FileLineManager* pFileLineHandler;
+extern int*		pCurrentLineNumber;
+char RealLineNumber[200];
+
+#include "ERRORHAN.H"
+
+#define REGISTER_LINE	ErrorHandler::Register(pFileLineHandler->GetCurrentFile(), pFileLineHandler->GetErrorLine(* pCurrentLineNumber))
+
+
+%}
+    
+Digit [0-9]
+Lower [a-z]
+Upper [A-Z]
+Letter {Lower}|{Upper}
+Alphanumeric {Letter}|{Digit}
+LetterOrUnderscore {Letter}|_
+AlphanumUscore {Alphanumeric}|_
+HexChar [A-Fa-f0-9]
+ExpChar [eE]
+FileNameChar [^"]
+
+%s string_rules
+	/* Rule set for string literals.			        */
+	/* n.b. Exclusive rule sets i.e. %x are available in MKS only	*/
+	/* so they are not used here; hence all the <INITIAL>'s.        */
+				
+%s file_line_rules
+	/* Rule set for file_line_directive.*/
+
+%s cpp_comment
+	/* C++ comment to end of line */
+
+%s c_comment
+	/* C comment */
+
+%s comment_tag
+	/* Doxygen-style comment tag */
+
+%%
+
+
+	/* Translations section */
+	/* ==================== */
+
+	/*******************************************/
+	/* Main keywords                           */
+	/*******************************************/
+<INITIAL>STRUCT				return L_STRUCT;
+<INITIAL>RESOURCE				return L_RESOURCE;
+<INITIAL>NAME					return L_NAME;
+<INITIAL>CHARACTER_SET			return L_CHARACTER_SET;
+<INITIAL>OFFSET				return L_OFFSET;
+<INITIAL>SYSTEM				return L_SYSTEM;
+<INITIAL>GLOBAL				return L_GLOBAL;
+<INITIAL>LOCAL				return L_LOCAL;
+<INITIAL>ENUM					return L_ENUM;
+<INITIAL>enum					return L_ENUM;
+<INITIAL>UID2					return L_UID_TWO;
+<INITIAL>UID3					return L_UID_THREE;
+<INITIAL>rls_string		return L_RLS_STRING;
+<INITIAL>rls_string8		return L_RLS_STRING8;
+<INITIAL>rls_double		return L_RLS_DOUBLE;
+<INITIAL>rls_byte		return L_RLS_BYTE;
+<INITIAL>rls_word		return L_RLS_WORD;
+<INITIAL>rls_long		return L_RLS_LONG;
+<INITIAL>multi		return L_MULTI;
+
+	/*******************************************/
+	/* Types                                   */
+	/*******************************************/
+<INITIAL>BUF					return L_BUF;
+<INITIAL>BUF8					return L_BUF8;
+<INITIAL>BUF16				return L_BUF16;
+<INITIAL>WORD					return L_WORD;
+<INITIAL>BYTE					return L_BYTE;
+<INITIAL>LONG					return L_LONG;
+<INITIAL>DOUBLE				return L_DOUBLE;
+<INITIAL>TEXT					return L_TEXT;
+<INITIAL>LTEXT				return L_LTEXT;
+<INITIAL>TEXT8				return L_TEXT8;
+<INITIAL>LTEXT8				return L_LTEXT8;
+<INITIAL>TEXT16				return L_TEXT16;
+<INITIAL>LTEXT16				return L_LTEXT16;
+<INITIAL>LINK					return L_LINK;
+<INITIAL>LLINK				return L_LLINK;
+<INITIAL>SRLINK				return L_SRLINK;
+
+
+	/*******************************************/
+	/* Others                                  */
+	/*******************************************/
+<INITIAL>LEN					return L_LEN;
+
+
+	/*******************************************/
+	/* String & character literals             */
+	/*******************************************/
+<INITIAL>\"					{ BEGIN(string_rules); pCh = buf; isCharLiteral=0; }
+<INITIAL>'					{ BEGIN(string_rules); pCh = buf; isCharLiteral=1; }
+
+	/* Escaped single- and double-quotes.*/
+<string_rules>\\\"		{ CHECK_APPEND('"'); }
+<string_rules>\\'		{ CHECK_APPEND('\''); };
+
+	/* Convert escaped character into corresponding actual character e.g. \t to tab. */
+<string_rules>\\[rbfntv]	{ CHECK_APPEND( * ( strchr("\rr\bb\ff\nn\tt\vv\aa", yytext[1])-1));}
+
+	/* Escaped backslash */
+<string_rules>\\\\			{ CHECK_APPEND('\\'); }
+
+<string_rules>\\\n				/* Escaped newline ignored*/ ;
+
+	/* End of line before terminating double-quotes.*/
+<string_rules>(\r)?\n		{ yyerror( isCharLiteral?"Unterminated character literal":"Unterminated string"); BEGIN 0; }
+
+	/* End of string reached.*/
+<string_rules>\"	{ 
+    if (!isCharLiteral) 
+	    {
+	    *pCh = '\0'; BEGIN(0); strcpy( yylval.Value, buf); 
+		return L_STRING_LITERAL; 
+	    }
+    CHECK_APPEND(*yytext);
+    }
+
+<string_rules>'		{ 
+    if (isCharLiteral) 
+	    {
+	    *pCh = '\0'; BEGIN(0); strcpy( yylval.Value, buf); return L_CHAR_LITERAL;
+	    }
+    CHECK_APPEND(*yytext);
+    }
+
+	/* Anything other than \n is stored.*/
+<string_rules>.			{ CHECK_APPEND(*yytext); }
+
+
+	/*******************************************/
+	/* Labels                                  */
+	/*******************************************/
+<INITIAL>{LetterOrUnderscore}{AlphanumUscore}*    {	
+    BEGIN(0);
+    strcpy( yylval.Value, yytext);
+    return L_LABEL;
+    }
+
+	/*******************************************/
+	/* Numbers                                 */
+	/*******************************************/
+<INITIAL>{Digit}+					{	strcpy( yylval.Value, yytext); return L_NUM_NATURAL; }
+<INITIAL>0x{HexChar}+					{	strcpy( yylval.Value, yytext); return L_NUM_NATURAL; }
+<INITIAL>{Digit}+\.{Digit}+{ExpChar}{Digit}+		{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
+<INITIAL>-{Digit}+\.{Digit}+{ExpChar}{Digit}+		{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
+<INITIAL>{Digit}+\.{Digit}+				{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
+<INITIAL>-{Digit}+\.{Digit}+				{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
+<INITIAL>{Digit}+{ExpChar}{Digit}+			{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
+<INITIAL>-{Digit}+{ExpChar}{Digit}+			{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
+
+	/*******************************************/
+	/* file_line_directive                     */
+	/*******************************************/
+<INITIAL>[#][ ]{Digit}+[ ]\"					{	BEGIN(file_line_rules); strcpy( RealLineNumber, yytext+2); }
+
+<file_line_rules>\"(\r)?$					{	BEGIN(0); // # <line> "" means start of base file.
+											pFileLineHandler->SetBase( InputBaseName, * pCurrentLineNumber);
+										}
+										
+<file_line_rules>{FileNameChar}*\"(\r)?$		{	BEGIN(0); // # <line> <filename> means @ line <line> of named base file.
+											pFileLineHandler->PostInclude( yytext, RealLineNumber, * pCurrentLineNumber);
+										}
+
+<file_line_rules>{FileNameChar}*\"[ ]1([ ]3){0,1}(\r)?$	{
+											BEGIN(0); // # <line> <filename> 1 means start of an included file.
+											pFileLineHandler->SetInclude( yytext, * pCurrentLineNumber);
+										}
+
+<file_line_rules>{FileNameChar}*\"[ ]2([ ]3){0,1}(\r)?$	{
+											BEGIN(0); // # <line> <filename> 2 means end of an included file and now at <line> in <filename>.
+											pFileLineHandler->PostInclude( yytext, RealLineNumber, * pCurrentLineNumber);
+										}
+
+
+
+	/*******************************************/
+	/* White space                             */
+	/*******************************************/
+<INITIAL,file_line_rules>[ \t]			; // skipped
+<INITIAL>[\n\r]							; // skipped
+<file_line_rules>[\n\r]					; // skipped
+<INITIAL,file_line_rules>"//"			{ BEGIN(cpp_comment); }
+<cpp_comment>[\n\r]						{ BEGIN(0); }
+<cpp_comment>.			    ;			// skipped
+<INITIAL,file_line_rules>"/*"/[^&\n]	{ BEGIN(c_comment); }
+<INITIAL,file_line_rules>"/*"[\n\r]		{ BEGIN(c_comment); }
+<c_comment>"*/"							{ BEGIN(0); }
+<c_comment>[\n\r]						; // skipped
+<c_comment>.							; // skipped
+
+	/*******************************************/
+	/* Comment tags                            */
+	/*******************************************/
+
+<INITIAL,file_line_rules>[ \t]*"/*&"	{ 
+										BEGIN(comment_tag);
+										pGL->SetStart(*(pFileLineHandler->GetCurrentFile()), pFileLineHandler->GetErrorLine(* pCurrentLineNumber));
+										return L_TAG_START; 
+										}	// any comment beginning with a slash followed by a star followed by an ampersand
+<comment_tag>"*/"						{ 
+										BEGIN(0); 
+										return L_TAG_END; 
+										}
+<comment_tag>"@"[^* \t\r\n]+			{ strcpy( yylval.Value, yytext);	return L_TAG_COMMAND; }
+<comment_tag>[^*@ \t\n\r][^ *\t\r\n]*	{ strcpy( yylval.Value, yytext);	return L_TAG_WORD; }
+<comment_tag>[\n\r]						{ strcpy( yylval.Value, "\n");		return L_TAG_NEW_LINE; }
+<comment_tag>[* \t]						;
+
+	/*******************************************/
+	/* Special single characters               */
+	/*******************************************/
+<INITIAL>[.{};=\[\],()+\-*/|<>]		return * yytext;
+
+
+	/*******************************************/
+	/* Everything else cannot be recognised    */
+	/*******************************************/
+.                       { yyerror("*** Unknown character '%c' (value 0x%x) ", *yytext, *yytext);}
--- a/bintools/rcomp/src/RCOMP.YACC	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/rcomp/src/RCOMP.YACC	Tue Jun 29 14:52:54 2010 +0800
@@ -1,1295 +1,1297 @@
-%{
-// Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies). 
-// All rights reserved.
-// This component and the accompanying materials are made available
-// under the terms of the License "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:
-// 
-// RCOMP.CPP
-// Generated from RCOMP.Y
-
-#include <assert.h>
-#include <ctype.h>
-#include <string.h>
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-#include <fstream>
-#include <iostream>
-using namespace std;
-using std::cout;
-using std::endl;
-#else //!__MSVCDOTNET__
-#include <fstream.h>
-#endif //__MSVCDOTNET__
-
-#ifdef __VC32__
-#pragma warning( disable : 4065 ) // C4065: switch statement contains 'default' but no 'case' labels
-#pragma warning( disable : 4102 ) // C4102: 'yyerrlab1' : unreferenced label
-#pragma warning( disable : 4127 ) // C4127: conditional expression is constant
-#pragma warning( disable : 4244 ) // C4244: '=' : conversion from 'int' to 'short', possible loss of data
-#endif //__VC32__
-
-#include "resource.h"
-#include "parser.h"
-
-int yylex();
-void yyerror(const char* string, ...);
-int yywrap();
-#define YYDEBUG 1
-extern int yylineno;
-
-#include "rcomp.hpp"
-#include "datatype.h"
-#include "mem.h"
-#include "rcbinstr.h"
-#include "rcscan.h"
-#include "errorhan.h"
-#include "fileacc.h"
-#include "version.h"
-#include "ctable.h"
-#include "localise.h"
-#include "main.h"
-
-#if defined(__VC32__) && !defined(_DEBUG)
-#pragma warning( disable : 4702 )	// unreachable code
-#pragma warning( disable : 4102 )	// 'yyerrlabel' : unreferenced label
-#pragma warning( disable : 4244 )	// '=' : conversion from 'int' to 'short', possible loss of data
-#endif
-
-
-
-String::CharacterSet CharacterSetID( const String & character_set_name );
-void asUTF8(char* aUtf8, int aUnicode);
-void SetIdFromName( const String & NameStatementValue);
-void CheckStructUsage();
-
-unsigned short & d = MemCheckControl::iLogMemory;
-
-StructHeader *		pSH;
-
-StructHeaderArray * 	pSHA;	// Used in resource struct handling functions.
-ResourceHeader *	pResourceHeader;
-ResourceItemArray *	pCurrentRIA;
-StringArray * pUsedLabelsArray = new StringArray();
-int			verbose;
-String::CharacterSet	SourceCharacterSet = String::CP1252;
-String::CharacterSet	TargetCharacterSet = String::CP1252;
-unsigned short		logmemorysetting;
-int *			pCurrentLineNumber;
-FileLineManager *	pFileLineHandler;
-NameIdMap *		pResourceNameIds;
-long			CurrentEnumValue;
-String			CurrentEnumName;
-char			TempStr[300];
-rcscan * pScan;
-
-int CurrentIdStep=1;
-long CurrentId=0;
-int FormatIdAsHex=0;	// defaults to decimal, changes in SetIdFromName
-
-unsigned long Uid2=0;
-unsigned long Uid3=0;
-
-
-
-const String	Divider("*******************************************");
-
-#define REGISTER_LINE	ErrorHandler::Register(pFileLineHandler->GetCurrentFile(), pFileLineHandler->GetErrorLine(* pCurrentLineNumber))
-
-// Convert a string containing a character literal in aQuoted
-// into a value suitable for LCHAR_LITERAL
-void SetCharacterLiteral(char* aOut, const String& aQuoted)
-	{
-	    UTF16 first;
-	    int length=1;
-	    if (aQuoted.Length() < 1 ) 
-	               { 
-                        REGISTER_LINE;
-                        ErrorHandler::OutputErrorLine("Warning: Empty Character literal");
-                       }
-	    if (aQuoted.Length() > 1 ) 
-	 	       {
-                        REGISTER_LINE;
-                        ErrorHandler::OutputErrorLine("Error: String Literal length greater than 1");
-			exit(1);
-                       }
-	    if (aQuoted.Export(&first, length, SourceCharacterSet)==0)
-			{
-			REGISTER_LINE;
-			ErrorHandler::OutputErrorLine("Warning: Ignoring trailing characters in character literal");
-			}
-	    sprintf(aOut, "%d", first);
-	}
-
-%}
-
-%union {
-	char				Value[1024*8];
-	TValueMaybeRls			ValueMaybeRls;
-	unsigned long 			Id;
-	StructItem *			pStructItem;
-	SimpleStructItem *		pSimpleStructItem;
-	ArrayStructItem *   	pArrayStructItem;
-	StructArrayStructItem *	pStructArrayStructItem;
-	StringArray *			pStringArray;
-	long					NumInitialiser;
-	TRlsQualifiers		RlsQualifiers;
-	TRlsType			RlsType;
-}
-
-%token <Id> L_STRUCT L_RESOURCE L_NAME L_OFFSET L_SYSTEM L_GLOBAL L_LOCAL L_CHARACTER_SET 
-%token <Id> L_BUF L_WORD L_BYTE L_LONG L_DOUBLE L_TEXT L_LTEXT L_LINK L_LLINK L_SRLINK
-%token <Id> L_BUF8 L_TEXT8 L_LTEXT8 L_BUF16 L_TEXT16 L_LTEXT16 L_UID_TWO L_UID_THREE
-%token <Id> L_RLS_STRING L_RLS_STRING8 L_RLS_DOUBLE
-%token <Id> L_RLS_BYTE L_RLS_WORD L_RLS_LONG
-%token <Id> L_MULTI
-%token <Id> L_TAG_START L_TAG_END 
-%token <Value> L_TAG_COMMAND L_TAG_WORD L_TAG_NEW_LINE
-%token <Value> L_LABEL L_NUM_NATURAL L_NUM_FLOAT L_NATURAL_EXPR L_ENUM
-%token <Value> L_LEN
-%token <Value> L_CHAR_LITERAL L_STRING_LITERAL
-
-%type <Id>			data_type len_declaration
-%type <pStructItem>		struct_item array_struct_item simple_struct_item
-%type <pSimpleStructItem>	simple_struct_item_start
-%type <pStructItem>		struct_type_struct_item  struct_array_struct_item
-%type <pArrayStructItem>	array_struct_item_start array_struct_item_base
-%type <pStructArrayStructItem>	struct_array_struct_item_base
-%type <Value>			simple_initialiser natural_expression
-%type <Value>			character_code_expression string_expression string_expression_item
-%type <pStringArray>		simple_initialiser_list
-%type <NumInitialiser>		natural_expression_numeric
-%type <RlsQualifiers>		rls_qualifiers rls_cardinality
-%type <Value>		rls_label
-%type <RlsType>		rls_string_item rls_num_item rls_float_item
-
-%left	'+' '-'
-%left	'*' '/'
-%left	'|'
-%left	UMINUS
-
-%%
-
-/*****************************************************************/
-/* TOP-MOST RULE                                                 */
-/*****************************************************************/
-source :	statement_list				{	if(verbose)	{	MOFF; cout << Divider << "\n" << Divider << endl; MON; }
-										}
-;
-/*****************************************************************/
-/* statement-list and statement                                  */
-/*****************************************************************/
-statement_list:
-	statement_list statement
-|	statement_list comment_tag
-|	/* Nothing */
-;
-
-statement:
-	struct_statement maybe_semicolon
-|	resource_statement maybe_semicolon
-|   character_set_statement maybe_semicolon
-|	name_statement maybe_semicolon
-|	offset_statement maybe_semicolon
-|	system_statement maybe_semicolon
-|   enum_statement
-|	uidX_statement maybe_semicolon
-|	rls_item_statement maybe_semicolon
-;
-
-maybe_semicolon:
-		';'
-		{
-		// This is my gift to the world: no more "syntax error" for adding
-		// an extra semicolon at the end of a struct or resource.
-	    REGISTER_LINE;
-	    ErrorHandler::OutputErrorLine("Warning: unnecessary semicolon");
-		}
-|
-;
-
-/******************************************************************/
-/* STRUCT statement                                               */
-/******************************************************************/
-struct_statement:
-	struct_statement_start struct_item_list '}'
-										{	if(verbose) { MOFF; cout << Divider << "\n" << * pSH << Divider << endl; MON;}	}
-;
-struct_statement_start:
-	L_STRUCT L_LABEL maybe_comment_tag '{'
-										{	if(verbose) {	MOFF;cout << "struct_statement_start                     " << $2 << endl; MON;}
-											pSH = new StructHeader($2);
-											REGISTER_LINE;
-											pG->SHA.Add(pSH);
-										}
-|	L_STRUCT L_LABEL len_declaration maybe_comment_tag '{'
-										{	if(verbose) {	RCTypeArray Types; MOFF;cout << "struct_statement_start                     " << $2 << " " << Types.GetName($3) << endl; MON;}
-											pSH = new StructHeader($2, $3);
-											REGISTER_LINE;
-											pG->SHA.Add(pSH);
-										}
-|	L_STRUCT L_LABEL L_LEN maybe_comment_tag '{'
-										{	if(verbose) {	MOFF;cout << "struct_statement_start                     " << $2 << " (WORD)" << endl; MON;}
-											pSH = new StructHeader($2, L_WORD);
-											REGISTER_LINE;
-											pG->SHA.Add(pSH);
-										}
-;
-struct_item_list:
-	struct_item_list struct_item ';'	{	if(verbose) {	MOFF;cout << "struct_item_list                           Adding struct_item." << endl; MON;}
-											REGISTER_LINE;
-											pSH->iSIA.Add($2);
-										}
-|	struct_item_list comment_tag struct_item ';'	{	if(verbose) {	MOFF;cout << "tagged struct_item_list                    Adding struct_item." << endl; MON;}
-											REGISTER_LINE;
-											pSH->iSIA.Add($3);
-										}
-|	/* Nothing */
-;
-struct_item:
-	simple_struct_item
-|	array_struct_item
-|	struct_type_struct_item
-|	struct_array_struct_item
-;
-simple_struct_item:
-	simple_struct_item_start			{	$$ = $1;}
-|	simple_struct_item_start '(' natural_expression ')'
-										{	if(verbose) { MOFF;cout << "    Limit: " << $3 << endl; MON;}
-											$1->iLengthLimit = $3;
-											$$ = $1;
-										}
-|	simple_struct_item_start '=' simple_initialiser	/****************************************************************/
-										{	if(verbose) { MOFF;cout << "    Default: " << $3 << endl; MON;}
-											$1->iDefault = $3;
-											$$ = $1;
-										}
-|	simple_struct_item_start '(' natural_expression ')' '=' string_expression /****************************************************************/
-										{	if(verbose) { MOFF;cout << "    Limit: " << $3 << ", Default: " << $6 << endl; MON;}
-											NumericValue Limit($3, L_LONG);
-											if(String($6).ExportLength(TargetCharacterSet,SourceCharacterSet) > Limit.GetULong() )
-											{
-												REGISTER_LINE;
-												ErrorHandler::OutputErrorLine("Text length exceeds specified limit");
-												exit(1);
-											}
-											$1->iLengthLimit = $3;
-											$1->iDefault = $6;
-											$$ = $1;
-										}
-
-;
-simple_struct_item_start:
-	data_type L_LABEL					{	if(verbose) 
-											{		
-												   RCTypeArray Types;
-														   MOFF;cout << "simple_struct_item                         " << Types.GetName($1) << " " << $2 << endl; MON;
-											}
-											$$ = new SimpleStructItem($1,$2); 
-											assert($$ != NULL);
-										}
-|	data_type '<' natural_expression_numeric '>' L_LABEL
-										{	if(verbose) 
-											{			   RCTypeArray Types;
-														   MOFF;cout << "simple_struct_item                         " << Types.GetName($1) << " " << $5 << endl; MON;
-											}
-											String s(NumericValue::ltoa($3));
-											$$ = new SimpleStructItem($1,$5,s);
-											assert($$ != NULL);
-										}
-;
-
-/* Note that generic text identifiers are converted to their explicit
-   8 or 16-bit forms at this point, depending on the target character set.
-*/
-data_type:
-	L_BYTE								{	$$ = L_BYTE;}
-|	L_WORD								{	$$ = L_WORD;}
-|	L_LONG								{	$$ = L_LONG;}
-|	L_DOUBLE							{	$$ = L_DOUBLE;}
-
-
-
-|	L_TEXT	
-	    { 
-	    $$ = ( TargetCharacterSet == String::Unicode ) ? L_TEXT16: L_TEXT8;
-	    REGISTER_LINE;
-	    ErrorHandler::OutputErrorLine("Warning: Deprecated use of zero-terminated TEXT - use LTEXT instead");
-	    }
-|	L_LTEXT	
-	    {
-	    $$ = ( TargetCharacterSet == String::Unicode ) ? L_LTEXT16: L_LTEXT8;
-	    }
-|	L_BUF	
-	    { 
-	    $$ = ( TargetCharacterSet == String::Unicode ) ? L_BUF16: L_BUF8;
-	    }
-
-
-
-|	L_TEXT8								{	$$ = L_TEXT8;
-											REGISTER_LINE;
-											ErrorHandler::OutputErrorLine("Warning: Deprecated use of zero-terminated TEXT8 - use LTEXT8 instead");
-										}
-|	L_TEXT16							{	$$ = L_TEXT16;
-											REGISTER_LINE;
-											ErrorHandler::OutputErrorLine("Warning: Deprecated use of zero-terminated TEXT16 - use LTEXT16 instead");
-										}
-|	L_LTEXT8							{	$$ = L_LTEXT8;}
-|	L_LTEXT16							{	$$ = L_LTEXT16;}
-|	L_BUF8								{	$$ = L_BUF8;}
-|	L_BUF16								{	$$ = L_BUF16;}
-|	L_LINK								{	$$ = L_LINK;}
-|	L_LLINK								{	$$ = L_LLINK;}
-|	L_SRLINK							{	$$ = L_SRLINK;}
-;
-array_struct_item:
-	array_struct_item_base				{	$$ = $1;}
-|	array_struct_item_base '=' '{' simple_initialiser_list '}'
-										{	if(verbose) {	MOFF;cout << "array_struct_item                          with simple_initialiser_list" << endl;MON;}
-											$1->iDefaults = * $4;
-											if($1->iSize.Length() > 0)
-											{
-												NumericValue v($1->iSize, L_LONG);
-												REGISTER_LINE;
-												if($4->Size()!=long(v.GetULong()))
-												{
-													ErrorHandler::OutputErrorLine("Size does not match number of initialisers");
-													exit(1);
-												}
-											}
-											$$ = $1;
-											delete $4;
-										}
-;
-array_struct_item_base:
-	array_struct_item_start ']'			{	if(verbose) {	MOFF;cout << "array_struct_item_base                     with no size" << endl;MON;}
-											$$ =$1;
-										}
-|	array_struct_item_start natural_expression ']'
-										{	if(verbose) {	MOFF;cout << "array_struct_item_base                     with size " << $2 << endl;MON;}
-											$1->iSize = $2;
-											$$ = $1;
-										}
-|	L_LEN len_declaration array_struct_item_start ']'
-										{	if(verbose) 
-												{		 	RCTypeArray Types;
-														 	MOFF;cout << "array_struct_item_base                     with LenType " << Types.GetName($2) << endl;MON;
-												}
-											$3->iLenType = $2;
-											$$ = $3;
-										}
-|	L_LEN len_declaration array_struct_item_start natural_expression ']'
-										{	if(verbose) 
-												{		 	RCTypeArray Types;
-														 	MOFF;cout << "array_struct_item_base                     with size " << $4 << " and LenType " << Types.GetName($2) << endl;MON;
-												}
-											$3->iLenType = $2;
-											$3->iSize = $4; 
-											$$ = $3; 
-										}
-;
-array_struct_item_start:
-	data_type L_LABEL '['				{	if(verbose) 
-												{		 	RCTypeArray Types; 
-														 	MOFF;cout << "array_struct_item_start                    " << Types.GetName($1) << " " << $2 << endl;MON;
-												}
-											$$ = new ArrayStructItem($1, $2);
-										}
-;
-len_declaration:
-	L_BYTE								{	$$ = L_BYTE;}
-|	L_WORD								{	$$ = L_WORD;}
-;
-struct_type_struct_item:
-	L_STRUCT L_LABEL					{	if(verbose) {	MOFF;cout << "struct_type_struct_item                    " << $2 << endl;MON;}
-											$$ = new StructTypeStructItem($2);
-										}
-;
-struct_array_struct_item:
-	struct_array_struct_item_base		{	$$ = $1;}
-|	L_LEN len_declaration struct_array_struct_item_base
-										{	if(verbose) {	RCTypeArray Types; MOFF;cout << "struct_array_struct_item                   - Setting Size to " << Types.GetName($2) << endl;MON;}
-											$3->iLenType = $2; $$ = $3;
-										}
-;
-struct_array_struct_item_base:
-	L_STRUCT L_LABEL '[' ']'			{	if(verbose) {	MOFF;cout << "struct_array_struct_item_base              " << $2 << endl;MON;}
-											$$ = new StructArrayStructItem($2);
-										}
-|	L_STRUCT L_LABEL '[' natural_expression ']'
-										{	if(verbose) {	MOFF;cout << "struct_array_struct_item_base              " << $2 << " " << $4 << endl;MON;}
-											$$ = new StructArrayStructItem($2, $4);
-										}
-;
-/*********************************************************************/
-/* RESOURCE statement                                                */
-/*********************************************************************/
-resource_statement:
-	resource_statement_start '{' resource_item_list '}'
-	    {	
-	    pResourceHeader->AddDefault();
-	    CurrentId+=CurrentIdStep;
-	    if(verbose) { MOFF;cout << "Resource ID "<< CurrentId << endl << Divider << "\n" << * pResourceHeader << Divider << endl;MON;}
-	    pResourceHeader->SetResourceId(*pResourceNameIds,CurrentId,FormatIdAsHex);
-	    pG->Index.Add(pResourceHeader);
-		
-		CheckStructUsage();
-
-		pUsedLabelsArray->Empty();
-
-	    pResourceHeader = NULL;
-	    }
-;
-resource_statement_start:
-	L_GLOBAL resource_statement_start_names {}	/* Ignore GLOBAL (obsolete feature).*/
-|	L_LOCAL  resource_statement_start_names
-	    {	
-	    if(verbose) { MOFF;cout << "resource_statement_start                   LOCAL" << endl;MON;}
-		    assert(pResourceHeader != NULL);
-		    pResourceHeader->iLocal = 1;
-	    }
-|	resource_statement_start_names {}
-;
-resource_statement_start_names:
-	L_RESOURCE L_LABEL L_LABEL			{	if(verbose) {	MOFF;cout << "resource_statement_start_names             " << $2 << " " << $3 << endl;MON;}
-											assert(pResourceHeader == NULL);
-											pResourceHeader = new ResourceHeader($3);
-											pCurrentRIA = & (pResourceHeader->iRIA);
-											REGISTER_LINE;
-											if(pResourceNameIds->IsStored($3))
-											{
-												ErrorHandler::OutputErrorLine("Resource with this name encountered already");
-												exit(1);
-											}
-											pCurrentRIA->FillFromStruct($2);
-											pG->AllIdentifiers.Add(new String($3)); // Add label to store
-										}
-|	L_RESOURCE L_LABEL					{	if(verbose) {	MOFF;cout << "resource_statement_start_names             " << $2 << " <Resource not named>" << endl;MON;}
-											assert(pResourceHeader == NULL);
-											pResourceHeader = new ResourceHeader;
-											pCurrentRIA = & (pResourceHeader->iRIA);
-											REGISTER_LINE;
-											pCurrentRIA->FillFromStruct($2);
-										}
-;
-resource_item_list:
-	resource_item_list resource_item ';'{	if(verbose) {	MOFF;cout << "resource_item_list" << endl;MON;}}
-|	resource_item_list comment_tag resource_item ';'{	if(verbose) {	MOFF;cout << "tagged resource_item_list" << endl;MON;}}
-|	resource_item_list error ';'		{	yyerrok; yyclearin; }
-|	/* Nothing */
-;
-resource_item:
-	L_LABEL '=' simple_initialiser		{	if(verbose) {	MOFF;cout << "resource_item                              " << $1 << " " << $3 << endl;MON;}
-											REGISTER_LINE;/****************************************************************/
-											pCurrentRIA->Set($1, $3);
-										}
-|	resource_simple_array_item
-|	struct_resource_item
-|	struct_array_resource_item
-;
-resource_simple_array_item:
-	L_LABEL '=' '{' '}'                 
-	    {	
-	    if (verbose) 
-		{ MOFF;cout << "resource_simple_array_item                 " << $1 << endl;MON;} 
-	    }
-|	L_LABEL '=' '{' simple_initialiser_list '}'
-	    {	
-	    if (verbose) 
-		{ MOFF;cout << "resource_simple_array_item                 " << $1 << " with simple_initialiser_list" << endl;MON;}
-	    REGISTER_LINE;
-	    pCurrentRIA->Set($1, * $4);
-	    delete $4;
-	    }
-;
-
-/*---------------------------------------------------------------------------*/
-/* A note about RIAStack, SRIStack and pCurrentRIA.                          */
-/*                                                                           */
-/*  RIA stands for Resource Item Array.                                      */
-/*  SRI stands for Struct Array Resource Item.                               */
-/*                                                                           */
-/*  A push to RIAStack is made when dropping inside a STRUCT or STRUCT[] in  */
-/*  order to set values for the components. When this happens pCurrentRIA is */
-/*  set to the RIA for the STRUCT or last item of the STRUCT[].              */
-/*                                                                           */
-/*  pCurrentRIA is set to the result of popping from RIAStack when a closing */
-/*  brace is reached.                                                        */
-/*                                                                           */
-/*  A push is made to SRIStack when going into an item for a STRUCT[]. On    */
-/*  reaching a closing brace the STRUCT[] is popped off the SRIStack. An new */
-/*  item may then be added to this array.                                    */
-/*---------------------------------------------------------------------------*/
-struct_resource_item:
-	struct_resource_item_start resource_item_list '}'
-										{	if(verbose) {	MOFF;cout << "struct_resource_item" << endl;MON;}
-											pCurrentRIA = pG->RIAStack.Pop();
-										}
-;
-struct_resource_item_start:
-	L_LABEL '=' L_LABEL '{'	{	if(verbose) {	MOFF;cout << "struct_resource_item_start                 " << $1 << " " << $3 << endl;MON;}
-											REGISTER_LINE;
-											pCurrentRIA->Set($1, $3);
-											String * thisLabel = new String($1);
-											pUsedLabelsArray->Add(thisLabel);
-											// in here add the label to a temp store
-											pG->RIAStack.Push(pCurrentRIA);
-											pCurrentRIA = pCurrentRIA->Find($1)->GetRIA();
-										}
-;
-struct_array_resource_item:
-	struct_array_resource_item_start struct_array_resource_item_list_top '}'
-										{	if(verbose) {	MOFF;cout << "struct_array_resource_item" << endl;MON;}
-											pG->SRIStack.Pop();
-										}
-|	struct_array_resource_item_start struct_array_resource_item_list_top error
-										{	pG->SRIStack.Pop();}
-;
-struct_array_resource_item_start:
-	L_LABEL '=' '{'	L_LABEL '{'			{	if(verbose) {	MOFF;cout << "struct_array_resource_item_start           " << $1 << " " << $4 << endl;MON;}
-											ResourceItem * p = pCurrentRIA->Find($1);
-											pG->SRIStack.Push(p);
-											REGISTER_LINE;
-											String * thisLabel = new String($1);
-											pUsedLabelsArray->Add(thisLabel);
-											// in here add the label to a temp store
-											p->Set($4);
-											pG->RIAStack.Push(pCurrentRIA);
-											pCurrentRIA = p->GetRIA();
-										}
-;
-struct_array_resource_item_list_top:
-	struct_array_resource_item_list_top_start
-|	struct_array_resource_item_list_top_start ',' struct_array_resource_item_list
-|	struct_array_resource_item_list_top_start ',' error
-;
-struct_array_resource_item_list_top_start:
-	resource_item_list '}'				{	if(verbose) {	MOFF;cout << "struct_array_resource_item_list_top        " << endl;MON;}
-											pCurrentRIA = pG->RIAStack.Pop();
-										}
-;
-struct_array_resource_item_list:
-	struct_array_resource_item_list_item
-|	struct_array_resource_item_list ',' struct_array_resource_item_list_item
-;
-struct_array_resource_item_list_item:
-	struct_array_resource_item_list_item_start resource_item_list '}'
-										{	if(verbose) {	MOFF;cout << "struct_array_resource_item_list_item       " << endl;MON;}
-											pCurrentRIA = pG->RIAStack.Pop();
-										}
-;
-struct_array_resource_item_list_item_start:
-	L_LABEL '{'							{	if(verbose) {	MOFF;cout << "struct_array_resource_item_list_item_start " << $1 << endl;MON;}
-											ResourceItem * p = pG->SRIStack.Peek();
-											REGISTER_LINE;
-											p->Set($1);
-											pG->RIAStack.Push(pCurrentRIA);
-											pCurrentRIA = p->GetRIA();
-										}
-;
-
-
-/*****************************************************************/
-/* simple_initialiser and simple_initialiser_list                */
-/*****************************************************************/
-simple_initialiser:
-	L_NUM_FLOAT
-|	L_CHAR_LITERAL  
-	    { 
-	    // convert literal to unsigned long value of 1st character
-		SetCharacterLiteral($$, $1);
-	    }
-|	string_expression
-|	natural_expression
-; 
-simple_initialiser_list:
-	simple_initialiser  
-	    {
-	    if(verbose) 
-		{	
-		MOFF;cout << "simple_initialiser_list                    - single string " << $1 << endl;MON;
-		}
-		
-	    $$ = new StringArray;
-	    $$->Add(new String($1) );
-	    }
-|	simple_initialiser_list ',' simple_initialiser	
-										{	if(verbose) {	MOFF;cout << "simple_initialiser_list                    - part of list " << $3 << endl;MON;}
-											assert($1 != NULL);
-											$1->Add(new String($3 ) );
-											$$ = $1;
-										}
-;
-
-natural_expression:
-	natural_expression_numeric			{	String s(NumericValue::ltoa($1) ); strcpy($$, s.GetAssertedNonEmptyBuffer() ); }
-;	
-natural_expression_numeric:
-	L_NUM_NATURAL						{	if(verbose) {	MOFF;cout << "Converting number " << $1 << endl;MON;}
-											REGISTER_LINE;
-											NumericValue v($1, L_LONG); $$ = (long)v.GetULong();
-										}
-|	natural_expression_numeric '+' natural_expression_numeric	{	$$ = $1 + $3;	}
-|	natural_expression_numeric '-' natural_expression_numeric	{	$$ = $1 - $3;	}
-|	natural_expression_numeric '*' natural_expression_numeric	{	$$ = $1 * $3;	}
-|	natural_expression_numeric '/' natural_expression_numeric	{	$$ = $1 / $3;	}
-|	natural_expression_numeric '|' natural_expression_numeric	{	$$ = $1 | $3;	}
-|	'-' natural_expression_numeric %prec UMINUS					{	if (!NumericValue::CheckSigned($2,L_LONG))
-																	{
-																	REGISTER_LINE;
-																	ErrorHandler::OutputErrorLine("Signed value too low");
-																	exit(1);
-																	}
-																	$$ = - $2;		
-																}
-|	'(' natural_expression_numeric ')'							{	$$ = $2;		}
-;
-string_expression:
-	string_expression_item  
-|	string_expression_item string_expression {
-	    if (strlen($$)+strlen($2) > sizeof($$)-1)
-		{
-		REGISTER_LINE;
-		ErrorHandler::OutputErrorLine("String expression is too long");
-		exit(1);
-		}
-	    strcat($$, $2);
-	    }
-;
-string_expression_item:
-	L_STRING_LITERAL
-|	character_code_expression
-|	L_LABEL 
-	    {
-		const char * fileName = (*ErrorHandler::GetFileName()).GetBuffer();
-		int lineNumber = ErrorHandler::GetLineNumber();
-		QualifiedString * thisLabel = new QualifiedString($1, new String(fileName), lineNumber);
-		// store the label in the UsedIdentifiers array for checking
-		// whether label was declared
-		pG->UsedIdentifiers.Add(thisLabel);
-
-	    if (pG->EnumValues.IsStored($1))
-			{
-			sprintf($$, "%d", pG->EnumValues.FindId($1));
-			}
-		else if (pG->RlsNameIndex.count($1)) // if rls item has already been defined
-			{
-			// Found a reference to an rls_string.
-			RlsValue &rv = pG->RlsValues[pG->RlsNameIndex[$1]];
-			++rv.iCitationCount; // iCitationCount counts the number of times this rls value has been referneced
-			// Warn for multiple uses if 'multi' keyword not used.
-			if (1 < rv.iCitationCount && rv.iCardinality == ERlsCardinalitySingle)
-				{
-				Message * message = pG->Messages.GetEntry(LT_001);
-				String fileLine = *(rv.iFileName);
-				if(message->GetActivated())
-				{
-					pGL->AddWarningToStore(fileLine, rv.iLineNumber, message->GetMessageOutput());
-				}
-				REGISTER_LINE;
-				if (!pG->WarningMultiExplained)
-					{
-					Message * message = pG->Messages.GetEntry(LT_002);
-					fileLine = String(*(pFileLineHandler->GetCurrentFile()));
-					if(message->GetActivated())
-						{
-						pGL->AddWarningToStore(fileLine, pFileLineHandler->GetErrorLine(* pCurrentLineNumber), message->GetMessageOutput());
-						pG->WarningMultiExplained = true;
-						}
-					}
-				}
-			switch (rv.iType)
-				{
-				// Strings and numbers are just copied to the next layer up.
-			case ERlsString:
-			case ERlsString8:
-			case ERlsByte:
-			case ERlsWord:
-			case ERlsLong:
-			case ERlsDouble:
-				strcpy($$, rv.iValue.GetBuffer());
-				break;
-				// Anything else is a character: this is converted to a number.
-			case ERlsStringChar:
-			case ERlsByteChar:
-			case ERlsWordChar:
-			case ERlsLongChar:
-				SetCharacterLiteral($$, rv.iValue);
-				break;
-			default:
-				Message * message = pG->Messages.GetEntry(LT_031);
-				if(message->GetActivated())
-					{
-					ErrorHandler::OutputErrorLine(message->GetMessageOutput());
-					exit(1);
-					}
-				break;
-				}
-			}
-		else
-			{
-			/*
-			Could be a reference to another resource, perhaps even a forward reference:
-			the OverwriteLink functions do FindId again when writing out the data.
-			Sadly this also permits things which are really syntax errors, inadvertently
-			converting labels into string literals..
-			*/
-			}
-	    }
-;
-character_code_expression:
-	'<' natural_expression_numeric '>'  
-	    {	
-	    REGISTER_LINE;
-	    if($2 < 0 || ($2 > 255 && TargetCharacterSet != String::Unicode))
-		{
-		    ErrorHandler::OutputErrorLine("Character code must be a number in the range 0 to 255.");
-		    exit(1);
-		}
-	    if (TargetCharacterSet != String::Unicode)
-		{
-		* $$ = char($2); * ($$ + 1) = '\0'; 
-		} 
-	    else
-		{
-		if (SourceCharacterSet == String::CP1252)
-		    {
-		    if ( ($2 >= 0x80) && ($2 <= 0x9F ) ) // 80-9F are illegal Unicode values.
-			{
-			ErrorHandler::OutputErrorLine("Warning: Deprecated non-unicode value in source stream");
-			}
-		    * $$ = char(UnicodeEscape);
-		    asUTF8($$ + 1, $2);
-		    }
-		else
-		if (SourceCharacterSet == String::UTF8)
-		    {
-		    asUTF8($$, $2);
-		    }
-		else
-		    {
-		    // Unsatisfactory, but do people use other character sets?
-		    if ($2 > 255)
-			{
-			ErrorHandler::OutputErrorLine("Don't know how to handle character > 255");
-			}
-		    * $$ = char($2); * ($$ + 1) = '\0'; 
-		    }
-		}
-	    }
-;
-
-
-/*****************************************************************/
-/* name_statement                                                */
-/*****************************************************************/
-name_statement:
-	L_NAME L_LABEL
-	    {
-	    REGISTER_LINE;
-	    SetIdFromName($2);
-	    }
-|	L_NAME L_STRING_LITERAL
-	    {
-	    REGISTER_LINE;
-	    SetIdFromName($2);
-	    }
-;
-
-
-/*****************************************************************/
-/* uidX_statement                                                */
-/*****************************************************************/
-uidX_statement:
-	L_UID_TWO natural_expression_numeric
-		{
-		REGISTER_LINE;
-		if ($2 == 0)
-			{ ErrorHandler::OutputErrorLine("UID2 must be non-zero"); exit(1); }
-		if (Uid2 != 0)
-			{ ErrorHandler::OutputErrorLine("Warning: overwriting previous UID2 value"); }
-		Uid2=$2;
-		if(verbose) 
-			{ MOFF;cout << "uidX_statement  UID2                       " << Uid2 << endl;MON;}
-		}
-|	L_UID_THREE natural_expression_numeric
-		{
-		REGISTER_LINE;
-		if ($2 == 0)
-			{ ErrorHandler::OutputErrorLine("UID3 must be non-zero"); exit(1); }
-		if (Uid3 != 0)
-			{ ErrorHandler::OutputErrorLine("Warning: overwriting previous UID3 value"); }
-		Uid3=$2;
-		if(verbose) 
-			{ MOFF;cout << "uidX_statement  UID3                       " << Uid3 << endl;MON;}
-		}
-;
- 
- 
-/*****************************************************************/
-/* character_set_statement                                       */
-/* Defines the SOURCE character set. Note that Unicode is a      */
-/* character set id, but we can't read Unicode source            */
-/* (because LEX and YACC can't handle it)                        */
-/*****************************************************************/
-
-character_set_statement:
-	L_CHARACTER_SET L_LABEL		{	if(verbose) {	MOFF;cout << "character_set_statement                    " << $2 << endl;MON;}
-											REGISTER_LINE;
-											SourceCharacterSet = CharacterSetID($2);
-											if ( SourceCharacterSet == String::UNKNOWN )
-											{
-												String err = "Warning: Unrecognised character set name '";
-												err += $2;
-												err += "'";
-												ErrorHandler::OutputErrorLine(err);
-											}
-											if ( SourceCharacterSet == String::Unicode )
-											{
-											    SourceCharacterSet = String::UNKNOWN;
-												ErrorHandler::OutputErrorLine("Unicode source is unsupported");
-											}
-										}
-;
-
-
-
-/*****************************************************************/
-/* offset_statement                                              */
-/*****************************************************************/
-offset_statement:
-	L_OFFSET natural_expression			{	if(verbose) {	RCTypeArray Types;
-															MOFF;cout << "offset_statement                           " << $2 << endl;MON; }
-											REGISTER_LINE;
-										 	CurrentId=((long) NumericValue($2, L_LONG).GetULong() );
-										}
-;
-
-/*****************************************************************/
-/* system_statement                                              */
-/*****************************************************************/
-system_statement:
-	L_SYSTEM							{	if(verbose) {	MOFF;cout << "system_statement" << endl;MON;}
-											CurrentIdStep=-1;
-										}
-;
-
-/*****************************************************************/
-/* enum_statement                                                */
-/*****************************************************************/
-enum_statement:
-    enum_statement_start enum_list '}'
-|	enum_statement_start enum_list '}' ';'
-;
-enum_statement_start:
-	L_ENUM L_LABEL '{'					 
-	    {	
-	    if(verbose) 
-		{ MOFF;cout << "enum_statement" << endl;MON;} 
-	    CurrentEnumName = $2;
-	    CurrentEnumValue=0;
-	    }
-|	L_ENUM '{'						
-	    {	
-	    if(verbose) 
-		{ MOFF;cout << "enum_statement" << endl;MON;} 
-	    CurrentEnumName = "";
-	    CurrentEnumValue=0;
-	    }
-;
-
-enum_list_entry:
-	L_LABEL                             
-		{	
-		pG->EnumValues.Add($1, CurrentEnumValue++);
-		pG->AllIdentifiers.Add(new String($1)); // Add label to store
-		}
-|	L_LABEL '=' simple_initialiser      
-	    {	
-	    CurrentEnumValue = atol($3);
-	    pG->EnumValues.Add($1, CurrentEnumValue);
-	    CurrentEnumValue++;			// Increment so that next field has value ($3+1)
-		pG->AllIdentifiers.Add(new String($1)); // Add label to store
-	    }
-;
-
-
-enum_list:
-		maybe_comment_tag enum_list_entry
-|		enum_list ',' maybe_comment_tag enum_list_entry
-;
-
-/************************/
-/* rls_xxxx statement */
-/************************/
-rls_item_statement:
-		rls_string_item rls_qualifiers rls_label string_expression
-		{
-		pG->RlsNameIndex[$3] = pG->RlsValues.size();
-		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
-			ErrorHandler::GetLineNumber(), $4, $1,
-			$2.iCardinality, $2.iMaxLength));
-		if($2.iMaxLength
-			< String($4).ExportLength(TargetCharacterSet,SourceCharacterSet))
-			{
-			Message * message = pG->Messages.GetEntry(LT_032);
-			if(message->GetActivated())
-				{
-				ErrorHandler::OutputErrorLine(message->GetMessageOutput());
-				exit(1);
-				}
-			}
-		}
-|		rls_string_item rls_qualifiers rls_label L_CHAR_LITERAL	/* This section is only for compatibility */
-		{
-		Message * message = pG->Messages.GetEntry(LT_033);
-		String fileName = *(pFileLineHandler->GetCurrentFile());
-		int lineNumber = pFileLineHandler->GetErrorLine(* pCurrentLineNumber);
-		if(message->GetActivated())
-			{
-			pGL->AddWarningToStore(fileName, lineNumber, message->GetMessageOutput());
-			}
-		//...
-		/* Produce a warning "rls_string used for character constant: use rls_long, rls_word or rls_byte" */
-		pG->RlsNameIndex[$3] = pG->RlsValues.size();
-		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
-			ErrorHandler::GetLineNumber(), $4, ERlsStringChar,
-			$2.iCardinality));
-		}
-|		rls_float_item rls_cardinality rls_label L_NUM_FLOAT
-		{
-		pG->RlsNameIndex[$3] = pG->RlsValues.size();
-		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
-			ErrorHandler::GetLineNumber(), $4, $1,
-			$2.iCardinality));
-		}
-|		rls_num_item rls_cardinality rls_label L_NUM_NATURAL
-		{
-		pG->RlsNameIndex[$3] = pG->RlsValues.size();
-		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
-			ErrorHandler::GetLineNumber(), $4, $1,
-			$2.iCardinality));
-		}
-|		rls_num_item rls_cardinality rls_label L_CHAR_LITERAL
-		{
-		TRlsType rlsCharType = $1 == ERlsByte? ERlsByteChar
-			: ( $1 ==  ERlsWord? ERlsWordChar : ERlsLongChar );
-		pG->RlsNameIndex[$3] = pG->RlsValues.size();
-		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
-			ErrorHandler::GetLineNumber(), $4, rlsCharType,
-			$2.iCardinality));
-		}
-;
-
-rls_label: L_LABEL
-		{
-		// Register line even if no warning here so that
-		// the rls_ item knows which line the label was on.
-		// Without this, the line registered would be the
-		// line following the declaration.
-		REGISTER_LINE;
-		strcpy($$, $1);
-
-		if (pG->RlsNameIndex.count($1) != 0)
-			{
-			Message * message = pG->Messages.GetEntry(LT_003);
-			if(message->GetActivated())
-				{
-				ErrorHandler::OutputErrorLine(message->GetMessageOutput());
-				}
-			}
-		pG->AllIdentifiers.Add(new String($1)); // Add label to store
-		}
-
-rls_qualifiers:
-		'<' L_NUM_NATURAL '>' rls_cardinality
-		{
-		NumericValue v($2, L_LONG);
-		$$.iMaxLength = v.GetULong();
-		$$.iCardinality = $4.iCardinality;
-		}
-|		rls_cardinality
-		{ $$ = $1; }
-;
-
-rls_cardinality:
-		L_MULTI
-		{
-		$$.iMaxLength = 0xFFFFFFF;
-		$$.iCardinality = ERlsCardinalityMultiple;
-		}
-|
-		{
-		$$.iMaxLength = 0xFFFFFFF;
-		$$.iCardinality = ERlsCardinalitySingle;
-		}
-;
-
-rls_string_item:
-		L_RLS_STRING
-		{ $$ = ERlsString; }
-|		L_RLS_STRING8
-		{ $$ = ERlsString8; }
-;
-
-rls_num_item:
-		L_RLS_BYTE
-		{ $$ = ERlsByte; }
-|		L_RLS_WORD
-		{ $$ = ERlsWord; }
-|		L_RLS_LONG
-		{ $$ = ERlsLong; }
-;
-
-rls_float_item:
-		L_RLS_DOUBLE
-		{ $$ = ERlsDouble; }
-;
-
-/************************/
-/* comment tags         */
-/************************/
-maybe_comment_tag:
-	comment_tag
-|
-;
-
-comment_tag:
-	L_TAG_START tag_line L_TAG_END {ErrorHandler::Register(pFileLineHandler->GetCurrentFile(), pFileLineHandler->GetErrorLine(*pCurrentLineNumber)); }
-   ;
-
-tag_line:
-	tag_line tag_word
-
-|
-;
-
-tag_word:
- 	L_TAG_NEW_LINE	{ pGL->StoreComment($1);	}
-|	L_TAG_COMMAND	{ pGL->StoreComment($1);	}
-|	L_TAG_WORD		{ pGL->StoreComment($1);	}
-;
-
-%%
-
-// Function section
-// ================
-
-void asUTF8(char* aUtf8, int aUnicode)
-	{
-	if ( aUnicode > 0xffff )
-		{
-		if ( aUnicode > 0x10ffff )
-		{
-		ErrorHandler::OutputErrorLine("Surrogate character code must be a number in the range 0x10000 to 0x10ffff");
-		exit(1);		
-		}
-		
-		UTF16 high = (UTF16)(0xD7C0 + (aUnicode >> 10));			// high surrogate
-		UTF16 low = (UTF16)(0xDC00 | (aUnicode & 0x3FF));			// low surrogate
-	
-		*aUtf8++ =(char)(0xe0|(high>>12));
-		*aUtf8++ =(char)(0x80|((high>>6)&0x3f));
-		*aUtf8++ =(char)(0x80|(high&0x3f));
-		*aUtf8++ =(char)(0xe0|(low>>12));
-		*aUtf8++ =(char)(0x80|((low>>6)&0x3f));
-		*aUtf8   =(char)(0x80|(low&0x3f));
-		}
-	else if ((aUnicode & 0xff80) == 0x0000)
-		{
-		*aUtf8 = (char)aUnicode;
-		}
-	else if ((aUnicode & 0xf800) == 0x0000)
-		{
-		*aUtf8++ =(char)(0xc0|(aUnicode>>6));
-		*aUtf8   =(char)(0x80|(aUnicode&0x3f));
-		}
-	else
-		{
-		*aUtf8++ =(char)(0xe0|(aUnicode>>12));
-		*aUtf8++ =(char)(0x80|((aUnicode>>6)&0x3f));
-		*aUtf8   =(char)(0x80|(aUnicode&0x3f));
-		}
-	*++aUtf8 = '\0';
-	}
-
-
-String::CharacterSet CharacterSetID( const String & character_set_name )
-// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-// Return a character set ID from a character set name.  The value UNKNOWN
-// is returned if the name is not recognised.
-// ----------------------------------------------------------------------------
-{
-	String::CharacterSet ids[] = { String::ISOLatin1, String::ASCII, String::CP1252
-	                              , String::CP850, String::ShiftJIS, String::Unicode
-								  , String::UTF8
-								  , String::UNKNOWN
-								 };
-	String names[] = { "ISOLATIN1", "ASCII", "CP1252", "CP850", "SHIFTJIS", "UNICODE", "UTF8" };
-
-	for ( int i=0; ids[i]!=String::UNKNOWN; i++ )
-	{
-		if ( names[i] == character_set_name ) return ids[i];
-	}
-
-	return String::UNKNOWN;
-
-} // end of CharacterSetID code
-
-void SetIdFromName( const String & NameStatementValue)
-	{
-	// space 	0
-	// A		1
-	// B		2
-	// ...
-	// Z		26
-	//
-	// ABCD corresponds to the number 4321 which becomes ( (4*27 + 3) * 27 + 2) * 27 + 1.
-	
-	if(verbose) 
-		{ MOFF;cout << "name_statement                             " << NameStatementValue << endl;MON;}
-	if ( NameStatementValue.Length() > 4)
-		{
-		ErrorHandler::OutputErrorLine( "Name must be no longer than four characters");
-		exit( 1);
-		}
-	
-	long NewId = 0;
-	
-	for( unsigned long i = 0; i < NameStatementValue.Length(); i++)
-		{
-		NewId *= 27;
-		if ( isalpha( NameStatementValue[i]) )
-			NewId += toupper( NameStatementValue[i]) - 'A' + 1;
-		}
-
-	CurrentId = NewId << 12;
-	FormatIdAsHex = 1;
-	if(verbose) 
-		{ MOFF;cout << "Current id                                " << CurrentId << endl;MON;}
-	}
-
-void RlsUnusedWarnings()
-	{
-	TNameIndex::iterator end = pG->RlsNameIndex.end();
-	for (TNameIndex::iterator i = pG->RlsNameIndex.begin(); i != end; ++i)
-		{
-		int index = i->second;
-		RlsValue& v = pG->RlsValues[index];
-		if (v.iCitationCount == 0)
-			{
-			Message * message = pG->Messages.GetEntry(LT_004);
-			String fileLine = *(v.iFileName);
-			if(message->GetActivated())
-				{
-				pGL->AddWarningToStore(fileLine, v.iLineNumber, message->GetMessageOutput());
-				}
-			}
-		}
-	}
-
-int ParseSourceFile(FILE* aFile, unsigned short aYYDebug)
-	{
-	// Set up various global pointers which refer to the pG structure
-	pSHA = & (pG->SHA);
-	pFileLineHandler = & (pG->FileLineHandler);
-	pResourceNameIds = & (pG->ResourceNameIds);
-
-	pScan = new rcscan(pG->FileLineHandler, aFile);
-
-	yydebug = aYYDebug;
-	pCurrentLineNumber = &yylineno;
-	int ReturnValue = yyparse();
-
-	RlsUnusedWarnings();
-
-	int bScanErrorFound = pScan->ErrorWasFound();
-
-	delete pScan;
-	pScan = NULL;
-
-	if(ReturnValue != 0)
-		return ReturnValue;
-	
-	if(bScanErrorFound)
-		return 1;
-	
-	return 0;	// successful parse - parse tree now in the pG data structure
-	}
-
-
-void CheckStructUsage()
-	{
-	ResourceItemArrayIterator	nextRI( *pCurrentRIA);
-	ResourceItem * pRI;
-	while ( ( pRI = nextRI() ) != NULL)
-		{
-		int resourceItemType = pRI->GetResourceItemType();
-		String resourceItemLabel = pRI->GetLabel();
-		if( (resourceItemType == EStructTypeResourceItem) || (resourceItemType == EStructArrayResourceItem) )
-			{
-			StringArrayIterator nextLabel( *pUsedLabelsArray);
-			String * pLabel;
-			bool flag = false;
-			while ( ( ( pLabel = nextLabel() ) != NULL ) && (! flag) )
-				{
-				StringLess stringCompare;
-				if( !stringCompare(resourceItemLabel,*pLabel) && !stringCompare(*pLabel,resourceItemLabel) )
-					{
-					flag = true;
-					}
-				}
-			if(! flag)
-				{
-				if(resourceItemType == EStructTypeResourceItem)
-					{
-					Message * message = pG->Messages.GetEntry(LT_046);
-					if(message->GetActivated())
-						{
-						String comment = message->GetMessageOutput();
-						comment += "'";
-						comment += resourceItemLabel;
-						comment += "'";
-						ErrorHandler::OutputErrorLine(comment);
-						}
-					}
-				else
-					{
-					Message * message = pG->Messages.GetEntry(LT_047);
-					if(message->GetActivated())
-						{
-						String comment = message->GetMessageOutput();
-						comment += "'";
-						comment += resourceItemLabel;
-						comment += "'";
-						ErrorHandler::OutputErrorLine(comment);
-						}
-					}
-				}
-			}
-		}
-	}
-
-int yywrap()
-{
-  return 1;
-}
-
-/* Called by yyparse on error */
-#include <stdarg.h>
-void yyerror (const char *s, ...)
-{
-  va_list list;
-  va_start(list, s);
-  pScan->yyerror(const_cast<char*>(s), list);
-  va_end(list);
-}
-
-
+%{
+// Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies). 
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of the License "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:
+// 
+// RCOMP.CPP
+// Generated from RCOMP.Y
+
+#include <assert.h>
+#include <ctype.h>
+#include <string.h>
+
+#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
+#include <fstream>
+#include <iostream>
+using namespace std;
+using std::cout;
+using std::endl;
+#else //!__MSVCDOTNET__
+#include <fstream.h>
+#endif //__MSVCDOTNET__
+
+#ifdef __VC32__
+#pragma warning( disable : 4065 ) // C4065: switch statement contains 'default' but no 'case' labels
+#pragma warning( disable : 4102 ) // C4102: 'yyerrlab1' : unreferenced label
+#pragma warning( disable : 4127 ) // C4127: conditional expression is constant
+#pragma warning( disable : 4244 ) // C4244: '=' : conversion from 'int' to 'short', possible loss of data
+#endif //__VC32__
+
+//#include "resource.h"
+//#include "parser.h"
+#include "RESOURCE.H"
+#include "parser.h"
+
+int yylex();
+void yyerror(const char* string, ...);
+int yywrap();
+#define YYDEBUG 1
+extern int yylineno;
+
+#include "rcomp.hpp"
+#include "datatype.h"
+#include "mem.h"
+#include "rcbinstr.h"
+#include "rcscan.h"
+#include "errorhan.h"
+#include "fileacc.h"
+#include "version.h"
+#include "ctable.h"
+#include "localise.h"
+#include "main.h"
+
+#if defined(__VC32__) && !defined(_DEBUG)
+#pragma warning( disable : 4702 )	// unreachable code
+#pragma warning( disable : 4102 )	// 'yyerrlabel' : unreferenced label
+#pragma warning( disable : 4244 )	// '=' : conversion from 'int' to 'short', possible loss of data
+#endif
+
+
+
+String::CharacterSet CharacterSetID( const String & character_set_name );
+void asUTF8(char* aUtf8, int aUnicode);
+void SetIdFromName( const String & NameStatementValue);
+void CheckStructUsage();
+
+unsigned short & d = MemCheckControl::iLogMemory;
+
+StructHeader *		pSH;
+
+StructHeaderArray * 	pSHA;	// Used in resource struct handling functions.
+ResourceHeader *	pResourceHeader;
+ResourceItemArray *	pCurrentRIA;
+StringArray * pUsedLabelsArray = new StringArray();
+int			verbose;
+String::CharacterSet	SourceCharacterSet = String::CP1252;
+String::CharacterSet	TargetCharacterSet = String::CP1252;
+unsigned short		logmemorysetting;
+int *			pCurrentLineNumber;
+FileLineManager *	pFileLineHandler;
+NameIdMap *		pResourceNameIds;
+long			CurrentEnumValue;
+String			CurrentEnumName;
+char			TempStr[300];
+rcscan * pScan;
+
+int CurrentIdStep=1;
+long CurrentId=0;
+int FormatIdAsHex=0;	// defaults to decimal, changes in SetIdFromName
+
+unsigned long Uid2=0;
+unsigned long Uid3=0;
+
+
+
+const String	Divider("*******************************************");
+
+#define REGISTER_LINE	ErrorHandler::Register(pFileLineHandler->GetCurrentFile(), pFileLineHandler->GetErrorLine(* pCurrentLineNumber))
+
+// Convert a string containing a character literal in aQuoted
+// into a value suitable for LCHAR_LITERAL
+void SetCharacterLiteral(char* aOut, const String& aQuoted)
+	{
+	    UTF16 first;
+	    int length=1;
+	    if (aQuoted.Length() < 1 ) 
+	               { 
+                        REGISTER_LINE;
+                        ErrorHandler::OutputErrorLine("Warning: Empty Character literal");
+                       }
+	    if (aQuoted.Length() > 1 ) 
+	 	       {
+                        REGISTER_LINE;
+                        ErrorHandler::OutputErrorLine("Error: String Literal length greater than 1");
+			exit(1);
+                       }
+	    if (aQuoted.Export(&first, length, SourceCharacterSet)==0)
+			{
+			REGISTER_LINE;
+			ErrorHandler::OutputErrorLine("Warning: Ignoring trailing characters in character literal");
+			}
+	    sprintf(aOut, "%d", first);
+	}
+
+%}
+
+%union {
+	char				Value[1024*8];
+	TValueMaybeRls			ValueMaybeRls;
+	unsigned long 			Id;
+	StructItem *			pStructItem;
+	SimpleStructItem *		pSimpleStructItem;
+	ArrayStructItem *   	pArrayStructItem;
+	StructArrayStructItem *	pStructArrayStructItem;
+	StringArray *			pStringArray;
+	long					NumInitialiser;
+	TRlsQualifiers		RlsQualifiers;
+	TRlsType			RlsType;
+}
+
+%token <Id> L_STRUCT L_RESOURCE L_NAME L_OFFSET L_SYSTEM L_GLOBAL L_LOCAL L_CHARACTER_SET 
+%token <Id> L_BUF L_WORD L_BYTE L_LONG L_DOUBLE L_TEXT L_LTEXT L_LINK L_LLINK L_SRLINK
+%token <Id> L_BUF8 L_TEXT8 L_LTEXT8 L_BUF16 L_TEXT16 L_LTEXT16 L_UID_TWO L_UID_THREE
+%token <Id> L_RLS_STRING L_RLS_STRING8 L_RLS_DOUBLE
+%token <Id> L_RLS_BYTE L_RLS_WORD L_RLS_LONG
+%token <Id> L_MULTI
+%token <Id> L_TAG_START L_TAG_END 
+%token <Value> L_TAG_COMMAND L_TAG_WORD L_TAG_NEW_LINE
+%token <Value> L_LABEL L_NUM_NATURAL L_NUM_FLOAT L_NATURAL_EXPR L_ENUM
+%token <Value> L_LEN
+%token <Value> L_CHAR_LITERAL L_STRING_LITERAL
+
+%type <Id>			data_type len_declaration
+%type <pStructItem>		struct_item array_struct_item simple_struct_item
+%type <pSimpleStructItem>	simple_struct_item_start
+%type <pStructItem>		struct_type_struct_item  struct_array_struct_item
+%type <pArrayStructItem>	array_struct_item_start array_struct_item_base
+%type <pStructArrayStructItem>	struct_array_struct_item_base
+%type <Value>			simple_initialiser natural_expression
+%type <Value>			character_code_expression string_expression string_expression_item
+%type <pStringArray>		simple_initialiser_list
+%type <NumInitialiser>		natural_expression_numeric
+%type <RlsQualifiers>		rls_qualifiers rls_cardinality
+%type <Value>		rls_label
+%type <RlsType>		rls_string_item rls_num_item rls_float_item
+
+%left	'+' '-'
+%left	'*' '/'
+%left	'|'
+%left	UMINUS
+
+%%
+
+/*****************************************************************/
+/* TOP-MOST RULE                                                 */
+/*****************************************************************/
+source :	statement_list				{	if(verbose)	{	MOFF; cout << Divider << "\n" << Divider << endl; MON; }
+										}
+;
+/*****************************************************************/
+/* statement-list and statement                                  */
+/*****************************************************************/
+statement_list:
+	statement_list statement
+|	statement_list comment_tag
+|	/* Nothing */
+;
+
+statement:
+	struct_statement maybe_semicolon
+|	resource_statement maybe_semicolon
+|   character_set_statement maybe_semicolon
+|	name_statement maybe_semicolon
+|	offset_statement maybe_semicolon
+|	system_statement maybe_semicolon
+|   enum_statement
+|	uidX_statement maybe_semicolon
+|	rls_item_statement maybe_semicolon
+;
+
+maybe_semicolon:
+		';'
+		{
+		// This is my gift to the world: no more "syntax error" for adding
+		// an extra semicolon at the end of a struct or resource.
+	    REGISTER_LINE;
+	    ErrorHandler::OutputErrorLine("Warning: unnecessary semicolon");
+		}
+|
+;
+
+/******************************************************************/
+/* STRUCT statement                                               */
+/******************************************************************/
+struct_statement:
+	struct_statement_start struct_item_list '}'
+										{	if(verbose) { MOFF; cout << Divider << "\n" << * pSH << Divider << endl; MON;}	}
+;
+struct_statement_start:
+	L_STRUCT L_LABEL maybe_comment_tag '{'
+										{	if(verbose) {	MOFF;cout << "struct_statement_start                     " << $2 << endl; MON;}
+											pSH = new StructHeader($2);
+											REGISTER_LINE;
+											pG->SHA.Add(pSH);
+										}
+|	L_STRUCT L_LABEL len_declaration maybe_comment_tag '{'
+										{	if(verbose) {	RCTypeArray Types; MOFF;cout << "struct_statement_start                     " << $2 << " " << Types.GetName($3) << endl; MON;}
+											pSH = new StructHeader($2, $3);
+											REGISTER_LINE;
+											pG->SHA.Add(pSH);
+										}
+|	L_STRUCT L_LABEL L_LEN maybe_comment_tag '{'
+										{	if(verbose) {	MOFF;cout << "struct_statement_start                     " << $2 << " (WORD)" << endl; MON;}
+											pSH = new StructHeader($2, L_WORD);
+											REGISTER_LINE;
+											pG->SHA.Add(pSH);
+										}
+;
+struct_item_list:
+	struct_item_list struct_item ';'	{	if(verbose) {	MOFF;cout << "struct_item_list                           Adding struct_item." << endl; MON;}
+											REGISTER_LINE;
+											pSH->iSIA.Add($2);
+										}
+|	struct_item_list comment_tag struct_item ';'	{	if(verbose) {	MOFF;cout << "tagged struct_item_list                    Adding struct_item." << endl; MON;}
+											REGISTER_LINE;
+											pSH->iSIA.Add($3);
+										}
+|	/* Nothing */
+;
+struct_item:
+	simple_struct_item
+|	array_struct_item
+|	struct_type_struct_item
+|	struct_array_struct_item
+;
+simple_struct_item:
+	simple_struct_item_start			{	$$ = $1;}
+|	simple_struct_item_start '(' natural_expression ')'
+										{	if(verbose) { MOFF;cout << "    Limit: " << $3 << endl; MON;}
+											$1->iLengthLimit = $3;
+											$$ = $1;
+										}
+|	simple_struct_item_start '=' simple_initialiser	/****************************************************************/
+										{	if(verbose) { MOFF;cout << "    Default: " << $3 << endl; MON;}
+											$1->iDefault = $3;
+											$$ = $1;
+										}
+|	simple_struct_item_start '(' natural_expression ')' '=' string_expression /****************************************************************/
+										{	if(verbose) { MOFF;cout << "    Limit: " << $3 << ", Default: " << $6 << endl; MON;}
+											NumericValue Limit($3, L_LONG);
+											if(String($6).ExportLength(TargetCharacterSet,SourceCharacterSet) > Limit.GetULong() )
+											{
+												REGISTER_LINE;
+												ErrorHandler::OutputErrorLine("Text length exceeds specified limit");
+												exit(1);
+											}
+											$1->iLengthLimit = $3;
+											$1->iDefault = $6;
+											$$ = $1;
+										}
+
+;
+simple_struct_item_start:
+	data_type L_LABEL					{	if(verbose) 
+											{		
+												   RCTypeArray Types;
+														   MOFF;cout << "simple_struct_item                         " << Types.GetName($1) << " " << $2 << endl; MON;
+											}
+											$$ = new SimpleStructItem($1,$2); 
+											assert($$ != NULL);
+										}
+|	data_type '<' natural_expression_numeric '>' L_LABEL
+										{	if(verbose) 
+											{			   RCTypeArray Types;
+														   MOFF;cout << "simple_struct_item                         " << Types.GetName($1) << " " << $5 << endl; MON;
+											}
+											String s(NumericValue::ltoa($3));
+											$$ = new SimpleStructItem($1,$5,s);
+											assert($$ != NULL);
+										}
+;
+
+/* Note that generic text identifiers are converted to their explicit
+   8 or 16-bit forms at this point, depending on the target character set.
+*/
+data_type:
+	L_BYTE								{	$$ = L_BYTE;}
+|	L_WORD								{	$$ = L_WORD;}
+|	L_LONG								{	$$ = L_LONG;}
+|	L_DOUBLE							{	$$ = L_DOUBLE;}
+
+
+
+|	L_TEXT	
+	    { 
+	    $$ = ( TargetCharacterSet == String::Unicode ) ? L_TEXT16: L_TEXT8;
+	    REGISTER_LINE;
+	    ErrorHandler::OutputErrorLine("Warning: Deprecated use of zero-terminated TEXT - use LTEXT instead");
+	    }
+|	L_LTEXT	
+	    {
+	    $$ = ( TargetCharacterSet == String::Unicode ) ? L_LTEXT16: L_LTEXT8;
+	    }
+|	L_BUF	
+	    { 
+	    $$ = ( TargetCharacterSet == String::Unicode ) ? L_BUF16: L_BUF8;
+	    }
+
+
+
+|	L_TEXT8								{	$$ = L_TEXT8;
+											REGISTER_LINE;
+											ErrorHandler::OutputErrorLine("Warning: Deprecated use of zero-terminated TEXT8 - use LTEXT8 instead");
+										}
+|	L_TEXT16							{	$$ = L_TEXT16;
+											REGISTER_LINE;
+											ErrorHandler::OutputErrorLine("Warning: Deprecated use of zero-terminated TEXT16 - use LTEXT16 instead");
+										}
+|	L_LTEXT8							{	$$ = L_LTEXT8;}
+|	L_LTEXT16							{	$$ = L_LTEXT16;}
+|	L_BUF8								{	$$ = L_BUF8;}
+|	L_BUF16								{	$$ = L_BUF16;}
+|	L_LINK								{	$$ = L_LINK;}
+|	L_LLINK								{	$$ = L_LLINK;}
+|	L_SRLINK							{	$$ = L_SRLINK;}
+;
+array_struct_item:
+	array_struct_item_base				{	$$ = $1;}
+|	array_struct_item_base '=' '{' simple_initialiser_list '}'
+										{	if(verbose) {	MOFF;cout << "array_struct_item                          with simple_initialiser_list" << endl;MON;}
+											$1->iDefaults = * $4;
+											if($1->iSize.Length() > 0)
+											{
+												NumericValue v($1->iSize, L_LONG);
+												REGISTER_LINE;
+												if($4->Size()!=long(v.GetULong()))
+												{
+													ErrorHandler::OutputErrorLine("Size does not match number of initialisers");
+													exit(1);
+												}
+											}
+											$$ = $1;
+											delete $4;
+										}
+;
+array_struct_item_base:
+	array_struct_item_start ']'			{	if(verbose) {	MOFF;cout << "array_struct_item_base                     with no size" << endl;MON;}
+											$$ =$1;
+										}
+|	array_struct_item_start natural_expression ']'
+										{	if(verbose) {	MOFF;cout << "array_struct_item_base                     with size " << $2 << endl;MON;}
+											$1->iSize = $2;
+											$$ = $1;
+										}
+|	L_LEN len_declaration array_struct_item_start ']'
+										{	if(verbose) 
+												{		 	RCTypeArray Types;
+														 	MOFF;cout << "array_struct_item_base                     with LenType " << Types.GetName($2) << endl;MON;
+												}
+											$3->iLenType = $2;
+											$$ = $3;
+										}
+|	L_LEN len_declaration array_struct_item_start natural_expression ']'
+										{	if(verbose) 
+												{		 	RCTypeArray Types;
+														 	MOFF;cout << "array_struct_item_base                     with size " << $4 << " and LenType " << Types.GetName($2) << endl;MON;
+												}
+											$3->iLenType = $2;
+											$3->iSize = $4; 
+											$$ = $3; 
+										}
+;
+array_struct_item_start:
+	data_type L_LABEL '['				{	if(verbose) 
+												{		 	RCTypeArray Types; 
+														 	MOFF;cout << "array_struct_item_start                    " << Types.GetName($1) << " " << $2 << endl;MON;
+												}
+											$$ = new ArrayStructItem($1, $2);
+										}
+;
+len_declaration:
+	L_BYTE								{	$$ = L_BYTE;}
+|	L_WORD								{	$$ = L_WORD;}
+;
+struct_type_struct_item:
+	L_STRUCT L_LABEL					{	if(verbose) {	MOFF;cout << "struct_type_struct_item                    " << $2 << endl;MON;}
+											$$ = new StructTypeStructItem($2);
+										}
+;
+struct_array_struct_item:
+	struct_array_struct_item_base		{	$$ = $1;}
+|	L_LEN len_declaration struct_array_struct_item_base
+										{	if(verbose) {	RCTypeArray Types; MOFF;cout << "struct_array_struct_item                   - Setting Size to " << Types.GetName($2) << endl;MON;}
+											$3->iLenType = $2; $$ = $3;
+										}
+;
+struct_array_struct_item_base:
+	L_STRUCT L_LABEL '[' ']'			{	if(verbose) {	MOFF;cout << "struct_array_struct_item_base              " << $2 << endl;MON;}
+											$$ = new StructArrayStructItem($2);
+										}
+|	L_STRUCT L_LABEL '[' natural_expression ']'
+										{	if(verbose) {	MOFF;cout << "struct_array_struct_item_base              " << $2 << " " << $4 << endl;MON;}
+											$$ = new StructArrayStructItem($2, $4);
+										}
+;
+/*********************************************************************/
+/* RESOURCE statement                                                */
+/*********************************************************************/
+resource_statement:
+	resource_statement_start '{' resource_item_list '}'
+	    {	
+	    pResourceHeader->AddDefault();
+	    CurrentId+=CurrentIdStep;
+	    if(verbose) { MOFF;cout << "Resource ID "<< CurrentId << endl << Divider << "\n" << * pResourceHeader << Divider << endl;MON;}
+	    pResourceHeader->SetResourceId(*pResourceNameIds,CurrentId,FormatIdAsHex);
+	    pG->Index.Add(pResourceHeader);
+		
+		CheckStructUsage();
+
+		pUsedLabelsArray->Empty();
+
+	    pResourceHeader = NULL;
+	    }
+;
+resource_statement_start:
+	L_GLOBAL resource_statement_start_names {}	/* Ignore GLOBAL (obsolete feature).*/
+|	L_LOCAL  resource_statement_start_names
+	    {	
+	    if(verbose) { MOFF;cout << "resource_statement_start                   LOCAL" << endl;MON;}
+		    assert(pResourceHeader != NULL);
+		    pResourceHeader->iLocal = 1;
+	    }
+|	resource_statement_start_names {}
+;
+resource_statement_start_names:
+	L_RESOURCE L_LABEL L_LABEL			{	if(verbose) {	MOFF;cout << "resource_statement_start_names             " << $2 << " " << $3 << endl;MON;}
+											assert(pResourceHeader == NULL);
+											pResourceHeader = new ResourceHeader($3);
+											pCurrentRIA = & (pResourceHeader->iRIA);
+											REGISTER_LINE;
+											if(pResourceNameIds->IsStored($3))
+											{
+												ErrorHandler::OutputErrorLine("Resource with this name encountered already");
+												exit(1);
+											}
+											pCurrentRIA->FillFromStruct($2);
+											pG->AllIdentifiers.Add(new String($3)); // Add label to store
+										}
+|	L_RESOURCE L_LABEL					{	if(verbose) {	MOFF;cout << "resource_statement_start_names             " << $2 << " <Resource not named>" << endl;MON;}
+											assert(pResourceHeader == NULL);
+											pResourceHeader = new ResourceHeader;
+											pCurrentRIA = & (pResourceHeader->iRIA);
+											REGISTER_LINE;
+											pCurrentRIA->FillFromStruct($2);
+										}
+;
+resource_item_list:
+	resource_item_list resource_item ';'{	if(verbose) {	MOFF;cout << "resource_item_list" << endl;MON;}}
+|	resource_item_list comment_tag resource_item ';'{	if(verbose) {	MOFF;cout << "tagged resource_item_list" << endl;MON;}}
+|	resource_item_list error ';'		{	yyerrok; yyclearin; }
+|	/* Nothing */
+;
+resource_item:
+	L_LABEL '=' simple_initialiser		{	if(verbose) {	MOFF;cout << "resource_item                              " << $1 << " " << $3 << endl;MON;}
+											REGISTER_LINE;/****************************************************************/
+											pCurrentRIA->Set($1, $3);
+										}
+|	resource_simple_array_item
+|	struct_resource_item
+|	struct_array_resource_item
+;
+resource_simple_array_item:
+	L_LABEL '=' '{' '}'                 
+	    {	
+	    if (verbose) 
+		{ MOFF;cout << "resource_simple_array_item                 " << $1 << endl;MON;} 
+	    }
+|	L_LABEL '=' '{' simple_initialiser_list '}'
+	    {	
+	    if (verbose) 
+		{ MOFF;cout << "resource_simple_array_item                 " << $1 << " with simple_initialiser_list" << endl;MON;}
+	    REGISTER_LINE;
+	    pCurrentRIA->Set($1, * $4);
+	    delete $4;
+	    }
+;
+
+/*---------------------------------------------------------------------------*/
+/* A note about RIAStack, SRIStack and pCurrentRIA.                          */
+/*                                                                           */
+/*  RIA stands for Resource Item Array.                                      */
+/*  SRI stands for Struct Array Resource Item.                               */
+/*                                                                           */
+/*  A push to RIAStack is made when dropping inside a STRUCT or STRUCT[] in  */
+/*  order to set values for the components. When this happens pCurrentRIA is */
+/*  set to the RIA for the STRUCT or last item of the STRUCT[].              */
+/*                                                                           */
+/*  pCurrentRIA is set to the result of popping from RIAStack when a closing */
+/*  brace is reached.                                                        */
+/*                                                                           */
+/*  A push is made to SRIStack when going into an item for a STRUCT[]. On    */
+/*  reaching a closing brace the STRUCT[] is popped off the SRIStack. An new */
+/*  item may then be added to this array.                                    */
+/*---------------------------------------------------------------------------*/
+struct_resource_item:
+	struct_resource_item_start resource_item_list '}'
+										{	if(verbose) {	MOFF;cout << "struct_resource_item" << endl;MON;}
+											pCurrentRIA = pG->RIAStack.Pop();
+										}
+;
+struct_resource_item_start:
+	L_LABEL '=' L_LABEL '{'	{	if(verbose) {	MOFF;cout << "struct_resource_item_start                 " << $1 << " " << $3 << endl;MON;}
+											REGISTER_LINE;
+											pCurrentRIA->Set($1, $3);
+											String * thisLabel = new String($1);
+											pUsedLabelsArray->Add(thisLabel);
+											// in here add the label to a temp store
+											pG->RIAStack.Push(pCurrentRIA);
+											pCurrentRIA = pCurrentRIA->Find($1)->GetRIA();
+										}
+;
+struct_array_resource_item:
+	struct_array_resource_item_start struct_array_resource_item_list_top '}'
+										{	if(verbose) {	MOFF;cout << "struct_array_resource_item" << endl;MON;}
+											pG->SRIStack.Pop();
+										}
+|	struct_array_resource_item_start struct_array_resource_item_list_top error
+										{	pG->SRIStack.Pop();}
+;
+struct_array_resource_item_start:
+	L_LABEL '=' '{'	L_LABEL '{'			{	if(verbose) {	MOFF;cout << "struct_array_resource_item_start           " << $1 << " " << $4 << endl;MON;}
+											ResourceItem * p = pCurrentRIA->Find($1);
+											pG->SRIStack.Push(p);
+											REGISTER_LINE;
+											String * thisLabel = new String($1);
+											pUsedLabelsArray->Add(thisLabel);
+											// in here add the label to a temp store
+											p->Set($4);
+											pG->RIAStack.Push(pCurrentRIA);
+											pCurrentRIA = p->GetRIA();
+										}
+;
+struct_array_resource_item_list_top:
+	struct_array_resource_item_list_top_start
+|	struct_array_resource_item_list_top_start ',' struct_array_resource_item_list
+|	struct_array_resource_item_list_top_start ',' error
+;
+struct_array_resource_item_list_top_start:
+	resource_item_list '}'				{	if(verbose) {	MOFF;cout << "struct_array_resource_item_list_top        " << endl;MON;}
+											pCurrentRIA = pG->RIAStack.Pop();
+										}
+;
+struct_array_resource_item_list:
+	struct_array_resource_item_list_item
+|	struct_array_resource_item_list ',' struct_array_resource_item_list_item
+;
+struct_array_resource_item_list_item:
+	struct_array_resource_item_list_item_start resource_item_list '}'
+										{	if(verbose) {	MOFF;cout << "struct_array_resource_item_list_item       " << endl;MON;}
+											pCurrentRIA = pG->RIAStack.Pop();
+										}
+;
+struct_array_resource_item_list_item_start:
+	L_LABEL '{'							{	if(verbose) {	MOFF;cout << "struct_array_resource_item_list_item_start " << $1 << endl;MON;}
+											ResourceItem * p = pG->SRIStack.Peek();
+											REGISTER_LINE;
+											p->Set($1);
+											pG->RIAStack.Push(pCurrentRIA);
+											pCurrentRIA = p->GetRIA();
+										}
+;
+
+
+/*****************************************************************/
+/* simple_initialiser and simple_initialiser_list                */
+/*****************************************************************/
+simple_initialiser:
+	L_NUM_FLOAT
+|	L_CHAR_LITERAL  
+	    { 
+	    // convert literal to unsigned long value of 1st character
+		SetCharacterLiteral($$, $1);
+	    }
+|	string_expression
+|	natural_expression
+; 
+simple_initialiser_list:
+	simple_initialiser  
+	    {
+	    if(verbose) 
+		{	
+		MOFF;cout << "simple_initialiser_list                    - single string " << $1 << endl;MON;
+		}
+		
+	    $$ = new StringArray;
+	    $$->Add(new String($1) );
+	    }
+|	simple_initialiser_list ',' simple_initialiser	
+										{	if(verbose) {	MOFF;cout << "simple_initialiser_list                    - part of list " << $3 << endl;MON;}
+											assert($1 != NULL);
+											$1->Add(new String($3 ) );
+											$$ = $1;
+										}
+;
+
+natural_expression:
+	natural_expression_numeric			{	String s(NumericValue::ltoa($1) ); strcpy($$, s.GetAssertedNonEmptyBuffer() ); }
+;	
+natural_expression_numeric:
+	L_NUM_NATURAL						{	if(verbose) {	MOFF;cout << "Converting number " << $1 << endl;MON;}
+											REGISTER_LINE;
+											NumericValue v($1, L_LONG); $$ = (long)v.GetULong();
+										}
+|	natural_expression_numeric '+' natural_expression_numeric	{	$$ = $1 + $3;	}
+|	natural_expression_numeric '-' natural_expression_numeric	{	$$ = $1 - $3;	}
+|	natural_expression_numeric '*' natural_expression_numeric	{	$$ = $1 * $3;	}
+|	natural_expression_numeric '/' natural_expression_numeric	{	$$ = $1 / $3;	}
+|	natural_expression_numeric '|' natural_expression_numeric	{	$$ = $1 | $3;	}
+|	'-' natural_expression_numeric %prec UMINUS					{	if (!NumericValue::CheckSigned($2,L_LONG))
+																	{
+																	REGISTER_LINE;
+																	ErrorHandler::OutputErrorLine("Signed value too low");
+																	exit(1);
+																	}
+																	$$ = - $2;		
+																}
+|	'(' natural_expression_numeric ')'							{	$$ = $2;		}
+;
+string_expression:
+	string_expression_item  
+|	string_expression_item string_expression {
+	    if (strlen($$)+strlen($2) > sizeof($$)-1)
+		{
+		REGISTER_LINE;
+		ErrorHandler::OutputErrorLine("String expression is too long");
+		exit(1);
+		}
+	    strcat($$, $2);
+	    }
+;
+string_expression_item:
+	L_STRING_LITERAL
+|	character_code_expression
+|	L_LABEL 
+	    {
+		const char * fileName = (*ErrorHandler::GetFileName()).GetBuffer();
+		int lineNumber = ErrorHandler::GetLineNumber();
+		QualifiedString * thisLabel = new QualifiedString($1, new String(fileName), lineNumber);
+		// store the label in the UsedIdentifiers array for checking
+		// whether label was declared
+		pG->UsedIdentifiers.Add(thisLabel);
+
+	    if (pG->EnumValues.IsStored($1))
+			{
+			sprintf($$, "%d", (int)(pG->EnumValues.FindId($1)));
+			}
+		else if (pG->RlsNameIndex.count($1)) // if rls item has already been defined
+			{
+			// Found a reference to an rls_string.
+			RlsValue &rv = pG->RlsValues[pG->RlsNameIndex[$1]];
+			++rv.iCitationCount; // iCitationCount counts the number of times this rls value has been referneced
+			// Warn for multiple uses if 'multi' keyword not used.
+			if (1 < rv.iCitationCount && rv.iCardinality == ERlsCardinalitySingle)
+				{
+				Message * message = pG->Messages.GetEntry(LT_001);
+				String fileLine = *(rv.iFileName);
+				if(message->GetActivated())
+				{
+					pGL->AddWarningToStore(fileLine, rv.iLineNumber, message->GetMessageOutput());
+				}
+				REGISTER_LINE;
+				if (!pG->WarningMultiExplained)
+					{
+					Message * message = pG->Messages.GetEntry(LT_002);
+					fileLine = String(*(pFileLineHandler->GetCurrentFile()));
+					if(message->GetActivated())
+						{
+						pGL->AddWarningToStore(fileLine, pFileLineHandler->GetErrorLine(* pCurrentLineNumber), message->GetMessageOutput());
+						pG->WarningMultiExplained = true;
+						}
+					}
+				}
+			switch (rv.iType)
+				{
+				// Strings and numbers are just copied to the next layer up.
+			case ERlsString:
+			case ERlsString8:
+			case ERlsByte:
+			case ERlsWord:
+			case ERlsLong:
+			case ERlsDouble:
+				strcpy($$, rv.iValue.GetBuffer());
+				break;
+				// Anything else is a character: this is converted to a number.
+			case ERlsStringChar:
+			case ERlsByteChar:
+			case ERlsWordChar:
+			case ERlsLongChar:
+				SetCharacterLiteral($$, rv.iValue);
+				break;
+			default:
+				Message * message = pG->Messages.GetEntry(LT_031);
+				if(message->GetActivated())
+					{
+					ErrorHandler::OutputErrorLine(message->GetMessageOutput());
+					exit(1);
+					}
+				break;
+				}
+			}
+		else
+			{
+			/*
+			Could be a reference to another resource, perhaps even a forward reference:
+			the OverwriteLink functions do FindId again when writing out the data.
+			Sadly this also permits things which are really syntax errors, inadvertently
+			converting labels into string literals..
+			*/
+			}
+	    }
+;
+character_code_expression:
+	'<' natural_expression_numeric '>'  
+	    {	
+	    REGISTER_LINE;
+	    if($2 < 0 || ($2 > 255 && TargetCharacterSet != String::Unicode))
+		{
+		    ErrorHandler::OutputErrorLine("Character code must be a number in the range 0 to 255.");
+		    exit(1);
+		}
+	    if (TargetCharacterSet != String::Unicode)
+		{
+		* $$ = char($2); * ($$ + 1) = '\0'; 
+		} 
+	    else
+		{
+		if (SourceCharacterSet == String::CP1252)
+		    {
+		    if ( ($2 >= 0x80) && ($2 <= 0x9F ) ) // 80-9F are illegal Unicode values.
+			{
+			ErrorHandler::OutputErrorLine("Warning: Deprecated non-unicode value in source stream");
+			}
+		    * $$ = char(UnicodeEscape);
+		    asUTF8($$ + 1, $2);
+		    }
+		else
+		if (SourceCharacterSet == String::UTF8)
+		    {
+		    asUTF8($$, $2);
+		    }
+		else
+		    {
+		    // Unsatisfactory, but do people use other character sets?
+		    if ($2 > 255)
+			{
+			ErrorHandler::OutputErrorLine("Don't know how to handle character > 255");
+			}
+		    * $$ = char($2); * ($$ + 1) = '\0'; 
+		    }
+		}
+	    }
+;
+
+
+/*****************************************************************/
+/* name_statement                                                */
+/*****************************************************************/
+name_statement:
+	L_NAME L_LABEL
+	    {
+	    REGISTER_LINE;
+	    SetIdFromName($2);
+	    }
+|	L_NAME L_STRING_LITERAL
+	    {
+	    REGISTER_LINE;
+	    SetIdFromName($2);
+	    }
+;
+
+
+/*****************************************************************/
+/* uidX_statement                                                */
+/*****************************************************************/
+uidX_statement:
+	L_UID_TWO natural_expression_numeric
+		{
+		REGISTER_LINE;
+		if ($2 == 0)
+			{ ErrorHandler::OutputErrorLine("UID2 must be non-zero"); exit(1); }
+		if (Uid2 != 0)
+			{ ErrorHandler::OutputErrorLine("Warning: overwriting previous UID2 value"); }
+		Uid2=$2;
+		if(verbose) 
+			{ MOFF;cout << "uidX_statement  UID2                       " << Uid2 << endl;MON;}
+		}
+|	L_UID_THREE natural_expression_numeric
+		{
+		REGISTER_LINE;
+		if ($2 == 0)
+			{ ErrorHandler::OutputErrorLine("UID3 must be non-zero"); exit(1); }
+		if (Uid3 != 0)
+			{ ErrorHandler::OutputErrorLine("Warning: overwriting previous UID3 value"); }
+		Uid3=$2;
+		if(verbose) 
+			{ MOFF;cout << "uidX_statement  UID3                       " << Uid3 << endl;MON;}
+		}
+;
+ 
+ 
+/*****************************************************************/
+/* character_set_statement                                       */
+/* Defines the SOURCE character set. Note that Unicode is a      */
+/* character set id, but we can't read Unicode source            */
+/* (because LEX and YACC can't handle it)                        */
+/*****************************************************************/
+
+character_set_statement:
+	L_CHARACTER_SET L_LABEL		{	if(verbose) {	MOFF;cout << "character_set_statement                    " << $2 << endl;MON;}
+											REGISTER_LINE;
+											SourceCharacterSet = CharacterSetID($2);
+											if ( SourceCharacterSet == String::UNKNOWN )
+											{
+												String err = "Warning: Unrecognised character set name '";
+												err += $2;
+												err += "'";
+												ErrorHandler::OutputErrorLine(err);
+											}
+											if ( SourceCharacterSet == String::Unicode )
+											{
+											    SourceCharacterSet = String::UNKNOWN;
+												ErrorHandler::OutputErrorLine("Unicode source is unsupported");
+											}
+										}
+;
+
+
+
+/*****************************************************************/
+/* offset_statement                                              */
+/*****************************************************************/
+offset_statement:
+	L_OFFSET natural_expression			{	if(verbose) {	RCTypeArray Types;
+															MOFF;cout << "offset_statement                           " << $2 << endl;MON; }
+											REGISTER_LINE;
+										 	CurrentId=((long) NumericValue($2, L_LONG).GetULong() );
+										}
+;
+
+/*****************************************************************/
+/* system_statement                                              */
+/*****************************************************************/
+system_statement:
+	L_SYSTEM							{	if(verbose) {	MOFF;cout << "system_statement" << endl;MON;}
+											CurrentIdStep=-1;
+										}
+;
+
+/*****************************************************************/
+/* enum_statement                                                */
+/*****************************************************************/
+enum_statement:
+    enum_statement_start enum_list '}'
+|	enum_statement_start enum_list '}' ';'
+;
+enum_statement_start:
+	L_ENUM L_LABEL '{'					 
+	    {	
+	    if(verbose) 
+		{ MOFF;cout << "enum_statement" << endl;MON;} 
+	    CurrentEnumName = $2;
+	    CurrentEnumValue=0;
+	    }
+|	L_ENUM '{'						
+	    {	
+	    if(verbose) 
+		{ MOFF;cout << "enum_statement" << endl;MON;} 
+	    CurrentEnumName = "";
+	    CurrentEnumValue=0;
+	    }
+;
+
+enum_list_entry:
+	L_LABEL                             
+		{	
+		pG->EnumValues.Add($1, CurrentEnumValue++);
+		pG->AllIdentifiers.Add(new String($1)); // Add label to store
+		}
+|	L_LABEL '=' simple_initialiser      
+	    {	
+	    CurrentEnumValue = atol($3);
+	    pG->EnumValues.Add($1, CurrentEnumValue);
+	    CurrentEnumValue++;			// Increment so that next field has value ($3+1)
+		pG->AllIdentifiers.Add(new String($1)); // Add label to store
+	    }
+;
+
+
+enum_list:
+		maybe_comment_tag enum_list_entry
+|		enum_list ',' maybe_comment_tag enum_list_entry
+;
+
+/************************/
+/* rls_xxxx statement */
+/************************/
+rls_item_statement:
+		rls_string_item rls_qualifiers rls_label string_expression
+		{
+		pG->RlsNameIndex[$3] = pG->RlsValues.size();
+		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
+			ErrorHandler::GetLineNumber(), $4, $1,
+			$2.iCardinality, $2.iMaxLength));
+		if($2.iMaxLength
+			< String($4).ExportLength(TargetCharacterSet,SourceCharacterSet))
+			{
+			Message * message = pG->Messages.GetEntry(LT_032);
+			if(message->GetActivated())
+				{
+				ErrorHandler::OutputErrorLine(message->GetMessageOutput());
+				exit(1);
+				}
+			}
+		}
+|		rls_string_item rls_qualifiers rls_label L_CHAR_LITERAL	/* This section is only for compatibility */
+		{
+		Message * message = pG->Messages.GetEntry(LT_033);
+		String fileName = *(pFileLineHandler->GetCurrentFile());
+		int lineNumber = pFileLineHandler->GetErrorLine(* pCurrentLineNumber);
+		if(message->GetActivated())
+			{
+			pGL->AddWarningToStore(fileName, lineNumber, message->GetMessageOutput());
+			}
+		//...
+		/* Produce a warning "rls_string used for character constant: use rls_long, rls_word or rls_byte" */
+		pG->RlsNameIndex[$3] = pG->RlsValues.size();
+		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
+			ErrorHandler::GetLineNumber(), $4, ERlsStringChar,
+			$2.iCardinality));
+		}
+|		rls_float_item rls_cardinality rls_label L_NUM_FLOAT
+		{
+		pG->RlsNameIndex[$3] = pG->RlsValues.size();
+		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
+			ErrorHandler::GetLineNumber(), $4, $1,
+			$2.iCardinality));
+		}
+|		rls_num_item rls_cardinality rls_label L_NUM_NATURAL
+		{
+		pG->RlsNameIndex[$3] = pG->RlsValues.size();
+		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
+			ErrorHandler::GetLineNumber(), $4, $1,
+			$2.iCardinality));
+		}
+|		rls_num_item rls_cardinality rls_label L_CHAR_LITERAL
+		{
+		TRlsType rlsCharType = $1 == ERlsByte? ERlsByteChar
+			: ( $1 ==  ERlsWord? ERlsWordChar : ERlsLongChar );
+		pG->RlsNameIndex[$3] = pG->RlsValues.size();
+		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
+			ErrorHandler::GetLineNumber(), $4, rlsCharType,
+			$2.iCardinality));
+		}
+;
+
+rls_label: L_LABEL
+		{
+		// Register line even if no warning here so that
+		// the rls_ item knows which line the label was on.
+		// Without this, the line registered would be the
+		// line following the declaration.
+		REGISTER_LINE;
+		strcpy($$, $1);
+
+		if (pG->RlsNameIndex.count($1) != 0)
+			{
+			Message * message = pG->Messages.GetEntry(LT_003);
+			if(message->GetActivated())
+				{
+				ErrorHandler::OutputErrorLine(message->GetMessageOutput());
+				}
+			}
+		pG->AllIdentifiers.Add(new String($1)); // Add label to store
+		}
+
+rls_qualifiers:
+		'<' L_NUM_NATURAL '>' rls_cardinality
+		{
+		NumericValue v($2, L_LONG);
+		$$.iMaxLength = v.GetULong();
+		$$.iCardinality = $4.iCardinality;
+		}
+|		rls_cardinality
+		{ $$ = $1; }
+;
+
+rls_cardinality:
+		L_MULTI
+		{
+		$$.iMaxLength = 0xFFFFFFF;
+		$$.iCardinality = ERlsCardinalityMultiple;
+		}
+|
+		{
+		$$.iMaxLength = 0xFFFFFFF;
+		$$.iCardinality = ERlsCardinalitySingle;
+		}
+;
+
+rls_string_item:
+		L_RLS_STRING
+		{ $$ = ERlsString; }
+|		L_RLS_STRING8
+		{ $$ = ERlsString8; }
+;
+
+rls_num_item:
+		L_RLS_BYTE
+		{ $$ = ERlsByte; }
+|		L_RLS_WORD
+		{ $$ = ERlsWord; }
+|		L_RLS_LONG
+		{ $$ = ERlsLong; }
+;
+
+rls_float_item:
+		L_RLS_DOUBLE
+		{ $$ = ERlsDouble; }
+;
+
+/************************/
+/* comment tags         */
+/************************/
+maybe_comment_tag:
+	comment_tag
+|
+;
+
+comment_tag:
+	L_TAG_START tag_line L_TAG_END {ErrorHandler::Register(pFileLineHandler->GetCurrentFile(), pFileLineHandler->GetErrorLine(*pCurrentLineNumber)); }
+   ;
+
+tag_line:
+	tag_line tag_word
+
+|
+;
+
+tag_word:
+ 	L_TAG_NEW_LINE	{ pGL->StoreComment($1);	}
+|	L_TAG_COMMAND	{ pGL->StoreComment($1);	}
+|	L_TAG_WORD		{ pGL->StoreComment($1);	}
+;
+
+%%
+
+// Function section
+// ================
+
+void asUTF8(char* aUtf8, int aUnicode)
+	{
+	if ( aUnicode > 0xffff )
+		{
+		if ( aUnicode > 0x10ffff )
+		{
+		ErrorHandler::OutputErrorLine("Surrogate character code must be a number in the range 0x10000 to 0x10ffff");
+		exit(1);		
+		}
+		
+		UTF16 high = (UTF16)(0xD7C0 + (aUnicode >> 10));			// high surrogate
+		UTF16 low = (UTF16)(0xDC00 | (aUnicode & 0x3FF));			// low surrogate
+	
+		*aUtf8++ =(char)(0xe0|(high>>12));
+		*aUtf8++ =(char)(0x80|((high>>6)&0x3f));
+		*aUtf8++ =(char)(0x80|(high&0x3f));
+		*aUtf8++ =(char)(0xe0|(low>>12));
+		*aUtf8++ =(char)(0x80|((low>>6)&0x3f));
+		*aUtf8   =(char)(0x80|(low&0x3f));
+		}
+	else if ((aUnicode & 0xff80) == 0x0000)
+		{
+		*aUtf8 = (char)aUnicode;
+		}
+	else if ((aUnicode & 0xf800) == 0x0000)
+		{
+		*aUtf8++ =(char)(0xc0|(aUnicode>>6));
+		*aUtf8   =(char)(0x80|(aUnicode&0x3f));
+		}
+	else
+		{
+		*aUtf8++ =(char)(0xe0|(aUnicode>>12));
+		*aUtf8++ =(char)(0x80|((aUnicode>>6)&0x3f));
+		*aUtf8   =(char)(0x80|(aUnicode&0x3f));
+		}
+	*++aUtf8 = '\0';
+	}
+
+
+String::CharacterSet CharacterSetID( const String & character_set_name )
+// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+// Return a character set ID from a character set name.  The value UNKNOWN
+// is returned if the name is not recognised.
+// ----------------------------------------------------------------------------
+{
+	String::CharacterSet ids[] = { String::ISOLatin1, String::ASCII, String::CP1252
+	                              , String::CP850, String::ShiftJIS, String::Unicode
+								  , String::UTF8
+								  , String::UNKNOWN
+								 };
+	String names[] = { "ISOLATIN1", "ASCII", "CP1252", "CP850", "SHIFTJIS", "UNICODE", "UTF8" };
+
+	for ( int i=0; ids[i]!=String::UNKNOWN; i++ )
+	{
+		if ( names[i] == character_set_name ) return ids[i];
+	}
+
+	return String::UNKNOWN;
+
+} // end of CharacterSetID code
+
+void SetIdFromName( const String & NameStatementValue)
+	{
+	// space 	0
+	// A		1
+	// B		2
+	// ...
+	// Z		26
+	//
+	// ABCD corresponds to the number 4321 which becomes ( (4*27 + 3) * 27 + 2) * 27 + 1.
+	
+	if(verbose) 
+		{ MOFF;cout << "name_statement                             " << NameStatementValue << endl;MON;}
+	if ( NameStatementValue.Length() > 4)
+		{
+		ErrorHandler::OutputErrorLine( "Name must be no longer than four characters");
+		exit( 1);
+		}
+	
+	long NewId = 0;
+	
+	for( unsigned long i = 0; i < NameStatementValue.Length(); i++)
+		{
+		NewId *= 27;
+		if ( isalpha( NameStatementValue[i]) )
+			NewId += toupper( NameStatementValue[i]) - 'A' + 1;
+		}
+
+	CurrentId = NewId << 12;
+	FormatIdAsHex = 1;
+	if(verbose) 
+		{ MOFF;cout << "Current id                                " << CurrentId << endl;MON;}
+	}
+
+void RlsUnusedWarnings()
+	{
+	TNameIndex::iterator end = pG->RlsNameIndex.end();
+	for (TNameIndex::iterator i = pG->RlsNameIndex.begin(); i != end; ++i)
+		{
+		int index = i->second;
+		RlsValue& v = pG->RlsValues[index];
+		if (v.iCitationCount == 0)
+			{
+			Message * message = pG->Messages.GetEntry(LT_004);
+			String fileLine = *(v.iFileName);
+			if(message->GetActivated())
+				{
+				pGL->AddWarningToStore(fileLine, v.iLineNumber, message->GetMessageOutput());
+				}
+			}
+		}
+	}
+
+int ParseSourceFile(FILE* aFile, unsigned short aYYDebug)
+	{
+	// Set up various global pointers which refer to the pG structure
+	pSHA = & (pG->SHA);
+	pFileLineHandler = & (pG->FileLineHandler);
+	pResourceNameIds = & (pG->ResourceNameIds);
+
+	pScan = new rcscan(pG->FileLineHandler, aFile);
+
+	yydebug = aYYDebug;
+	pCurrentLineNumber = &yylineno;
+	int ReturnValue = yyparse();
+
+	RlsUnusedWarnings();
+
+	int bScanErrorFound = pScan->ErrorWasFound();
+
+	delete pScan;
+	pScan = NULL;
+
+	if(ReturnValue != 0)
+		return ReturnValue;
+	
+	if(bScanErrorFound)
+		return 1;
+	
+	return 0;	// successful parse - parse tree now in the pG data structure
+	}
+
+
+void CheckStructUsage()
+	{
+	ResourceItemArrayIterator	nextRI( *pCurrentRIA);
+	ResourceItem * pRI;
+	while ( ( pRI = nextRI() ) != NULL)
+		{
+		int resourceItemType = pRI->GetResourceItemType();
+		String resourceItemLabel = pRI->GetLabel();
+		if( (resourceItemType == EStructTypeResourceItem) || (resourceItemType == EStructArrayResourceItem) )
+			{
+			StringArrayIterator nextLabel( *pUsedLabelsArray);
+			String * pLabel;
+			bool flag = false;
+			while ( ( ( pLabel = nextLabel() ) != NULL ) && (! flag) )
+				{
+				StringLess stringCompare;
+				if( !stringCompare(resourceItemLabel,*pLabel) && !stringCompare(*pLabel,resourceItemLabel) )
+					{
+					flag = true;
+					}
+				}
+			if(! flag)
+				{
+				if(resourceItemType == EStructTypeResourceItem)
+					{
+					Message * message = pG->Messages.GetEntry(LT_046);
+					if(message->GetActivated())
+						{
+						String comment = message->GetMessageOutput();
+						comment += "'";
+						comment += resourceItemLabel;
+						comment += "'";
+						ErrorHandler::OutputErrorLine(comment);
+						}
+					}
+				else
+					{
+					Message * message = pG->Messages.GetEntry(LT_047);
+					if(message->GetActivated())
+						{
+						String comment = message->GetMessageOutput();
+						comment += "'";
+						comment += resourceItemLabel;
+						comment += "'";
+						ErrorHandler::OutputErrorLine(comment);
+						}
+					}
+				}
+			}
+		}
+	}
+
+int yywrap()
+{
+  return 1;
+}
+
+/* Called by yyparse on error */
+#include <stdarg.h>
+void yyerror (const char *s, ...)
+{
+  va_list list;
+  va_start(list, s);
+  pScan->yyerror(const_cast<char*>(s), list);
+  va_end(list);
+}
+
+
--- a/bintools/rcomp/src/main.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/rcomp/src/main.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,568 +1,630 @@
-/*
-* Copyright (c) 2000-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include <assert.h>
-#include <stdio.h>
-#include <string.h>
-
-#include "unistd.h"
-
-#if defined( __MSVCDOTNET__) || defined(__TOOLS2__)
-#include <iostream>
-using std::cout;
-using std::endl;
-using std::cerr;
-#else //!__MSVCDOTNET__
-#ifndef __LINUX__
-#include <io.h>
-#endif //!__LINUX__
-#endif //__MSVCDOTNET__
-
-#include "RESOURCE.H"
-#include "DATATYPE.H"
-#include "MEM.H"     
-#include "RCBINSTR.H"
-#include "NUMVAL.H"  
-#include "ERRORHAN.H"
-#include "FILEACC.H" 
-#include "VERSION.H" 
-#include "CTABLE.H"  
-#include "main.h"
-#include "TOKENS.H"
-#include "localise.h"
-#include "qualifar.h"
-#include "messages.h"
-
-extern NameIdMap* pResourceNameIds;
-extern long CurrentId;
-
-void WriteHeaderFile(FILE* aRSG, IndexTable& aIndex)
-	{
-	IndexTableIterator next(aIndex);
-	IndexTableItem * p;
-	while( ( p = next() ) != NULL)
-		{
-		ResourceHeader& r=p->Resource();
-		if (r.iLabel.Length()>0 && !r.iLocal)
-			{
-			r.iLabel.Upper();
-			if (r.iFormatAsHex)
-				fprintf(aRSG, "#define %-41s 0x%x\n", r.iLabel.GetAssertedNonEmptyBuffer(), r.iResourceId);
-			else
-				fprintf(aRSG, "#define %-41s %d\n", r.iLabel.GetAssertedNonEmptyBuffer(), r.iResourceId);
-			}
-		}
-	}
-
-void WriteBitArrayOfResourcesContainingCompressedUnicode(RCBinaryStream& aRSC, const IndexTable& aIndex)
-	{
-	IndexTableIterator next(aIndex);
-	unsigned char bitBuffer = 0;
-	int numberOfBitsInBuffer = 0;
-	for (;;)
-		{
-		IndexTableItem* const p = next();
-		if (p == NULL)
-			{
-			if (numberOfBitsInBuffer > 0)
-				{
-				aRSC.Write(&bitBuffer, 1);
-				}
-			break;
-			}
-		if (p->Resource().ContainsCompressedUnicode())
-			{
-			bitBuffer |= (1 << numberOfBitsInBuffer);
-			}
-		++numberOfBitsInBuffer;
-		if (numberOfBitsInBuffer == 8)
-			{
-			aRSC.Write(&bitBuffer, 1);
-			bitBuffer = 0;
-			numberOfBitsInBuffer = 0;
-			}
-		}
-	}
-
-void WriteBinaryResourceData(RCBinaryStream& aRSC, IndexTable& aIndex, int& aSizeOfLargestResourceWhenUncompressed, const char* aDumpDirectory)
-	{
-	IndexTableIterator next(aIndex);
-	IndexTableItem * p;
-	int resourceIndex=1;
-	while( ( p = next() ) != NULL)
-		{
-		char* dumpFile=NULL;
-		if (aDumpDirectory!=NULL)
-			{
-			dumpFile=new char[strlen(aDumpDirectory)+20];
-			strcpy(dumpFile, aDumpDirectory);
-			char resourceIndexAsString[20];
-			sprintf(resourceIndexAsString, "%d", resourceIndex);
-			strcat(dumpFile, resourceIndexAsString);
-			}
-		p->SetOffset(aRSC.GetPosition()); // record start of this resource in the index
-		p->Resource().StreamOut(aRSC, aSizeOfLargestResourceWhenUncompressed, dumpFile); // write out binary form of resource
-		delete [] dumpFile;
-		++resourceIndex;
-		}
-	}
-
-void WriteResourceFile(RCBinaryStream& aRSC, IndexTable& aIndex, bool aThirdUidIsOffset, const char* aDumpDirectory)
-	{
-	char flags=0;
-	if (aThirdUidIsOffset)
-		{
-		flags|=0x01;
-		}
-	aRSC << flags; // these flags are to be used only by a dictionary-compressing program rather than to be used directly by Bafl when reading non-dictionary-compressed resource files (as output by Rcomp)
-	const int positionToOverWriteFrom=aRSC.GetPosition();
-	NumericValue twoByteSizeOfLargestResourceWhenUncompressed(L_WORD);
-	aRSC << twoByteSizeOfLargestResourceWhenUncompressed;
-	WriteBitArrayOfResourcesContainingCompressedUnicode(aRSC, aIndex); // simply makes space for the bit-array without writing anything sensible in it (as we don't yet know which resources will contain compressed Unicode)
-	int sizeOfLargestResourceWhenUncompressed=0;
-	WriteBinaryResourceData(aRSC, aIndex, sizeOfLargestResourceWhenUncompressed, aDumpDirectory);
-	aIndex.SetIndexOffset(aRSC.GetPosition());
-	aRSC << aIndex;
-	aRSC.SetPosition(positionToOverWriteFrom);
-	twoByteSizeOfLargestResourceWhenUncompressed=sizeOfLargestResourceWhenUncompressed;
-	aRSC << twoByteSizeOfLargestResourceWhenUncompressed;
-	WriteBitArrayOfResourcesContainingCompressedUnicode(aRSC, aIndex); // overwrites the bit array with correct data
-
-	if(verbose) 
-		{
-		MOFF; cout << aIndex; cout << endl; MON;
-		}
-	}
-
-void CheckLabels() // checks whether the labels that are used in the input have been declared
-	{
-	QualifiedStringArrayIterator nextLabel(pG->UsedIdentifiers);
-	QualifiedString * pLabel;
-	while ((pLabel = nextLabel() ) != NULL)
-		{
-		bool found = false; // gets set to true if the label in question is declared
-		StringArrayIterator nextDeclared(pG->AllIdentifiers);
-		String * pDeclared;
-		while ( ( (pDeclared = nextDeclared() ) != NULL) && ( ! found ))
-			{
-			StringLess stringCompare;
-			if( !stringCompare(*pDeclared,(*pLabel).GetEntry()) && !stringCompare((*pLabel).GetEntry(),*pDeclared) )
-				{ // this comparison returns true if the label is the same as the declared label
-				found = true;
-				}
-			}
-		if( ! found ) // if label hasn't been declared emit warning
-			{
-			Message * message = pG->Messages.GetEntry(LT_045);
-			String fileName = (*pLabel).GetFileName();
-			int lineNumber = (*pLabel).GetLineNumber();
-			if(message->GetActivated())
-				{
-				String comment = message->GetMessageOutput();
-				comment += (*pLabel).GetEntry();
-				ErrorHandler::OutputWholeLine(fileName, lineNumber, comment);
-				}
-			}
-		}
-	}
-
-
-/*  Tokenize expects a string in the following format:
- *	  \d{3}(,\d{3})*
- *  i.e. comma-separated three digit numbers. 
- *  The string should contain no whitespace.
- */
-void Tokenize(String aString)
-	{
-	int length = aString.Length();
-
-	for(int end=3; end<=length; end+=4)
-		{
-		String messageNumber = aString.ExtractSubString(end-3,end-1);
-		if(messageNumber.IsDecNatural())
-			{
-			Message * message = pG->Messages.GetTextEntry(messageNumber);
-			if(message != NULL)
-				{
-				message->SetActivationStatus(false);
-				}
-			}
-		}
-	}
-				
-
-void OutputHelp()
-	{
-	cerr << "Resource compiler version " << version << " (Build " << build << ") (C) 1997-2009 Nokia Corporation." << endl;
-	cerr << "Usage: rcomp [-vpul] [-force] [-oRSCFile] [-{uid2,uid3}] [-hHeaderFile] [-sSourceFile] [-iBaseInputFileName]" << endl;
-	cerr << "\tv" << "\tverbose" << endl;
-	cerr << "\tp" << "\tParser debugging" << endl;
-	cerr << "\tl" << "\tCheck localisation comments" << endl;
-	cerr << "\tforce" << "\tEmit localisation warnings even if no localisation tags are present" << endl;
-	cerr << "\tadd-defaults" << "\tAmend input rss/rpp file to add missing default localisation options" << endl;
-	cerr << endl;
-	cerr << "\tu" << "\tGenerate Unicode resource binary" << endl;
-	cerr << endl;
-	cerr << "If no source file is specified, the source will be read from standard input." << endl;
-	cerr << "(-i is used to specify the file given to the preprocessor this " << endl;
-	cerr << "    name is used in generating debug output.)" << endl;
-	}
-
-
-
-GlobalData *pG;
-GlobalLocalisationData *pGL;
-String InputBaseName;
-
-int main(int argc, char * argv[])
-	{
-	cout << "\n"; 
-	int vParam=0;
-	bool lParam = false; // used as flag to specify whether checking of localisation comment tags should be performed
-	bool lForce = false; // used as flag to force localisation output even if there are no localisation comments
-	bool lAddDefaults = false; // used as flag to add missing default localisation data to input rss/rpp file, this is not the default behaviour
-	logmemorysetting = 0;
-	unsigned short	pParam = 0;
-	String			DataOutputFileName;
-	String			HeaderOutputFileName;
-	String			MessageSuppressionList;
-	String			BasePath;
-	String			SourceFileName;
-	FILE *			pSourceFile;
-	char*			uidsParameter=NULL;
-	char*			dumpDirectory=NULL;
-	fpos_t			filePositionIndicator;
-	int				i;
-	
-	char *fullcommand = argv[0];
-	std::string s(fullcommand);
-
-	if(argc<=1)
-		{
-		OutputHelp();
-		exit(-1);
-		}
-	else
-		{
-		// Look through arguments for ones beginning with '-?'.
-		for(i = 1; i < argc; i++)
-			{
-			if(* argv[i] == '-')
-				{
-				char * settings = argv[i] + 1;
-			
-				if(strchr(settings, '?') )
-					{
-					OutputHelp();
-					exit(-1);
-					}
-				}
-			}
-
-		for(i = 1; i < argc; i++)
-			{
-			if(* argv[i] == '-')
-				{
-				char * settings = argv[i] + 1;
-			
-				if(* settings == 'o' || * settings == 'O')
-					{
-					DataOutputFileName = (settings + 1);
-					continue;
-					}
-
-				if(* settings == 'm' || * settings == 'M')
-					{
-					MessageSuppressionList = (settings + 1);
-					continue;
-					}
-					
-				if(* settings == 'h' || * settings == 'H')
-					{
-					HeaderOutputFileName = (settings + 1);
-					continue;
-					}
-
-				if(* settings == 'i' || * settings == 'I')
-					{
-					InputBaseName = (settings + 1);
-					String DriveAndDirectory = FileAccess::GetDriveAndDirectory(InputBaseName);
-					BasePath = FileAccess::FullPath(DriveAndDirectory);
-					continue;
-					}
-
-				if(* settings == 's' || * settings == 'S')
-					{
-					SourceFileName = (settings + 1);
-					continue;
-					}
-
-				if(* settings == '{')
-					{
-					uidsParameter = settings + 1;
-					char* temp = strchr(uidsParameter, ',');
-					if ((temp == NULL) || (temp == uidsParameter) || (strchr(temp + 1, ',') != NULL)) // check that there is *one* comma in this parameter (no more and no less), and that it is not the first thing immediately after the '{'
-						{
-						OutputHelp();
-						exit(-1);
-						}
-					*temp = ' ';
-					temp = strchr(uidsParameter, '}');
-					if ((temp == NULL) || (temp[1] != '\0'))
-						{
-						OutputHelp();
-						exit(-1);
-						}
-					*temp = ' ';
-					continue;
-					}
-
-				if(* settings == ':')
-					{
-					dumpDirectory=settings+1;
-					continue;
-					}
-
-				if(strchr(settings, 'u') || strchr(settings, 'U') )
-					{
-					SourceCharacterSet = String::CP1252;
-					TargetCharacterSet = String::Unicode;
-					}
-
-				if(strchr(settings, 'v') || strchr(settings, 'V') )
-					vParam = 1;
-				if(strchr(settings, 'p') || strchr(settings, 'P') )
-					pParam = 1;
-				if(strchr(settings, 'l') || strchr(settings, 'L') )
-					lParam = true;
-				if(strchr(settings, 'f') || strchr(settings, 'F') )
-					lForce = true;
-				if(strchr(settings, 'a') || strchr(settings, 'A') )
-					lAddDefaults = true;
-				}
-			}
-		}
-	if(SourceFileName.Length() == 0)
-		{
-		pSourceFile = stdin;
-		}
-	else 
-		{
-		if((pSourceFile = fopen(SourceFileName.GetAssertedNonEmptyBuffer(), "r") ) == NULL)
-			{
-			cerr << "Failed to open " << SourceFileName << endl;
-			exit(-2);
-			}
-		}
-	//Searchig for BOM signature which if found will be ignored
-
-	unsigned char buffer[3];
-	fread( buffer, sizeof( char ), 3, pSourceFile);
-	
-	if((buffer[0]!=239) && (buffer[1]!=187) && (buffer[2]!=191))
-		{
-		// BOM not found. Set the file-position indicator to 0
-		filePositionIndicator = fpos_t();
-		if(fsetpos(pSourceFile, &filePositionIndicator) !=0)
-			{
-			perror("fsetpos error");
-			} 
-		}	
-	verbose = vParam;
-
-	pG = new GlobalData;
-	if (pG==NULL)
-		exit(-4);
-	
-	Tokenize(MessageSuppressionList);
-
-	pGL = new GlobalLocalisationData;
-	if(pG==NULL)
-		exit(-4);
-
-	pG->WarningMultiExplained = false;
-	pG->FileLineHandler.SetPath(BasePath);
-	
-	#ifdef __TOOLS2__
-	pG->FileLineHandler.SetBase(SourceFileName,0);
-	#endif
-	
-	int ret=ParseSourceFile(pSourceFile, pParam);
-	fclose(pSourceFile);
-	
-	pGL->StoreFinalComment(); // final comment not stored during running of lex and yacc
-	if(lParam && (pGL->LocalisationCommentsExist() || lForce))
-		{
-		pGL->AnalyseLocalisationData();
-		pGL->PrintLocalisationWarnings();
-		if(lAddDefaults)
-			{
-			// only add deafult localisation values to rpp/rss file if the option has been set on the command line
-			if(verbose)
-				{
-				cout << "* Reparsing source file and adding any missing default localisation comments" << endl;
-				}
-			pGL->OutputLocalisedFile(SourceFileName);
-			}
-		}
-	if (ret != 0) 
-		{
-		cerr << "RCOMP failed with code " << ret << endl;
-		exit(ret);
-		}
-	// A successful parse, now generate the output files
-
-	CheckLabels(); // check that all labels are declared and emit suitable warnings if not
-
-	if(DataOutputFileName.Length() != 0)
-		{
-
-
-#ifdef __LINUX__
-
-		std::string totalpath(s.substr( 0, s.rfind("/")+1 ));
-		const char* uidTool = "uidcrc";
-
-#else
-		std::string totalpath(s.substr( 0, s.rfind("\\")+1 ));
-		const char* uidTool = "uidcrc.exe";
-
-#endif
-
-		// Calls the uidcrc tool with the full path to where RCOMP resides in
-		std::string uidpath(uidTool);
-		totalpath += uidpath;
-		
-		// Find and replace all occurences of \ with /
-		std::string searchString( "\\" ); 
-		std::string replaceString( "/" );
- 		std::string::size_type pos = 0;
-	    	while ( (pos = totalpath.find("\\", pos)) != std::string::npos ) {
-        		totalpath.replace( pos, searchString.size(), replaceString );
-		        pos++;
-		    }
-			
-		const char *uidcrcTool = totalpath.c_str();
-
-		bool thirdUidIsOffset=true;
-		
-		char uidcrcUIDs[3][100];
-		strcpy (uidcrcUIDs[0], "0x101f4a6b");
-
-		if (uidsParameter)
-			{
-			// Command line argument takes precedence 
-			
-			strcpy (uidcrcUIDs[1], strtok (uidsParameter, " "));
-			strcpy (uidcrcUIDs[2], strtok (NULL, " "));
- 
-			char* const temp = strchr(uidcrcUIDs[2], '*');		
-			if (temp == NULL)
-				{
-				thirdUidIsOffset=false;
-				}
-			}
-		else
-			{
-			// otherwise use values supplied in source
-
-			extern unsigned long Uid2;
-			extern unsigned long Uid3;
-			sprintf(uidcrcUIDs[1], "0x%08lx", Uid2);
-			if (Uid3 != 0)
-				{
-				sprintf(uidcrcUIDs[2], "0x%08lx", Uid3);
-				thirdUidIsOffset=false;
-				}
-			}
-
-
-		if (thirdUidIsOffset)
-			{
-			const unsigned int idOfAnyResource = CurrentId; // *must* be unsigned so that when we right-shift it, the top bit doesn't get propagated if its set (i.e. "negative")
-			sprintf(uidcrcUIDs[2], "0x%08x", idOfAnyResource >> 12); // use the 20 bits derived from the resource file's NAME as the 3rd UID
-			}
-
-		if (verbose)
-			{
-			MOFF; cout << uidcrcTool << " " << uidcrcUIDs[0] << " " << uidcrcUIDs[1] << " " << uidcrcUIDs[2] << " " << DataOutputFileName.GetAssertedNonEmptyBuffer(); cout << endl; MON;
-			}
-
-#ifndef __LINUX__
-		const int error = _spawnlp (_P_WAIT,
-									uidcrcTool,
-									uidcrcTool,
-									uidcrcUIDs[0],
-									uidcrcUIDs[1],
-									uidcrcUIDs[2],
-									DataOutputFileName.GetAssertedNonEmptyBuffer(),
-									NULL);
-#else
-		char uidcrc_params[256];
-		const int ret = snprintf(uidcrc_params,
-					 sizeof(uidcrc_params),
-					 "%s %s %s %s %s",
-					 uidcrcTool,
-					 uidcrcUIDs[0],
-					 uidcrcUIDs[1],
-					 uidcrcUIDs[2],
-					 DataOutputFileName.GetBuffer());
-		if(ret <= 0) {
-			cerr << "Failed to write UIDs to " << DataOutputFileName << endl;
-			exit(ret);
-		}
-		const int error = system(uidcrc_params);
-#endif //__LINUX__
-
-		if(error != 0)
-			{
-			cerr << "Failed to write UIDs to " << DataOutputFileName << endl;
-			exit(error);
-			}
-		RCBinaryStream RSCStream;
-		RSCStream.OpenForAppend(DataOutputFileName);
-		if(! RSCStream.IsOpen())
-			{
-			cerr << "Failed to open " << DataOutputFileName << endl;
-			exit(-2);
-			}
-		WriteResourceFile(RSCStream, pG->Index, thirdUidIsOffset, dumpDirectory);
-		}
-	
-	if(HeaderOutputFileName.Length() != 0)
-		{
-		FILE* RSG;
-		RSG = fopen(HeaderOutputFileName.GetAssertedNonEmptyBuffer(), "w");
-		if(RSG==NULL)
-			{
-			cerr << "Failed to open " << HeaderOutputFileName << endl;
-			exit(-2);
-			}
-		WriteHeaderFile(RSG, pG->Index);
-		fclose(RSG);
-		}
-
-	delete pG;
-	delete pGL;
-
-	return 0;
-	}
-
-
-
-
+/*
+* Copyright (c) 2000-2010 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+
+
+#include "unistd.h"
+
+#if defined( __MSVCDOTNET__) || defined(__TOOLS2__)
+#include <iostream>
+#include <fstream>
+using std::cout;
+using std::endl;
+using std::cerr;
+#else //!__MSVCDOTNET__
+#ifndef __LINUX__
+#include <io.h>
+#endif //!__LINUX__
+#endif //__MSVCDOTNET__
+
+#include "RESOURCE.H"
+#include "DATATYPE.H"
+#include "MEM.H"     
+#include "RCBINSTR.H"
+#include "NUMVAL.H"  
+#include "ERRORHAN.H"
+#include "FILEACC.H" 
+#include "VERSION.H" 
+#include "CTABLE.H"  
+#include "main.h"
+#include "TOKENS.H"
+#include "localise.h"
+#include "qualifar.h"
+#include "messages.h"
+
+extern NameIdMap* pResourceNameIds;
+extern long CurrentId;
+
+void WriteHeaderFile(FILE* aRSG, IndexTable& aIndex)
+	{
+	IndexTableIterator next(aIndex);
+	IndexTableItem * p;
+	while( ( p = next() ) != NULL)
+		{
+		ResourceHeader& r=p->Resource();
+		if (r.iLabel.Length()>0 && !r.iLocal)
+			{
+			r.iLabel.Upper();
+			if (r.iFormatAsHex)
+				fprintf(aRSG, "#define %-41s 0x%x\n", r.iLabel.GetAssertedNonEmptyBuffer(), r.iResourceId);
+			else
+				fprintf(aRSG, "#define %-41s %d\n", r.iLabel.GetAssertedNonEmptyBuffer(), r.iResourceId);
+			}
+		}
+	}
+
+void WriteBitArrayOfResourcesContainingCompressedUnicode(RCBinaryStream& aRSC, const IndexTable& aIndex)
+	{
+	IndexTableIterator next(aIndex);
+	unsigned char bitBuffer = 0;
+	int numberOfBitsInBuffer = 0;
+	for (;;)
+		{
+		IndexTableItem* const p = next();
+		if (p == NULL)
+			{
+			if (numberOfBitsInBuffer > 0)
+				{
+				aRSC.Write(&bitBuffer, 1);
+				}
+			break;
+			}
+		if (p->Resource().ContainsCompressedUnicode())
+			{
+			bitBuffer |= (1 << numberOfBitsInBuffer);
+			}
+		++numberOfBitsInBuffer;
+		if (numberOfBitsInBuffer == 8)
+			{
+			aRSC.Write(&bitBuffer, 1);
+			bitBuffer = 0;
+			numberOfBitsInBuffer = 0;
+			}
+		}
+	}
+
+void WriteBinaryResourceData(RCBinaryStream& aRSC, IndexTable& aIndex, int& aSizeOfLargestResourceWhenUncompressed, const char* aDumpDirectory)
+	{
+	IndexTableIterator next(aIndex);
+	IndexTableItem * p;
+	int resourceIndex=1;
+	while( ( p = next() ) != NULL)
+		{
+		char* dumpFile=NULL;
+		if (aDumpDirectory!=NULL)
+			{
+			dumpFile=new char[strlen(aDumpDirectory)+20];
+			strcpy(dumpFile, aDumpDirectory);
+			char resourceIndexAsString[20];
+			sprintf(resourceIndexAsString, "%d", resourceIndex);
+			strcat(dumpFile, resourceIndexAsString);
+			}
+		p->SetOffset(aRSC.GetPosition()); // record start of this resource in the index
+		p->Resource().StreamOut(aRSC, aSizeOfLargestResourceWhenUncompressed, dumpFile); // write out binary form of resource
+		delete [] dumpFile;
+		++resourceIndex;
+		}
+	}
+
+void WriteResourceFile(RCBinaryStream& aRSC, IndexTable& aIndex, bool aThirdUidIsOffset, const char* aDumpDirectory)
+	{
+	char flags=0;
+	if (aThirdUidIsOffset)
+		{
+		flags|=0x01;
+		}
+	aRSC << flags; // these flags are to be used only by a dictionary-compressing program rather than to be used directly by Bafl when reading non-dictionary-compressed resource files (as output by Rcomp)
+	const int positionToOverWriteFrom=aRSC.GetPosition();
+	NumericValue twoByteSizeOfLargestResourceWhenUncompressed(L_WORD);
+	aRSC << twoByteSizeOfLargestResourceWhenUncompressed;
+	WriteBitArrayOfResourcesContainingCompressedUnicode(aRSC, aIndex); // simply makes space for the bit-array without writing anything sensible in it (as we don't yet know which resources will contain compressed Unicode)
+	int sizeOfLargestResourceWhenUncompressed=0;
+	WriteBinaryResourceData(aRSC, aIndex, sizeOfLargestResourceWhenUncompressed, aDumpDirectory);
+	aIndex.SetIndexOffset(aRSC.GetPosition());
+	aRSC << aIndex;
+	aRSC.SetPosition(positionToOverWriteFrom);
+	twoByteSizeOfLargestResourceWhenUncompressed=sizeOfLargestResourceWhenUncompressed;
+	aRSC << twoByteSizeOfLargestResourceWhenUncompressed;
+	WriteBitArrayOfResourcesContainingCompressedUnicode(aRSC, aIndex); // overwrites the bit array with correct data
+
+	if(verbose) 
+		{
+		MOFF; cout << aIndex; cout << endl; MON;
+		}
+	}
+
+void CheckLabels() // checks whether the labels that are used in the input have been declared
+	{
+	QualifiedStringArrayIterator nextLabel(pG->UsedIdentifiers);
+	QualifiedString * pLabel;
+	while ((pLabel = nextLabel() ) != NULL)
+		{
+		bool found = false; // gets set to true if the label in question is declared
+		StringArrayIterator nextDeclared(pG->AllIdentifiers);
+		String * pDeclared;
+		while ( ( (pDeclared = nextDeclared() ) != NULL) && ( ! found ))
+			{
+			StringLess stringCompare;
+			if( !stringCompare(*pDeclared,(*pLabel).GetEntry()) && !stringCompare((*pLabel).GetEntry(),*pDeclared) )
+				{ // this comparison returns true if the label is the same as the declared label
+				found = true;
+				}
+			}
+		if( ! found ) // if label hasn't been declared emit warning
+			{
+			Message * message = pG->Messages.GetEntry(LT_045);
+			String fileName = (*pLabel).GetFileName();
+			int lineNumber = (*pLabel).GetLineNumber();
+			if(message->GetActivated())
+				{
+				String comment = message->GetMessageOutput();
+				comment += (*pLabel).GetEntry();
+				ErrorHandler::OutputWholeLine(fileName, lineNumber, comment);
+				}
+			}
+		}
+	}
+
+
+/*  Tokenize expects a string in the following format:
+ *	  \d{3}(,\d{3})*
+ *  i.e. comma-separated three digit numbers. 
+ *  The string should contain no whitespace.
+ */
+void Tokenize(String aString)
+	{
+	int length = aString.Length();
+
+	for(int end=3; end<=length; end+=4)
+		{
+		String messageNumber = aString.ExtractSubString(end-3,end-1);
+		if(messageNumber.IsDecNatural())
+			{
+			Message * message = pG->Messages.GetTextEntry(messageNumber);
+			if(message != NULL)
+				{
+				message->SetActivationStatus(false);
+				}
+			}
+		}
+	}
+				
+
+void OutputHelp()
+	{
+	cerr << "Resource compiler version " << version << " (Build " << build << ") (C) 1997-2010 Nokia Corporation." << endl;
+	cerr << "Usage: rcomp [-vpul] [-force] [-oRSCFile] [-{uid2,uid3}] [-hHeaderFile] [-sSourceFile] [-iBaseInputFileName]" << endl;
+	cerr << "\tv" << "\tverbose" << endl;
+	cerr << "\tp" << "\tParser debugging" << endl;
+	cerr << "\tl" << "\tCheck localisation comments" << endl;
+	cerr << "\tforce" << "\tEmit localisation warnings even if no localisation tags are present" << endl;
+	cerr << "\tadd-defaults" << "\tAmend input rss/rpp file to add missing default localisation options" << endl;
+	cerr << endl;
+	cerr << "\tu" << "\tGenerate Unicode resource binary" << endl;
+	cerr << endl;
+	cerr << "If no source file is specified, the source will be read from standard input." << endl;
+	cerr << "(-i is used to specify the file given to the preprocessor this " << endl;
+	cerr << "    name is used in generating debug output.)" << endl;
+	}
+
+
+
+GlobalData *pG;
+GlobalLocalisationData *pGL;
+String InputBaseName;
+
+int main(int argc, char * argv[])
+	{
+	cout << "\n"; 
+	int vParam=0;
+	bool lParam = false; // used as flag to specify whether checking of localisation comment tags should be performed
+	bool lForce = false; // used as flag to force localisation output even if there are no localisation comments
+	bool lAddDefaults = false; // used as flag to add missing default localisation data to input rss/rpp file, this is not the default behaviour
+	logmemorysetting = 0;
+	unsigned short	pParam = 0;
+	String			DataOutputFileName;
+	String			HeaderOutputFileName;
+	String			MessageSuppressionList;
+	String			BasePath;
+	String			SourceFileName;
+	FILE *			pSourceFile;
+	char*			uidsParameter=NULL;
+	char*			dumpDirectory=NULL;
+	fpos_t			filePositionIndicator;
+	int				i;
+	
+	char *fullcommand = argv[0];
+	std::string s(fullcommand);
+
+	if(argc<=1)
+		{
+		OutputHelp();
+		exit(-1);
+		}
+	else
+		{
+		// Look through arguments for ones beginning with '-?'.
+		for(i = 1; i < argc; i++)
+			{
+			if(* argv[i] == '-')
+				{
+				char * settings = argv[i] + 1;
+			
+				if(strchr(settings, '?') )
+					{
+					OutputHelp();
+					exit(-1);
+					}
+				}
+			}
+
+		for(i = 1; i < argc; i++)
+			{
+			if(* argv[i] == '-')
+				{
+				char * settings = argv[i] + 1;
+			
+				if(* settings == 'o' || * settings == 'O')
+					{
+					DataOutputFileName = (settings + 1);
+					continue;
+					}
+
+				if(* settings == 'm' || * settings == 'M')
+					{
+					MessageSuppressionList = (settings + 1);
+					continue;
+					}
+					
+				if(* settings == 'h' || * settings == 'H')
+					{
+					HeaderOutputFileName = (settings + 1);
+					continue;
+					}
+
+				if(* settings == 'i' || * settings == 'I')
+					{
+					InputBaseName = (settings + 1);
+					String DriveAndDirectory = FileAccess::GetDriveAndDirectory(InputBaseName);
+					BasePath = FileAccess::FullPath(DriveAndDirectory);
+					continue;
+					}
+
+				if(* settings == 's' || * settings == 'S')
+					{
+					SourceFileName = (settings + 1);
+					continue;
+					}
+
+				if(* settings == '{')
+					{
+					uidsParameter = settings + 1;
+					char* temp = strchr(uidsParameter, ',');
+					if ((temp == NULL) || (temp == uidsParameter) || (strchr(temp + 1, ',') != NULL)) // check that there is *one* comma in this parameter (no more and no less), and that it is not the first thing immediately after the '{'
+						{
+						OutputHelp();
+						exit(-1);
+						}
+					*temp = ' ';
+					temp = strchr(uidsParameter, '}');
+					if ((temp == NULL) || (temp[1] != '\0'))
+						{
+						OutputHelp();
+						exit(-1);
+						}
+					*temp = ' ';
+					continue;
+					}
+
+				if(* settings == ':')
+					{
+					dumpDirectory=settings+1;
+					continue;
+					}
+
+				if(strchr(settings, 'u') || strchr(settings, 'U') )
+					{
+					SourceCharacterSet = String::CP1252;
+					TargetCharacterSet = String::Unicode;
+					}
+
+				if(strchr(settings, 'v') || strchr(settings, 'V') )
+					vParam = 1;
+				if(strchr(settings, 'p') || strchr(settings, 'P') )
+					pParam = 1;
+				if(strchr(settings, 'l') || strchr(settings, 'L') )
+					lParam = true;
+				if(strchr(settings, 'f') || strchr(settings, 'F') )
+					lForce = true;
+				if(strchr(settings, 'a') || strchr(settings, 'A') )
+					lAddDefaults = true;
+				}
+			}
+		}
+	if(SourceFileName.Length() == 0)
+		{
+		pSourceFile = NULL ; //stdin;
+		}
+	else  
+	{
+		if((pSourceFile = fopen(SourceFileName.GetAssertedNonEmptyBuffer(), "r") ) == NULL)
+		{
+			cerr << "Failed to open " << SourceFileName << endl;
+			exit(-2);
+		}
+		//Searchig for BOM signature which if found will be ignored
+		unsigned char buffer[3];
+		fread( buffer, sizeof( char ), 3, pSourceFile);	
+		if((buffer[0]!=239) && (buffer[1]!=187) && (buffer[2]!=191))
+		{
+			// BOM not found. Set the file-position indicator to 0
+			filePositionIndicator = fpos_t();
+			if(fsetpos(pSourceFile, &filePositionIndicator) !=0)
+			{
+				perror("fsetpos error");
+				exit(-2);
+			} 
+		}		
+	}
+		
+	verbose = vParam;
+	pG = new GlobalData;
+	if (pG==NULL)
+		exit(-4);
+		
+	if(NULL == pSourceFile){ // Cache the standard input		
+		pG->StdInBufLength = 0; 
+		unsigned long allocSize = 0x100000 ; // 1M bytes
+		pG->StdInfBufPos = 0 ;
+		pG->StdInBuffer = (char*)malloc(allocSize);
+		if(NULL == pG->StdInBuffer){
+			delete pG ;
+			exit(-4);
+		}
+		int result = 1;
+		char* buffer = pG->StdInBuffer;
+		FILE *file = stdin ;
+		const int KIOBytes = 0x20000 ;
+		while(1) {		 
+			result = fread(buffer, 1, KIOBytes, file);  
+			if(result == 0){
+				*buffer = 0;
+				break ;
+			}
+			buffer += result ;
+			pG->StdInBufLength += result ;
+			if((pG->StdInBufLength + KIOBytes) > allocSize) {
+				allocSize += KIOBytes ;
+				pG->StdInBuffer = (char*)realloc(pG->StdInBuffer,allocSize);
+				if(NULL == pG->StdInBuffer){
+					delete pG ;
+					exit(-4);
+				}
+				buffer = pG->StdInBuffer + pG->StdInBufLength;
+			}
+			
+		}
+		const unsigned char BOM[] = {0xef , 0xbb, 0xbf, 0x0 };
+		if(0 == memcmp(pG->StdInBuffer,BOM,3))
+			pG->StdInfBufPos = 3 ; 
+	}
+	else {
+		pG->StdInBuffer = 0 ;
+		pG->StdInBufLength = 0; 
+	}
+	
+	Tokenize(MessageSuppressionList);
+
+	pGL = new GlobalLocalisationData;
+	if(pG==NULL)
+		exit(-4);
+
+	pG->WarningMultiExplained = false;
+	pG->FileLineHandler.SetPath(BasePath);
+	
+	#ifdef __TOOLS2__
+	pG->FileLineHandler.SetBase(SourceFileName,0);
+	#endif
+	
+	int ret=ParseSourceFile(pSourceFile, pParam);
+	if(pSourceFile != NULL)
+		fclose(pSourceFile);
+	if(pG->StdInBuffer != NULL)
+		free(pG->StdInBuffer);
+	
+	pGL->StoreFinalComment(); // final comment not stored during running of lex and yacc
+	if(lParam && (pGL->LocalisationCommentsExist() || lForce))
+		{
+		pGL->AnalyseLocalisationData();
+		pGL->PrintLocalisationWarnings();
+		if(lAddDefaults)
+			{
+			// only add deafult localisation values to rpp/rss file if the option has been set on the command line
+			if(verbose)
+				{
+				cout << "* Reparsing source file and adding any missing default localisation comments" << endl;
+				}
+			pGL->OutputLocalisedFile(SourceFileName);
+			}
+		}
+	if (ret != 0) 
+		{
+		cerr << "RCOMP failed with code " << ret << endl;
+		exit(ret);
+		}
+	// A successful parse, now generate the output files
+
+	CheckLabels(); // check that all labels are declared and emit suitable warnings if not
+
+	if(DataOutputFileName.Length() != 0)
+		{
+
+
+#ifdef __LINUX__
+
+		std::string totalpath(s.substr( 0, s.rfind("/")+1 ));
+		const char* uidTool = "uidcrc";
+
+#else
+
+		std::string totalpath(s.substr( 0, s.rfind("\\")+1 ));
+		const char* uidTool = "uidcrc.exe";
+    
+		// in case unix style of seperator is used in windows.
+		if(!totalpath.length()){
+			totalpath = s.substr( 0, s.rfind("/")+1 );
+		}
+		
+#endif
+		
+		std::string uidpath(uidTool);
+		
+		// try to call the uidcrc tool with the full path to where RCOMP resides in
+		// if does not exists, search uidcrc in PATH 
+		if(totalpath.length()){
+		
+			std::string trypath(totalpath);
+			trypath += uidpath;
+			
+			std::fstream _file;
+			_file.open(trypath.c_str(), std::ios::in);
+			if(!_file){
+				// try to search from PATH
+				totalpath = uidpath;
+			}
+			else{
+				_file.close();
+				// invoke from the path RCOMP resides in
+				totalpath += uidpath;
+			}
+		}
+		else{
+			// search from PATH
+			totalpath = uidpath;
+		}
+		
+		// Find and replace all occurences of \ with /
+		std::string searchString( "\\" ); 
+		std::string replaceString( "/" );
+ 		std::string::size_type pos = 0;
+	    	while ( (pos = totalpath.find("\\", pos)) != std::string::npos ) {
+        		totalpath.replace( pos, searchString.size(), replaceString );
+		        pos++;
+		    }
+			
+		const char *uidcrcTool = totalpath.c_str();
+
+		bool thirdUidIsOffset=true;
+		
+		char uidcrcUIDs[3][100];
+		strcpy (uidcrcUIDs[0], "0x101f4a6b");
+
+		if (uidsParameter)
+			{
+			// Command line argument takes precedence 
+			
+			strcpy (uidcrcUIDs[1], strtok (uidsParameter, " "));
+			strcpy (uidcrcUIDs[2], strtok (NULL, " "));
+ 
+			char* const temp = strchr(uidcrcUIDs[2], '*');		
+			if (temp == NULL)
+				{
+				thirdUidIsOffset=false;
+				}
+			}
+		else
+			{
+			// otherwise use values supplied in source
+
+			extern unsigned long Uid2;
+			extern unsigned long Uid3;
+			sprintf(uidcrcUIDs[1], "0x%08lx", Uid2);
+			if (Uid3 != 0)
+				{
+				sprintf(uidcrcUIDs[2], "0x%08lx", Uid3);
+				thirdUidIsOffset=false;
+				}
+			}
+
+
+		if (thirdUidIsOffset)
+			{
+			const unsigned int idOfAnyResource = CurrentId; // *must* be unsigned so that when we right-shift it, the top bit doesn't get propagated if its set (i.e. "negative")
+			sprintf(uidcrcUIDs[2], "0x%08x", idOfAnyResource >> 12); // use the 20 bits derived from the resource file's NAME as the 3rd UID
+			}
+
+		if (verbose)
+			{
+			MOFF; cout << uidcrcTool << " " << uidcrcUIDs[0] << " " << uidcrcUIDs[1] << " " << uidcrcUIDs[2] << " " << DataOutputFileName.GetAssertedNonEmptyBuffer(); cout << endl; MON;
+			}
+
+		char uidcrc_params[512];
+		const int ret = snprintf(uidcrc_params,
+					 sizeof(uidcrc_params),
+					 "%s %s %s %s %s",
+					 uidcrcTool,
+					 uidcrcUIDs[0],
+					 uidcrcUIDs[1],
+					 uidcrcUIDs[2],
+					 DataOutputFileName.GetBuffer());
+		if(ret <= 0) {
+			cerr << "Failed to write UIDs to " << DataOutputFileName << endl;
+			exit(ret);
+		}
+		const int error = system(uidcrc_params);
+
+		if(error != 0)
+			{
+			cerr << "Failed to write UIDs to " << DataOutputFileName << endl;
+			exit(error);
+			}
+		RCBinaryStream RSCStream;
+		RSCStream.OpenForAppend(DataOutputFileName);
+		if(! RSCStream.IsOpen())
+			{
+			cerr << "Failed to open " << DataOutputFileName << endl;
+			exit(-2);
+			}
+		WriteResourceFile(RSCStream, pG->Index, thirdUidIsOffset, dumpDirectory);
+		}
+	
+	if(HeaderOutputFileName.Length() != 0)
+		{
+		FILE* RSG;
+		RSG = fopen(HeaderOutputFileName.GetAssertedNonEmptyBuffer(), "w");
+		if(RSG==NULL)
+			{
+			cerr << "Failed to open " << HeaderOutputFileName << endl;
+			exit(-2);
+			}
+		WriteHeaderFile(RSG, pG->Index);
+		fclose(RSG);
+		}
+
+	delete pG;
+	delete pGL;
+
+	return 0;
+	}
+
+
+
+
--- a/bintools/rcomp/src/rcomp.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/rcomp/src/rcomp.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,3449 +1,3449 @@
-/* A Bison parser, made by GNU Bison 2.4.1.  */
-
-/* Skeleton implementation for Bison's Yacc-like parsers in C
-   
-      Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
-   Free Software Foundation, Inc.
-   
-   This program is free software: you can redistribute it and/or modify
-   it under the terms of the GNU General Public License as published by
-   the Free Software Foundation, either version 3 of the License, or
-   (at your option) any later version.
-   
-   This program is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-   GNU General Public License for more details.
-   
-   You should have received a copy of the GNU General Public License
-   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
-
-/* As a special exception, you may create a larger work that contains
-   part or all of the Bison parser skeleton and distribute that work
-   under terms of your choice, so long as that work isn't itself a
-   parser generator using the skeleton or a modified version thereof
-   as a parser skeleton.  Alternatively, if you modify or redistribute
-   the parser skeleton itself, you may (at your option) remove this
-   special exception, which will cause the skeleton and the resulting
-   Bison output files to be licensed under the GNU General Public
-   License without this special exception.
-   
-   This special exception was added by the Free Software Foundation in
-   version 2.2 of Bison.  */
-
-/* C LALR(1) parser skeleton written by Richard Stallman, by
-   simplifying the original so-called "semantic" parser.  */
-
-/* All symbols defined below should begin with yy or YY, to avoid
-   infringing on user name space.  This should be done even for local
-   variables, as they might otherwise be expanded by user macros.
-   There are some unavoidable exceptions within include files to
-   define necessary library symbols; they are noted "INFRINGES ON
-   USER NAME SPACE" below.  */
-
-/* Identify Bison output.  */
-#define YYBISON 1
-
-/* Bison version.  */
-#define YYBISON_VERSION "2.4.1"
-
-/* Skeleton name.  */
-#define YYSKELETON_NAME "yacc.c"
-
-/* Pure parsers.  */
-#define YYPURE 0
-
-/* Push parsers.  */
-#define YYPUSH 0
-
-/* Pull parsers.  */
-#define YYPULL 1
-
-/* Using locations.  */
-#define YYLSP_NEEDED 0
-
-
-
-/* Copy the first part of user declarations.  */
-
-/* Line 189 of yacc.c  */
-#line 1 "rcomp.yacc"
-
-#include <assert.h>
-#include <ctype.h>
-#include <string.h>
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-#include <fstream>
-#include <iostream>
-using namespace std;
-using std::cout;
-using std::endl;
-#else //!__MSVCDOTNET__
-#include <fstream.h>
-#endif //__MSVCDOTNET__
-
-#ifdef __VC32__
-#pragma warning( disable : 4065 ) // C4065: switch statement contains 'default' but no 'case' labels
-#pragma warning( disable : 4102 ) // C4102: 'yyerrlab1' : unreferenced label
-#pragma warning( disable : 4127 ) // C4127: conditional expression is constant
-#pragma warning( disable : 4244 ) // C4244: '=' : conversion from 'int' to 'short', possible loss of data
-#endif //__VC32__
-
-#include "resource.h"
-#include "parser.h"
-
-int yylex();
-void yyerror(const char* string, ...);
-int yywrap();
-#define YYDEBUG 1
-extern int yylineno;
-
-#include "rcomp.hpp"
-#include "datatype.h"
-#include "mem.h"
-#include "rcbinstr.h"
-#include "rcscan.h"
-#include "errorhan.h"
-#include "fileacc.h"
-#include "version.h"
-#include "ctable.h"
-#include "localise.h"
-#include "main.h"
-
-#if defined(__VC32__) && !defined(_DEBUG)
-#pragma warning( disable : 4702 )	// unreachable code
-#pragma warning( disable : 4102 )	// 'yyerrlabel' : unreferenced label
-#pragma warning( disable : 4244 )	// '=' : conversion from 'int' to 'short', possible loss of data
-#endif
-
-
-
-String::CharacterSet CharacterSetID( const String & character_set_name );
-void asUTF8(char* aUtf8, int aUnicode);
-void SetIdFromName( const String & NameStatementValue);
-void CheckStructUsage();
-
-unsigned short & d = MemCheckControl::iLogMemory;
-
-StructHeader *		pSH;
-
-StructHeaderArray * 	pSHA;	// Used in resource struct handling functions.
-ResourceHeader *	pResourceHeader;
-ResourceItemArray *	pCurrentRIA;
-StringArray * pUsedLabelsArray = new StringArray();
-int			verbose;
-String::CharacterSet	SourceCharacterSet = String::CP1252;
-String::CharacterSet	TargetCharacterSet = String::CP1252;
-unsigned short		logmemorysetting;
-int *			pCurrentLineNumber;
-FileLineManager *	pFileLineHandler;
-NameIdMap *		pResourceNameIds;
-long			CurrentEnumValue;
-String			CurrentEnumName;
-char			TempStr[300];
-rcscan * pScan;
-
-int CurrentIdStep=1;
-long CurrentId=0;
-int FormatIdAsHex=0;	// defaults to decimal, changes in SetIdFromName
-
-unsigned long Uid2=0;
-unsigned long Uid3=0;
-
-
-
-const String	Divider("*******************************************");
-
-#define REGISTER_LINE	ErrorHandler::Register(pFileLineHandler->GetCurrentFile(), pFileLineHandler->GetErrorLine(* pCurrentLineNumber))
-
-// Convert a string containing a character literal in aQuoted
-// into a value suitable for LCHAR_LITERAL
-void SetCharacterLiteral(char* aOut, const String& aQuoted)
-	{
-	    UTF16 first;
-	    int length=1;
-	    if (aQuoted.Length() < 1 ) 
-	               { 
-                        REGISTER_LINE;
-                        ErrorHandler::OutputErrorLine("Warning: Empty Character literal");
-                       }
-	    if (aQuoted.Length() > 1 ) 
-	 	       {
-                        REGISTER_LINE;
-                        ErrorHandler::OutputErrorLine("Error: String Literal length greater than 1");
-			exit(1);
-                       }
-	    if (aQuoted.Export(&first, length, SourceCharacterSet)==0)
-			{
-			REGISTER_LINE;
-			ErrorHandler::OutputErrorLine("Warning: Ignoring trailing characters in character literal");
-			}
-	    sprintf(aOut, "%d", first);
-	}
-
-
-
-/* Line 189 of yacc.c  */
-#line 205 "rcomp.tab.cacc"
-
-/* Enabling traces.  */
-#ifndef YYDEBUG
-# define YYDEBUG 0
-#endif
-
-/* Enabling verbose error messages.  */
-#ifdef YYERROR_VERBOSE
-# undef YYERROR_VERBOSE
-# define YYERROR_VERBOSE 1
-#else
-# define YYERROR_VERBOSE 0
-#endif
-
-/* Enabling the token table.  */
-#ifndef YYTOKEN_TABLE
-# define YYTOKEN_TABLE 0
-#endif
-
-
-/* Tokens.  */
-#ifndef YYTOKENTYPE
-# define YYTOKENTYPE
-   /* Put the tokens into the symbol table, so that GDB and other debuggers
-      know about them.  */
-   enum yytokentype {
-     L_STRUCT = 258,
-     L_RESOURCE = 259,
-     L_NAME = 260,
-     L_OFFSET = 261,
-     L_SYSTEM = 262,
-     L_GLOBAL = 263,
-     L_LOCAL = 264,
-     L_CHARACTER_SET = 265,
-     L_BUF = 266,
-     L_WORD = 267,
-     L_BYTE = 268,
-     L_LONG = 269,
-     L_DOUBLE = 270,
-     L_TEXT = 271,
-     L_LTEXT = 272,
-     L_LINK = 273,
-     L_LLINK = 274,
-     L_SRLINK = 275,
-     L_BUF8 = 276,
-     L_TEXT8 = 277,
-     L_LTEXT8 = 278,
-     L_BUF16 = 279,
-     L_TEXT16 = 280,
-     L_LTEXT16 = 281,
-     L_UID_TWO = 282,
-     L_UID_THREE = 283,
-     L_RLS_STRING = 284,
-     L_RLS_STRING8 = 285,
-     L_RLS_DOUBLE = 286,
-     L_RLS_BYTE = 287,
-     L_RLS_WORD = 288,
-     L_RLS_LONG = 289,
-     L_MULTI = 290,
-     L_TAG_START = 291,
-     L_TAG_END = 292,
-     L_TAG_COMMAND = 293,
-     L_TAG_WORD = 294,
-     L_TAG_NEW_LINE = 295,
-     L_LABEL = 296,
-     L_NUM_NATURAL = 297,
-     L_NUM_FLOAT = 298,
-     L_NATURAL_EXPR = 299,
-     L_ENUM = 300,
-     L_LEN = 301,
-     L_CHAR_LITERAL = 302,
-     L_STRING_LITERAL = 303,
-     UMINUS = 304
-   };
-#endif
-
-
-
-#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
-typedef union YYSTYPE
-{
-
-/* Line 214 of yacc.c  */
-#line 132 "rcomp.yacc"
-
-	char				Value[1024*8];
-	TValueMaybeRls			ValueMaybeRls;
-	unsigned long 			Id;
-	StructItem *			pStructItem;
-	SimpleStructItem *		pSimpleStructItem;
-	ArrayStructItem *   	pArrayStructItem;
-	StructArrayStructItem *	pStructArrayStructItem;
-	StringArray *			pStringArray;
-	long					NumInitialiser;
-	TRlsQualifiers		RlsQualifiers;
-	TRlsType			RlsType;
-
-
-
-/* Line 214 of yacc.c  */
-#line 306 "rcomp.tab.cacc"
-} YYSTYPE;
-# define YYSTYPE_IS_TRIVIAL 1
-# define yystype YYSTYPE /* obsolescent; will be withdrawn */
-# define YYSTYPE_IS_DECLARED 1
-#endif
-
-
-/* Copy the second part of user declarations.  */
-
-
-/* Line 264 of yacc.c  */
-#line 318 "rcomp.tab.cacc"
-
-#ifdef short
-# undef short
-#endif
-
-#ifdef YYTYPE_UINT8
-typedef YYTYPE_UINT8 yytype_uint8;
-#else
-typedef unsigned char yytype_uint8;
-#endif
-
-#ifdef YYTYPE_INT8
-typedef YYTYPE_INT8 yytype_int8;
-#elif (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-typedef signed char yytype_int8;
-#else
-typedef short int yytype_int8;
-#endif
-
-#ifdef YYTYPE_UINT16
-typedef YYTYPE_UINT16 yytype_uint16;
-#else
-typedef unsigned short int yytype_uint16;
-#endif
-
-#ifdef YYTYPE_INT16
-typedef YYTYPE_INT16 yytype_int16;
-#else
-typedef short int yytype_int16;
-#endif
-
-#ifndef YYSIZE_T
-# ifdef __SIZE_TYPE__
-#  define YYSIZE_T __SIZE_TYPE__
-# elif defined size_t
-#  define YYSIZE_T size_t
-# elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-#  include <stddef.h> /* INFRINGES ON USER NAME SPACE */
-#  define YYSIZE_T size_t
-# else
-#  define YYSIZE_T unsigned int
-# endif
-#endif
-
-#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
-
-#ifndef YY_
-# if YYENABLE_NLS
-#  if ENABLE_NLS
-#   include <libintl.h> /* INFRINGES ON USER NAME SPACE */
-#   define YY_(msgid) dgettext ("bison-runtime", msgid)
-#  endif
-# endif
-# ifndef YY_
-#  define YY_(msgid) msgid
-# endif
-#endif
-
-/* Suppress unused-variable warnings by "using" E.  */
-#if ! defined lint || defined __GNUC__
-# define YYUSE(e) ((void) (e))
-#else
-# define YYUSE(e) /* empty */
-#endif
-
-/* Identity function, used to suppress warnings about constant conditions.  */
-#ifndef lint
-# define YYID(n) (n)
-#else
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-static int
-YYID (int yyi)
-#else
-static int
-YYID (yyi)
-    int yyi;
-#endif
-{
-  return yyi;
-}
-#endif
-
-#if ! defined yyoverflow || YYERROR_VERBOSE
-
-/* The parser invokes alloca or malloc; define the necessary symbols.  */
-
-# ifdef YYSTACK_USE_ALLOCA
-#  if YYSTACK_USE_ALLOCA
-#   ifdef __GNUC__
-#    define YYSTACK_ALLOC __builtin_alloca
-#   elif defined __BUILTIN_VA_ARG_INCR
-#    include <alloca.h> /* INFRINGES ON USER NAME SPACE */
-#   elif defined _AIX
-#    define YYSTACK_ALLOC __alloca
-#   elif defined _MSC_VER
-#    include <malloc.h> /* INFRINGES ON USER NAME SPACE */
-#    define alloca _alloca
-#   else
-#    define YYSTACK_ALLOC alloca
-#    if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-#     include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
-#     ifndef _STDLIB_H
-#      define _STDLIB_H 1
-#     endif
-#    endif
-#   endif
-#  endif
-# endif
-
-# ifdef YYSTACK_ALLOC
-   /* Pacify GCC's `empty if-body' warning.  */
-#  define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0))
-#  ifndef YYSTACK_ALLOC_MAXIMUM
-    /* The OS might guarantee only one guard page at the bottom of the stack,
-       and a page size can be as small as 4096 bytes.  So we cannot safely
-       invoke alloca (N) if N exceeds 4096.  Use a slightly smaller number
-       to allow for a few compiler-allocated temporary stack slots.  */
-#   define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
-#  endif
-# else
-#  define YYSTACK_ALLOC YYMALLOC
-#  define YYSTACK_FREE YYFREE
-#  ifndef YYSTACK_ALLOC_MAXIMUM
-#   define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
-#  endif
-#  if (defined __cplusplus && ! defined _STDLIB_H \
-       && ! ((defined YYMALLOC || defined malloc) \
-	     && (defined YYFREE || defined free)))
-#   include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
-#   ifndef _STDLIB_H
-#    define _STDLIB_H 1
-#   endif
-#  endif
-#  ifndef YYMALLOC
-#   define YYMALLOC malloc
-#   if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
-#   endif
-#  endif
-#  ifndef YYFREE
-#   define YYFREE free
-#   if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-void free (void *); /* INFRINGES ON USER NAME SPACE */
-#   endif
-#  endif
-# endif
-#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
-
-
-#if (! defined yyoverflow \
-     && (! defined __cplusplus \
-	 || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
-
-/* A type that is properly aligned for any stack member.  */
-union yyalloc
-{
-  yytype_int16 yyss_alloc;
-  YYSTYPE yyvs_alloc;
-};
-
-/* The size of the maximum gap between one aligned stack and the next.  */
-# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
-
-/* The size of an array large to enough to hold all stacks, each with
-   N elements.  */
-# define YYSTACK_BYTES(N) \
-     ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
-      + YYSTACK_GAP_MAXIMUM)
-
-/* Copy COUNT objects from FROM to TO.  The source and destination do
-   not overlap.  */
-# ifndef YYCOPY
-#  if defined __GNUC__ && 1 < __GNUC__
-#   define YYCOPY(To, From, Count) \
-      __builtin_memcpy (To, From, (Count) * sizeof (*(From)))
-#  else
-#   define YYCOPY(To, From, Count)		\
-      do					\
-	{					\
-	  YYSIZE_T yyi;				\
-	  for (yyi = 0; yyi < (Count); yyi++)	\
-	    (To)[yyi] = (From)[yyi];		\
-	}					\
-      while (YYID (0))
-#  endif
-# endif
-
-/* Relocate STACK from its old location to the new one.  The
-   local variables YYSIZE and YYSTACKSIZE give the old and new number of
-   elements in the stack, and YYPTR gives the new location of the
-   stack.  Advance YYPTR to a properly aligned location for the next
-   stack.  */
-# define YYSTACK_RELOCATE(Stack_alloc, Stack)				\
-    do									\
-      {									\
-	YYSIZE_T yynewbytes;						\
-	YYCOPY (&yyptr->Stack_alloc, Stack, yysize);			\
-	Stack = &yyptr->Stack_alloc;					\
-	yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
-	yyptr += yynewbytes / sizeof (*yyptr);				\
-      }									\
-    while (YYID (0))
-
-#endif
-
-/* YYFINAL -- State number of the termination state.  */
-#define YYFINAL  3
-/* YYLAST -- Last index in YYTABLE.  */
-#define YYLAST   303
-
-/* YYNTOKENS -- Number of terminals.  */
-#define YYNTOKENS  66
-/* YYNNTS -- Number of nonterminals.  */
-#define YYNNTS  61
-/* YYNRULES -- Number of rules.  */
-#define YYNRULES  152
-/* YYNRULES -- Number of states.  */
-#define YYNSTATES  255
-
-/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX.  */
-#define YYUNDEFTOK  2
-#define YYMAXUTOK   304
-
-#define YYTRANSLATE(YYX)						\
-  ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
-
-/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX.  */
-static const yytype_uint8 yytranslate[] =
-{
-       0,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-      58,    59,    51,    49,    65,    50,     2,    52,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,    55,
-      61,    60,    62,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,    64,     2,    63,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,    57,    53,    56,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     1,     2,     3,     4,
-       5,     6,     7,     8,     9,    10,    11,    12,    13,    14,
-      15,    16,    17,    18,    19,    20,    21,    22,    23,    24,
-      25,    26,    27,    28,    29,    30,    31,    32,    33,    34,
-      35,    36,    37,    38,    39,    40,    41,    42,    43,    44,
-      45,    46,    47,    48,    54
-};
-
-#if YYDEBUG
-/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
-   YYRHS.  */
-static const yytype_uint16 yyprhs[] =
-{
-       0,     0,     3,     5,     8,    11,    12,    15,    18,    21,
-      24,    27,    30,    32,    35,    38,    40,    41,    45,    50,
-      56,    62,    66,    71,    72,    74,    76,    78,    80,    82,
-      87,    91,    98,   101,   107,   109,   111,   113,   115,   117,
-     119,   121,   123,   125,   127,   129,   131,   133,   135,   137,
-     139,   141,   147,   150,   154,   159,   165,   169,   171,   173,
-     176,   178,   182,   187,   193,   198,   201,   204,   206,   210,
-     213,   217,   222,   226,   227,   231,   233,   235,   237,   242,
-     248,   252,   257,   261,   265,   271,   273,   277,   281,   284,
-     286,   290,   294,   297,   299,   301,   303,   305,   307,   311,
-     313,   315,   319,   323,   327,   331,   335,   338,   342,   344,
-     347,   349,   351,   353,   357,   360,   363,   366,   369,   372,
-     375,   377,   381,   386,   390,   393,   395,   399,   402,   407,
-     412,   417,   422,   427,   432,   434,   439,   441,   443,   444,
-     446,   448,   450,   452,   454,   456,   458,   459,   463,   466,
-     467,   469,   471
-};
-
-/* YYRHS -- A `-1'-separated list of the rules' RHS.  */
-static const yytype_int8 yyrhs[] =
-{
-      67,     0,    -1,    68,    -1,    68,    69,    -1,    68,   124,
-      -1,    -1,    71,    70,    -1,    85,    70,    -1,   109,    70,
-      -1,   107,    70,    -1,   110,    70,    -1,   111,    70,    -1,
-     112,    -1,   108,    70,    -1,   116,    70,    -1,    55,    -1,
-      -1,    72,    73,    56,    -1,     3,    41,   123,    57,    -1,
-       3,    41,    81,   123,    57,    -1,     3,    41,    46,   123,
-      57,    -1,    73,    74,    55,    -1,    73,   124,    74,    55,
-      -1,    -1,    75,    -1,    78,    -1,    82,    -1,    83,    -1,
-      76,    -1,    76,    58,   102,    59,    -1,    76,    60,   100,
-      -1,    76,    58,   102,    59,    60,   104,    -1,    77,    41,
-      -1,    77,    61,   103,    62,    41,    -1,    13,    -1,    12,
-      -1,    14,    -1,    15,    -1,    16,    -1,    17,    -1,    11,
-      -1,    22,    -1,    25,    -1,    23,    -1,    26,    -1,    21,
-      -1,    24,    -1,    18,    -1,    19,    -1,    20,    -1,    79,
-      -1,    79,    60,    57,   101,    56,    -1,    80,    63,    -1,
-      80,   102,    63,    -1,    46,    81,    80,    63,    -1,    46,
-      81,    80,   102,    63,    -1,    77,    41,    64,    -1,    13,
-      -1,    12,    -1,     3,    41,    -1,    84,    -1,    46,    81,
-      84,    -1,     3,    41,    64,    63,    -1,     3,    41,    64,
-     102,    63,    -1,    86,    57,    88,    56,    -1,     8,    87,
-      -1,     9,    87,    -1,    87,    -1,     4,    41,    41,    -1,
-       4,    41,    -1,    88,    89,    55,    -1,    88,   124,    89,
-      55,    -1,    88,     1,    55,    -1,    -1,    41,    60,   100,
-      -1,    90,    -1,    91,    -1,    93,    -1,    41,    60,    57,
-      56,    -1,    41,    60,    57,   101,    56,    -1,    92,    88,
-      56,    -1,    41,    60,    41,    57,    -1,    94,    95,    56,
-      -1,    94,    95,     1,    -1,    41,    60,    57,    41,    57,
-      -1,    96,    -1,    96,    65,    97,    -1,    96,    65,     1,
-      -1,    88,    56,    -1,    98,    -1,    97,    65,    98,    -1,
-      99,    88,    56,    -1,    41,    57,    -1,    43,    -1,    47,
-      -1,   104,    -1,   102,    -1,   100,    -1,   101,    65,   100,
-      -1,   103,    -1,    42,    -1,   103,    49,   103,    -1,   103,
-      50,   103,    -1,   103,    51,   103,    -1,   103,    52,   103,
-      -1,   103,    53,   103,    -1,    50,   103,    -1,    58,   103,
-      59,    -1,   105,    -1,   105,   104,    -1,    48,    -1,   106,
-      -1,    41,    -1,    61,   103,    62,    -1,     5,    41,    -1,
-       5,    48,    -1,    27,   103,    -1,    28,   103,    -1,    10,
-      41,    -1,     6,   102,    -1,     7,    -1,   113,   115,    56,
-      -1,   113,   115,    56,    55,    -1,    45,    41,    57,    -1,
-      45,    57,    -1,    41,    -1,    41,    60,   100,    -1,   123,
-     114,    -1,   115,    65,   123,   114,    -1,   120,   118,   117,
-     104,    -1,   120,   118,   117,    47,    -1,   122,   119,   117,
-      43,    -1,   121,   119,   117,    42,    -1,   121,   119,   117,
-      47,    -1,    41,    -1,    61,    42,    62,   119,    -1,   119,
-      -1,    35,    -1,    -1,    29,    -1,    30,    -1,    32,    -1,
-      33,    -1,    34,    -1,    31,    -1,   124,    -1,    -1,    36,
-     125,    37,    -1,   125,   126,    -1,    -1,    40,    -1,    38,
-      -1,    39,    -1
-};
-
-/* YYRLINE[YYN] -- source line where rule number YYN was defined.  */
-static const yytype_uint16 yyrline[] =
-{
-       0,   182,   182,   189,   190,   191,   195,   196,   197,   198,
-     199,   200,   201,   202,   203,   207,   214,   221,   225,   231,
-     237,   245,   249,   253,   256,   257,   258,   259,   262,   263,
-     268,   273,   289,   297,   312,   313,   314,   315,   319,   325,
-     329,   336,   340,   344,   345,   346,   347,   348,   349,   350,
-     353,   354,   372,   375,   380,   388,   399,   407,   408,   411,
-     416,   417,   423,   426,   435,   451,   452,   458,   461,   474,
-     483,   484,   485,   486,   489,   493,   494,   495,   498,   503,
-     531,   537,   548,   552,   556,   569,   570,   571,   574,   579,
-     580,   583,   589,   603,   604,   609,   610,   613,   623,   632,
-     635,   639,   640,   641,   642,   643,   644,   652,   655,   656,
-     667,   668,   669,   748,   794,   799,   811,   822,   844,   868,
-     879,   888,   889,   892,   899,   909,   914,   925,   926,   933,
-     950,   966,   973,   980,   991,  1012,  1018,  1023,  1029,  1036,
-    1038,  1043,  1045,  1047,  1052,  1060,  1061,  1065,  1069,  1071,
-    1075,  1076,  1077
-};
-#endif
-
-#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
-/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
-   First, the terminals, then, starting at YYNTOKENS, nonterminals.  */
-static const char *const yytname[] =
-{
-  "$end", "error", "$undefined", "L_STRUCT", "L_RESOURCE", "L_NAME",
-  "L_OFFSET", "L_SYSTEM", "L_GLOBAL", "L_LOCAL", "L_CHARACTER_SET",
-  "L_BUF", "L_WORD", "L_BYTE", "L_LONG", "L_DOUBLE", "L_TEXT", "L_LTEXT",
-  "L_LINK", "L_LLINK", "L_SRLINK", "L_BUF8", "L_TEXT8", "L_LTEXT8",
-  "L_BUF16", "L_TEXT16", "L_LTEXT16", "L_UID_TWO", "L_UID_THREE",
-  "L_RLS_STRING", "L_RLS_STRING8", "L_RLS_DOUBLE", "L_RLS_BYTE",
-  "L_RLS_WORD", "L_RLS_LONG", "L_MULTI", "L_TAG_START", "L_TAG_END",
-  "L_TAG_COMMAND", "L_TAG_WORD", "L_TAG_NEW_LINE", "L_LABEL",
-  "L_NUM_NATURAL", "L_NUM_FLOAT", "L_NATURAL_EXPR", "L_ENUM", "L_LEN",
-  "L_CHAR_LITERAL", "L_STRING_LITERAL", "'+'", "'-'", "'*'", "'/'", "'|'",
-  "UMINUS", "';'", "'}'", "'{'", "'('", "')'", "'='", "'<'", "'>'", "']'",
-  "'['", "','", "$accept", "source", "statement_list", "statement",
-  "maybe_semicolon", "struct_statement", "struct_statement_start",
-  "struct_item_list", "struct_item", "simple_struct_item",
-  "simple_struct_item_start", "data_type", "array_struct_item",
-  "array_struct_item_base", "array_struct_item_start", "len_declaration",
-  "struct_type_struct_item", "struct_array_struct_item",
-  "struct_array_struct_item_base", "resource_statement",
-  "resource_statement_start", "resource_statement_start_names",
-  "resource_item_list", "resource_item", "resource_simple_array_item",
-  "struct_resource_item", "struct_resource_item_start",
-  "struct_array_resource_item", "struct_array_resource_item_start",
-  "struct_array_resource_item_list_top",
-  "struct_array_resource_item_list_top_start",
-  "struct_array_resource_item_list",
-  "struct_array_resource_item_list_item",
-  "struct_array_resource_item_list_item_start", "simple_initialiser",
-  "simple_initialiser_list", "natural_expression",
-  "natural_expression_numeric", "string_expression",
-  "string_expression_item", "character_code_expression", "name_statement",
-  "uidX_statement", "character_set_statement", "offset_statement",
-  "system_statement", "enum_statement", "enum_statement_start",
-  "enum_list_entry", "enum_list", "rls_item_statement", "rls_label",
-  "rls_qualifiers", "rls_cardinality", "rls_string_item", "rls_num_item",
-  "rls_float_item", "maybe_comment_tag", "comment_tag", "tag_line",
-  "tag_word", 0
-};
-#endif
-
-# ifdef YYPRINT
-/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to
-   token YYLEX-NUM.  */
-static const yytype_uint16 yytoknum[] =
-{
-       0,   256,   257,   258,   259,   260,   261,   262,   263,   264,
-     265,   266,   267,   268,   269,   270,   271,   272,   273,   274,
-     275,   276,   277,   278,   279,   280,   281,   282,   283,   284,
-     285,   286,   287,   288,   289,   290,   291,   292,   293,   294,
-     295,   296,   297,   298,   299,   300,   301,   302,   303,    43,
-      45,    42,    47,   124,   304,    59,   125,   123,    40,    41,
-      61,    60,    62,    93,    91,    44
-};
-# endif
-
-/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives.  */
-static const yytype_uint8 yyr1[] =
-{
-       0,    66,    67,    68,    68,    68,    69,    69,    69,    69,
-      69,    69,    69,    69,    69,    70,    70,    71,    72,    72,
-      72,    73,    73,    73,    74,    74,    74,    74,    75,    75,
-      75,    75,    76,    76,    77,    77,    77,    77,    77,    77,
-      77,    77,    77,    77,    77,    77,    77,    77,    77,    77,
-      78,    78,    79,    79,    79,    79,    80,    81,    81,    82,
-      83,    83,    84,    84,    85,    86,    86,    86,    87,    87,
-      88,    88,    88,    88,    89,    89,    89,    89,    90,    90,
-      91,    92,    93,    93,    94,    95,    95,    95,    96,    97,
-      97,    98,    99,   100,   100,   100,   100,   101,   101,   102,
-     103,   103,   103,   103,   103,   103,   103,   103,   104,   104,
-     105,   105,   105,   106,   107,   107,   108,   108,   109,   110,
-     111,   112,   112,   113,   113,   114,   114,   115,   115,   116,
-     116,   116,   116,   116,   117,   118,   118,   119,   119,   120,
-     120,   121,   121,   121,   122,   123,   123,   124,   125,   125,
-     126,   126,   126
-};
-
-/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN.  */
-static const yytype_uint8 yyr2[] =
-{
-       0,     2,     1,     2,     2,     0,     2,     2,     2,     2,
-       2,     2,     1,     2,     2,     1,     0,     3,     4,     5,
-       5,     3,     4,     0,     1,     1,     1,     1,     1,     4,
-       3,     6,     2,     5,     1,     1,     1,     1,     1,     1,
-       1,     1,     1,     1,     1,     1,     1,     1,     1,     1,
-       1,     5,     2,     3,     4,     5,     3,     1,     1,     2,
-       1,     3,     4,     5,     4,     2,     2,     1,     3,     2,
-       3,     4,     3,     0,     3,     1,     1,     1,     4,     5,
-       3,     4,     3,     3,     5,     1,     3,     3,     2,     1,
-       3,     3,     2,     1,     1,     1,     1,     1,     3,     1,
-       1,     3,     3,     3,     3,     3,     2,     3,     1,     2,
-       1,     1,     1,     3,     2,     2,     2,     2,     2,     2,
-       1,     3,     4,     3,     2,     1,     3,     2,     4,     4,
-       4,     4,     4,     4,     1,     4,     1,     1,     0,     1,
-       1,     1,     1,     1,     1,     1,     0,     3,     2,     0,
-       1,     1,     1
-};
-
-/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state
-   STATE-NUM when YYTABLE doesn't specify something else to do.  Zero
-   means the default is an error.  */
-static const yytype_uint8 yydefact[] =
-{
-       5,     0,     2,     1,     0,     0,     0,     0,   120,     0,
-       0,     0,     0,     0,   139,   140,   144,   141,   142,   143,
-     149,     0,     3,    16,    23,    16,     0,    67,    16,    16,
-      16,    16,    16,    12,   146,    16,   138,   138,   138,     4,
-     146,    69,   114,   115,   100,     0,     0,   119,    99,    65,
-      66,   118,   116,   117,     0,     0,   124,    15,     6,     0,
-       7,    73,     9,    13,     8,    10,    11,     0,     0,   145,
-      14,   137,     0,     0,   136,     0,     0,    58,    57,   146,
-     146,     0,    68,   106,     0,     0,     0,     0,     0,     0,
-     147,   151,   152,   150,   148,   123,     0,    40,    35,    34,
-      36,    37,    38,    39,    47,    48,    49,    45,    41,    43,
-      46,    42,    44,     0,    17,     0,    24,    28,     0,    25,
-      50,     0,    26,    27,    60,     0,     0,   121,   146,   125,
-     127,     0,   134,     0,     0,     0,     0,     0,    18,   107,
-     101,   102,   103,   104,   105,    59,     0,    21,     0,     0,
-      32,     0,     0,    52,     0,     0,     0,     0,    64,     0,
-      75,    76,    73,    77,    73,     0,   122,     0,     0,   138,
-     112,   130,   110,     0,   129,   108,   111,   132,   133,   131,
-      20,    19,     0,     0,     0,     0,    61,     0,    93,    94,
-      30,    96,    95,    56,     0,     0,    53,    22,    72,     0,
-      70,     0,     0,     0,    85,     0,   128,   126,   135,     0,
-     109,    62,     0,     0,     0,    54,     0,    29,     0,    97,
-       0,   112,     0,    74,    80,    88,    83,    82,     0,    71,
-     113,    63,    55,     0,    33,    51,     0,    81,   112,    78,
-       0,    87,     0,    86,    89,    73,    31,    98,    84,    79,
-      92,     0,     0,    90,    91
-};
-
-/* YYDEFGOTO[NTERM-NUM].  */
-static const yytype_int16 yydefgoto[] =
-{
-      -1,     1,     2,    22,    58,    23,    24,    59,   115,   116,
-     117,   118,   119,   120,   121,    80,   122,   123,   124,    25,
-      26,    27,   126,   159,   160,   161,   162,   163,   164,   203,
-     204,   243,   244,   245,   219,   220,   191,    48,   192,   175,
-     176,    28,    29,    30,    31,    32,    33,    34,   130,    67,
-      35,   133,    73,    74,    36,    37,    38,    68,    69,    54,
-      94
-};
-
-/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
-   STATE-NUM.  */
-#define YYPACT_NINF -156
-static const yytype_int16 yypact[] =
-{
-    -156,    20,   215,  -156,   -18,    15,    21,    41,  -156,    13,
-      13,    63,    41,    41,  -156,  -156,  -156,  -156,  -156,  -156,
-    -156,     4,  -156,    27,  -156,    27,    59,  -156,    27,    27,
-      27,    27,    27,  -156,    -5,    27,   -21,    37,    37,  -156,
-      17,    78,  -156,  -156,  -156,    41,    41,  -156,   145,  -156,
-    -156,  -156,   145,   145,    74,    66,  -156,  -156,  -156,   132,
-    -156,  -156,  -156,  -156,  -156,  -156,  -156,    32,    96,  -156,
-    -156,  -156,    97,   118,  -156,   118,   118,  -156,  -156,    -5,
-      -5,   124,  -156,  -156,    81,    41,    41,    41,    41,    41,
-    -156,  -156,  -156,  -156,  -156,  -156,   141,  -156,  -156,  -156,
-    -156,  -156,  -156,  -156,  -156,  -156,  -156,  -156,  -156,  -156,
-    -156,  -156,  -156,    80,  -156,   129,  -156,    62,   -19,  -156,
-     125,   -26,  -156,  -156,  -156,   190,    10,   131,    -5,   127,
-    -156,   128,  -156,    23,    -9,   146,   134,   135,  -156,  -156,
-      34,    34,   164,   164,  -156,   162,   250,  -156,    41,   236,
-     165,    41,   171,  -156,   172,   183,   184,   180,  -156,   186,
-    -156,  -156,  -156,  -156,  -156,   211,  -156,    96,   236,    37,
-    -156,  -156,  -156,    41,  -156,   -20,  -156,  -156,  -156,  -156,
-    -156,  -156,   -24,   213,   214,    31,  -156,   197,  -156,  -156,
-    -156,  -156,  -156,  -156,    76,   236,  -156,  -156,  -156,    60,
-    -156,    11,    18,    12,   192,   203,  -156,  -156,  -156,   121,
-    -156,  -156,   196,   162,   165,  -156,   217,   221,   241,  -156,
-      40,   228,   119,  -156,  -156,  -156,  -156,  -156,    14,  -156,
-    -156,  -156,  -156,   -20,  -156,  -156,   236,  -156,   230,  -156,
-      44,  -156,   231,   224,  -156,  -156,  -156,  -156,  -156,  -156,
-    -156,   249,    24,  -156,  -156
-};
-
-/* YYPGOTO[NTERM-NUM].  */
-static const yytype_int16 yypgoto[] =
-{
-    -156,  -156,  -156,  -156,   202,  -156,  -156,  -156,   166,  -156,
-    -156,   147,  -156,  -156,   149,   179,  -156,  -156,   150,  -156,
-    -156,   155,  -155,   133,  -156,  -156,  -156,  -156,  -156,  -156,
-    -156,  -156,    48,  -156,  -141,    79,    -6,   -10,  -127,  -156,
-    -156,  -156,  -156,  -156,  -156,  -156,  -156,  -156,   136,  -156,
-    -156,   -32,  -156,   -33,  -156,  -156,  -156,   -30,    -2,  -156,
-    -156
-};
-
-/* YYTABLE[YYPACT[STATE-NUM]].  What to do in state STATE-NUM.  If
-   positive, shift that token.  If negative, reduce the rule which
-   number is the opposite.  If zero, do what YYDEFACT says.
-   If YYTABLE_NINF, syntax error.  */
-#define YYTABLE_NINF -1
-static const yytype_uint8 yytable[] =
-{
-      39,    47,    52,    53,    75,    76,   174,   201,   190,   202,
-      81,   156,   156,   226,    71,   241,    44,     5,    44,   156,
-       3,   170,   150,    40,    45,   156,    45,   207,   172,    77,
-      78,    20,    46,   177,    46,    83,    84,   153,   178,   211,
-      72,   173,   151,   134,   135,    55,    20,    20,   210,   136,
-     137,   157,   157,    20,    20,   242,    41,   125,   223,   157,
-      20,    56,    42,    79,   170,   157,   158,   224,   227,    43,
-     171,   172,    71,    44,   225,   140,   141,   142,   143,   144,
-     254,    45,    57,    44,   173,    87,    88,    89,   127,    46,
-     252,    45,    77,    78,   215,   247,   235,   128,   167,    46,
-     249,   221,    44,   188,    51,   236,   246,   189,   172,   236,
-      45,    90,    91,    92,    93,   154,    61,   222,    46,    82,
-     148,   173,   149,    95,   165,    85,    86,    87,    88,    89,
-      85,    86,    87,    88,    89,    96,   208,   129,   218,   131,
-     139,   194,   187,    97,    98,    99,   100,   101,   102,   103,
-     104,   105,   106,   107,   108,   109,   110,   111,   112,   132,
-     238,    44,   188,   209,    49,    50,   189,   172,    20,    45,
-      85,    86,    87,    88,    89,   239,   212,    46,   113,   216,
-     173,   138,   145,   230,   147,   152,   166,   168,   114,   179,
-     169,   180,   181,    96,    85,    86,    87,    88,    89,   165,
-     165,    97,    98,    99,   100,   101,   102,   103,   104,   105,
-     106,   107,   108,   109,   110,   111,   112,    89,     4,     5,
-       6,     7,     8,     9,    10,    11,   182,    60,   195,   193,
-      62,    63,    64,    65,    66,   196,   113,    70,   197,   198,
-     199,   200,    12,    13,    14,    15,    16,    17,    18,    19,
-     165,    20,   157,   183,   213,   214,   217,   228,   229,   231,
-      21,    97,    98,    99,   100,   101,   102,   103,   104,   105,
-     106,   107,   108,   109,   110,   111,   112,   170,    44,   188,
-     232,   233,   234,   189,   172,   237,    45,   248,   250,   251,
-     242,   155,   146,   184,    46,   185,   186,   173,   205,   253,
-       0,   240,     0,   206
-};
-
-static const yytype_int16 yycheck[] =
-{
-       2,     7,    12,    13,    37,    38,   133,   162,   149,   164,
-      40,     1,     1,     1,    35,     1,    42,     4,    42,     1,
-       0,    41,    41,    41,    50,     1,    50,   168,    48,    12,
-      13,    36,    58,    42,    58,    45,    46,    63,    47,    63,
-      61,    61,    61,    75,    76,    41,    36,    36,   175,    79,
-      80,    41,    41,    36,    36,    41,    41,    59,   199,    41,
-      36,    57,    41,    46,    41,    41,    56,    56,    56,    48,
-      47,    48,    35,    42,    56,    85,    86,    87,    88,    89,
-      56,    50,    55,    42,    61,    51,    52,    53,    56,    58,
-     245,    50,    12,    13,    63,   236,    56,    65,   128,    58,
-      56,    41,    42,    43,    41,    65,   233,    47,    48,    65,
-      50,    37,    38,    39,    40,   121,    57,    57,    58,    41,
-      58,    61,    60,    57,   126,    49,    50,    51,    52,    53,
-      49,    50,    51,    52,    53,     3,   169,    41,    62,    42,
-      59,   151,   148,    11,    12,    13,    14,    15,    16,    17,
-      18,    19,    20,    21,    22,    23,    24,    25,    26,    41,
-      41,    42,    43,   173,     9,    10,    47,    48,    36,    50,
-      49,    50,    51,    52,    53,    56,   182,    58,    46,   185,
-      61,    57,    41,    62,    55,    60,    55,    60,    56,    43,
-      62,    57,    57,     3,    49,    50,    51,    52,    53,   201,
-     202,    11,    12,    13,    14,    15,    16,    17,    18,    19,
-      20,    21,    22,    23,    24,    25,    26,    53,     3,     4,
-       5,     6,     7,     8,     9,    10,    64,    25,    57,    64,
-      28,    29,    30,    31,    32,    63,    46,    35,    55,    55,
-      60,    55,    27,    28,    29,    30,    31,    32,    33,    34,
-     252,    36,    41,     3,    41,    41,    59,    65,    55,    63,
-      45,    11,    12,    13,    14,    15,    16,    17,    18,    19,
-      20,    21,    22,    23,    24,    25,    26,    41,    42,    43,
-      63,    60,    41,    47,    48,    57,    50,    57,    57,    65,
-      41,   125,   113,   146,    58,   146,   146,    61,   165,   251,
-      -1,   222,    -1,   167
-};
-
-/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
-   symbol of state STATE-NUM.  */
-static const yytype_uint8 yystos[] =
-{
-       0,    67,    68,     0,     3,     4,     5,     6,     7,     8,
-       9,    10,    27,    28,    29,    30,    31,    32,    33,    34,
-      36,    45,    69,    71,    72,    85,    86,    87,   107,   108,
-     109,   110,   111,   112,   113,   116,   120,   121,   122,   124,
-      41,    41,    41,    48,    42,    50,    58,   102,   103,    87,
-      87,    41,   103,   103,   125,    41,    57,    55,    70,    73,
-      70,    57,    70,    70,    70,    70,    70,   115,   123,   124,
-      70,    35,    61,   118,   119,   119,   119,    12,    13,    46,
-      81,   123,    41,   103,   103,    49,    50,    51,    52,    53,
-      37,    38,    39,    40,   126,    57,     3,    11,    12,    13,
-      14,    15,    16,    17,    18,    19,    20,    21,    22,    23,
-      24,    25,    26,    46,    56,    74,    75,    76,    77,    78,
-      79,    80,    82,    83,    84,   124,    88,    56,    65,    41,
-     114,    42,    41,   117,   117,   117,   123,   123,    57,    59,
-     103,   103,   103,   103,   103,    41,    81,    55,    58,    60,
-      41,    61,    60,    63,   102,    74,     1,    41,    56,    89,
-      90,    91,    92,    93,    94,   124,    55,   123,    60,    62,
-      41,    47,    48,    61,   104,   105,   106,    42,    47,    43,
-      57,    57,    64,     3,    77,    80,    84,   102,    43,    47,
-     100,   102,   104,    64,   103,    57,    63,    55,    55,    60,
-      55,    88,    88,    95,    96,    89,   114,   100,   119,   103,
-     104,    63,   102,    41,    41,    63,   102,    59,    62,   100,
-     101,    41,    57,   100,    56,    56,     1,    56,    65,    55,
-      62,    63,    63,    60,    41,    56,    65,    57,    41,    56,
-     101,     1,    41,    97,    98,    99,   104,   100,    57,    56,
-      57,    65,    88,    98,    56
-};
-
-#define yyerrok		(yyerrstatus = 0)
-#define yyclearin	(yychar = YYEMPTY)
-#define YYEMPTY		(-2)
-#define YYEOF		0
-
-#define YYACCEPT	goto yyacceptlab
-#define YYABORT		goto yyabortlab
-#define YYERROR		goto yyerrorlab
-
-
-/* Like YYERROR except do call yyerror.  This remains here temporarily
-   to ease the transition to the new meaning of YYERROR, for GCC.
-   Once GCC version 2 has supplanted version 1, this can go.  */
-
-#define YYFAIL		goto yyerrlab
-
-#define YYRECOVERING()  (!!yyerrstatus)
-
-#define YYBACKUP(Token, Value)					\
-do								\
-  if (yychar == YYEMPTY && yylen == 1)				\
-    {								\
-      yychar = (Token);						\
-      yylval = (Value);						\
-      yytoken = YYTRANSLATE (yychar);				\
-      YYPOPSTACK (1);						\
-      goto yybackup;						\
-    }								\
-  else								\
-    {								\
-      yyerror (YY_("syntax error: cannot back up")); \
-      YYERROR;							\
-    }								\
-while (YYID (0))
-
-
-#define YYTERROR	1
-#define YYERRCODE	256
-
-
-/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
-   If N is 0, then set CURRENT to the empty location which ends
-   the previous symbol: RHS[0] (always defined).  */
-
-#define YYRHSLOC(Rhs, K) ((Rhs)[K])
-#ifndef YYLLOC_DEFAULT
-# define YYLLOC_DEFAULT(Current, Rhs, N)				\
-    do									\
-      if (YYID (N))                                                    \
-	{								\
-	  (Current).first_line   = YYRHSLOC (Rhs, 1).first_line;	\
-	  (Current).first_column = YYRHSLOC (Rhs, 1).first_column;	\
-	  (Current).last_line    = YYRHSLOC (Rhs, N).last_line;		\
-	  (Current).last_column  = YYRHSLOC (Rhs, N).last_column;	\
-	}								\
-      else								\
-	{								\
-	  (Current).first_line   = (Current).last_line   =		\
-	    YYRHSLOC (Rhs, 0).last_line;				\
-	  (Current).first_column = (Current).last_column =		\
-	    YYRHSLOC (Rhs, 0).last_column;				\
-	}								\
-    while (YYID (0))
-#endif
-
-
-/* YY_LOCATION_PRINT -- Print the location on the stream.
-   This macro was not mandated originally: define only if we know
-   we won't break user code: when these are the locations we know.  */
-
-#ifndef YY_LOCATION_PRINT
-# if YYLTYPE_IS_TRIVIAL
-#  define YY_LOCATION_PRINT(File, Loc)			\
-     fprintf (File, "%d.%d-%d.%d",			\
-	      (Loc).first_line, (Loc).first_column,	\
-	      (Loc).last_line,  (Loc).last_column)
-# else
-#  define YY_LOCATION_PRINT(File, Loc) ((void) 0)
-# endif
-#endif
-
-
-/* YYLEX -- calling `yylex' with the right arguments.  */
-
-#ifdef YYLEX_PARAM
-# define YYLEX yylex (YYLEX_PARAM)
-#else
-# define YYLEX yylex ()
-#endif
-
-/* Enable debugging if requested.  */
-#if YYDEBUG
-
-# ifndef YYFPRINTF
-#  include <stdio.h> /* INFRINGES ON USER NAME SPACE */
-#  define YYFPRINTF fprintf
-# endif
-
-# define YYDPRINTF(Args)			\
-do {						\
-  if (yydebug)					\
-    YYFPRINTF Args;				\
-} while (YYID (0))
-
-# define YY_SYMBOL_PRINT(Title, Type, Value, Location)			  \
-do {									  \
-  if (yydebug)								  \
-    {									  \
-      YYFPRINTF (stderr, "%s ", Title);					  \
-      yy_symbol_print (stderr,						  \
-		  Type, Value); \
-      YYFPRINTF (stderr, "\n");						  \
-    }									  \
-} while (YYID (0))
-
-
-/*--------------------------------.
-| Print this symbol on YYOUTPUT.  |
-`--------------------------------*/
-
-/*ARGSUSED*/
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-static void
-yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
-#else
-static void
-yy_symbol_value_print (yyoutput, yytype, yyvaluep)
-    FILE *yyoutput;
-    int yytype;
-    YYSTYPE const * const yyvaluep;
-#endif
-{
-  if (!yyvaluep)
-    return;
-# ifdef YYPRINT
-  if (yytype < YYNTOKENS)
-    YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
-# else
-  YYUSE (yyoutput);
-# endif
-  switch (yytype)
-    {
-      default:
-	break;
-    }
-}
-
-
-/*--------------------------------.
-| Print this symbol on YYOUTPUT.  |
-`--------------------------------*/
-
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-static void
-yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
-#else
-static void
-yy_symbol_print (yyoutput, yytype, yyvaluep)
-    FILE *yyoutput;
-    int yytype;
-    YYSTYPE const * const yyvaluep;
-#endif
-{
-  if (yytype < YYNTOKENS)
-    YYFPRINTF (yyoutput, "token %s (", yytname[yytype]);
-  else
-    YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]);
-
-  yy_symbol_value_print (yyoutput, yytype, yyvaluep);
-  YYFPRINTF (yyoutput, ")");
-}
-
-/*------------------------------------------------------------------.
-| yy_stack_print -- Print the state stack from its BOTTOM up to its |
-| TOP (included).                                                   |
-`------------------------------------------------------------------*/
-
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-static void
-yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
-#else
-static void
-yy_stack_print (yybottom, yytop)
-    yytype_int16 *yybottom;
-    yytype_int16 *yytop;
-#endif
-{
-  YYFPRINTF (stderr, "Stack now");
-  for (; yybottom <= yytop; yybottom++)
-    {
-      int yybot = *yybottom;
-      YYFPRINTF (stderr, " %d", yybot);
-    }
-  YYFPRINTF (stderr, "\n");
-}
-
-# define YY_STACK_PRINT(Bottom, Top)				\
-do {								\
-  if (yydebug)							\
-    yy_stack_print ((Bottom), (Top));				\
-} while (YYID (0))
-
-
-/*------------------------------------------------.
-| Report that the YYRULE is going to be reduced.  |
-`------------------------------------------------*/
-
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-static void
-yy_reduce_print (YYSTYPE *yyvsp, int yyrule)
-#else
-static void
-yy_reduce_print (yyvsp, yyrule)
-    YYSTYPE *yyvsp;
-    int yyrule;
-#endif
-{
-  int yynrhs = yyr2[yyrule];
-  int yyi;
-  unsigned long int yylno = yyrline[yyrule];
-  YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
-	     yyrule - 1, yylno);
-  /* The symbols being reduced.  */
-  for (yyi = 0; yyi < yynrhs; yyi++)
-    {
-      YYFPRINTF (stderr, "   $%d = ", yyi + 1);
-      yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi],
-		       &(yyvsp[(yyi + 1) - (yynrhs)])
-		       		       );
-      YYFPRINTF (stderr, "\n");
-    }
-}
-
-# define YY_REDUCE_PRINT(Rule)		\
-do {					\
-  if (yydebug)				\
-    yy_reduce_print (yyvsp, Rule); \
-} while (YYID (0))
-
-/* Nonzero means print parse trace.  It is left uninitialized so that
-   multiple parsers can coexist.  */
-int yydebug;
-#else /* !YYDEBUG */
-# define YYDPRINTF(Args)
-# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
-# define YY_STACK_PRINT(Bottom, Top)
-# define YY_REDUCE_PRINT(Rule)
-#endif /* !YYDEBUG */
-
-
-/* YYINITDEPTH -- initial size of the parser's stacks.  */
-#ifndef	YYINITDEPTH
-# define YYINITDEPTH 200
-#endif
-
-/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
-   if the built-in stack extension method is used).
-
-   Do not make this value too large; the results are undefined if
-   YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
-   evaluated with infinite-precision integer arithmetic.  */
-
-#ifndef YYMAXDEPTH
-# define YYMAXDEPTH 10000
-#endif
-
-
-
-#if YYERROR_VERBOSE
-
-# ifndef yystrlen
-#  if defined __GLIBC__ && defined _STRING_H
-#   define yystrlen strlen
-#  else
-/* Return the length of YYSTR.  */
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-static YYSIZE_T
-yystrlen (const char *yystr)
-#else
-static YYSIZE_T
-yystrlen (yystr)
-    const char *yystr;
-#endif
-{
-  YYSIZE_T yylen;
-  for (yylen = 0; yystr[yylen]; yylen++)
-    continue;
-  return yylen;
-}
-#  endif
-# endif
-
-# ifndef yystpcpy
-#  if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
-#   define yystpcpy stpcpy
-#  else
-/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
-   YYDEST.  */
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-static char *
-yystpcpy (char *yydest, const char *yysrc)
-#else
-static char *
-yystpcpy (yydest, yysrc)
-    char *yydest;
-    const char *yysrc;
-#endif
-{
-  char *yyd = yydest;
-  const char *yys = yysrc;
-
-  while ((*yyd++ = *yys++) != '\0')
-    continue;
-
-  return yyd - 1;
-}
-#  endif
-# endif
-
-# ifndef yytnamerr
-/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
-   quotes and backslashes, so that it's suitable for yyerror.  The
-   heuristic is that double-quoting is unnecessary unless the string
-   contains an apostrophe, a comma, or backslash (other than
-   backslash-backslash).  YYSTR is taken from yytname.  If YYRES is
-   null, do not copy; instead, return the length of what the result
-   would have been.  */
-static YYSIZE_T
-yytnamerr (char *yyres, const char *yystr)
-{
-  if (*yystr == '"')
-    {
-      YYSIZE_T yyn = 0;
-      char const *yyp = yystr;
-
-      for (;;)
-	switch (*++yyp)
-	  {
-	  case '\'':
-	  case ',':
-	    goto do_not_strip_quotes;
-
-	  case '\\':
-	    if (*++yyp != '\\')
-	      goto do_not_strip_quotes;
-	    /* Fall through.  */
-	  default:
-	    if (yyres)
-	      yyres[yyn] = *yyp;
-	    yyn++;
-	    break;
-
-	  case '"':
-	    if (yyres)
-	      yyres[yyn] = '\0';
-	    return yyn;
-	  }
-    do_not_strip_quotes: ;
-    }
-
-  if (! yyres)
-    return yystrlen (yystr);
-
-  return yystpcpy (yyres, yystr) - yyres;
-}
-# endif
-
-/* Copy into YYRESULT an error message about the unexpected token
-   YYCHAR while in state YYSTATE.  Return the number of bytes copied,
-   including the terminating null byte.  If YYRESULT is null, do not
-   copy anything; just return the number of bytes that would be
-   copied.  As a special case, return 0 if an ordinary "syntax error"
-   message will do.  Return YYSIZE_MAXIMUM if overflow occurs during
-   size calculation.  */
-static YYSIZE_T
-yysyntax_error (char *yyresult, int yystate, int yychar)
-{
-  int yyn = yypact[yystate];
-
-  if (! (YYPACT_NINF < yyn && yyn <= YYLAST))
-    return 0;
-  else
-    {
-      int yytype = YYTRANSLATE (yychar);
-      YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]);
-      YYSIZE_T yysize = yysize0;
-      YYSIZE_T yysize1;
-      int yysize_overflow = 0;
-      enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
-      char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
-      int yyx;
-
-# if 0
-      /* This is so xgettext sees the translatable formats that are
-	 constructed on the fly.  */
-      YY_("syntax error, unexpected %s");
-      YY_("syntax error, unexpected %s, expecting %s");
-      YY_("syntax error, unexpected %s, expecting %s or %s");
-      YY_("syntax error, unexpected %s, expecting %s or %s or %s");
-      YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s");
-# endif
-      char *yyfmt;
-      char const *yyf;
-      static char const yyunexpected[] = "syntax error, unexpected %s";
-      static char const yyexpecting[] = ", expecting %s";
-      static char const yyor[] = " or %s";
-      char yyformat[sizeof yyunexpected
-		    + sizeof yyexpecting - 1
-		    + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2)
-		       * (sizeof yyor - 1))];
-      char const *yyprefix = yyexpecting;
-
-      /* Start YYX at -YYN if negative to avoid negative indexes in
-	 YYCHECK.  */
-      int yyxbegin = yyn < 0 ? -yyn : 0;
-
-      /* Stay within bounds of both yycheck and yytname.  */
-      int yychecklim = YYLAST - yyn + 1;
-      int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
-      int yycount = 1;
-
-      yyarg[0] = yytname[yytype];
-      yyfmt = yystpcpy (yyformat, yyunexpected);
-
-      for (yyx = yyxbegin; yyx < yyxend; ++yyx)
-	if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
-	  {
-	    if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
-	      {
-		yycount = 1;
-		yysize = yysize0;
-		yyformat[sizeof yyunexpected - 1] = '\0';
-		break;
-	      }
-	    yyarg[yycount++] = yytname[yyx];
-	    yysize1 = yysize + yytnamerr (0, yytname[yyx]);
-	    yysize_overflow |= (yysize1 < yysize);
-	    yysize = yysize1;
-	    yyfmt = yystpcpy (yyfmt, yyprefix);
-	    yyprefix = yyor;
-	  }
-
-      yyf = YY_(yyformat);
-      yysize1 = yysize + yystrlen (yyf);
-      yysize_overflow |= (yysize1 < yysize);
-      yysize = yysize1;
-
-      if (yysize_overflow)
-	return YYSIZE_MAXIMUM;
-
-      if (yyresult)
-	{
-	  /* Avoid sprintf, as that infringes on the user's name space.
-	     Don't have undefined behavior even if the translation
-	     produced a string with the wrong number of "%s"s.  */
-	  char *yyp = yyresult;
-	  int yyi = 0;
-	  while ((*yyp = *yyf) != '\0')
-	    {
-	      if (*yyp == '%' && yyf[1] == 's' && yyi < yycount)
-		{
-		  yyp += yytnamerr (yyp, yyarg[yyi++]);
-		  yyf += 2;
-		}
-	      else
-		{
-		  yyp++;
-		  yyf++;
-		}
-	    }
-	}
-      return yysize;
-    }
-}
-#endif /* YYERROR_VERBOSE */
-
-
-/*-----------------------------------------------.
-| Release the memory associated to this symbol.  |
-`-----------------------------------------------*/
-
-/*ARGSUSED*/
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-static void
-yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep)
-#else
-static void
-yydestruct (yymsg, yytype, yyvaluep)
-    const char *yymsg;
-    int yytype;
-    YYSTYPE *yyvaluep;
-#endif
-{
-  YYUSE (yyvaluep);
-
-  if (!yymsg)
-    yymsg = "Deleting";
-  YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
-
-  switch (yytype)
-    {
-
-      default:
-	break;
-    }
-}
-
-/* Prevent warnings from -Wmissing-prototypes.  */
-#ifdef YYPARSE_PARAM
-#if defined __STDC__ || defined __cplusplus
-int yyparse (void *YYPARSE_PARAM);
-#else
-int yyparse ();
-#endif
-#else /* ! YYPARSE_PARAM */
-#if defined __STDC__ || defined __cplusplus
-int yyparse (void);
-#else
-int yyparse ();
-#endif
-#endif /* ! YYPARSE_PARAM */
-
-
-/* The lookahead symbol.  */
-int yychar;
-
-/* The semantic value of the lookahead symbol.  */
-YYSTYPE yylval;
-
-/* Number of syntax errors so far.  */
-int yynerrs;
-
-
-
-/*-------------------------.
-| yyparse or yypush_parse.  |
-`-------------------------*/
-
-#ifdef YYPARSE_PARAM
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-int
-yyparse (void *YYPARSE_PARAM)
-#else
-int
-yyparse (YYPARSE_PARAM)
-    void *YYPARSE_PARAM;
-#endif
-#else /* ! YYPARSE_PARAM */
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-int
-yyparse (void)
-#else
-int
-yyparse ()
-
-#endif
-#endif
-{
-
-
-    int yystate;
-    /* Number of tokens to shift before error messages enabled.  */
-    int yyerrstatus;
-
-    /* The stacks and their tools:
-       `yyss': related to states.
-       `yyvs': related to semantic values.
-
-       Refer to the stacks thru separate pointers, to allow yyoverflow
-       to reallocate them elsewhere.  */
-
-    /* The state stack.  */
-    yytype_int16 yyssa[YYINITDEPTH];
-    yytype_int16 *yyss;
-    yytype_int16 *yyssp;
-
-    /* The semantic value stack.  */
-    YYSTYPE yyvsa[YYINITDEPTH];
-    YYSTYPE *yyvs;
-    YYSTYPE *yyvsp;
-
-    YYSIZE_T yystacksize;
-
-  int yyn;
-  int yyresult;
-  /* Lookahead token as an internal (translated) token number.  */
-  int yytoken;
-  /* The variables used to return semantic value and location from the
-     action routines.  */
-  YYSTYPE yyval;
-
-#if YYERROR_VERBOSE
-  /* Buffer for error messages, and its allocated size.  */
-  char yymsgbuf[128];
-  char *yymsg = yymsgbuf;
-  YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
-#endif
-
-#define YYPOPSTACK(N)   (yyvsp -= (N), yyssp -= (N))
-
-  /* The number of symbols on the RHS of the reduced rule.
-     Keep to zero when no symbol should be popped.  */
-  int yylen = 0;
-
-  yytoken = 0;
-  yyss = yyssa;
-  yyvs = yyvsa;
-  yystacksize = YYINITDEPTH;
-
-  YYDPRINTF ((stderr, "Starting parse\n"));
-
-  yystate = 0;
-  yyerrstatus = 0;
-  yynerrs = 0;
-  yychar = YYEMPTY; /* Cause a token to be read.  */
-
-  /* Initialize stack pointers.
-     Waste one element of value and location stack
-     so that they stay on the same level as the state stack.
-     The wasted elements are never initialized.  */
-  yyssp = yyss;
-  yyvsp = yyvs;
-
-  goto yysetstate;
-
-/*------------------------------------------------------------.
-| yynewstate -- Push a new state, which is found in yystate.  |
-`------------------------------------------------------------*/
- yynewstate:
-  /* In all cases, when you get here, the value and location stacks
-     have just been pushed.  So pushing a state here evens the stacks.  */
-  yyssp++;
-
- yysetstate:
-  *yyssp = yystate;
-
-  if (yyss + yystacksize - 1 <= yyssp)
-    {
-      /* Get the current used size of the three stacks, in elements.  */
-      YYSIZE_T yysize = yyssp - yyss + 1;
-
-#ifdef yyoverflow
-      {
-	/* Give user a chance to reallocate the stack.  Use copies of
-	   these so that the &'s don't force the real ones into
-	   memory.  */
-	YYSTYPE *yyvs1 = yyvs;
-	yytype_int16 *yyss1 = yyss;
-
-	/* Each stack pointer address is followed by the size of the
-	   data in use in that stack, in bytes.  This used to be a
-	   conditional around just the two extra args, but that might
-	   be undefined if yyoverflow is a macro.  */
-	yyoverflow (YY_("memory exhausted"),
-		    &yyss1, yysize * sizeof (*yyssp),
-		    &yyvs1, yysize * sizeof (*yyvsp),
-		    &yystacksize);
-
-	yyss = yyss1;
-	yyvs = yyvs1;
-      }
-#else /* no yyoverflow */
-# ifndef YYSTACK_RELOCATE
-      goto yyexhaustedlab;
-# else
-      /* Extend the stack our own way.  */
-      if (YYMAXDEPTH <= yystacksize)
-	goto yyexhaustedlab;
-      yystacksize *= 2;
-      if (YYMAXDEPTH < yystacksize)
-	yystacksize = YYMAXDEPTH;
-
-      {
-	yytype_int16 *yyss1 = yyss;
-	union yyalloc *yyptr =
-	  (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
-	if (! yyptr)
-	  goto yyexhaustedlab;
-	YYSTACK_RELOCATE (yyss_alloc, yyss);
-	YYSTACK_RELOCATE (yyvs_alloc, yyvs);
-#  undef YYSTACK_RELOCATE
-	if (yyss1 != yyssa)
-	  YYSTACK_FREE (yyss1);
-      }
-# endif
-#endif /* no yyoverflow */
-
-      yyssp = yyss + yysize - 1;
-      yyvsp = yyvs + yysize - 1;
-
-      YYDPRINTF ((stderr, "Stack size increased to %lu\n",
-		  (unsigned long int) yystacksize));
-
-      if (yyss + yystacksize - 1 <= yyssp)
-	YYABORT;
-    }
-
-  YYDPRINTF ((stderr, "Entering state %d\n", yystate));
-
-  if (yystate == YYFINAL)
-    YYACCEPT;
-
-  goto yybackup;
-
-/*-----------.
-| yybackup.  |
-`-----------*/
-yybackup:
-
-  /* Do appropriate processing given the current state.  Read a
-     lookahead token if we need one and don't already have one.  */
-
-  /* First try to decide what to do without reference to lookahead token.  */
-  yyn = yypact[yystate];
-  if (yyn == YYPACT_NINF)
-    goto yydefault;
-
-  /* Not known => get a lookahead token if don't already have one.  */
-
-  /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol.  */
-  if (yychar == YYEMPTY)
-    {
-      YYDPRINTF ((stderr, "Reading a token: "));
-      yychar = YYLEX;
-    }
-
-  if (yychar <= YYEOF)
-    {
-      yychar = yytoken = YYEOF;
-      YYDPRINTF ((stderr, "Now at end of input.\n"));
-    }
-  else
-    {
-      yytoken = YYTRANSLATE (yychar);
-      YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
-    }
-
-  /* If the proper action on seeing token YYTOKEN is to reduce or to
-     detect an error, take that action.  */
-  yyn += yytoken;
-  if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
-    goto yydefault;
-  yyn = yytable[yyn];
-  if (yyn <= 0)
-    {
-      if (yyn == 0 || yyn == YYTABLE_NINF)
-	goto yyerrlab;
-      yyn = -yyn;
-      goto yyreduce;
-    }
-
-  /* Count tokens shifted since error; after three, turn off error
-     status.  */
-  if (yyerrstatus)
-    yyerrstatus--;
-
-  /* Shift the lookahead token.  */
-  YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
-
-  /* Discard the shifted token.  */
-  yychar = YYEMPTY;
-
-  yystate = yyn;
-  *++yyvsp = yylval;
-
-  goto yynewstate;
-
-
-/*-----------------------------------------------------------.
-| yydefault -- do the default action for the current state.  |
-`-----------------------------------------------------------*/
-yydefault:
-  yyn = yydefact[yystate];
-  if (yyn == 0)
-    goto yyerrlab;
-  goto yyreduce;
-
-
-/*-----------------------------.
-| yyreduce -- Do a reduction.  |
-`-----------------------------*/
-yyreduce:
-  /* yyn is the number of a rule to reduce with.  */
-  yylen = yyr2[yyn];
-
-  /* If YYLEN is nonzero, implement the default value of the action:
-     `$$ = $1'.
-
-     Otherwise, the following line sets YYVAL to garbage.
-     This behavior is undocumented and Bison
-     users should not rely upon it.  Assigning to YYVAL
-     unconditionally makes the parser a bit smaller, and it avoids a
-     GCC warning that YYVAL may be used uninitialized.  */
-  yyval = yyvsp[1-yylen];
-
-
-  YY_REDUCE_PRINT (yyn);
-  switch (yyn)
-    {
-        case 2:
-
-/* Line 1455 of yacc.c  */
-#line 182 "rcomp.yacc"
-    {	if(verbose)	{	MOFF; cout << Divider << "\n" << Divider << endl; MON; }
-										;}
-    break;
-
-  case 15:
-
-/* Line 1455 of yacc.c  */
-#line 208 "rcomp.yacc"
-    {
-		// This is my gift to the world: no more "syntax error" for adding
-		// an extra semicolon at the end of a struct or resource.
-	    REGISTER_LINE;
-	    ErrorHandler::OutputErrorLine("Warning: unnecessary semicolon");
-		;}
-    break;
-
-  case 17:
-
-/* Line 1455 of yacc.c  */
-#line 222 "rcomp.yacc"
-    {	if(verbose) { MOFF; cout << Divider << "\n" << * pSH << Divider << endl; MON;}	;}
-    break;
-
-  case 18:
-
-/* Line 1455 of yacc.c  */
-#line 226 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "struct_statement_start                     " << (yyvsp[(2) - (4)].Value) << endl; MON;}
-											pSH = new StructHeader((yyvsp[(2) - (4)].Value));
-											REGISTER_LINE;
-											pG->SHA.Add(pSH);
-										;}
-    break;
-
-  case 19:
-
-/* Line 1455 of yacc.c  */
-#line 232 "rcomp.yacc"
-    {	if(verbose) {	RCTypeArray Types; MOFF;cout << "struct_statement_start                     " << (yyvsp[(2) - (5)].Value) << " " << Types.GetName((yyvsp[(3) - (5)].Id)) << endl; MON;}
-											pSH = new StructHeader((yyvsp[(2) - (5)].Value), (yyvsp[(3) - (5)].Id));
-											REGISTER_LINE;
-											pG->SHA.Add(pSH);
-										;}
-    break;
-
-  case 20:
-
-/* Line 1455 of yacc.c  */
-#line 238 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "struct_statement_start                     " << (yyvsp[(2) - (5)].Value) << " (WORD)" << endl; MON;}
-											pSH = new StructHeader((yyvsp[(2) - (5)].Value), L_WORD);
-											REGISTER_LINE;
-											pG->SHA.Add(pSH);
-										;}
-    break;
-
-  case 21:
-
-/* Line 1455 of yacc.c  */
-#line 245 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "struct_item_list                           Adding struct_item." << endl; MON;}
-											REGISTER_LINE;
-											pSH->iSIA.Add((yyvsp[(2) - (3)].pStructItem));
-										;}
-    break;
-
-  case 22:
-
-/* Line 1455 of yacc.c  */
-#line 249 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "tagged struct_item_list                    Adding struct_item." << endl; MON;}
-											REGISTER_LINE;
-											pSH->iSIA.Add((yyvsp[(3) - (4)].pStructItem));
-										;}
-    break;
-
-  case 28:
-
-/* Line 1455 of yacc.c  */
-#line 262 "rcomp.yacc"
-    {	(yyval.pStructItem) = (yyvsp[(1) - (1)].pSimpleStructItem);;}
-    break;
-
-  case 29:
-
-/* Line 1455 of yacc.c  */
-#line 264 "rcomp.yacc"
-    {	if(verbose) { MOFF;cout << "    Limit: " << (yyvsp[(3) - (4)].Value) << endl; MON;}
-											(yyvsp[(1) - (4)].pSimpleStructItem)->iLengthLimit = (yyvsp[(3) - (4)].Value);
-											(yyval.pStructItem) = (yyvsp[(1) - (4)].pSimpleStructItem);
-										;}
-    break;
-
-  case 30:
-
-/* Line 1455 of yacc.c  */
-#line 269 "rcomp.yacc"
-    {	if(verbose) { MOFF;cout << "    Default: " << (yyvsp[(3) - (3)].Value) << endl; MON;}
-											(yyvsp[(1) - (3)].pSimpleStructItem)->iDefault = (yyvsp[(3) - (3)].Value);
-											(yyval.pStructItem) = (yyvsp[(1) - (3)].pSimpleStructItem);
-										;}
-    break;
-
-  case 31:
-
-/* Line 1455 of yacc.c  */
-#line 274 "rcomp.yacc"
-    {	if(verbose) { MOFF;cout << "    Limit: " << (yyvsp[(3) - (6)].Value) << ", Default: " << (yyvsp[(6) - (6)].Value) << endl; MON;}
-											NumericValue Limit((yyvsp[(3) - (6)].Value), L_LONG);
-											if(String((yyvsp[(6) - (6)].Value)).ExportLength(TargetCharacterSet,SourceCharacterSet) > Limit.GetULong() )
-											{
-												REGISTER_LINE;
-												ErrorHandler::OutputErrorLine("Text length exceeds specified limit");
-												exit(1);
-											}
-											(yyvsp[(1) - (6)].pSimpleStructItem)->iLengthLimit = (yyvsp[(3) - (6)].Value);
-											(yyvsp[(1) - (6)].pSimpleStructItem)->iDefault = (yyvsp[(6) - (6)].Value);
-											(yyval.pStructItem) = (yyvsp[(1) - (6)].pSimpleStructItem);
-										;}
-    break;
-
-  case 32:
-
-/* Line 1455 of yacc.c  */
-#line 289 "rcomp.yacc"
-    {	if(verbose) 
-											{		
-												   RCTypeArray Types;
-														   MOFF;cout << "simple_struct_item                         " << Types.GetName((yyvsp[(1) - (2)].Id)) << " " << (yyvsp[(2) - (2)].Value) << endl; MON;
-											}
-											(yyval.pSimpleStructItem) = new SimpleStructItem((yyvsp[(1) - (2)].Id),(yyvsp[(2) - (2)].Value)); 
-											assert((yyval.pSimpleStructItem) != NULL);
-										;}
-    break;
-
-  case 33:
-
-/* Line 1455 of yacc.c  */
-#line 298 "rcomp.yacc"
-    {	if(verbose) 
-											{			   RCTypeArray Types;
-														   MOFF;cout << "simple_struct_item                         " << Types.GetName((yyvsp[(1) - (5)].Id)) << " " << (yyvsp[(5) - (5)].Value) << endl; MON;
-											}
-											String s(NumericValue::ltoa((yyvsp[(3) - (5)].NumInitialiser)));
-											(yyval.pSimpleStructItem) = new SimpleStructItem((yyvsp[(1) - (5)].Id),(yyvsp[(5) - (5)].Value),s);
-											assert((yyval.pSimpleStructItem) != NULL);
-										;}
-    break;
-
-  case 34:
-
-/* Line 1455 of yacc.c  */
-#line 312 "rcomp.yacc"
-    {	(yyval.Id) = L_BYTE;;}
-    break;
-
-  case 35:
-
-/* Line 1455 of yacc.c  */
-#line 313 "rcomp.yacc"
-    {	(yyval.Id) = L_WORD;;}
-    break;
-
-  case 36:
-
-/* Line 1455 of yacc.c  */
-#line 314 "rcomp.yacc"
-    {	(yyval.Id) = L_LONG;;}
-    break;
-
-  case 37:
-
-/* Line 1455 of yacc.c  */
-#line 315 "rcomp.yacc"
-    {	(yyval.Id) = L_DOUBLE;;}
-    break;
-
-  case 38:
-
-/* Line 1455 of yacc.c  */
-#line 320 "rcomp.yacc"
-    { 
-	    (yyval.Id) = ( TargetCharacterSet == String::Unicode ) ? L_TEXT16: L_TEXT8;
-	    REGISTER_LINE;
-	    ErrorHandler::OutputErrorLine("Warning: Deprecated use of zero-terminated TEXT - use LTEXT instead");
-	    ;}
-    break;
-
-  case 39:
-
-/* Line 1455 of yacc.c  */
-#line 326 "rcomp.yacc"
-    {
-	    (yyval.Id) = ( TargetCharacterSet == String::Unicode ) ? L_LTEXT16: L_LTEXT8;
-	    ;}
-    break;
-
-  case 40:
-
-/* Line 1455 of yacc.c  */
-#line 330 "rcomp.yacc"
-    { 
-	    (yyval.Id) = ( TargetCharacterSet == String::Unicode ) ? L_BUF16: L_BUF8;
-	    ;}
-    break;
-
-  case 41:
-
-/* Line 1455 of yacc.c  */
-#line 336 "rcomp.yacc"
-    {	(yyval.Id) = L_TEXT8;
-											REGISTER_LINE;
-											ErrorHandler::OutputErrorLine("Warning: Deprecated use of zero-terminated TEXT8 - use LTEXT8 instead");
-										;}
-    break;
-
-  case 42:
-
-/* Line 1455 of yacc.c  */
-#line 340 "rcomp.yacc"
-    {	(yyval.Id) = L_TEXT16;
-											REGISTER_LINE;
-											ErrorHandler::OutputErrorLine("Warning: Deprecated use of zero-terminated TEXT16 - use LTEXT16 instead");
-										;}
-    break;
-
-  case 43:
-
-/* Line 1455 of yacc.c  */
-#line 344 "rcomp.yacc"
-    {	(yyval.Id) = L_LTEXT8;;}
-    break;
-
-  case 44:
-
-/* Line 1455 of yacc.c  */
-#line 345 "rcomp.yacc"
-    {	(yyval.Id) = L_LTEXT16;;}
-    break;
-
-  case 45:
-
-/* Line 1455 of yacc.c  */
-#line 346 "rcomp.yacc"
-    {	(yyval.Id) = L_BUF8;;}
-    break;
-
-  case 46:
-
-/* Line 1455 of yacc.c  */
-#line 347 "rcomp.yacc"
-    {	(yyval.Id) = L_BUF16;;}
-    break;
-
-  case 47:
-
-/* Line 1455 of yacc.c  */
-#line 348 "rcomp.yacc"
-    {	(yyval.Id) = L_LINK;;}
-    break;
-
-  case 48:
-
-/* Line 1455 of yacc.c  */
-#line 349 "rcomp.yacc"
-    {	(yyval.Id) = L_LLINK;;}
-    break;
-
-  case 49:
-
-/* Line 1455 of yacc.c  */
-#line 350 "rcomp.yacc"
-    {	(yyval.Id) = L_SRLINK;;}
-    break;
-
-  case 50:
-
-/* Line 1455 of yacc.c  */
-#line 353 "rcomp.yacc"
-    {	(yyval.pStructItem) = (yyvsp[(1) - (1)].pArrayStructItem);;}
-    break;
-
-  case 51:
-
-/* Line 1455 of yacc.c  */
-#line 355 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "array_struct_item                          with simple_initialiser_list" << endl;MON;}
-											(yyvsp[(1) - (5)].pArrayStructItem)->iDefaults = * (yyvsp[(4) - (5)].pStringArray);
-											if((yyvsp[(1) - (5)].pArrayStructItem)->iSize.Length() > 0)
-											{
-												NumericValue v((yyvsp[(1) - (5)].pArrayStructItem)->iSize, L_LONG);
-												REGISTER_LINE;
-												if((yyvsp[(4) - (5)].pStringArray)->Size()!=long(v.GetULong()))
-												{
-													ErrorHandler::OutputErrorLine("Size does not match number of initialisers");
-													exit(1);
-												}
-											}
-											(yyval.pStructItem) = (yyvsp[(1) - (5)].pArrayStructItem);
-											delete (yyvsp[(4) - (5)].pStringArray);
-										;}
-    break;
-
-  case 52:
-
-/* Line 1455 of yacc.c  */
-#line 372 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "array_struct_item_base                     with no size" << endl;MON;}
-											(yyval.pArrayStructItem) =(yyvsp[(1) - (2)].pArrayStructItem);
-										;}
-    break;
-
-  case 53:
-
-/* Line 1455 of yacc.c  */
-#line 376 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "array_struct_item_base                     with size " << (yyvsp[(2) - (3)].Value) << endl;MON;}
-											(yyvsp[(1) - (3)].pArrayStructItem)->iSize = (yyvsp[(2) - (3)].Value);
-											(yyval.pArrayStructItem) = (yyvsp[(1) - (3)].pArrayStructItem);
-										;}
-    break;
-
-  case 54:
-
-/* Line 1455 of yacc.c  */
-#line 381 "rcomp.yacc"
-    {	if(verbose) 
-												{		 	RCTypeArray Types;
-														 	MOFF;cout << "array_struct_item_base                     with LenType " << Types.GetName((yyvsp[(2) - (4)].Id)) << endl;MON;
-												}
-											(yyvsp[(3) - (4)].pArrayStructItem)->iLenType = (yyvsp[(2) - (4)].Id);
-											(yyval.pArrayStructItem) = (yyvsp[(3) - (4)].pArrayStructItem);
-										;}
-    break;
-
-  case 55:
-
-/* Line 1455 of yacc.c  */
-#line 389 "rcomp.yacc"
-    {	if(verbose) 
-												{		 	RCTypeArray Types;
-														 	MOFF;cout << "array_struct_item_base                     with size " << (yyvsp[(4) - (5)].Value) << " and LenType " << Types.GetName((yyvsp[(2) - (5)].Id)) << endl;MON;
-												}
-											(yyvsp[(3) - (5)].pArrayStructItem)->iLenType = (yyvsp[(2) - (5)].Id);
-											(yyvsp[(3) - (5)].pArrayStructItem)->iSize = (yyvsp[(4) - (5)].Value); 
-											(yyval.pArrayStructItem) = (yyvsp[(3) - (5)].pArrayStructItem); 
-										;}
-    break;
-
-  case 56:
-
-/* Line 1455 of yacc.c  */
-#line 399 "rcomp.yacc"
-    {	if(verbose) 
-												{		 	RCTypeArray Types; 
-														 	MOFF;cout << "array_struct_item_start                    " << Types.GetName((yyvsp[(1) - (3)].Id)) << " " << (yyvsp[(2) - (3)].Value) << endl;MON;
-												}
-											(yyval.pArrayStructItem) = new ArrayStructItem((yyvsp[(1) - (3)].Id), (yyvsp[(2) - (3)].Value));
-										;}
-    break;
-
-  case 57:
-
-/* Line 1455 of yacc.c  */
-#line 407 "rcomp.yacc"
-    {	(yyval.Id) = L_BYTE;;}
-    break;
-
-  case 58:
-
-/* Line 1455 of yacc.c  */
-#line 408 "rcomp.yacc"
-    {	(yyval.Id) = L_WORD;;}
-    break;
-
-  case 59:
-
-/* Line 1455 of yacc.c  */
-#line 411 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "struct_type_struct_item                    " << (yyvsp[(2) - (2)].Value) << endl;MON;}
-											(yyval.pStructItem) = new StructTypeStructItem((yyvsp[(2) - (2)].Value));
-										;}
-    break;
-
-  case 60:
-
-/* Line 1455 of yacc.c  */
-#line 416 "rcomp.yacc"
-    {	(yyval.pStructItem) = (yyvsp[(1) - (1)].pStructArrayStructItem);;}
-    break;
-
-  case 61:
-
-/* Line 1455 of yacc.c  */
-#line 418 "rcomp.yacc"
-    {	if(verbose) {	RCTypeArray Types; MOFF;cout << "struct_array_struct_item                   - Setting Size to " << Types.GetName((yyvsp[(2) - (3)].Id)) << endl;MON;}
-											(yyvsp[(3) - (3)].pStructArrayStructItem)->iLenType = (yyvsp[(2) - (3)].Id); (yyval.pStructItem) = (yyvsp[(3) - (3)].pStructArrayStructItem);
-										;}
-    break;
-
-  case 62:
-
-/* Line 1455 of yacc.c  */
-#line 423 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "struct_array_struct_item_base              " << (yyvsp[(2) - (4)].Value) << endl;MON;}
-											(yyval.pStructArrayStructItem) = new StructArrayStructItem((yyvsp[(2) - (4)].Value));
-										;}
-    break;
-
-  case 63:
-
-/* Line 1455 of yacc.c  */
-#line 427 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "struct_array_struct_item_base              " << (yyvsp[(2) - (5)].Value) << " " << (yyvsp[(4) - (5)].Value) << endl;MON;}
-											(yyval.pStructArrayStructItem) = new StructArrayStructItem((yyvsp[(2) - (5)].Value), (yyvsp[(4) - (5)].Value));
-										;}
-    break;
-
-  case 64:
-
-/* Line 1455 of yacc.c  */
-#line 436 "rcomp.yacc"
-    {	
-	    pResourceHeader->AddDefault();
-	    CurrentId+=CurrentIdStep;
-	    if(verbose) { MOFF;cout << "Resource ID "<< CurrentId << endl << Divider << "\n" << * pResourceHeader << Divider << endl;MON;}
-	    pResourceHeader->SetResourceId(*pResourceNameIds,CurrentId,FormatIdAsHex);
-	    pG->Index.Add(pResourceHeader);
-		
-		CheckStructUsage();
-
-		pUsedLabelsArray->Empty();
-
-	    pResourceHeader = NULL;
-	    ;}
-    break;
-
-  case 65:
-
-/* Line 1455 of yacc.c  */
-#line 451 "rcomp.yacc"
-    {;}
-    break;
-
-  case 66:
-
-/* Line 1455 of yacc.c  */
-#line 453 "rcomp.yacc"
-    {	
-	    if(verbose) { MOFF;cout << "resource_statement_start                   LOCAL" << endl;MON;}
-		    assert(pResourceHeader != NULL);
-		    pResourceHeader->iLocal = 1;
-	    ;}
-    break;
-
-  case 67:
-
-/* Line 1455 of yacc.c  */
-#line 458 "rcomp.yacc"
-    {;}
-    break;
-
-  case 68:
-
-/* Line 1455 of yacc.c  */
-#line 461 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "resource_statement_start_names             " << (yyvsp[(2) - (3)].Value) << " " << (yyvsp[(3) - (3)].Value) << endl;MON;}
-											assert(pResourceHeader == NULL);
-											pResourceHeader = new ResourceHeader((yyvsp[(3) - (3)].Value));
-											pCurrentRIA = & (pResourceHeader->iRIA);
-											REGISTER_LINE;
-											if(pResourceNameIds->IsStored((yyvsp[(3) - (3)].Value)))
-											{
-												ErrorHandler::OutputErrorLine("Resource with this name encountered already");
-												exit(1);
-											}
-											pCurrentRIA->FillFromStruct((yyvsp[(2) - (3)].Value));
-											pG->AllIdentifiers.Add(new String((yyvsp[(3) - (3)].Value))); // Add label to store
-										;}
-    break;
-
-  case 69:
-
-/* Line 1455 of yacc.c  */
-#line 474 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "resource_statement_start_names             " << (yyvsp[(2) - (2)].Value) << " <Resource not named>" << endl;MON;}
-											assert(pResourceHeader == NULL);
-											pResourceHeader = new ResourceHeader;
-											pCurrentRIA = & (pResourceHeader->iRIA);
-											REGISTER_LINE;
-											pCurrentRIA->FillFromStruct((yyvsp[(2) - (2)].Value));
-										;}
-    break;
-
-  case 70:
-
-/* Line 1455 of yacc.c  */
-#line 483 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "resource_item_list" << endl;MON;};}
-    break;
-
-  case 71:
-
-/* Line 1455 of yacc.c  */
-#line 484 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "tagged resource_item_list" << endl;MON;};}
-    break;
-
-  case 72:
-
-/* Line 1455 of yacc.c  */
-#line 485 "rcomp.yacc"
-    {	yyerrok; yyclearin; ;}
-    break;
-
-  case 74:
-
-/* Line 1455 of yacc.c  */
-#line 489 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "resource_item                              " << (yyvsp[(1) - (3)].Value) << " " << (yyvsp[(3) - (3)].Value) << endl;MON;}
-											REGISTER_LINE;/****************************************************************/
-											pCurrentRIA->Set((yyvsp[(1) - (3)].Value), (yyvsp[(3) - (3)].Value));
-										;}
-    break;
-
-  case 78:
-
-/* Line 1455 of yacc.c  */
-#line 499 "rcomp.yacc"
-    {	
-	    if (verbose) 
-		{ MOFF;cout << "resource_simple_array_item                 " << (yyvsp[(1) - (4)].Value) << endl;MON;} 
-	    ;}
-    break;
-
-  case 79:
-
-/* Line 1455 of yacc.c  */
-#line 504 "rcomp.yacc"
-    {	
-	    if (verbose) 
-		{ MOFF;cout << "resource_simple_array_item                 " << (yyvsp[(1) - (5)].Value) << " with simple_initialiser_list" << endl;MON;}
-	    REGISTER_LINE;
-	    pCurrentRIA->Set((yyvsp[(1) - (5)].Value), * (yyvsp[(4) - (5)].pStringArray));
-	    delete (yyvsp[(4) - (5)].pStringArray);
-	    ;}
-    break;
-
-  case 80:
-
-/* Line 1455 of yacc.c  */
-#line 532 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "struct_resource_item" << endl;MON;}
-											pCurrentRIA = pG->RIAStack.Pop();
-										;}
-    break;
-
-  case 81:
-
-/* Line 1455 of yacc.c  */
-#line 537 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "struct_resource_item_start                 " << (yyvsp[(1) - (4)].Value) << " " << (yyvsp[(3) - (4)].Value) << endl;MON;}
-											REGISTER_LINE;
-											pCurrentRIA->Set((yyvsp[(1) - (4)].Value), (yyvsp[(3) - (4)].Value));
-											String * thisLabel = new String((yyvsp[(1) - (4)].Value));
-											pUsedLabelsArray->Add(thisLabel);
-											// in here add the label to a temp store
-											pG->RIAStack.Push(pCurrentRIA);
-											pCurrentRIA = pCurrentRIA->Find((yyvsp[(1) - (4)].Value))->GetRIA();
-										;}
-    break;
-
-  case 82:
-
-/* Line 1455 of yacc.c  */
-#line 549 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "struct_array_resource_item" << endl;MON;}
-											pG->SRIStack.Pop();
-										;}
-    break;
-
-  case 83:
-
-/* Line 1455 of yacc.c  */
-#line 553 "rcomp.yacc"
-    {	pG->SRIStack.Pop();;}
-    break;
-
-  case 84:
-
-/* Line 1455 of yacc.c  */
-#line 556 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "struct_array_resource_item_start           " << (yyvsp[(1) - (5)].Value) << " " << (yyvsp[(4) - (5)].Value) << endl;MON;}
-											ResourceItem * p = pCurrentRIA->Find((yyvsp[(1) - (5)].Value));
-											pG->SRIStack.Push(p);
-											REGISTER_LINE;
-											String * thisLabel = new String((yyvsp[(1) - (5)].Value));
-											pUsedLabelsArray->Add(thisLabel);
-											// in here add the label to a temp store
-											p->Set((yyvsp[(4) - (5)].Value));
-											pG->RIAStack.Push(pCurrentRIA);
-											pCurrentRIA = p->GetRIA();
-										;}
-    break;
-
-  case 88:
-
-/* Line 1455 of yacc.c  */
-#line 574 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "struct_array_resource_item_list_top        " << endl;MON;}
-											pCurrentRIA = pG->RIAStack.Pop();
-										;}
-    break;
-
-  case 91:
-
-/* Line 1455 of yacc.c  */
-#line 584 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "struct_array_resource_item_list_item       " << endl;MON;}
-											pCurrentRIA = pG->RIAStack.Pop();
-										;}
-    break;
-
-  case 92:
-
-/* Line 1455 of yacc.c  */
-#line 589 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "struct_array_resource_item_list_item_start " << (yyvsp[(1) - (2)].Value) << endl;MON;}
-											ResourceItem * p = pG->SRIStack.Peek();
-											REGISTER_LINE;
-											p->Set((yyvsp[(1) - (2)].Value));
-											pG->RIAStack.Push(pCurrentRIA);
-											pCurrentRIA = p->GetRIA();
-										;}
-    break;
-
-  case 94:
-
-/* Line 1455 of yacc.c  */
-#line 605 "rcomp.yacc"
-    { 
-	    // convert literal to unsigned long value of 1st character
-		SetCharacterLiteral((yyval.Value), (yyvsp[(1) - (1)].Value));
-	    ;}
-    break;
-
-  case 97:
-
-/* Line 1455 of yacc.c  */
-#line 614 "rcomp.yacc"
-    {
-	    if(verbose) 
-		{	
-		MOFF;cout << "simple_initialiser_list                    - single string " << (yyvsp[(1) - (1)].Value) << endl;MON;
-		}
-		
-	    (yyval.pStringArray) = new StringArray;
-	    (yyval.pStringArray)->Add(new String((yyvsp[(1) - (1)].Value)) );
-	    ;}
-    break;
-
-  case 98:
-
-/* Line 1455 of yacc.c  */
-#line 624 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "simple_initialiser_list                    - part of list " << (yyvsp[(3) - (3)].Value) << endl;MON;}
-											assert((yyvsp[(1) - (3)].pStringArray) != NULL);
-											(yyvsp[(1) - (3)].pStringArray)->Add(new String((yyvsp[(3) - (3)].Value) ) );
-											(yyval.pStringArray) = (yyvsp[(1) - (3)].pStringArray);
-										;}
-    break;
-
-  case 99:
-
-/* Line 1455 of yacc.c  */
-#line 632 "rcomp.yacc"
-    {	String s(NumericValue::ltoa((yyvsp[(1) - (1)].NumInitialiser)) ); strcpy((yyval.Value), s.GetAssertedNonEmptyBuffer() ); ;}
-    break;
-
-  case 100:
-
-/* Line 1455 of yacc.c  */
-#line 635 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "Converting number " << (yyvsp[(1) - (1)].Value) << endl;MON;}
-											REGISTER_LINE;
-											NumericValue v((yyvsp[(1) - (1)].Value), L_LONG); (yyval.NumInitialiser) = (long)v.GetULong();
-										;}
-    break;
-
-  case 101:
-
-/* Line 1455 of yacc.c  */
-#line 639 "rcomp.yacc"
-    {	(yyval.NumInitialiser) = (yyvsp[(1) - (3)].NumInitialiser) + (yyvsp[(3) - (3)].NumInitialiser);	;}
-    break;
-
-  case 102:
-
-/* Line 1455 of yacc.c  */
-#line 640 "rcomp.yacc"
-    {	(yyval.NumInitialiser) = (yyvsp[(1) - (3)].NumInitialiser) - (yyvsp[(3) - (3)].NumInitialiser);	;}
-    break;
-
-  case 103:
-
-/* Line 1455 of yacc.c  */
-#line 641 "rcomp.yacc"
-    {	(yyval.NumInitialiser) = (yyvsp[(1) - (3)].NumInitialiser) * (yyvsp[(3) - (3)].NumInitialiser);	;}
-    break;
-
-  case 104:
-
-/* Line 1455 of yacc.c  */
-#line 642 "rcomp.yacc"
-    {	(yyval.NumInitialiser) = (yyvsp[(1) - (3)].NumInitialiser) / (yyvsp[(3) - (3)].NumInitialiser);	;}
-    break;
-
-  case 105:
-
-/* Line 1455 of yacc.c  */
-#line 643 "rcomp.yacc"
-    {	(yyval.NumInitialiser) = (yyvsp[(1) - (3)].NumInitialiser) | (yyvsp[(3) - (3)].NumInitialiser);	;}
-    break;
-
-  case 106:
-
-/* Line 1455 of yacc.c  */
-#line 644 "rcomp.yacc"
-    {	if (!NumericValue::CheckSigned((yyvsp[(2) - (2)].NumInitialiser),L_LONG))
-																	{
-																	REGISTER_LINE;
-																	ErrorHandler::OutputErrorLine("Signed value too low");
-																	exit(1);
-																	}
-																	(yyval.NumInitialiser) = - (yyvsp[(2) - (2)].NumInitialiser);		
-																;}
-    break;
-
-  case 107:
-
-/* Line 1455 of yacc.c  */
-#line 652 "rcomp.yacc"
-    {	(yyval.NumInitialiser) = (yyvsp[(2) - (3)].NumInitialiser);		;}
-    break;
-
-  case 109:
-
-/* Line 1455 of yacc.c  */
-#line 656 "rcomp.yacc"
-    {
-	    if (strlen((yyval.Value))+strlen((yyvsp[(2) - (2)].Value)) > sizeof((yyval.Value))-1)
-		{
-		REGISTER_LINE;
-		ErrorHandler::OutputErrorLine("String expression is too long");
-		exit(1);
-		}
-	    strcat((yyval.Value), (yyvsp[(2) - (2)].Value));
-	    ;}
-    break;
-
-  case 112:
-
-/* Line 1455 of yacc.c  */
-#line 670 "rcomp.yacc"
-    {
-		const char * fileName = (*ErrorHandler::GetFileName()).GetBuffer();
-		int lineNumber = ErrorHandler::GetLineNumber();
-		QualifiedString * thisLabel = new QualifiedString((yyvsp[(1) - (1)].Value), new String(fileName), lineNumber);
-		// store the label in the UsedIdentifiers array for checking
-		// whether label was declared
-		pG->UsedIdentifiers.Add(thisLabel);
-
-	    if (pG->EnumValues.IsStored((yyvsp[(1) - (1)].Value)))
-			{
-			sprintf((yyval.Value), "%d", pG->EnumValues.FindId((yyvsp[(1) - (1)].Value)));
-			}
-		else if (pG->RlsNameIndex.count((yyvsp[(1) - (1)].Value))) // if rls item has already been defined
-			{
-			// Found a reference to an rls_string.
-			RlsValue &rv = pG->RlsValues[pG->RlsNameIndex[(yyvsp[(1) - (1)].Value)]];
-			++rv.iCitationCount; // iCitationCount counts the number of times this rls value has been referneced
-			// Warn for multiple uses if 'multi' keyword not used.
-			if (1 < rv.iCitationCount && rv.iCardinality == ERlsCardinalitySingle)
-				{
-				Message * message = pG->Messages.GetEntry(LT_001);
-				String fileLine = *(rv.iFileName);
-				if(message->GetActivated())
-				{
-					pGL->AddWarningToStore(fileLine, rv.iLineNumber, message->GetMessageOutput());
-				}
-				REGISTER_LINE;
-				if (!pG->WarningMultiExplained)
-					{
-					Message * message = pG->Messages.GetEntry(LT_002);
-					fileLine = String(*(pFileLineHandler->GetCurrentFile()));
-					if(message->GetActivated())
-						{
-						pGL->AddWarningToStore(fileLine, pFileLineHandler->GetErrorLine(* pCurrentLineNumber), message->GetMessageOutput());
-						pG->WarningMultiExplained = true;
-						}
-					}
-				}
-			switch (rv.iType)
-				{
-				// Strings and numbers are just copied to the next layer up.
-			case ERlsString:
-			case ERlsString8:
-			case ERlsByte:
-			case ERlsWord:
-			case ERlsLong:
-			case ERlsDouble:
-				strcpy((yyval.Value), rv.iValue.GetBuffer());
-				break;
-				// Anything else is a character: this is converted to a number.
-			case ERlsStringChar:
-			case ERlsByteChar:
-			case ERlsWordChar:
-			case ERlsLongChar:
-				SetCharacterLiteral((yyval.Value), rv.iValue);
-				break;
-			default:
-				Message * message = pG->Messages.GetEntry(LT_031);
-				if(message->GetActivated())
-					{
-					ErrorHandler::OutputErrorLine(message->GetMessageOutput());
-					exit(1);
-					}
-				break;
-				}
-			}
-		else
-			{
-			/*
-			Could be a reference to another resource, perhaps even a forward reference:
-			the OverwriteLink functions do FindId again when writing out the data.
-			Sadly this also permits things which are really syntax errors, inadvertently
-			converting labels into string literals..
-			*/
-			}
-	    ;}
-    break;
-
-  case 113:
-
-/* Line 1455 of yacc.c  */
-#line 749 "rcomp.yacc"
-    {	
-	    REGISTER_LINE;
-	    if((yyvsp[(2) - (3)].NumInitialiser) < 0 || ((yyvsp[(2) - (3)].NumInitialiser) > 255 && TargetCharacterSet != String::Unicode))
-		{
-		    ErrorHandler::OutputErrorLine("Character code must be a number in the range 0 to 255.");
-		    exit(1);
-		}
-	    if (TargetCharacterSet != String::Unicode)
-		{
-		* (yyval.Value) = char((yyvsp[(2) - (3)].NumInitialiser)); * ((yyval.Value) + 1) = '\0'; 
-		} 
-	    else
-		{
-		if (SourceCharacterSet == String::CP1252)
-		    {
-		    if ( ((yyvsp[(2) - (3)].NumInitialiser) >= 0x80) && ((yyvsp[(2) - (3)].NumInitialiser) <= 0x9F ) ) // 80-9F are illegal Unicode values.
-			{
-			ErrorHandler::OutputErrorLine("Warning: Deprecated non-unicode value in source stream");
-			}
-		    * (yyval.Value) = char(UnicodeEscape);
-		    asUTF8((yyval.Value) + 1, (yyvsp[(2) - (3)].NumInitialiser));
-		    }
-		else
-		if (SourceCharacterSet == String::UTF8)
-		    {
-		    asUTF8((yyval.Value), (yyvsp[(2) - (3)].NumInitialiser));
-		    }
-		else
-		    {
-		    // Unsatisfactory, but do people use other character sets?
-		    if ((yyvsp[(2) - (3)].NumInitialiser) > 255)
-			{
-			ErrorHandler::OutputErrorLine("Don't know how to handle character > 255");
-			}
-		    * (yyval.Value) = char((yyvsp[(2) - (3)].NumInitialiser)); * ((yyval.Value) + 1) = '\0'; 
-		    }
-		}
-	    ;}
-    break;
-
-  case 114:
-
-/* Line 1455 of yacc.c  */
-#line 795 "rcomp.yacc"
-    {
-	    REGISTER_LINE;
-	    SetIdFromName((yyvsp[(2) - (2)].Value));
-	    ;}
-    break;
-
-  case 115:
-
-/* Line 1455 of yacc.c  */
-#line 800 "rcomp.yacc"
-    {
-	    REGISTER_LINE;
-	    SetIdFromName((yyvsp[(2) - (2)].Value));
-	    ;}
-    break;
-
-  case 116:
-
-/* Line 1455 of yacc.c  */
-#line 812 "rcomp.yacc"
-    {
-		REGISTER_LINE;
-		if ((yyvsp[(2) - (2)].NumInitialiser) == 0)
-			{ ErrorHandler::OutputErrorLine("UID2 must be non-zero"); exit(1); }
-		if (Uid2 != 0)
-			{ ErrorHandler::OutputErrorLine("Warning: overwriting previous UID2 value"); }
-		Uid2=(yyvsp[(2) - (2)].NumInitialiser);
-		if(verbose) 
-			{ MOFF;cout << "uidX_statement  UID2                       " << Uid2 << endl;MON;}
-		;}
-    break;
-
-  case 117:
-
-/* Line 1455 of yacc.c  */
-#line 823 "rcomp.yacc"
-    {
-		REGISTER_LINE;
-		if ((yyvsp[(2) - (2)].NumInitialiser) == 0)
-			{ ErrorHandler::OutputErrorLine("UID3 must be non-zero"); exit(1); }
-		if (Uid3 != 0)
-			{ ErrorHandler::OutputErrorLine("Warning: overwriting previous UID3 value"); }
-		Uid3=(yyvsp[(2) - (2)].NumInitialiser);
-		if(verbose) 
-			{ MOFF;cout << "uidX_statement  UID3                       " << Uid3 << endl;MON;}
-		;}
-    break;
-
-  case 118:
-
-/* Line 1455 of yacc.c  */
-#line 844 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "character_set_statement                    " << (yyvsp[(2) - (2)].Value) << endl;MON;}
-											REGISTER_LINE;
-											SourceCharacterSet = CharacterSetID((yyvsp[(2) - (2)].Value));
-											if ( SourceCharacterSet == String::UNKNOWN )
-											{
-												String err = "Warning: Unrecognised character set name '";
-												err += (yyvsp[(2) - (2)].Value);
-												err += "'";
-												ErrorHandler::OutputErrorLine(err);
-											}
-											if ( SourceCharacterSet == String::Unicode )
-											{
-											    SourceCharacterSet = String::UNKNOWN;
-												ErrorHandler::OutputErrorLine("Unicode source is unsupported");
-											}
-										;}
-    break;
-
-  case 119:
-
-/* Line 1455 of yacc.c  */
-#line 868 "rcomp.yacc"
-    {	if(verbose) {	RCTypeArray Types;
-															MOFF;cout << "offset_statement                           " << (yyvsp[(2) - (2)].Value) << endl;MON; }
-											REGISTER_LINE;
-										 	CurrentId=((long) NumericValue((yyvsp[(2) - (2)].Value), L_LONG).GetULong() );
-										;}
-    break;
-
-  case 120:
-
-/* Line 1455 of yacc.c  */
-#line 879 "rcomp.yacc"
-    {	if(verbose) {	MOFF;cout << "system_statement" << endl;MON;}
-											CurrentIdStep=-1;
-										;}
-    break;
-
-  case 123:
-
-/* Line 1455 of yacc.c  */
-#line 893 "rcomp.yacc"
-    {	
-	    if(verbose) 
-		{ MOFF;cout << "enum_statement" << endl;MON;} 
-	    CurrentEnumName = (yyvsp[(2) - (3)].Value);
-	    CurrentEnumValue=0;
-	    ;}
-    break;
-
-  case 124:
-
-/* Line 1455 of yacc.c  */
-#line 900 "rcomp.yacc"
-    {	
-	    if(verbose) 
-		{ MOFF;cout << "enum_statement" << endl;MON;} 
-	    CurrentEnumName = "";
-	    CurrentEnumValue=0;
-	    ;}
-    break;
-
-  case 125:
-
-/* Line 1455 of yacc.c  */
-#line 910 "rcomp.yacc"
-    {	
-		pG->EnumValues.Add((yyvsp[(1) - (1)].Value), CurrentEnumValue++);
-		pG->AllIdentifiers.Add(new String((yyvsp[(1) - (1)].Value))); // Add label to store
-		;}
-    break;
-
-  case 126:
-
-/* Line 1455 of yacc.c  */
-#line 915 "rcomp.yacc"
-    {	
-	    CurrentEnumValue = atol((yyvsp[(3) - (3)].Value));
-	    pG->EnumValues.Add((yyvsp[(1) - (3)].Value), CurrentEnumValue);
-	    CurrentEnumValue++;			// Increment so that next field has value ($3+1)
-		pG->AllIdentifiers.Add(new String((yyvsp[(1) - (3)].Value))); // Add label to store
-	    ;}
-    break;
-
-  case 129:
-
-/* Line 1455 of yacc.c  */
-#line 934 "rcomp.yacc"
-    {
-		pG->RlsNameIndex[(yyvsp[(3) - (4)].Value)] = pG->RlsValues.size();
-		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
-			ErrorHandler::GetLineNumber(), (yyvsp[(4) - (4)].Value), (yyvsp[(1) - (4)].RlsType),
-			(yyvsp[(2) - (4)].RlsQualifiers).iCardinality, (yyvsp[(2) - (4)].RlsQualifiers).iMaxLength));
-		if((yyvsp[(2) - (4)].RlsQualifiers).iMaxLength
-			< String((yyvsp[(4) - (4)].Value)).ExportLength(TargetCharacterSet,SourceCharacterSet))
-			{
-			Message * message = pG->Messages.GetEntry(LT_032);
-			if(message->GetActivated())
-				{
-				ErrorHandler::OutputErrorLine(message->GetMessageOutput());
-				exit(1);
-				}
-			}
-		;}
-    break;
-
-  case 130:
-
-/* Line 1455 of yacc.c  */
-#line 951 "rcomp.yacc"
-    {
-		Message * message = pG->Messages.GetEntry(LT_033);
-		String fileName = *(pFileLineHandler->GetCurrentFile());
-		int lineNumber = pFileLineHandler->GetErrorLine(* pCurrentLineNumber);
-		if(message->GetActivated())
-			{
-			pGL->AddWarningToStore(fileName, lineNumber, message->GetMessageOutput());
-			}
-		//...
-		/* Produce a warning "rls_string used for character constant: use rls_long, rls_word or rls_byte" */
-		pG->RlsNameIndex[(yyvsp[(3) - (4)].Value)] = pG->RlsValues.size();
-		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
-			ErrorHandler::GetLineNumber(), (yyvsp[(4) - (4)].Value), ERlsStringChar,
-			(yyvsp[(2) - (4)].RlsQualifiers).iCardinality));
-		;}
-    break;
-
-  case 131:
-
-/* Line 1455 of yacc.c  */
-#line 967 "rcomp.yacc"
-    {
-		pG->RlsNameIndex[(yyvsp[(3) - (4)].Value)] = pG->RlsValues.size();
-		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
-			ErrorHandler::GetLineNumber(), (yyvsp[(4) - (4)].Value), (yyvsp[(1) - (4)].RlsType),
-			(yyvsp[(2) - (4)].RlsQualifiers).iCardinality));
-		;}
-    break;
-
-  case 132:
-
-/* Line 1455 of yacc.c  */
-#line 974 "rcomp.yacc"
-    {
-		pG->RlsNameIndex[(yyvsp[(3) - (4)].Value)] = pG->RlsValues.size();
-		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
-			ErrorHandler::GetLineNumber(), (yyvsp[(4) - (4)].Value), (yyvsp[(1) - (4)].RlsType),
-			(yyvsp[(2) - (4)].RlsQualifiers).iCardinality));
-		;}
-    break;
-
-  case 133:
-
-/* Line 1455 of yacc.c  */
-#line 981 "rcomp.yacc"
-    {
-		TRlsType rlsCharType = (yyvsp[(1) - (4)].RlsType) == ERlsByte? ERlsByteChar
-			: ( (yyvsp[(1) - (4)].RlsType) ==  ERlsWord? ERlsWordChar : ERlsLongChar );
-		pG->RlsNameIndex[(yyvsp[(3) - (4)].Value)] = pG->RlsValues.size();
-		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
-			ErrorHandler::GetLineNumber(), (yyvsp[(4) - (4)].Value), rlsCharType,
-			(yyvsp[(2) - (4)].RlsQualifiers).iCardinality));
-		;}
-    break;
-
-  case 134:
-
-/* Line 1455 of yacc.c  */
-#line 992 "rcomp.yacc"
-    {
-		// Register line even if no warning here so that
-		// the rls_ item knows which line the label was on.
-		// Without this, the line registered would be the
-		// line following the declaration.
-		REGISTER_LINE;
-		strcpy((yyval.Value), (yyvsp[(1) - (1)].Value));
-
-		if (pG->RlsNameIndex.count((yyvsp[(1) - (1)].Value)) != 0)
-			{
-			Message * message = pG->Messages.GetEntry(LT_003);
-			if(message->GetActivated())
-				{
-				ErrorHandler::OutputErrorLine(message->GetMessageOutput());
-				}
-			}
-		pG->AllIdentifiers.Add(new String((yyvsp[(1) - (1)].Value))); // Add label to store
-		;}
-    break;
-
-  case 135:
-
-/* Line 1455 of yacc.c  */
-#line 1013 "rcomp.yacc"
-    {
-		NumericValue v((yyvsp[(2) - (4)].Value), L_LONG);
-		(yyval.RlsQualifiers).iMaxLength = v.GetULong();
-		(yyval.RlsQualifiers).iCardinality = (yyvsp[(4) - (4)].RlsQualifiers).iCardinality;
-		;}
-    break;
-
-  case 136:
-
-/* Line 1455 of yacc.c  */
-#line 1019 "rcomp.yacc"
-    { (yyval.RlsQualifiers) = (yyvsp[(1) - (1)].RlsQualifiers); ;}
-    break;
-
-  case 137:
-
-/* Line 1455 of yacc.c  */
-#line 1024 "rcomp.yacc"
-    {
-		(yyval.RlsQualifiers).iMaxLength = 0xFFFFFFF;
-		(yyval.RlsQualifiers).iCardinality = ERlsCardinalityMultiple;
-		;}
-    break;
-
-  case 138:
-
-/* Line 1455 of yacc.c  */
-#line 1029 "rcomp.yacc"
-    {
-		(yyval.RlsQualifiers).iMaxLength = 0xFFFFFFF;
-		(yyval.RlsQualifiers).iCardinality = ERlsCardinalitySingle;
-		;}
-    break;
-
-  case 139:
-
-/* Line 1455 of yacc.c  */
-#line 1037 "rcomp.yacc"
-    { (yyval.RlsType) = ERlsString; ;}
-    break;
-
-  case 140:
-
-/* Line 1455 of yacc.c  */
-#line 1039 "rcomp.yacc"
-    { (yyval.RlsType) = ERlsString8; ;}
-    break;
-
-  case 141:
-
-/* Line 1455 of yacc.c  */
-#line 1044 "rcomp.yacc"
-    { (yyval.RlsType) = ERlsByte; ;}
-    break;
-
-  case 142:
-
-/* Line 1455 of yacc.c  */
-#line 1046 "rcomp.yacc"
-    { (yyval.RlsType) = ERlsWord; ;}
-    break;
-
-  case 143:
-
-/* Line 1455 of yacc.c  */
-#line 1048 "rcomp.yacc"
-    { (yyval.RlsType) = ERlsLong; ;}
-    break;
-
-  case 144:
-
-/* Line 1455 of yacc.c  */
-#line 1053 "rcomp.yacc"
-    { (yyval.RlsType) = ERlsDouble; ;}
-    break;
-
-  case 147:
-
-/* Line 1455 of yacc.c  */
-#line 1065 "rcomp.yacc"
-    {ErrorHandler::Register(pFileLineHandler->GetCurrentFile(), pFileLineHandler->GetErrorLine(*pCurrentLineNumber)); ;}
-    break;
-
-  case 150:
-
-/* Line 1455 of yacc.c  */
-#line 1075 "rcomp.yacc"
-    { pGL->StoreComment((yyvsp[(1) - (1)].Value));	;}
-    break;
-
-  case 151:
-
-/* Line 1455 of yacc.c  */
-#line 1076 "rcomp.yacc"
-    { pGL->StoreComment((yyvsp[(1) - (1)].Value));	;}
-    break;
-
-  case 152:
-
-/* Line 1455 of yacc.c  */
-#line 1077 "rcomp.yacc"
-    { pGL->StoreComment((yyvsp[(1) - (1)].Value));	;}
-    break;
-
-
-
-/* Line 1455 of yacc.c  */
-#line 3037 "rcomp.tab.cacc"
-      default: break;
-    }
-  YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
-
-  YYPOPSTACK (yylen);
-  yylen = 0;
-  YY_STACK_PRINT (yyss, yyssp);
-
-  *++yyvsp = yyval;
-
-  /* Now `shift' the result of the reduction.  Determine what state
-     that goes to, based on the state we popped back to and the rule
-     number reduced by.  */
-
-  yyn = yyr1[yyn];
-
-  yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
-  if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
-    yystate = yytable[yystate];
-  else
-    yystate = yydefgoto[yyn - YYNTOKENS];
-
-  goto yynewstate;
-
-
-/*------------------------------------.
-| yyerrlab -- here on detecting error |
-`------------------------------------*/
-yyerrlab:
-  /* If not already recovering from an error, report this error.  */
-  if (!yyerrstatus)
-    {
-      ++yynerrs;
-#if ! YYERROR_VERBOSE
-      yyerror (YY_("syntax error"));
-#else
-      {
-	YYSIZE_T yysize = yysyntax_error (0, yystate, yychar);
-	if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM)
-	  {
-	    YYSIZE_T yyalloc = 2 * yysize;
-	    if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM))
-	      yyalloc = YYSTACK_ALLOC_MAXIMUM;
-	    if (yymsg != yymsgbuf)
-	      YYSTACK_FREE (yymsg);
-	    yymsg = (char *) YYSTACK_ALLOC (yyalloc);
-	    if (yymsg)
-	      yymsg_alloc = yyalloc;
-	    else
-	      {
-		yymsg = yymsgbuf;
-		yymsg_alloc = sizeof yymsgbuf;
-	      }
-	  }
-
-	if (0 < yysize && yysize <= yymsg_alloc)
-	  {
-	    (void) yysyntax_error (yymsg, yystate, yychar);
-	    yyerror (yymsg);
-	  }
-	else
-	  {
-	    yyerror (YY_("syntax error"));
-	    if (yysize != 0)
-	      goto yyexhaustedlab;
-	  }
-      }
-#endif
-    }
-
-
-
-  if (yyerrstatus == 3)
-    {
-      /* If just tried and failed to reuse lookahead token after an
-	 error, discard it.  */
-
-      if (yychar <= YYEOF)
-	{
-	  /* Return failure if at end of input.  */
-	  if (yychar == YYEOF)
-	    YYABORT;
-	}
-      else
-	{
-	  yydestruct ("Error: discarding",
-		      yytoken, &yylval);
-	  yychar = YYEMPTY;
-	}
-    }
-
-  /* Else will try to reuse lookahead token after shifting the error
-     token.  */
-  goto yyerrlab1;
-
-
-/*---------------------------------------------------.
-| yyerrorlab -- error raised explicitly by YYERROR.  |
-`---------------------------------------------------*/
-yyerrorlab:
-
-  /* Pacify compilers like GCC when the user code never invokes
-     YYERROR and the label yyerrorlab therefore never appears in user
-     code.  */
-  if (/*CONSTCOND*/ 0)
-     goto yyerrorlab;
-
-  /* Do not reclaim the symbols of the rule which action triggered
-     this YYERROR.  */
-  YYPOPSTACK (yylen);
-  yylen = 0;
-  YY_STACK_PRINT (yyss, yyssp);
-  yystate = *yyssp;
-  goto yyerrlab1;
-
-
-/*-------------------------------------------------------------.
-| yyerrlab1 -- common code for both syntax error and YYERROR.  |
-`-------------------------------------------------------------*/
-yyerrlab1:
-  yyerrstatus = 3;	/* Each real token shifted decrements this.  */
-
-  for (;;)
-    {
-      yyn = yypact[yystate];
-      if (yyn != YYPACT_NINF)
-	{
-	  yyn += YYTERROR;
-	  if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
-	    {
-	      yyn = yytable[yyn];
-	      if (0 < yyn)
-		break;
-	    }
-	}
-
-      /* Pop the current state because it cannot handle the error token.  */
-      if (yyssp == yyss)
-	YYABORT;
-
-
-      yydestruct ("Error: popping",
-		  yystos[yystate], yyvsp);
-      YYPOPSTACK (1);
-      yystate = *yyssp;
-      YY_STACK_PRINT (yyss, yyssp);
-    }
-
-  *++yyvsp = yylval;
-
-
-  /* Shift the error token.  */
-  YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
-
-  yystate = yyn;
-  goto yynewstate;
-
-
-/*-------------------------------------.
-| yyacceptlab -- YYACCEPT comes here.  |
-`-------------------------------------*/
-yyacceptlab:
-  yyresult = 0;
-  goto yyreturn;
-
-/*-----------------------------------.
-| yyabortlab -- YYABORT comes here.  |
-`-----------------------------------*/
-yyabortlab:
-  yyresult = 1;
-  goto yyreturn;
-
-#if !defined(yyoverflow) || YYERROR_VERBOSE
-/*-------------------------------------------------.
-| yyexhaustedlab -- memory exhaustion comes here.  |
-`-------------------------------------------------*/
-yyexhaustedlab:
-  yyerror (YY_("memory exhausted"));
-  yyresult = 2;
-  /* Fall through.  */
-#endif
-
-yyreturn:
-  if (yychar != YYEMPTY)
-     yydestruct ("Cleanup: discarding lookahead",
-		 yytoken, &yylval);
-  /* Do not reclaim the symbols of the rule which action triggered
-     this YYABORT or YYACCEPT.  */
-  YYPOPSTACK (yylen);
-  YY_STACK_PRINT (yyss, yyssp);
-  while (yyssp != yyss)
-    {
-      yydestruct ("Cleanup: popping",
-		  yystos[*yyssp], yyvsp);
-      YYPOPSTACK (1);
-    }
-#ifndef yyoverflow
-  if (yyss != yyssa)
-    YYSTACK_FREE (yyss);
-#endif
-#if YYERROR_VERBOSE
-  if (yymsg != yymsgbuf)
-    YYSTACK_FREE (yymsg);
-#endif
-  /* Make sure YYID is used.  */
-  return YYID (yyresult);
-}
-
-
-
-/* Line 1675 of yacc.c  */
-#line 1080 "rcomp.yacc"
-
-
-// Function section
-// ================
-
-void asUTF8(char* aUtf8, int aUnicode)
-	{
-	if ( aUnicode > 0xffff )
-		{
-		if ( aUnicode > 0x10ffff )
-		{
-		ErrorHandler::OutputErrorLine("Surrogate character code must be a number in the range 0x10000 to 0x10ffff");
-		exit(1);		
-		}
-		
-		UTF16 high = (UTF16)(0xD7C0 + (aUnicode >> 10));			// high surrogate
-		UTF16 low = (UTF16)(0xDC00 | (aUnicode & 0x3FF));			// low surrogate
-	
-		*aUtf8++ =(char)(0xe0|(high>>12));
-		*aUtf8++ =(char)(0x80|((high>>6)&0x3f));
-		*aUtf8++ =(char)(0x80|(high&0x3f));
-		*aUtf8++ =(char)(0xe0|(low>>12));
-		*aUtf8++ =(char)(0x80|((low>>6)&0x3f));
-		*aUtf8   =(char)(0x80|(low&0x3f));
-		}
-	else if ((aUnicode & 0xff80) == 0x0000)
-		{
-		*aUtf8 = (char)aUnicode;
-		}
-	else if ((aUnicode & 0xf800) == 0x0000)
-		{
-		*aUtf8++ =(char)(0xc0|(aUnicode>>6));
-		*aUtf8   =(char)(0x80|(aUnicode&0x3f));
-		}
-	else
-		{
-		*aUtf8++ =(char)(0xe0|(aUnicode>>12));
-		*aUtf8++ =(char)(0x80|((aUnicode>>6)&0x3f));
-		*aUtf8   =(char)(0x80|(aUnicode&0x3f));
-		}
-	*++aUtf8 = '\0';
-	}
-
-
-String::CharacterSet CharacterSetID( const String & character_set_name )
-// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-// Return a character set ID from a character set name.  The value UNKNOWN
-// is returned if the name is not recognised.
-// ----------------------------------------------------------------------------
-{
-	String::CharacterSet ids[] = { String::ISOLatin1, String::ASCII, String::CP1252
-	                              , String::CP850, String::ShiftJIS, String::Unicode
-								  , String::UTF8
-								  , String::UNKNOWN
-								 };
-	String names[] = { "ISOLATIN1", "ASCII", "CP1252", "CP850", "SHIFTJIS", "UNICODE", "UTF8" };
-
-	for ( int i=0; ids[i]!=String::UNKNOWN; i++ )
-	{
-		if ( names[i] == character_set_name ) return ids[i];
-	}
-
-	return String::UNKNOWN;
-
-} // end of CharacterSetID code
-
-void SetIdFromName( const String & NameStatementValue)
-	{
-	// space 	0
-	// A		1
-	// B		2
-	// ...
-	// Z		26
-	//
-	// ABCD corresponds to the number 4321 which becomes ( (4*27 + 3) * 27 + 2) * 27 + 1.
-	
-	if(verbose) 
-		{ MOFF;cout << "name_statement                             " << NameStatementValue << endl;MON;}
-	if ( NameStatementValue.Length() > 4)
-		{
-		ErrorHandler::OutputErrorLine( "Name must be no longer than four characters");
-		exit( 1);
-		}
-	
-	long NewId = 0;
-	
-	for( unsigned long i = 0; i < NameStatementValue.Length(); i++)
-		{
-		NewId *= 27;
-		if ( isalpha( NameStatementValue[i]) )
-			NewId += toupper( NameStatementValue[i]) - 'A' + 1;
-		}
-
-	CurrentId = NewId << 12;
-	FormatIdAsHex = 1;
-	if(verbose) 
-		{ MOFF;cout << "Current id                                " << CurrentId << endl;MON;}
-	}
-
-void RlsUnusedWarnings()
-	{
-	TNameIndex::iterator end = pG->RlsNameIndex.end();
-	for (TNameIndex::iterator i = pG->RlsNameIndex.begin(); i != end; ++i)
-		{
-		int index = i->second;
-		RlsValue& v = pG->RlsValues[index];
-		if (v.iCitationCount == 0)
-			{
-			Message * message = pG->Messages.GetEntry(LT_004);
-			String fileLine = *(v.iFileName);
-			if(message->GetActivated())
-				{
-				pGL->AddWarningToStore(fileLine, v.iLineNumber, message->GetMessageOutput());
-				}
-			}
-		}
-	}
-
-int ParseSourceFile(FILE* aFile, unsigned short aYYDebug)
-	{
-	// Set up various global pointers which refer to the pG structure
-	pSHA = & (pG->SHA);
-	pFileLineHandler = & (pG->FileLineHandler);
-	pResourceNameIds = & (pG->ResourceNameIds);
-
-	pScan = new rcscan(pG->FileLineHandler, aFile);
-
-	yydebug = aYYDebug;
-	pCurrentLineNumber = &yylineno;
-	int ReturnValue = yyparse();
-
-	RlsUnusedWarnings();
-
-	int bScanErrorFound = pScan->ErrorWasFound();
-
-	delete pScan;
-	pScan = NULL;
-
-	if(ReturnValue != 0)
-		return ReturnValue;
-	
-	if(bScanErrorFound)
-		return 1;
-	
-	return 0;	// successful parse - parse tree now in the pG data structure
-	}
-
-
-void CheckStructUsage()
-	{
-	ResourceItemArrayIterator	nextRI( *pCurrentRIA);
-	ResourceItem * pRI;
-	while ( ( pRI = nextRI() ) != NULL)
-		{
-		int resourceItemType = pRI->GetResourceItemType();
-		String resourceItemLabel = pRI->GetLabel();
-		if( (resourceItemType == EStructTypeResourceItem) || (resourceItemType == EStructArrayResourceItem) )
-			{
-			StringArrayIterator nextLabel( *pUsedLabelsArray);
-			String * pLabel;
-			bool flag = false;
-			while ( ( ( pLabel = nextLabel() ) != NULL ) && (! flag) )
-				{
-				StringLess stringCompare;
-				if( !stringCompare(resourceItemLabel,*pLabel) && !stringCompare(*pLabel,resourceItemLabel) )
-					{
-					flag = true;
-					}
-				}
-			if(! flag)
-				{
-				if(resourceItemType == EStructTypeResourceItem)
-					{
-					Message * message = pG->Messages.GetEntry(LT_046);
-					if(message->GetActivated())
-						{
-						String comment = message->GetMessageOutput();
-						comment += "'";
-						comment += resourceItemLabel;
-						comment += "'";
-						ErrorHandler::OutputErrorLine(comment);
-						}
-					}
-				else
-					{
-					Message * message = pG->Messages.GetEntry(LT_047);
-					if(message->GetActivated())
-						{
-						String comment = message->GetMessageOutput();
-						comment += "'";
-						comment += resourceItemLabel;
-						comment += "'";
-						ErrorHandler::OutputErrorLine(comment);
-						}
-					}
-				}
-			}
-		}
-	}
-
-int yywrap()
-{
-  return 1;
-}
-
-/* Called by yyparse on error */
-#include <stdarg.h>
-void yyerror (const char *s, ...)
-{
-  va_list list;
-  va_start(list, s);
-  pScan->yyerror(const_cast<char*>(s), list);
-  va_end(list);
-}
-
-
-
+/* A Bison parser, made by GNU Bison 2.4.1.  */
+
+/* Skeleton implementation for Bison's Yacc-like parsers in C
+   
+      Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
+   Free Software Foundation, Inc.
+   
+   This program is free software: you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+   
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+   
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+/* As a special exception, you may create a larger work that contains
+   part or all of the Bison parser skeleton and distribute that work
+   under terms of your choice, so long as that work isn't itself a
+   parser generator using the skeleton or a modified version thereof
+   as a parser skeleton.  Alternatively, if you modify or redistribute
+   the parser skeleton itself, you may (at your option) remove this
+   special exception, which will cause the skeleton and the resulting
+   Bison output files to be licensed under the GNU General Public
+   License without this special exception.
+   
+   This special exception was added by the Free Software Foundation in
+   version 2.2 of Bison.  */
+
+/* C LALR(1) parser skeleton written by Richard Stallman, by
+   simplifying the original so-called "semantic" parser.  */
+
+/* All symbols defined below should begin with yy or YY, to avoid
+   infringing on user name space.  This should be done even for local
+   variables, as they might otherwise be expanded by user macros.
+   There are some unavoidable exceptions within include files to
+   define necessary library symbols; they are noted "INFRINGES ON
+   USER NAME SPACE" below.  */
+
+/* Identify Bison output.  */
+#define YYBISON 1
+
+/* Bison version.  */
+#define YYBISON_VERSION "2.4.1"
+
+/* Skeleton name.  */
+#define YYSKELETON_NAME "yacc.c"
+
+/* Pure parsers.  */
+#define YYPURE 0
+
+/* Push parsers.  */
+#define YYPUSH 0
+
+/* Pull parsers.  */
+#define YYPULL 1
+
+/* Using locations.  */
+#define YYLSP_NEEDED 0
+
+
+
+/* Copy the first part of user declarations.  */
+
+/* Line 189 of yacc.c  */
+#line 1 "rcomp.yacc"
+
+#include <assert.h>
+#include <ctype.h>
+#include <string.h>
+
+#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
+#include <fstream>
+#include <iostream>
+using namespace std;
+using std::cout;
+using std::endl;
+#else //!__MSVCDOTNET__
+#include <fstream.h>
+#endif //__MSVCDOTNET__
+
+#ifdef __VC32__
+#pragma warning( disable : 4065 ) // C4065: switch statement contains 'default' but no 'case' labels
+#pragma warning( disable : 4102 ) // C4102: 'yyerrlab1' : unreferenced label
+#pragma warning( disable : 4127 ) // C4127: conditional expression is constant
+#pragma warning( disable : 4244 ) // C4244: '=' : conversion from 'int' to 'short', possible loss of data
+#endif //__VC32__
+
+#include "RESOURCE.H"
+#include "Parser.h"
+
+int yylex();
+void yyerror(const char* string, ...);
+int yywrap();
+#define YYDEBUG 1
+extern int yylineno;
+
+#include "rcomp.hpp"
+#include "DATATYPE.H"
+#include "MEM.H"
+#include "RCBINSTR.H"
+#include "RCSCAN.H"
+#include "ERRORHAN.H"
+#include "FILEACC.H"
+#include "VERSION.H"
+#include "CTABLE.H"
+#include "localise.h"
+#include "main.h"
+
+#if defined(__VC32__) && !defined(_DEBUG)
+#pragma warning( disable : 4702 )	// unreachable code
+#pragma warning( disable : 4102 )	// 'yyerrlabel' : unreferenced label
+#pragma warning( disable : 4244 )	// '=' : conversion from 'int' to 'short', possible loss of data
+#endif
+
+
+
+String::CharacterSet CharacterSetID( const String & character_set_name );
+void asUTF8(char* aUtf8, int aUnicode);
+void SetIdFromName( const String & NameStatementValue);
+void CheckStructUsage();
+
+unsigned short & d = MemCheckControl::iLogMemory;
+
+StructHeader *		pSH;
+
+StructHeaderArray * 	pSHA;	// Used in resource struct handling functions.
+ResourceHeader *	pResourceHeader;
+ResourceItemArray *	pCurrentRIA;
+StringArray * pUsedLabelsArray = new StringArray();
+int			verbose;
+String::CharacterSet	SourceCharacterSet = String::CP1252;
+String::CharacterSet	TargetCharacterSet = String::CP1252;
+unsigned short		logmemorysetting;
+int *			pCurrentLineNumber;
+FileLineManager *	pFileLineHandler;
+NameIdMap *		pResourceNameIds;
+long			CurrentEnumValue;
+String			CurrentEnumName;
+char			TempStr[300];
+rcscan * pScan;
+
+int CurrentIdStep=1;
+long CurrentId=0;
+int FormatIdAsHex=0;	// defaults to decimal, changes in SetIdFromName
+
+unsigned long Uid2=0;
+unsigned long Uid3=0;
+
+
+
+const String	Divider("*******************************************");
+
+#define REGISTER_LINE	ErrorHandler::Register(pFileLineHandler->GetCurrentFile(), pFileLineHandler->GetErrorLine(* pCurrentLineNumber))
+
+// Convert a string containing a character literal in aQuoted
+// into a value suitable for LCHAR_LITERAL
+void SetCharacterLiteral(char* aOut, const String& aQuoted)
+	{
+	    UTF16 first;
+	    int length=1;
+	    if (aQuoted.Length() < 1 ) 
+	               { 
+                        REGISTER_LINE;
+                        ErrorHandler::OutputErrorLine("Warning: Empty Character literal");
+                       }
+	    if (aQuoted.Length() > 1 ) 
+	 	       {
+                        REGISTER_LINE;
+                        ErrorHandler::OutputErrorLine("Error: String Literal length greater than 1");
+			exit(1);
+                       }
+	    if (aQuoted.Export(&first, length, SourceCharacterSet)==0)
+			{
+			REGISTER_LINE;
+			ErrorHandler::OutputErrorLine("Warning: Ignoring trailing characters in character literal");
+			}
+	    sprintf(aOut, "%d", first);
+	}
+
+
+
+/* Line 189 of yacc.c  */
+#line 205 "rcomp.tab.cacc"
+
+/* Enabling traces.  */
+#ifndef YYDEBUG
+# define YYDEBUG 0
+#endif
+
+/* Enabling verbose error messages.  */
+#ifdef YYERROR_VERBOSE
+# undef YYERROR_VERBOSE
+# define YYERROR_VERBOSE 1
+#else
+# define YYERROR_VERBOSE 0
+#endif
+
+/* Enabling the token table.  */
+#ifndef YYTOKEN_TABLE
+# define YYTOKEN_TABLE 0
+#endif
+
+
+/* Tokens.  */
+#ifndef YYTOKENTYPE
+# define YYTOKENTYPE
+   /* Put the tokens into the symbol table, so that GDB and other debuggers
+      know about them.  */
+   enum yytokentype {
+     L_STRUCT = 258,
+     L_RESOURCE = 259,
+     L_NAME = 260,
+     L_OFFSET = 261,
+     L_SYSTEM = 262,
+     L_GLOBAL = 263,
+     L_LOCAL = 264,
+     L_CHARACTER_SET = 265,
+     L_BUF = 266,
+     L_WORD = 267,
+     L_BYTE = 268,
+     L_LONG = 269,
+     L_DOUBLE = 270,
+     L_TEXT = 271,
+     L_LTEXT = 272,
+     L_LINK = 273,
+     L_LLINK = 274,
+     L_SRLINK = 275,
+     L_BUF8 = 276,
+     L_TEXT8 = 277,
+     L_LTEXT8 = 278,
+     L_BUF16 = 279,
+     L_TEXT16 = 280,
+     L_LTEXT16 = 281,
+     L_UID_TWO = 282,
+     L_UID_THREE = 283,
+     L_RLS_STRING = 284,
+     L_RLS_STRING8 = 285,
+     L_RLS_DOUBLE = 286,
+     L_RLS_BYTE = 287,
+     L_RLS_WORD = 288,
+     L_RLS_LONG = 289,
+     L_MULTI = 290,
+     L_TAG_START = 291,
+     L_TAG_END = 292,
+     L_TAG_COMMAND = 293,
+     L_TAG_WORD = 294,
+     L_TAG_NEW_LINE = 295,
+     L_LABEL = 296,
+     L_NUM_NATURAL = 297,
+     L_NUM_FLOAT = 298,
+     L_NATURAL_EXPR = 299,
+     L_ENUM = 300,
+     L_LEN = 301,
+     L_CHAR_LITERAL = 302,
+     L_STRING_LITERAL = 303,
+     UMINUS = 304
+   };
+#endif
+
+
+
+#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
+typedef union YYSTYPE
+{
+
+/* Line 214 of yacc.c  */
+#line 132 "rcomp.yacc"
+
+	char				Value[1024*8];
+	TValueMaybeRls			ValueMaybeRls;
+	unsigned long 			Id;
+	StructItem *			pStructItem;
+	SimpleStructItem *		pSimpleStructItem;
+	ArrayStructItem *   	pArrayStructItem;
+	StructArrayStructItem *	pStructArrayStructItem;
+	StringArray *			pStringArray;
+	long					NumInitialiser;
+	TRlsQualifiers		RlsQualifiers;
+	TRlsType			RlsType;
+
+
+
+/* Line 214 of yacc.c  */
+#line 306 "rcomp.tab.cacc"
+} YYSTYPE;
+# define YYSTYPE_IS_TRIVIAL 1
+# define yystype YYSTYPE /* obsolescent; will be withdrawn */
+# define YYSTYPE_IS_DECLARED 1
+#endif
+
+
+/* Copy the second part of user declarations.  */
+
+
+/* Line 264 of yacc.c  */
+#line 318 "rcomp.tab.cacc"
+
+#ifdef short
+# undef short
+#endif
+
+#ifdef YYTYPE_UINT8
+typedef YYTYPE_UINT8 yytype_uint8;
+#else
+typedef unsigned char yytype_uint8;
+#endif
+
+#ifdef YYTYPE_INT8
+typedef YYTYPE_INT8 yytype_int8;
+#elif (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+typedef signed char yytype_int8;
+#else
+typedef short int yytype_int8;
+#endif
+
+#ifdef YYTYPE_UINT16
+typedef YYTYPE_UINT16 yytype_uint16;
+#else
+typedef unsigned short int yytype_uint16;
+#endif
+
+#ifdef YYTYPE_INT16
+typedef YYTYPE_INT16 yytype_int16;
+#else
+typedef short int yytype_int16;
+#endif
+
+#ifndef YYSIZE_T
+# ifdef __SIZE_TYPE__
+#  define YYSIZE_T __SIZE_TYPE__
+# elif defined size_t
+#  define YYSIZE_T size_t
+# elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+#  include <stddef.h> /* INFRINGES ON USER NAME SPACE */
+#  define YYSIZE_T size_t
+# else
+#  define YYSIZE_T unsigned int
+# endif
+#endif
+
+#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
+
+#ifndef YY_
+# if YYENABLE_NLS
+#  if ENABLE_NLS
+#   include <libintl.h> /* INFRINGES ON USER NAME SPACE */
+#   define YY_(msgid) dgettext ("bison-runtime", msgid)
+#  endif
+# endif
+# ifndef YY_
+#  define YY_(msgid) msgid
+# endif
+#endif
+
+/* Suppress unused-variable warnings by "using" E.  */
+#if ! defined lint || defined __GNUC__
+# define YYUSE(e) ((void) (e))
+#else
+# define YYUSE(e) /* empty */
+#endif
+
+/* Identity function, used to suppress warnings about constant conditions.  */
+#ifndef lint
+# define YYID(n) (n)
+#else
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+static int
+YYID (int yyi)
+#else
+static int
+YYID (yyi)
+    int yyi;
+#endif
+{
+  return yyi;
+}
+#endif
+
+#if ! defined yyoverflow || YYERROR_VERBOSE
+
+/* The parser invokes alloca or malloc; define the necessary symbols.  */
+
+# ifdef YYSTACK_USE_ALLOCA
+#  if YYSTACK_USE_ALLOCA
+#   ifdef __GNUC__
+#    define YYSTACK_ALLOC __builtin_alloca
+#   elif defined __BUILTIN_VA_ARG_INCR
+#    include <alloca.h> /* INFRINGES ON USER NAME SPACE */
+#   elif defined _AIX
+#    define YYSTACK_ALLOC __alloca
+#   elif defined _MSC_VER
+#    include <malloc.h> /* INFRINGES ON USER NAME SPACE */
+#    define alloca _alloca
+#   else
+#    define YYSTACK_ALLOC alloca
+#    if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+#     include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
+#     ifndef _STDLIB_H
+#      define _STDLIB_H 1
+#     endif
+#    endif
+#   endif
+#  endif
+# endif
+
+# ifdef YYSTACK_ALLOC
+   /* Pacify GCC's `empty if-body' warning.  */
+#  define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0))
+#  ifndef YYSTACK_ALLOC_MAXIMUM
+    /* The OS might guarantee only one guard page at the bottom of the stack,
+       and a page size can be as small as 4096 bytes.  So we cannot safely
+       invoke alloca (N) if N exceeds 4096.  Use a slightly smaller number
+       to allow for a few compiler-allocated temporary stack slots.  */
+#   define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
+#  endif
+# else
+#  define YYSTACK_ALLOC YYMALLOC
+#  define YYSTACK_FREE YYFREE
+#  ifndef YYSTACK_ALLOC_MAXIMUM
+#   define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
+#  endif
+#  if (defined __cplusplus && ! defined _STDLIB_H \
+       && ! ((defined YYMALLOC || defined malloc) \
+	     && (defined YYFREE || defined free)))
+#   include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
+#   ifndef _STDLIB_H
+#    define _STDLIB_H 1
+#   endif
+#  endif
+#  ifndef YYMALLOC
+#   define YYMALLOC malloc
+#   if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
+#   endif
+#  endif
+#  ifndef YYFREE
+#   define YYFREE free
+#   if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+void free (void *); /* INFRINGES ON USER NAME SPACE */
+#   endif
+#  endif
+# endif
+#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
+
+
+#if (! defined yyoverflow \
+     && (! defined __cplusplus \
+	 || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
+
+/* A type that is properly aligned for any stack member.  */
+union yyalloc
+{
+  yytype_int16 yyss_alloc;
+  YYSTYPE yyvs_alloc;
+};
+
+/* The size of the maximum gap between one aligned stack and the next.  */
+# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
+
+/* The size of an array large to enough to hold all stacks, each with
+   N elements.  */
+# define YYSTACK_BYTES(N) \
+     ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
+      + YYSTACK_GAP_MAXIMUM)
+
+/* Copy COUNT objects from FROM to TO.  The source and destination do
+   not overlap.  */
+# ifndef YYCOPY
+#  if defined __GNUC__ && 1 < __GNUC__
+#   define YYCOPY(To, From, Count) \
+      __builtin_memcpy (To, From, (Count) * sizeof (*(From)))
+#  else
+#   define YYCOPY(To, From, Count)		\
+      do					\
+	{					\
+	  YYSIZE_T yyi;				\
+	  for (yyi = 0; yyi < (Count); yyi++)	\
+	    (To)[yyi] = (From)[yyi];		\
+	}					\
+      while (YYID (0))
+#  endif
+# endif
+
+/* Relocate STACK from its old location to the new one.  The
+   local variables YYSIZE and YYSTACKSIZE give the old and new number of
+   elements in the stack, and YYPTR gives the new location of the
+   stack.  Advance YYPTR to a properly aligned location for the next
+   stack.  */
+# define YYSTACK_RELOCATE(Stack_alloc, Stack)				\
+    do									\
+      {									\
+	YYSIZE_T yynewbytes;						\
+	YYCOPY (&yyptr->Stack_alloc, Stack, yysize);			\
+	Stack = &yyptr->Stack_alloc;					\
+	yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
+	yyptr += yynewbytes / sizeof (*yyptr);				\
+      }									\
+    while (YYID (0))
+
+#endif
+
+/* YYFINAL -- State number of the termination state.  */
+#define YYFINAL  3
+/* YYLAST -- Last index in YYTABLE.  */
+#define YYLAST   303
+
+/* YYNTOKENS -- Number of terminals.  */
+#define YYNTOKENS  66
+/* YYNNTS -- Number of nonterminals.  */
+#define YYNNTS  61
+/* YYNRULES -- Number of rules.  */
+#define YYNRULES  152
+/* YYNRULES -- Number of states.  */
+#define YYNSTATES  255
+
+/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX.  */
+#define YYUNDEFTOK  2
+#define YYMAXUTOK   304
+
+#define YYTRANSLATE(YYX)						\
+  ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
+
+/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX.  */
+static const yytype_uint8 yytranslate[] =
+{
+       0,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+      58,    59,    51,    49,    65,    50,     2,    52,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,    55,
+      61,    60,    62,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,    64,     2,    63,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,    57,    53,    56,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     1,     2,     3,     4,
+       5,     6,     7,     8,     9,    10,    11,    12,    13,    14,
+      15,    16,    17,    18,    19,    20,    21,    22,    23,    24,
+      25,    26,    27,    28,    29,    30,    31,    32,    33,    34,
+      35,    36,    37,    38,    39,    40,    41,    42,    43,    44,
+      45,    46,    47,    48,    54
+};
+
+#if YYDEBUG
+/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
+   YYRHS.  */
+static const yytype_uint16 yyprhs[] =
+{
+       0,     0,     3,     5,     8,    11,    12,    15,    18,    21,
+      24,    27,    30,    32,    35,    38,    40,    41,    45,    50,
+      56,    62,    66,    71,    72,    74,    76,    78,    80,    82,
+      87,    91,    98,   101,   107,   109,   111,   113,   115,   117,
+     119,   121,   123,   125,   127,   129,   131,   133,   135,   137,
+     139,   141,   147,   150,   154,   159,   165,   169,   171,   173,
+     176,   178,   182,   187,   193,   198,   201,   204,   206,   210,
+     213,   217,   222,   226,   227,   231,   233,   235,   237,   242,
+     248,   252,   257,   261,   265,   271,   273,   277,   281,   284,
+     286,   290,   294,   297,   299,   301,   303,   305,   307,   311,
+     313,   315,   319,   323,   327,   331,   335,   338,   342,   344,
+     347,   349,   351,   353,   357,   360,   363,   366,   369,   372,
+     375,   377,   381,   386,   390,   393,   395,   399,   402,   407,
+     412,   417,   422,   427,   432,   434,   439,   441,   443,   444,
+     446,   448,   450,   452,   454,   456,   458,   459,   463,   466,
+     467,   469,   471
+};
+
+/* YYRHS -- A `-1'-separated list of the rules' RHS.  */
+static const yytype_int8 yyrhs[] =
+{
+      67,     0,    -1,    68,    -1,    68,    69,    -1,    68,   124,
+      -1,    -1,    71,    70,    -1,    85,    70,    -1,   109,    70,
+      -1,   107,    70,    -1,   110,    70,    -1,   111,    70,    -1,
+     112,    -1,   108,    70,    -1,   116,    70,    -1,    55,    -1,
+      -1,    72,    73,    56,    -1,     3,    41,   123,    57,    -1,
+       3,    41,    81,   123,    57,    -1,     3,    41,    46,   123,
+      57,    -1,    73,    74,    55,    -1,    73,   124,    74,    55,
+      -1,    -1,    75,    -1,    78,    -1,    82,    -1,    83,    -1,
+      76,    -1,    76,    58,   102,    59,    -1,    76,    60,   100,
+      -1,    76,    58,   102,    59,    60,   104,    -1,    77,    41,
+      -1,    77,    61,   103,    62,    41,    -1,    13,    -1,    12,
+      -1,    14,    -1,    15,    -1,    16,    -1,    17,    -1,    11,
+      -1,    22,    -1,    25,    -1,    23,    -1,    26,    -1,    21,
+      -1,    24,    -1,    18,    -1,    19,    -1,    20,    -1,    79,
+      -1,    79,    60,    57,   101,    56,    -1,    80,    63,    -1,
+      80,   102,    63,    -1,    46,    81,    80,    63,    -1,    46,
+      81,    80,   102,    63,    -1,    77,    41,    64,    -1,    13,
+      -1,    12,    -1,     3,    41,    -1,    84,    -1,    46,    81,
+      84,    -1,     3,    41,    64,    63,    -1,     3,    41,    64,
+     102,    63,    -1,    86,    57,    88,    56,    -1,     8,    87,
+      -1,     9,    87,    -1,    87,    -1,     4,    41,    41,    -1,
+       4,    41,    -1,    88,    89,    55,    -1,    88,   124,    89,
+      55,    -1,    88,     1,    55,    -1,    -1,    41,    60,   100,
+      -1,    90,    -1,    91,    -1,    93,    -1,    41,    60,    57,
+      56,    -1,    41,    60,    57,   101,    56,    -1,    92,    88,
+      56,    -1,    41,    60,    41,    57,    -1,    94,    95,    56,
+      -1,    94,    95,     1,    -1,    41,    60,    57,    41,    57,
+      -1,    96,    -1,    96,    65,    97,    -1,    96,    65,     1,
+      -1,    88,    56,    -1,    98,    -1,    97,    65,    98,    -1,
+      99,    88,    56,    -1,    41,    57,    -1,    43,    -1,    47,
+      -1,   104,    -1,   102,    -1,   100,    -1,   101,    65,   100,
+      -1,   103,    -1,    42,    -1,   103,    49,   103,    -1,   103,
+      50,   103,    -1,   103,    51,   103,    -1,   103,    52,   103,
+      -1,   103,    53,   103,    -1,    50,   103,    -1,    58,   103,
+      59,    -1,   105,    -1,   105,   104,    -1,    48,    -1,   106,
+      -1,    41,    -1,    61,   103,    62,    -1,     5,    41,    -1,
+       5,    48,    -1,    27,   103,    -1,    28,   103,    -1,    10,
+      41,    -1,     6,   102,    -1,     7,    -1,   113,   115,    56,
+      -1,   113,   115,    56,    55,    -1,    45,    41,    57,    -1,
+      45,    57,    -1,    41,    -1,    41,    60,   100,    -1,   123,
+     114,    -1,   115,    65,   123,   114,    -1,   120,   118,   117,
+     104,    -1,   120,   118,   117,    47,    -1,   122,   119,   117,
+      43,    -1,   121,   119,   117,    42,    -1,   121,   119,   117,
+      47,    -1,    41,    -1,    61,    42,    62,   119,    -1,   119,
+      -1,    35,    -1,    -1,    29,    -1,    30,    -1,    32,    -1,
+      33,    -1,    34,    -1,    31,    -1,   124,    -1,    -1,    36,
+     125,    37,    -1,   125,   126,    -1,    -1,    40,    -1,    38,
+      -1,    39,    -1
+};
+
+/* YYRLINE[YYN] -- source line where rule number YYN was defined.  */
+static const yytype_uint16 yyrline[] =
+{
+       0,   182,   182,   189,   190,   191,   195,   196,   197,   198,
+     199,   200,   201,   202,   203,   207,   214,   221,   225,   231,
+     237,   245,   249,   253,   256,   257,   258,   259,   262,   263,
+     268,   273,   289,   297,   312,   313,   314,   315,   319,   325,
+     329,   336,   340,   344,   345,   346,   347,   348,   349,   350,
+     353,   354,   372,   375,   380,   388,   399,   407,   408,   411,
+     416,   417,   423,   426,   435,   451,   452,   458,   461,   474,
+     483,   484,   485,   486,   489,   493,   494,   495,   498,   503,
+     531,   537,   548,   552,   556,   569,   570,   571,   574,   579,
+     580,   583,   589,   603,   604,   609,   610,   613,   623,   632,
+     635,   639,   640,   641,   642,   643,   644,   652,   655,   656,
+     667,   668,   669,   748,   794,   799,   811,   822,   844,   868,
+     879,   888,   889,   892,   899,   909,   914,   925,   926,   933,
+     950,   966,   973,   980,   991,  1012,  1018,  1023,  1029,  1036,
+    1038,  1043,  1045,  1047,  1052,  1060,  1061,  1065,  1069,  1071,
+    1075,  1076,  1077
+};
+#endif
+
+#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
+/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
+   First, the terminals, then, starting at YYNTOKENS, nonterminals.  */
+static const char *const yytname[] =
+{
+  "$end", "error", "$undefined", "L_STRUCT", "L_RESOURCE", "L_NAME",
+  "L_OFFSET", "L_SYSTEM", "L_GLOBAL", "L_LOCAL", "L_CHARACTER_SET",
+  "L_BUF", "L_WORD", "L_BYTE", "L_LONG", "L_DOUBLE", "L_TEXT", "L_LTEXT",
+  "L_LINK", "L_LLINK", "L_SRLINK", "L_BUF8", "L_TEXT8", "L_LTEXT8",
+  "L_BUF16", "L_TEXT16", "L_LTEXT16", "L_UID_TWO", "L_UID_THREE",
+  "L_RLS_STRING", "L_RLS_STRING8", "L_RLS_DOUBLE", "L_RLS_BYTE",
+  "L_RLS_WORD", "L_RLS_LONG", "L_MULTI", "L_TAG_START", "L_TAG_END",
+  "L_TAG_COMMAND", "L_TAG_WORD", "L_TAG_NEW_LINE", "L_LABEL",
+  "L_NUM_NATURAL", "L_NUM_FLOAT", "L_NATURAL_EXPR", "L_ENUM", "L_LEN",
+  "L_CHAR_LITERAL", "L_STRING_LITERAL", "'+'", "'-'", "'*'", "'/'", "'|'",
+  "UMINUS", "';'", "'}'", "'{'", "'('", "')'", "'='", "'<'", "'>'", "']'",
+  "'['", "','", "$accept", "source", "statement_list", "statement",
+  "maybe_semicolon", "struct_statement", "struct_statement_start",
+  "struct_item_list", "struct_item", "simple_struct_item",
+  "simple_struct_item_start", "data_type", "array_struct_item",
+  "array_struct_item_base", "array_struct_item_start", "len_declaration",
+  "struct_type_struct_item", "struct_array_struct_item",
+  "struct_array_struct_item_base", "resource_statement",
+  "resource_statement_start", "resource_statement_start_names",
+  "resource_item_list", "resource_item", "resource_simple_array_item",
+  "struct_resource_item", "struct_resource_item_start",
+  "struct_array_resource_item", "struct_array_resource_item_start",
+  "struct_array_resource_item_list_top",
+  "struct_array_resource_item_list_top_start",
+  "struct_array_resource_item_list",
+  "struct_array_resource_item_list_item",
+  "struct_array_resource_item_list_item_start", "simple_initialiser",
+  "simple_initialiser_list", "natural_expression",
+  "natural_expression_numeric", "string_expression",
+  "string_expression_item", "character_code_expression", "name_statement",
+  "uidX_statement", "character_set_statement", "offset_statement",
+  "system_statement", "enum_statement", "enum_statement_start",
+  "enum_list_entry", "enum_list", "rls_item_statement", "rls_label",
+  "rls_qualifiers", "rls_cardinality", "rls_string_item", "rls_num_item",
+  "rls_float_item", "maybe_comment_tag", "comment_tag", "tag_line",
+  "tag_word", 0
+};
+#endif
+
+# ifdef YYPRINT
+/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to
+   token YYLEX-NUM.  */
+static const yytype_uint16 yytoknum[] =
+{
+       0,   256,   257,   258,   259,   260,   261,   262,   263,   264,
+     265,   266,   267,   268,   269,   270,   271,   272,   273,   274,
+     275,   276,   277,   278,   279,   280,   281,   282,   283,   284,
+     285,   286,   287,   288,   289,   290,   291,   292,   293,   294,
+     295,   296,   297,   298,   299,   300,   301,   302,   303,    43,
+      45,    42,    47,   124,   304,    59,   125,   123,    40,    41,
+      61,    60,    62,    93,    91,    44
+};
+# endif
+
+/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives.  */
+static const yytype_uint8 yyr1[] =
+{
+       0,    66,    67,    68,    68,    68,    69,    69,    69,    69,
+      69,    69,    69,    69,    69,    70,    70,    71,    72,    72,
+      72,    73,    73,    73,    74,    74,    74,    74,    75,    75,
+      75,    75,    76,    76,    77,    77,    77,    77,    77,    77,
+      77,    77,    77,    77,    77,    77,    77,    77,    77,    77,
+      78,    78,    79,    79,    79,    79,    80,    81,    81,    82,
+      83,    83,    84,    84,    85,    86,    86,    86,    87,    87,
+      88,    88,    88,    88,    89,    89,    89,    89,    90,    90,
+      91,    92,    93,    93,    94,    95,    95,    95,    96,    97,
+      97,    98,    99,   100,   100,   100,   100,   101,   101,   102,
+     103,   103,   103,   103,   103,   103,   103,   103,   104,   104,
+     105,   105,   105,   106,   107,   107,   108,   108,   109,   110,
+     111,   112,   112,   113,   113,   114,   114,   115,   115,   116,
+     116,   116,   116,   116,   117,   118,   118,   119,   119,   120,
+     120,   121,   121,   121,   122,   123,   123,   124,   125,   125,
+     126,   126,   126
+};
+
+/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN.  */
+static const yytype_uint8 yyr2[] =
+{
+       0,     2,     1,     2,     2,     0,     2,     2,     2,     2,
+       2,     2,     1,     2,     2,     1,     0,     3,     4,     5,
+       5,     3,     4,     0,     1,     1,     1,     1,     1,     4,
+       3,     6,     2,     5,     1,     1,     1,     1,     1,     1,
+       1,     1,     1,     1,     1,     1,     1,     1,     1,     1,
+       1,     5,     2,     3,     4,     5,     3,     1,     1,     2,
+       1,     3,     4,     5,     4,     2,     2,     1,     3,     2,
+       3,     4,     3,     0,     3,     1,     1,     1,     4,     5,
+       3,     4,     3,     3,     5,     1,     3,     3,     2,     1,
+       3,     3,     2,     1,     1,     1,     1,     1,     3,     1,
+       1,     3,     3,     3,     3,     3,     2,     3,     1,     2,
+       1,     1,     1,     3,     2,     2,     2,     2,     2,     2,
+       1,     3,     4,     3,     2,     1,     3,     2,     4,     4,
+       4,     4,     4,     4,     1,     4,     1,     1,     0,     1,
+       1,     1,     1,     1,     1,     1,     0,     3,     2,     0,
+       1,     1,     1
+};
+
+/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state
+   STATE-NUM when YYTABLE doesn't specify something else to do.  Zero
+   means the default is an error.  */
+static const yytype_uint8 yydefact[] =
+{
+       5,     0,     2,     1,     0,     0,     0,     0,   120,     0,
+       0,     0,     0,     0,   139,   140,   144,   141,   142,   143,
+     149,     0,     3,    16,    23,    16,     0,    67,    16,    16,
+      16,    16,    16,    12,   146,    16,   138,   138,   138,     4,
+     146,    69,   114,   115,   100,     0,     0,   119,    99,    65,
+      66,   118,   116,   117,     0,     0,   124,    15,     6,     0,
+       7,    73,     9,    13,     8,    10,    11,     0,     0,   145,
+      14,   137,     0,     0,   136,     0,     0,    58,    57,   146,
+     146,     0,    68,   106,     0,     0,     0,     0,     0,     0,
+     147,   151,   152,   150,   148,   123,     0,    40,    35,    34,
+      36,    37,    38,    39,    47,    48,    49,    45,    41,    43,
+      46,    42,    44,     0,    17,     0,    24,    28,     0,    25,
+      50,     0,    26,    27,    60,     0,     0,   121,   146,   125,
+     127,     0,   134,     0,     0,     0,     0,     0,    18,   107,
+     101,   102,   103,   104,   105,    59,     0,    21,     0,     0,
+      32,     0,     0,    52,     0,     0,     0,     0,    64,     0,
+      75,    76,    73,    77,    73,     0,   122,     0,     0,   138,
+     112,   130,   110,     0,   129,   108,   111,   132,   133,   131,
+      20,    19,     0,     0,     0,     0,    61,     0,    93,    94,
+      30,    96,    95,    56,     0,     0,    53,    22,    72,     0,
+      70,     0,     0,     0,    85,     0,   128,   126,   135,     0,
+     109,    62,     0,     0,     0,    54,     0,    29,     0,    97,
+       0,   112,     0,    74,    80,    88,    83,    82,     0,    71,
+     113,    63,    55,     0,    33,    51,     0,    81,   112,    78,
+       0,    87,     0,    86,    89,    73,    31,    98,    84,    79,
+      92,     0,     0,    90,    91
+};
+
+/* YYDEFGOTO[NTERM-NUM].  */
+static const yytype_int16 yydefgoto[] =
+{
+      -1,     1,     2,    22,    58,    23,    24,    59,   115,   116,
+     117,   118,   119,   120,   121,    80,   122,   123,   124,    25,
+      26,    27,   126,   159,   160,   161,   162,   163,   164,   203,
+     204,   243,   244,   245,   219,   220,   191,    48,   192,   175,
+     176,    28,    29,    30,    31,    32,    33,    34,   130,    67,
+      35,   133,    73,    74,    36,    37,    38,    68,    69,    54,
+      94
+};
+
+/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
+   STATE-NUM.  */
+#define YYPACT_NINF -156
+static const yytype_int16 yypact[] =
+{
+    -156,    20,   215,  -156,   -18,    15,    21,    41,  -156,    13,
+      13,    63,    41,    41,  -156,  -156,  -156,  -156,  -156,  -156,
+    -156,     4,  -156,    27,  -156,    27,    59,  -156,    27,    27,
+      27,    27,    27,  -156,    -5,    27,   -21,    37,    37,  -156,
+      17,    78,  -156,  -156,  -156,    41,    41,  -156,   145,  -156,
+    -156,  -156,   145,   145,    74,    66,  -156,  -156,  -156,   132,
+    -156,  -156,  -156,  -156,  -156,  -156,  -156,    32,    96,  -156,
+    -156,  -156,    97,   118,  -156,   118,   118,  -156,  -156,    -5,
+      -5,   124,  -156,  -156,    81,    41,    41,    41,    41,    41,
+    -156,  -156,  -156,  -156,  -156,  -156,   141,  -156,  -156,  -156,
+    -156,  -156,  -156,  -156,  -156,  -156,  -156,  -156,  -156,  -156,
+    -156,  -156,  -156,    80,  -156,   129,  -156,    62,   -19,  -156,
+     125,   -26,  -156,  -156,  -156,   190,    10,   131,    -5,   127,
+    -156,   128,  -156,    23,    -9,   146,   134,   135,  -156,  -156,
+      34,    34,   164,   164,  -156,   162,   250,  -156,    41,   236,
+     165,    41,   171,  -156,   172,   183,   184,   180,  -156,   186,
+    -156,  -156,  -156,  -156,  -156,   211,  -156,    96,   236,    37,
+    -156,  -156,  -156,    41,  -156,   -20,  -156,  -156,  -156,  -156,
+    -156,  -156,   -24,   213,   214,    31,  -156,   197,  -156,  -156,
+    -156,  -156,  -156,  -156,    76,   236,  -156,  -156,  -156,    60,
+    -156,    11,    18,    12,   192,   203,  -156,  -156,  -156,   121,
+    -156,  -156,   196,   162,   165,  -156,   217,   221,   241,  -156,
+      40,   228,   119,  -156,  -156,  -156,  -156,  -156,    14,  -156,
+    -156,  -156,  -156,   -20,  -156,  -156,   236,  -156,   230,  -156,
+      44,  -156,   231,   224,  -156,  -156,  -156,  -156,  -156,  -156,
+    -156,   249,    24,  -156,  -156
+};
+
+/* YYPGOTO[NTERM-NUM].  */
+static const yytype_int16 yypgoto[] =
+{
+    -156,  -156,  -156,  -156,   202,  -156,  -156,  -156,   166,  -156,
+    -156,   147,  -156,  -156,   149,   179,  -156,  -156,   150,  -156,
+    -156,   155,  -155,   133,  -156,  -156,  -156,  -156,  -156,  -156,
+    -156,  -156,    48,  -156,  -141,    79,    -6,   -10,  -127,  -156,
+    -156,  -156,  -156,  -156,  -156,  -156,  -156,  -156,   136,  -156,
+    -156,   -32,  -156,   -33,  -156,  -156,  -156,   -30,    -2,  -156,
+    -156
+};
+
+/* YYTABLE[YYPACT[STATE-NUM]].  What to do in state STATE-NUM.  If
+   positive, shift that token.  If negative, reduce the rule which
+   number is the opposite.  If zero, do what YYDEFACT says.
+   If YYTABLE_NINF, syntax error.  */
+#define YYTABLE_NINF -1
+static const yytype_uint8 yytable[] =
+{
+      39,    47,    52,    53,    75,    76,   174,   201,   190,   202,
+      81,   156,   156,   226,    71,   241,    44,     5,    44,   156,
+       3,   170,   150,    40,    45,   156,    45,   207,   172,    77,
+      78,    20,    46,   177,    46,    83,    84,   153,   178,   211,
+      72,   173,   151,   134,   135,    55,    20,    20,   210,   136,
+     137,   157,   157,    20,    20,   242,    41,   125,   223,   157,
+      20,    56,    42,    79,   170,   157,   158,   224,   227,    43,
+     171,   172,    71,    44,   225,   140,   141,   142,   143,   144,
+     254,    45,    57,    44,   173,    87,    88,    89,   127,    46,
+     252,    45,    77,    78,   215,   247,   235,   128,   167,    46,
+     249,   221,    44,   188,    51,   236,   246,   189,   172,   236,
+      45,    90,    91,    92,    93,   154,    61,   222,    46,    82,
+     148,   173,   149,    95,   165,    85,    86,    87,    88,    89,
+      85,    86,    87,    88,    89,    96,   208,   129,   218,   131,
+     139,   194,   187,    97,    98,    99,   100,   101,   102,   103,
+     104,   105,   106,   107,   108,   109,   110,   111,   112,   132,
+     238,    44,   188,   209,    49,    50,   189,   172,    20,    45,
+      85,    86,    87,    88,    89,   239,   212,    46,   113,   216,
+     173,   138,   145,   230,   147,   152,   166,   168,   114,   179,
+     169,   180,   181,    96,    85,    86,    87,    88,    89,   165,
+     165,    97,    98,    99,   100,   101,   102,   103,   104,   105,
+     106,   107,   108,   109,   110,   111,   112,    89,     4,     5,
+       6,     7,     8,     9,    10,    11,   182,    60,   195,   193,
+      62,    63,    64,    65,    66,   196,   113,    70,   197,   198,
+     199,   200,    12,    13,    14,    15,    16,    17,    18,    19,
+     165,    20,   157,   183,   213,   214,   217,   228,   229,   231,
+      21,    97,    98,    99,   100,   101,   102,   103,   104,   105,
+     106,   107,   108,   109,   110,   111,   112,   170,    44,   188,
+     232,   233,   234,   189,   172,   237,    45,   248,   250,   251,
+     242,   155,   146,   184,    46,   185,   186,   173,   205,   253,
+       0,   240,     0,   206
+};
+
+static const yytype_int16 yycheck[] =
+{
+       2,     7,    12,    13,    37,    38,   133,   162,   149,   164,
+      40,     1,     1,     1,    35,     1,    42,     4,    42,     1,
+       0,    41,    41,    41,    50,     1,    50,   168,    48,    12,
+      13,    36,    58,    42,    58,    45,    46,    63,    47,    63,
+      61,    61,    61,    75,    76,    41,    36,    36,   175,    79,
+      80,    41,    41,    36,    36,    41,    41,    59,   199,    41,
+      36,    57,    41,    46,    41,    41,    56,    56,    56,    48,
+      47,    48,    35,    42,    56,    85,    86,    87,    88,    89,
+      56,    50,    55,    42,    61,    51,    52,    53,    56,    58,
+     245,    50,    12,    13,    63,   236,    56,    65,   128,    58,
+      56,    41,    42,    43,    41,    65,   233,    47,    48,    65,
+      50,    37,    38,    39,    40,   121,    57,    57,    58,    41,
+      58,    61,    60,    57,   126,    49,    50,    51,    52,    53,
+      49,    50,    51,    52,    53,     3,   169,    41,    62,    42,
+      59,   151,   148,    11,    12,    13,    14,    15,    16,    17,
+      18,    19,    20,    21,    22,    23,    24,    25,    26,    41,
+      41,    42,    43,   173,     9,    10,    47,    48,    36,    50,
+      49,    50,    51,    52,    53,    56,   182,    58,    46,   185,
+      61,    57,    41,    62,    55,    60,    55,    60,    56,    43,
+      62,    57,    57,     3,    49,    50,    51,    52,    53,   201,
+     202,    11,    12,    13,    14,    15,    16,    17,    18,    19,
+      20,    21,    22,    23,    24,    25,    26,    53,     3,     4,
+       5,     6,     7,     8,     9,    10,    64,    25,    57,    64,
+      28,    29,    30,    31,    32,    63,    46,    35,    55,    55,
+      60,    55,    27,    28,    29,    30,    31,    32,    33,    34,
+     252,    36,    41,     3,    41,    41,    59,    65,    55,    63,
+      45,    11,    12,    13,    14,    15,    16,    17,    18,    19,
+      20,    21,    22,    23,    24,    25,    26,    41,    42,    43,
+      63,    60,    41,    47,    48,    57,    50,    57,    57,    65,
+      41,   125,   113,   146,    58,   146,   146,    61,   165,   251,
+      -1,   222,    -1,   167
+};
+
+/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
+   symbol of state STATE-NUM.  */
+static const yytype_uint8 yystos[] =
+{
+       0,    67,    68,     0,     3,     4,     5,     6,     7,     8,
+       9,    10,    27,    28,    29,    30,    31,    32,    33,    34,
+      36,    45,    69,    71,    72,    85,    86,    87,   107,   108,
+     109,   110,   111,   112,   113,   116,   120,   121,   122,   124,
+      41,    41,    41,    48,    42,    50,    58,   102,   103,    87,
+      87,    41,   103,   103,   125,    41,    57,    55,    70,    73,
+      70,    57,    70,    70,    70,    70,    70,   115,   123,   124,
+      70,    35,    61,   118,   119,   119,   119,    12,    13,    46,
+      81,   123,    41,   103,   103,    49,    50,    51,    52,    53,
+      37,    38,    39,    40,   126,    57,     3,    11,    12,    13,
+      14,    15,    16,    17,    18,    19,    20,    21,    22,    23,
+      24,    25,    26,    46,    56,    74,    75,    76,    77,    78,
+      79,    80,    82,    83,    84,   124,    88,    56,    65,    41,
+     114,    42,    41,   117,   117,   117,   123,   123,    57,    59,
+     103,   103,   103,   103,   103,    41,    81,    55,    58,    60,
+      41,    61,    60,    63,   102,    74,     1,    41,    56,    89,
+      90,    91,    92,    93,    94,   124,    55,   123,    60,    62,
+      41,    47,    48,    61,   104,   105,   106,    42,    47,    43,
+      57,    57,    64,     3,    77,    80,    84,   102,    43,    47,
+     100,   102,   104,    64,   103,    57,    63,    55,    55,    60,
+      55,    88,    88,    95,    96,    89,   114,   100,   119,   103,
+     104,    63,   102,    41,    41,    63,   102,    59,    62,   100,
+     101,    41,    57,   100,    56,    56,     1,    56,    65,    55,
+      62,    63,    63,    60,    41,    56,    65,    57,    41,    56,
+     101,     1,    41,    97,    98,    99,   104,   100,    57,    56,
+      57,    65,    88,    98,    56
+};
+
+#define yyerrok		(yyerrstatus = 0)
+#define yyclearin	(yychar = YYEMPTY)
+#define YYEMPTY		(-2)
+#define YYEOF		0
+
+#define YYACCEPT	goto yyacceptlab
+#define YYABORT		goto yyabortlab
+#define YYERROR		goto yyerrorlab
+
+
+/* Like YYERROR except do call yyerror.  This remains here temporarily
+   to ease the transition to the new meaning of YYERROR, for GCC.
+   Once GCC version 2 has supplanted version 1, this can go.  */
+
+#define YYFAIL		goto yyerrlab
+
+#define YYRECOVERING()  (!!yyerrstatus)
+
+#define YYBACKUP(Token, Value)					\
+do								\
+  if (yychar == YYEMPTY && yylen == 1)				\
+    {								\
+      yychar = (Token);						\
+      yylval = (Value);						\
+      yytoken = YYTRANSLATE (yychar);				\
+      YYPOPSTACK (1);						\
+      goto yybackup;						\
+    }								\
+  else								\
+    {								\
+      yyerror (YY_("syntax error: cannot back up")); \
+      YYERROR;							\
+    }								\
+while (YYID (0))
+
+
+#define YYTERROR	1
+#define YYERRCODE	256
+
+
+/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
+   If N is 0, then set CURRENT to the empty location which ends
+   the previous symbol: RHS[0] (always defined).  */
+
+#define YYRHSLOC(Rhs, K) ((Rhs)[K])
+#ifndef YYLLOC_DEFAULT
+# define YYLLOC_DEFAULT(Current, Rhs, N)				\
+    do									\
+      if (YYID (N))                                                    \
+	{								\
+	  (Current).first_line   = YYRHSLOC (Rhs, 1).first_line;	\
+	  (Current).first_column = YYRHSLOC (Rhs, 1).first_column;	\
+	  (Current).last_line    = YYRHSLOC (Rhs, N).last_line;		\
+	  (Current).last_column  = YYRHSLOC (Rhs, N).last_column;	\
+	}								\
+      else								\
+	{								\
+	  (Current).first_line   = (Current).last_line   =		\
+	    YYRHSLOC (Rhs, 0).last_line;				\
+	  (Current).first_column = (Current).last_column =		\
+	    YYRHSLOC (Rhs, 0).last_column;				\
+	}								\
+    while (YYID (0))
+#endif
+
+
+/* YY_LOCATION_PRINT -- Print the location on the stream.
+   This macro was not mandated originally: define only if we know
+   we won't break user code: when these are the locations we know.  */
+
+#ifndef YY_LOCATION_PRINT
+# if YYLTYPE_IS_TRIVIAL
+#  define YY_LOCATION_PRINT(File, Loc)			\
+     fprintf (File, "%d.%d-%d.%d",			\
+	      (Loc).first_line, (Loc).first_column,	\
+	      (Loc).last_line,  (Loc).last_column)
+# else
+#  define YY_LOCATION_PRINT(File, Loc) ((void) 0)
+# endif
+#endif
+
+
+/* YYLEX -- calling `yylex' with the right arguments.  */
+
+#ifdef YYLEX_PARAM
+# define YYLEX yylex (YYLEX_PARAM)
+#else
+# define YYLEX yylex ()
+#endif
+
+/* Enable debugging if requested.  */
+#if YYDEBUG
+
+# ifndef YYFPRINTF
+#  include <stdio.h> /* INFRINGES ON USER NAME SPACE */
+#  define YYFPRINTF fprintf
+# endif
+
+# define YYDPRINTF(Args)			\
+do {						\
+  if (yydebug)					\
+    YYFPRINTF Args;				\
+} while (YYID (0))
+
+# define YY_SYMBOL_PRINT(Title, Type, Value, Location)			  \
+do {									  \
+  if (yydebug)								  \
+    {									  \
+      YYFPRINTF (stderr, "%s ", Title);					  \
+      yy_symbol_print (stderr,						  \
+		  Type, Value); \
+      YYFPRINTF (stderr, "\n");						  \
+    }									  \
+} while (YYID (0))
+
+
+/*--------------------------------.
+| Print this symbol on YYOUTPUT.  |
+`--------------------------------*/
+
+/*ARGSUSED*/
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+static void
+yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
+#else
+static void
+yy_symbol_value_print (yyoutput, yytype, yyvaluep)
+    FILE *yyoutput;
+    int yytype;
+    YYSTYPE const * const yyvaluep;
+#endif
+{
+  if (!yyvaluep)
+    return;
+# ifdef YYPRINT
+  if (yytype < YYNTOKENS)
+    YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
+# else
+  YYUSE (yyoutput);
+# endif
+  switch (yytype)
+    {
+      default:
+	break;
+    }
+}
+
+
+/*--------------------------------.
+| Print this symbol on YYOUTPUT.  |
+`--------------------------------*/
+
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+static void
+yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
+#else
+static void
+yy_symbol_print (yyoutput, yytype, yyvaluep)
+    FILE *yyoutput;
+    int yytype;
+    YYSTYPE const * const yyvaluep;
+#endif
+{
+  if (yytype < YYNTOKENS)
+    YYFPRINTF (yyoutput, "token %s (", yytname[yytype]);
+  else
+    YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]);
+
+  yy_symbol_value_print (yyoutput, yytype, yyvaluep);
+  YYFPRINTF (yyoutput, ")");
+}
+
+/*------------------------------------------------------------------.
+| yy_stack_print -- Print the state stack from its BOTTOM up to its |
+| TOP (included).                                                   |
+`------------------------------------------------------------------*/
+
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+static void
+yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
+#else
+static void
+yy_stack_print (yybottom, yytop)
+    yytype_int16 *yybottom;
+    yytype_int16 *yytop;
+#endif
+{
+  YYFPRINTF (stderr, "Stack now");
+  for (; yybottom <= yytop; yybottom++)
+    {
+      int yybot = *yybottom;
+      YYFPRINTF (stderr, " %d", yybot);
+    }
+  YYFPRINTF (stderr, "\n");
+}
+
+# define YY_STACK_PRINT(Bottom, Top)				\
+do {								\
+  if (yydebug)							\
+    yy_stack_print ((Bottom), (Top));				\
+} while (YYID (0))
+
+
+/*------------------------------------------------.
+| Report that the YYRULE is going to be reduced.  |
+`------------------------------------------------*/
+
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+static void
+yy_reduce_print (YYSTYPE *yyvsp, int yyrule)
+#else
+static void
+yy_reduce_print (yyvsp, yyrule)
+    YYSTYPE *yyvsp;
+    int yyrule;
+#endif
+{
+  int yynrhs = yyr2[yyrule];
+  int yyi;
+  unsigned long int yylno = yyrline[yyrule];
+  YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
+	     yyrule - 1, yylno);
+  /* The symbols being reduced.  */
+  for (yyi = 0; yyi < yynrhs; yyi++)
+    {
+      YYFPRINTF (stderr, "   $%d = ", yyi + 1);
+      yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi],
+		       &(yyvsp[(yyi + 1) - (yynrhs)])
+		       		       );
+      YYFPRINTF (stderr, "\n");
+    }
+}
+
+# define YY_REDUCE_PRINT(Rule)		\
+do {					\
+  if (yydebug)				\
+    yy_reduce_print (yyvsp, Rule); \
+} while (YYID (0))
+
+/* Nonzero means print parse trace.  It is left uninitialized so that
+   multiple parsers can coexist.  */
+int yydebug;
+#else /* !YYDEBUG */
+# define YYDPRINTF(Args)
+# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
+# define YY_STACK_PRINT(Bottom, Top)
+# define YY_REDUCE_PRINT(Rule)
+#endif /* !YYDEBUG */
+
+
+/* YYINITDEPTH -- initial size of the parser's stacks.  */
+#ifndef	YYINITDEPTH
+# define YYINITDEPTH 200
+#endif
+
+/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
+   if the built-in stack extension method is used).
+
+   Do not make this value too large; the results are undefined if
+   YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
+   evaluated with infinite-precision integer arithmetic.  */
+
+#ifndef YYMAXDEPTH
+# define YYMAXDEPTH 10000
+#endif
+
+
+
+#if YYERROR_VERBOSE
+
+# ifndef yystrlen
+#  if defined __GLIBC__ && defined _STRING_H
+#   define yystrlen strlen
+#  else
+/* Return the length of YYSTR.  */
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+static YYSIZE_T
+yystrlen (const char *yystr)
+#else
+static YYSIZE_T
+yystrlen (yystr)
+    const char *yystr;
+#endif
+{
+  YYSIZE_T yylen;
+  for (yylen = 0; yystr[yylen]; yylen++)
+    continue;
+  return yylen;
+}
+#  endif
+# endif
+
+# ifndef yystpcpy
+#  if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
+#   define yystpcpy stpcpy
+#  else
+/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
+   YYDEST.  */
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+static char *
+yystpcpy (char *yydest, const char *yysrc)
+#else
+static char *
+yystpcpy (yydest, yysrc)
+    char *yydest;
+    const char *yysrc;
+#endif
+{
+  char *yyd = yydest;
+  const char *yys = yysrc;
+
+  while ((*yyd++ = *yys++) != '\0')
+    continue;
+
+  return yyd - 1;
+}
+#  endif
+# endif
+
+# ifndef yytnamerr
+/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
+   quotes and backslashes, so that it's suitable for yyerror.  The
+   heuristic is that double-quoting is unnecessary unless the string
+   contains an apostrophe, a comma, or backslash (other than
+   backslash-backslash).  YYSTR is taken from yytname.  If YYRES is
+   null, do not copy; instead, return the length of what the result
+   would have been.  */
+static YYSIZE_T
+yytnamerr (char *yyres, const char *yystr)
+{
+  if (*yystr == '"')
+    {
+      YYSIZE_T yyn = 0;
+      char const *yyp = yystr;
+
+      for (;;)
+	switch (*++yyp)
+	  {
+	  case '\'':
+	  case ',':
+	    goto do_not_strip_quotes;
+
+	  case '\\':
+	    if (*++yyp != '\\')
+	      goto do_not_strip_quotes;
+	    /* Fall through.  */
+	  default:
+	    if (yyres)
+	      yyres[yyn] = *yyp;
+	    yyn++;
+	    break;
+
+	  case '"':
+	    if (yyres)
+	      yyres[yyn] = '\0';
+	    return yyn;
+	  }
+    do_not_strip_quotes: ;
+    }
+
+  if (! yyres)
+    return yystrlen (yystr);
+
+  return yystpcpy (yyres, yystr) - yyres;
+}
+# endif
+
+/* Copy into YYRESULT an error message about the unexpected token
+   YYCHAR while in state YYSTATE.  Return the number of bytes copied,
+   including the terminating null byte.  If YYRESULT is null, do not
+   copy anything; just return the number of bytes that would be
+   copied.  As a special case, return 0 if an ordinary "syntax error"
+   message will do.  Return YYSIZE_MAXIMUM if overflow occurs during
+   size calculation.  */
+static YYSIZE_T
+yysyntax_error (char *yyresult, int yystate, int yychar)
+{
+  int yyn = yypact[yystate];
+
+  if (! (YYPACT_NINF < yyn && yyn <= YYLAST))
+    return 0;
+  else
+    {
+      int yytype = YYTRANSLATE (yychar);
+      YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]);
+      YYSIZE_T yysize = yysize0;
+      YYSIZE_T yysize1;
+      int yysize_overflow = 0;
+      enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
+      char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
+      int yyx;
+
+# if 0
+      /* This is so xgettext sees the translatable formats that are
+	 constructed on the fly.  */
+      YY_("syntax error, unexpected %s");
+      YY_("syntax error, unexpected %s, expecting %s");
+      YY_("syntax error, unexpected %s, expecting %s or %s");
+      YY_("syntax error, unexpected %s, expecting %s or %s or %s");
+      YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s");
+# endif
+      char *yyfmt;
+      char const *yyf;
+      static char const yyunexpected[] = "syntax error, unexpected %s";
+      static char const yyexpecting[] = ", expecting %s";
+      static char const yyor[] = " or %s";
+      char yyformat[sizeof yyunexpected
+		    + sizeof yyexpecting - 1
+		    + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2)
+		       * (sizeof yyor - 1))];
+      char const *yyprefix = yyexpecting;
+
+      /* Start YYX at -YYN if negative to avoid negative indexes in
+	 YYCHECK.  */
+      int yyxbegin = yyn < 0 ? -yyn : 0;
+
+      /* Stay within bounds of both yycheck and yytname.  */
+      int yychecklim = YYLAST - yyn + 1;
+      int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
+      int yycount = 1;
+
+      yyarg[0] = yytname[yytype];
+      yyfmt = yystpcpy (yyformat, yyunexpected);
+
+      for (yyx = yyxbegin; yyx < yyxend; ++yyx)
+	if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
+	  {
+	    if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
+	      {
+		yycount = 1;
+		yysize = yysize0;
+		yyformat[sizeof yyunexpected - 1] = '\0';
+		break;
+	      }
+	    yyarg[yycount++] = yytname[yyx];
+	    yysize1 = yysize + yytnamerr (0, yytname[yyx]);
+	    yysize_overflow |= (yysize1 < yysize);
+	    yysize = yysize1;
+	    yyfmt = yystpcpy (yyfmt, yyprefix);
+	    yyprefix = yyor;
+	  }
+
+      yyf = YY_(yyformat);
+      yysize1 = yysize + yystrlen (yyf);
+      yysize_overflow |= (yysize1 < yysize);
+      yysize = yysize1;
+
+      if (yysize_overflow)
+	return YYSIZE_MAXIMUM;
+
+      if (yyresult)
+	{
+	  /* Avoid sprintf, as that infringes on the user's name space.
+	     Don't have undefined behavior even if the translation
+	     produced a string with the wrong number of "%s"s.  */
+	  char *yyp = yyresult;
+	  int yyi = 0;
+	  while ((*yyp = *yyf) != '\0')
+	    {
+	      if (*yyp == '%' && yyf[1] == 's' && yyi < yycount)
+		{
+		  yyp += yytnamerr (yyp, yyarg[yyi++]);
+		  yyf += 2;
+		}
+	      else
+		{
+		  yyp++;
+		  yyf++;
+		}
+	    }
+	}
+      return yysize;
+    }
+}
+#endif /* YYERROR_VERBOSE */
+
+
+/*-----------------------------------------------.
+| Release the memory associated to this symbol.  |
+`-----------------------------------------------*/
+
+/*ARGSUSED*/
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+static void
+yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep)
+#else
+static void
+yydestruct (yymsg, yytype, yyvaluep)
+    const char *yymsg;
+    int yytype;
+    YYSTYPE *yyvaluep;
+#endif
+{
+  YYUSE (yyvaluep);
+
+  if (!yymsg)
+    yymsg = "Deleting";
+  YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
+
+  switch (yytype)
+    {
+
+      default:
+	break;
+    }
+}
+
+/* Prevent warnings from -Wmissing-prototypes.  */
+#ifdef YYPARSE_PARAM
+#if defined __STDC__ || defined __cplusplus
+int yyparse (void *YYPARSE_PARAM);
+#else
+int yyparse ();
+#endif
+#else /* ! YYPARSE_PARAM */
+#if defined __STDC__ || defined __cplusplus
+int yyparse (void);
+#else
+int yyparse ();
+#endif
+#endif /* ! YYPARSE_PARAM */
+
+
+/* The lookahead symbol.  */
+int yychar;
+
+/* The semantic value of the lookahead symbol.  */
+YYSTYPE yylval;
+
+/* Number of syntax errors so far.  */
+int yynerrs;
+
+
+
+/*-------------------------.
+| yyparse or yypush_parse.  |
+`-------------------------*/
+
+#ifdef YYPARSE_PARAM
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+int
+yyparse (void *YYPARSE_PARAM)
+#else
+int
+yyparse (YYPARSE_PARAM)
+    void *YYPARSE_PARAM;
+#endif
+#else /* ! YYPARSE_PARAM */
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+int
+yyparse (void)
+#else
+int
+yyparse ()
+
+#endif
+#endif
+{
+
+
+    int yystate;
+    /* Number of tokens to shift before error messages enabled.  */
+    int yyerrstatus;
+
+    /* The stacks and their tools:
+       `yyss': related to states.
+       `yyvs': related to semantic values.
+
+       Refer to the stacks thru separate pointers, to allow yyoverflow
+       to reallocate them elsewhere.  */
+
+    /* The state stack.  */
+    yytype_int16 yyssa[YYINITDEPTH];
+    yytype_int16 *yyss;
+    yytype_int16 *yyssp;
+
+    /* The semantic value stack.  */
+    YYSTYPE yyvsa[YYINITDEPTH];
+    YYSTYPE *yyvs;
+    YYSTYPE *yyvsp;
+
+    YYSIZE_T yystacksize;
+
+  int yyn;
+  int yyresult;
+  /* Lookahead token as an internal (translated) token number.  */
+  int yytoken;
+  /* The variables used to return semantic value and location from the
+     action routines.  */
+  YYSTYPE yyval;
+
+#if YYERROR_VERBOSE
+  /* Buffer for error messages, and its allocated size.  */
+  char yymsgbuf[128];
+  char *yymsg = yymsgbuf;
+  YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
+#endif
+
+#define YYPOPSTACK(N)   (yyvsp -= (N), yyssp -= (N))
+
+  /* The number of symbols on the RHS of the reduced rule.
+     Keep to zero when no symbol should be popped.  */
+  int yylen = 0;
+
+  yytoken = 0;
+  yyss = yyssa;
+  yyvs = yyvsa;
+  yystacksize = YYINITDEPTH;
+
+  YYDPRINTF ((stderr, "Starting parse\n"));
+
+  yystate = 0;
+  yyerrstatus = 0;
+  yynerrs = 0;
+  yychar = YYEMPTY; /* Cause a token to be read.  */
+
+  /* Initialize stack pointers.
+     Waste one element of value and location stack
+     so that they stay on the same level as the state stack.
+     The wasted elements are never initialized.  */
+  yyssp = yyss;
+  yyvsp = yyvs;
+
+  goto yysetstate;
+
+/*------------------------------------------------------------.
+| yynewstate -- Push a new state, which is found in yystate.  |
+`------------------------------------------------------------*/
+ yynewstate:
+  /* In all cases, when you get here, the value and location stacks
+     have just been pushed.  So pushing a state here evens the stacks.  */
+  yyssp++;
+
+ yysetstate:
+  *yyssp = yystate;
+
+  if (yyss + yystacksize - 1 <= yyssp)
+    {
+      /* Get the current used size of the three stacks, in elements.  */
+      YYSIZE_T yysize = yyssp - yyss + 1;
+
+#ifdef yyoverflow
+      {
+	/* Give user a chance to reallocate the stack.  Use copies of
+	   these so that the &'s don't force the real ones into
+	   memory.  */
+	YYSTYPE *yyvs1 = yyvs;
+	yytype_int16 *yyss1 = yyss;
+
+	/* Each stack pointer address is followed by the size of the
+	   data in use in that stack, in bytes.  This used to be a
+	   conditional around just the two extra args, but that might
+	   be undefined if yyoverflow is a macro.  */
+	yyoverflow (YY_("memory exhausted"),
+		    &yyss1, yysize * sizeof (*yyssp),
+		    &yyvs1, yysize * sizeof (*yyvsp),
+		    &yystacksize);
+
+	yyss = yyss1;
+	yyvs = yyvs1;
+      }
+#else /* no yyoverflow */
+# ifndef YYSTACK_RELOCATE
+      goto yyexhaustedlab;
+# else
+      /* Extend the stack our own way.  */
+      if (YYMAXDEPTH <= yystacksize)
+	goto yyexhaustedlab;
+      yystacksize *= 2;
+      if (YYMAXDEPTH < yystacksize)
+	yystacksize = YYMAXDEPTH;
+
+      {
+	yytype_int16 *yyss1 = yyss;
+	union yyalloc *yyptr =
+	  (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
+	if (! yyptr)
+	  goto yyexhaustedlab;
+	YYSTACK_RELOCATE (yyss_alloc, yyss);
+	YYSTACK_RELOCATE (yyvs_alloc, yyvs);
+#  undef YYSTACK_RELOCATE
+	if (yyss1 != yyssa)
+	  YYSTACK_FREE (yyss1);
+      }
+# endif
+#endif /* no yyoverflow */
+
+      yyssp = yyss + yysize - 1;
+      yyvsp = yyvs + yysize - 1;
+
+      YYDPRINTF ((stderr, "Stack size increased to %lu\n",
+		  (unsigned long int) yystacksize));
+
+      if (yyss + yystacksize - 1 <= yyssp)
+	YYABORT;
+    }
+
+  YYDPRINTF ((stderr, "Entering state %d\n", yystate));
+
+  if (yystate == YYFINAL)
+    YYACCEPT;
+
+  goto yybackup;
+
+/*-----------.
+| yybackup.  |
+`-----------*/
+yybackup:
+
+  /* Do appropriate processing given the current state.  Read a
+     lookahead token if we need one and don't already have one.  */
+
+  /* First try to decide what to do without reference to lookahead token.  */
+  yyn = yypact[yystate];
+  if (yyn == YYPACT_NINF)
+    goto yydefault;
+
+  /* Not known => get a lookahead token if don't already have one.  */
+
+  /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol.  */
+  if (yychar == YYEMPTY)
+    {
+      YYDPRINTF ((stderr, "Reading a token: "));
+      yychar = YYLEX;
+    }
+
+  if (yychar <= YYEOF)
+    {
+      yychar = yytoken = YYEOF;
+      YYDPRINTF ((stderr, "Now at end of input.\n"));
+    }
+  else
+    {
+      yytoken = YYTRANSLATE (yychar);
+      YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
+    }
+
+  /* If the proper action on seeing token YYTOKEN is to reduce or to
+     detect an error, take that action.  */
+  yyn += yytoken;
+  if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
+    goto yydefault;
+  yyn = yytable[yyn];
+  if (yyn <= 0)
+    {
+      if (yyn == 0 || yyn == YYTABLE_NINF)
+	goto yyerrlab;
+      yyn = -yyn;
+      goto yyreduce;
+    }
+
+  /* Count tokens shifted since error; after three, turn off error
+     status.  */
+  if (yyerrstatus)
+    yyerrstatus--;
+
+  /* Shift the lookahead token.  */
+  YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
+
+  /* Discard the shifted token.  */
+  yychar = YYEMPTY;
+
+  yystate = yyn;
+  *++yyvsp = yylval;
+
+  goto yynewstate;
+
+
+/*-----------------------------------------------------------.
+| yydefault -- do the default action for the current state.  |
+`-----------------------------------------------------------*/
+yydefault:
+  yyn = yydefact[yystate];
+  if (yyn == 0)
+    goto yyerrlab;
+  goto yyreduce;
+
+
+/*-----------------------------.
+| yyreduce -- Do a reduction.  |
+`-----------------------------*/
+yyreduce:
+  /* yyn is the number of a rule to reduce with.  */
+  yylen = yyr2[yyn];
+
+  /* If YYLEN is nonzero, implement the default value of the action:
+     `$$ = $1'.
+
+     Otherwise, the following line sets YYVAL to garbage.
+     This behavior is undocumented and Bison
+     users should not rely upon it.  Assigning to YYVAL
+     unconditionally makes the parser a bit smaller, and it avoids a
+     GCC warning that YYVAL may be used uninitialized.  */
+  yyval = yyvsp[1-yylen];
+
+
+  YY_REDUCE_PRINT (yyn);
+  switch (yyn)
+    {
+        case 2:
+
+/* Line 1455 of yacc.c  */
+#line 182 "rcomp.yacc"
+    {	if(verbose)	{	MOFF; cout << Divider << "\n" << Divider << endl; MON; }
+										;}
+    break;
+
+  case 15:
+
+/* Line 1455 of yacc.c  */
+#line 208 "rcomp.yacc"
+    {
+		// This is my gift to the world: no more "syntax error" for adding
+		// an extra semicolon at the end of a struct or resource.
+	    REGISTER_LINE;
+	    ErrorHandler::OutputErrorLine("Warning: unnecessary semicolon");
+		;}
+    break;
+
+  case 17:
+
+/* Line 1455 of yacc.c  */
+#line 222 "rcomp.yacc"
+    {	if(verbose) { MOFF; cout << Divider << "\n" << * pSH << Divider << endl; MON;}	;}
+    break;
+
+  case 18:
+
+/* Line 1455 of yacc.c  */
+#line 226 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "struct_statement_start                     " << (yyvsp[(2) - (4)].Value) << endl; MON;}
+											pSH = new StructHeader((yyvsp[(2) - (4)].Value));
+											REGISTER_LINE;
+											pG->SHA.Add(pSH);
+										;}
+    break;
+
+  case 19:
+
+/* Line 1455 of yacc.c  */
+#line 232 "rcomp.yacc"
+    {	if(verbose) {	RCTypeArray Types; MOFF;cout << "struct_statement_start                     " << (yyvsp[(2) - (5)].Value) << " " << Types.GetName((yyvsp[(3) - (5)].Id)) << endl; MON;}
+											pSH = new StructHeader((yyvsp[(2) - (5)].Value), (yyvsp[(3) - (5)].Id));
+											REGISTER_LINE;
+											pG->SHA.Add(pSH);
+										;}
+    break;
+
+  case 20:
+
+/* Line 1455 of yacc.c  */
+#line 238 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "struct_statement_start                     " << (yyvsp[(2) - (5)].Value) << " (WORD)" << endl; MON;}
+											pSH = new StructHeader((yyvsp[(2) - (5)].Value), L_WORD);
+											REGISTER_LINE;
+											pG->SHA.Add(pSH);
+										;}
+    break;
+
+  case 21:
+
+/* Line 1455 of yacc.c  */
+#line 245 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "struct_item_list                           Adding struct_item." << endl; MON;}
+											REGISTER_LINE;
+											pSH->iSIA.Add((yyvsp[(2) - (3)].pStructItem));
+										;}
+    break;
+
+  case 22:
+
+/* Line 1455 of yacc.c  */
+#line 249 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "tagged struct_item_list                    Adding struct_item." << endl; MON;}
+											REGISTER_LINE;
+											pSH->iSIA.Add((yyvsp[(3) - (4)].pStructItem));
+										;}
+    break;
+
+  case 28:
+
+/* Line 1455 of yacc.c  */
+#line 262 "rcomp.yacc"
+    {	(yyval.pStructItem) = (yyvsp[(1) - (1)].pSimpleStructItem);;}
+    break;
+
+  case 29:
+
+/* Line 1455 of yacc.c  */
+#line 264 "rcomp.yacc"
+    {	if(verbose) { MOFF;cout << "    Limit: " << (yyvsp[(3) - (4)].Value) << endl; MON;}
+											(yyvsp[(1) - (4)].pSimpleStructItem)->iLengthLimit = (yyvsp[(3) - (4)].Value);
+											(yyval.pStructItem) = (yyvsp[(1) - (4)].pSimpleStructItem);
+										;}
+    break;
+
+  case 30:
+
+/* Line 1455 of yacc.c  */
+#line 269 "rcomp.yacc"
+    {	if(verbose) { MOFF;cout << "    Default: " << (yyvsp[(3) - (3)].Value) << endl; MON;}
+											(yyvsp[(1) - (3)].pSimpleStructItem)->iDefault = (yyvsp[(3) - (3)].Value);
+											(yyval.pStructItem) = (yyvsp[(1) - (3)].pSimpleStructItem);
+										;}
+    break;
+
+  case 31:
+
+/* Line 1455 of yacc.c  */
+#line 274 "rcomp.yacc"
+    {	if(verbose) { MOFF;cout << "    Limit: " << (yyvsp[(3) - (6)].Value) << ", Default: " << (yyvsp[(6) - (6)].Value) << endl; MON;}
+											NumericValue Limit((yyvsp[(3) - (6)].Value), L_LONG);
+											if(String((yyvsp[(6) - (6)].Value)).ExportLength(TargetCharacterSet,SourceCharacterSet) > Limit.GetULong() )
+											{
+												REGISTER_LINE;
+												ErrorHandler::OutputErrorLine("Text length exceeds specified limit");
+												exit(1);
+											}
+											(yyvsp[(1) - (6)].pSimpleStructItem)->iLengthLimit = (yyvsp[(3) - (6)].Value);
+											(yyvsp[(1) - (6)].pSimpleStructItem)->iDefault = (yyvsp[(6) - (6)].Value);
+											(yyval.pStructItem) = (yyvsp[(1) - (6)].pSimpleStructItem);
+										;}
+    break;
+
+  case 32:
+
+/* Line 1455 of yacc.c  */
+#line 289 "rcomp.yacc"
+    {	if(verbose) 
+											{		
+												   RCTypeArray Types;
+														   MOFF;cout << "simple_struct_item                         " << Types.GetName((yyvsp[(1) - (2)].Id)) << " " << (yyvsp[(2) - (2)].Value) << endl; MON;
+											}
+											(yyval.pSimpleStructItem) = new SimpleStructItem((yyvsp[(1) - (2)].Id),(yyvsp[(2) - (2)].Value)); 
+											assert((yyval.pSimpleStructItem) != NULL);
+										;}
+    break;
+
+  case 33:
+
+/* Line 1455 of yacc.c  */
+#line 298 "rcomp.yacc"
+    {	if(verbose) 
+											{			   RCTypeArray Types;
+														   MOFF;cout << "simple_struct_item                         " << Types.GetName((yyvsp[(1) - (5)].Id)) << " " << (yyvsp[(5) - (5)].Value) << endl; MON;
+											}
+											String s(NumericValue::ltoa((yyvsp[(3) - (5)].NumInitialiser)));
+											(yyval.pSimpleStructItem) = new SimpleStructItem((yyvsp[(1) - (5)].Id),(yyvsp[(5) - (5)].Value),s);
+											assert((yyval.pSimpleStructItem) != NULL);
+										;}
+    break;
+
+  case 34:
+
+/* Line 1455 of yacc.c  */
+#line 312 "rcomp.yacc"
+    {	(yyval.Id) = L_BYTE;;}
+    break;
+
+  case 35:
+
+/* Line 1455 of yacc.c  */
+#line 313 "rcomp.yacc"
+    {	(yyval.Id) = L_WORD;;}
+    break;
+
+  case 36:
+
+/* Line 1455 of yacc.c  */
+#line 314 "rcomp.yacc"
+    {	(yyval.Id) = L_LONG;;}
+    break;
+
+  case 37:
+
+/* Line 1455 of yacc.c  */
+#line 315 "rcomp.yacc"
+    {	(yyval.Id) = L_DOUBLE;;}
+    break;
+
+  case 38:
+
+/* Line 1455 of yacc.c  */
+#line 320 "rcomp.yacc"
+    { 
+	    (yyval.Id) = ( TargetCharacterSet == String::Unicode ) ? L_TEXT16: L_TEXT8;
+	    REGISTER_LINE;
+	    ErrorHandler::OutputErrorLine("Warning: Deprecated use of zero-terminated TEXT - use LTEXT instead");
+	    ;}
+    break;
+
+  case 39:
+
+/* Line 1455 of yacc.c  */
+#line 326 "rcomp.yacc"
+    {
+	    (yyval.Id) = ( TargetCharacterSet == String::Unicode ) ? L_LTEXT16: L_LTEXT8;
+	    ;}
+    break;
+
+  case 40:
+
+/* Line 1455 of yacc.c  */
+#line 330 "rcomp.yacc"
+    { 
+	    (yyval.Id) = ( TargetCharacterSet == String::Unicode ) ? L_BUF16: L_BUF8;
+	    ;}
+    break;
+
+  case 41:
+
+/* Line 1455 of yacc.c  */
+#line 336 "rcomp.yacc"
+    {	(yyval.Id) = L_TEXT8;
+											REGISTER_LINE;
+											ErrorHandler::OutputErrorLine("Warning: Deprecated use of zero-terminated TEXT8 - use LTEXT8 instead");
+										;}
+    break;
+
+  case 42:
+
+/* Line 1455 of yacc.c  */
+#line 340 "rcomp.yacc"
+    {	(yyval.Id) = L_TEXT16;
+											REGISTER_LINE;
+											ErrorHandler::OutputErrorLine("Warning: Deprecated use of zero-terminated TEXT16 - use LTEXT16 instead");
+										;}
+    break;
+
+  case 43:
+
+/* Line 1455 of yacc.c  */
+#line 344 "rcomp.yacc"
+    {	(yyval.Id) = L_LTEXT8;;}
+    break;
+
+  case 44:
+
+/* Line 1455 of yacc.c  */
+#line 345 "rcomp.yacc"
+    {	(yyval.Id) = L_LTEXT16;;}
+    break;
+
+  case 45:
+
+/* Line 1455 of yacc.c  */
+#line 346 "rcomp.yacc"
+    {	(yyval.Id) = L_BUF8;;}
+    break;
+
+  case 46:
+
+/* Line 1455 of yacc.c  */
+#line 347 "rcomp.yacc"
+    {	(yyval.Id) = L_BUF16;;}
+    break;
+
+  case 47:
+
+/* Line 1455 of yacc.c  */
+#line 348 "rcomp.yacc"
+    {	(yyval.Id) = L_LINK;;}
+    break;
+
+  case 48:
+
+/* Line 1455 of yacc.c  */
+#line 349 "rcomp.yacc"
+    {	(yyval.Id) = L_LLINK;;}
+    break;
+
+  case 49:
+
+/* Line 1455 of yacc.c  */
+#line 350 "rcomp.yacc"
+    {	(yyval.Id) = L_SRLINK;;}
+    break;
+
+  case 50:
+
+/* Line 1455 of yacc.c  */
+#line 353 "rcomp.yacc"
+    {	(yyval.pStructItem) = (yyvsp[(1) - (1)].pArrayStructItem);;}
+    break;
+
+  case 51:
+
+/* Line 1455 of yacc.c  */
+#line 355 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "array_struct_item                          with simple_initialiser_list" << endl;MON;}
+											(yyvsp[(1) - (5)].pArrayStructItem)->iDefaults = * (yyvsp[(4) - (5)].pStringArray);
+											if((yyvsp[(1) - (5)].pArrayStructItem)->iSize.Length() > 0)
+											{
+												NumericValue v((yyvsp[(1) - (5)].pArrayStructItem)->iSize, L_LONG);
+												REGISTER_LINE;
+												if((yyvsp[(4) - (5)].pStringArray)->Size()!=long(v.GetULong()))
+												{
+													ErrorHandler::OutputErrorLine("Size does not match number of initialisers");
+													exit(1);
+												}
+											}
+											(yyval.pStructItem) = (yyvsp[(1) - (5)].pArrayStructItem);
+											delete (yyvsp[(4) - (5)].pStringArray);
+										;}
+    break;
+
+  case 52:
+
+/* Line 1455 of yacc.c  */
+#line 372 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "array_struct_item_base                     with no size" << endl;MON;}
+											(yyval.pArrayStructItem) =(yyvsp[(1) - (2)].pArrayStructItem);
+										;}
+    break;
+
+  case 53:
+
+/* Line 1455 of yacc.c  */
+#line 376 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "array_struct_item_base                     with size " << (yyvsp[(2) - (3)].Value) << endl;MON;}
+											(yyvsp[(1) - (3)].pArrayStructItem)->iSize = (yyvsp[(2) - (3)].Value);
+											(yyval.pArrayStructItem) = (yyvsp[(1) - (3)].pArrayStructItem);
+										;}
+    break;
+
+  case 54:
+
+/* Line 1455 of yacc.c  */
+#line 381 "rcomp.yacc"
+    {	if(verbose) 
+												{		 	RCTypeArray Types;
+														 	MOFF;cout << "array_struct_item_base                     with LenType " << Types.GetName((yyvsp[(2) - (4)].Id)) << endl;MON;
+												}
+											(yyvsp[(3) - (4)].pArrayStructItem)->iLenType = (yyvsp[(2) - (4)].Id);
+											(yyval.pArrayStructItem) = (yyvsp[(3) - (4)].pArrayStructItem);
+										;}
+    break;
+
+  case 55:
+
+/* Line 1455 of yacc.c  */
+#line 389 "rcomp.yacc"
+    {	if(verbose) 
+												{		 	RCTypeArray Types;
+														 	MOFF;cout << "array_struct_item_base                     with size " << (yyvsp[(4) - (5)].Value) << " and LenType " << Types.GetName((yyvsp[(2) - (5)].Id)) << endl;MON;
+												}
+											(yyvsp[(3) - (5)].pArrayStructItem)->iLenType = (yyvsp[(2) - (5)].Id);
+											(yyvsp[(3) - (5)].pArrayStructItem)->iSize = (yyvsp[(4) - (5)].Value); 
+											(yyval.pArrayStructItem) = (yyvsp[(3) - (5)].pArrayStructItem); 
+										;}
+    break;
+
+  case 56:
+
+/* Line 1455 of yacc.c  */
+#line 399 "rcomp.yacc"
+    {	if(verbose) 
+												{		 	RCTypeArray Types; 
+														 	MOFF;cout << "array_struct_item_start                    " << Types.GetName((yyvsp[(1) - (3)].Id)) << " " << (yyvsp[(2) - (3)].Value) << endl;MON;
+												}
+											(yyval.pArrayStructItem) = new ArrayStructItem((yyvsp[(1) - (3)].Id), (yyvsp[(2) - (3)].Value));
+										;}
+    break;
+
+  case 57:
+
+/* Line 1455 of yacc.c  */
+#line 407 "rcomp.yacc"
+    {	(yyval.Id) = L_BYTE;;}
+    break;
+
+  case 58:
+
+/* Line 1455 of yacc.c  */
+#line 408 "rcomp.yacc"
+    {	(yyval.Id) = L_WORD;;}
+    break;
+
+  case 59:
+
+/* Line 1455 of yacc.c  */
+#line 411 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "struct_type_struct_item                    " << (yyvsp[(2) - (2)].Value) << endl;MON;}
+											(yyval.pStructItem) = new StructTypeStructItem((yyvsp[(2) - (2)].Value));
+										;}
+    break;
+
+  case 60:
+
+/* Line 1455 of yacc.c  */
+#line 416 "rcomp.yacc"
+    {	(yyval.pStructItem) = (yyvsp[(1) - (1)].pStructArrayStructItem);;}
+    break;
+
+  case 61:
+
+/* Line 1455 of yacc.c  */
+#line 418 "rcomp.yacc"
+    {	if(verbose) {	RCTypeArray Types; MOFF;cout << "struct_array_struct_item                   - Setting Size to " << Types.GetName((yyvsp[(2) - (3)].Id)) << endl;MON;}
+											(yyvsp[(3) - (3)].pStructArrayStructItem)->iLenType = (yyvsp[(2) - (3)].Id); (yyval.pStructItem) = (yyvsp[(3) - (3)].pStructArrayStructItem);
+										;}
+    break;
+
+  case 62:
+
+/* Line 1455 of yacc.c  */
+#line 423 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "struct_array_struct_item_base              " << (yyvsp[(2) - (4)].Value) << endl;MON;}
+											(yyval.pStructArrayStructItem) = new StructArrayStructItem((yyvsp[(2) - (4)].Value));
+										;}
+    break;
+
+  case 63:
+
+/* Line 1455 of yacc.c  */
+#line 427 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "struct_array_struct_item_base              " << (yyvsp[(2) - (5)].Value) << " " << (yyvsp[(4) - (5)].Value) << endl;MON;}
+											(yyval.pStructArrayStructItem) = new StructArrayStructItem((yyvsp[(2) - (5)].Value), (yyvsp[(4) - (5)].Value));
+										;}
+    break;
+
+  case 64:
+
+/* Line 1455 of yacc.c  */
+#line 436 "rcomp.yacc"
+    {	
+	    pResourceHeader->AddDefault();
+	    CurrentId+=CurrentIdStep;
+	    if(verbose) { MOFF;cout << "Resource ID "<< CurrentId << endl << Divider << "\n" << * pResourceHeader << Divider << endl;MON;}
+	    pResourceHeader->SetResourceId(*pResourceNameIds,CurrentId,FormatIdAsHex);
+	    pG->Index.Add(pResourceHeader);
+		
+		CheckStructUsage();
+
+		pUsedLabelsArray->Empty();
+
+	    pResourceHeader = NULL;
+	    ;}
+    break;
+
+  case 65:
+
+/* Line 1455 of yacc.c  */
+#line 451 "rcomp.yacc"
+    {;}
+    break;
+
+  case 66:
+
+/* Line 1455 of yacc.c  */
+#line 453 "rcomp.yacc"
+    {	
+	    if(verbose) { MOFF;cout << "resource_statement_start                   LOCAL" << endl;MON;}
+		    assert(pResourceHeader != NULL);
+		    pResourceHeader->iLocal = 1;
+	    ;}
+    break;
+
+  case 67:
+
+/* Line 1455 of yacc.c  */
+#line 458 "rcomp.yacc"
+    {;}
+    break;
+
+  case 68:
+
+/* Line 1455 of yacc.c  */
+#line 461 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "resource_statement_start_names             " << (yyvsp[(2) - (3)].Value) << " " << (yyvsp[(3) - (3)].Value) << endl;MON;}
+											assert(pResourceHeader == NULL);
+											pResourceHeader = new ResourceHeader((yyvsp[(3) - (3)].Value));
+											pCurrentRIA = & (pResourceHeader->iRIA);
+											REGISTER_LINE;
+											if(pResourceNameIds->IsStored((yyvsp[(3) - (3)].Value)))
+											{
+												ErrorHandler::OutputErrorLine("Resource with this name encountered already");
+												exit(1);
+											}
+											pCurrentRIA->FillFromStruct((yyvsp[(2) - (3)].Value));
+											pG->AllIdentifiers.Add(new String((yyvsp[(3) - (3)].Value))); // Add label to store
+										;}
+    break;
+
+  case 69:
+
+/* Line 1455 of yacc.c  */
+#line 474 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "resource_statement_start_names             " << (yyvsp[(2) - (2)].Value) << " <Resource not named>" << endl;MON;}
+											assert(pResourceHeader == NULL);
+											pResourceHeader = new ResourceHeader;
+											pCurrentRIA = & (pResourceHeader->iRIA);
+											REGISTER_LINE;
+											pCurrentRIA->FillFromStruct((yyvsp[(2) - (2)].Value));
+										;}
+    break;
+
+  case 70:
+
+/* Line 1455 of yacc.c  */
+#line 483 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "resource_item_list" << endl;MON;};}
+    break;
+
+  case 71:
+
+/* Line 1455 of yacc.c  */
+#line 484 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "tagged resource_item_list" << endl;MON;};}
+    break;
+
+  case 72:
+
+/* Line 1455 of yacc.c  */
+#line 485 "rcomp.yacc"
+    {	yyerrok; yyclearin; ;}
+    break;
+
+  case 74:
+
+/* Line 1455 of yacc.c  */
+#line 489 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "resource_item                              " << (yyvsp[(1) - (3)].Value) << " " << (yyvsp[(3) - (3)].Value) << endl;MON;}
+											REGISTER_LINE;/****************************************************************/
+											pCurrentRIA->Set((yyvsp[(1) - (3)].Value), (yyvsp[(3) - (3)].Value));
+										;}
+    break;
+
+  case 78:
+
+/* Line 1455 of yacc.c  */
+#line 499 "rcomp.yacc"
+    {	
+	    if (verbose) 
+		{ MOFF;cout << "resource_simple_array_item                 " << (yyvsp[(1) - (4)].Value) << endl;MON;} 
+	    ;}
+    break;
+
+  case 79:
+
+/* Line 1455 of yacc.c  */
+#line 504 "rcomp.yacc"
+    {	
+	    if (verbose) 
+		{ MOFF;cout << "resource_simple_array_item                 " << (yyvsp[(1) - (5)].Value) << " with simple_initialiser_list" << endl;MON;}
+	    REGISTER_LINE;
+	    pCurrentRIA->Set((yyvsp[(1) - (5)].Value), * (yyvsp[(4) - (5)].pStringArray));
+	    delete (yyvsp[(4) - (5)].pStringArray);
+	    ;}
+    break;
+
+  case 80:
+
+/* Line 1455 of yacc.c  */
+#line 532 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "struct_resource_item" << endl;MON;}
+											pCurrentRIA = pG->RIAStack.Pop();
+										;}
+    break;
+
+  case 81:
+
+/* Line 1455 of yacc.c  */
+#line 537 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "struct_resource_item_start                 " << (yyvsp[(1) - (4)].Value) << " " << (yyvsp[(3) - (4)].Value) << endl;MON;}
+											REGISTER_LINE;
+											pCurrentRIA->Set((yyvsp[(1) - (4)].Value), (yyvsp[(3) - (4)].Value));
+											String * thisLabel = new String((yyvsp[(1) - (4)].Value));
+											pUsedLabelsArray->Add(thisLabel);
+											// in here add the label to a temp store
+											pG->RIAStack.Push(pCurrentRIA);
+											pCurrentRIA = pCurrentRIA->Find((yyvsp[(1) - (4)].Value))->GetRIA();
+										;}
+    break;
+
+  case 82:
+
+/* Line 1455 of yacc.c  */
+#line 549 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "struct_array_resource_item" << endl;MON;}
+											pG->SRIStack.Pop();
+										;}
+    break;
+
+  case 83:
+
+/* Line 1455 of yacc.c  */
+#line 553 "rcomp.yacc"
+    {	pG->SRIStack.Pop();;}
+    break;
+
+  case 84:
+
+/* Line 1455 of yacc.c  */
+#line 556 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "struct_array_resource_item_start           " << (yyvsp[(1) - (5)].Value) << " " << (yyvsp[(4) - (5)].Value) << endl;MON;}
+											ResourceItem * p = pCurrentRIA->Find((yyvsp[(1) - (5)].Value));
+											pG->SRIStack.Push(p);
+											REGISTER_LINE;
+											String * thisLabel = new String((yyvsp[(1) - (5)].Value));
+											pUsedLabelsArray->Add(thisLabel);
+											// in here add the label to a temp store
+											p->Set((yyvsp[(4) - (5)].Value));
+											pG->RIAStack.Push(pCurrentRIA);
+											pCurrentRIA = p->GetRIA();
+										;}
+    break;
+
+  case 88:
+
+/* Line 1455 of yacc.c  */
+#line 574 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "struct_array_resource_item_list_top        " << endl;MON;}
+											pCurrentRIA = pG->RIAStack.Pop();
+										;}
+    break;
+
+  case 91:
+
+/* Line 1455 of yacc.c  */
+#line 584 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "struct_array_resource_item_list_item       " << endl;MON;}
+											pCurrentRIA = pG->RIAStack.Pop();
+										;}
+    break;
+
+  case 92:
+
+/* Line 1455 of yacc.c  */
+#line 589 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "struct_array_resource_item_list_item_start " << (yyvsp[(1) - (2)].Value) << endl;MON;}
+											ResourceItem * p = pG->SRIStack.Peek();
+											REGISTER_LINE;
+											p->Set((yyvsp[(1) - (2)].Value));
+											pG->RIAStack.Push(pCurrentRIA);
+											pCurrentRIA = p->GetRIA();
+										;}
+    break;
+
+  case 94:
+
+/* Line 1455 of yacc.c  */
+#line 605 "rcomp.yacc"
+    { 
+	    // convert literal to unsigned long value of 1st character
+		SetCharacterLiteral((yyval.Value), (yyvsp[(1) - (1)].Value));
+	    ;}
+    break;
+
+  case 97:
+
+/* Line 1455 of yacc.c  */
+#line 614 "rcomp.yacc"
+    {
+	    if(verbose) 
+		{	
+		MOFF;cout << "simple_initialiser_list                    - single string " << (yyvsp[(1) - (1)].Value) << endl;MON;
+		}
+		
+	    (yyval.pStringArray) = new StringArray;
+	    (yyval.pStringArray)->Add(new String((yyvsp[(1) - (1)].Value)) );
+	    ;}
+    break;
+
+  case 98:
+
+/* Line 1455 of yacc.c  */
+#line 624 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "simple_initialiser_list                    - part of list " << (yyvsp[(3) - (3)].Value) << endl;MON;}
+											assert((yyvsp[(1) - (3)].pStringArray) != NULL);
+											(yyvsp[(1) - (3)].pStringArray)->Add(new String((yyvsp[(3) - (3)].Value) ) );
+											(yyval.pStringArray) = (yyvsp[(1) - (3)].pStringArray);
+										;}
+    break;
+
+  case 99:
+
+/* Line 1455 of yacc.c  */
+#line 632 "rcomp.yacc"
+    {	String s(NumericValue::ltoa((yyvsp[(1) - (1)].NumInitialiser)) ); strcpy((yyval.Value), s.GetAssertedNonEmptyBuffer() ); ;}
+    break;
+
+  case 100:
+
+/* Line 1455 of yacc.c  */
+#line 635 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "Converting number " << (yyvsp[(1) - (1)].Value) << endl;MON;}
+											REGISTER_LINE;
+											NumericValue v((yyvsp[(1) - (1)].Value), L_LONG); (yyval.NumInitialiser) = (long)v.GetULong();
+										;}
+    break;
+
+  case 101:
+
+/* Line 1455 of yacc.c  */
+#line 639 "rcomp.yacc"
+    {	(yyval.NumInitialiser) = (yyvsp[(1) - (3)].NumInitialiser) + (yyvsp[(3) - (3)].NumInitialiser);	;}
+    break;
+
+  case 102:
+
+/* Line 1455 of yacc.c  */
+#line 640 "rcomp.yacc"
+    {	(yyval.NumInitialiser) = (yyvsp[(1) - (3)].NumInitialiser) - (yyvsp[(3) - (3)].NumInitialiser);	;}
+    break;
+
+  case 103:
+
+/* Line 1455 of yacc.c  */
+#line 641 "rcomp.yacc"
+    {	(yyval.NumInitialiser) = (yyvsp[(1) - (3)].NumInitialiser) * (yyvsp[(3) - (3)].NumInitialiser);	;}
+    break;
+
+  case 104:
+
+/* Line 1455 of yacc.c  */
+#line 642 "rcomp.yacc"
+    {	(yyval.NumInitialiser) = (yyvsp[(1) - (3)].NumInitialiser) / (yyvsp[(3) - (3)].NumInitialiser);	;}
+    break;
+
+  case 105:
+
+/* Line 1455 of yacc.c  */
+#line 643 "rcomp.yacc"
+    {	(yyval.NumInitialiser) = (yyvsp[(1) - (3)].NumInitialiser) | (yyvsp[(3) - (3)].NumInitialiser);	;}
+    break;
+
+  case 106:
+
+/* Line 1455 of yacc.c  */
+#line 644 "rcomp.yacc"
+    {	if (!NumericValue::CheckSigned((yyvsp[(2) - (2)].NumInitialiser),L_LONG))
+																	{
+																	REGISTER_LINE;
+																	ErrorHandler::OutputErrorLine("Signed value too low");
+																	exit(1);
+																	}
+																	(yyval.NumInitialiser) = - (yyvsp[(2) - (2)].NumInitialiser);		
+																;}
+    break;
+
+  case 107:
+
+/* Line 1455 of yacc.c  */
+#line 652 "rcomp.yacc"
+    {	(yyval.NumInitialiser) = (yyvsp[(2) - (3)].NumInitialiser);		;}
+    break;
+
+  case 109:
+
+/* Line 1455 of yacc.c  */
+#line 656 "rcomp.yacc"
+    {
+	    if (strlen((yyval.Value))+strlen((yyvsp[(2) - (2)].Value)) > sizeof((yyval.Value))-1)
+		{
+		REGISTER_LINE;
+		ErrorHandler::OutputErrorLine("String expression is too long");
+		exit(1);
+		}
+	    strcat((yyval.Value), (yyvsp[(2) - (2)].Value));
+	    ;}
+    break;
+
+  case 112:
+
+/* Line 1455 of yacc.c  */
+#line 670 "rcomp.yacc"
+    {
+		const char * fileName = (*ErrorHandler::GetFileName()).GetBuffer();
+		int lineNumber = ErrorHandler::GetLineNumber();
+		QualifiedString * thisLabel = new QualifiedString((yyvsp[(1) - (1)].Value), new String(fileName), lineNumber);
+		// store the label in the UsedIdentifiers array for checking
+		// whether label was declared
+		pG->UsedIdentifiers.Add(thisLabel);
+
+	    if (pG->EnumValues.IsStored((yyvsp[(1) - (1)].Value)))
+			{
+			sprintf((yyval.Value), "%d", (int)(pG->EnumValues.FindId((yyvsp[(1) - (1)].Value))));
+			}
+		else if (pG->RlsNameIndex.count((yyvsp[(1) - (1)].Value))) // if rls item has already been defined
+			{
+			// Found a reference to an rls_string.
+			RlsValue &rv = pG->RlsValues[pG->RlsNameIndex[(yyvsp[(1) - (1)].Value)]];
+			++rv.iCitationCount; // iCitationCount counts the number of times this rls value has been referneced
+			// Warn for multiple uses if 'multi' keyword not used.
+			if (1 < rv.iCitationCount && rv.iCardinality == ERlsCardinalitySingle)
+				{
+				Message * message = pG->Messages.GetEntry(LT_001);
+				String fileLine = *(rv.iFileName);
+				if(message->GetActivated())
+				{
+					pGL->AddWarningToStore(fileLine, rv.iLineNumber, message->GetMessageOutput());
+				}
+				REGISTER_LINE;
+				if (!pG->WarningMultiExplained)
+					{
+					Message * message = pG->Messages.GetEntry(LT_002);
+					fileLine = String(*(pFileLineHandler->GetCurrentFile()));
+					if(message->GetActivated())
+						{
+						pGL->AddWarningToStore(fileLine, pFileLineHandler->GetErrorLine(* pCurrentLineNumber), message->GetMessageOutput());
+						pG->WarningMultiExplained = true;
+						}
+					}
+				}
+			switch (rv.iType)
+				{
+				// Strings and numbers are just copied to the next layer up.
+			case ERlsString:
+			case ERlsString8:
+			case ERlsByte:
+			case ERlsWord:
+			case ERlsLong:
+			case ERlsDouble:
+				strcpy((yyval.Value), rv.iValue.GetBuffer());
+				break;
+				// Anything else is a character: this is converted to a number.
+			case ERlsStringChar:
+			case ERlsByteChar:
+			case ERlsWordChar:
+			case ERlsLongChar:
+				SetCharacterLiteral((yyval.Value), rv.iValue);
+				break;
+			default:
+				Message * message = pG->Messages.GetEntry(LT_031);
+				if(message->GetActivated())
+					{
+					ErrorHandler::OutputErrorLine(message->GetMessageOutput());
+					exit(1);
+					}
+				break;
+				}
+			}
+		else
+			{
+			/*
+			Could be a reference to another resource, perhaps even a forward reference:
+			the OverwriteLink functions do FindId again when writing out the data.
+			Sadly this also permits things which are really syntax errors, inadvertently
+			converting labels into string literals..
+			*/
+			}
+	    ;}
+    break;
+
+  case 113:
+
+/* Line 1455 of yacc.c  */
+#line 749 "rcomp.yacc"
+    {	
+	    REGISTER_LINE;
+	    if((yyvsp[(2) - (3)].NumInitialiser) < 0 || ((yyvsp[(2) - (3)].NumInitialiser) > 255 && TargetCharacterSet != String::Unicode))
+		{
+		    ErrorHandler::OutputErrorLine("Character code must be a number in the range 0 to 255.");
+		    exit(1);
+		}
+	    if (TargetCharacterSet != String::Unicode)
+		{
+		* (yyval.Value) = char((yyvsp[(2) - (3)].NumInitialiser)); * ((yyval.Value) + 1) = '\0'; 
+		} 
+	    else
+		{
+		if (SourceCharacterSet == String::CP1252)
+		    {
+		    if ( ((yyvsp[(2) - (3)].NumInitialiser) >= 0x80) && ((yyvsp[(2) - (3)].NumInitialiser) <= 0x9F ) ) // 80-9F are illegal Unicode values.
+			{
+			ErrorHandler::OutputErrorLine("Warning: Deprecated non-unicode value in source stream");
+			}
+		    * (yyval.Value) = char(UnicodeEscape);
+		    asUTF8((yyval.Value) + 1, (yyvsp[(2) - (3)].NumInitialiser));
+		    }
+		else
+		if (SourceCharacterSet == String::UTF8)
+		    {
+		    asUTF8((yyval.Value), (yyvsp[(2) - (3)].NumInitialiser));
+		    }
+		else
+		    {
+		    // Unsatisfactory, but do people use other character sets?
+		    if ((yyvsp[(2) - (3)].NumInitialiser) > 255)
+			{
+			ErrorHandler::OutputErrorLine("Don't know how to handle character > 255");
+			}
+		    * (yyval.Value) = char((yyvsp[(2) - (3)].NumInitialiser)); * ((yyval.Value) + 1) = '\0'; 
+		    }
+		}
+	    ;}
+    break;
+
+  case 114:
+
+/* Line 1455 of yacc.c  */
+#line 795 "rcomp.yacc"
+    {
+	    REGISTER_LINE;
+	    SetIdFromName((yyvsp[(2) - (2)].Value));
+	    ;}
+    break;
+
+  case 115:
+
+/* Line 1455 of yacc.c  */
+#line 800 "rcomp.yacc"
+    {
+	    REGISTER_LINE;
+	    SetIdFromName((yyvsp[(2) - (2)].Value));
+	    ;}
+    break;
+
+  case 116:
+
+/* Line 1455 of yacc.c  */
+#line 812 "rcomp.yacc"
+    {
+		REGISTER_LINE;
+		if ((yyvsp[(2) - (2)].NumInitialiser) == 0)
+			{ ErrorHandler::OutputErrorLine("UID2 must be non-zero"); exit(1); }
+		if (Uid2 != 0)
+			{ ErrorHandler::OutputErrorLine("Warning: overwriting previous UID2 value"); }
+		Uid2=(yyvsp[(2) - (2)].NumInitialiser);
+		if(verbose) 
+			{ MOFF;cout << "uidX_statement  UID2                       " << Uid2 << endl;MON;}
+		;}
+    break;
+
+  case 117:
+
+/* Line 1455 of yacc.c  */
+#line 823 "rcomp.yacc"
+    {
+		REGISTER_LINE;
+		if ((yyvsp[(2) - (2)].NumInitialiser) == 0)
+			{ ErrorHandler::OutputErrorLine("UID3 must be non-zero"); exit(1); }
+		if (Uid3 != 0)
+			{ ErrorHandler::OutputErrorLine("Warning: overwriting previous UID3 value"); }
+		Uid3=(yyvsp[(2) - (2)].NumInitialiser);
+		if(verbose) 
+			{ MOFF;cout << "uidX_statement  UID3                       " << Uid3 << endl;MON;}
+		;}
+    break;
+
+  case 118:
+
+/* Line 1455 of yacc.c  */
+#line 844 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "character_set_statement                    " << (yyvsp[(2) - (2)].Value) << endl;MON;}
+											REGISTER_LINE;
+											SourceCharacterSet = CharacterSetID((yyvsp[(2) - (2)].Value));
+											if ( SourceCharacterSet == String::UNKNOWN )
+											{
+												String err = "Warning: Unrecognised character set name '";
+												err += (yyvsp[(2) - (2)].Value);
+												err += "'";
+												ErrorHandler::OutputErrorLine(err);
+											}
+											if ( SourceCharacterSet == String::Unicode )
+											{
+											    SourceCharacterSet = String::UNKNOWN;
+												ErrorHandler::OutputErrorLine("Unicode source is unsupported");
+											}
+										;}
+    break;
+
+  case 119:
+
+/* Line 1455 of yacc.c  */
+#line 868 "rcomp.yacc"
+    {	if(verbose) {	RCTypeArray Types;
+															MOFF;cout << "offset_statement                           " << (yyvsp[(2) - (2)].Value) << endl;MON; }
+											REGISTER_LINE;
+										 	CurrentId=((long) NumericValue((yyvsp[(2) - (2)].Value), L_LONG).GetULong() );
+										;}
+    break;
+
+  case 120:
+
+/* Line 1455 of yacc.c  */
+#line 879 "rcomp.yacc"
+    {	if(verbose) {	MOFF;cout << "system_statement" << endl;MON;}
+											CurrentIdStep=-1;
+										;}
+    break;
+
+  case 123:
+
+/* Line 1455 of yacc.c  */
+#line 893 "rcomp.yacc"
+    {	
+	    if(verbose) 
+		{ MOFF;cout << "enum_statement" << endl;MON;} 
+	    CurrentEnumName = (yyvsp[(2) - (3)].Value);
+	    CurrentEnumValue=0;
+	    ;}
+    break;
+
+  case 124:
+
+/* Line 1455 of yacc.c  */
+#line 900 "rcomp.yacc"
+    {	
+	    if(verbose) 
+		{ MOFF;cout << "enum_statement" << endl;MON;} 
+	    CurrentEnumName = "";
+	    CurrentEnumValue=0;
+	    ;}
+    break;
+
+  case 125:
+
+/* Line 1455 of yacc.c  */
+#line 910 "rcomp.yacc"
+    {	
+		pG->EnumValues.Add((yyvsp[(1) - (1)].Value), CurrentEnumValue++);
+		pG->AllIdentifiers.Add(new String((yyvsp[(1) - (1)].Value))); // Add label to store
+		;}
+    break;
+
+  case 126:
+
+/* Line 1455 of yacc.c  */
+#line 915 "rcomp.yacc"
+    {	
+	    CurrentEnumValue = atol((yyvsp[(3) - (3)].Value));
+	    pG->EnumValues.Add((yyvsp[(1) - (3)].Value), CurrentEnumValue);
+	    CurrentEnumValue++;			// Increment so that next field has value ($3+1)
+		pG->AllIdentifiers.Add(new String((yyvsp[(1) - (3)].Value))); // Add label to store
+	    ;}
+    break;
+
+  case 129:
+
+/* Line 1455 of yacc.c  */
+#line 934 "rcomp.yacc"
+    {
+		pG->RlsNameIndex[(yyvsp[(3) - (4)].Value)] = pG->RlsValues.size();
+		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
+			ErrorHandler::GetLineNumber(), (yyvsp[(4) - (4)].Value), (yyvsp[(1) - (4)].RlsType),
+			(yyvsp[(2) - (4)].RlsQualifiers).iCardinality, (yyvsp[(2) - (4)].RlsQualifiers).iMaxLength));
+		if((yyvsp[(2) - (4)].RlsQualifiers).iMaxLength
+			< String((yyvsp[(4) - (4)].Value)).ExportLength(TargetCharacterSet,SourceCharacterSet))
+			{
+			Message * message = pG->Messages.GetEntry(LT_032);
+			if(message->GetActivated())
+				{
+				ErrorHandler::OutputErrorLine(message->GetMessageOutput());
+				exit(1);
+				}
+			}
+		;}
+    break;
+
+  case 130:
+
+/* Line 1455 of yacc.c  */
+#line 951 "rcomp.yacc"
+    {
+		Message * message = pG->Messages.GetEntry(LT_033);
+		String fileName = *(pFileLineHandler->GetCurrentFile());
+		int lineNumber = pFileLineHandler->GetErrorLine(* pCurrentLineNumber);
+		if(message->GetActivated())
+			{
+			pGL->AddWarningToStore(fileName, lineNumber, message->GetMessageOutput());
+			}
+		//...
+		/* Produce a warning "rls_string used for character constant: use rls_long, rls_word or rls_byte" */
+		pG->RlsNameIndex[(yyvsp[(3) - (4)].Value)] = pG->RlsValues.size();
+		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
+			ErrorHandler::GetLineNumber(), (yyvsp[(4) - (4)].Value), ERlsStringChar,
+			(yyvsp[(2) - (4)].RlsQualifiers).iCardinality));
+		;}
+    break;
+
+  case 131:
+
+/* Line 1455 of yacc.c  */
+#line 967 "rcomp.yacc"
+    {
+		pG->RlsNameIndex[(yyvsp[(3) - (4)].Value)] = pG->RlsValues.size();
+		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
+			ErrorHandler::GetLineNumber(), (yyvsp[(4) - (4)].Value), (yyvsp[(1) - (4)].RlsType),
+			(yyvsp[(2) - (4)].RlsQualifiers).iCardinality));
+		;}
+    break;
+
+  case 132:
+
+/* Line 1455 of yacc.c  */
+#line 974 "rcomp.yacc"
+    {
+		pG->RlsNameIndex[(yyvsp[(3) - (4)].Value)] = pG->RlsValues.size();
+		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
+			ErrorHandler::GetLineNumber(), (yyvsp[(4) - (4)].Value), (yyvsp[(1) - (4)].RlsType),
+			(yyvsp[(2) - (4)].RlsQualifiers).iCardinality));
+		;}
+    break;
+
+  case 133:
+
+/* Line 1455 of yacc.c  */
+#line 981 "rcomp.yacc"
+    {
+		TRlsType rlsCharType = (yyvsp[(1) - (4)].RlsType) == ERlsByte? ERlsByteChar
+			: ( (yyvsp[(1) - (4)].RlsType) ==  ERlsWord? ERlsWordChar : ERlsLongChar );
+		pG->RlsNameIndex[(yyvsp[(3) - (4)].Value)] = pG->RlsValues.size();
+		pG->RlsValues.push_back(RlsValue(ErrorHandler::GetFileName(),
+			ErrorHandler::GetLineNumber(), (yyvsp[(4) - (4)].Value), rlsCharType,
+			(yyvsp[(2) - (4)].RlsQualifiers).iCardinality));
+		;}
+    break;
+
+  case 134:
+
+/* Line 1455 of yacc.c  */
+#line 992 "rcomp.yacc"
+    {
+		// Register line even if no warning here so that
+		// the rls_ item knows which line the label was on.
+		// Without this, the line registered would be the
+		// line following the declaration.
+		REGISTER_LINE;
+		strcpy((yyval.Value), (yyvsp[(1) - (1)].Value));
+
+		if (pG->RlsNameIndex.count((yyvsp[(1) - (1)].Value)) != 0)
+			{
+			Message * message = pG->Messages.GetEntry(LT_003);
+			if(message->GetActivated())
+				{
+				ErrorHandler::OutputErrorLine(message->GetMessageOutput());
+				}
+			}
+		pG->AllIdentifiers.Add(new String((yyvsp[(1) - (1)].Value))); // Add label to store
+		;}
+    break;
+
+  case 135:
+
+/* Line 1455 of yacc.c  */
+#line 1013 "rcomp.yacc"
+    {
+		NumericValue v((yyvsp[(2) - (4)].Value), L_LONG);
+		(yyval.RlsQualifiers).iMaxLength = v.GetULong();
+		(yyval.RlsQualifiers).iCardinality = (yyvsp[(4) - (4)].RlsQualifiers).iCardinality;
+		;}
+    break;
+
+  case 136:
+
+/* Line 1455 of yacc.c  */
+#line 1019 "rcomp.yacc"
+    { (yyval.RlsQualifiers) = (yyvsp[(1) - (1)].RlsQualifiers); ;}
+    break;
+
+  case 137:
+
+/* Line 1455 of yacc.c  */
+#line 1024 "rcomp.yacc"
+    {
+		(yyval.RlsQualifiers).iMaxLength = 0xFFFFFFF;
+		(yyval.RlsQualifiers).iCardinality = ERlsCardinalityMultiple;
+		;}
+    break;
+
+  case 138:
+
+/* Line 1455 of yacc.c  */
+#line 1029 "rcomp.yacc"
+    {
+		(yyval.RlsQualifiers).iMaxLength = 0xFFFFFFF;
+		(yyval.RlsQualifiers).iCardinality = ERlsCardinalitySingle;
+		;}
+    break;
+
+  case 139:
+
+/* Line 1455 of yacc.c  */
+#line 1037 "rcomp.yacc"
+    { (yyval.RlsType) = ERlsString; ;}
+    break;
+
+  case 140:
+
+/* Line 1455 of yacc.c  */
+#line 1039 "rcomp.yacc"
+    { (yyval.RlsType) = ERlsString8; ;}
+    break;
+
+  case 141:
+
+/* Line 1455 of yacc.c  */
+#line 1044 "rcomp.yacc"
+    { (yyval.RlsType) = ERlsByte; ;}
+    break;
+
+  case 142:
+
+/* Line 1455 of yacc.c  */
+#line 1046 "rcomp.yacc"
+    { (yyval.RlsType) = ERlsWord; ;}
+    break;
+
+  case 143:
+
+/* Line 1455 of yacc.c  */
+#line 1048 "rcomp.yacc"
+    { (yyval.RlsType) = ERlsLong; ;}
+    break;
+
+  case 144:
+
+/* Line 1455 of yacc.c  */
+#line 1053 "rcomp.yacc"
+    { (yyval.RlsType) = ERlsDouble; ;}
+    break;
+
+  case 147:
+
+/* Line 1455 of yacc.c  */
+#line 1065 "rcomp.yacc"
+    {ErrorHandler::Register(pFileLineHandler->GetCurrentFile(), pFileLineHandler->GetErrorLine(*pCurrentLineNumber)); ;}
+    break;
+
+  case 150:
+
+/* Line 1455 of yacc.c  */
+#line 1075 "rcomp.yacc"
+    { pGL->StoreComment((yyvsp[(1) - (1)].Value));	;}
+    break;
+
+  case 151:
+
+/* Line 1455 of yacc.c  */
+#line 1076 "rcomp.yacc"
+    { pGL->StoreComment((yyvsp[(1) - (1)].Value));	;}
+    break;
+
+  case 152:
+
+/* Line 1455 of yacc.c  */
+#line 1077 "rcomp.yacc"
+    { pGL->StoreComment((yyvsp[(1) - (1)].Value));	;}
+    break;
+
+
+
+/* Line 1455 of yacc.c  */
+#line 3037 "rcomp.tab.cacc"
+      default: break;
+    }
+  YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
+
+  YYPOPSTACK (yylen);
+  yylen = 0;
+  YY_STACK_PRINT (yyss, yyssp);
+
+  *++yyvsp = yyval;
+
+  /* Now `shift' the result of the reduction.  Determine what state
+     that goes to, based on the state we popped back to and the rule
+     number reduced by.  */
+
+  yyn = yyr1[yyn];
+
+  yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
+  if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
+    yystate = yytable[yystate];
+  else
+    yystate = yydefgoto[yyn - YYNTOKENS];
+
+  goto yynewstate;
+
+
+/*------------------------------------.
+| yyerrlab -- here on detecting error |
+`------------------------------------*/
+yyerrlab:
+  /* If not already recovering from an error, report this error.  */
+  if (!yyerrstatus)
+    {
+      ++yynerrs;
+#if ! YYERROR_VERBOSE
+      yyerror (YY_("syntax error"));
+#else
+      {
+	YYSIZE_T yysize = yysyntax_error (0, yystate, yychar);
+	if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM)
+	  {
+	    YYSIZE_T yyalloc = 2 * yysize;
+	    if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM))
+	      yyalloc = YYSTACK_ALLOC_MAXIMUM;
+	    if (yymsg != yymsgbuf)
+	      YYSTACK_FREE (yymsg);
+	    yymsg = (char *) YYSTACK_ALLOC (yyalloc);
+	    if (yymsg)
+	      yymsg_alloc = yyalloc;
+	    else
+	      {
+		yymsg = yymsgbuf;
+		yymsg_alloc = sizeof yymsgbuf;
+	      }
+	  }
+
+	if (0 < yysize && yysize <= yymsg_alloc)
+	  {
+	    (void) yysyntax_error (yymsg, yystate, yychar);
+	    yyerror (yymsg);
+	  }
+	else
+	  {
+	    yyerror (YY_("syntax error"));
+	    if (yysize != 0)
+	      goto yyexhaustedlab;
+	  }
+      }
+#endif
+    }
+
+
+
+  if (yyerrstatus == 3)
+    {
+      /* If just tried and failed to reuse lookahead token after an
+	 error, discard it.  */
+
+      if (yychar <= YYEOF)
+	{
+	  /* Return failure if at end of input.  */
+	  if (yychar == YYEOF)
+	    YYABORT;
+	}
+      else
+	{
+	  yydestruct ("Error: discarding",
+		      yytoken, &yylval);
+	  yychar = YYEMPTY;
+	}
+    }
+
+  /* Else will try to reuse lookahead token after shifting the error
+     token.  */
+  goto yyerrlab1;
+
+
+/*---------------------------------------------------.
+| yyerrorlab -- error raised explicitly by YYERROR.  |
+`---------------------------------------------------*/
+yyerrorlab:
+
+  /* Pacify compilers like GCC when the user code never invokes
+     YYERROR and the label yyerrorlab therefore never appears in user
+     code.  */
+  if (/*CONSTCOND*/ 0)
+     goto yyerrorlab;
+
+  /* Do not reclaim the symbols of the rule which action triggered
+     this YYERROR.  */
+  YYPOPSTACK (yylen);
+  yylen = 0;
+  YY_STACK_PRINT (yyss, yyssp);
+  yystate = *yyssp;
+  goto yyerrlab1;
+
+
+/*-------------------------------------------------------------.
+| yyerrlab1 -- common code for both syntax error and YYERROR.  |
+`-------------------------------------------------------------*/
+yyerrlab1:
+  yyerrstatus = 3;	/* Each real token shifted decrements this.  */
+
+  for (;;)
+    {
+      yyn = yypact[yystate];
+      if (yyn != YYPACT_NINF)
+	{
+	  yyn += YYTERROR;
+	  if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
+	    {
+	      yyn = yytable[yyn];
+	      if (0 < yyn)
+		break;
+	    }
+	}
+
+      /* Pop the current state because it cannot handle the error token.  */
+      if (yyssp == yyss)
+	YYABORT;
+
+
+      yydestruct ("Error: popping",
+		  yystos[yystate], yyvsp);
+      YYPOPSTACK (1);
+      yystate = *yyssp;
+      YY_STACK_PRINT (yyss, yyssp);
+    }
+
+  *++yyvsp = yylval;
+
+
+  /* Shift the error token.  */
+  YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
+
+  yystate = yyn;
+  goto yynewstate;
+
+
+/*-------------------------------------.
+| yyacceptlab -- YYACCEPT comes here.  |
+`-------------------------------------*/
+yyacceptlab:
+  yyresult = 0;
+  goto yyreturn;
+
+/*-----------------------------------.
+| yyabortlab -- YYABORT comes here.  |
+`-----------------------------------*/
+yyabortlab:
+  yyresult = 1;
+  goto yyreturn;
+
+#if !defined(yyoverflow) || YYERROR_VERBOSE
+/*-------------------------------------------------.
+| yyexhaustedlab -- memory exhaustion comes here.  |
+`-------------------------------------------------*/
+yyexhaustedlab:
+  yyerror (YY_("memory exhausted"));
+  yyresult = 2;
+  /* Fall through.  */
+#endif
+
+yyreturn:
+  if (yychar != YYEMPTY)
+     yydestruct ("Cleanup: discarding lookahead",
+		 yytoken, &yylval);
+  /* Do not reclaim the symbols of the rule which action triggered
+     this YYABORT or YYACCEPT.  */
+  YYPOPSTACK (yylen);
+  YY_STACK_PRINT (yyss, yyssp);
+  while (yyssp != yyss)
+    {
+      yydestruct ("Cleanup: popping",
+		  yystos[*yyssp], yyvsp);
+      YYPOPSTACK (1);
+    }
+#ifndef yyoverflow
+  if (yyss != yyssa)
+    YYSTACK_FREE (yyss);
+#endif
+#if YYERROR_VERBOSE
+  if (yymsg != yymsgbuf)
+    YYSTACK_FREE (yymsg);
+#endif
+  /* Make sure YYID is used.  */
+  return YYID (yyresult);
+}
+
+
+
+/* Line 1675 of yacc.c  */
+#line 1080 "rcomp.yacc"
+
+
+// Function section
+// ================
+
+void asUTF8(char* aUtf8, int aUnicode)
+	{
+	if ( aUnicode > 0xffff )
+		{
+		if ( aUnicode > 0x10ffff )
+		{
+		ErrorHandler::OutputErrorLine("Surrogate character code must be a number in the range 0x10000 to 0x10ffff");
+		exit(1);		
+		}
+		
+		UTF16 high = (UTF16)(0xD7C0 + (aUnicode >> 10));			// high surrogate
+		UTF16 low = (UTF16)(0xDC00 | (aUnicode & 0x3FF));			// low surrogate
+	
+		*aUtf8++ =(char)(0xe0|(high>>12));
+		*aUtf8++ =(char)(0x80|((high>>6)&0x3f));
+		*aUtf8++ =(char)(0x80|(high&0x3f));
+		*aUtf8++ =(char)(0xe0|(low>>12));
+		*aUtf8++ =(char)(0x80|((low>>6)&0x3f));
+		*aUtf8   =(char)(0x80|(low&0x3f));
+		}
+	else if ((aUnicode & 0xff80) == 0x0000)
+		{
+		*aUtf8 = (char)aUnicode;
+		}
+	else if ((aUnicode & 0xf800) == 0x0000)
+		{
+		*aUtf8++ =(char)(0xc0|(aUnicode>>6));
+		*aUtf8   =(char)(0x80|(aUnicode&0x3f));
+		}
+	else
+		{
+		*aUtf8++ =(char)(0xe0|(aUnicode>>12));
+		*aUtf8++ =(char)(0x80|((aUnicode>>6)&0x3f));
+		*aUtf8   =(char)(0x80|(aUnicode&0x3f));
+		}
+	*++aUtf8 = '\0';
+	}
+
+
+String::CharacterSet CharacterSetID( const String & character_set_name )
+// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+// Return a character set ID from a character set name.  The value UNKNOWN
+// is returned if the name is not recognised.
+// ----------------------------------------------------------------------------
+{
+	String::CharacterSet ids[] = { String::ISOLatin1, String::ASCII, String::CP1252
+	                              , String::CP850, String::ShiftJIS, String::Unicode
+								  , String::UTF8
+								  , String::UNKNOWN
+								 };
+	String names[] = { "ISOLATIN1", "ASCII", "CP1252", "CP850", "SHIFTJIS", "UNICODE", "UTF8" };
+
+	for ( int i=0; ids[i]!=String::UNKNOWN; i++ )
+	{
+		if ( names[i] == character_set_name ) return ids[i];
+	}
+
+	return String::UNKNOWN;
+
+} // end of CharacterSetID code
+
+void SetIdFromName( const String & NameStatementValue)
+	{
+	// space 	0
+	// A		1
+	// B		2
+	// ...
+	// Z		26
+	//
+	// ABCD corresponds to the number 4321 which becomes ( (4*27 + 3) * 27 + 2) * 27 + 1.
+	
+	if(verbose) 
+		{ MOFF;cout << "name_statement                             " << NameStatementValue << endl;MON;}
+	if ( NameStatementValue.Length() > 4)
+		{
+		ErrorHandler::OutputErrorLine( "Name must be no longer than four characters");
+		exit( 1);
+		}
+	
+	long NewId = 0;
+	
+	for( unsigned long i = 0; i < NameStatementValue.Length(); i++)
+		{
+		NewId *= 27;
+		if ( isalpha( NameStatementValue[i]) )
+			NewId += toupper( NameStatementValue[i]) - 'A' + 1;
+		}
+
+	CurrentId = NewId << 12;
+	FormatIdAsHex = 1;
+	if(verbose) 
+		{ MOFF;cout << "Current id                                " << CurrentId << endl;MON;}
+	}
+
+void RlsUnusedWarnings()
+	{
+	TNameIndex::iterator end = pG->RlsNameIndex.end();
+	for (TNameIndex::iterator i = pG->RlsNameIndex.begin(); i != end; ++i)
+		{
+		int index = i->second;
+		RlsValue& v = pG->RlsValues[index];
+		if (v.iCitationCount == 0)
+			{
+			Message * message = pG->Messages.GetEntry(LT_004);
+			String fileLine = *(v.iFileName);
+			if(message->GetActivated())
+				{
+				pGL->AddWarningToStore(fileLine, v.iLineNumber, message->GetMessageOutput());
+				}
+			}
+		}
+	}
+
+int ParseSourceFile(FILE* aFile, unsigned short aYYDebug)
+	{
+	// Set up various global pointers which refer to the pG structure
+	pSHA = & (pG->SHA);
+	pFileLineHandler = & (pG->FileLineHandler);
+	pResourceNameIds = & (pG->ResourceNameIds);
+
+	pScan = new rcscan(pG->FileLineHandler, aFile);
+
+	yydebug = aYYDebug;
+	pCurrentLineNumber = &yylineno;
+	int ReturnValue = yyparse();
+
+	RlsUnusedWarnings();
+
+	int bScanErrorFound = pScan->ErrorWasFound();
+
+	delete pScan;
+	pScan = NULL;
+
+	if(ReturnValue != 0)
+		return ReturnValue;
+	
+	if(bScanErrorFound)
+		return 1;
+	
+	return 0;	// successful parse - parse tree now in the pG data structure
+	}
+
+
+void CheckStructUsage()
+	{
+	ResourceItemArrayIterator	nextRI( *pCurrentRIA);
+	ResourceItem * pRI;
+	while ( ( pRI = nextRI() ) != NULL)
+		{
+		int resourceItemType = pRI->GetResourceItemType();
+		String resourceItemLabel = pRI->GetLabel();
+		if( (resourceItemType == EStructTypeResourceItem) || (resourceItemType == EStructArrayResourceItem) )
+			{
+			StringArrayIterator nextLabel( *pUsedLabelsArray);
+			String * pLabel;
+			bool flag = false;
+			while ( ( ( pLabel = nextLabel() ) != NULL ) && (! flag) )
+				{
+				StringLess stringCompare;
+				if( !stringCompare(resourceItemLabel,*pLabel) && !stringCompare(*pLabel,resourceItemLabel) )
+					{
+					flag = true;
+					}
+				}
+			if(! flag)
+				{
+				if(resourceItemType == EStructTypeResourceItem)
+					{
+					Message * message = pG->Messages.GetEntry(LT_046);
+					if(message->GetActivated())
+						{
+						String comment = message->GetMessageOutput();
+						comment += "'";
+						comment += resourceItemLabel;
+						comment += "'";
+						ErrorHandler::OutputErrorLine(comment);
+						}
+					}
+				else
+					{
+					Message * message = pG->Messages.GetEntry(LT_047);
+					if(message->GetActivated())
+						{
+						String comment = message->GetMessageOutput();
+						comment += "'";
+						comment += resourceItemLabel;
+						comment += "'";
+						ErrorHandler::OutputErrorLine(comment);
+						}
+					}
+				}
+			}
+		}
+	}
+
+int yywrap()
+{
+  return 1;
+}
+
+/* Called by yyparse on error */
+#include <stdarg.h>
+void yyerror (const char *s, ...)
+{
+  va_list list;
+  va_start(list, s);
+  pScan->yyerror(const_cast<char*>(s), list);
+  va_end(list);
+}
+
+
+
--- a/bintools/rcomp/src/rcompl.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/bintools/rcomp/src/rcompl.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,2390 +1,2376 @@
-/*
-* Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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 lexical scanner generated by flex.
-* Scanner skeleton version:
-* $Header: /home/daffy/u0/vern/flex/RCS/flex.skl,v 2.91 96/09/10 16:58:48 vern Exp $
-*
-*/
-
-
-#define FLEX_SCANNER
-#define YY_FLEX_MAJOR_VERSION 2
-#define YY_FLEX_MINOR_VERSION 5
-
-#include <stdio.h>
-
-
-/* cfront 1.2 defines "c_plusplus" instead of "__cplusplus" */
-#ifdef c_plusplus
-#ifndef __cplusplus
-#define __cplusplus
-#endif
-#endif
-
-
-#ifdef __cplusplus
-
-#include <stdlib.h>
-#include <unistd.h>
-
-/* Use prototypes in function declarations. */
-#define YY_USE_PROTOS
-
-/* The "const" storage-class-modifier is valid. */
-#define YY_USE_CONST
-
-#else	/* ! __cplusplus */
-
-#if __STDC__
-
-#define YY_USE_PROTOS
-#define YY_USE_CONST
-
-#endif	/* __STDC__ */
-#endif	/* ! __cplusplus */
-
-#ifdef __TURBOC__
- #pragma warn -rch
- #pragma warn -use
-#include <io.h>
-#include <stdlib.h>
-#define YY_USE_CONST
-#define YY_USE_PROTOS
-#endif
-
-#ifdef YY_USE_CONST
-#define yyconst const
-#else
-#define yyconst
-#endif
-
-
-#ifdef YY_USE_PROTOS
-#define YY_PROTO(proto) proto
-#else
-#define YY_PROTO(proto) ()
-#endif
-
-/* Returned upon end-of-file. */
-#define YY_NULL 0
-
-/* Promotes a possibly negative, possibly signed char to an unsigned
- * integer for use as an array index.  If the signed char is negative,
- * we want to instead treat it as an 8-bit unsigned char, hence the
- * double cast.
- */
-#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
-
-/* Enter a start condition.  This macro really ought to take a parameter,
- * but we do it the disgusting crufty way forced on us by the ()-less
- * definition of BEGIN.
- */
-#define BEGIN yy_start = 1 + 2 *
-
-/* Translate the current start state into a value that can be later handed
- * to BEGIN to return to the state.  The YYSTATE alias is for lex
- * compatibility.
- */
-#define YY_START ((yy_start - 1) / 2)
-#define YYSTATE YY_START
-
-/* Action number for EOF rule of a given start state. */
-#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
-
-/* Special action meaning "start processing a new file". */
-#define YY_NEW_FILE yyrestart( yyin )
-
-#define YY_END_OF_BUFFER_CHAR 0
-
-/* Size of default input buffer. */
-#define YY_BUF_SIZE 16384
-
-typedef struct yy_buffer_state *YY_BUFFER_STATE;
-
-extern int yyleng;
-extern FILE *yyin, *yyout;
-
-#define EOB_ACT_CONTINUE_SCAN 0
-#define EOB_ACT_END_OF_FILE 1
-#define EOB_ACT_LAST_MATCH 2
-
-/* The funky do-while in the following #define is used to turn the definition
- * int a single C statement (which needs a semi-colon terminator).  This
- * avoids problems with code like:
- *
- * 	if ( condition_holds )
- *		yyless( 5 );
- *	else
- *		do_something_else();
- *
- * Prior to using the do-while the compiler would get upset at the
- * "else" because it interpreted the "if" statement as being all
- * done when it reached the ';' after the yyless() call.
- */
-
-/* Return all but the first 'n' matched characters back to the input stream. */
-
-#define yyless(n) \
-	do \
-		{ \
-		/* Undo effects of setting up yytext. */ \
-		*yy_cp = yy_hold_char; \
-		YY_RESTORE_YY_MORE_OFFSET \
-		yy_c_buf_p = yy_cp = yy_bp + n - YY_MORE_ADJ; \
-		YY_DO_BEFORE_ACTION; /* set up yytext again */ \
-		} \
-	while ( 0 )
-
-#define unput(c) yyunput( c, yytext_ptr )
-
-/* The following is because we cannot portably get our hands on size_t
- * (without autoconf's help, which isn't available because we want
- * flex-generated scanners to compile on their own).
- */
-typedef unsigned int yy_size_t;
-
-
-struct yy_buffer_state
-	{
-	FILE *yy_input_file;
-
-	char *yy_ch_buf;		/* input buffer */
-	char *yy_buf_pos;		/* current position in input buffer */
-
-	/* Size of input buffer in bytes, not including room for EOB
-	 * characters.
-	 */
-	yy_size_t yy_buf_size;
-
-	/* Number of characters read into yy_ch_buf, not including EOB
-	 * characters.
-	 */
-	int yy_n_chars;
-
-	/* Whether we "own" the buffer - i.e., we know we created it,
-	 * and can realloc() it to grow it, and should free() it to
-	 * delete it.
-	 */
-	int yy_is_our_buffer;
-
-	/* Whether this is an "interactive" input source; if so, and
-	 * if we're using stdio for input, then we want to use getc()
-	 * instead of fread(), to make sure we stop fetching input after
-	 * each newline.
-	 */
-	int yy_is_interactive;
-
-	/* Whether we're considered to be at the beginning of a line.
-	 * If so, '^' rules will be active on the next match, otherwise
-	 * not.
-	 */
-	int yy_at_bol;
-
-	/* Whether to try to fill the input buffer when we reach the
-	 * end of it.
-	 */
-	int yy_fill_buffer;
-
-	int yy_buffer_status;
-#define YY_BUFFER_NEW 0
-#define YY_BUFFER_NORMAL 1
-	/* When an EOF's been seen but there's still some text to process
-	 * then we mark the buffer as YY_EOF_PENDING, to indicate that we
-	 * shouldn't try reading from the input source any more.  We might
-	 * still have a bunch of tokens to match, though, because of
-	 * possible backing-up.
-	 *
-	 * When we actually see the EOF, we change the status to "new"
-	 * (via yyrestart()), so that the user can continue scanning by
-	 * just pointing yyin at a new input file.
-	 */
-#define YY_BUFFER_EOF_PENDING 2
-	};
-
-static YY_BUFFER_STATE yy_current_buffer = 0;
-
-/* We provide macros for accessing buffer states in case in the
- * future we want to put the buffer states in a more general
- * "scanner state".
- */
-#define YY_CURRENT_BUFFER yy_current_buffer
-
-
-/* yy_hold_char holds the character lost when yytext is formed. */
-static char yy_hold_char;
-
-static int yy_n_chars;		/* number of characters read into yy_ch_buf */
-
-
-int yyleng;
-
-/* Points to current character in buffer. */
-static char *yy_c_buf_p = (char *) 0;
-static int yy_init = 1;		/* whether we need to initialize */
-static int yy_start = 0;	/* start state number */
-
-/* Flag which is used to allow yywrap()'s to do buffer switches
- * instead of setting up a fresh yyin.  A bit of a hack ...
- */
-static int yy_did_buffer_switch_on_eof;
-
-void yyrestart YY_PROTO(( FILE *input_file ));
-
-void yy_switch_to_buffer YY_PROTO(( YY_BUFFER_STATE new_buffer ));
-void yy_load_buffer_state YY_PROTO(( void ));
-YY_BUFFER_STATE yy_create_buffer YY_PROTO(( FILE *file, int size ));
-void yy_delete_buffer YY_PROTO(( YY_BUFFER_STATE b ));
-void yy_init_buffer YY_PROTO(( YY_BUFFER_STATE b, FILE *file ));
-void yy_flush_buffer YY_PROTO(( YY_BUFFER_STATE b ));
-#define YY_FLUSH_BUFFER yy_flush_buffer( yy_current_buffer )
-
-YY_BUFFER_STATE yy_scan_buffer YY_PROTO(( char *base, yy_size_t size ));
-YY_BUFFER_STATE yy_scan_string YY_PROTO(( yyconst char *yy_str ));
-YY_BUFFER_STATE yy_scan_bytes YY_PROTO(( yyconst char *bytes, int len ));
-
-static void *yy_flex_alloc YY_PROTO(( yy_size_t ));
-static void *yy_flex_realloc YY_PROTO(( void *, yy_size_t ));
-static void yy_flex_free YY_PROTO(( void * ));
-
-#define yy_new_buffer yy_create_buffer
-
-#define yy_set_interactive(is_interactive) \
-	{ \
-	if ( ! yy_current_buffer ) \
-		yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \
-	yy_current_buffer->yy_is_interactive = is_interactive; \
-	}
-
-#define yy_set_bol(at_bol) \
-	{ \
-	if ( ! yy_current_buffer ) \
-		yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \
-	yy_current_buffer->yy_at_bol = at_bol; \
-	}
-
-#define YY_AT_BOL() (yy_current_buffer->yy_at_bol)
-
-
-#define YY_USES_REJECT
-typedef unsigned char YY_CHAR;
-FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0;
-typedef int yy_state_type;
-extern int yylineno;
-int yylineno = 1;
-extern char *yytext;
-#define yytext_ptr yytext
-
-static yy_state_type yy_get_previous_state YY_PROTO(( void ));
-static yy_state_type yy_try_NUL_trans YY_PROTO(( yy_state_type current_state ));
-static int yy_get_next_buffer YY_PROTO(( void ));
-static void yy_fatal_error YY_PROTO(( yyconst char msg[] ));
-
-/* Done after the current pattern has been matched and before the
- * corresponding action - sets up yytext.
- */
-#define YY_DO_BEFORE_ACTION \
-	yytext_ptr = yy_bp; \
-	yyleng = (int) (yy_cp - yy_bp); \
-	yy_hold_char = *yy_cp; \
-	*yy_cp = '\0'; \
-	yy_c_buf_p = yy_cp;
-
-#define YY_NUM_RULES 81
-#define YY_END_OF_BUFFER 82
-static yyconst short int yy_acclist[363] =
-    {   0,
-       82,   80,   81,   62,   80,   81,   63,   81,   63,   80,
-       81,   37,   80,   81,   80,   81,   38,   80,   81,   79,
-       80,   81,   79,   80,   81,   79,   80,   81,   49,   80,
-       81,   49,   80,   81,   48,   80,   81,   48,   80,   81,
-       48,   80,   81,   48,   80,   81,   48,   80,   81,   48,
-       80,   81,   48,   80,   81,   48,   80,   81,   48,   80,
-       81,   48,   80,   81,   48,   80,   81,   48,   80,   81,
-       48,   80,   81,   48,   80,   81,   48,   80,   81,   48,
-       80,   81,   48,   80,   81,   47,   80,   81,   44,   81,
-       47,   80,   81,   45,   47,   80,   81,   46,   47,   80,
-
-       81,   47,   80,   81,   80,   81,   62,   80,   81,   64,
-       81,   64,   80,   81,   80,   81,   80,   81,   67,   80,
-       81,   66,   81,   66,   67,   80,   81,   72,   80,   81,
-       71,   81,   71,   72,   80,   81,   72,   80,   81,   76,
-       80,   81,   78,   80,   81,   77,   81,   77,   80,   81,
-       78,   80,   81,   80,   81,   65,   49,   48,   48,   48,
-       48,   48,   48,   48,   48,   48,   48,   48,   48,   48,
-       48,   48,   48,   48,   48,   48,   48,   48,   48,   48,
-       48,   44,   43,   39,   40,   42,   41,   58,   59,   65,
-       70,   76,   74,   75,   68,   69,   68,   69,   73,   53,
-
-       55,   50,   20,   48,   48,   48,   48,   48,   48,   36,
-       48,   48,   48,   48,   48,   48,   48,   48,   48,   48,
-       48,   48,   48,   48,   48,   48,   48,   48,   59,   68,
-       69,   68,   69,   68,   73,   54,   56,   48,   21,   48,
-       24,   48,   48,   48,    9,   48,   48,   33,   48,   48,
-       48,   25,   48,   48,    3,   48,   48,   48,   48,   48,
-       48,   27,   48,   11,   48,   12,   48,   23,   48,   10,
-       48,   48,   48,   60,   61,   57,   51,   22,   48,   48,
-       48,   48,   34,   48,    8,   48,   28,   48,   48,   48,
-       48,   48,   48,   48,   29,   48,   19,   48,   48,   48,
-
-       48,   48,   48,   52,   48,   26,   48,    7,   48,   48,
-       30,   48,    5,   48,   48,   35,   48,    1,   48,    6,
-       48,   31,   48,   48,   48,   48,   48,   48,   48,   32,
-       48,   48,   48,   48,   48,   48,   48,   48,    2,   48,
-       16,   48,   48,   18,   48,   48,   17,   48,   48,   48,
-       48,   48,   15,   48,   13,   48,   48,   14,   48,   48,
-        4,   48
-    } ;
-
-static yyconst short int yy_accept[270] =
-    {   0,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    2,    4,    7,    9,   12,   15,   17,
-       20,   23,   26,   29,   32,   35,   38,   41,   44,   47,
-       50,   53,   56,   59,   62,   65,   68,   71,   74,   77,
-       80,   83,   86,   89,   91,   94,   98,  102,  105,  107,
-      110,  112,  115,  117,  119,  122,  124,  128,  131,  133,
-      137,  140,  143,  146,  148,  151,  154,  156,  156,  156,
-      156,  156,  156,  157,  157,  158,  158,  158,  159,  160,
-      161,  162,  163,  164,  165,  166,  167,  168,  169,  170,
-      171,  172,  173,  174,  175,  176,  177,  178,  179,  180,
-
-      181,  182,  183,  184,  185,  186,  187,  188,  188,  188,
-      188,  188,  190,  190,  190,  190,  191,  192,  193,  194,
-      195,  195,  195,  195,  195,  196,  197,  199,  200,  201,
-      202,  203,  205,  206,  207,  208,  209,  210,  212,  213,
-      214,  215,  216,  217,  218,  219,  220,  221,  222,  223,
-      224,  225,  226,  227,  228,  229,  230,  230,  230,  230,
-      230,  231,  232,  234,  235,  236,  236,  237,  238,  238,
-      239,  241,  243,  244,  245,  247,  248,  250,  251,  252,
-      254,  255,  257,  258,  259,  260,  261,  262,  264,  266,
-      268,  270,  272,  273,  274,  275,  275,  275,  276,  276,
-
-      276,  277,  277,  278,  280,  281,  282,  283,  285,  287,
-      289,  290,  291,  292,  293,  294,  295,  297,  299,  300,
-      301,  302,  303,  304,  304,  304,  305,  306,  308,  310,
-      311,  313,  315,  316,  318,  320,  322,  324,  325,  326,
-      327,  328,  329,  330,  332,  333,  334,  335,  336,  337,
-      338,  339,  341,  343,  344,  346,  347,  349,  350,  351,
-      352,  353,  355,  357,  358,  360,  361,  363,  363
-    } ;
-
-static yyconst int yy_ec[256] =
-    {   0,
-        1,    1,    1,    1,    1,    1,    1,    1,    2,    3,
-        1,    1,    4,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    5,    1,    6,    7,    1,    1,    8,    9,   10,
-       10,   11,   10,   10,   12,   13,   14,   15,   16,   17,
-       18,   19,   19,   20,   19,   21,   19,    1,   10,   10,
-       10,   10,    1,   22,   23,   24,   25,   26,   27,   28,
-       29,   30,   31,   32,   33,   34,   35,   36,   37,   32,
-       32,   38,   39,   40,   41,   32,   42,   43,   44,   32,
-       10,   45,   10,    1,   46,    1,   47,   48,   47,   49,
-
-       50,   51,   52,   53,   54,   53,   53,   55,   56,   57,
-       58,   53,   53,   59,   60,   61,   62,   63,   64,   65,
-       66,   53,   10,   10,   10,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1
-    } ;
-
-static yyconst int yy_meta[67] =
-    {   0,
-        1,    2,    3,    2,    2,    4,    1,    1,    4,    1,
-        2,    1,    5,    1,    6,    6,    6,    6,    6,    6,
-        6,    1,    7,    7,    7,    7,    6,    7,    8,    8,
-        8,    8,    8,    8,    8,    8,    8,    8,    8,    8,
-        8,    8,    8,    8,    4,    8,    7,    9,    7,    6,
-        9,    8,    8,    8,    8,    8,   10,    8,   10,    8,
-       10,    8,   10,    8,   11,    8
-    } ;
-
-static yyconst short int yy_base[284] =
-    {   0,
-        0,    0,   64,   68,   76,   81,   72,   85,   88,   90,
-      100,  112,  566,  567,  105,  567,  567,  567,  560,  567,
-      567,  109,   86,   85,   93,    0,   77,  534,  526,  526,
-      527,  105,  537,  531,  531,   93,  530,  525,  518,  497,
-      491,  497,  567,  567,  548,  567,  567,  135,  544,  146,
-      543,  542,  150,  150,  567,  567,  567,  567,  567,  567,
-      533,    0,  567,  567,  567,  532,    0,  157,  534,  157,
-      136,  162,  567,  172,    0,  179,    0,    0,  516,  503,
-      519,  500,  499,  502,  502,  501,  505,  121,  508,  499,
-      505,  493,  497,  492,  490,  485,  501,  488,  463,  469,
-
-      463,  567,  567,  567,  567,  567,  567,  516,  164,  199,
-      173,  567,  518,  165,  203,  514,  567,    0,  567,    0,
-      511,  203,  210,  217,  567,  567,  567,  567,  224,  237,
-        0,  194,  491,  479,  492,  480,  490,    0,  480,  476,
-      488,  481,  466,  481,  468,  469,  474,  463,  463,  462,
-      185,  475,  444,  438,  452,  567,  494,  177,  243,  256,
-      490,  489,  488,  259,  487,  486,  250,  263,  270,  471,
-        0,    0,  467,  455,    0,  465,    0,  454,  452,    0,
-      445,    0,  457,  442,  446,  456,  453,  196,    0,    0,
-        0,    0,  425,  244,  567,  475,  459,  567,  473,  457,
-
-      567,  294,  301,    0,  449,  446,  438,    0,    0,  280,
-      431,  432,  436,  428,  432,  434,    0,    0,  364,  371,
-      361,  357,  345,  246,  269,  308,  362,    0,    0,  381,
-        0,    0,  375,    0,    0,    0,    0,  329,  327,  331,
-      328,  248,  279,    0,  278,  253,  254,  246,  243,  246,
-      256,    0,    0,  221,    0,  218,    0,  170,  164,   95,
-      101,    0,   87,   69,    0,   29,    0,  567,  329,  340,
-      351,  362,  373,  380,  386,  395,  405,  416,  427,  434,
-      440,  446,  455
-    } ;
-
-static yyconst short int yy_def[284] =
-    {   0,
-      268,    1,  269,  269,  270,  270,  271,  271,  272,  272,
-      273,  273,  268,  268,  268,  268,  268,  268,  268,  268,
-      268,  268,  268,  274,  274,  275,  275,  275,  275,  275,
-      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
-      275,  275,  268,  268,  268,  268,  268,  276,  277,  277,
-      277,  277,  268,  277,  268,  268,  268,  268,  268,  268,
-      268,  278,  268,  268,  268,  268,  279,  268,  268,  268,
-      280,  281,  268,  268,   25,  268,  282,  275,  275,  275,
-      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
-      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
-
-      275,  268,  268,  268,  268,  268,  268,  277,  268,  277,
-      277,  268,  268,  268,  283,  277,  268,  278,  268,  279,
-      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
-      282,  275,  275,  275,  275,  275,  275,  275,  275,  275,
-      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
-      275,  275,  275,  275,  275,  268,  268,  277,  268,  268,
-      277,  277,  277,  268,  277,  268,  268,  268,  268,  275,
-      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
-      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
-      275,  275,  275,  275,  268,  268,  268,  268,  268,  268,
-
-      268,  268,  268,  275,  275,  275,  275,  275,  275,  275,
-      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
-      275,  275,  275,  268,  268,  268,  275,  275,  275,  275,
-      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
-      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
-      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
-      275,  275,  275,  275,  275,  275,  275,    0,  268,  268,
-      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
-      268,  268,  268
-    } ;
-
-static yyconst short int yy_nxt[634] =
-    {   0,
-       14,   15,   16,   17,   15,   18,   19,   14,   20,   21,
-       21,   22,   21,   23,   24,   25,   25,   25,   25,   25,
-       25,   14,   26,   27,   28,   29,   30,   26,   31,   26,
-       26,   26,   26,   32,   26,   33,   34,   35,   36,   37,
-       38,   39,   26,   26,   14,   26,   26,   26,   26,   40,
-       26,   26,   26,   26,   26,   41,   26,   26,   42,   26,
-       26,   26,   26,   26,   26,   26,   44,   45,  267,   46,
-       44,   45,   47,   46,   56,   57,   47,   50,   51,   52,
-       50,   53,   50,   51,   52,   50,   53,   56,   57,   54,
-       59,   60,   59,   60,   54,  266,   72,   74,   61,   73,
-
-       61,   63,   64,   65,   63,   74,   68,  265,   48,   68,
-       66,   76,   48,   63,   64,   65,   63,   79,   69,   76,
-       80,   67,   66,   71,   71,   71,   71,   71,   71,   71,
-       93,   85,   94,   67,   76,   86,   95,  103,   87,  264,
-      104,   88,   76,  105,   89,  141,  263,  110,  123,   77,
-      110,  109,  112,  113,  114,  109,  142,  268,   68,  111,
-      115,   68,  124,  116,  126,  127,  156,  157,  114,  128,
-       69,  122,  122,  122,  122,  122,  122,  122,  109,  106,
-      159,  160,  109,  158,  165,  124,  129,  129,  129,  129,
-      129,  129,  129,  130,  130,  130,  130,  130,  130,  130,
-
-      110,  189,  190,  110,  109,  162,  163,  166,  164,  170,
-      165,  216,  111,  262,  171,  261,  217,  122,  122,  122,
-      122,  122,  122,  122,  167,  167,  167,  167,  167,  167,
-      167,  168,  168,  168,  168,  168,  168,  168,  129,  129,
-      129,  129,  129,  129,  129,  195,  196,  197,  195,  196,
-      169,  130,  130,  130,  130,  130,  130,  130,  198,  199,
-      200,  156,  157,  114,  167,  167,  167,  167,  167,  167,
-      167,  198,  199,  169,  260,  259,  202,  168,  168,  168,
-      168,  168,  168,  168,  203,  203,  203,  203,  203,  203,
-      203,  219,  220,  258,  257,  230,  256,  255,  221,  202,
-
-      231,  254,  253,  222,  252,  251,  250,  223,  226,  226,
-      226,  226,  226,  226,  226,  203,  203,  203,  203,  203,
-      203,  203,  226,  226,  226,  226,  226,  226,  226,   43,
-       43,   43,   43,   43,   43,   43,   43,   43,   43,   43,
-       49,   49,   49,   49,   49,   49,   49,   49,   49,   49,
-       49,   55,   55,   55,   55,   55,   55,   55,   55,   55,
-       55,   55,   58,   58,   58,   58,   58,   58,   58,   58,
-       58,   58,   58,   62,   62,   62,   62,   62,   62,   62,
-       62,   62,   62,   62,   75,   75,  249,  248,  247,  246,
-       75,   78,   78,   78,   78,   78,   78,  107,  107,  245,
-
-      244,  243,  242,  107,  107,  108,  108,  108,  108,  108,
-      108,  108,  108,  108,  108,  108,  118,  241,  240,  118,
-      118,  118,  118,  118,  118,  118,  118,  120,  239,  238,
-      120,  120,  120,  120,  120,  120,  120,  120,   71,   71,
-      125,  125,  125,  125,  125,  125,  125,  125,  125,  125,
-      125,  131,  131,  237,  131,  161,  161,  161,  161,  161,
-      161,  161,  161,  161,  161,  161,  236,  235,  234,  233,
-      232,  229,  228,  227,  225,  198,  224,  195,  218,  215,
-      214,  213,  212,  211,  210,  209,  208,  207,  206,  205,
-      204,  201,  109,  109,  109,  109,  156,  194,  193,  192,
-
-      191,  188,  187,  186,  185,  184,  183,  182,  181,  180,
-      179,  178,  177,  176,  175,  174,  173,  172,  128,  109,
-      112,  109,  155,  154,  153,  152,  151,  150,  149,  148,
-      147,  146,  145,  144,  143,  140,  139,  138,  137,  136,
-      135,  134,  133,  132,  121,  119,  117,  109,  109,  109,
-      102,  101,  100,   99,   98,   97,   96,   92,   91,   90,
-       84,   83,   82,   81,   70,  268,   13,  268,  268,  268,
-      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
-      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
-      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
-
-      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
-      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
-      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
-      268,  268,  268
-    } ;
-
-static yyconst short int yy_chk[634] =
-    {   0,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    3,    3,  266,    3,
-        4,    4,    3,    4,    7,    7,    4,    5,    5,    5,
-        5,    5,    6,    6,    6,    6,    6,    8,    8,    5,
-        9,    9,   10,   10,    6,  264,   23,   24,    9,   23,
-
-       10,   11,   11,   11,   11,   25,   15,  263,    3,   15,
-       11,   24,    4,   12,   12,   12,   12,   27,   15,   25,
-       27,   11,   12,   22,   22,   22,   22,   22,   22,   22,
-       36,   32,   36,   12,   24,   32,   36,   48,   32,  261,
-       48,   32,   25,   48,   32,   88,  260,   50,   71,   24,
-       50,   50,   53,   53,   53,   54,   88,   25,   68,   50,
-       54,   68,   71,   54,   72,   72,  109,  109,  109,   72,
-       68,   70,   70,   70,   70,   70,   70,   70,  111,   48,
-      114,  114,  158,  111,  158,   71,   74,   74,   74,   74,
-       74,   74,   74,   76,   76,   76,   76,   76,   76,   76,
-
-      110,  151,  151,  110,  110,  115,  115,  122,  115,  132,
-      115,  188,  110,  259,  132,  258,  188,  122,  122,  122,
-      122,  122,  122,  122,  123,  123,  123,  123,  123,  123,
-      123,  124,  124,  124,  124,  124,  124,  124,  129,  129,
-      129,  129,  129,  129,  129,  159,  159,  159,  224,  224,
-      129,  130,  130,  130,  130,  130,  130,  130,  160,  160,
-      160,  164,  164,  164,  167,  167,  167,  167,  167,  167,
-      167,  225,  225,  129,  256,  254,  167,  168,  168,  168,
-      168,  168,  168,  168,  169,  169,  169,  169,  169,  169,
-      169,  194,  194,  251,  250,  210,  249,  248,  194,  167,
-
-      210,  247,  246,  194,  245,  243,  242,  194,  202,  202,
-      202,  202,  202,  202,  202,  203,  203,  203,  203,  203,
-      203,  203,  226,  226,  226,  226,  226,  226,  226,  269,
-      269,  269,  269,  269,  269,  269,  269,  269,  269,  269,
-      270,  270,  270,  270,  270,  270,  270,  270,  270,  270,
-      270,  271,  271,  271,  271,  271,  271,  271,  271,  271,
-      271,  271,  272,  272,  272,  272,  272,  272,  272,  272,
-      272,  272,  272,  273,  273,  273,  273,  273,  273,  273,
-      273,  273,  273,  273,  274,  274,  241,  240,  239,  238,
-      274,  275,  275,  275,  275,  275,  275,  276,  276,  233,
-
-      230,  227,  223,  276,  276,  277,  277,  277,  277,  277,
-      277,  277,  277,  277,  277,  277,  278,  222,  221,  278,
-      278,  278,  278,  278,  278,  278,  278,  279,  220,  219,
-      279,  279,  279,  279,  279,  279,  279,  279,  280,  280,
-      281,  281,  281,  281,  281,  281,  281,  281,  281,  281,
-      281,  282,  282,  216,  282,  283,  283,  283,  283,  283,
-      283,  283,  283,  283,  283,  283,  215,  214,  213,  212,
-      211,  207,  206,  205,  200,  199,  197,  196,  193,  187,
-      186,  185,  184,  183,  181,  179,  178,  176,  174,  173,
-      170,  166,  165,  163,  162,  161,  157,  155,  154,  153,
-
-      152,  150,  149,  148,  147,  146,  145,  144,  143,  142,
-      141,  140,  139,  137,  136,  135,  134,  133,  121,  116,
-      113,  108,  101,  100,   99,   98,   97,   96,   95,   94,
-       93,   92,   91,   90,   89,   87,   86,   85,   84,   83,
-       82,   81,   80,   79,   69,   66,   61,   52,   51,   49,
-       45,   42,   41,   40,   39,   38,   37,   35,   34,   33,
-       31,   30,   29,   28,   19,   13,  268,  268,  268,  268,
-      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
-      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
-      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
-
-      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
-      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
-      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
-      268,  268,  268
-    } ;
-
-static yy_state_type yy_state_buf[YY_BUF_SIZE + 2], *yy_state_ptr;
-static char *yy_full_match;
-static int yy_lp;
-#define REJECT \
-{ \
-*yy_cp = yy_hold_char; /* undo effects of setting up yytext */ \
-yy_cp = yy_full_match; /* restore poss. backed-over text */ \
-++yy_lp; \
-goto find_rule; \
-}
-#define yymore() yymore_used_but_not_detected
-#define YY_MORE_ADJ 0
-#define YY_RESTORE_YY_MORE_OFFSET
-char *yytext;
-#line 1 "RCOMP.LEX"
-#define INITIAL 0
-#line 3 "RCOMP.LEX"
-
-#include <limits.h>
-#include <string.h>
-#include "main.h"
-#include "structst.h"
-#include "parser.h"
-#include "localise.h"
-
-#define YY_SKIP_YYWRAP 1
-#define YY_NEVER_INTERACTIVE 1
-int yywrap();
-void yyerror(const char* string, ...);
-
-// Redefine YY_INPUT so we can parse binary data.
-#undef YY_INPUT
-#define YY_INPUT(buf, result, max_size) (result = new_yy_input(buf, max_size))
-
-int new_yy_input(char *buf, int max_size)
-{
-   int result;
-   result = fread(buf, 1, max_size, yyin);
-   if (result == 0)
-      return YY_NULL;
-   
-   // check for utf8 (BOM) header in buf
-   for (int i = 0; i < result-3; i++)
-   {
-      if (buf[i] == 0xffffffef && buf[i+1] == 0xffffffbb && buf[i+2] == 0xffffffbf)
-      {
-		buf[i] = ' ';
-		buf[i+1] = ' ';
-		buf[i+2] = ' ';
-      }
-   }
-   return result;
-}
-
-#include "rcomp.hpp"
-#include "fileline.h"
-
-#define VALUE_LEN   (1024*8)	// must match sizeof(YYSTYPE.Value)
-char buf[VALUE_LEN];
-char * pCh;
-#define CHECK_APPEND(x)	\
-    if (pCh-buf==VALUE_LEN-1) { yyerror("string too long - %c ignored", (x)); } else {*pCh++ = (x); }
-
-int isCharLiteral;
-
-extern String		InputBaseName;
-extern FileLineManager* pFileLineHandler;
-extern int*		pCurrentLineNumber;
-char RealLineNumber[200];
-//
-// Disable MSVC warnings
-//
-#ifdef __VC32__
-#if 0
-..\src\RCOMP.L(95) : warning C4127: conditional expression is constant
-..\src\RCOMP.L(114) : warning C4244: 'initializing' : conversion from 'const int' to 'YY_CHAR', possible loss of data
-..\src\RCOMP.L(119) : warning C4244: '=' : conversion from 'const int' to 'YY_CHAR', possible loss of data
-..\src\RCOMP.L(130) : warning C4102: 'find_rule' : unreferenced label
-..\src\RCOMP.L(513) : warning C4244: 'initializing' : conversion from 'int' to 'YY_CHAR', possible loss of data
-..\src\RCOMP.L(518) : warning C4244: '=' : conversion from 'const int' to 'YY_CHAR', possible loss of data
-..\src\RCOMP.L(548) : warning C4244: '=' : conversion from 'const int' to 'YY_CHAR', possible loss of data
-..\src\RCOMP.L(63) : warning C4505: 'yyunput' : unreferenced local function has been removed
-\epoc32\BUILD\generatedcpp\rcomp\rcompl.cpp(243) : warning C4505: 'yy_flex_realloc' : unreferenced local function has been removed
-#endif
-
-#pragma warning( disable : 4100 )
-#pragma warning( disable : 4102 )
-#pragma warning( disable : 4127 )
-#pragma warning( disable : 4244 )
-#pragma warning( disable : 4245 )
-#pragma warning( disable : 4505 )
-#endif //__VC32__
-
-#include "errorhan.h"
-
-#define REGISTER_LINE	ErrorHandler::Register(pFileLineHandler->GetCurrentFile(), pFileLineHandler->GetErrorLine(* pCurrentLineNumber))
-
-
-#define string_rules 1
-
-/* Rule set for string literals.			        */
-/* n.b. Exclusive rule sets i.e. %x are available in MKS only	*/
-/* so they are not used here; hence all the <INITIAL>'s.        */
-#define file_line_rules 2
-
-/* Rule set for file_line_directive.*/
-#define cpp_comment 3
-
-/* C++ comment to end of line */
-#define c_comment 4
-
-/* C comment */
-#define comment_tag 5
-
-/* Doxygen-style comment tag */
-#line 761 "lex.yy.c"
-
-/* Macros after this point can all be overridden by user definitions in
- * section 1.
- */
-
-#ifndef YY_SKIP_YYWRAP
-#ifdef __cplusplus
-extern "C" int yywrap YY_PROTO(( void ));
-#else
-extern int yywrap YY_PROTO(( void ));
-#endif
-#endif
-
-#ifndef YY_NO_UNPUT
-static void yyunput YY_PROTO(( int c, char *buf_ptr ));
-#endif
-
-#ifndef yytext_ptr
-static void yy_flex_strncpy YY_PROTO(( char *, yyconst char *, int ));
-#endif
-
-#ifdef YY_NEED_STRLEN
-static int yy_flex_strlen YY_PROTO(( yyconst char * ));
-#endif
-
-#ifndef YY_NO_INPUT
-#ifdef __cplusplus
-static int yyinput YY_PROTO(( void ));
-#else
-static int input YY_PROTO(( void ));
-#endif
-#endif
-
-#if YY_STACK_USED
-static int yy_start_stack_ptr = 0;
-static int yy_start_stack_depth = 0;
-static int *yy_start_stack = 0;
-#ifndef YY_NO_PUSH_STATE
-static void yy_push_state YY_PROTO(( int new_state ));
-#endif
-#ifndef YY_NO_POP_STATE
-static void yy_pop_state YY_PROTO(( void ));
-#endif
-#ifndef YY_NO_TOP_STATE
-static int yy_top_state YY_PROTO(( void ));
-#endif
-
-#else
-#define YY_NO_PUSH_STATE 1
-#define YY_NO_POP_STATE 1
-#define YY_NO_TOP_STATE 1
-#endif
-
-#ifdef YY_MALLOC_DECL
-YY_MALLOC_DECL
-#else
-#if __STDC__
-#ifndef __cplusplus
-#include <stdlib.h>
-#endif
-#else
-/* Just try to get by without declaring the routines.  This will fail
- * miserably on non-ANSI systems for which sizeof(size_t) != sizeof(int)
- * or sizeof(void*) != sizeof(int).
- */
-#endif
-#endif
-
-/* Amount of stuff to slurp up with each read. */
-#ifndef YY_READ_BUF_SIZE
-#define YY_READ_BUF_SIZE 8192
-#endif
-
-/* Copy whatever the last rule matched to the standard output. */
-
-#ifndef ECHO
-/* This used to be an fputs(), but since the string might contain NUL's,
- * we now use fwrite().
- */
-#define ECHO (void) fwrite( yytext, yyleng, 1, yyout )
-#endif
-
-/* Gets input and stuffs it into "buf".  number of characters read, or YY_NULL,
- * is returned in "result".
- */
-#ifndef YY_INPUT
-#define YY_INPUT(buf,result,max_size) \
-	if ( yy_current_buffer->yy_is_interactive ) \
-		{ \
-		int c = '*', n; \
-		for ( n = 0; n < max_size && \
-			     (c = getc( yyin )) != EOF && c != '\n'; ++n ) \
-			buf[n] = (char) c; \
-		if ( c == '\n' ) \
-			buf[n++] = (char) c; \
-		if ( c == EOF && ferror( yyin ) ) \
-			YY_FATAL_ERROR( "input in flex scanner failed" ); \
-		result = n; \
-		} \
-	else if ( ((result = fread( buf, 1, max_size, yyin )) == 0) \
-		  && ferror( yyin ) ) \
-		YY_FATAL_ERROR( "input in flex scanner failed" );
-#endif
-
-/* No semi-colon after return; correct usage is to write "yyterminate();" -
- * we don't want an extra ';' after the "return" because that will cause
- * some compilers to complain about unreachable statements.
- */
-#ifndef yyterminate
-#define yyterminate() return YY_NULL
-#endif
-
-/* Number of entries by which start-condition stack grows. */
-#ifndef YY_START_STACK_INCR
-#define YY_START_STACK_INCR 25
-#endif
-
-/* Report a fatal error. */
-#ifndef YY_FATAL_ERROR
-#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
-#endif
-
-/* Default declaration of generated scanner - a define so the user can
- * easily add parameters.
- */
-#ifndef YY_DECL
-#define YY_DECL int yylex YY_PROTO(( void ))
-#endif
-
-/* Code executed at the beginning of each rule, after yytext and yyleng
- * have been set up.
- */
-#ifndef YY_USER_ACTION
-#define YY_USER_ACTION
-#endif
-
-/* Code executed at the end of each rule. */
-#ifndef YY_BREAK
-#define YY_BREAK break;
-#endif
-
-#define YY_RULE_SETUP \
-	YY_USER_ACTION
-
-YY_DECL
-	{
-	register yy_state_type yy_current_state;
-	register char *yy_cp, *yy_bp;
-	register int yy_act;
-
-#line 130 "RCOMP.LEX"
-
-
-
-	/* Translations section */
-	/* ==================== */
-
-	/*******************************************/
-	/* Main keywords                           */
-	/*******************************************/
-#line 922 "lex.yy.c"
-
-	if ( yy_init )
-		{
-		yy_init = 0;
-
-#ifdef YY_USER_INIT
-		YY_USER_INIT;
-#endif
-
-		if ( ! yy_start )
-			yy_start = 1;	/* first start state */
-
-		if ( ! yyin )
-			yyin = stdin;
-
-		if ( ! yyout )
-			yyout = stdout;
-
-		if ( ! yy_current_buffer )
-			yy_current_buffer =
-				yy_create_buffer( yyin, YY_BUF_SIZE );
-
-		yy_load_buffer_state();
-		}
-
-	while ( 1 )		/* loops until end-of-file is reached */
-		{
-		yy_cp = yy_c_buf_p;
-
-		/* Support of yytext. */
-		*yy_cp = yy_hold_char;
-
-		/* yy_bp points to the position in yy_ch_buf of the start of
-		 * the current run.
-		 */
-		yy_bp = yy_cp;
-
-		yy_current_state = yy_start;
-		yy_state_ptr = yy_state_buf;
-		*yy_state_ptr++ = yy_current_state;
-yy_match:
-		do
-			{
-			register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
-			while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
-				{
-				yy_current_state = (int) yy_def[yy_current_state];
-				if ( yy_current_state >= 269 )
-					yy_c = yy_meta[(unsigned int) yy_c];
-				}
-			yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-			*yy_state_ptr++ = yy_current_state;
-			++yy_cp;
-			}
-		while ( yy_base[yy_current_state] != 567 );
-
-yy_find_action:
-		yy_current_state = *--yy_state_ptr;
-		yy_lp = yy_accept[yy_current_state];
-find_rule: /* we branch to this label when backing up */
-		for ( ; ; ) /* until we find what rule we matched */
-			{
-			if ( yy_lp && yy_lp < yy_accept[yy_current_state + 1] )
-				{
-				yy_act = yy_acclist[yy_lp];
-					{
-					yy_full_match = yy_cp;
-					break;
-					}
-				}
-			--yy_cp;
-			yy_current_state = *--yy_state_ptr;
-			yy_lp = yy_accept[yy_current_state];
-			}
-
-		YY_DO_BEFORE_ACTION;
-
-		if ( yy_act != YY_END_OF_BUFFER )
-			{
-			int yyl;
-			for ( yyl = 0; yyl < yyleng; ++yyl )
-				if ( yytext[yyl] == '\n' )
-					++yylineno;
-			}
-
-do_action:	/* This label is used only to access EOF actions. */
-
-
-		switch ( yy_act )
-	{ /* beginning of action switch */
-case 1:
-YY_RULE_SETUP
-#line 139 "RCOMP.LEX"
-return L_STRUCT;
-	YY_BREAK
-case 2:
-YY_RULE_SETUP
-#line 140 "RCOMP.LEX"
-return L_RESOURCE;
-	YY_BREAK
-case 3:
-YY_RULE_SETUP
-#line 141 "RCOMP.LEX"
-return L_NAME;
-	YY_BREAK
-case 4:
-YY_RULE_SETUP
-#line 142 "RCOMP.LEX"
-return L_CHARACTER_SET;
-	YY_BREAK
-case 5:
-YY_RULE_SETUP
-#line 143 "RCOMP.LEX"
-return L_OFFSET;
-	YY_BREAK
-case 6:
-YY_RULE_SETUP
-#line 144 "RCOMP.LEX"
-return L_SYSTEM;
-	YY_BREAK
-case 7:
-YY_RULE_SETUP
-#line 145 "RCOMP.LEX"
-return L_GLOBAL;
-	YY_BREAK
-case 8:
-YY_RULE_SETUP
-#line 146 "RCOMP.LEX"
-return L_LOCAL;
-	YY_BREAK
-case 9:
-YY_RULE_SETUP
-#line 147 "RCOMP.LEX"
-return L_ENUM;
-	YY_BREAK
-case 10:
-YY_RULE_SETUP
-#line 148 "RCOMP.LEX"
-return L_ENUM;
-	YY_BREAK
-case 11:
-YY_RULE_SETUP
-#line 149 "RCOMP.LEX"
-return L_UID_TWO;
-	YY_BREAK
-case 12:
-YY_RULE_SETUP
-#line 150 "RCOMP.LEX"
-return L_UID_THREE;
-	YY_BREAK
-case 13:
-YY_RULE_SETUP
-#line 151 "RCOMP.LEX"
-return L_RLS_STRING;
-	YY_BREAK
-case 14:
-YY_RULE_SETUP
-#line 152 "RCOMP.LEX"
-return L_RLS_STRING8;
-	YY_BREAK
-case 15:
-YY_RULE_SETUP
-#line 153 "RCOMP.LEX"
-return L_RLS_DOUBLE;
-	YY_BREAK
-case 16:
-YY_RULE_SETUP
-#line 154 "RCOMP.LEX"
-return L_RLS_BYTE;
-	YY_BREAK
-case 17:
-YY_RULE_SETUP
-#line 155 "RCOMP.LEX"
-return L_RLS_WORD;
-	YY_BREAK
-case 18:
-YY_RULE_SETUP
-#line 156 "RCOMP.LEX"
-return L_RLS_LONG;
-	YY_BREAK
-case 19:
-YY_RULE_SETUP
-#line 157 "RCOMP.LEX"
-return L_MULTI;
-	YY_BREAK
-/*******************************************/
-/* Types                                   */
-/*******************************************/
-case 20:
-YY_RULE_SETUP
-#line 162 "RCOMP.LEX"
-return L_BUF;
-	YY_BREAK
-case 21:
-YY_RULE_SETUP
-#line 163 "RCOMP.LEX"
-return L_BUF8;
-	YY_BREAK
-case 22:
-YY_RULE_SETUP
-#line 164 "RCOMP.LEX"
-return L_BUF16;
-	YY_BREAK
-case 23:
-YY_RULE_SETUP
-#line 165 "RCOMP.LEX"
-return L_WORD;
-	YY_BREAK
-case 24:
-YY_RULE_SETUP
-#line 166 "RCOMP.LEX"
-return L_BYTE;
-	YY_BREAK
-case 25:
-YY_RULE_SETUP
-#line 167 "RCOMP.LEX"
-return L_LONG;
-	YY_BREAK
-case 26:
-YY_RULE_SETUP
-#line 168 "RCOMP.LEX"
-return L_DOUBLE;
-	YY_BREAK
-case 27:
-YY_RULE_SETUP
-#line 169 "RCOMP.LEX"
-return L_TEXT;
-	YY_BREAK
-case 28:
-YY_RULE_SETUP
-#line 170 "RCOMP.LEX"
-return L_LTEXT;
-	YY_BREAK
-case 29:
-YY_RULE_SETUP
-#line 171 "RCOMP.LEX"
-return L_TEXT8;
-	YY_BREAK
-case 30:
-YY_RULE_SETUP
-#line 172 "RCOMP.LEX"
-return L_LTEXT8;
-	YY_BREAK
-case 31:
-YY_RULE_SETUP
-#line 173 "RCOMP.LEX"
-return L_TEXT16;
-	YY_BREAK
-case 32:
-YY_RULE_SETUP
-#line 174 "RCOMP.LEX"
-return L_LTEXT16;
-	YY_BREAK
-case 33:
-YY_RULE_SETUP
-#line 175 "RCOMP.LEX"
-return L_LINK;
-	YY_BREAK
-case 34:
-YY_RULE_SETUP
-#line 176 "RCOMP.LEX"
-return L_LLINK;
-	YY_BREAK
-case 35:
-YY_RULE_SETUP
-#line 177 "RCOMP.LEX"
-return L_SRLINK;
-	YY_BREAK
-/*******************************************/
-/* Others                                  */
-/*******************************************/
-case 36:
-YY_RULE_SETUP
-#line 183 "RCOMP.LEX"
-return L_LEN;
-	YY_BREAK
-/*******************************************/
-/* String & character literals             */
-/*******************************************/
-case 37:
-YY_RULE_SETUP
-#line 189 "RCOMP.LEX"
-{ BEGIN(string_rules); pCh = buf; isCharLiteral=0; }
-	YY_BREAK
-case 38:
-YY_RULE_SETUP
-#line 190 "RCOMP.LEX"
-{ BEGIN(string_rules); pCh = buf; isCharLiteral=1; }
-	YY_BREAK
-/* Escaped single- and double-quotes.*/
-case 39:
-YY_RULE_SETUP
-#line 193 "RCOMP.LEX"
-{ CHECK_APPEND('"'); }
-	YY_BREAK
-case 40:
-YY_RULE_SETUP
-#line 194 "RCOMP.LEX"
-{ CHECK_APPEND('\''); };
-	YY_BREAK
-/* Convert escaped character into corresponding actual character e.g. \t to tab. */
-case 41:
-YY_RULE_SETUP
-#line 197 "RCOMP.LEX"
-{ CHECK_APPEND( * ( strchr("\rr\bb\ff\nn\tt\vv\aa", yytext[1])-1));}
-	YY_BREAK
-/* Escaped backslash */
-case 42:
-YY_RULE_SETUP
-#line 200 "RCOMP.LEX"
-{ CHECK_APPEND('\\'); }
-	YY_BREAK
-case 43:
-YY_RULE_SETUP
-#line 202 "RCOMP.LEX"
-/* Escaped newline ignored*/ ;
-	YY_BREAK
-/* End of line before terminating double-quotes.*/
-case 44:
-YY_RULE_SETUP
-#line 205 "RCOMP.LEX"
-{ yyerror( isCharLiteral?"Unterminated character literal":"Unterminated string"); BEGIN 0; }
-	YY_BREAK
-/* End of string reached.*/
-case 45:
-YY_RULE_SETUP
-#line 208 "RCOMP.LEX"
-{ 
-    if (!isCharLiteral) 
-	    {
-	    *pCh = '\0'; BEGIN(0); strcpy( yylval.Value, buf); 
-		return L_STRING_LITERAL; 
-	    }
-    CHECK_APPEND(*yytext);
-    }
-	YY_BREAK
-case 46:
-YY_RULE_SETUP
-#line 217 "RCOMP.LEX"
-{ 
-    if (isCharLiteral) 
-	    {
-	    *pCh = '\0'; BEGIN(0); strcpy( yylval.Value, buf); return L_CHAR_LITERAL;
-	    }
-    CHECK_APPEND(*yytext);
-    }
-	YY_BREAK
-/* Anything other than \n is stored.*/
-case 47:
-YY_RULE_SETUP
-#line 226 "RCOMP.LEX"
-{ CHECK_APPEND(*yytext); }
-	YY_BREAK
-/*******************************************/
-/* Labels                                  */
-/*******************************************/
-case 48:
-YY_RULE_SETUP
-#line 232 "RCOMP.LEX"
-{	
-    BEGIN(0);
-    strcpy( yylval.Value, yytext);
-    return L_LABEL;
-    }
-	YY_BREAK
-/*******************************************/
-/* Numbers                                 */
-/*******************************************/
-case 49:
-YY_RULE_SETUP
-#line 241 "RCOMP.LEX"
-{	strcpy( yylval.Value, yytext); return L_NUM_NATURAL; }
-	YY_BREAK
-case 50:
-YY_RULE_SETUP
-#line 242 "RCOMP.LEX"
-{	strcpy( yylval.Value, yytext); return L_NUM_NATURAL; }
-	YY_BREAK
-case 51:
-YY_RULE_SETUP
-#line 243 "RCOMP.LEX"
-{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
-	YY_BREAK
-case 52:
-YY_RULE_SETUP
-#line 244 "RCOMP.LEX"
-{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
-	YY_BREAK
-case 53:
-YY_RULE_SETUP
-#line 245 "RCOMP.LEX"
-{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
-	YY_BREAK
-case 54:
-YY_RULE_SETUP
-#line 246 "RCOMP.LEX"
-{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
-	YY_BREAK
-case 55:
-YY_RULE_SETUP
-#line 247 "RCOMP.LEX"
-{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
-	YY_BREAK
-case 56:
-YY_RULE_SETUP
-#line 248 "RCOMP.LEX"
-{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
-	YY_BREAK
-/*******************************************/
-/* file_line_directive                     */
-/*******************************************/
-case 57:
-YY_RULE_SETUP
-#line 253 "RCOMP.LEX"
-{	BEGIN(file_line_rules); strcpy( RealLineNumber, yytext+2); }
-	YY_BREAK
-case 58:
-*yy_cp = yy_hold_char; /* undo effects of setting up yytext */
-yy_c_buf_p = yy_cp -= 1;
-YY_DO_BEFORE_ACTION; /* set up yytext again */
-YY_RULE_SETUP
-#line 255 "RCOMP.LEX"
-{	BEGIN(0); // # <line> "" means start of base file.
-											pFileLineHandler->SetBase( InputBaseName, * pCurrentLineNumber);
-										}
-	YY_BREAK
-case 59:
-*yy_cp = yy_hold_char; /* undo effects of setting up yytext */
-yy_c_buf_p = yy_cp -= 1;
-YY_DO_BEFORE_ACTION; /* set up yytext again */
-YY_RULE_SETUP
-#line 259 "RCOMP.LEX"
-{	BEGIN(0); // # <line> <filename> means @ line <line> of named base file.
-											pFileLineHandler->PostInclude( yytext, RealLineNumber, * pCurrentLineNumber);
-										}
-	YY_BREAK
-case 60:
-*yy_cp = yy_hold_char; /* undo effects of setting up yytext */
-yy_c_buf_p = yy_cp -= 1;
-YY_DO_BEFORE_ACTION; /* set up yytext again */
-YY_RULE_SETUP
-#line 263 "RCOMP.LEX"
-{
-											BEGIN(0); // # <line> <filename> 1 means start of an included file.
-											pFileLineHandler->SetInclude( yytext, * pCurrentLineNumber);
-										}
-	YY_BREAK
-case 61:
-*yy_cp = yy_hold_char; /* undo effects of setting up yytext */
-yy_c_buf_p = yy_cp -= 1;
-YY_DO_BEFORE_ACTION; /* set up yytext again */
-YY_RULE_SETUP
-#line 268 "RCOMP.LEX"
-{
-											BEGIN(0); // # <line> <filename> 2 means end of an included file and now at <line> in <filename>.
-											pFileLineHandler->PostInclude( yytext, RealLineNumber, * pCurrentLineNumber);
-										}
-	YY_BREAK
-/*******************************************/
-/* White space                             */
-/*******************************************/
-case 62:
-YY_RULE_SETUP
-#line 278 "RCOMP.LEX"
-; // skipped
-	YY_BREAK
-case 63:
-YY_RULE_SETUP
-#line 279 "RCOMP.LEX"
-; // skipped
-	YY_BREAK
-case 64:
-YY_RULE_SETUP
-#line 280 "RCOMP.LEX"
-; // skipped
-	YY_BREAK
-case 65:
-YY_RULE_SETUP
-#line 281 "RCOMP.LEX"
-{ BEGIN(cpp_comment); }
-	YY_BREAK
-case 66:
-YY_RULE_SETUP
-#line 282 "RCOMP.LEX"
-{ BEGIN(0); }
-	YY_BREAK
-case 67:
-YY_RULE_SETUP
-#line 283 "RCOMP.LEX"
-;			// skipped
-	YY_BREAK
-case 68:
-*yy_cp = yy_hold_char; /* undo effects of setting up yytext */
-yy_c_buf_p = yy_cp = yy_bp + 2;
-YY_DO_BEFORE_ACTION; /* set up yytext again */
-YY_RULE_SETUP
-#line 284 "RCOMP.LEX"
-{ BEGIN(c_comment); }
-	YY_BREAK
-case 69:
-YY_RULE_SETUP
-#line 285 "RCOMP.LEX"
-{ BEGIN(c_comment); }
-	YY_BREAK
-case 70:
-YY_RULE_SETUP
-#line 286 "RCOMP.LEX"
-{ BEGIN(0); }
-	YY_BREAK
-case 71:
-YY_RULE_SETUP
-#line 287 "RCOMP.LEX"
-; // skipped
-	YY_BREAK
-case 72:
-YY_RULE_SETUP
-#line 288 "RCOMP.LEX"
-; // skipped
-	YY_BREAK
-/*******************************************/
-/* Comment tags                            */
-/*******************************************/
-case 73:
-YY_RULE_SETUP
-#line 294 "RCOMP.LEX"
-{ 
-										BEGIN(comment_tag);
-										pGL->SetStart(*(pFileLineHandler->GetCurrentFile()), pFileLineHandler->GetErrorLine(* pCurrentLineNumber));
-										return L_TAG_START; 
-										}	// any comment beginning with a slash followed by a star followed by an ampersand
-	YY_BREAK
-case 74:
-YY_RULE_SETUP
-#line 299 "RCOMP.LEX"
-{ 
-										BEGIN(0); 
-										return L_TAG_END; 
-										}
-	YY_BREAK
-case 75:
-YY_RULE_SETUP
-#line 303 "RCOMP.LEX"
-{ strcpy( yylval.Value, yytext);	return L_TAG_COMMAND; }
-	YY_BREAK
-case 76:
-YY_RULE_SETUP
-#line 304 "RCOMP.LEX"
-{ strcpy( yylval.Value, yytext);	return L_TAG_WORD; }
-	YY_BREAK
-case 77:
-YY_RULE_SETUP
-#line 305 "RCOMP.LEX"
-{ strcpy( yylval.Value, "\n");		return L_TAG_NEW_LINE; }
-	YY_BREAK
-case 78:
-YY_RULE_SETUP
-#line 306 "RCOMP.LEX"
-;
-	YY_BREAK
-/*******************************************/
-/* Special single characters               */
-/*******************************************/
-case 79:
-YY_RULE_SETUP
-#line 311 "RCOMP.LEX"
-return * yytext;
-	YY_BREAK
-/*******************************************/
-/* Everything else cannot be recognised    */
-/*******************************************/
-case 80:
-YY_RULE_SETUP
-#line 317 "RCOMP.LEX"
-{ yyerror("*** Unknown character '%c' (value 0x%x) ", *yytext, *yytext);}
-	YY_BREAK
-case 81:
-YY_RULE_SETUP
-#line 318 "RCOMP.LEX"
-ECHO;
-	YY_BREAK
-#line 1503 "lex.yy.c"
-			case YY_STATE_EOF(INITIAL):
-			case YY_STATE_EOF(string_rules):
-			case YY_STATE_EOF(file_line_rules):
-			case YY_STATE_EOF(cpp_comment):
-			case YY_STATE_EOF(c_comment):
-			case YY_STATE_EOF(comment_tag):
-				yyterminate();
-
-	case YY_END_OF_BUFFER:
-		{
-		/* Amount of text matched not including the EOB char. */
-		int yy_amount_of_matched_text = (int) (yy_cp - yytext_ptr) - 1;
-
-		/* Undo the effects of YY_DO_BEFORE_ACTION. */
-		*yy_cp = yy_hold_char;
-		YY_RESTORE_YY_MORE_OFFSET
-
-		if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_NEW )
-			{
-			/* We're scanning a new file or input source.  It's
-			 * possible that this happened because the user
-			 * just pointed yyin at a new source and called
-			 * yylex().  If so, then we have to assure
-			 * consistency between yy_current_buffer and our
-			 * globals.  Here is the right place to do so, because
-			 * this is the first action (other than possibly a
-			 * back-up) that will match for the new input source.
-			 */
-			yy_n_chars = yy_current_buffer->yy_n_chars;
-			yy_current_buffer->yy_input_file = yyin;
-			yy_current_buffer->yy_buffer_status = YY_BUFFER_NORMAL;
-			}
-
-		/* Note that here we test for yy_c_buf_p "<=" to the position
-		 * of the first EOB in the buffer, since yy_c_buf_p will
-		 * already have been incremented past the NUL character
-		 * (since all states make transitions on EOB to the
-		 * end-of-buffer state).  Contrast this with the test
-		 * in input().
-		 */
-		if ( yy_c_buf_p <= &yy_current_buffer->yy_ch_buf[yy_n_chars] )
-			{ /* This was really a NUL. */
-			yy_state_type yy_next_state;
-
-			yy_c_buf_p = yytext_ptr + yy_amount_of_matched_text;
-
-			yy_current_state = yy_get_previous_state();
-
-			/* Okay, we're now positioned to make the NUL
-			 * transition.  We couldn't have
-			 * yy_get_previous_state() go ahead and do it
-			 * for us because it doesn't know how to deal
-			 * with the possibility of jamming (and we don't
-			 * want to build jamming into it because then it
-			 * will run more slowly).
-			 */
-
-			yy_next_state = yy_try_NUL_trans( yy_current_state );
-
-			yy_bp = yytext_ptr + YY_MORE_ADJ;
-
-			if ( yy_next_state )
-				{
-				/* Consume the NUL. */
-				yy_cp = ++yy_c_buf_p;
-				yy_current_state = yy_next_state;
-				goto yy_match;
-				}
-
-			else
-				{
-				yy_cp = yy_c_buf_p;
-				goto yy_find_action;
-				}
-			}
-
-		else switch ( yy_get_next_buffer() )
-			{
-			case EOB_ACT_END_OF_FILE:
-				{
-				yy_did_buffer_switch_on_eof = 0;
-
-				if ( yywrap() )
-					{
-					/* Note: because we've taken care in
-					 * yy_get_next_buffer() to have set up
-					 * yytext, we can now set up
-					 * yy_c_buf_p so that if some total
-					 * hoser (like flex itself) wants to
-					 * call the scanner after we return the
-					 * YY_NULL, it'll still work - another
-					 * YY_NULL will get returned.
-					 */
-					yy_c_buf_p = yytext_ptr + YY_MORE_ADJ;
-
-					yy_act = YY_STATE_EOF(YY_START);
-					goto do_action;
-					}
-
-				else
-					{
-					if ( ! yy_did_buffer_switch_on_eof )
-						YY_NEW_FILE;
-					}
-				break;
-				}
-
-			case EOB_ACT_CONTINUE_SCAN:
-				yy_c_buf_p =
-					yytext_ptr + yy_amount_of_matched_text;
-
-				yy_current_state = yy_get_previous_state();
-
-				yy_cp = yy_c_buf_p;
-				yy_bp = yytext_ptr + YY_MORE_ADJ;
-				goto yy_match;
-
-			case EOB_ACT_LAST_MATCH:
-				yy_c_buf_p =
-				&yy_current_buffer->yy_ch_buf[yy_n_chars];
-
-				yy_current_state = yy_get_previous_state();
-
-				yy_cp = yy_c_buf_p;
-				yy_bp = yytext_ptr + YY_MORE_ADJ;
-				goto yy_find_action;
-			}
-		break;
-		}
-
-	default:
-		YY_FATAL_ERROR(
-			"fatal flex scanner internal error--no action found" );
-	} /* end of action switch */
-		} /* end of scanning one token */
-	} /* end of yylex */
-
-
-/* yy_get_next_buffer - try to read in a new buffer
- *
- * Returns a code representing an action:
- *	EOB_ACT_LAST_MATCH -
- *	EOB_ACT_CONTINUE_SCAN - continue scanning from current position
- *	EOB_ACT_END_OF_FILE - end of file
- */
-
-static int yy_get_next_buffer()
-	{
-	register char *dest = yy_current_buffer->yy_ch_buf;
-	register char *source = yytext_ptr;
-	register int number_to_move, i;
-	int ret_val;
-
-	if ( yy_c_buf_p > &yy_current_buffer->yy_ch_buf[yy_n_chars + 1] )
-		YY_FATAL_ERROR(
-		"fatal flex scanner internal error--end of buffer missed" );
-
-	if ( yy_current_buffer->yy_fill_buffer == 0 )
-		{ /* Don't try to fill the buffer, so this is an EOF. */
-		if ( yy_c_buf_p - yytext_ptr - YY_MORE_ADJ == 1 )
-			{
-			/* We matched a single character, the EOB, so
-			 * treat this as a final EOF.
-			 */
-			return EOB_ACT_END_OF_FILE;
-			}
-
-		else
-			{
-			/* We matched some text prior to the EOB, first
-			 * process it.
-			 */
-			return EOB_ACT_LAST_MATCH;
-			}
-		}
-
-	/* Try to read more data. */
-
-	/* First move last chars to start of buffer. */
-	number_to_move = (int) (yy_c_buf_p - yytext_ptr) - 1;
-
-	for ( i = 0; i < number_to_move; ++i )
-		*(dest++) = *(source++);
-
-	if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_EOF_PENDING )
-		/* don't do the read, it's not guaranteed to return an EOF,
-		 * just force an EOF
-		 */
-		yy_current_buffer->yy_n_chars = yy_n_chars = 0;
-
-	else
-		{
-		int num_to_read =
-			yy_current_buffer->yy_buf_size - number_to_move - 1;
-
-		while ( num_to_read <= 0 )
-			{ /* Not enough room in the buffer - grow it. */
-#ifdef YY_USES_REJECT
-			YY_FATAL_ERROR(
-"input buffer overflow, can't enlarge buffer because scanner uses REJECT" );
-#else
-
-			/* just a shorter name for the current buffer */
-			YY_BUFFER_STATE b = yy_current_buffer;
-
-			int yy_c_buf_p_offset =
-				(int) (yy_c_buf_p - b->yy_ch_buf);
-
-			if ( b->yy_is_our_buffer )
-				{
-				int new_size = b->yy_buf_size * 2;
-
-				if ( new_size <= 0 )
-					b->yy_buf_size += b->yy_buf_size / 8;
-				else
-					b->yy_buf_size *= 2;
-
-				b->yy_ch_buf = (char *)
-					/* Include room in for 2 EOB chars. */
-					yy_flex_realloc( (void *) b->yy_ch_buf,
-							 b->yy_buf_size + 2 );
-				}
-			else
-				/* Can't grow it, we don't own it. */
-				b->yy_ch_buf = 0;
-
-			if ( ! b->yy_ch_buf )
-				YY_FATAL_ERROR(
-				"fatal error - scanner input buffer overflow" );
-
-			yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset];
-
-			num_to_read = yy_current_buffer->yy_buf_size -
-						number_to_move - 1;
-#endif
-			}
-
-		if ( num_to_read > YY_READ_BUF_SIZE )
-			num_to_read = YY_READ_BUF_SIZE;
-
-		/* Read in more data. */
-		YY_INPUT( (&yy_current_buffer->yy_ch_buf[number_to_move]),
-			yy_n_chars, num_to_read );
-
-		yy_current_buffer->yy_n_chars = yy_n_chars;
-		}
-
-	if ( yy_n_chars == 0 )
-		{
-		if ( number_to_move == YY_MORE_ADJ )
-			{
-			ret_val = EOB_ACT_END_OF_FILE;
-			yyrestart( yyin );
-			}
-
-		else
-			{
-			ret_val = EOB_ACT_LAST_MATCH;
-			yy_current_buffer->yy_buffer_status =
-				YY_BUFFER_EOF_PENDING;
-			}
-		}
-
-	else
-		ret_val = EOB_ACT_CONTINUE_SCAN;
-
-	yy_n_chars += number_to_move;
-	yy_current_buffer->yy_ch_buf[yy_n_chars] = YY_END_OF_BUFFER_CHAR;
-	yy_current_buffer->yy_ch_buf[yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR;
-
-	yytext_ptr = &yy_current_buffer->yy_ch_buf[0];
-
-	return ret_val;
-	}
-
-
-/* yy_get_previous_state - get the state just before the EOB char was reached */
-
-static yy_state_type yy_get_previous_state()
-	{
-	register yy_state_type yy_current_state;
-	register char *yy_cp;
-
-	yy_current_state = yy_start;
-	yy_state_ptr = yy_state_buf;
-	*yy_state_ptr++ = yy_current_state;
-
-	for ( yy_cp = yytext_ptr + YY_MORE_ADJ; yy_cp < yy_c_buf_p; ++yy_cp )
-		{
-		register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
-		while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
-			{
-			yy_current_state = (int) yy_def[yy_current_state];
-			if ( yy_current_state >= 269 )
-				yy_c = yy_meta[(unsigned int) yy_c];
-			}
-		yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-		*yy_state_ptr++ = yy_current_state;
-		}
-
-	return yy_current_state;
-	}
-
-
-/* yy_try_NUL_trans - try to make a transition on the NUL character
- *
- * synopsis
- *	next_state = yy_try_NUL_trans( current_state );
- */
-
-#ifdef YY_USE_PROTOS
-static yy_state_type yy_try_NUL_trans( yy_state_type yy_current_state )
-#else
-static yy_state_type yy_try_NUL_trans( yy_current_state )
-yy_state_type yy_current_state;
-#endif
-	{
-	register int yy_is_jam;
-
-	register YY_CHAR yy_c = 1;
-	while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
-		{
-		yy_current_state = (int) yy_def[yy_current_state];
-		if ( yy_current_state >= 269 )
-			yy_c = yy_meta[(unsigned int) yy_c];
-		}
-	yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-	yy_is_jam = (yy_current_state == 268);
-	if ( ! yy_is_jam )
-		*yy_state_ptr++ = yy_current_state;
-
-	return yy_is_jam ? 0 : yy_current_state;
-	}
-
-
-#ifndef YY_NO_UNPUT
-#ifdef YY_USE_PROTOS
-static void yyunput( int c, register char *yy_bp )
-#else
-static void yyunput( c, yy_bp )
-int c;
-register char *yy_bp;
-#endif
-	{
-	register char *yy_cp = yy_c_buf_p;
-
-	/* undo effects of setting up yytext */
-	*yy_cp = yy_hold_char;
-
-	if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 )
-		{ /* need to shift things up to make room */
-		/* +2 for EOB chars. */
-		register int number_to_move = yy_n_chars + 2;
-		register char *dest = &yy_current_buffer->yy_ch_buf[
-					yy_current_buffer->yy_buf_size + 2];
-		register char *source =
-				&yy_current_buffer->yy_ch_buf[number_to_move];
-
-		while ( source > yy_current_buffer->yy_ch_buf )
-			*--dest = *--source;
-
-		yy_cp += (int) (dest - source);
-		yy_bp += (int) (dest - source);
-		yy_current_buffer->yy_n_chars =
-			yy_n_chars = yy_current_buffer->yy_buf_size;
-
-		if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 )
-			YY_FATAL_ERROR( "flex scanner push-back overflow" );
-		}
-
-	*--yy_cp = (char) c;
-
-	if ( c == '\n' )
-		--yylineno;
-
-	yytext_ptr = yy_bp;
-	yy_hold_char = *yy_cp;
-	yy_c_buf_p = yy_cp;
-	}
-#endif	/* ifndef YY_NO_UNPUT */
-
-
-#ifdef __cplusplus
-static int yyinput()
-#else
-static int input()
-#endif
-	{
-	int c;
-
-	*yy_c_buf_p = yy_hold_char;
-
-	if ( *yy_c_buf_p == YY_END_OF_BUFFER_CHAR )
-		{
-		/* yy_c_buf_p now points to the character we want to return.
-		 * If this occurs *before* the EOB characters, then it's a
-		 * valid NUL; if not, then we've hit the end of the buffer.
-		 */
-		if ( yy_c_buf_p < &yy_current_buffer->yy_ch_buf[yy_n_chars] )
-			/* This was really a NUL. */
-			*yy_c_buf_p = '\0';
-
-		else
-			{ /* need more input */
-			int offset = yy_c_buf_p - yytext_ptr;
-			++yy_c_buf_p;
-
-			switch ( yy_get_next_buffer() )
-				{
-				case EOB_ACT_LAST_MATCH:
-					/* This happens because yy_g_n_b()
-					 * sees that we've accumulated a
-					 * token and flags that we need to
-					 * try matching the token before
-					 * proceeding.  But for input(),
-					 * there's no matching to consider.
-					 * So convert the EOB_ACT_LAST_MATCH
-					 * to EOB_ACT_END_OF_FILE.
-					 */
-
-					/* Reset buffer status. */
-					yyrestart( yyin );
-
-					/* fall through */
-
-				case EOB_ACT_END_OF_FILE:
-					{
-					if ( yywrap() )
-						return EOF;
-
-					if ( ! yy_did_buffer_switch_on_eof )
-						YY_NEW_FILE;
-#ifdef __cplusplus
-					return yyinput();
-#else
-					return input();
-#endif
-					}
-
-				case EOB_ACT_CONTINUE_SCAN:
-					yy_c_buf_p = yytext_ptr + offset;
-					break;
-				}
-			}
-		}
-
-	c = *(unsigned char *) yy_c_buf_p;	/* cast for 8-bit char's */
-	*yy_c_buf_p = '\0';	/* preserve yytext */
-	yy_hold_char = *++yy_c_buf_p;
-
-	if ( c == '\n' )
-		++yylineno;
-
-	return c;
-	}
-
-
-#ifdef YY_USE_PROTOS
-void yyrestart( FILE *input_file )
-#else
-void yyrestart( input_file )
-FILE *input_file;
-#endif
-	{
-	if ( ! yy_current_buffer )
-		yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE );
-
-	yy_init_buffer( yy_current_buffer, input_file );
-	yy_load_buffer_state();
-	}
-
-
-#ifdef YY_USE_PROTOS
-void yy_switch_to_buffer( YY_BUFFER_STATE new_buffer )
-#else
-void yy_switch_to_buffer( new_buffer )
-YY_BUFFER_STATE new_buffer;
-#endif
-	{
-	if ( yy_current_buffer == new_buffer )
-		return;
-
-	if ( yy_current_buffer )
-		{
-		/* Flush out information for old buffer. */
-		*yy_c_buf_p = yy_hold_char;
-		yy_current_buffer->yy_buf_pos = yy_c_buf_p;
-		yy_current_buffer->yy_n_chars = yy_n_chars;
-		}
-
-	yy_current_buffer = new_buffer;
-	yy_load_buffer_state();
-
-	/* We don't actually know whether we did this switch during
-	 * EOF (yywrap()) processing, but the only time this flag
-	 * is looked at is after yywrap() is called, so it's safe
-	 * to go ahead and always set it.
-	 */
-	yy_did_buffer_switch_on_eof = 1;
-	}
-
-
-#ifdef YY_USE_PROTOS
-void yy_load_buffer_state( void )
-#else
-void yy_load_buffer_state()
-#endif
-	{
-	yy_n_chars = yy_current_buffer->yy_n_chars;
-	yytext_ptr = yy_c_buf_p = yy_current_buffer->yy_buf_pos;
-	yyin = yy_current_buffer->yy_input_file;
-	yy_hold_char = *yy_c_buf_p;
-	}
-
-
-#ifdef YY_USE_PROTOS
-YY_BUFFER_STATE yy_create_buffer( FILE *file, int size )
-#else
-YY_BUFFER_STATE yy_create_buffer( file, size )
-FILE *file;
-int size;
-#endif
-	{
-	YY_BUFFER_STATE b;
-
-	b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) );
-	if ( ! b )
-		YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
-
-	b->yy_buf_size = size;
-
-	/* yy_ch_buf has to be 2 characters longer than the size given because
-	 * we need to put in 2 end-of-buffer characters.
-	 */
-	b->yy_ch_buf = (char *) yy_flex_alloc( b->yy_buf_size + 2 );
-	if ( ! b->yy_ch_buf )
-		YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
-
-	b->yy_is_our_buffer = 1;
-
-	yy_init_buffer( b, file );
-
-	return b;
-	}
-
-
-#ifdef YY_USE_PROTOS
-void yy_delete_buffer( YY_BUFFER_STATE b )
-#else
-void yy_delete_buffer( b )
-YY_BUFFER_STATE b;
-#endif
-	{
-	if ( ! b )
-		return;
-
-	if ( b == yy_current_buffer )
-		yy_current_buffer = (YY_BUFFER_STATE) 0;
-
-	if ( b->yy_is_our_buffer )
-		yy_flex_free( (void *) b->yy_ch_buf );
-
-	yy_flex_free( (void *) b );
-	}
-
-
-#ifndef YY_ALWAYS_INTERACTIVE
-#ifndef YY_NEVER_INTERACTIVE
-extern int isatty YY_PROTO(( int ));
-#endif
-#endif
-
-#ifdef YY_USE_PROTOS
-void yy_init_buffer( YY_BUFFER_STATE b, FILE *file )
-#else
-void yy_init_buffer( b, file )
-YY_BUFFER_STATE b;
-FILE *file;
-#endif
-
-
-	{
-	yy_flush_buffer( b );
-
-	b->yy_input_file = file;
-	b->yy_fill_buffer = 1;
-
-#if YY_ALWAYS_INTERACTIVE
-	b->yy_is_interactive = 1;
-#else
-#if YY_NEVER_INTERACTIVE
-	b->yy_is_interactive = 0;
-#else
-	b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
-#endif
-#endif
-	}
-
-
-#ifdef YY_USE_PROTOS
-void yy_flush_buffer( YY_BUFFER_STATE b )
-#else
-void yy_flush_buffer( b )
-YY_BUFFER_STATE b;
-#endif
-
-	{
-	if ( ! b )
-		return;
-
-	b->yy_n_chars = 0;
-
-	/* We always need two end-of-buffer characters.  The first causes
-	 * a transition to the end-of-buffer state.  The second causes
-	 * a jam in that state.
-	 */
-	b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
-	b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
-
-	b->yy_buf_pos = &b->yy_ch_buf[0];
-
-	b->yy_at_bol = 1;
-	b->yy_buffer_status = YY_BUFFER_NEW;
-
-	if ( b == yy_current_buffer )
-		yy_load_buffer_state();
-	}
-
-
-#ifndef YY_NO_SCAN_BUFFER
-#ifdef YY_USE_PROTOS
-YY_BUFFER_STATE yy_scan_buffer( char *base, yy_size_t size )
-#else
-YY_BUFFER_STATE yy_scan_buffer( base, size )
-char *base;
-yy_size_t size;
-#endif
-	{
-	YY_BUFFER_STATE b;
-
-	if ( size < 2 ||
-	     base[size-2] != YY_END_OF_BUFFER_CHAR ||
-	     base[size-1] != YY_END_OF_BUFFER_CHAR )
-		/* They forgot to leave room for the EOB's. */
-		return 0;
-
-	b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) );
-	if ( ! b )
-		YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
-
-	b->yy_buf_size = size - 2;	/* "- 2" to take care of EOB's */
-	b->yy_buf_pos = b->yy_ch_buf = base;
-	b->yy_is_our_buffer = 0;
-	b->yy_input_file = 0;
-	b->yy_n_chars = b->yy_buf_size;
-	b->yy_is_interactive = 0;
-	b->yy_at_bol = 1;
-	b->yy_fill_buffer = 0;
-	b->yy_buffer_status = YY_BUFFER_NEW;
-
-	yy_switch_to_buffer( b );
-
-	return b;
-	}
-#endif
-
-
-#ifndef YY_NO_SCAN_STRING
-#ifdef YY_USE_PROTOS
-YY_BUFFER_STATE yy_scan_string( yyconst char *yy_str )
-#else
-YY_BUFFER_STATE yy_scan_string( yy_str )
-yyconst char *yy_str;
-#endif
-	{
-	int len;
-	for ( len = 0; yy_str[len]; ++len )
-		;
-
-	return yy_scan_bytes( yy_str, len );
-	}
-#endif
-
-
-#ifndef YY_NO_SCAN_BYTES
-#ifdef YY_USE_PROTOS
-YY_BUFFER_STATE yy_scan_bytes( yyconst char *bytes, int len )
-#else
-YY_BUFFER_STATE yy_scan_bytes( bytes, len )
-yyconst char *bytes;
-int len;
-#endif
-	{
-	YY_BUFFER_STATE b;
-	char *buf;
-	yy_size_t n;
-	int i;
-
-	/* Get memory for full buffer, including space for trailing EOB's. */
-	n = len + 2;
-	buf = (char *) yy_flex_alloc( n );
-	if ( ! buf )
-		YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
-
-	for ( i = 0; i < len; ++i )
-		buf[i] = bytes[i];
-
-	buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR;
-
-	b = yy_scan_buffer( buf, n );
-	if ( ! b )
-		YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
-
-	/* It's okay to grow etc. this buffer, and we should throw it
-	 * away when we're done.
-	 */
-	b->yy_is_our_buffer = 1;
-
-	return b;
-	}
-#endif
-
-
-#ifndef YY_NO_PUSH_STATE
-#ifdef YY_USE_PROTOS
-static void yy_push_state( int new_state )
-#else
-static void yy_push_state( new_state )
-int new_state;
-#endif
-	{
-	if ( yy_start_stack_ptr >= yy_start_stack_depth )
-		{
-		yy_size_t new_size;
-
-		yy_start_stack_depth += YY_START_STACK_INCR;
-		new_size = yy_start_stack_depth * sizeof( int );
-
-		if ( ! yy_start_stack )
-			yy_start_stack = (int *) yy_flex_alloc( new_size );
-
-		else
-			yy_start_stack = (int *) yy_flex_realloc(
-					(void *) yy_start_stack, new_size );
-
-		if ( ! yy_start_stack )
-			YY_FATAL_ERROR(
-			"out of memory expanding start-condition stack" );
-		}
-
-	yy_start_stack[yy_start_stack_ptr++] = YY_START;
-
-	BEGIN(new_state);
-	}
-#endif
-
-
-#ifndef YY_NO_POP_STATE
-static void yy_pop_state()
-	{
-	if ( --yy_start_stack_ptr < 0 )
-		YY_FATAL_ERROR( "start-condition stack underflow" );
-
-	BEGIN(yy_start_stack[yy_start_stack_ptr]);
-	}
-#endif
-
-
-#ifndef YY_NO_TOP_STATE
-static int yy_top_state()
-	{
-	return yy_start_stack[yy_start_stack_ptr - 1];
-	}
-#endif
-
-#ifndef YY_EXIT_FAILURE
-#define YY_EXIT_FAILURE 2
-#endif
-
-#ifdef YY_USE_PROTOS
-static void yy_fatal_error( yyconst char msg[] )
-#else
-static void yy_fatal_error( msg )
-char msg[];
-#endif
-	{
-	(void) fprintf( stderr, "%s\n", msg );
-	exit( YY_EXIT_FAILURE );
-	}
-
-
-
-/* Redefine yyless() so it works in section 3 code. */
-
-#undef yyless
-#define yyless(n) \
-	do \
-		{ \
-		/* Undo effects of setting up yytext. */ \
-		yytext[yyleng] = yy_hold_char; \
-		yy_c_buf_p = yytext + n; \
-		yy_hold_char = *yy_c_buf_p; \
-		*yy_c_buf_p = '\0'; \
-		yyleng = n; \
-		} \
-	while ( 0 )
-
-
-/* Internal utility routines. */
-
-#ifndef yytext_ptr
-#ifdef YY_USE_PROTOS
-static void yy_flex_strncpy( char *s1, yyconst char *s2, int n )
-#else
-static void yy_flex_strncpy( s1, s2, n )
-char *s1;
-yyconst char *s2;
-int n;
-#endif
-	{
-	register int i;
-	for ( i = 0; i < n; ++i )
-		s1[i] = s2[i];
-	}
-#endif
-
-#ifdef YY_NEED_STRLEN
-#ifdef YY_USE_PROTOS
-static int yy_flex_strlen( yyconst char *s )
-#else
-static int yy_flex_strlen( s )
-yyconst char *s;
-#endif
-	{
-	register int n;
-	for ( n = 0; s[n]; ++n )
-		;
-
-	return n;
-	}
-#endif
-
-
-#ifdef YY_USE_PROTOS
-static void *yy_flex_alloc( yy_size_t size )
-#else
-static void *yy_flex_alloc( size )
-yy_size_t size;
-#endif
-	{
-	return (void *) malloc( size );
-	}
-
-#ifdef YY_USE_PROTOS
-static void *yy_flex_realloc( void *ptr, yy_size_t size )
-#else
-static void *yy_flex_realloc( ptr, size )
-void *ptr;
-yy_size_t size;
-#endif
-	{
-	/* The cast to (char *) in the following accommodates both
-	 * implementations that use char* generic pointers, and those
-	 * that use void* generic pointers.  It works with the latter
-	 * because both ANSI C and C++ allow castless assignment from
-	 * any pointer type to void*, and deal with argument conversions
-	 * as though doing an assignment.
-	 */
-	return (void *) realloc( (char *) ptr, size );
-	}
-
-#ifdef YY_USE_PROTOS
-static void yy_flex_free( void *ptr )
-#else
-static void yy_flex_free( ptr )
-void *ptr;
-#endif
-	{
-	free( ptr );
-	}
-
-#if YY_MAIN
-int main()
-	{
-	yylex();
-	return 0;
-	}
-#endif
-#line 318 "RCOMP.LEX"
+/*
+* Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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 lexical scanner generated by flex.
+* Scanner skeleton version:
+* $Header: /home/daffy/u0/vern/flex/RCS/flex.skl,v 2.91 96/09/10 16:58:48 vern Exp $
+*
+*/
+
+
+#define FLEX_SCANNER
+#define YY_FLEX_MAJOR_VERSION 2
+#define YY_FLEX_MINOR_VERSION 5
+
+#include <stdio.h>
+
+
+/* cfront 1.2 defines "c_plusplus" instead of "__cplusplus" */
+#ifdef c_plusplus
+#ifndef __cplusplus
+#define __cplusplus
+#endif
+#endif
+
+
+#ifdef __cplusplus
+
+#include <stdlib.h>
+#include <unistd.h>
+
+/* Use prototypes in function declarations. */
+#define YY_USE_PROTOS
+
+/* The "const" storage-class-modifier is valid. */
+#define YY_USE_CONST
+
+#else	/* ! __cplusplus */
+
+#if __STDC__
+
+#define YY_USE_PROTOS
+#define YY_USE_CONST
+
+#endif	/* __STDC__ */
+#endif	/* ! __cplusplus */
+
+#ifdef __TURBOC__
+ #pragma warn -rch
+ #pragma warn -use
+#include <io.h>
+#include <stdlib.h>
+#define YY_USE_CONST
+#define YY_USE_PROTOS
+#endif
+
+#ifdef YY_USE_CONST
+#define yyconst const
+#else
+#define yyconst
+#endif
+
+
+#ifdef YY_USE_PROTOS
+#define YY_PROTO(proto) proto
+#else
+#define YY_PROTO(proto) ()
+#endif
+
+/* Returned upon end-of-file. */
+#define YY_NULL 0
+
+/* Promotes a possibly negative, possibly signed char to an unsigned
+ * integer for use as an array index.  If the signed char is negative,
+ * we want to instead treat it as an 8-bit unsigned char, hence the
+ * double cast.
+ */
+#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
+
+/* Enter a start condition.  This macro really ought to take a parameter,
+ * but we do it the disgusting crufty way forced on us by the ()-less
+ * definition of BEGIN.
+ */
+#define BEGIN yy_start = 1 + 2 *
+
+/* Translate the current start state into a value that can be later handed
+ * to BEGIN to return to the state.  The YYSTATE alias is for lex
+ * compatibility.
+ */
+#define YY_START ((yy_start - 1) / 2)
+#define YYSTATE YY_START
+
+/* Action number for EOF rule of a given start state. */
+#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
+
+/* Special action meaning "start processing a new file". */
+#define YY_NEW_FILE yyrestart( yyin )
+
+#define YY_END_OF_BUFFER_CHAR 0
+
+/* Size of default input buffer. */
+#define YY_BUF_SIZE 16384
+
+typedef struct yy_buffer_state *YY_BUFFER_STATE;
+
+extern int yyleng;
+extern FILE *yyin, *yyout;
+
+#define EOB_ACT_CONTINUE_SCAN 0
+#define EOB_ACT_END_OF_FILE 1
+#define EOB_ACT_LAST_MATCH 2
+
+/* The funky do-while in the following #define is used to turn the definition
+ * int a single C statement (which needs a semi-colon terminator).  This
+ * avoids problems with code like:
+ *
+ * 	if ( condition_holds )
+ *		yyless( 5 );
+ *	else
+ *		do_something_else();
+ *
+ * Prior to using the do-while the compiler would get upset at the
+ * "else" because it interpreted the "if" statement as being all
+ * done when it reached the ';' after the yyless() call.
+ */
+
+/* Return all but the first 'n' matched characters back to the input stream. */
+
+#define yyless(n) \
+	do \
+		{ \
+		/* Undo effects of setting up yytext. */ \
+		*yy_cp = yy_hold_char; \
+		YY_RESTORE_YY_MORE_OFFSET \
+		yy_c_buf_p = yy_cp = yy_bp + n - YY_MORE_ADJ; \
+		YY_DO_BEFORE_ACTION; /* set up yytext again */ \
+		} \
+	while ( 0 )
+
+#define unput(c) yyunput( c, yytext_ptr )
+
+/* The following is because we cannot portably get our hands on size_t
+ * (without autoconf's help, which isn't available because we want
+ * flex-generated scanners to compile on their own).
+ */
+typedef unsigned int yy_size_t;
+
+
+struct yy_buffer_state
+	{
+	FILE *yy_input_file;
+
+	char *yy_ch_buf;		/* input buffer */
+	char *yy_buf_pos;		/* current position in input buffer */
+
+	/* Size of input buffer in bytes, not including room for EOB
+	 * characters.
+	 */
+	yy_size_t yy_buf_size;
+
+	/* Number of characters read into yy_ch_buf, not including EOB
+	 * characters.
+	 */
+	int yy_n_chars;
+
+	/* Whether we "own" the buffer - i.e., we know we created it,
+	 * and can realloc() it to grow it, and should free() it to
+	 * delete it.
+	 */
+	int yy_is_our_buffer;
+
+	/* Whether this is an "interactive" input source; if so, and
+	 * if we're using stdio for input, then we want to use getc()
+	 * instead of fread(), to make sure we stop fetching input after
+	 * each newline.
+	 */
+	int yy_is_interactive;
+
+	/* Whether we're considered to be at the beginning of a line.
+	 * If so, '^' rules will be active on the next match, otherwise
+	 * not.
+	 */
+	int yy_at_bol;
+
+	/* Whether to try to fill the input buffer when we reach the
+	 * end of it.
+	 */
+	int yy_fill_buffer;
+
+	int yy_buffer_status;
+#define YY_BUFFER_NEW 0
+#define YY_BUFFER_NORMAL 1
+	/* When an EOF's been seen but there's still some text to process
+	 * then we mark the buffer as YY_EOF_PENDING, to indicate that we
+	 * shouldn't try reading from the input source any more.  We might
+	 * still have a bunch of tokens to match, though, because of
+	 * possible backing-up.
+	 *
+	 * When we actually see the EOF, we change the status to "new"
+	 * (via yyrestart()), so that the user can continue scanning by
+	 * just pointing yyin at a new input file.
+	 */
+#define YY_BUFFER_EOF_PENDING 2
+	};
+
+static YY_BUFFER_STATE yy_current_buffer = 0;
+
+/* We provide macros for accessing buffer states in case in the
+ * future we want to put the buffer states in a more general
+ * "scanner state".
+ */
+#define YY_CURRENT_BUFFER yy_current_buffer
+
+
+/* yy_hold_char holds the character lost when yytext is formed. */
+static char yy_hold_char;
+
+static int yy_n_chars;		/* number of characters read into yy_ch_buf */
+
+
+int yyleng;
+
+/* Points to current character in buffer. */
+static char *yy_c_buf_p = (char *) 0;
+static int yy_init = 1;		/* whether we need to initialize */
+static int yy_start = 0;	/* start state number */
+
+/* Flag which is used to allow yywrap()'s to do buffer switches
+ * instead of setting up a fresh yyin.  A bit of a hack ...
+ */
+static int yy_did_buffer_switch_on_eof;
+
+void yyrestart YY_PROTO(( FILE *input_file ));
+
+void yy_switch_to_buffer YY_PROTO(( YY_BUFFER_STATE new_buffer ));
+void yy_load_buffer_state YY_PROTO(( void ));
+YY_BUFFER_STATE yy_create_buffer YY_PROTO(( FILE *file, int size ));
+void yy_delete_buffer YY_PROTO(( YY_BUFFER_STATE b ));
+void yy_init_buffer YY_PROTO(( YY_BUFFER_STATE b, FILE *file ));
+void yy_flush_buffer YY_PROTO(( YY_BUFFER_STATE b ));
+#define YY_FLUSH_BUFFER yy_flush_buffer( yy_current_buffer )
+
+YY_BUFFER_STATE yy_scan_buffer YY_PROTO(( char *base, yy_size_t size ));
+YY_BUFFER_STATE yy_scan_string YY_PROTO(( yyconst char *yy_str ));
+YY_BUFFER_STATE yy_scan_bytes YY_PROTO(( yyconst char *bytes, int len ));
+
+static void *yy_flex_alloc YY_PROTO(( yy_size_t ));
+static void *yy_flex_realloc YY_PROTO(( void *, yy_size_t ));
+static void yy_flex_free YY_PROTO(( void * ));
+
+#define yy_new_buffer yy_create_buffer
+
+#define yy_set_interactive(is_interactive) \
+	{ \
+	if ( ! yy_current_buffer ) \
+		yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \
+	yy_current_buffer->yy_is_interactive = is_interactive; \
+	}
+
+#define yy_set_bol(at_bol) \
+	{ \
+	if ( ! yy_current_buffer ) \
+		yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \
+	yy_current_buffer->yy_at_bol = at_bol; \
+	}
+
+#define YY_AT_BOL() (yy_current_buffer->yy_at_bol)
+
+
+#define YY_USES_REJECT
+typedef unsigned char YY_CHAR;
+FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0;
+typedef int yy_state_type;
+extern int yylineno;
+int yylineno = 1;
+extern char *yytext;
+#define yytext_ptr yytext
+
+static yy_state_type yy_get_previous_state YY_PROTO(( void ));
+static yy_state_type yy_try_NUL_trans YY_PROTO(( yy_state_type current_state ));
+static int yy_get_next_buffer YY_PROTO(( void ));
+static void yy_fatal_error YY_PROTO(( yyconst char msg[] ));
+
+/* Done after the current pattern has been matched and before the
+ * corresponding action - sets up yytext.
+ */
+#define YY_DO_BEFORE_ACTION \
+	yytext_ptr = yy_bp; \
+	yyleng = (int) (yy_cp - yy_bp); \
+	yy_hold_char = *yy_cp; \
+	*yy_cp = '\0'; \
+	yy_c_buf_p = yy_cp;
+
+#define YY_NUM_RULES 81
+#define YY_END_OF_BUFFER 82
+static yyconst short int yy_acclist[363] =
+    {   0,
+       82,   80,   81,   62,   80,   81,   63,   81,   63,   80,
+       81,   37,   80,   81,   80,   81,   38,   80,   81,   79,
+       80,   81,   79,   80,   81,   79,   80,   81,   49,   80,
+       81,   49,   80,   81,   48,   80,   81,   48,   80,   81,
+       48,   80,   81,   48,   80,   81,   48,   80,   81,   48,
+       80,   81,   48,   80,   81,   48,   80,   81,   48,   80,
+       81,   48,   80,   81,   48,   80,   81,   48,   80,   81,
+       48,   80,   81,   48,   80,   81,   48,   80,   81,   48,
+       80,   81,   48,   80,   81,   47,   80,   81,   44,   81,
+       47,   80,   81,   45,   47,   80,   81,   46,   47,   80,
+
+       81,   47,   80,   81,   80,   81,   62,   80,   81,   64,
+       81,   64,   80,   81,   80,   81,   80,   81,   67,   80,
+       81,   66,   81,   66,   67,   80,   81,   72,   80,   81,
+       71,   81,   71,   72,   80,   81,   72,   80,   81,   76,
+       80,   81,   78,   80,   81,   77,   81,   77,   80,   81,
+       78,   80,   81,   80,   81,   65,   49,   48,   48,   48,
+       48,   48,   48,   48,   48,   48,   48,   48,   48,   48,
+       48,   48,   48,   48,   48,   48,   48,   48,   48,   48,
+       48,   44,   43,   39,   40,   42,   41,   58,   59,   65,
+       70,   76,   74,   75,   68,   69,   68,   69,   73,   53,
+
+       55,   50,   20,   48,   48,   48,   48,   48,   48,   36,
+       48,   48,   48,   48,   48,   48,   48,   48,   48,   48,
+       48,   48,   48,   48,   48,   48,   48,   48,   59,   68,
+       69,   68,   69,   68,   73,   54,   56,   48,   21,   48,
+       24,   48,   48,   48,    9,   48,   48,   33,   48,   48,
+       48,   25,   48,   48,    3,   48,   48,   48,   48,   48,
+       48,   27,   48,   11,   48,   12,   48,   23,   48,   10,
+       48,   48,   48,   60,   61,   57,   51,   22,   48,   48,
+       48,   48,   34,   48,    8,   48,   28,   48,   48,   48,
+       48,   48,   48,   48,   29,   48,   19,   48,   48,   48,
+
+       48,   48,   48,   52,   48,   26,   48,    7,   48,   48,
+       30,   48,    5,   48,   48,   35,   48,    1,   48,    6,
+       48,   31,   48,   48,   48,   48,   48,   48,   48,   32,
+       48,   48,   48,   48,   48,   48,   48,   48,    2,   48,
+       16,   48,   48,   18,   48,   48,   17,   48,   48,   48,
+       48,   48,   15,   48,   13,   48,   48,   14,   48,   48,
+        4,   48
+    } ;
+
+static yyconst short int yy_accept[270] =
+    {   0,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    2,    4,    7,    9,   12,   15,   17,
+       20,   23,   26,   29,   32,   35,   38,   41,   44,   47,
+       50,   53,   56,   59,   62,   65,   68,   71,   74,   77,
+       80,   83,   86,   89,   91,   94,   98,  102,  105,  107,
+      110,  112,  115,  117,  119,  122,  124,  128,  131,  133,
+      137,  140,  143,  146,  148,  151,  154,  156,  156,  156,
+      156,  156,  156,  157,  157,  158,  158,  158,  159,  160,
+      161,  162,  163,  164,  165,  166,  167,  168,  169,  170,
+      171,  172,  173,  174,  175,  176,  177,  178,  179,  180,
+
+      181,  182,  183,  184,  185,  186,  187,  188,  188,  188,
+      188,  188,  190,  190,  190,  190,  191,  192,  193,  194,
+      195,  195,  195,  195,  195,  196,  197,  199,  200,  201,
+      202,  203,  205,  206,  207,  208,  209,  210,  212,  213,
+      214,  215,  216,  217,  218,  219,  220,  221,  222,  223,
+      224,  225,  226,  227,  228,  229,  230,  230,  230,  230,
+      230,  231,  232,  234,  235,  236,  236,  237,  238,  238,
+      239,  241,  243,  244,  245,  247,  248,  250,  251,  252,
+      254,  255,  257,  258,  259,  260,  261,  262,  264,  266,
+      268,  270,  272,  273,  274,  275,  275,  275,  276,  276,
+
+      276,  277,  277,  278,  280,  281,  282,  283,  285,  287,
+      289,  290,  291,  292,  293,  294,  295,  297,  299,  300,
+      301,  302,  303,  304,  304,  304,  305,  306,  308,  310,
+      311,  313,  315,  316,  318,  320,  322,  324,  325,  326,
+      327,  328,  329,  330,  332,  333,  334,  335,  336,  337,
+      338,  339,  341,  343,  344,  346,  347,  349,  350,  351,
+      352,  353,  355,  357,  358,  360,  361,  363,  363
+    } ;
+
+static yyconst int yy_ec[256] =
+    {   0,
+        1,    1,    1,    1,    1,    1,    1,    1,    2,    3,
+        1,    1,    4,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    5,    1,    6,    7,    1,    1,    8,    9,   10,
+       10,   11,   10,   10,   12,   13,   14,   15,   16,   17,
+       18,   19,   19,   20,   19,   21,   19,    1,   10,   10,
+       10,   10,    1,   22,   23,   24,   25,   26,   27,   28,
+       29,   30,   31,   32,   33,   34,   35,   36,   37,   32,
+       32,   38,   39,   40,   41,   32,   42,   43,   44,   32,
+       10,   45,   10,    1,   46,    1,   47,   48,   47,   49,
+
+       50,   51,   52,   53,   54,   53,   53,   55,   56,   57,
+       58,   53,   53,   59,   60,   61,   62,   63,   64,   65,
+       66,   53,   10,   10,   10,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1
+    } ;
+
+static yyconst int yy_meta[67] =
+    {   0,
+        1,    2,    3,    2,    2,    4,    1,    1,    4,    1,
+        2,    1,    5,    1,    6,    6,    6,    6,    6,    6,
+        6,    1,    7,    7,    7,    7,    6,    7,    8,    8,
+        8,    8,    8,    8,    8,    8,    8,    8,    8,    8,
+        8,    8,    8,    8,    4,    8,    7,    9,    7,    6,
+        9,    8,    8,    8,    8,    8,   10,    8,   10,    8,
+       10,    8,   10,    8,   11,    8
+    } ;
+
+static yyconst short int yy_base[284] =
+    {   0,
+        0,    0,   64,   68,   76,   81,   72,   85,   88,   90,
+      100,  112,  566,  567,  105,  567,  567,  567,  560,  567,
+      567,  109,   86,   85,   93,    0,   77,  534,  526,  526,
+      527,  105,  537,  531,  531,   93,  530,  525,  518,  497,
+      491,  497,  567,  567,  548,  567,  567,  135,  544,  146,
+      543,  542,  150,  150,  567,  567,  567,  567,  567,  567,
+      533,    0,  567,  567,  567,  532,    0,  157,  534,  157,
+      136,  162,  567,  172,    0,  179,    0,    0,  516,  503,
+      519,  500,  499,  502,  502,  501,  505,  121,  508,  499,
+      505,  493,  497,  492,  490,  485,  501,  488,  463,  469,
+
+      463,  567,  567,  567,  567,  567,  567,  516,  164,  199,
+      173,  567,  518,  165,  203,  514,  567,    0,  567,    0,
+      511,  203,  210,  217,  567,  567,  567,  567,  224,  237,
+        0,  194,  491,  479,  492,  480,  490,    0,  480,  476,
+      488,  481,  466,  481,  468,  469,  474,  463,  463,  462,
+      185,  475,  444,  438,  452,  567,  494,  177,  243,  256,
+      490,  489,  488,  259,  487,  486,  250,  263,  270,  471,
+        0,    0,  467,  455,    0,  465,    0,  454,  452,    0,
+      445,    0,  457,  442,  446,  456,  453,  196,    0,    0,
+        0,    0,  425,  244,  567,  475,  459,  567,  473,  457,
+
+      567,  294,  301,    0,  449,  446,  438,    0,    0,  280,
+      431,  432,  436,  428,  432,  434,    0,    0,  364,  371,
+      361,  357,  345,  246,  269,  308,  362,    0,    0,  381,
+        0,    0,  375,    0,    0,    0,    0,  329,  327,  331,
+      328,  248,  279,    0,  278,  253,  254,  246,  243,  246,
+      256,    0,    0,  221,    0,  218,    0,  170,  164,   95,
+      101,    0,   87,   69,    0,   29,    0,  567,  329,  340,
+      351,  362,  373,  380,  386,  395,  405,  416,  427,  434,
+      440,  446,  455
+    } ;
+
+static yyconst short int yy_def[284] =
+    {   0,
+      268,    1,  269,  269,  270,  270,  271,  271,  272,  272,
+      273,  273,  268,  268,  268,  268,  268,  268,  268,  268,
+      268,  268,  268,  274,  274,  275,  275,  275,  275,  275,
+      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
+      275,  275,  268,  268,  268,  268,  268,  276,  277,  277,
+      277,  277,  268,  277,  268,  268,  268,  268,  268,  268,
+      268,  278,  268,  268,  268,  268,  279,  268,  268,  268,
+      280,  281,  268,  268,   25,  268,  282,  275,  275,  275,
+      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
+      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
+
+      275,  268,  268,  268,  268,  268,  268,  277,  268,  277,
+      277,  268,  268,  268,  283,  277,  268,  278,  268,  279,
+      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
+      282,  275,  275,  275,  275,  275,  275,  275,  275,  275,
+      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
+      275,  275,  275,  275,  275,  268,  268,  277,  268,  268,
+      277,  277,  277,  268,  277,  268,  268,  268,  268,  275,
+      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
+      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
+      275,  275,  275,  275,  268,  268,  268,  268,  268,  268,
+
+      268,  268,  268,  275,  275,  275,  275,  275,  275,  275,
+      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
+      275,  275,  275,  268,  268,  268,  275,  275,  275,  275,
+      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
+      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
+      275,  275,  275,  275,  275,  275,  275,  275,  275,  275,
+      275,  275,  275,  275,  275,  275,  275,    0,  268,  268,
+      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
+      268,  268,  268
+    } ;
+
+static yyconst short int yy_nxt[634] =
+    {   0,
+       14,   15,   16,   17,   15,   18,   19,   14,   20,   21,
+       21,   22,   21,   23,   24,   25,   25,   25,   25,   25,
+       25,   14,   26,   27,   28,   29,   30,   26,   31,   26,
+       26,   26,   26,   32,   26,   33,   34,   35,   36,   37,
+       38,   39,   26,   26,   14,   26,   26,   26,   26,   40,
+       26,   26,   26,   26,   26,   41,   26,   26,   42,   26,
+       26,   26,   26,   26,   26,   26,   44,   45,  267,   46,
+       44,   45,   47,   46,   56,   57,   47,   50,   51,   52,
+       50,   53,   50,   51,   52,   50,   53,   56,   57,   54,
+       59,   60,   59,   60,   54,  266,   72,   74,   61,   73,
+
+       61,   63,   64,   65,   63,   74,   68,  265,   48,   68,
+       66,   76,   48,   63,   64,   65,   63,   79,   69,   76,
+       80,   67,   66,   71,   71,   71,   71,   71,   71,   71,
+       93,   85,   94,   67,   76,   86,   95,  103,   87,  264,
+      104,   88,   76,  105,   89,  141,  263,  110,  123,   77,
+      110,  109,  112,  113,  114,  109,  142,  268,   68,  111,
+      115,   68,  124,  116,  126,  127,  156,  157,  114,  128,
+       69,  122,  122,  122,  122,  122,  122,  122,  109,  106,
+      159,  160,  109,  158,  165,  124,  129,  129,  129,  129,
+      129,  129,  129,  130,  130,  130,  130,  130,  130,  130,
+
+      110,  189,  190,  110,  109,  162,  163,  166,  164,  170,
+      165,  216,  111,  262,  171,  261,  217,  122,  122,  122,
+      122,  122,  122,  122,  167,  167,  167,  167,  167,  167,
+      167,  168,  168,  168,  168,  168,  168,  168,  129,  129,
+      129,  129,  129,  129,  129,  195,  196,  197,  195,  196,
+      169,  130,  130,  130,  130,  130,  130,  130,  198,  199,
+      200,  156,  157,  114,  167,  167,  167,  167,  167,  167,
+      167,  198,  199,  169,  260,  259,  202,  168,  168,  168,
+      168,  168,  168,  168,  203,  203,  203,  203,  203,  203,
+      203,  219,  220,  258,  257,  230,  256,  255,  221,  202,
+
+      231,  254,  253,  222,  252,  251,  250,  223,  226,  226,
+      226,  226,  226,  226,  226,  203,  203,  203,  203,  203,
+      203,  203,  226,  226,  226,  226,  226,  226,  226,   43,
+       43,   43,   43,   43,   43,   43,   43,   43,   43,   43,
+       49,   49,   49,   49,   49,   49,   49,   49,   49,   49,
+       49,   55,   55,   55,   55,   55,   55,   55,   55,   55,
+       55,   55,   58,   58,   58,   58,   58,   58,   58,   58,
+       58,   58,   58,   62,   62,   62,   62,   62,   62,   62,
+       62,   62,   62,   62,   75,   75,  249,  248,  247,  246,
+       75,   78,   78,   78,   78,   78,   78,  107,  107,  245,
+
+      244,  243,  242,  107,  107,  108,  108,  108,  108,  108,
+      108,  108,  108,  108,  108,  108,  118,  241,  240,  118,
+      118,  118,  118,  118,  118,  118,  118,  120,  239,  238,
+      120,  120,  120,  120,  120,  120,  120,  120,   71,   71,
+      125,  125,  125,  125,  125,  125,  125,  125,  125,  125,
+      125,  131,  131,  237,  131,  161,  161,  161,  161,  161,
+      161,  161,  161,  161,  161,  161,  236,  235,  234,  233,
+      232,  229,  228,  227,  225,  198,  224,  195,  218,  215,
+      214,  213,  212,  211,  210,  209,  208,  207,  206,  205,
+      204,  201,  109,  109,  109,  109,  156,  194,  193,  192,
+
+      191,  188,  187,  186,  185,  184,  183,  182,  181,  180,
+      179,  178,  177,  176,  175,  174,  173,  172,  128,  109,
+      112,  109,  155,  154,  153,  152,  151,  150,  149,  148,
+      147,  146,  145,  144,  143,  140,  139,  138,  137,  136,
+      135,  134,  133,  132,  121,  119,  117,  109,  109,  109,
+      102,  101,  100,   99,   98,   97,   96,   92,   91,   90,
+       84,   83,   82,   81,   70,  268,   13,  268,  268,  268,
+      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
+      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
+      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
+
+      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
+      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
+      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
+      268,  268,  268
+    } ;
+
+static yyconst short int yy_chk[634] =
+    {   0,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    3,    3,  266,    3,
+        4,    4,    3,    4,    7,    7,    4,    5,    5,    5,
+        5,    5,    6,    6,    6,    6,    6,    8,    8,    5,
+        9,    9,   10,   10,    6,  264,   23,   24,    9,   23,
+
+       10,   11,   11,   11,   11,   25,   15,  263,    3,   15,
+       11,   24,    4,   12,   12,   12,   12,   27,   15,   25,
+       27,   11,   12,   22,   22,   22,   22,   22,   22,   22,
+       36,   32,   36,   12,   24,   32,   36,   48,   32,  261,
+       48,   32,   25,   48,   32,   88,  260,   50,   71,   24,
+       50,   50,   53,   53,   53,   54,   88,   25,   68,   50,
+       54,   68,   71,   54,   72,   72,  109,  109,  109,   72,
+       68,   70,   70,   70,   70,   70,   70,   70,  111,   48,
+      114,  114,  158,  111,  158,   71,   74,   74,   74,   74,
+       74,   74,   74,   76,   76,   76,   76,   76,   76,   76,
+
+      110,  151,  151,  110,  110,  115,  115,  122,  115,  132,
+      115,  188,  110,  259,  132,  258,  188,  122,  122,  122,
+      122,  122,  122,  122,  123,  123,  123,  123,  123,  123,
+      123,  124,  124,  124,  124,  124,  124,  124,  129,  129,
+      129,  129,  129,  129,  129,  159,  159,  159,  224,  224,
+      129,  130,  130,  130,  130,  130,  130,  130,  160,  160,
+      160,  164,  164,  164,  167,  167,  167,  167,  167,  167,
+      167,  225,  225,  129,  256,  254,  167,  168,  168,  168,
+      168,  168,  168,  168,  169,  169,  169,  169,  169,  169,
+      169,  194,  194,  251,  250,  210,  249,  248,  194,  167,
+
+      210,  247,  246,  194,  245,  243,  242,  194,  202,  202,
+      202,  202,  202,  202,  202,  203,  203,  203,  203,  203,
+      203,  203,  226,  226,  226,  226,  226,  226,  226,  269,
+      269,  269,  269,  269,  269,  269,  269,  269,  269,  269,
+      270,  270,  270,  270,  270,  270,  270,  270,  270,  270,
+      270,  271,  271,  271,  271,  271,  271,  271,  271,  271,
+      271,  271,  272,  272,  272,  272,  272,  272,  272,  272,
+      272,  272,  272,  273,  273,  273,  273,  273,  273,  273,
+      273,  273,  273,  273,  274,  274,  241,  240,  239,  238,
+      274,  275,  275,  275,  275,  275,  275,  276,  276,  233,
+
+      230,  227,  223,  276,  276,  277,  277,  277,  277,  277,
+      277,  277,  277,  277,  277,  277,  278,  222,  221,  278,
+      278,  278,  278,  278,  278,  278,  278,  279,  220,  219,
+      279,  279,  279,  279,  279,  279,  279,  279,  280,  280,
+      281,  281,  281,  281,  281,  281,  281,  281,  281,  281,
+      281,  282,  282,  216,  282,  283,  283,  283,  283,  283,
+      283,  283,  283,  283,  283,  283,  215,  214,  213,  212,
+      211,  207,  206,  205,  200,  199,  197,  196,  193,  187,
+      186,  185,  184,  183,  181,  179,  178,  176,  174,  173,
+      170,  166,  165,  163,  162,  161,  157,  155,  154,  153,
+
+      152,  150,  149,  148,  147,  146,  145,  144,  143,  142,
+      141,  140,  139,  137,  136,  135,  134,  133,  121,  116,
+      113,  108,  101,  100,   99,   98,   97,   96,   95,   94,
+       93,   92,   91,   90,   89,   87,   86,   85,   84,   83,
+       82,   81,   80,   79,   69,   66,   61,   52,   51,   49,
+       45,   42,   41,   40,   39,   38,   37,   35,   34,   33,
+       31,   30,   29,   28,   19,   13,  268,  268,  268,  268,
+      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
+      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
+      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
+
+      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
+      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
+      268,  268,  268,  268,  268,  268,  268,  268,  268,  268,
+      268,  268,  268
+    } ;
+
+static yy_state_type yy_state_buf[YY_BUF_SIZE + 2], *yy_state_ptr;
+static char *yy_full_match;
+static int yy_lp;
+#define REJECT \
+{ \
+*yy_cp = yy_hold_char; /* undo effects of setting up yytext */ \
+yy_cp = yy_full_match; /* restore poss. backed-over text */ \
+++yy_lp; \
+goto find_rule; \
+}
+#define yymore() yymore_used_but_not_detected
+#define YY_MORE_ADJ 0
+#define YY_RESTORE_YY_MORE_OFFSET
+char *yytext;
+#line 1 "RCOMP.LEX"
+#define INITIAL 0
+#line 3 "RCOMP.LEX"
+
+#include <limits.h>
+#include <string.h>
+#include "main.h"
+#include "STRUCTST.H"
+#include "Parser.h"
+#include "localise.h"
+
+#define YY_SKIP_YYWRAP 1
+#define YY_NEVER_INTERACTIVE 1
+int yywrap();
+void yyerror(const char* string, ...);
+
+// Redefine YY_INPUT so we can parse binary data.
+#undef YY_INPUT
+#define YY_INPUT(buf, result, max_size) (result = new_yy_input(buf, max_size))
+
+int new_yy_input(char *buf, int max_size)
+{
+   int result;
+   if(yyin != NULL) {
+		result = fread(buf, 1, max_size, yyin);
+	}
+   else if((pG->StdInBuffer != NULL) && (pG->StdInBufLength > 0)) {
+		int left = pG->StdInBufLength - pG->StdInfBufPos ;
+		if(left == 0)
+			return YY_NULL ;
+		result = (max_size < left) ? max_size : left ; 
+		memcpy(buf,&(pG->StdInBuffer[pG->StdInfBufPos]),result); 
+		pG->StdInfBufPos += result ;
+   }
+
+   if (result == 0)
+      return YY_NULL;
+   const unsigned char BOM[] = {0xef , 0xbb, 0xbf, 0x0 };
+   // check for utf8 (BOM) header in buf
+   for (int i = 0; i < result-3; i++) {
+      if (0 == memcmp(&buf[i],BOM,3)) {
+		memset(&buf[i],0x20,3);
+      }
+   }
+   return result;
+}
+
+#include "rcomp.hpp"
+#include "FILELINE.H"
+
+#define VALUE_LEN   (1024*8)	// must match sizeof(YYSTYPE.Value)
+char buf[VALUE_LEN];
+char * pCh;
+#define CHECK_APPEND(x)	\
+    if (pCh-buf==VALUE_LEN-1) { yyerror("string too long - %c ignored", (x)); } else {*pCh++ = (x); }
+
+int isCharLiteral;
+
+extern String		InputBaseName;
+extern FileLineManager* pFileLineHandler;
+extern int*		pCurrentLineNumber;
+char RealLineNumber[200];
+ 
+
+#include "ERRORHAN.H"
+
+#define REGISTER_LINE	ErrorHandler::Register(pFileLineHandler->GetCurrentFile(), pFileLineHandler->GetErrorLine(* pCurrentLineNumber))
+
+
+#define string_rules 1
+
+/* Rule set for string literals.			        */
+/* n.b. Exclusive rule sets i.e. %x are available in MKS only	*/
+/* so they are not used here; hence all the <INITIAL>'s.        */
+#define file_line_rules 2
+
+/* Rule set for file_line_directive.*/
+#define cpp_comment 3
+
+/* C++ comment to end of line */
+#define c_comment 4
+
+/* C comment */
+#define comment_tag 5
+
+/* Doxygen-style comment tag */
+#line 761 "lex.yy.c"
+
+/* Macros after this point can all be overridden by user definitions in
+ * section 1.
+ */
+
+#ifndef YY_SKIP_YYWRAP
+#ifdef __cplusplus
+extern "C" int yywrap YY_PROTO(( void ));
+#else
+extern int yywrap YY_PROTO(( void ));
+#endif
+#endif
+
+#ifndef YY_NO_UNPUT
+static void yyunput YY_PROTO(( int c, char *buf_ptr ));
+#endif
+
+#ifndef yytext_ptr
+static void yy_flex_strncpy YY_PROTO(( char *, yyconst char *, int ));
+#endif
+
+#ifdef YY_NEED_STRLEN
+static int yy_flex_strlen YY_PROTO(( yyconst char * ));
+#endif
+
+#ifndef YY_NO_INPUT
+#ifdef __cplusplus
+static int yyinput YY_PROTO(( void ));
+#else
+static int input YY_PROTO(( void ));
+#endif
+#endif
+
+#if YY_STACK_USED
+static int yy_start_stack_ptr = 0;
+static int yy_start_stack_depth = 0;
+static int *yy_start_stack = 0;
+#ifndef YY_NO_PUSH_STATE
+static void yy_push_state YY_PROTO(( int new_state ));
+#endif
+#ifndef YY_NO_POP_STATE
+static void yy_pop_state YY_PROTO(( void ));
+#endif
+#ifndef YY_NO_TOP_STATE
+static int yy_top_state YY_PROTO(( void ));
+#endif
+
+#else
+#define YY_NO_PUSH_STATE 1
+#define YY_NO_POP_STATE 1
+#define YY_NO_TOP_STATE 1
+#endif
+
+#ifdef YY_MALLOC_DECL
+YY_MALLOC_DECL
+#else
+#if __STDC__
+#ifndef __cplusplus
+#include <stdlib.h>
+#endif
+#else
+/* Just try to get by without declaring the routines.  This will fail
+ * miserably on non-ANSI systems for which sizeof(size_t) != sizeof(int)
+ * or sizeof(void*) != sizeof(int).
+ */
+#endif
+#endif
+
+/* Amount of stuff to slurp up with each read. */
+#ifndef YY_READ_BUF_SIZE
+#define YY_READ_BUF_SIZE 8192
+#endif
+
+/* Copy whatever the last rule matched to the standard output. */
+
+#ifndef ECHO
+/* This used to be an fputs(), but since the string might contain NUL's,
+ * we now use fwrite().
+ */
+#define ECHO (void) fwrite( yytext, yyleng, 1, yyout )
+#endif
+
+/* Gets input and stuffs it into "buf".  number of characters read, or YY_NULL,
+ * is returned in "result".
+ */
+#ifndef YY_INPUT
+#error "Unexpected behavior!"
+#define YY_INPUT(buf,result,max_size) \
+	if ( yy_current_buffer->yy_is_interactive ) \
+		{ \
+		int c = '*', n; \
+		for ( n = 0; n < max_size && \
+			     (c = getc( yyin )) != EOF && c != '\n'; ++n ) \
+			buf[n] = (char) c; \
+		if ( c == '\n' ) \
+			buf[n++] = (char) c; \
+		if ( c == EOF && ferror( yyin ) ) \
+			YY_FATAL_ERROR( "input in flex scanner failed" ); \
+		result = n; \
+		} \
+	else if ( ((result = fread( buf, 1, max_size, yyin )) == 0) \
+		  && ferror( yyin ) ) \
+		YY_FATAL_ERROR( "input in flex scanner failed" );
+#endif
+
+/* No semi-colon after return; correct usage is to write "yyterminate();" -
+ * we don't want an extra ';' after the "return" because that will cause
+ * some compilers to complain about unreachable statements.
+ */
+#ifndef yyterminate
+#define yyterminate() return YY_NULL
+#endif
+
+/* Number of entries by which start-condition stack grows. */
+#ifndef YY_START_STACK_INCR
+#define YY_START_STACK_INCR 25
+#endif
+
+/* Report a fatal error. */
+#ifndef YY_FATAL_ERROR
+#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
+#endif
+
+/* Default declaration of generated scanner - a define so the user can
+ * easily add parameters.
+ */
+#ifndef YY_DECL
+#define YY_DECL int yylex YY_PROTO(( void ))
+#endif
+
+/* Code executed at the beginning of each rule, after yytext and yyleng
+ * have been set up.
+ */
+#ifndef YY_USER_ACTION
+#define YY_USER_ACTION
+#endif
+
+/* Code executed at the end of each rule. */
+#ifndef YY_BREAK
+#define YY_BREAK break;
+#endif
+
+#define YY_RULE_SETUP \
+	YY_USER_ACTION
+
+YY_DECL
+	{
+	register yy_state_type yy_current_state;
+	register char *yy_cp, *yy_bp;
+	register int yy_act;
+
+#line 130 "RCOMP.LEX"
+
+
+
+	/* Translations section */
+	/* ==================== */
+
+	/*******************************************/
+	/* Main keywords                           */
+	/*******************************************/
+#line 922 "lex.yy.c"
+
+	if ( yy_init )
+		{
+		yy_init = 0;
+
+#ifdef YY_USER_INIT
+		YY_USER_INIT;
+#endif
+
+		if ( ! yy_start )
+			yy_start = 1;	/* first start state */
+
+		if ( ! yyin )
+			yyin = stdin;
+
+		if ( ! yyout )
+			yyout = stdout;
+
+		if ( ! yy_current_buffer )
+			yy_current_buffer =
+				yy_create_buffer( yyin, YY_BUF_SIZE );
+
+		yy_load_buffer_state();
+		}
+
+	while ( 1 )		/* loops until end-of-file is reached */
+		{
+		yy_cp = yy_c_buf_p;
+
+		/* Support of yytext. */
+		*yy_cp = yy_hold_char;
+
+		/* yy_bp points to the position in yy_ch_buf of the start of
+		 * the current run.
+		 */
+		yy_bp = yy_cp;
+
+		yy_current_state = yy_start;
+		yy_state_ptr = yy_state_buf;
+		*yy_state_ptr++ = yy_current_state;
+yy_match:
+		do
+			{
+			register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
+			while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+				{
+				yy_current_state = (int) yy_def[yy_current_state];
+				if ( yy_current_state >= 269 )
+					yy_c = yy_meta[(unsigned int) yy_c];
+				}
+			yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
+			*yy_state_ptr++ = yy_current_state;
+			++yy_cp;
+			}
+		while ( yy_base[yy_current_state] != 567 );
+
+yy_find_action:
+		yy_current_state = *--yy_state_ptr;
+		yy_lp = yy_accept[yy_current_state];
+find_rule: /* we branch to this label when backing up */
+		for ( ; ; ) /* until we find what rule we matched */
+			{
+			if ( yy_lp && yy_lp < yy_accept[yy_current_state + 1] )
+				{
+				yy_act = yy_acclist[yy_lp];
+					{
+					yy_full_match = yy_cp;
+					break;
+					}
+				}
+			--yy_cp;
+			yy_current_state = *--yy_state_ptr;
+			yy_lp = yy_accept[yy_current_state];
+			}
+
+		YY_DO_BEFORE_ACTION;
+
+		if ( yy_act != YY_END_OF_BUFFER )
+			{
+			int yyl;
+			for ( yyl = 0; yyl < yyleng; ++yyl )
+				if ( yytext[yyl] == '\n' )
+					++yylineno;
+			}
+
+do_action:	/* This label is used only to access EOF actions. */
+
+
+		switch ( yy_act )
+	{ /* beginning of action switch */
+case 1:
+YY_RULE_SETUP
+#line 139 "RCOMP.LEX"
+return L_STRUCT;
+	YY_BREAK
+case 2:
+YY_RULE_SETUP
+#line 140 "RCOMP.LEX"
+return L_RESOURCE;
+	YY_BREAK
+case 3:
+YY_RULE_SETUP
+#line 141 "RCOMP.LEX"
+return L_NAME;
+	YY_BREAK
+case 4:
+YY_RULE_SETUP
+#line 142 "RCOMP.LEX"
+return L_CHARACTER_SET;
+	YY_BREAK
+case 5:
+YY_RULE_SETUP
+#line 143 "RCOMP.LEX"
+return L_OFFSET;
+	YY_BREAK
+case 6:
+YY_RULE_SETUP
+#line 144 "RCOMP.LEX"
+return L_SYSTEM;
+	YY_BREAK
+case 7:
+YY_RULE_SETUP
+#line 145 "RCOMP.LEX"
+return L_GLOBAL;
+	YY_BREAK
+case 8:
+YY_RULE_SETUP
+#line 146 "RCOMP.LEX"
+return L_LOCAL;
+	YY_BREAK
+case 9:
+YY_RULE_SETUP
+#line 147 "RCOMP.LEX"
+return L_ENUM;
+	YY_BREAK
+case 10:
+YY_RULE_SETUP
+#line 148 "RCOMP.LEX"
+return L_ENUM;
+	YY_BREAK
+case 11:
+YY_RULE_SETUP
+#line 149 "RCOMP.LEX"
+return L_UID_TWO;
+	YY_BREAK
+case 12:
+YY_RULE_SETUP
+#line 150 "RCOMP.LEX"
+return L_UID_THREE;
+	YY_BREAK
+case 13:
+YY_RULE_SETUP
+#line 151 "RCOMP.LEX"
+return L_RLS_STRING;
+	YY_BREAK
+case 14:
+YY_RULE_SETUP
+#line 152 "RCOMP.LEX"
+return L_RLS_STRING8;
+	YY_BREAK
+case 15:
+YY_RULE_SETUP
+#line 153 "RCOMP.LEX"
+return L_RLS_DOUBLE;
+	YY_BREAK
+case 16:
+YY_RULE_SETUP
+#line 154 "RCOMP.LEX"
+return L_RLS_BYTE;
+	YY_BREAK
+case 17:
+YY_RULE_SETUP
+#line 155 "RCOMP.LEX"
+return L_RLS_WORD;
+	YY_BREAK
+case 18:
+YY_RULE_SETUP
+#line 156 "RCOMP.LEX"
+return L_RLS_LONG;
+	YY_BREAK
+case 19:
+YY_RULE_SETUP
+#line 157 "RCOMP.LEX"
+return L_MULTI;
+	YY_BREAK
+/*******************************************/
+/* Types                                   */
+/*******************************************/
+case 20:
+YY_RULE_SETUP
+#line 162 "RCOMP.LEX"
+return L_BUF;
+	YY_BREAK
+case 21:
+YY_RULE_SETUP
+#line 163 "RCOMP.LEX"
+return L_BUF8;
+	YY_BREAK
+case 22:
+YY_RULE_SETUP
+#line 164 "RCOMP.LEX"
+return L_BUF16;
+	YY_BREAK
+case 23:
+YY_RULE_SETUP
+#line 165 "RCOMP.LEX"
+return L_WORD;
+	YY_BREAK
+case 24:
+YY_RULE_SETUP
+#line 166 "RCOMP.LEX"
+return L_BYTE;
+	YY_BREAK
+case 25:
+YY_RULE_SETUP
+#line 167 "RCOMP.LEX"
+return L_LONG;
+	YY_BREAK
+case 26:
+YY_RULE_SETUP
+#line 168 "RCOMP.LEX"
+return L_DOUBLE;
+	YY_BREAK
+case 27:
+YY_RULE_SETUP
+#line 169 "RCOMP.LEX"
+return L_TEXT;
+	YY_BREAK
+case 28:
+YY_RULE_SETUP
+#line 170 "RCOMP.LEX"
+return L_LTEXT;
+	YY_BREAK
+case 29:
+YY_RULE_SETUP
+#line 171 "RCOMP.LEX"
+return L_TEXT8;
+	YY_BREAK
+case 30:
+YY_RULE_SETUP
+#line 172 "RCOMP.LEX"
+return L_LTEXT8;
+	YY_BREAK
+case 31:
+YY_RULE_SETUP
+#line 173 "RCOMP.LEX"
+return L_TEXT16;
+	YY_BREAK
+case 32:
+YY_RULE_SETUP
+#line 174 "RCOMP.LEX"
+return L_LTEXT16;
+	YY_BREAK
+case 33:
+YY_RULE_SETUP
+#line 175 "RCOMP.LEX"
+return L_LINK;
+	YY_BREAK
+case 34:
+YY_RULE_SETUP
+#line 176 "RCOMP.LEX"
+return L_LLINK;
+	YY_BREAK
+case 35:
+YY_RULE_SETUP
+#line 177 "RCOMP.LEX"
+return L_SRLINK;
+	YY_BREAK
+/*******************************************/
+/* Others                                  */
+/*******************************************/
+case 36:
+YY_RULE_SETUP
+#line 183 "RCOMP.LEX"
+return L_LEN;
+	YY_BREAK
+/*******************************************/
+/* String & character literals             */
+/*******************************************/
+case 37:
+YY_RULE_SETUP
+#line 189 "RCOMP.LEX"
+{ BEGIN(string_rules); pCh = buf; isCharLiteral=0; }
+	YY_BREAK
+case 38:
+YY_RULE_SETUP
+#line 190 "RCOMP.LEX"
+{ BEGIN(string_rules); pCh = buf; isCharLiteral=1; }
+	YY_BREAK
+/* Escaped single- and double-quotes.*/
+case 39:
+YY_RULE_SETUP
+#line 193 "RCOMP.LEX"
+{ CHECK_APPEND('"'); }
+	YY_BREAK
+case 40:
+YY_RULE_SETUP
+#line 194 "RCOMP.LEX"
+{ CHECK_APPEND('\''); };
+	YY_BREAK
+/* Convert escaped character into corresponding actual character e.g. \t to tab. */
+case 41:
+YY_RULE_SETUP
+#line 197 "RCOMP.LEX"
+{ CHECK_APPEND( * ( strchr("\rr\bb\ff\nn\tt\vv\aa", yytext[1])-1));}
+	YY_BREAK
+/* Escaped backslash */
+case 42:
+YY_RULE_SETUP
+#line 200 "RCOMP.LEX"
+{ CHECK_APPEND('\\'); }
+	YY_BREAK
+case 43:
+YY_RULE_SETUP
+#line 202 "RCOMP.LEX"
+/* Escaped newline ignored*/ ;
+	YY_BREAK
+/* End of line before terminating double-quotes.*/
+case 44:
+YY_RULE_SETUP
+#line 205 "RCOMP.LEX"
+{ yyerror( isCharLiteral?"Unterminated character literal":"Unterminated string"); BEGIN 0; }
+	YY_BREAK
+/* End of string reached.*/
+case 45:
+YY_RULE_SETUP
+#line 208 "RCOMP.LEX"
+{ 
+    if (!isCharLiteral) 
+	    {
+	    *pCh = '\0'; BEGIN(0); strcpy( yylval.Value, buf); 
+		return L_STRING_LITERAL; 
+	    }
+    CHECK_APPEND(*yytext);
+    }
+	YY_BREAK
+case 46:
+YY_RULE_SETUP
+#line 217 "RCOMP.LEX"
+{ 
+    if (isCharLiteral) 
+	    {
+	    *pCh = '\0'; BEGIN(0); strcpy( yylval.Value, buf); return L_CHAR_LITERAL;
+	    }
+    CHECK_APPEND(*yytext);
+    }
+	YY_BREAK
+/* Anything other than \n is stored.*/
+case 47:
+YY_RULE_SETUP
+#line 226 "RCOMP.LEX"
+{ CHECK_APPEND(*yytext); }
+	YY_BREAK
+/*******************************************/
+/* Labels                                  */
+/*******************************************/
+case 48:
+YY_RULE_SETUP
+#line 232 "RCOMP.LEX"
+{	
+    BEGIN(0);
+    strcpy( yylval.Value, yytext);
+    return L_LABEL;
+    }
+	YY_BREAK
+/*******************************************/
+/* Numbers                                 */
+/*******************************************/
+case 49:
+YY_RULE_SETUP
+#line 241 "RCOMP.LEX"
+{	strcpy( yylval.Value, yytext); return L_NUM_NATURAL; }
+	YY_BREAK
+case 50:
+YY_RULE_SETUP
+#line 242 "RCOMP.LEX"
+{	strcpy( yylval.Value, yytext); return L_NUM_NATURAL; }
+	YY_BREAK
+case 51:
+YY_RULE_SETUP
+#line 243 "RCOMP.LEX"
+{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
+	YY_BREAK
+case 52:
+YY_RULE_SETUP
+#line 244 "RCOMP.LEX"
+{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
+	YY_BREAK
+case 53:
+YY_RULE_SETUP
+#line 245 "RCOMP.LEX"
+{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
+	YY_BREAK
+case 54:
+YY_RULE_SETUP
+#line 246 "RCOMP.LEX"
+{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
+	YY_BREAK
+case 55:
+YY_RULE_SETUP
+#line 247 "RCOMP.LEX"
+{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
+	YY_BREAK
+case 56:
+YY_RULE_SETUP
+#line 248 "RCOMP.LEX"
+{	strcpy( yylval.Value, yytext); return L_NUM_FLOAT;}
+	YY_BREAK
+/*******************************************/
+/* file_line_directive                     */
+/*******************************************/
+case 57:
+YY_RULE_SETUP
+#line 253 "RCOMP.LEX"
+{	BEGIN(file_line_rules); strcpy( RealLineNumber, yytext+2); }
+	YY_BREAK
+case 58:
+*yy_cp = yy_hold_char; /* undo effects of setting up yytext */
+yy_c_buf_p = yy_cp -= 1;
+YY_DO_BEFORE_ACTION; /* set up yytext again */
+YY_RULE_SETUP
+#line 255 "RCOMP.LEX"
+{	BEGIN(0); // # <line> "" means start of base file.
+											pFileLineHandler->SetBase( InputBaseName, * pCurrentLineNumber);
+										}
+	YY_BREAK
+case 59:
+*yy_cp = yy_hold_char; /* undo effects of setting up yytext */
+yy_c_buf_p = yy_cp -= 1;
+YY_DO_BEFORE_ACTION; /* set up yytext again */
+YY_RULE_SETUP
+#line 259 "RCOMP.LEX"
+{	BEGIN(0); // # <line> <filename> means @ line <line> of named base file.
+											pFileLineHandler->PostInclude( yytext, RealLineNumber, * pCurrentLineNumber);
+										}
+	YY_BREAK
+case 60:
+*yy_cp = yy_hold_char; /* undo effects of setting up yytext */
+yy_c_buf_p = yy_cp -= 1;
+YY_DO_BEFORE_ACTION; /* set up yytext again */
+YY_RULE_SETUP
+#line 263 "RCOMP.LEX"
+{
+											BEGIN(0); // # <line> <filename> 1 means start of an included file.
+											pFileLineHandler->SetInclude( yytext, * pCurrentLineNumber);
+										}
+	YY_BREAK
+case 61:
+*yy_cp = yy_hold_char; /* undo effects of setting up yytext */
+yy_c_buf_p = yy_cp -= 1;
+YY_DO_BEFORE_ACTION; /* set up yytext again */
+YY_RULE_SETUP
+#line 268 "RCOMP.LEX"
+{
+											BEGIN(0); // # <line> <filename> 2 means end of an included file and now at <line> in <filename>.
+											pFileLineHandler->PostInclude( yytext, RealLineNumber, * pCurrentLineNumber);
+										}
+	YY_BREAK
+/*******************************************/
+/* White space                             */
+/*******************************************/
+case 62:
+YY_RULE_SETUP
+#line 278 "RCOMP.LEX"
+; // skipped
+	YY_BREAK
+case 63:
+YY_RULE_SETUP
+#line 279 "RCOMP.LEX"
+; // skipped
+	YY_BREAK
+case 64:
+YY_RULE_SETUP
+#line 280 "RCOMP.LEX"
+; // skipped
+	YY_BREAK
+case 65:
+YY_RULE_SETUP
+#line 281 "RCOMP.LEX"
+{ BEGIN(cpp_comment); }
+	YY_BREAK
+case 66:
+YY_RULE_SETUP
+#line 282 "RCOMP.LEX"
+{ BEGIN(0); }
+	YY_BREAK
+case 67:
+YY_RULE_SETUP
+#line 283 "RCOMP.LEX"
+;			// skipped
+	YY_BREAK
+case 68:
+*yy_cp = yy_hold_char; /* undo effects of setting up yytext */
+yy_c_buf_p = yy_cp = yy_bp + 2;
+YY_DO_BEFORE_ACTION; /* set up yytext again */
+YY_RULE_SETUP
+#line 284 "RCOMP.LEX"
+{ BEGIN(c_comment); }
+	YY_BREAK
+case 69:
+YY_RULE_SETUP
+#line 285 "RCOMP.LEX"
+{ BEGIN(c_comment); }
+	YY_BREAK
+case 70:
+YY_RULE_SETUP
+#line 286 "RCOMP.LEX"
+{ BEGIN(0); }
+	YY_BREAK
+case 71:
+YY_RULE_SETUP
+#line 287 "RCOMP.LEX"
+; // skipped
+	YY_BREAK
+case 72:
+YY_RULE_SETUP
+#line 288 "RCOMP.LEX"
+; // skipped
+	YY_BREAK
+/*******************************************/
+/* Comment tags                            */
+/*******************************************/
+case 73:
+YY_RULE_SETUP
+#line 294 "RCOMP.LEX"
+{ 
+										BEGIN(comment_tag);
+										pGL->SetStart(*(pFileLineHandler->GetCurrentFile()), pFileLineHandler->GetErrorLine(* pCurrentLineNumber));
+										return L_TAG_START; 
+										}	// any comment beginning with a slash followed by a star followed by an ampersand
+	YY_BREAK
+case 74:
+YY_RULE_SETUP
+#line 299 "RCOMP.LEX"
+{ 
+										BEGIN(0); 
+										return L_TAG_END; 
+										}
+	YY_BREAK
+case 75:
+YY_RULE_SETUP
+#line 303 "RCOMP.LEX"
+{ strcpy( yylval.Value, yytext);	return L_TAG_COMMAND; }
+	YY_BREAK
+case 76:
+YY_RULE_SETUP
+#line 304 "RCOMP.LEX"
+{ strcpy( yylval.Value, yytext);	return L_TAG_WORD; }
+	YY_BREAK
+case 77:
+YY_RULE_SETUP
+#line 305 "RCOMP.LEX"
+{ strcpy( yylval.Value, "\n");		return L_TAG_NEW_LINE; }
+	YY_BREAK
+case 78:
+YY_RULE_SETUP
+#line 306 "RCOMP.LEX"
+;
+	YY_BREAK
+/*******************************************/
+/* Special single characters               */
+/*******************************************/
+case 79:
+YY_RULE_SETUP
+#line 311 "RCOMP.LEX"
+return * yytext;
+	YY_BREAK
+/*******************************************/
+/* Everything else cannot be recognised    */
+/*******************************************/
+case 80:
+YY_RULE_SETUP
+#line 317 "RCOMP.LEX"
+{ yyerror("*** Unknown character '%c' (value 0x%x) ", *yytext, *yytext);}
+	YY_BREAK
+case 81:
+YY_RULE_SETUP
+#line 318 "RCOMP.LEX"
+ECHO;
+	YY_BREAK
+#line 1503 "lex.yy.c"
+			case YY_STATE_EOF(INITIAL):
+			case YY_STATE_EOF(string_rules):
+			case YY_STATE_EOF(file_line_rules):
+			case YY_STATE_EOF(cpp_comment):
+			case YY_STATE_EOF(c_comment):
+			case YY_STATE_EOF(comment_tag):
+				yyterminate();
+
+	case YY_END_OF_BUFFER:
+		{
+		/* Amount of text matched not including the EOB char. */
+		int yy_amount_of_matched_text = (int) (yy_cp - yytext_ptr) - 1;
+
+		/* Undo the effects of YY_DO_BEFORE_ACTION. */
+		*yy_cp = yy_hold_char;
+		YY_RESTORE_YY_MORE_OFFSET
+
+		if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_NEW )
+			{
+			/* We're scanning a new file or input source.  It's
+			 * possible that this happened because the user
+			 * just pointed yyin at a new source and called
+			 * yylex().  If so, then we have to assure
+			 * consistency between yy_current_buffer and our
+			 * globals.  Here is the right place to do so, because
+			 * this is the first action (other than possibly a
+			 * back-up) that will match for the new input source.
+			 */
+			yy_n_chars = yy_current_buffer->yy_n_chars;
+			yy_current_buffer->yy_input_file = yyin;
+			yy_current_buffer->yy_buffer_status = YY_BUFFER_NORMAL;
+			}
+
+		/* Note that here we test for yy_c_buf_p "<=" to the position
+		 * of the first EOB in the buffer, since yy_c_buf_p will
+		 * already have been incremented past the NUL character
+		 * (since all states make transitions on EOB to the
+		 * end-of-buffer state).  Contrast this with the test
+		 * in input().
+		 */
+		if ( yy_c_buf_p <= &yy_current_buffer->yy_ch_buf[yy_n_chars] )
+			{ /* This was really a NUL. */
+			yy_state_type yy_next_state;
+
+			yy_c_buf_p = yytext_ptr + yy_amount_of_matched_text;
+
+			yy_current_state = yy_get_previous_state();
+
+			/* Okay, we're now positioned to make the NUL
+			 * transition.  We couldn't have
+			 * yy_get_previous_state() go ahead and do it
+			 * for us because it doesn't know how to deal
+			 * with the possibility of jamming (and we don't
+			 * want to build jamming into it because then it
+			 * will run more slowly).
+			 */
+
+			yy_next_state = yy_try_NUL_trans( yy_current_state );
+
+			yy_bp = yytext_ptr + YY_MORE_ADJ;
+
+			if ( yy_next_state )
+				{
+				/* Consume the NUL. */
+				yy_cp = ++yy_c_buf_p;
+				yy_current_state = yy_next_state;
+				goto yy_match;
+				}
+
+			else
+				{
+				yy_cp = yy_c_buf_p;
+				goto yy_find_action;
+				}
+			}
+
+		else switch ( yy_get_next_buffer() )
+			{
+			case EOB_ACT_END_OF_FILE:
+				{
+				yy_did_buffer_switch_on_eof = 0;
+
+				if ( yywrap() )
+					{
+					/* Note: because we've taken care in
+					 * yy_get_next_buffer() to have set up
+					 * yytext, we can now set up
+					 * yy_c_buf_p so that if some total
+					 * hoser (like flex itself) wants to
+					 * call the scanner after we return the
+					 * YY_NULL, it'll still work - another
+					 * YY_NULL will get returned.
+					 */
+					yy_c_buf_p = yytext_ptr + YY_MORE_ADJ;
+
+					yy_act = YY_STATE_EOF(YY_START);
+					goto do_action;
+					}
+
+				else
+					{
+					if ( ! yy_did_buffer_switch_on_eof )
+						YY_NEW_FILE;
+					}
+				break;
+				}
+
+			case EOB_ACT_CONTINUE_SCAN:
+				yy_c_buf_p =
+					yytext_ptr + yy_amount_of_matched_text;
+
+				yy_current_state = yy_get_previous_state();
+
+				yy_cp = yy_c_buf_p;
+				yy_bp = yytext_ptr + YY_MORE_ADJ;
+				goto yy_match;
+
+			case EOB_ACT_LAST_MATCH:
+				yy_c_buf_p =
+				&yy_current_buffer->yy_ch_buf[yy_n_chars];
+
+				yy_current_state = yy_get_previous_state();
+
+				yy_cp = yy_c_buf_p;
+				yy_bp = yytext_ptr + YY_MORE_ADJ;
+				goto yy_find_action;
+			}
+		break;
+		}
+
+	default:
+		YY_FATAL_ERROR(
+			"fatal flex scanner internal error--no action found" );
+	} /* end of action switch */
+		} /* end of scanning one token */
+	} /* end of yylex */
+
+
+/* yy_get_next_buffer - try to read in a new buffer
+ *
+ * Returns a code representing an action:
+ *	EOB_ACT_LAST_MATCH -
+ *	EOB_ACT_CONTINUE_SCAN - continue scanning from current position
+ *	EOB_ACT_END_OF_FILE - end of file
+ */
+
+static int yy_get_next_buffer()
+	{
+	register char *dest = yy_current_buffer->yy_ch_buf;
+	register char *source = yytext_ptr;
+	register int number_to_move, i;
+	int ret_val;
+
+	if ( yy_c_buf_p > &yy_current_buffer->yy_ch_buf[yy_n_chars + 1] )
+		YY_FATAL_ERROR(
+		"fatal flex scanner internal error--end of buffer missed" );
+
+	if ( yy_current_buffer->yy_fill_buffer == 0 )
+		{ /* Don't try to fill the buffer, so this is an EOF. */
+		if ( yy_c_buf_p - yytext_ptr - YY_MORE_ADJ == 1 )
+			{
+			/* We matched a single character, the EOB, so
+			 * treat this as a final EOF.
+			 */
+			return EOB_ACT_END_OF_FILE;
+			}
+
+		else
+			{
+			/* We matched some text prior to the EOB, first
+			 * process it.
+			 */
+			return EOB_ACT_LAST_MATCH;
+			}
+		}
+
+	/* Try to read more data. */
+
+	/* First move last chars to start of buffer. */
+	number_to_move = (int) (yy_c_buf_p - yytext_ptr) - 1;
+
+	for ( i = 0; i < number_to_move; ++i )
+		*(dest++) = *(source++);
+
+	if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_EOF_PENDING )
+		/* don't do the read, it's not guaranteed to return an EOF,
+		 * just force an EOF
+		 */
+		yy_current_buffer->yy_n_chars = yy_n_chars = 0;
+
+	else
+		{
+		int num_to_read =
+			yy_current_buffer->yy_buf_size - number_to_move - 1;
+
+		while ( num_to_read <= 0 )
+			{ /* Not enough room in the buffer - grow it. */
+#ifdef YY_USES_REJECT
+			YY_FATAL_ERROR(
+"input buffer overflow, can't enlarge buffer because scanner uses REJECT" );
+#else
+
+			/* just a shorter name for the current buffer */
+			YY_BUFFER_STATE b = yy_current_buffer;
+
+			int yy_c_buf_p_offset =
+				(int) (yy_c_buf_p - b->yy_ch_buf);
+
+			if ( b->yy_is_our_buffer )
+				{
+				int new_size = b->yy_buf_size * 2;
+
+				if ( new_size <= 0 )
+					b->yy_buf_size += b->yy_buf_size / 8;
+				else
+					b->yy_buf_size *= 2;
+
+				b->yy_ch_buf = (char *)
+					/* Include room in for 2 EOB chars. */
+					yy_flex_realloc( (void *) b->yy_ch_buf,
+							 b->yy_buf_size + 2 );
+				}
+			else
+				/* Can't grow it, we don't own it. */
+				b->yy_ch_buf = 0;
+
+			if ( ! b->yy_ch_buf )
+				YY_FATAL_ERROR(
+				"fatal error - scanner input buffer overflow" );
+
+			yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset];
+
+			num_to_read = yy_current_buffer->yy_buf_size -
+						number_to_move - 1;
+#endif
+			}
+
+		if ( num_to_read > YY_READ_BUF_SIZE )
+			num_to_read = YY_READ_BUF_SIZE;
+
+		/* Read in more data. */
+		YY_INPUT( (&yy_current_buffer->yy_ch_buf[number_to_move]),
+			yy_n_chars, num_to_read );
+
+		yy_current_buffer->yy_n_chars = yy_n_chars;
+		}
+
+	if ( yy_n_chars == 0 )
+		{
+		if ( number_to_move == YY_MORE_ADJ )
+			{
+			ret_val = EOB_ACT_END_OF_FILE;
+			yyrestart( yyin );
+			}
+
+		else
+			{
+			ret_val = EOB_ACT_LAST_MATCH;
+			yy_current_buffer->yy_buffer_status =
+				YY_BUFFER_EOF_PENDING;
+			}
+		}
+
+	else
+		ret_val = EOB_ACT_CONTINUE_SCAN;
+
+	yy_n_chars += number_to_move;
+	yy_current_buffer->yy_ch_buf[yy_n_chars] = YY_END_OF_BUFFER_CHAR;
+	yy_current_buffer->yy_ch_buf[yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR;
+
+	yytext_ptr = &yy_current_buffer->yy_ch_buf[0];
+
+	return ret_val;
+	}
+
+
+/* yy_get_previous_state - get the state just before the EOB char was reached */
+
+static yy_state_type yy_get_previous_state()
+	{
+	register yy_state_type yy_current_state;
+	register char *yy_cp;
+
+	yy_current_state = yy_start;
+	yy_state_ptr = yy_state_buf;
+	*yy_state_ptr++ = yy_current_state;
+
+	for ( yy_cp = yytext_ptr + YY_MORE_ADJ; yy_cp < yy_c_buf_p; ++yy_cp )
+		{
+		register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
+		while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+			{
+			yy_current_state = (int) yy_def[yy_current_state];
+			if ( yy_current_state >= 269 )
+				yy_c = yy_meta[(unsigned int) yy_c];
+			}
+		yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
+		*yy_state_ptr++ = yy_current_state;
+		}
+
+	return yy_current_state;
+	}
+
+
+/* yy_try_NUL_trans - try to make a transition on the NUL character
+ *
+ * synopsis
+ *	next_state = yy_try_NUL_trans( current_state );
+ */
+
+#ifdef YY_USE_PROTOS
+static yy_state_type yy_try_NUL_trans( yy_state_type yy_current_state )
+#else
+static yy_state_type yy_try_NUL_trans( yy_current_state )
+yy_state_type yy_current_state;
+#endif
+	{
+	register int yy_is_jam;
+
+	register YY_CHAR yy_c = 1;
+	while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+		{
+		yy_current_state = (int) yy_def[yy_current_state];
+		if ( yy_current_state >= 269 )
+			yy_c = yy_meta[(unsigned int) yy_c];
+		}
+	yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
+	yy_is_jam = (yy_current_state == 268);
+	if ( ! yy_is_jam )
+		*yy_state_ptr++ = yy_current_state;
+
+	return yy_is_jam ? 0 : yy_current_state;
+	}
+
+
+#ifndef YY_NO_UNPUT
+#ifdef YY_USE_PROTOS
+static void yyunput( int c, register char *yy_bp )
+#else
+static void yyunput( c, yy_bp )
+int c;
+register char *yy_bp;
+#endif
+	{
+	register char *yy_cp = yy_c_buf_p;
+
+	/* undo effects of setting up yytext */
+	*yy_cp = yy_hold_char;
+
+	if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 )
+		{ /* need to shift things up to make room */
+		/* +2 for EOB chars. */
+		register int number_to_move = yy_n_chars + 2;
+		register char *dest = &yy_current_buffer->yy_ch_buf[
+					yy_current_buffer->yy_buf_size + 2];
+		register char *source =
+				&yy_current_buffer->yy_ch_buf[number_to_move];
+
+		while ( source > yy_current_buffer->yy_ch_buf )
+			*--dest = *--source;
+
+		yy_cp += (int) (dest - source);
+		yy_bp += (int) (dest - source);
+		yy_current_buffer->yy_n_chars =
+			yy_n_chars = yy_current_buffer->yy_buf_size;
+
+		if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 )
+			YY_FATAL_ERROR( "flex scanner push-back overflow" );
+		}
+
+	*--yy_cp = (char) c;
+
+	if ( c == '\n' )
+		--yylineno;
+
+	yytext_ptr = yy_bp;
+	yy_hold_char = *yy_cp;
+	yy_c_buf_p = yy_cp;
+	}
+#endif	/* ifndef YY_NO_UNPUT */
+
+
+#ifdef __cplusplus
+static int yyinput()
+#else
+static int input()
+#endif
+	{
+	int c;
+
+	*yy_c_buf_p = yy_hold_char;
+
+	if ( *yy_c_buf_p == YY_END_OF_BUFFER_CHAR )
+		{
+		/* yy_c_buf_p now points to the character we want to return.
+		 * If this occurs *before* the EOB characters, then it's a
+		 * valid NUL; if not, then we've hit the end of the buffer.
+		 */
+		if ( yy_c_buf_p < &yy_current_buffer->yy_ch_buf[yy_n_chars] )
+			/* This was really a NUL. */
+			*yy_c_buf_p = '\0';
+
+		else
+			{ /* need more input */
+			int offset = yy_c_buf_p - yytext_ptr;
+			++yy_c_buf_p;
+
+			switch ( yy_get_next_buffer() )
+				{
+				case EOB_ACT_LAST_MATCH:
+					/* This happens because yy_g_n_b()
+					 * sees that we've accumulated a
+					 * token and flags that we need to
+					 * try matching the token before
+					 * proceeding.  But for input(),
+					 * there's no matching to consider.
+					 * So convert the EOB_ACT_LAST_MATCH
+					 * to EOB_ACT_END_OF_FILE.
+					 */
+
+					/* Reset buffer status. */
+					yyrestart( yyin );
+
+					/* fall through */
+
+				case EOB_ACT_END_OF_FILE:
+					{
+					if ( yywrap() )
+						return EOF;
+
+					if ( ! yy_did_buffer_switch_on_eof )
+						YY_NEW_FILE;
+#ifdef __cplusplus
+					return yyinput();
+#else
+					return input();
+#endif
+					}
+
+				case EOB_ACT_CONTINUE_SCAN:
+					yy_c_buf_p = yytext_ptr + offset;
+					break;
+				}
+			}
+		}
+
+	c = *(unsigned char *) yy_c_buf_p;	/* cast for 8-bit char's */
+	*yy_c_buf_p = '\0';	/* preserve yytext */
+	yy_hold_char = *++yy_c_buf_p;
+
+	if ( c == '\n' )
+		++yylineno;
+
+	return c;
+	}
+
+
+#ifdef YY_USE_PROTOS
+void yyrestart( FILE *input_file )
+#else
+void yyrestart( input_file )
+FILE *input_file;
+#endif
+	{
+	if ( ! yy_current_buffer )
+		yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE );
+
+	yy_init_buffer( yy_current_buffer, input_file );
+	yy_load_buffer_state();
+	}
+
+
+#ifdef YY_USE_PROTOS
+void yy_switch_to_buffer( YY_BUFFER_STATE new_buffer )
+#else
+void yy_switch_to_buffer( new_buffer )
+YY_BUFFER_STATE new_buffer;
+#endif
+	{
+	if ( yy_current_buffer == new_buffer )
+		return;
+
+	if ( yy_current_buffer )
+		{
+		/* Flush out information for old buffer. */
+		*yy_c_buf_p = yy_hold_char;
+		yy_current_buffer->yy_buf_pos = yy_c_buf_p;
+		yy_current_buffer->yy_n_chars = yy_n_chars;
+		}
+
+	yy_current_buffer = new_buffer;
+	yy_load_buffer_state();
+
+	/* We don't actually know whether we did this switch during
+	 * EOF (yywrap()) processing, but the only time this flag
+	 * is looked at is after yywrap() is called, so it's safe
+	 * to go ahead and always set it.
+	 */
+	yy_did_buffer_switch_on_eof = 1;
+	}
+
+
+#ifdef YY_USE_PROTOS
+void yy_load_buffer_state( void )
+#else
+void yy_load_buffer_state()
+#endif
+	{
+	yy_n_chars = yy_current_buffer->yy_n_chars;
+	yytext_ptr = yy_c_buf_p = yy_current_buffer->yy_buf_pos;
+	yyin = yy_current_buffer->yy_input_file;
+	yy_hold_char = *yy_c_buf_p;
+	}
+
+
+#ifdef YY_USE_PROTOS
+YY_BUFFER_STATE yy_create_buffer( FILE *file, int size )
+#else
+YY_BUFFER_STATE yy_create_buffer( file, size )
+FILE *file;
+int size;
+#endif
+	{
+	YY_BUFFER_STATE b;
+
+	b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) );
+	if ( ! b )
+		YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
+
+	b->yy_buf_size = size;
+
+	/* yy_ch_buf has to be 2 characters longer than the size given because
+	 * we need to put in 2 end-of-buffer characters.
+	 */
+	b->yy_ch_buf = (char *) yy_flex_alloc( b->yy_buf_size + 2 );
+	if ( ! b->yy_ch_buf )
+		YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
+
+	b->yy_is_our_buffer = 1;
+
+	yy_init_buffer( b, file );
+
+	return b;
+	}
+
+
+#ifdef YY_USE_PROTOS
+void yy_delete_buffer( YY_BUFFER_STATE b )
+#else
+void yy_delete_buffer( b )
+YY_BUFFER_STATE b;
+#endif
+	{
+	if ( ! b )
+		return;
+
+	if ( b == yy_current_buffer )
+		yy_current_buffer = (YY_BUFFER_STATE) 0;
+
+	if ( b->yy_is_our_buffer )
+		yy_flex_free( (void *) b->yy_ch_buf );
+
+	yy_flex_free( (void *) b );
+	}
+
+
+#ifndef YY_ALWAYS_INTERACTIVE
+#ifndef YY_NEVER_INTERACTIVE
+extern int isatty YY_PROTO(( int ));
+#endif
+#endif
+
+#ifdef YY_USE_PROTOS
+void yy_init_buffer( YY_BUFFER_STATE b, FILE *file )
+#else
+void yy_init_buffer( b, file )
+YY_BUFFER_STATE b;
+FILE *file;
+#endif
+
+
+	{
+	yy_flush_buffer( b );
+
+	b->yy_input_file = file;
+	b->yy_fill_buffer = 1;
+
+#if YY_ALWAYS_INTERACTIVE
+	b->yy_is_interactive = 1;
+#else
+#if YY_NEVER_INTERACTIVE
+	b->yy_is_interactive = 0;
+#else
+	b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
+#endif
+#endif
+	}
+
+
+#ifdef YY_USE_PROTOS
+void yy_flush_buffer( YY_BUFFER_STATE b )
+#else
+void yy_flush_buffer( b )
+YY_BUFFER_STATE b;
+#endif
+
+	{
+	if ( ! b )
+		return;
+
+	b->yy_n_chars = 0;
+
+	/* We always need two end-of-buffer characters.  The first causes
+	 * a transition to the end-of-buffer state.  The second causes
+	 * a jam in that state.
+	 */
+	b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
+	b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
+
+	b->yy_buf_pos = &b->yy_ch_buf[0];
+
+	b->yy_at_bol = 1;
+	b->yy_buffer_status = YY_BUFFER_NEW;
+
+	if ( b == yy_current_buffer )
+		yy_load_buffer_state();
+	}
+
+
+#ifndef YY_NO_SCAN_BUFFER
+#ifdef YY_USE_PROTOS
+YY_BUFFER_STATE yy_scan_buffer( char *base, yy_size_t size )
+#else
+YY_BUFFER_STATE yy_scan_buffer( base, size )
+char *base;
+yy_size_t size;
+#endif
+	{
+	YY_BUFFER_STATE b;
+
+	if ( size < 2 ||
+	     base[size-2] != YY_END_OF_BUFFER_CHAR ||
+	     base[size-1] != YY_END_OF_BUFFER_CHAR )
+		/* They forgot to leave room for the EOB's. */
+		return 0;
+
+	b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) );
+	if ( ! b )
+		YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
+
+	b->yy_buf_size = size - 2;	/* "- 2" to take care of EOB's */
+	b->yy_buf_pos = b->yy_ch_buf = base;
+	b->yy_is_our_buffer = 0;
+	b->yy_input_file = 0;
+	b->yy_n_chars = b->yy_buf_size;
+	b->yy_is_interactive = 0;
+	b->yy_at_bol = 1;
+	b->yy_fill_buffer = 0;
+	b->yy_buffer_status = YY_BUFFER_NEW;
+
+	yy_switch_to_buffer( b );
+
+	return b;
+	}
+#endif
+
+
+#ifndef YY_NO_SCAN_STRING
+#ifdef YY_USE_PROTOS
+YY_BUFFER_STATE yy_scan_string( yyconst char *yy_str )
+#else
+YY_BUFFER_STATE yy_scan_string( yy_str )
+yyconst char *yy_str;
+#endif
+	{
+	int len;
+	for ( len = 0; yy_str[len]; ++len )
+		;
+
+	return yy_scan_bytes( yy_str, len );
+	}
+#endif
+
+
+#ifndef YY_NO_SCAN_BYTES
+#ifdef YY_USE_PROTOS
+YY_BUFFER_STATE yy_scan_bytes( yyconst char *bytes, int len )
+#else
+YY_BUFFER_STATE yy_scan_bytes( bytes, len )
+yyconst char *bytes;
+int len;
+#endif
+	{
+	YY_BUFFER_STATE b;
+	char *buf;
+	yy_size_t n;
+	int i;
+
+	/* Get memory for full buffer, including space for trailing EOB's. */
+	n = len + 2;
+	buf = (char *) yy_flex_alloc( n );
+	if ( ! buf )
+		YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
+
+	for ( i = 0; i < len; ++i )
+		buf[i] = bytes[i];
+
+	buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR;
+
+	b = yy_scan_buffer( buf, n );
+	if ( ! b )
+		YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
+
+	/* It's okay to grow etc. this buffer, and we should throw it
+	 * away when we're done.
+	 */
+	b->yy_is_our_buffer = 1;
+
+	return b;
+	}
+#endif
+
+
+#ifndef YY_NO_PUSH_STATE
+#ifdef YY_USE_PROTOS
+static void yy_push_state( int new_state )
+#else
+static void yy_push_state( new_state )
+int new_state;
+#endif
+	{
+	if ( yy_start_stack_ptr >= yy_start_stack_depth )
+		{
+		yy_size_t new_size;
+
+		yy_start_stack_depth += YY_START_STACK_INCR;
+		new_size = yy_start_stack_depth * sizeof( int );
+
+		if ( ! yy_start_stack )
+			yy_start_stack = (int *) yy_flex_alloc( new_size );
+
+		else
+			yy_start_stack = (int *) yy_flex_realloc(
+					(void *) yy_start_stack, new_size );
+
+		if ( ! yy_start_stack )
+			YY_FATAL_ERROR(
+			"out of memory expanding start-condition stack" );
+		}
+
+	yy_start_stack[yy_start_stack_ptr++] = YY_START;
+
+	BEGIN(new_state);
+	}
+#endif
+
+
+#ifndef YY_NO_POP_STATE
+static void yy_pop_state()
+	{
+	if ( --yy_start_stack_ptr < 0 )
+		YY_FATAL_ERROR( "start-condition stack underflow" );
+
+	BEGIN(yy_start_stack[yy_start_stack_ptr]);
+	}
+#endif
+
+
+#ifndef YY_NO_TOP_STATE
+static int yy_top_state()
+	{
+	return yy_start_stack[yy_start_stack_ptr - 1];
+	}
+#endif
+
+#ifndef YY_EXIT_FAILURE
+#define YY_EXIT_FAILURE 2
+#endif
+
+#ifdef YY_USE_PROTOS
+static void yy_fatal_error( yyconst char msg[] )
+#else
+static void yy_fatal_error( msg )
+char msg[];
+#endif
+	{
+	(void) fprintf( stderr, "%s\n", msg );
+	exit( YY_EXIT_FAILURE );
+	}
+
+
+
+/* Redefine yyless() so it works in section 3 code. */
+
+#undef yyless
+#define yyless(n) \
+	do \
+		{ \
+		/* Undo effects of setting up yytext. */ \
+		yytext[yyleng] = yy_hold_char; \
+		yy_c_buf_p = yytext + n; \
+		yy_hold_char = *yy_c_buf_p; \
+		*yy_c_buf_p = '\0'; \
+		yyleng = n; \
+		} \
+	while ( 0 )
+
+
+/* Internal utility routines. */
+
+#ifndef yytext_ptr
+#ifdef YY_USE_PROTOS
+static void yy_flex_strncpy( char *s1, yyconst char *s2, int n )
+#else
+static void yy_flex_strncpy( s1, s2, n )
+char *s1;
+yyconst char *s2;
+int n;
+#endif
+	{
+	register int i;
+	for ( i = 0; i < n; ++i )
+		s1[i] = s2[i];
+	}
+#endif
+
+#ifdef YY_NEED_STRLEN
+#ifdef YY_USE_PROTOS
+static int yy_flex_strlen( yyconst char *s )
+#else
+static int yy_flex_strlen( s )
+yyconst char *s;
+#endif
+	{
+	register int n;
+	for ( n = 0; s[n]; ++n )
+		;
+
+	return n;
+	}
+#endif
+
+
+#ifdef YY_USE_PROTOS
+static void *yy_flex_alloc( yy_size_t size )
+#else
+static void *yy_flex_alloc( size )
+yy_size_t size;
+#endif
+	{
+	return (void *) malloc( size );
+	}
+
+#ifdef YY_USE_PROTOS
+static void *yy_flex_realloc( void *ptr, yy_size_t size )
+#else
+static void *yy_flex_realloc( ptr, size )
+void *ptr;
+yy_size_t size;
+#endif
+	{
+	/* The cast to (char *) in the following accommodates both
+	 * implementations that use char* generic pointers, and those
+	 * that use void* generic pointers.  It works with the latter
+	 * because both ANSI C and C++ allow castless assignment from
+	 * any pointer type to void*, and deal with argument conversions
+	 * as though doing an assignment.
+	 */
+	return (void *) realloc( (char *) ptr, size );
+	}
+
+#ifdef YY_USE_PROTOS
+static void yy_flex_free( void *ptr )
+#else
+static void yy_flex_free( ptr )
+void *ptr;
+#endif
+	{
+	free( ptr );
+	}
+
+#if YY_MAIN
+int main()
+	{
+	yylex();
+	return 0;
+	}
+#endif
+#line 318 "RCOMP.LEX"
--- a/e32tools/e32lib/group/bld.inf	Fri Jun 25 20:58:33 2010 +0800
+++ b/e32tools/e32lib/group/bld.inf	Tue Jun 29 14:52:54 2010 +0800
@@ -14,8 +14,12 @@
 //
 
 PRJ_PLATFORMS
-TOOLS2
+TOOLS TOOLS2
+
+PRJ_EXPORTS
+../seclib/seclib.h				SYMBIAN_OS_LAYER_PLATFORM_EXPORT_PATH(seclib.h)
 
 PRJ_MMPFILES
-seclib
+seclib.mmp
 
+
--- a/e32tools/e32lib/group/e32lib.mrp	Fri Jun 25 20:58:33 2010 +0800
+++ b/e32tools/e32lib/group/e32lib.mrp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,7 +1,8 @@
 component       dev_build_e32tools_e32lib
 
-source          /src/tools/dev/build/e32tools/e32lib
-binary          /src/tools/dev/build/e32tools/e32lib/group all
+source          /src/tools/build/e32tools/e32lib
+binary          /src/tools/build/e32tools/e32lib/group all
+exports         /src/tools/build/e32tools/e32lib/group
 
 notes_source    release.txt
 
--- a/e32tools/e32lib/group/release.txt	Fri Jun 25 20:58:33 2010 +0800
+++ b/e32tools/e32lib/group/release.txt	Tue Jun 29 14:52:54 2010 +0800
@@ -3,3 +3,8 @@
 
 NOTESRC_RELEASE_REASON
 Seclib Release
+
+version ??
+===============
+Released by Zheng Shen, 22/02/2010
+	1) DPDEF144562	Build Tools cannot be built in Linux
--- a/e32tools/e32lib/group/seclib.mmp	Fri Jun 25 20:58:33 2010 +0800
+++ b/e32tools/e32lib/group/seclib.mmp	Tue Jun 29 14:52:54 2010 +0800
@@ -23,10 +23,10 @@
 sourcepath		../seclib
 source			seclib.cpp
 
-sourcepath		../e32image
+sourcepath		../../../imgtools/imglib/e32image
 source			e32image.cpp
 
-sourcepath		../e32image/deflate
+sourcepath		../../../imgtools/imglib/e32image/deflate
 source			decode.cpp encode.cpp deflate.cpp inflate.cpp panic.cpp compress.cpp
 
 sourcepath      ../../../imgtools/imglib/compress
@@ -42,9 +42,11 @@
 source			h_file.cpp h_mem.cpp h_utl.cpp
 
 userinclude     ../../../imgtools/imglib/compress
+userinclude     ../../../imgtools/imglib/inc
 userinclude     ../setcap 
-userinclude     ../../e32lib/e32image/inc
-systeminclude   /epoc32/include
+userinclude     ../seclib
+
+OS_LAYER_SYSTEMINCLUDE_SYMBIAN
 
 OPTION          GCC -w
 
--- a/e32tools/e32lib/seclib/seclib.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/e32tools/e32lib/seclib/seclib.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -18,7 +18,7 @@
 
 #include <e32cmn.h>
 #include <e32ldr.h>
-#include <seclib.h>
+#include "seclib.h"
 
 #include "e32image.h"
 #include "h_utl.h"
--- a/e32tools/e32lib/setcap/setcap.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/e32tools/e32lib/setcap/setcap.h	Tue Jun 29 14:52:54 2010 +0800
@@ -17,8 +17,11 @@
 
 #ifndef __SETCAP_H__
 // We need to build for both TOOLS2 and TOOLS for the moment
-#if !defined(__TOOLS2_LINUX__)
+#ifdef WIN32
 #include <e32wins.h>
+#ifdef _STLP_INTERNAL_WINDOWS_H
+#define __INTERLOCKED_DECLARED
+#endif
 #include <emulator.h>
 #endif
 #include <stdlib.h>
--- a/e32tools/elf2e32/group/elf2e32.mmp	Fri Jun 25 20:58:33 2010 +0800
+++ b/e32tools/elf2e32/group/elf2e32.mmp	Tue Jun 29 14:52:54 2010 +0800
@@ -19,17 +19,23 @@
 
 sourcepath	../source
 source 	    deffile.cpp  deflatecompress.cpp  dll_fb_target.cpp  dll_rebuild_target.cpp  e32exporttable.cpp 
-source	 	filedump.cpp  e32imagefile.cpp elf2e32.cpp  elffilesupplied.cpp errorhandler.cpp exetarget.cpp exexp_fb_target.cpp 
-source	 	exexp_rebuild_target.cpp  export_type_fb_target.cpp  export_type_rebuild_target.cpp  export_type_target.cpp  h_utl.cpp 
+source	 	filedump.cpp  elf2e32.cpp  elffilesupplied.cpp errorhandler.cpp exetarget.cpp exexp_fb_target.cpp 
+source	 	exexp_rebuild_target.cpp  export_type_fb_target.cpp  export_type_rebuild_target.cpp  export_type_target.cpp 
 source	 	huffman.cpp  imgdump.cpp  inflate.cpp  librarytarget.cpp  main.cpp  messagehandler.cpp  messageimplementation.cpp 
 source	 	parameterlistinterface.cpp  parametermanager.cpp  pl_common.cpp  pl_dllsymbol.cpp 	pl_dso_handler.cpp  pl_elfconsumer.cpp 
 source	 	pl_elfexecutable.cpp  pl_elfexports.cpp  pl_elfimportrelocation.cpp  pl_elfimports.cpp  pl_elflocalrelocation.cpp  pl_elfproducer.cpp 
 source	 	pl_elfrelocation.cpp  pl_elfrelocations.cpp  pl_symbol.cpp  polydll_fb_target.cpp  polydll_rebuild_target.cpp  usecasebase.cpp 
-source	 	byte_pair.cpp  pagedcompress.cpp checksum.cpp stdexe_target.cpp
+source	 	checksum.cpp stdexe_target.cpp e32imagefile.cpp
 
-systeminclude    /epoc32/include  /epoc32/include/tools  
-userinclude		../source ../include
+sourcepath ../../../imgtools/imglib/host
+source	 	h_utl.cpp
+sourcepath ../../../imgtools/imglib/compress
+source	 	byte_pair.cpp pagedcompress.cpp
 
-option 	GCC -w
+userinclude		../source ../include ../../../bintools/elftools/inc
+userinclude   ../../../imgtools/imglib/compress ../../../imgtools/imglib/inc
+OS_LAYER_SYSTEMINCLUDE_SYMBIAN
+
+option 	GCC -O2 -w
 
 VENDORID 0x70000001
--- a/e32tools/elf2e32/group/elf2e32.mrp	Fri Jun 25 20:58:33 2010 +0800
+++ b/e32tools/elf2e32/group/elf2e32.mrp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,7 +1,7 @@
 component       dev_build_e32tools_elf2e32
 
-source          /src/tools/dev/build/e32tools/elf2e32
-binary          /src/tools/dev/build/e32tools/elf2e32/group all
+source          /src/tools/build/e32tools/elf2e32
+binary          /src/tools/build/e32tools/elf2e32/group all
 
 notes_source    release.txt
 
--- a/e32tools/elf2e32/group/release.txt	Fri Jun 25 20:58:33 2010 +0800
+++ b/e32tools/elf2e32/group/release.txt	Tue Jun 29 14:52:54 2010 +0800
@@ -3,3 +3,28 @@
 
 NOTESRC_RELEASE_REASON
 Postlinker(elf2e32) Release
+
+version 2.2 build(004)
+===============
+Released by Lorence Wang, 11/06/2010
+    1) elf2e32 use new bytepair in imglib
+
+version 2.2 build(003)
+===============
+Released by Lorence Wang, 26/04/2010
+    1) DPDEF145378 elf2e32 has compilation errors when buid with Gcc4.4 and STLport 5.2.1
+
+version 2.2 build(002)
+===============
+Released by Zheng Shen, 10/03/2010
+    1) DPDEF144887  [System build] : NE1 smoketest not booting up for TB92SF_1069 vtb92sf build
+
+version 2.2 build(001)
+===============
+Released by Zheng Shen, 09/03/2010
+	1) DPDEF144861 	elf2e32 in linux will do in wrong behavior when there is space in cmd line.
+
+version 2.2 build(000)
+===============
+Released by Zheng Shen, 22/02/2010
+	1) DPDEF144562	Build Tools cannot be built in Linux
--- a/e32tools/elf2e32/include/h_ver.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/e32tools/elf2e32/include/h_ver.h	Tue Jun 29 14:52:54 2010 +0800
@@ -17,8 +17,8 @@
 #define __H_VER_H__
 
 const TInt MajorVersion=2;
-const TInt MinorVersion=1;
-const TInt Build=14;
+const TInt MinorVersion=2;
+const TInt Build=4;
 
 #endif
 
--- a/e32tools/elf2e32/source/deflatecompress.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/e32tools/elf2e32/source/deflatecompress.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -29,6 +29,15 @@
 const TUint KDeflateHashMultiplier=0xAC4B9B19u;
 const TInt KDeflateHashShift=24;
 
+#define COMPILE_TIME_ASSERT(e)	\
+ 	switch (0)					\
+ 	{							\
+ 	case 0:						\
+ 	case e:						\
+ 		;						\
+ 	}
+
+
 /**
 Class HDeflateHash
 @internalComponent
@@ -125,9 +134,31 @@
 */
 inline HDeflateHash* HDeflateHash::NewLC(TInt aLinks)
 {
-	//return new(HMem::Alloc(0,_FOFF(HDeflateHash,iOffset[Min(aLinks,KDeflateMaxDistance)]))) HDeflateHash;
-	return new(new char[_FOFF(HDeflateHash,iOffset[Min(aLinks,KDeflateMaxDistance)])]) HDeflateHash;
-}
+#if __GNUC__ >= 4
+ 	// Try to detect if the class' layout has changed.
+ 	COMPILE_TIME_ASSERT( sizeof(HDeflateHash) == 1028 );
+ 	COMPILE_TIME_ASSERT( sizeof(TOffset) == 2 );
+ 	COMPILE_TIME_ASSERT( offsetof(HDeflateHash, iHash) < offsetof(HDeflateHash, iOffset) );
+ 
+ 	// Compute the size of the class, including rounding it up to a multiple of 4
+ 	// bytes.
+ 
+ 	unsigned n = sizeof(TInt) * 256 + sizeof(TOffset) * Min(aLinks, KDeflateMaxDistance);
+ 
+ 	while (n & 0x1f)
+ 	{
+ 		n++;	
+ 	}
+ 	// Allocate the raw memory ...
+ 	void* p = ::operator new(n);
+ 	// ... And create the object in that memory.
+ 	return new(p) HDeflateHash;
+#else
+   	return new(new char[_FOFF(HDeflateHash,iOffset[Min(aLinks,KDeflateMaxDistance)])]) HDeflateHash;
+#endif
+   }
+
+
 
 /**
 Hash function for HDeflateHash
--- a/e32tools/elf2e32/source/e32imagefile.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/e32tools/elf2e32/source/e32imagefile.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -33,6 +33,7 @@
 #include "h_ver.h"
 #include "checksum.h"
 #include "errorhandler.h"
+#include "byte_pair.h"
 
 #include <string>
 #include <vector>
@@ -57,25 +58,6 @@
 	return (T)res;
 }
 
-// Need a default constructor for TVersion, but don't want all the other stuff in h_utl.cpp
-/**
-Default constructor for TVersion class.
-@internalComponent
-@released
-*/
-TVersion::TVersion(){}
-
-/**
-Constructor for TVersion class.
-@internalComponent
-@released
-*/
-TVersion::TVersion(TInt aMajor, TInt aMinor, TInt aBuild): 
-	iMajor((TInt8)aMajor), iMinor((TInt8)aMinor), iBuild((TInt16)aBuild)
-{
-}
-
-
 /**
 Constructor for E32ImageChunkDesc class.
 @internalComponent
@@ -1177,6 +1159,10 @@
 
 	if (iUseCase->GetFPU() == 1)
 		iHdr->iFlags |= KImageHWFloat_VFPv2;
+	else if (iUseCase->GetFPU() == 2)
+		iHdr->iFlags |= KImageHWFloat_VFPv3;
+	else if (iUseCase->GetFPU() == 3)
+		iHdr->iFlags |= KImageHWFloat_VFPv3D16; 
 }
 
 /**
@@ -1402,7 +1388,7 @@
 @internalComponent
 @released
 */
-void CompressPages(TUint8 * bytes, TInt size, ofstream& os);
+void CompressPages(TUint8 * bytes, TInt size, ostream& os, CBytePair *aBPE);
 
 
 /**
@@ -1432,15 +1418,16 @@
 			os->write(iE32Image, aHeaderSize);
 			
 			// Compress and write out code part
+			CBytePair bpe;
 			int srcStart = GetExtendedE32ImageHeaderSize();
-			CompressPages( (TUint8*)iE32Image + srcStart, iHdr->iCodeSize, *os);
+			CompressPages( (TUint8*)iE32Image + srcStart, iHdr->iCodeSize, *os, &bpe);
 			
 			
 			// Compress and write out data part
 			srcStart += iHdr->iCodeSize;
 			int srcLen = GetE32ImageSize() - srcStart;
 			
-			CompressPages((TUint8*)iE32Image + srcStart, srcLen, *os);		
+			CompressPages((TUint8*)iE32Image + srcStart, srcLen, *os, &bpe);		
 
 		}
 		else if (compression == 0)
@@ -1698,7 +1685,7 @@
 }
 
 
-int  DecompressPages(TUint8 * bytes, ifstream& is);
+int DecompressPages(TUint8 * bytes, istream& is, CBytePair *aBPE);
 
 
 /**
@@ -1769,13 +1756,13 @@
 		oh = aImage.iOrigHdr;
 
 		// Read and decompress code part of the image
-
-		unsigned int uncompressedCodeSize = DecompressPages((TUint8 *) (aImage.iData + orighdrsz), is);
+		CBytePair bpe;
+		unsigned int uncompressedCodeSize = DecompressPages((TUint8 *) (aImage.iData + orighdrsz), is, &bpe);
 
 		
 		// Read and decompress data part of the image
 
-		unsigned int uncompressedDataSize = DecompressPages((TUint8 *) (aImage.iData + orighdrsz + uncompressedCodeSize), is);
+		unsigned int uncompressedDataSize = DecompressPages((TUint8 *) (aImage.iData + orighdrsz + uncompressedCodeSize), is, &bpe);
 
 		if (uncompressedCodeSize + uncompressedDataSize != uncompsize)
 			MessageHandler::GetInstance()->ReportMessage(WARNING, BYTEPAIRINCONSISTENTSIZEERROR);
--- a/e32tools/elf2e32/source/e32imagefile.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/e32tools/elf2e32/source/e32imagefile.h	Tue Jun 29 14:52:54 2010 +0800
@@ -173,10 +173,10 @@
 
 	void UpdateHeaderCrc();
 
-	bool WriteImage(const char * aName);
+	bool WriteImage(const char* aName);
 
 public:
-	const char * iFileName;
+	const char* iFileName;
 
 	char * iE32Image;
 	uint8 * iExportBitMap;
@@ -226,7 +226,7 @@
 	TUint32 Capability();
 	TUint32 Format();
 
-	void Dump(TText *aFileName,TInt aDumpFlags);
+	void Dump(const char* aFileName,TInt aDumpFlags);
 	void DumpHeader(TInt aDumpFlags);
 	void DumpData(TInt aDumpFlags);
 	void DumpSymbolInfo(E32EpocExpSymInfoHdr *aSymInfoHdr);
--- a/e32tools/elf2e32/source/elffilesupplied.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/e32tools/elf2e32/source/elffilesupplied.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -234,14 +234,9 @@
 			
 			while( aResultPos != aAbsentListEnd ) 
 			{
-				// intersection set {Absent,ELF_Symbols} is non-empty
-				// Ignore the non callable exports
-				if ((strncmp("_ZTI", (*aResultPos)->SymbolName(), len)) &&
-				    (strncmp("_ZTV", (*aResultPos)->SymbolName(), len)))
-				{	
-					iSymList.insert(iSymList.end(), *aResultPos);			
-					cout << "Elf2e32: Warning: Symbol " << (*aResultPos)->SymbolName() << " absent in the DEF file, but present in the ELF file" << endl;
-				}
+				// intersection set {Absent,ELF_Symbols} is non-empty				
+				iSymList.insert(iSymList.end(), *aResultPos);			
+				cout << "Elf2e32: Warning: Symbol " << (*aResultPos)->SymbolName() << " absent in the DEF file, but present in the ELF file" << endl;
 				aResultPos++;
 			}
 		}
--- a/e32tools/elf2e32/source/filedump.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/e32tools/elf2e32/source/filedump.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -170,16 +170,16 @@
 		return 1;
 	else if (result == KErrCorrupt || result == KErrNotSupported)
 	{
-		throw InvalidE32ImageError(INVALIDE32IMAGEERROR, (char *)afileName);
+		throw InvalidE32ImageError(INVALIDE32IMAGEERROR, (char*)afileName);
 	}
 	else if (result != 0)
 	{
-		throw FileError(FILEREADERROR, (char *)afileName);
+		throw FileError(FILEREADERROR, (char*)afileName);
 	}
 
 	int dumpOptions=iParameterListInterface->DumpOptions();
 	
-	aE32Imagefile->Dump((TText*)afileName, dumpOptions);
+	aE32Imagefile->Dump(afileName, dumpOptions);
 	delete aE32Imagefile;
 	return KErrNone;
 }
--- a/e32tools/elf2e32/source/imgdump.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/e32tools/elf2e32/source/imgdump.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -46,7 +46,7 @@
 */
 void PrintString(const char *aFmt,...)
 {
-	TText imageText[KMaxStringLength];
+	char imageText[KMaxStringLength];
 	va_list list;
 	va_start(list,aFmt);
 	VSNPRINTF((char *)imageText,KMaxStringLength,aFmt,list);
@@ -122,7 +122,7 @@
 @param aDumpFlags
 sub options passed to the 'dump' option
 */
-void E32ImageFile::Dump(TText *aFileName,TInt aDumpFlags)
+void E32ImageFile::Dump(const char* aFileName,TInt aDumpFlags)
 {
 	PrintString("E32ImageFile '%s'\n", aFileName);
 	DumpHeader(aDumpFlags);
--- a/e32tools/elf2e32/source/parametermanager.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/e32tools/elf2e32/source/parametermanager.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -18,13 +18,14 @@
 //
 
 // This must go before ParameterManager.h
-#define __INCLUDE_CAPABILITY_NAMES__
+#define __REFERENCE_CAPABILITY_NAMES__
 #include <e32capability.h>
 
 #include "pl_common.h"
 #include "parametermanager.h"
 #include "errorhandler.h"
 #include <iostream>
+#include <ctype.h>
 
 #include "h_utl.h"
 #include "h_ver.h"
@@ -375,7 +376,7 @@
 	{
 		"fpu",
 		(void *)ParameterManager::ParseFPU,
-		"FPU type [softvfp|vfpv2]",
+		"FPU type [softvfp|vfpv2|vfpv3|vfpv3D16]",
 	},
 	{
         "codepaging",
@@ -2241,21 +2242,33 @@
 		int q = 0;
 		unsigned int ordinalnum = 0;
 		char *symbol = 0;
-
-		int nq = aSysDefValues.find_first_of(",", q,sizeof(*p));
+		int nq = aSysDefValues.find_first_not_of(" 	");
+		if (nq && (nq != string::npos))
+		{
+			sysdeflength -= nq;
+			aSysDefValues.erase(0, nq);
+		}		
+
+		nq = aSysDefValues.find_first_of(",", q,sizeof(*p));
 		if (nq && (nq != string::npos))
 		{
 			int len = nq;
+			while (*(p+len-1) == ' ' || *(p+len-1) == '	')
+				len --;
 			symbol = new char[len+1];
 			memcpy(symbol, p, len);
 			symbol[len] = 0;
 			q = nq+1;
+      while (*(p+q) == ' ' || *(p+q) == '	')
+      	q ++;
 
 			char val = *(p+q);
 			if (!val || !isdigit(val))
 				throw ParameterParserError(SYSDEFERROR, "--sysdef");
 			ordinalnum = *(p+q) - '0';
 			aPM->SetSysDefs(ordinalnum, symbol, sysdefcount);
+      while (*(p+q+1) == ' ' || *(p+q+1) == '	')
+      	q ++;
 
 			unsigned int separator = aSysDefValues.find(";", 0);
 
@@ -2565,8 +2578,12 @@
 
 	if (strnicmp(aValue, "softvfp", 7)==0)
 		aPM->SetFPU(0);
-	else if (strnicmp(aValue, "vfpv2", 5)==0)
+	else if ((strnicmp(aValue, "vfpv2", 5)==0) || (strnicmp(aValue, "softvfp+vfpv2",13 )==0))
 		aPM->SetFPU(1);
+	else if (strnicmp(aValue,"vfpv3", 5)==0)
+		aPM->SetFPU(2);
+	else if (strnicmp(aValue,"vfpv3D16", 8)==0)
+		aPM->SetFPU(3);
 	else
 		throw InvalidArgumentError(INVALIDARGUMENTERROR, aValue, aOption);
 }
--- a/imgtools/buildrom/group/BLD.INF	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/group/BLD.INF	Tue Jun 29 14:52:54 2010 +0800
@@ -1,60 +1,79 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-/**
-@file
-
-@SYMPurpose Tool for building ROMs
-*/
-
-PRJ_EXPORTS
-
-../tools/buildrom.pl		/epoc32/tools/buildrom.pl
-../tools/buildrom.pm		/epoc32/tools/buildrom.pm
-../tools/buildrom.cmd		/epoc32/tools/buildrom.cmd
-../tools/cdfparser.pm		/epoc32/tools/cdfparser.pm
-../tools/datadriveimage.pm	/epoc32/tools/datadriveimage.pm
-../tools/Dep_Lister.pm		/epoc32/tools/dep_lister.pm
-../tools/externaltools.pm	/epoc32/tools/externaltools.pm
-../tools/featureparser.pm	/epoc32/tools/featureparser.pm
-../tools/GenericParser.pm	/epoc32/tools/genericparser.pm
-../tools/ImageContentHandler.pm	/epoc32/tools/imagecontenthandler.pm
-../tools/spitool.pm		/epoc32/tools/spitool.pm
-../tools/spitool.pl		/epoc32/tools/spitool.pl
-../tools/CONVERT.PL		/epoc32/rom/tools/
-../tools/CODESIZE.PL		/epoc32/rom/tools/
-../tools/configpaging.pm	/epoc32/tools/configpaging.pm
-../tools/efficient_rom_paging.pm /epoc32/tools/efficient_rom_paging.pm
-
-//
-// Files for Enhanced Feature Manager Support
-//
-../tools/featuresutil.pm	/epoc32/tools/featuresutil.pm
-../tools/featureregistry.pm	/epoc32/tools/featureregistry.pm
-../tools/featuremanager.pm	/epoc32/tools/featuremanager.pm
-../tools/featurefile.pm		/epoc32/tools/featurefile.pm
-../tools/featurecfg.pm		/epoc32/tools/featurecfg.pm
-../tools/featuresdat.pm		/epoc32/tools/featuresdat.pm
-../tools/features.cmd		/epoc32/tools/features.cmd
-../tools/features.pl		/epoc32/tools/features.pl
-../tools/features.pm		/epoc32/tools/features.pm
-
-// backwards compatibility for buildrom commandlines...
-
-../tools/buildrom.cmd		/epoc32/rom/tools/
-
+/*
+* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+PRJ_PLATFORMS
+TOOLS2
+
+/**
+@file
+
+@SYMPurpose Tool for building ROMs
+*/
+
+PRJ_EXPORTS
+
+../tools/buildrom.pl		/epoc32/tools/buildrom.pl
+../tools/buildrom.pm		/epoc32/tools/buildrom.pm
+../tools/cdfparser.pm		/epoc32/tools/cdfparser.pm
+../tools/datadriveimage.pm	/epoc32/tools/datadriveimage.pm
+../tools/Dep_Lister.pm		/epoc32/tools/dep_lister.pm
+../tools/externaltools.pm	/epoc32/tools/externaltools.pm
+../tools/featureparser.pm	/epoc32/tools/featureparser.pm
+../tools/GenericParser.pm	/epoc32/tools/genericparser.pm
+../tools/ImageContentHandler.pm	/epoc32/tools/imagecontenthandler.pm
+../tools/spitool.pm		/epoc32/tools/spitool.pm
+../tools/spitool.pl		/epoc32/tools/spitool.pl
+../tools/CONVERT.PL		/epoc32/rom/tools/
+../tools/CODESIZE.PL		/epoc32/rom/tools/
+../tools/efficient_rom_paging.pm /epoc32/tools/efficient_rom_paging.pm
+../tools/flexmodload.pm  /epoc32/tools/flexmodload.pm
+../tools/romutl.pm  /epoc32/tools/romutl.pm
+../tools/romosvariant.pm  /epoc32/tools/romosvariant.pm
+../tools/checkincludeslash.pl  /epoc32/tools/checkincludeslash.pl
+../tools/checkepocroot.pl  /epoc32/tools/checkepocroot.pl
+../tools/directory.bat  /epoc32/tools/directory.bat
+
+
+//
+// Files for Enhanced Feature Manager Support
+//
+../tools/featuresutil.pm	/epoc32/tools/featuresutil.pm
+../tools/featureregistry.pm	/epoc32/tools/featureregistry.pm
+../tools/featuremanager.pm	/epoc32/tools/featuremanager.pm
+../tools/featurefile.pm		/epoc32/tools/featurefile.pm
+../tools/featurecfg.pm		/epoc32/tools/featurecfg.pm
+../tools/featuresdat.pm		/epoc32/tools/featuresdat.pm
+../tools/features.pl		/epoc32/tools/features.pl
+../tools/features.pm		/epoc32/tools/features.pm
+
+#ifndef TOOLS2_LINUX 
+../tools/features.cmd		/epoc32/tools/features.cmd
+../tools/buildrom.cmd		/epoc32/tools/buildrom.cmd
+// backwards compatibility for buildrom commandlines...
+../tools/buildrom.cmd		/epoc32/rom/tools/buildrom.cmd
+#else
+../tools/features		/epoc32/tools/features
+../tools/buildrom		/epoc32/tools/buildrom
+// backwards compatibility for buildrom commandlines...
+../tools/buildrom		/epoc32/rom/tools/buildrom
+#endif
+
+PRJ_MMPFILES
+configpaging
+
+
+ 
--- a/imgtools/buildrom/group/buildrom.mrp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/group/buildrom.mrp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,7 +1,7 @@
 component	dev_build_imgtools_buildrom
-source	\src\tools\dev\build\imgtools\buildrom
-binary	\src\tools\dev\build\imgtools\buildrom\group all
-exports	\src\tools\dev\build\imgtools\buildrom\group
+source	\src\tools\build\imgtools\buildrom
+binary	\src\tools\build\imgtools\buildrom\group all
+exports	\src\tools\build\imgtools\buildrom\group
 
 notes_source	\component_defs\release.src
 
--- a/imgtools/buildrom/group/release.txt	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/group/release.txt	Tue Jun 29 14:52:54 2010 +0800
@@ -1,45 +1,176 @@
-Version 3.17.0
-================
-(Made by Zhi Dou, 26/10/2009)
-  1. RM-RIM406-1263: BU: Visual ROM Layout
-
-Version 3.16.0
-================
-(Made by Zhi Dou, 21/10/2009)
-  1. RM-RIM406-1229: BU: Feature Name Alias.
-
-Version 3.15.2
-================
-(Made by Zhi Dou, 19/10/2009)
-  1. Minor change for copyright from SPL to EPL.
-
-Version 3.15.1
-================
-(Made by Zhi Dou, 19/08/2009)
-  1. DPDEF141566 Textshell ROM fails to build due to 'cannot open obey file' 
-
-Version 3.15.0
-================
-(Made by Zhi Dou, 31/07/2009)
-  1. PREQ2465's REQ12562 Byte-pair compression update
-
-Version 3.14.0
-================
-(Made by Zhi Dou, 21/07/2009)
-  1. PREQ2465's REQ12561 BUILDROM performance improvement
-
-Version 3.13.1
-================
-(Made by Zhi Dou, 21/07/2009)
-  1. DPDEF140655 Update of tools_romkit for DEF140419 need to be propagated to TCL as well   
-
-Version 3.13.0
-================
-(Made by Zhi Dou, 20/07/2009)
-  1. PREQ2131 Hardware Configuration Repository
-
-Version 3.12.38
-================
-(Made by Zhi Dou, 16/07/2009)
-  1. DPDEF140976 breaks textshell builds (RAM-ROM)
-
+Version 3.26.0 (BUILDROM)
+===============
+Released by Lorence Wang 28/06/2010
+	1) Prepend EPOCROOT to epoc32 feature
+
+Version 3.25.2 (BUILDROM)
+===============
+Reoleased by Jason Cui 11/06/2010
+	1) Empty Directory Support in FAT Image
+
+Version 3.24.2 (BUILDROM)
+===============
+Reoleased by Jason Cui 09/06/2010
+	1) DPDEF145499: buildrom cannot support romname <name>
+
+Version 3.24.1 (buildrom)
+===============
+Released by Lorence Wang, 31/05/2010
+	1) DPDEF145359 Buildrom cannot find dso file in linux
+	2) DPDEF145470 buildrom with "-wordir=pathname" has error
+
+Version 3.24.0 (buildrom)
+===============
+Released by Lorence Wang, 20/05/2010
+	1) DPDEF145452 work path config -workdir feature
+
+Version 3.23.1 (buildrom)
+===============
+Released by Lorence Wang, 04/05/2010
+	1) DPDEF145374 Symbian Foundation License found in package build
+
+Version 3.23.0 (buildrom)
+===============
+Released by Lorence Wang, 21/04/2010
+	1) DPDEF145365 check path submit  
+
+Version 3.22.2 (buildrom)
+===============
+Released by Ross Qin, 14/04/2010
+	1) DPDEF145300 Rombuild hangs in S60 2010wk13 vasco_ui rom building 
+
+Version 1.2.1 (configpaging)
+===============
+Released by Zheng Shen, 09/04/2010
+	1) DPDEF145281 Paged meaning change
+
+Version 3.22.1 (buildrom)
+===============
+Released by Zheng Shen, 07/04/2010
+	1) DPDEF145287 ROmbuild.exe will hang with -symbols on TB92
+
+Version 3.22.0 (buildrom)
+===============
+Released by Ross Qin, 26/03/2010
+  1. RM-RIM406-1232: BU: MAKSYMROFS Integration
+Version 3.21.4 (buildrom)
+===============
+Released by Lorence Wang, 25/03/2010
+	1) DPDEF145165: S60 build break caused by latest Buildrom.
+
+Version 3.21.3 (buildrom)
+Version 1.1.1 (configpaging)
+===============
+Released by Zheng Shen, 16/03/2010
+	1) DPDEF145030  configpaging will hang as some time.
+        2) DPDEF144882  buildrom, rombuild,rofsbuil -keepgoing option
+
+Version 3.20.2 (buildrom)
+===============
+Released by Zheng Shen, 08/03/2010
+	1) DPDEF144795  ROM Tools cannot handle mixed binary variation scenario.
+    2) DPDEF144862  Correct handling of variant configuration file in a platform independent way
+
+Version 3.20.1 (buildrom)
+===============
+Released by Zheng Shen, 05/03/2010
+	1) DPDEF144535  remove -fastcompress option for rombuild/rofsbuild
+
+version 3.20.0 (buildrom)
+version 0.3 (features)
+Version 1.1.0 (configpaging)
+===============
+Released by Zheng Shen, 22/02/2010
+	1) DPDEF144562	Build Tools cannot be built in Linux
+
+Version 3.19.4 (buildrom)
+================
+(Made by Marvin Shi, 27/01/2010)
+  1. DPDEF143872 the warning from features.pl needs to be updated
+
+Version 3.19.3 (buildrom)
+Version 1.0.0 (configpaging)
+================
+(Made by Zheng Shen, 15/12/2009)
+  1. DPDEF143392 Change Configpaging.pm to Configpaging.exe
+
+Version 3.19.2
+================
+(Made by Marvin Shi, 23/11/2009)
+  1. DPDEF143057 BUILDROM reports "Invalid Switch" if one or more options contains "/" 
+  2. DPDEF143123 Feature variant failed in wk47 SOS. 
+  
+Version 3.19.1
+================
+(Made by Marvin Shi, 17/11/2009)
+  1. DPDEF142921 TSW error CSTI-7X4GHW: Buildtool creates invalid long names in FAT images 
+  2. DEF142972  buildrom produces garbled logs 
+
+Version 3.19.0
+================
+(Made by Marvin Shi, 13/11/2009)
+  1. RM-RIM406-1233: BU: MAKSYMROFS Integration
+Version 3.18.1
+================
+(Made by Marvin Shi, 13/11/2009)
+  1. DPDEF142937  S60 image creation is failed at feature variant phase 
+Version 3.18.0
+================
+(Made by Zhi Dou, 03/11/2009)
+  1. RM-RIM406-1228: BU: ROFSBUILD Cache
+  
+Version 3.17.1
+================
+(Made by Zhi Dou, 28/10/2009)
+  1. DPDEF142726 - ROM tools needs to be running stand alone according to the requirement of SymSEE  
+
+Version 3.17.0
+================
+(Made by Zhi Dou, 26/10/2009)
+  1. RM-RIM406-1263: BU: Visual ROM Layout
+
+Version 3.16.1
+================
+(Made by Zhi Dou, 26/10/2009)
+  1. DEF142435 Configpaging is case sensitive when trying to match binary names
+
+Version 3.16.0
+================
+(Made by Zhi Dou, 21/10/2009)
+  1. RM-RIM406-1229: BU: Feature Name Alias.
+
+Version 3.15.2
+================
+(Made by Zhi Dou, 19/10/2009)
+  1. Minor change for copyright from SPL to EPL.
+
+Version 3.15.1
+================
+(Made by Zhi Dou, 19/08/2009)
+  1. DPDEF141566 Textshell ROM fails to build due to 'cannot open obey file' 
+
+Version 3.15.0
+================
+(Made by Zhi Dou, 31/07/2009)
+  1. PREQ2465's REQ12562 Byte-pair compression update
+
+Version 3.14.0
+================
+(Made by Zhi Dou, 21/07/2009)
+  1. PREQ2465's REQ12561 BUILDROM performance improvement
+
+Version 3.13.1
+================
+(Made by Zhi Dou, 21/07/2009)
+  1. DPDEF140655 Update of tools_romkit for DEF140419 need to be propagated to TCL as well   
+
+Version 3.13.0
+================
+(Made by Zhi Dou, 20/07/2009)
+  1. PREQ2131 Hardware Configuration Repository
+
+Version 3.12.38
+================
+(Made by Zhi Dou, 16/07/2009)
+  1. DPDEF140976 breaks textshell builds (RAM-ROM)
+
--- a/imgtools/buildrom/tools/CODESIZE.PL	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/CODESIZE.PL	Tue Jun 29 14:52:54 2010 +0800
@@ -1,28 +1,29 @@
-#
-# Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-# Add up the codesize lines
-# Code size:               00028f4c
-#
-
-while ($line=<>)
-	{
-	if ($line =~ /^Code size:\s+(\S+)/i)
-		{
-		$totalcode += hex($1);
-		$count++;
-		}
-	}
-
-print "$count binaries totalling $totalcode\n";
+#!/usr/bin/perl
+#
+# Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+# Add up the codesize lines
+# Code size:               00028f4c
+#
+
+while ($line=<>)
+	{
+	if ($line =~ /^Code size:\s+(\S+)/i)
+		{
+		$totalcode += hex($1);
+		$count++;
+		}
+	}
+
+print "$count binaries totalling $totalcode\n";
--- a/imgtools/buildrom/tools/CONVERT.PL	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/CONVERT.PL	Tue Jun 29 14:52:54 2010 +0800
@@ -1,80 +1,85 @@
-#
-# Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-# parameter %1 is the string which is to occur around (i.e. before and after) the language names in the rest of the parameters to convert to 2-digit language codes
-# parameter %2 is the command to execute
-# parameters %3 onwards are the parameters to %2
-# example:
-# perl -w CONVERT.PL # echo the language code for french is #french#
-
-$conversionDelimiter=shift;
-open(E32STD_H, "< \\epoc32\\include\\E32STD.H") or die "\\epoc32\\include\\E32STD.H could not be opened";
-while ($line=<E32STD_H>)
-	{
-	if ($line=~/\benum\s+TLanguage\b(.*)$/)
-		{
-		$line=$1;
-		while (1)
-			{
-			if ($line=~/\{(.*)$/)
-				{
-				$line=$1;
-				last;
-				}
-			$line=<E32STD_H>;
-			}
-		$last=0;
-		$languageCode=0;
-		while (1)
-			{
-			if ($line=~/^(.*?)\}/)
-				{
-				$line=$1;
-				$last=1;
-				}
-			while ($line=~/^.*?ELang(\w+)\b(.*)$/)
-				{
-				$languageNameInLowerCase=lc $1;
-				$line=$2;
-				if ($line=~/^=(\d+)(.*)$/)
-					{
-					$languageCode=$1;
-					$line=$2;
-					}
-				$languageData{$languageNameInLowerCase}=$languageCode;
-				++$languageCode;
-				}
-			if ($last)
-				{
-				last;
-				}
-			$line=<E32STD_H>;
-			}
-		last;
-		}
-	}
-close(E32STD_H);
-for ($i=$#ARGV; $i>=0; --$i)
-	{
-	if ($ARGV[$i]=~/^(.*?)$conversionDelimiter(.*?)$conversionDelimiter(.*)$/)
-		{
-		$bitBefore=$1;
-		$languageNameInLowerCase=lc $2;
-		$bitAfter=$3;
-		defined $languageData{$languageNameInLowerCase} or die "The language \"$languageNameInLowerCase\" is not defined in \\epoc32\\include\\E32STD.H";
-		$ARGV[$i]=sprintf("$bitBefore%02d$bitAfter", $languageData{$languageNameInLowerCase});
-		}
-	}
-system("@ARGV");
-
+#!/usr/bin/perl
+#
+# Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+# parameter %1 is the string which is to occur around (i.e. before and after) the language names in the rest of the parameters to convert to 2-digit language codes
+# parameter %2 is the command to execute
+# parameters %3 onwards are the parameters to %2
+# example:
+# perl -w CONVERT.PL # echo the language code for french is #french#
+
+use romutl;
+
+my $include_path=&get_epocroot."epoc32\/include\/";
+$conversionDelimiter=shift;
+
+open(E32STD_H, "< ${include_path}E32STD.H") or die "${include_path}E32STD.H could not be opened";
+while ($line=<E32STD_H>)
+	{
+	if ($line=~/\benum\s+TLanguage\b(.*)$/)
+		{
+		$line=$1;
+		while (1)
+			{
+			if ($line=~/\{(.*)$/)
+				{
+				$line=$1;
+				last;
+				}
+			$line=<E32STD_H>;
+			}
+		$last=0;
+		$languageCode=0;
+		while (1)
+			{
+			if ($line=~/^(.*?)\}/)
+				{
+				$line=$1;
+				$last=1;
+				}
+			while ($line=~/^.*?ELang(\w+)\b(.*)$/)
+				{
+				$languageNameInLowerCase=lc $1;
+				$line=$2;
+				if ($line=~/^=(\d+)(.*)$/)
+					{
+					$languageCode=$1;
+					$line=$2;
+					}
+				$languageData{$languageNameInLowerCase}=$languageCode;
+				++$languageCode;
+				}
+			if ($last)
+				{
+				last;
+				}
+			$line=<E32STD_H>;
+			}
+		last;
+		}
+	}
+close(E32STD_H);
+for ($i=$#ARGV; $i>=0; --$i)
+	{
+	if ($ARGV[$i]=~/^(.*?)$conversionDelimiter(.*?)$conversionDelimiter(.*)$/)
+		{
+		$bitBefore=$1;
+		$languageNameInLowerCase=lc $2;
+		$bitAfter=$3;
+		defined $languageData{$languageNameInLowerCase} or die "The language \"$languageNameInLowerCase\" is not defined in \/epoc32\/include\/E32STD.H";
+		$ARGV[$i]=sprintf("$bitBefore%02d$bitAfter", $languageData{$languageNameInLowerCase});
+		}
+	}
+system("@ARGV");
+
--- a/imgtools/buildrom/tools/Dep_Lister.pm	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/Dep_Lister.pm	Tue Jun 29 14:52:54 2010 +0800
@@ -1,86 +1,89 @@
-#
-# Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-#
-
-# This package contains routines to find the static and dynamic dependencies of a binary.
-package Dep_Lister;
-
-use cdfparser;
-require Exporter;
-@ISA=qw(Exporter);
-@EXPORT=qw(
-	StaticDeps
-);
-
-use strict;
-
-# This subroutine evaluates the static dependencies of an E32 executable and returns the list of
-# binary names that this binary is dependent on (as found in its import table). If the input file
-# is not a valid E32 executable, this routine returns an 'undef'.
-sub StaticDeps()
-{
-	my ($file) = @_;
-	my @statdeps;
-
-	open PIPE, "elf2e32 --dump i --e32input=$file 2>&1 | ";
-	my $executable;
-	my $ver;
-	my $ext;
-	my $binary;
-	my $binaryInfoRef;
-	my $fileName;
-
-	if($file =~ /.*\\(\S+)/)
-	{
-		$fileName = $1;
-	}
-	while(<PIPE>)
-	{
-		if($_ =~ /(\d+) imports from (.*)\{(.*)\}\[?(.*)\]?\.(.*)/i)
-		{
-			my $skipLines = $1;
-			$executable = $2;
-			$ver = $3;
-			$ext = $5;
-
-			$binary = $executable . "." . $ext;
-			
-			push @statdeps,$binary;
-
-#			Each imported symbol's ordinal number is printed in these lines...
-#			Skip them
-			if($skipLines > 0)
-			{
-				while(<PIPE>)
-				{
-					$skipLines--;
-					if($skipLines == 0 )
-					{
-						last;
-					}
-				}	
-			}
-		}
-		elsif($_ =~ /elf2e32 : Error: .* is not a valid E32Image file/)
-		{
-#			not an e32 image...mark the file as a data file
-			return undef;
-		}
-	}
-	close PIPE;
-	return (@statdeps);
-}
-
-1;
+#
+# Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+#
+
+# This package contains routines to find the static and dynamic dependencies of a binary.
+package dep_lister;
+
+use cdfparser;
+use romutl;
+
+require Exporter;
+@ISA=qw(Exporter);
+@EXPORT=qw(
+	StaticDeps
+);
+
+use strict;
+
+# This subroutine evaluates the static dependencies of an E32 executable and returns the list of
+# binary names that this binary is dependent on (as found in its import table). If the input file
+# is not a valid E32 executable, this routine returns an 'undef'.
+sub StaticDeps()
+{
+	my ($file) = @_;
+	my @statdeps;
+
+    is_existinpath("elf2e32", Romutl::DIE_NOT_FOUND);
+	open PIPE, "elf2e32 --dump i --e32input=$file 2>&1 | ";
+	my $executable;
+	my $ver;
+	my $ext;
+	my $binary;
+	my $binaryInfoRef;
+	my $fileName;
+
+	if($file =~ /.*[\/\\](\S+)/)
+	{
+		$fileName = $1;
+	}
+	while(<PIPE>)
+	{
+		if($_ =~ /(\d+) imports from (.*)\{(.*)\}\[?(.*)\]?\.(.*)/i)
+		{
+			my $skipLines = $1;
+			$executable = $2;
+			$ver = $3;
+			$ext = $5;
+
+			$binary = $executable . "." . $ext;
+			
+			push @statdeps,$binary;
+
+#			Each imported symbol's ordinal number is printed in these lines...
+#			Skip them
+			if($skipLines > 0)
+			{
+				while(<PIPE>)
+				{
+					$skipLines--;
+					if($skipLines == 0 )
+					{
+						last;
+					}
+				}	
+			}
+		}
+		elsif($_ =~ /elf2e32 : Error: .* is not a valid E32Image file/)
+		{
+#			not an e32 image...mark the file as a data file
+			return undef;
+		}
+	}
+	close PIPE;
+	return (@statdeps);
+}
+
+1;
--- a/imgtools/buildrom/tools/GenericParser.pm	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/GenericParser.pm	Tue Jun 29 14:52:54 2010 +0800
@@ -1,194 +1,196 @@
-#
-# Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-# Provides generic methods retrieving data from the XML file.
-# Internally uses DOM API. Uses XML Checker to validate the XML.
-#
-
-package genericparser;
-require Exporter;
-@ISA=qw(Exporter);
-
-@EXPORT=qw(
-
-	getRootElement
-	getAttrValue
-	getElementValue
-	getSiblingElements
-	getNodeAttributes
-	getChildElements
-	getNodeFromTree
-	getElementsTagName
-	getElementName
-);
-
-use strict;
-use XML::DOM;
-use XML::DOM::ValParser;#XML Validator
-
-my $validxml; # XML validation status
-$XML::Checker::FAIL = \&failhandler; # User defined fail handler
-
-# User defined fail handler for the XML checker
-sub failhandler
-{
-	my ($code, $msg, @context) = @_;
-	print "ERROR: $msg\n";
-	$validxml = 0;
-}
-
-#Returns the root element of the XML file
-sub getRootElement() {
-	my ($xmlfile) = shift;
-	die "ERROR: XML File does not exists in the specified path $xmlfile\n" if (!-f $xmlfile);
-	my $DOMParser = new XML::DOM::Parser(); #DOM Parser
-	#Set the SGML_SEARCH_PATH to the path where the DTD files are found ($ENV{EPOCROOT}epoc32\\tools).
-	XML::Checker::Parser::set_sgml_search_path ("$ENV{EPOCROOT}epoc32/tools");
-	my $xmlValidator = new XML::Checker::Parser();#Validates XML against Schema
-	$validxml = 1;
-	$xmlValidator->parsefile($xmlfile);
-	
-	if($validxml)
-	{
-		my $document = $DOMParser->parsefile($xmlfile);#Parse XML file
-		my $root = $document->getDocumentElement();
-		return $root;
-	}
-	
-	return 0;
-}
-
-#Returns the attribute value of the element
-#Optional argument strictcaseflg does not convert the case of the attribute value
-sub getAttrValue(){
-	my ($elementname, $name, $strictcaseflg) = @_;
-	my $attrVal =  $elementname->getAttribute($name) ;
-	if ($attrVal eq "") {
-  		return undef;
-  	}
-	if(!defined $strictcaseflg) {
-		return lc($attrVal);
-	}
-	else {
-		return $attrVal;
-	}
-}
-
-#Returns the element value
-#Optional argument strictcaseflg does not convert the case of the element value
-sub getElementValue(){
-	my ($elementname) = shift;
-	my ($strictcaseflg)=shift;
-	my $elementVal;
-	if( !$elementname->hasChildNodes() )
-	{
-		return undef;
-	}
-	if ($elementname->getNodeType == XML::DOM::ELEMENT_NODE) {
-		$elementVal =  $elementname->getFirstChild()->getData ;
-	}
-	
-	if(!defined $strictcaseflg) {
-		return lc($elementVal);
-	}
-	else {
-		return $elementVal;
-	}
-}
-
-#Returns the sibling elements for the given node
-sub getSiblingElements {
-	my $child = shift;
-	my @nodeList;
-	while($child) {
-		if($child->getNodeType eq XML::DOM::ELEMENT_NODE) {
-			@nodeList=(@nodeList,$child); 
-		} 
-		$child = $child->getNextSibling;
-	}
-	return 	@nodeList;
-}
-
-#Returns the attribute list reference for the given node
-sub getNodeAttributes() {
-	my $node = shift;
-	my $attlist;
-	if ($node->getNodeType() eq XML::DOM::ELEMENT_NODE)	{
-		$attlist = $node->getAttributes;
-	}
-	return $attlist;
-}
-
-#Returns the children for the given node element
-sub getChildElements {
-	my $child = shift;
-	my @childList;
-	my @newChildList;	
-		
-	@childList=$child->getChildNodes;
-	foreach my $node (@childList) {
-		if($node->getNodeType eq XML::DOM::ELEMENT_NODE) {
-			@newChildList=(@newChildList,$node); 
-		}
-	}
-	return 	@newChildList;
-}
-
-#Returns the list of nodes that matches the specified node tree
-sub getNodeFromTree(){
-
-	my @resultNodes;
-	my ($element, @nodeNames) = @_;
-	my $nodeName;
-	my @children = $element->getChildNodes();
-
-	foreach my $child (@children) {
-		if ($child->getNodeType eq XML::DOM::ELEMENT_NODE) {
-			if (($child->getNodeName) eq $nodeNames[0]) {
-				if ($#nodeNames) {
-					$nodeName = shift @nodeNames;#Pop unmatched node
-					push @resultNodes,&getNodeFromTree($child, @nodeNames);
-					unshift @nodeNames, $nodeName;#Put back the nodes to proper level
-				}
-				else {
-					push @resultNodes,$child;#Push matched node to the destination
-				}
-				
-			}		
-
-		}
-
-	}
-	
-	return @resultNodes;
-}
-
-#Returns the list of elements whose node matches with the node name supplied
-sub getElementsTagName{
-	my ($node, $name) = @_;
-	if ($node->getNodeType eq XML::DOM::ELEMENT_NODE) {
-		my @taggedElements = $node->getElementsByTagName($name);
-		return @taggedElements;
-	}
-}
-
-#Returns the element name for the given node
-sub getElementName{
-	my $node = shift;
-	if ($node->getNodeType eq XML::DOM::ELEMENT_NODE) {
-		return lc($node->getNodeName);
-	}
-}
-
-1;
\ No newline at end of file
+#
+# Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+# Provides generic methods retrieving data from the XML file.
+# Internally uses DOM API. Uses XML Checker to validate the XML.
+#
+
+package genericparser;
+require Exporter;
+@ISA=qw(Exporter);
+
+@EXPORT=qw(
+
+	getRootElement
+	getAttrValue
+	getElementValue
+	getSiblingElements
+	getNodeAttributes
+	getChildElements
+	getNodeFromTree
+	getElementsTagName
+	getElementName
+);
+
+use strict;
+use XML::DOM;
+use XML::DOM::ValParser;#XML Validator
+
+use romutl;
+
+my $validxml; # XML validation status
+$XML::Checker::FAIL = \&failhandler; # User defined fail handler
+
+# User defined fail handler for the XML checker
+sub failhandler
+{
+	my ($code, $msg, @context) = @_;
+	print "ERROR: $msg\n";
+	$validxml = 0;
+}
+
+#Returns the root element of the XML file
+sub getRootElement() {
+	my ($xmlfile) = shift;
+	die "ERROR: XML File does not exists in the specified path $xmlfile\n" if (!-f $xmlfile);
+	my $DOMParser = new XML::DOM::Parser(); #DOM Parser
+	#Set the SGML_SEARCH_PATH to the path where the DTD files are found ($ENV{EPOCROOT}epoc32\\tools).
+	XML::Checker::Parser::set_sgml_search_path (&get_epocroot."epoc32/tools");
+	my $xmlValidator = new XML::Checker::Parser();#Validates XML against Schema
+	$validxml = 1;
+	$xmlValidator->parsefile($xmlfile);
+	
+	if($validxml)
+	{
+		my $document = $DOMParser->parsefile($xmlfile);#Parse XML file
+		my $root = $document->getDocumentElement();
+		return $root;
+	}
+	
+	return 0;
+}
+
+#Returns the attribute value of the element
+#Optional argument strictcaseflg does not convert the case of the attribute value
+sub getAttrValue(){
+	my ($elementname, $name, $strictcaseflg) = @_;
+	my $attrVal =  $elementname->getAttribute($name) ;
+	if ($attrVal eq "") {
+  		return undef;
+  	}
+	if(!defined $strictcaseflg) {
+		return lc($attrVal);
+	}
+	else {
+		return $attrVal;
+	}
+}
+
+#Returns the element value
+#Optional argument strictcaseflg does not convert the case of the element value
+sub getElementValue(){
+	my ($elementname) = shift;
+	my ($strictcaseflg)=shift;
+	my $elementVal;
+	if( !$elementname->hasChildNodes() )
+	{
+		return undef;
+	}
+	if ($elementname->getNodeType == XML::DOM::ELEMENT_NODE) {
+		$elementVal =  $elementname->getFirstChild()->getData ;
+	}
+	
+	if(!defined $strictcaseflg) {
+		return lc($elementVal);
+	}
+	else {
+		return $elementVal;
+	}
+}
+
+#Returns the sibling elements for the given node
+sub getSiblingElements {
+	my $child = shift;
+	my @nodeList;
+	while($child) {
+		if($child->getNodeType eq XML::DOM::ELEMENT_NODE) {
+			@nodeList=(@nodeList,$child); 
+		} 
+		$child = $child->getNextSibling;
+	}
+	return 	@nodeList;
+}
+
+#Returns the attribute list reference for the given node
+sub getNodeAttributes() {
+	my $node = shift;
+	my $attlist;
+	if ($node->getNodeType() eq XML::DOM::ELEMENT_NODE)	{
+		$attlist = $node->getAttributes;
+	}
+	return $attlist;
+}
+
+#Returns the children for the given node element
+sub getChildElements {
+	my $child = shift;
+	my @childList;
+	my @newChildList;	
+		
+	@childList=$child->getChildNodes;
+	foreach my $node (@childList) {
+		if($node->getNodeType eq XML::DOM::ELEMENT_NODE) {
+			@newChildList=(@newChildList,$node); 
+		}
+	}
+	return 	@newChildList;
+}
+
+#Returns the list of nodes that matches the specified node tree
+sub getNodeFromTree(){
+
+	my @resultNodes;
+	my ($element, @nodeNames) = @_;
+	my $nodeName;
+	my @children = $element->getChildNodes();
+
+	foreach my $child (@children) {
+		if ($child->getNodeType eq XML::DOM::ELEMENT_NODE) {
+			if (($child->getNodeName) eq $nodeNames[0]) {
+				if ($#nodeNames) {
+					$nodeName = shift @nodeNames;#Pop unmatched node
+					push @resultNodes,&getNodeFromTree($child, @nodeNames);
+					unshift @nodeNames, $nodeName;#Put back the nodes to proper level
+				}
+				else {
+					push @resultNodes,$child;#Push matched node to the destination
+				}
+				
+			}		
+
+		}
+
+	}
+	
+	return @resultNodes;
+}
+
+#Returns the list of elements whose node matches with the node name supplied
+sub getElementsTagName{
+	my ($node, $name) = @_;
+	if ($node->getNodeType eq XML::DOM::ELEMENT_NODE) {
+		my @taggedElements = $node->getElementsByTagName($name);
+		return @taggedElements;
+	}
+}
+
+#Returns the element name for the given node
+sub getElementName{
+	my $node = shift;
+	if ($node->getNodeType eq XML::DOM::ELEMENT_NODE) {
+		return lc($node->getNodeName);
+	}
+}
+
+1;
--- a/imgtools/buildrom/tools/ImageContentHandler.pm	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/ImageContentHandler.pm	Tue Jun 29 14:52:54 2010 +0800
@@ -1,1550 +1,1551 @@
-#
-# Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-#
-
-# This package processes the Image Content XML, and creates an OBY file to create a Rom image.
-package ImageContentHandler;
-
-
-require Exporter;
-@ISA=qw(Exporter);
-@EXPORT=qw(
-	ParseImageContentXML
-	ProcessImageContent
-	AddBinary
-	GetBldRomOpts
-	SetBldRomOpts
-	GenObyFile
-	GetObyFiles
-	AddBinaryFromOby
-	UpdateObyBinaryStaticDep
-	PrintMsg
-	DumpBinaries
-);
-
-use strict;
-use genericparser;
-use cdfparser;
-use Dep_Lister;
-
-#Error list
-my @errors;
-
-my %ImageContent=();		#Image details are stored in this tree
-my $RootNode;				#The root node of the XML root document element
-my @TargetImageList;		#The list of target element nodes in the XML. These are ordered based on their 
-							#  imageid (if it is a number, else, based on the availibility of Rom locations within 0..7).
-my @binarySelectionArray;	#This array stores the ABI directories to be looked up to select binaries.
-my @ImageContentBinaries;	#This list is for the biaries mentioned in Image content XML for 
-							#  keywords like, 'primary', 'secondary', 'device', 'extension', 'variant'.
-
-# List that contains information of binary from OBY file. This list is maintained to check if their static dependencies
-#	have been included already in Rom.
-my %obyFileInfo=();
-
-my $ImageIndex=-1;
-
-my @Includes;		#List of included features. The included feature in this list is a hash table giving the 
-					#Uid or the name. These features are collected either from the Image content or the CDF XMLs.
-my @Excludes;		#List of excluded features.The excluded feature in this list is a hash table giving the 
-					#Uid or the name. These features are collected either from the Image content or the CDF XMLs.
-
-my %DefaultDirs =();#This hash table records the default ABI and the BUILD directories. These are updated in case
-					#  the overriding buildrom options are provided e.g., -D_FULL_DEBUG or -D_PLAT=GCCE etc.
-
-my @BPABIPlats = &BPABIutl::BPABIutl_Plat_List; # Add the BPABI Platforms to be added
-
-my $isEcomPlugin=0; # This flag will be set when PLUGINs are provided in the CDF file.
-
-sub ParseImageContentXML
-{
-	my $XMLFile = shift;
-
-	$XMLFile =~ s/\\/\//g;
-	$RootNode = &getRootElement($XMLFile);
-
-	&SetImageDetails(\%ImageContent, $RootNode);
-}
-
-
-my @padding;
-#This subroutine traverses the XML tree and stores the fields in the hast table %ImageContent. The keys
-#	are the branch names. For target nodes., it stores the nodes themselves in the hash table and doesn't
-#	go deeper. These nodes are processed laster. For the other nodes, it keeps traversing recursively.
-# There are some special keys used to store the nodes and values in the tree. While storing an XML::DOM
-#  node, it sores with the keys 'nodes', while, for storing a value, it is stored with the key 'vals'.
-# These are the keys used to retrieve the contents of the tree while generating the final OBY.
-sub SetImageDetails
-{
-	my ($ImageDetailRef, $ImageNode) = @_;
-	my @children = &genericparser::getChildElements($ImageNode);
-	my $child;
-	my $TreeRef;
-	my $branch;
-	my $parentName = &genericparser::getElementName($ImageNode);
-	my $childCnt = scalar @children;
-
-	my ($indent) = join('', @padding);
-
-	my $val = &genericparser::getElementValue($ImageNode);
-	$val = Trim($val);
-	if($val ne "")
-	{
-		push @{$ImageDetailRef->{vals}}, $val;
-	}
-
-	my $NodeRef;
-	foreach $child (@children)
-	{
-		$branch = &genericparser::getElementName($child);
-
-		$NodeRef = \%{$ImageDetailRef->{$branch}};
-
-		if($branch eq "cdf" and $parentName eq "romscope")
-		{
-#			Record the romscope node. This node indicates the oby files or cdf files/directories
-#			that may be used.
-			push @{$NodeRef->{nodes}}, $child;
-			next;
-		}
-		if($branch eq "target" and $parentName eq "romtarget")
-		{
-			push @{$NodeRef->{nodes}}, $child;
-			next;
-		}
-		if( ($branch =~ /primary/i  ) ||
-			($branch =~ /secondary/i) ||
-			($branch =~ /extension/i) ||
-			($branch =~ /variant/i  ) ||
-			($branch =~ /device/i   ) )
-		{
-			next;
-		}
-		
-		if( $child->hasChildNodes() )
-		{
-			$NodeRef->{hasChildren} = 1;
-			push @padding, ".";
-			SetImageDetails($NodeRef, $child);
-		}
-		else
-		{
-			$NodeRef->{hasChildren} = 0;
-		}
-
-#		Get all attributes...
-		my $attribs = &genericparser::getNodeAttributes($child);
-		my $attrib;
-
-		my $nodeName;
-		my $nodeVal;
-		my %attr=();
-		my $attrLen = $attribs->getLength;
-		for (my $pos = 0; $pos < $attrLen;$pos++)
-		{
-			$attrib = $attribs->item($pos);
-			if(!$attrib)
-			{
-				next;
-			}
-			$nodeName = lc ($attrib->getName);
-			$nodeVal = lc  ($attrib->getValue);
-			$attr{$nodeName}=$nodeVal;
-
-		}
-		push @{$NodeRef->{vals}}, \%attr;
-	}
-
-	pop @padding;
-}
-
-my @romGeometry;			#Array to store all Roms mentioned in RomGeometry
-my %romGeometryHash = ();	#This Hash table records the indices in @romGeometry array, keying on their Ids.
-
-my $curRomImageIndex;		#This scalar records the current Rom image being processed. An binary encountered
-							#  becomes part of the Rom image corresponding to this partition.
-
-# This subroutine associates the RomGeometry and the RomTarget sub-trees to set indices for the Rom-target
-#   nodes.It stores the Image content XML entries for primary/secondary/device/extension/variant keywords.
-#   It also stores the features that are included/excluded in Image content XML.
-
-sub ProcessImageContent
-{
-	my $TotalImages = &ProcessRomGeometry();
-
-	my @trgList;
-	if( defined @{$ImageContent{romtarget}{target}{nodes}})
-	{
-		@trgList = @{$ImageContent{romtarget}{target}{nodes}};
-	}
-
-#	Go through the romgeometry to find the location of each image. The valid IDs are 0 through 7.
-
-	foreach my $trg (@trgList)
-	{
-#		The ID field in romgeometry can be an integer in the range 0 through 7.
-#		If it is not a number, its location is assumed as its sequence number
-		my $imageid = &genericparser::getAttrValue($trg, "imageid");
-		if($imageid =~ /Any/i)
-		{
-			next;
-		}
-		elsif(exists $romGeometryHash{$imageid})
-		{
-			$ImageIndex = $romGeometryHash{$imageid};
-			push @{$TargetImageList[$ImageIndex]} , $trg;
-		}
-	}
-
-#	Romscope - update the maps if the files and directories are mentioned.
-	my @romScopeNodes;
-	if(defined @{$ImageContent{romscope}{cdf}{nodes}})
-	{
-		@romScopeNodes = @{$ImageContent{romscope}{cdf}{nodes}};
-	}
-
-	my $type;
-	my $file;
-	my $dir;
-	foreach my $aNode (@romScopeNodes)
-	{
-		$type = &genericparser::getAttrValue($aNode, "type");
-		if( $type =~ /dir/i)
-		{
-			$dir = &genericparser::getElementValue($aNode);
-			&cdfparser::CreateCDFFileBinaryMapFromDir($dir);
-		}
-		elsif($type =~ /file/i)
-		{
-			$file = &genericparser::getElementValue($aNode);
-			&cdfparser::CreateCDFFileBinaryMap($file);
-		}
-	}
-
-	my $availablePos = 0;
-	foreach my $trg (@trgList)
-	{
-		if(&genericparser::getAttrValue($trg, "imageid") =~ /Any/i)
-		{
-			while($availablePos < $TotalImages)
-			{
-				if( !defined($TargetImageList[$availablePos][0]) )
-				{
-					push @{$TargetImageList[$availablePos]}, $trg;
-					last;
-				}
-				$availablePos++;
-			}
-		}
-	}
-
-	my $pos = 0;
-	while( $pos < 8)
-	{
-		if( defined $TargetImageList[$pos][0] )
-		{
-#			Record the current Rom image index so that the binaries are included in the corresponding
-#			Rom image.
-#			The romGeometry and TargetImageList arrays are associated both being indexed on
-#			the Rom-image index.
-
-			$curRomImageIndex = $pos;
-			&ProcessTarget($pos, \@{$TargetImageList[$pos]});
-		}
-		$pos++;
-	}
-
-#	Pick the primary/secondary/device binaries
-	my @nodes = &genericparser::getNodeFromTree($RootNode, "options", "primary", "file");
-	if( defined @nodes)
-	{
-		&SaveImageContentBinaries(\@nodes, "primary");
-	}
-
-	@nodes = &genericparser::getNodeFromTree($RootNode, "options", "secondary", "file");
-	if( defined @nodes)
-	{
-		&SaveImageContentBinaries(\@nodes, "secondary");
-	}
-
-	@nodes = &genericparser::getNodeFromTree($RootNode, "options", "extension", "file");
-	if( defined @nodes)
-	{
-		&SaveImageContentBinaries(\@nodes, "extension");
-	}
-
-	@nodes = &genericparser::getNodeFromTree($RootNode, "options", "variant", "file");
-	if( defined @nodes)
-	{
-		&SaveImageContentBinaries(\@nodes, "variant");
-	}
-
-	@nodes = &genericparser::getNodeFromTree($RootNode, "options", "device", "file");
-	if( defined @nodes)
-	{
-		&SaveImageContentBinaries(\@nodes, "device");
-	}
-
-	foreach my $imgBin (@ImageContentBinaries)
-	{
-		&ProcessStaticDep($imgBin->{source});
-	}
-
-#	Pick the binary selection order
-	if (exists($ImageContent{options}{binaryselectionorder}{vals}))
-	{
-	    my ($abiDirs) = @{$ImageContent{options}{binaryselectionorder}{vals}};
-	    @binarySelectionArray = split(',', $abiDirs);
-	    @binarySelectionArray = Trim(@binarySelectionArray);
-
-	}
-
-	my $featureList = &cdfparser::GetIncludedFeatureList();
-	foreach my $feature (@$featureList)
-	{
-		push @Includes, $feature;
-	}
-
-	$featureList = &cdfparser::GetExcludedFeatureList();
-	foreach my $feature (@$featureList)
-	{
-		push @Excludes, $feature;
-	}
-}
-
-#Arrange the Rom-geometry according to their Id when they are numbers. The named images
-#are arranged starting from the empty slots in Rom geometry array.
-sub ProcessRomGeometry
-{
-	my $RomImageCount = 0;
-	my $pos = 0;
-	while($pos < 8)
-	{
-		$romGeometry[$pos++] = undef;
-	}
-
-	my @roms = @{$ImageContent{romgeometry}{image}{vals}};
-	$RomImageCount = scalar (@roms);
-	my @namedImages;
-
-#	Visit all images and allocate them the indices they mention.
-	foreach my $img (@roms)
-	{
-		if($img->{id} =~ /(\d+)/)
-		{
-			$pos = $1;
-			if( defined($romGeometry[$pos]) )
-			{
-				print "Error: $romGeometry[$pos]->{id} and $img->{id} cant be allocated the same position\n";
-				exit;
-			}
-			$romGeometry[$pos] = $img;
-
-#			Record the index of this Rom
-			$romGeometryHash{$img->{id}} = $pos;
-		}
-		else
-		{
-#			These are the named images that are allocated there positions sequentially starting from
-#			the first available empty position
-			push @namedImages, $img;
-		}
-	}
-
-#	Revisit the images and allocate the remaining (unallocated) positions.
-
-	$pos = 0;
-	my $namedImageCount = scalar (@namedImages);
-	my $firstNamedImgIdx = 0;
-	my $img;
-	while(	($pos < 8) and ($namedImageCount > 0) )
-	{
-		if( $romGeometry[$pos] )
-		{
-#			skip the positions already allocated.
-			$pos++;
-			next;
-		}
-		$img = $namedImages[$firstNamedImgIdx];
-		$romGeometry[$pos] = $img;
-
-#		Record the index of this Rom
-		$romGeometryHash{$img->{id}} = $pos;
-		
-		$pos++;$firstNamedImgIdx++;
-		$namedImageCount--;
-	}
-
-	return $RomImageCount;
-}
-
-my @ObyFileList;
-
-#This subrouting processes the target nodes that may include OBYs/CDFs or features. For CDFs, the satic/dynamic
-#  dependencies are evaluated.
-
-sub ProcessTarget
-{
-	my ($ImgPos , $trgNodesRef) = @_;
-	my @cdfFileList;
-
-#	For all the 'target' nodes associated with an image in romgeometry at the given index...
-#	The link between a target and an image in romGeometry is the image id. If the imageid
-#	of a target is 'Any', then the first available image in romGeometry is allocated to
-#	that target.
-
-	foreach my $target (@$trgNodesRef)
-	{
-
-#		Fetch any cdfs included within the Image Content file
-		my @cdfs = &getNodeFromTree($target, "include","cdf");
-
-		my $type;
-		my $file;
-		my $dir;
-		foreach my $cdfNode (@cdfs)
-		{
-			$type = &genericparser::getAttrValue($cdfNode, "type");
-			
-			if( !($type) || ($type eq "file") )
-			{
-				$file = &genericparser::getElementValue($cdfNode);
-				push @cdfFileList, $file;
-			}
-			elsif($type eq "dir")
-			{
-				$dir = &genericparser::getElementValue($cdfNode);
-				&cdfparser::CreateCDFFileBinaryMapFromDir($dir);
-			}
-		}
-
-#		Collect all the obey files mentioned in this 'target' node.
-		my @obys = &getNodeFromTree($target, "include","obyFile");
-		foreach my $obyNode (@obys)
-		{
-			$file = &genericparser::getElementValue($obyNode);
-			push @ObyFileList, $file;
-		}
-
-		&CollectFeatures($target, 1, \@Includes);
-		&CollectFeatures($target, 0, \@Excludes);
-	}
-
-	ProcessCDFList(\@cdfFileList);
-}
-
-# This subroutine updates the include or exclude feature list collected from Image content XML.
-sub CollectFeatures
-{
-#	Collect all the features included/excluded in this 'target' node.
-
-	my ($target, $Inc, $IncludeExcludeListRef) = @_;
-	my $IncExcStr;
-	if($Inc == 1)
-	{
-		$IncExcStr = "include";
-	}
-	else
-	{
-		$IncExcStr = "exclude";
-	}
-
-	my @nodes = &getNodeFromTree($target, $IncExcStr,"feature");
-
-	foreach my $node (@nodes)
-	{
-		my %aFeatureInfo = ();
-		my $isValidFeature = 0;
-		my $feature = &genericparser::getAttrValue($node, "name");
-
-		if($Inc)
-		{
-#			Mark the feature included.
-			$aFeatureInfo{include} = 1;
-		}
-		else
-		{
-#			Mark the feature excluded.
-			$aFeatureInfo{exclude} = 1;
-		}
-
-		if(defined $feature and $feature ne "")
-		{
-			$aFeatureInfo{name}= $feature;
-			$aFeatureInfo{uid} = undef;
-			$isValidFeature = 1;
-		}
-		else
-		{
-			$feature = &genericparser::getAttrValue($node, "uid");
-			if(!defined $feature or $feature eq "")
-			{
-				print "Warning: Neither feature name nor uid is defined \n";
-			}
-			else
-			{
-				if(&featureparser::ValidateUIDValue($feature))
-				{
-					$feature = &featureparser::ConvertHexToDecimal($feature);
-					$aFeatureInfo{uid}= $feature;
-					$aFeatureInfo{name}= undef;
-					$isValidFeature = 1;
-				}
-				else
-				{
-					print "The uid value $feature specified in the Image Content Description is not a valid number\n";
-				}
-			}
-		}
-
-		if($isValidFeature)
-		{
-			push @$IncludeExcludeListRef, \%aFeatureInfo;
-		}
-	}
-}
-
-sub DumpImageDetails
-{
-	my ($HRef) = @_;
-	my %hash = %$HRef;
-	my $ChildHRef;
-
-	foreach my $Key (keys %hash)
-	{
-		if($Key eq "hasChildren" || $Key eq "vals")
-		{
-			next;
-		}
-		my $indent = join('', @padding);
-		&PrintMsg ($indent. $Key);
-		if($hash{$Key}{hasChildren} == 1)
-		{
-			push @padding, ".";
-			&PrintMsg ("\n");
-			$ChildHRef = \%{$hash{$Key}};
-			&DumpImageDetails($ChildHRef);
-		}
-		elsif( defined ($hash{$Key}{vals}) )
-		{
-			&PrintMsg ("\nVals $hash{$Key}{vals}\n");
-			push @padding, ".";
-			$indent = join('', @padding);
-			my @array = @{$hash{$Key}{vals}};
-			&PrintMsg ("array len = " . scalar(@array) . "\n");
-			foreach my $attrib ( @array )
-			{
-				foreach my $key1 (keys %$attrib)
-				{
-					&PrintMsg ($indent . $Key. " ". "$key1=$$attrib{$key1}\n");
-				}
-				&PrintMsg ("\n");
-			}
-		}
-		elsif( defined (@{$hash{$Key}{nodes}}) )
-		{
-			my $node = $hash{$Key}{nodes}[0];
-			&PrintMsg ("{". scalar(@{$hash{$Key}{nodes}})."}\n");
-		}
-	}
-	pop @padding;
-}
-
-sub CheckErrors
-{
-	if($#errors > -1)
-	{
-		&PrintMsg ("errors..........$#errors \n");
-		foreach (@errors)
-		{
-			&PrintMsg ($_ ."\n");
-		}
-		exit;
-	}
-}
-
-my @ImageBinaryList;#2d array storing the list of binaries per rom image
-sub AddBinary
-{
-	my ($binaryName) = @_;
-	{
-		push @{$ImageBinaryList[$curRomImageIndex]}, $binaryName;
-	}
-}
-
-sub SetBldRomOpts
-{
-	my ($key, $value) = @_;
-	if( $key eq undef )
-	{
-#		The default ABI directory is armv5 unless specified otherwise in the buildrom command-line.
-#		The default build directory is urel unless specified otherwise in the buildrom command-line.
-		$DefaultDirs{ABI_DIR} = 'ARMV5';
-		$DefaultDirs{BUILD_DIR}='urel';
-
-		$DefaultDirs{DEST_DIR}= "\\sys\\bin";
-
-	}
-	else
-	{
-#		trim the value for leading/trailing whitespace
-		$value = Trim($value);
-		$DefaultDirs{$key} = $value;
-	}
-}
-
-sub Trim()
-{
-	my @out = @_;
-	for (@out) {
-		s/^\s+//;
-		s/\s+$//;
-	}
-	return wantarray ? @out : $out[0];
-}
-
-sub GetBldRomOpts
-{
-	my ($key) = @_;
-	return $DefaultDirs{$key};
-}
-
-sub DumpBinaries
-{
-	&PrintMsg ("***********Binaries in ROM***********\n");
-	my $img_idx = 0;
-	while ($img_idx < 8 and defined ($ImageBinaryList[$img_idx]))
-	{
-		my @list = @{$ImageBinaryList[$img_idx]};
-		&PrintMsg ("Image $img_idx has ". scalar (@list ) . " binaries\n");
-		foreach my $bin (@list)
-		{
-			&PrintMsg ("file[$img_idx]=$bin\n");
-		}
-		$img_idx++;
-	}
-
-	&PrintMsg ("***********END***********\n");
-}
-
-sub PrintMsg
-{
-	my ($msg) = @_;
-	print "$msg";
-}
-
-# This subroutine is used to generate OBY-contents based on contents of the Image content XML. The image content XML 
-#   may have, in turn, included other OBYs/CDFs. These contents are appended to the Phase-I OBY file (where, the 
-#   Phase-I OBY file is generated by the preprocessor which is the conglomeration of all the buildrom supplied OBY files).
-sub GenObyFile
-{
-	my ($ObyFileName) = @_;
-	open (OBYFH, ">>$ObyFileName") or die("* Can't open $ObyFileName\n");
-	my $binRef;
-	my $line;
-	my $index;
-	my $new_src_path;
-	my $exec_src_path = $ENV{EPOCROOT};#This is the Executable source path
-	$exec_src_path .= "epoc32\\release\\";
-	my $abidir = $DefaultDirs{ABI_DIR};
-	my $blddir = $DefaultDirs{BUILD_DIR};
-
-	GenObyHeader(*OBYFH);
-
-	for($index = 0;$index < 8;$index++)
-	{
-		if( !defined $romGeometry[$index] )
-		{
-			next;
-		}
-
-		$line = "rom_image $index ";
-		$line .= $romGeometry[$index]{name} . " ";
-		$line .= "size=" . $romGeometry[$index]{size} . " ";
-		if( $romGeometry[$index]{type} =~ /nonxip/)
-		{
-			$line .= " non-xip ";
-		}
-		else
-		{
-			$line .= " xip ";
-		}
-
-		$line .= $romGeometry[$index]{compression} . " ";
-		if($romGeometry[$index]{extension} eq "yes")
-		{
-			$line .= " extension ";
-		}
-
-		$line .= "\n";
-
-		print OBYFH $line;
-
-		$line = "ROM_IMAGE[$index] {\n";	#Start of contents of this image
-		print OBYFH $line;
-
-		foreach my $binary (@{$ImageBinaryList[$index]}) {
-			$binRef = &cdfparser::GetBinaryInfo($binary);
-			if( defined ($binRef) and $binRef->{IsFoundInCDF})
-			{
-				if(exists $binRef->{default})
-				{
-					$line = "DEFAULT_LANGUAGE $binRef->{default} \n";
-					print OBYFH "$line";
-				}
-				
-				if(exists $binRef->{language})
-				{
-					my $langCodes = $binRef->{language};
- 					foreach my $lang (@$langCodes)
-					{
-						$line = "LANGUAGE_CODE $lang \n";
-						print OBYFH "$line";
-					}
-				}
-
-#				Replace the BUILD_DIR with udeb or urel
-#				Default BUILD_DIR is urel and can be overridden by using cmd line option '_FULL_DEBUG'
-#				If a binary is to be picked always from udeb, then the src path in CDF must be mentioned
-#				as udeb e.g. <source>abi_dir\udeb\drtaeabi.dll</source>, in which case, the mentioned dir
-#				is picked as it is.
-
-				$new_src_path = $binRef->{source};
-
-				$new_src_path =~ s/ABI_DIR/$abidir/i;
-				$new_src_path =~ s/BUILD_DIR/$blddir/i;
-				$new_src_path =~ s/DEBUG_DIR/udeb/i;
-
-				$new_src_path =~ s/epocroot/EPOCROOT/;
-				$new_src_path =~ s/zresource/ZRESOURCE/;
-				$new_src_path =~ s/zprivate/ZPRIVATE/;
-				$new_src_path =~ s/zsystem/ZSYSTEM/;
-
-				
-				my $FileFound = 0;
-				
-				if($binRef->{IsExecutable})
-				{
-					$new_src_path = $exec_src_path . $new_src_path;
-					if(!-f $new_src_path)
-					{
-						foreach my $newAbiDir (@binarySelectionArray)
-						{
-							$new_src_path =~ s/$abidir/$newAbiDir/i;
-							if(-f $new_src_path)
-							{
-								$FileFound = 1;
-								last;
-							}
-							$abidir = $newAbiDir;
-						}
-
-						if( !$FileFound )
-						{
-							$FileFound = fallback($abidir, \$new_src_path);
-  							if( !$FileFound )
-							{
-								print "Missing file $binRef->{source} \n";
-								$new_src_path = $binRef->{source};
-							}
-
-						}
-					}
-#					compress options
-					if(exists $binRef->{compress} and ($binRef->{compress} eq "uncompress") )
-					{
-						$line = "fileuncompress=";
-					}
-					elsif($binRef->{compress} eq "compress")
-					{
-						$line = "filecompress=";
-					}
-					elsif( exists $binRef->{dll})
-					{
-						$line = "dll=";
-					}
-#					Checks the plugin type
-					elsif( exists $binRef->{type} and $binRef->{type} eq "plugin")
-					{
-						if (exists $binRef->{plugin_name})
-						{
-							$isEcomPlugin=1;
-							$line = "__$binRef->{plugin_name}_PLUGIN(ABI_DIR\\BUILD_DIR,ECOM_BIN_DIR,DATAZ_,ECOM_RSC_DIR,$binRef->{id},$binRef->{id})\n";
-						}
-					}
-					else
-					{
-						$isEcomPlugin=0;
-						$line = "file=";
-					}
-
-					if (!$isEcomPlugin)
-					{
-						$line .= $new_src_path . " ";
-						$line .= $binRef->{destination};
-					}
-
-
-#					stack,heap,fixed,priority,uid,dll,dlldatatop
-					if( exists $binRef->{stack})
-					{
-						$line .= " stack " . $binRef->{stack};
-					}
-					if( exists $binRef->{heapmin})
-					{
-						$line .= " heapmin " . $binRef->{heapmin};
-					}
-					if( exists $binRef->{heapmax})
-					{
-						$line .= " heapmax " . $binRef->{heapmax};
-					}
-					if( exists $binRef->{fixed})
-					{
-						$line .= " fixed";
-					}
-					if( exists $binRef->{priority})
-					{
-						$line .= " priority " . $binRef->{priority};
-					}
-					if( exists $binRef->{uid1})
-					{
-						$line .= " uid1 " . $binRef->{uid1};
-					}
-					if( exists $binRef->{uid2})
-					{
-						$line .= " uid2 " . $binRef->{uid2};
-					}
-					if( exists $binRef->{uid3})
-					{
-						$line .= " uid3 " . $binRef->{uid3};
-					}
-					if( exists $binRef->{dlldatatop})
-					{
-						$line .= " dlldatatop ". $binRef->{dlldatatop}; 
-					}
-					if( exists $binRef->{customisable} and $binRef->{customisable} eq "true")
-					{
-						$line .= " patched ";
-					}
-				}
-				else
-				{
-					my $type = $binRef->{type};
-					if($type =~ /normal/i)
-					{
-						$line = "data=";
-					}
-					if($type =~ /aif/i)
-					{
-						$line = "aif=";
-					}
-					elsif($type =~ /compressedbitmap/i)
-					{
-						$line = "compressed-bitmap=";
-					}
-					elsif($type =~ /autobitmap/i)
-					{
-						$line = "auto-bitmap=";
-					}
-					elsif($type =~ /bitmap/i)
-					{
-						$line = "bitmap=";
-					}
-
-					if(exists $binRef->{multilinguify})
-					{
-						my $extension;
-						my $srcNameWithoutExt;
-						my $dstNameWithoutExt;
-
-						if($new_src_path =~ /(.*)\.(.*)/)
-						{
-							$srcNameWithoutExt = $1;
-							$extension = $2;
-						}
-						if($binRef->{destination} =~ /(.*)\.(.*)/)
-						{
-							$dstNameWithoutExt = $1;
-						}
-
-						$line .= "MULTI_LINGUIFY(";
-						$line .= $extension . " ";
-						$line .= $srcNameWithoutExt . " ";
-						$line .= $dstNameWithoutExt;
-						$line .= ") ";
-					}
-					else
-					{
-						$line .= $new_src_path . " ";
-						$line .= $binRef->{destination};
-					}
-				}
-
-				$line .= "\n";
-				print OBYFH $line;
-			}
-			else
-			{
-				#Check if the binary is from ImageContent XML file.
-				my $imagecontentbin = 0;
-				foreach my $bin (@ImageContentBinaries) {
-					my $source;
-					if( $bin->{source} =~ /.*\\(\S+)/)
-					{
-						$source = $1;
-					}
-					if (grep /$binary/i, $source) {#Skip the binary that is already included in the OBY Header
-						$imagecontentbin = 1;
-						next;
-					}
-				}
-
-				if ($imagecontentbin) {
-					next;
-				}
-				my $obyInfo = &ImageContentHandler::GetObyBinaryInfo($binary);
-				if(!defined $obyInfo)
-				{
-					$line = "file=" . $exec_src_path. $DefaultDirs{ABI_DIR}. "\\" . $DefaultDirs{BUILD_DIR}. "\\". $binary. " ";
-					$line .= $DefaultDirs{DEST_DIR}. "\\". $binary;
-					$line .= "\n";
-					print OBYFH $line;
-				}
-			}
-		}
-		$line = "\n}\n";
-		print OBYFH $line;
-	}
-	close OBYFH;
-}
-
-#Sets default target to ARMV5 directory if the requested binary is not found
-sub fallback{
-	
-	my ($abidir, $abiFileRef) = @_;
-	my $foundFile=0;
-	foreach my $BpabiPlat (@BPABIPlats)
-	{
-		if ($$abiFileRef =~ /^(.*)\\$BpabiPlat\\(.*)$/)
-		{
-			$$abiFileRef =~ s/$abidir/ARMV5/i;
-			if(-f $$abiFileRef)
-			{
-				$foundFile = 1;
-				last;
-			}
-		}
-	}
-	return $foundFile;
-}
-
-# This subroutine generates the Rom configuration details like, 'bootbinary', 'romlinearbase', romalign,
-#   'kerneldataaddress', 'kernelheapmin' etc.
-sub GenObyHeader
-{
-	my ($fh) = @_;
-	my $line;
-
-#	version
-	if( defined @{$ImageContent{version}{vals}})
-	{
-		my $ver = @{$ImageContent{version}{vals}}[0];
-		if(defined $ver)
-		{
-			$line = "version=$ver\n";
-			print $fh $line;
-		}
-	}
-
-#	romchecksum
-	if( defined @{$ImageContent{romchecksum}{vals}})
-	{
-		my $cksum = @{$ImageContent{romchecksum}{vals}}[0];
-		if(defined $cksum)
-		{
-			$line = "romchecksum=$cksum\n";
-			print $fh $line;
-		}
-	}
-
-#	time
-	if( defined @{$ImageContent{time}{vals}})
-	{
-		my $time = @{$ImageContent{time}{vals}}[0];
-		if(defined $time)
-		{
-			$line = "time=ROMDATE $time\n";
-			print $fh $line;
-		}
-	}
-
-
-#	The Binary selection order
-	if(scalar @binarySelectionArray )
-	{
-		my $abilist = join (',', @binarySelectionArray);
-		$line = "\nBINARY_SELECTION_ORDER $abilist\n";
-		print $fh $line;
-	}
-
-#	trace
-	if( defined @{$ImageContent{options}{trace}{vals}})
-	{
-		my @traceFlags = @{$ImageContent{options}{trace}{vals}};
-		if(scalar @traceFlags)
-		{
-			$line = "trace $traceFlags[0]\n";
-			print $fh $line;
-		}
-	}
-
-#	The bootbinary
-	if( defined @{$ImageContent{options}{bootbinary}{vals}})
-	{
-		my $binary;
-		my @bootbin = @{$ImageContent{options}{bootbinary}{vals}};
-		if(scalar @bootbin)
-		{
-			$binary = $bootbin[0];
-			$binary =~ s/abi_dir/ABI_DIR/;
- 			$line = "bootbinary=$binary\n";
-			print $fh $line;
-		}
-	}
-
-
-#	dataaddress
-	if( defined @{$ImageContent{options}{dataaddress}{vals}})
-	{
-		my @dataAddr = @{$ImageContent{options}{dataaddress}{vals}};
-		if(scalar @dataAddr)
-		{
-			$line = "dataaddress=$dataAddr[0]\n";
-			print $fh $line;
-		}
-	}
-
-#	debugport
-	if( defined @{$ImageContent{options}{debugport}{vals}})
-	{
-		my @dgbPort = @{$ImageContent{options}{debugport}{vals}};
-		if(scalar @dgbPort)
-		{
-			$line = "debugport=$dgbPort[0]\n";
-			print $fh $line;
-		}
-	}
-
-#	defaultstackreserve
-	if( defined @{$ImageContent{options}{defaultstackreserve}{vals}})
-	{
-		my @defStackRes = @{$ImageContent{options}{defaultstackreserve}{vals}};
-		if(scalar @defStackRes)
-		{
-			$line = "defaultstackreserve=$defStackRes[0]\n";
-			print $fh $line;
-		}
-	}
-
-#	wrapper
-	if( defined @{$ImageContent{options}{wrapper}{vals}})
-	{
-		my %tbl = @{$ImageContent{options}{wrapper}{vals}}[0];
-		if(exists $tbl{epoc})
-		{
-			$line = "epocwrapper\n";
-			print $fh $line;
-		}
-		elsif(exists $tbl{coff})
-		{
-			$line = "coffwrapper\n";
-			print $fh $line;
-		}
-		elsif(exists $tbl{none})
-		{
-			$line = "nowrapper\n";
-			print $fh $line;
-		}
-	}
-
-#	kernel options
-	my $val;
-	if( defined @{$ImageContent{options}{kernel}{name}{vals}})
-	{
-		$val = @{$ImageContent{options}{kernel}{name}{vals}}[0];
-		$line = "kernelromname=$val\n";
-		print $fh $line;
-	}
-	if( defined @{$ImageContent{options}{kernel}{dataaddress}{vals}})
-	{
-		$val = @{$ImageContent{options}{kernel}{dataaddress}{vals}}[0];
-		$line = "kerneldataaddress=$val\n";
-		print $fh $line;
-	}
-	if( defined @{$ImageContent{options}{kernel}{trace}{vals}})
-	{
-		$val = @{$ImageContent{options}{kernel}{trace}{vals}}[0];
-		$line = "kerneltrace $val\n";
-		print $fh $line;
-	}
-	if( defined @{$ImageContent{options}{kernel}{heapmin}{vals}})
-	{
-		$val = @{$ImageContent{options}{kernel}{heapmin}{vals}}[0];
-		$line = "kernelheapmin=$val\n";
-		print $fh $line;
-	}
-	if( defined @{$ImageContent{options}{kernel}{heapmax}{vals}})
-	{
-		$val = @{$ImageContent{options}{kernel}{heapmax}{vals}}[0];
-		$line = "kernelheapmax=$val\n";
-		print $fh $line;
-	}
-#	romlinearbase
-	if( defined @{$ImageContent{options}{romlinearbase}{vals}})
-	{
-		my @romLinBase = @{$ImageContent{options}{romlinearbase}{vals}};
-		if(scalar @romLinBase)
-		{
-			$line = "romlinearbase=$romLinBase[0]\n";
-			print $fh $line;
-		}
-	}
-
-#   romalign
-	if( defined @{$ImageContent{options}{romalign}{vals}})
-	{
-		my @romAlign = @{$ImageContent{options}{romalign}{vals}};
-		if(scalar @romAlign )
-		{
-			$line = "romalign=$romAlign[0]\n";
-			print $fh $line;
-		}
-	}
-
-
-
-
-#	autosize keyword with the block size
-	if( defined @{$ImageContent{options}{autosize}{vals}})
-	{
-		my @autoSz = @{$ImageContent{options}{autosize}{vals}};
-		if(scalar @autoSz )
-		{
-			$line = "autosize=$autoSz[0]\n";
-			print $fh $line;
-		}
-	}
-
-#	coreimage keyword with the coreimage name.
-	if( defined @{$ImageContent{options}{coreimage}{vals}})
-	{
-		my @coreImg = @{$ImageContent{options}{coreimage}{vals}};
-		if(scalar @coreImg)
-		{
-			$line = "coreimage=$coreImg[0]\n";
-			print $fh $line;
-		}
-	}
-
-
-
-	foreach my $imgBin (@ImageContentBinaries)
-	{
-		$line = $imgBin->{keyword};
-		my $srcPath = $imgBin->{source};
-		$srcPath =~ s/abi_dir/ABI_DIR/;
-		$srcPath =~ s/kernel_dir/KERNEL_DIR/;
-		$srcPath =~ s/debug_dir/DEBUG_DIR/;
-		$srcPath =~ s/build_dir/BUILD_DIR/;
-		if(! ($imgBin->{keyword} =~ /secondary/i) )
-		{
-#			VARID mentioned for primary, device, extension and variant keywords.
-			$line .= "[VARID]" ;
-		}
-		$line .= "=" . $srcPath . "\t\t" .  $imgBin->{destination};
-		for my $key (keys %$imgBin)
-		{
-			if( ($key =~ /keyword/i) ||
-				($key =~ /source/i) ||
-				($key =~ /destination/i))
-			{
-#				These keys are already taken care.
-				next;
-			}
-
-#			Write the rest of the keywords if any, (e.g., 'fixed' or HEAPMAX(0x40000) ) to the oby line.
-			$line .= " ".($key);
-			if( defined $imgBin->{$key})
-			{
-				$line .= "(". $imgBin->{$key}. ") ";
-			}
-		}
-		print $fh "$line\n";
-	}
-}
-
-sub GetObyFiles
-{
-	return \@ObyFileList;
-}
-
-sub GetBinarySelectionOrder
-{
-	return \@binarySelectionArray;
-}
-
-sub GetFeatures()
-{
-	my %FeatureMap = ();
-	my @FeatList;
-	my $featRef;
-	my $uid;
-	foreach my $feat (@Includes)
-	{
-		if($feat->{name})
-		{
-			$uid = &featureparser::getFeatureUID($feat->{name});
-			if(!defined $uid)
-			{
-				print "Error: Feature $feat->{name} not found in feature list XML\n";
-				next;
-			}
-			$feat->{uid} = $uid;
-		}
-		else
-		{
-			$uid = $feat->{uid};
-			if(!&featureparser::getFeatureInfo($uid))
-			{
-				print "Error: Feature Uid $uid not found in feature list XML\n";
-				next;
-			}
-		}
-
-		$featRef = $FeatureMap{$uid};
-		if( $featRef->{include} == 1 )
-		{
-#			Already added to the final feature list
-		}
-		else
-		{
-			$FeatureMap{$uid} = $feat;
-			push @FeatList, $feat;
-		}
-	}
-
-	foreach my $feat (@Excludes)
-	{
-		if($feat->{name})
-		{
-			$uid = &featureparser::getFeatureUID($feat->{name});
-			if(!defined $uid)
-			{
-				print "Error: Feature $feat->{name} not found in feature list XML\n";
-				next;
-			}
-			$feat->{uid} = $uid;
-		}
-		else
-		{
-			$uid = $feat->{uid};
-			if(!&featureparser::getFeatureInfo($uid))
-			{
-				print "Error: Feature Uid $uid not found in feature list XML\n";
-				next;
-			}
-		}
-
-		$featRef = $FeatureMap{$uid};
-		if( $featRef->{include} == 1 )
-		{
-			print "Error:The feature Uid $uid was added into the include as well as exclude list\n";
-			next;
-		}
-		elsif($featRef->{exclude} == 1)
-		{
-#			Already added to the final feature list
-			next;
-		}
-		else
-		{
-			$FeatureMap{$uid} = $feat;
-			push @FeatList, $feat;
-		}
-	}
-	return \@FeatList;
-}
-
-sub AddBinaryFromOby
-{
-		my $aBinary = lc shift;
-	my $aFullPath = lc shift;
-
-	my $bin = \%{$obyFileInfo{$aBinary}};
-	$bin->{IsFoundInOby}  = 1;
-	$bin->{fullpath} = $aFullPath;
-}
-
-sub GetObyBinaryInfo
-{
-	my $aBinary = lc shift;
-
-	my $aBinaryInfoHash = \%{$obyFileInfo{$aBinary}};
-
-	if( $aBinaryInfoHash->{IsFoundInOby} == 1)
-	{
-		return $aBinaryInfoHash;
-	}
-	return undef;
-}
-
-sub UpdateObyBinaryStaticDep
-{
-#	Go through the files added from Oby to see if any of their static
-#	dependencies need to be resolved.
-
-	foreach my $obyBin (keys %obyFileInfo)
-	{
-		if(!defined (&VisitedBinaryInfo($obyBin)) )
-		{
-			&ProcessStaticDep($obyFileInfo{$obyBin}{fullpath});
-		}
-	} 
-}
-
-sub SaveImageContentBinaries
-{
-	my ($binaryListRef, $aKeyword) = @_;
-	
-	foreach my $node (@$binaryListRef)
-	{
-		my %binInfo = ();
-
-#		The keywords being primary, secondary, extension, variant and device
-		$binInfo{keyword} = $aKeyword;
-
-		my @children = &genericparser::getChildElements($node);
-
-		foreach my $child (@children)
-		{
-			my $name = &genericparser::getElementName($child);
-			my $val = &genericparser::getElementValue($child);
-			$binInfo{$name} = $val;
-		}
-		push @ImageContentBinaries, \%binInfo;
-	}
-}
-
-my %VisitedBinaries = ();
-my @RomIncludeList;
-
-sub ProcessCDFList {
-
-	my ($CDFListRef) = @_;
-
-	foreach my $cdf (@$CDFListRef)
-	{
-		&LoadFromCDF($cdf);
-	}
-
-}
-
-my @padding ;
-sub LoadFromCDF
-{
-	my $cdf;
-	my $binFile;
-
-	my @BinList;
-	($cdf, $binFile) = @_;
-
-#Load the XML and get its contents
-	cdfparser::LoadCDF($cdf);
-
-#Get all binaries from the mdf
-	(@BinList) = &cdfparser::GetBinaries($cdf);
-
-	my $DynBinListRef;
-	my $aBinary;
-	my $aFile;
-
-	my $VisitedBinaryInfoHash;
-	my $indent = join('', @padding);
-	my $binInfo;
-	foreach $aBinary (@BinList)
-	{
-		$VisitedBinaryInfoHash = &VisitedBinaryInfo($aBinary);
-		if($VisitedBinaryInfoHash)
-		{
-			next;
-		}
-		else
-		{
-			$VisitedBinaryInfoHash = \%{$VisitedBinaries{$aBinary}};
-		}
-
-		&ImageContentHandler::AddBinary($aBinary);
-
-		$VisitedBinaryInfoHash->{Marked} = 1;
-		push @RomIncludeList, $aBinary;
-
-#		Include the dynamic dependencies.
-		($DynBinListRef) = cdfparser::GetDynamicDependencies($aBinary);
-		foreach $aFile (@$DynBinListRef)
-		{
-			if(grep $aFile, @BinList)
-			{
-#				the dynamic dependency is found in the same cdf file which
-#				is already loaded.
-				next;
-			}
-
-			my $new_cdf = cdfparser::GetCDFFileName($aFile);
-#			In case there is no cdf describing this binary, ignore it.
-			if( defined $new_cdf )
-			{
-				push @padding, ".";
-				LoadFromCDF($new_cdf, $aFile);
-			}
-		}
-		$binInfo = cdfparser::GetBinaryInfo($aBinary);
-		&ProcessStaticDep($binInfo->{source}, $aBinary);
-	}
-}
-
-sub ProcessStaticDep
-{
-	my ($aBinary) = @_;
-
-	my $aAbsFile;
-#	Include the static dependencies.
-
-	my $dir = "$ENV{EPOCROOT}epoc32\\release\\";
-	my $abidir = &ImageContentHandler::GetBldRomOpts("ABI_DIR");
-	my $blddir = &ImageContentHandler::GetBldRomOpts("BUILD_DIR"); 
-
-	if($aBinary =~ /(.*)\\.*/)
-	{
-		$aBinary =~ s/ABI_DIR/$abidir/i;
-		$aBinary =~ s/BUILD_DIR/$blddir/i;
-		$aBinary =~ s/DEBUG_DIR/udeb/i;
-	}
-	else
-	{
-		$dir .= $abidir . "\\";
-		$dir .= $blddir. "\\";
-	}
-	$aAbsFile = $dir. $aBinary;
-
-	if(!-f $aAbsFile)
-	{
-#		While evaluating the static dependency, check if the file is found in the 
-#		default abi directory. Otherwise, look into the binary selection order.
-		my $binSelOrderRef = &ImageContentHandler::GetBinarySelectionOrder();
-		my $foundFile = 0;
-		foreach my $newAbiDir (@$binSelOrderRef)
-		{
-			$aAbsFile =~ s/$abidir/$newAbiDir/i;
-			if(-f $aAbsFile)
-			{
-				$foundFile = 1;
-				last;
-			}
-			$abidir = $newAbiDir;
-		}
-		if($foundFile == 0)
-		{
-#While evaluating the static dependency, check if the file is found in the 
-#default abi directory. Otherwise, fallback to the default ARMV5 directory.
-			$foundFile = fallback($abidir, \$aAbsFile);
-			if($foundFile == 0)
-			{
-				return;
-			}
-
-		}
-	}
-
-#	Collect the static dependencies of this binary.
-	my (@StatDepsList) = &Dep_Lister::StaticDeps($aAbsFile);
-
-#	Remove the path portion from the file name if found to get the filename.
-#	This is the key into the BinaryInfo map maintained by cdfparser.
-	my $filename;
-
-	if( $aBinary =~ /.*\\(\S+)/)
-	{
-		$filename = $1;
-	}
-	else
-	{
-		$filename = $aBinary;
-	}
-
-	my $binaryInfoRef = cdfparser::GetBinaryInfo($filename);
-
-	if( defined $binaryInfoRef)
-	{
-#		Mark the binary it it is a valid E32 executable.
-		if(defined @StatDepsList)
-		{
-			$binaryInfoRef->{IsExecutable} = 1;
-		}
-		else
-		{
-			$binaryInfoRef->{IsExecutable} = 0;
-		}
-	}
-
-	my $VisitedBinaryInfoHash;
-	foreach my $aFile (@StatDepsList)
-	{
-		my $new_cdf = cdfparser::GetCDFFileName($aFile);
-
-		if(defined($new_cdf))
-		{
-			LoadFromCDF($new_cdf, $aFile);
-		}
-		else
-		{
-#			Include the static dependencies even if there is no mdf describing this binary
-
-			$VisitedBinaryInfoHash = &VisitedBinaryInfo($aFile);
-			if( !defined ($VisitedBinaryInfoHash) )
-			{
-				$VisitedBinaryInfoHash = \%{$VisitedBinaries{$aFile}};
-				$VisitedBinaryInfoHash->{Marked} = 1;
-				&ImageContentHandler::AddBinary($aFile);
-				&ProcessStaticDep($aFile);
-			}
-			else
-			{
-			}
-		}
-	}
-}
-
-sub VisitedBinaryInfo
-{
-	my ($aBinary) = @_;
-	my $VisitedBinaryInfoHash = \%{$VisitedBinaries{$aBinary}};
-	if($VisitedBinaryInfoHash->{Marked} == 1)
-	{
-		return $VisitedBinaryInfoHash;
-	}
-	return undef;
-}
-
-1;
+#
+# Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+#
+
+# This package processes the Image Content XML, and creates an OBY file to create a Rom image.
+package imagecontenthandler;
+
+
+require Exporter;
+@ISA=qw(Exporter);
+@EXPORT=qw(
+	ParseImageContentXML
+	ProcessImageContent
+	AddBinary
+	GetBldRomOpts
+	SetBldRomOpts
+	GenObyFile
+	GetObyFiles
+	AddBinaryFromOby
+	UpdateObyBinaryStaticDep
+	PrintMsg
+	DumpBinaries
+);
+
+use strict;
+use genericparser;
+use cdfparser;
+use dep_lister;
+use romutl;
+
+#Error list
+my @errors;
+
+my %ImageContent=();		#Image details are stored in this tree
+my $RootNode;				#The root node of the XML root document element
+my @TargetImageList;		#The list of target element nodes in the XML. These are ordered based on their 
+							#  imageid (if it is a number, else, based on the availibility of Rom locations within 0..7).
+my @binarySelectionArray;	#This array stores the ABI directories to be looked up to select binaries.
+my @ImageContentBinaries;	#This list is for the biaries mentioned in Image content XML for 
+							#  keywords like, 'primary', 'secondary', 'device', 'extension', 'variant'.
+
+# List that contains information of binary from OBY file. This list is maintained to check if their static dependencies
+#	have been included already in Rom.
+my %obyFileInfo=();
+
+my $ImageIndex=-1;
+
+my @Includes;		#List of included features. The included feature in this list is a hash table giving the 
+					#Uid or the name. These features are collected either from the Image content or the CDF XMLs.
+my @Excludes;		#List of excluded features.The excluded feature in this list is a hash table giving the 
+					#Uid or the name. These features are collected either from the Image content or the CDF XMLs.
+
+my %DefaultDirs =();#This hash table records the default ABI and the BUILD directories. These are updated in case
+					#  the overriding buildrom options are provided e.g., -D_FULL_DEBUG or -D_PLAT=GCCE etc.
+
+my @BPABIPlats = &BPABIutl::BPABIutl_Plat_List; # Add the BPABI Platforms to be added
+
+my $isEcomPlugin=0; # This flag will be set when PLUGINs are provided in the CDF file.
+
+sub ParseImageContentXML
+{
+	my $XMLFile = shift;
+
+	$XMLFile =~ s/\\/\//g;
+	$RootNode = &getRootElement($XMLFile);
+
+	&SetImageDetails(\%ImageContent, $RootNode);
+}
+
+
+my @padding;
+#This subroutine traverses the XML tree and stores the fields in the hast table %ImageContent. The keys
+#	are the branch names. For target nodes., it stores the nodes themselves in the hash table and doesn't
+#	go deeper. These nodes are processed laster. For the other nodes, it keeps traversing recursively.
+# There are some special keys used to store the nodes and values in the tree. While storing an XML::DOM
+#  node, it sores with the keys 'nodes', while, for storing a value, it is stored with the key 'vals'.
+# These are the keys used to retrieve the contents of the tree while generating the final OBY.
+sub SetImageDetails
+{
+	my ($ImageDetailRef, $ImageNode) = @_;
+	my @children = &genericparser::getChildElements($ImageNode);
+	my $child;
+	my $TreeRef;
+	my $branch;
+	my $parentName = &genericparser::getElementName($ImageNode);
+	my $childCnt = scalar @children;
+
+	my ($indent) = join('', @padding);
+
+	my $val = &genericparser::getElementValue($ImageNode);
+	$val = Trim($val);
+	if($val ne "")
+	{
+		push @{$ImageDetailRef->{vals}}, $val;
+	}
+
+	my $NodeRef;
+	foreach $child (@children)
+	{
+		$branch = &genericparser::getElementName($child);
+
+		$NodeRef = \%{$ImageDetailRef->{$branch}};
+
+		if($branch eq "cdf" and $parentName eq "romscope")
+		{
+#			Record the romscope node. This node indicates the oby files or cdf files/directories
+#			that may be used.
+			push @{$NodeRef->{nodes}}, $child;
+			next;
+		}
+		if($branch eq "target" and $parentName eq "romtarget")
+		{
+			push @{$NodeRef->{nodes}}, $child;
+			next;
+		}
+		if( ($branch =~ /primary/i  ) ||
+			($branch =~ /secondary/i) ||
+			($branch =~ /extension/i) ||
+			($branch =~ /variant/i  ) ||
+			($branch =~ /device/i   ) )
+		{
+			next;
+		}
+		
+		if( $child->hasChildNodes() )
+		{
+			$NodeRef->{hasChildren} = 1;
+			push @padding, ".";
+			SetImageDetails($NodeRef, $child);
+		}
+		else
+		{
+			$NodeRef->{hasChildren} = 0;
+		}
+
+#		Get all attributes...
+		my $attribs = &genericparser::getNodeAttributes($child);
+		my $attrib;
+
+		my $nodeName;
+		my $nodeVal;
+		my %attr=();
+		my $attrLen = $attribs->getLength;
+		for (my $pos = 0; $pos < $attrLen;$pos++)
+		{
+			$attrib = $attribs->item($pos);
+			if(!$attrib)
+			{
+				next;
+			}
+			$nodeName = lc ($attrib->getName);
+			$nodeVal = lc  ($attrib->getValue);
+			$attr{$nodeName}=$nodeVal;
+
+		}
+		push @{$NodeRef->{vals}}, \%attr;
+	}
+
+	pop @padding;
+}
+
+my @romGeometry;			#Array to store all Roms mentioned in RomGeometry
+my %romGeometryHash = ();	#This Hash table records the indices in @romGeometry array, keying on their Ids.
+
+my $curRomImageIndex;		#This scalar records the current Rom image being processed. An binary encountered
+							#  becomes part of the Rom image corresponding to this partition.
+
+# This subroutine associates the RomGeometry and the RomTarget sub-trees to set indices for the Rom-target
+#   nodes.It stores the Image content XML entries for primary/secondary/device/extension/variant keywords.
+#   It also stores the features that are included/excluded in Image content XML.
+
+sub ProcessImageContent
+{
+	my $TotalImages = &ProcessRomGeometry();
+
+	my @trgList;
+	if( defined @{$ImageContent{romtarget}{target}{nodes}})
+	{
+		@trgList = @{$ImageContent{romtarget}{target}{nodes}};
+	}
+
+#	Go through the romgeometry to find the location of each image. The valid IDs are 0 through 7.
+
+	foreach my $trg (@trgList)
+	{
+#		The ID field in romgeometry can be an integer in the range 0 through 7.
+#		If it is not a number, its location is assumed as its sequence number
+		my $imageid = &genericparser::getAttrValue($trg, "imageid");
+		if($imageid =~ /Any/i)
+		{
+			next;
+		}
+		elsif(exists $romGeometryHash{$imageid})
+		{
+			$ImageIndex = $romGeometryHash{$imageid};
+			push @{$TargetImageList[$ImageIndex]} , $trg;
+		}
+	}
+
+#	Romscope - update the maps if the files and directories are mentioned.
+	my @romScopeNodes;
+	if(defined @{$ImageContent{romscope}{cdf}{nodes}})
+	{
+		@romScopeNodes = @{$ImageContent{romscope}{cdf}{nodes}};
+	}
+
+	my $type;
+	my $file;
+	my $dir;
+	foreach my $aNode (@romScopeNodes)
+	{
+		$type = &genericparser::getAttrValue($aNode, "type");
+		if( $type =~ /dir/i)
+		{
+			$dir = &genericparser::getElementValue($aNode);
+			&cdfparser::CreateCDFFileBinaryMapFromDir($dir);
+		}
+		elsif($type =~ /file/i)
+		{
+			$file = &genericparser::getElementValue($aNode);
+			&cdfparser::CreateCDFFileBinaryMap($file);
+		}
+	}
+
+	my $availablePos = 0;
+	foreach my $trg (@trgList)
+	{
+		if(&genericparser::getAttrValue($trg, "imageid") =~ /Any/i)
+		{
+			while($availablePos < $TotalImages)
+			{
+				if( !defined($TargetImageList[$availablePos][0]) )
+				{
+					push @{$TargetImageList[$availablePos]}, $trg;
+					last;
+				}
+				$availablePos++;
+			}
+		}
+	}
+
+	my $pos = 0;
+	while( $pos < 8)
+	{
+		if( defined $TargetImageList[$pos][0] )
+		{
+#			Record the current Rom image index so that the binaries are included in the corresponding
+#			Rom image.
+#			The romGeometry and TargetImageList arrays are associated both being indexed on
+#			the Rom-image index.
+
+			$curRomImageIndex = $pos;
+			&ProcessTarget($pos, \@{$TargetImageList[$pos]});
+		}
+		$pos++;
+	}
+
+#	Pick the primary/secondary/device binaries
+	my @nodes = &genericparser::getNodeFromTree($RootNode, "options", "primary", "file");
+	if( defined @nodes)
+	{
+		&SaveImageContentBinaries(\@nodes, "primary");
+	}
+
+	@nodes = &genericparser::getNodeFromTree($RootNode, "options", "secondary", "file");
+	if( defined @nodes)
+	{
+		&SaveImageContentBinaries(\@nodes, "secondary");
+	}
+
+	@nodes = &genericparser::getNodeFromTree($RootNode, "options", "extension", "file");
+	if( defined @nodes)
+	{
+		&SaveImageContentBinaries(\@nodes, "extension");
+	}
+
+	@nodes = &genericparser::getNodeFromTree($RootNode, "options", "variant", "file");
+	if( defined @nodes)
+	{
+		&SaveImageContentBinaries(\@nodes, "variant");
+	}
+
+	@nodes = &genericparser::getNodeFromTree($RootNode, "options", "device", "file");
+	if( defined @nodes)
+	{
+		&SaveImageContentBinaries(\@nodes, "device");
+	}
+
+	foreach my $imgBin (@ImageContentBinaries)
+	{
+		&ProcessStaticDep($imgBin->{source});
+	}
+
+#	Pick the binary selection order
+	if (exists($ImageContent{options}{binaryselectionorder}{vals}))
+	{
+	    my ($abiDirs) = @{$ImageContent{options}{binaryselectionorder}{vals}};
+	    @binarySelectionArray = split(',', $abiDirs);
+	    @binarySelectionArray = Trim(@binarySelectionArray);
+
+	}
+
+	my $featureList = &cdfparser::GetIncludedFeatureList();
+	foreach my $feature (@$featureList)
+	{
+		push @Includes, $feature;
+	}
+
+	$featureList = &cdfparser::GetExcludedFeatureList();
+	foreach my $feature (@$featureList)
+	{
+		push @Excludes, $feature;
+	}
+}
+
+#Arrange the Rom-geometry according to their Id when they are numbers. The named images
+#are arranged starting from the empty slots in Rom geometry array.
+sub ProcessRomGeometry
+{
+	my $RomImageCount = 0;
+	my $pos = 0;
+	while($pos < 8)
+	{
+		$romGeometry[$pos++] = undef;
+	}
+
+	my @roms = @{$ImageContent{romgeometry}{image}{vals}};
+	$RomImageCount = scalar (@roms);
+	my @namedImages;
+
+#	Visit all images and allocate them the indices they mention.
+	foreach my $img (@roms)
+	{
+		if($img->{id} =~ /(\d+)/)
+		{
+			$pos = $1;
+			if( defined($romGeometry[$pos]) )
+			{
+				print "Error: $romGeometry[$pos]->{id} and $img->{id} cant be allocated the same position\n";
+				exit;
+			}
+			$romGeometry[$pos] = $img;
+
+#			Record the index of this Rom
+			$romGeometryHash{$img->{id}} = $pos;
+		}
+		else
+		{
+#			These are the named images that are allocated there positions sequentially starting from
+#			the first available empty position
+			push @namedImages, $img;
+		}
+	}
+
+#	Revisit the images and allocate the remaining (unallocated) positions.
+
+	$pos = 0;
+	my $namedImageCount = scalar (@namedImages);
+	my $firstNamedImgIdx = 0;
+	my $img;
+	while(	($pos < 8) and ($namedImageCount > 0) )
+	{
+		if( $romGeometry[$pos] )
+		{
+#			skip the positions already allocated.
+			$pos++;
+			next;
+		}
+		$img = $namedImages[$firstNamedImgIdx];
+		$romGeometry[$pos] = $img;
+
+#		Record the index of this Rom
+		$romGeometryHash{$img->{id}} = $pos;
+		
+		$pos++;$firstNamedImgIdx++;
+		$namedImageCount--;
+	}
+
+	return $RomImageCount;
+}
+
+my @ObyFileList;
+
+#This subrouting processes the target nodes that may include OBYs/CDFs or features. For CDFs, the satic/dynamic
+#  dependencies are evaluated.
+
+sub ProcessTarget
+{
+	my ($ImgPos , $trgNodesRef) = @_;
+	my @cdfFileList;
+
+#	For all the 'target' nodes associated with an image in romgeometry at the given index...
+#	The link between a target and an image in romGeometry is the image id. If the imageid
+#	of a target is 'Any', then the first available image in romGeometry is allocated to
+#	that target.
+
+	foreach my $target (@$trgNodesRef)
+	{
+
+#		Fetch any cdfs included within the Image Content file
+		my @cdfs = &getNodeFromTree($target, "include","cdf");
+
+		my $type;
+		my $file;
+		my $dir;
+		foreach my $cdfNode (@cdfs)
+		{
+			$type = &genericparser::getAttrValue($cdfNode, "type");
+			
+			if( !($type) || ($type eq "file") )
+			{
+				$file = &genericparser::getElementValue($cdfNode);
+				push @cdfFileList, $file;
+			}
+			elsif($type eq "dir")
+			{
+				$dir = &genericparser::getElementValue($cdfNode);
+				&cdfparser::CreateCDFFileBinaryMapFromDir($dir);
+			}
+		}
+
+#		Collect all the obey files mentioned in this 'target' node.
+		my @obys = &getNodeFromTree($target, "include","obyFile");
+		foreach my $obyNode (@obys)
+		{
+			$file = &genericparser::getElementValue($obyNode);
+			push @ObyFileList, $file;
+		}
+
+		&CollectFeatures($target, 1, \@Includes);
+		&CollectFeatures($target, 0, \@Excludes);
+	}
+
+	ProcessCDFList(\@cdfFileList);
+}
+
+# This subroutine updates the include or exclude feature list collected from Image content XML.
+sub CollectFeatures
+{
+#	Collect all the features included/excluded in this 'target' node.
+
+	my ($target, $Inc, $IncludeExcludeListRef) = @_;
+	my $IncExcStr;
+	if($Inc == 1)
+	{
+		$IncExcStr = "include";
+	}
+	else
+	{
+		$IncExcStr = "exclude";
+	}
+
+	my @nodes = &getNodeFromTree($target, $IncExcStr,"feature");
+
+	foreach my $node (@nodes)
+	{
+		my %aFeatureInfo = ();
+		my $isValidFeature = 0;
+		my $feature = &genericparser::getAttrValue($node, "name");
+
+		if($Inc)
+		{
+#			Mark the feature included.
+			$aFeatureInfo{include} = 1;
+		}
+		else
+		{
+#			Mark the feature excluded.
+			$aFeatureInfo{exclude} = 1;
+		}
+
+		if(defined $feature and $feature ne "")
+		{
+			$aFeatureInfo{name}= $feature;
+			$aFeatureInfo{uid} = undef;
+			$isValidFeature = 1;
+		}
+		else
+		{
+			$feature = &genericparser::getAttrValue($node, "uid");
+			if(!defined $feature or $feature eq "")
+			{
+				print "Warning: Neither feature name nor uid is defined \n";
+			}
+			else
+			{
+				if(&featureparser::ValidateUIDValue($feature))
+				{
+					$feature = &featureparser::ConvertHexToDecimal($feature);
+					$aFeatureInfo{uid}= $feature;
+					$aFeatureInfo{name}= undef;
+					$isValidFeature = 1;
+				}
+				else
+				{
+					print "The uid value $feature specified in the Image Content Description is not a valid number\n";
+				}
+			}
+		}
+
+		if($isValidFeature)
+		{
+			push @$IncludeExcludeListRef, \%aFeatureInfo;
+		}
+	}
+}
+
+sub DumpImageDetails
+{
+	my ($HRef) = @_;
+	my %hash = %$HRef;
+	my $ChildHRef;
+
+	foreach my $Key (keys %hash)
+	{
+		if($Key eq "hasChildren" || $Key eq "vals")
+		{
+			next;
+		}
+		my $indent = join('', @padding);
+		&PrintMsg ($indent. $Key);
+		if($hash{$Key}{hasChildren} == 1)
+		{
+			push @padding, ".";
+			&PrintMsg ("\n");
+			$ChildHRef = \%{$hash{$Key}};
+			&DumpImageDetails($ChildHRef);
+		}
+		elsif( defined ($hash{$Key}{vals}) )
+		{
+			&PrintMsg ("\nVals $hash{$Key}{vals}\n");
+			push @padding, ".";
+			$indent = join('', @padding);
+			my @array = @{$hash{$Key}{vals}};
+			&PrintMsg ("array len = " . scalar(@array) . "\n");
+			foreach my $attrib ( @array )
+			{
+				foreach my $key1 (keys %$attrib)
+				{
+					&PrintMsg ($indent . $Key. " ". "$key1=$$attrib{$key1}\n");
+				}
+				&PrintMsg ("\n");
+			}
+		}
+		elsif( defined (@{$hash{$Key}{nodes}}) )
+		{
+			my $node = $hash{$Key}{nodes}[0];
+			&PrintMsg ("{". scalar(@{$hash{$Key}{nodes}})."}\n");
+		}
+	}
+	pop @padding;
+}
+
+sub CheckErrors
+{
+	if($#errors > -1)
+	{
+		&PrintMsg ("errors..........$#errors \n");
+		foreach (@errors)
+		{
+			&PrintMsg ($_ ."\n");
+		}
+		exit;
+	}
+}
+
+my @ImageBinaryList;#2d array storing the list of binaries per rom image
+sub AddBinary
+{
+	my ($binaryName) = @_;
+	{
+		push @{$ImageBinaryList[$curRomImageIndex]}, $binaryName;
+	}
+}
+
+sub SetBldRomOpts
+{
+	my ($key, $value) = @_;
+	if( $key eq undef )
+	{
+#		The default ABI directory is armv5 unless specified otherwise in the buildrom command-line.
+#		The default build directory is urel unless specified otherwise in the buildrom command-line.
+		$DefaultDirs{ABI_DIR} = 'ARMV5';
+		$DefaultDirs{BUILD_DIR}='urel';
+
+		$DefaultDirs{DEST_DIR}= "\/sys\/bin";
+
+	}
+	else
+	{
+#		trim the value for leading/trailing whitespace
+		$value = Trim($value);
+		$DefaultDirs{$key} = $value;
+	}
+}
+
+sub Trim()
+{
+	my @out = @_;
+	for (@out) {
+		s/^\s+//;
+		s/\s+$//;
+	}
+	return wantarray ? @out : $out[0];
+}
+
+sub GetBldRomOpts
+{
+	my ($key) = @_;
+	return $DefaultDirs{$key};
+}
+
+sub DumpBinaries
+{
+	&PrintMsg ("***********Binaries in ROM***********\n");
+	my $img_idx = 0;
+	while ($img_idx < 8 and defined ($ImageBinaryList[$img_idx]))
+	{
+		my @list = @{$ImageBinaryList[$img_idx]};
+		&PrintMsg ("Image $img_idx has ". scalar (@list ) . " binaries\n");
+		foreach my $bin (@list)
+		{
+			&PrintMsg ("file[$img_idx]=$bin\n");
+		}
+		$img_idx++;
+	}
+
+	&PrintMsg ("***********END***********\n");
+}
+
+sub PrintMsg
+{
+	my ($msg) = @_;
+	print "$msg";
+}
+
+# This subroutine is used to generate OBY-contents based on contents of the Image content XML. The image content XML 
+#   may have, in turn, included other OBYs/CDFs. These contents are appended to the Phase-I OBY file (where, the 
+#   Phase-I OBY file is generated by the preprocessor which is the conglomeration of all the buildrom supplied OBY files).
+sub GenObyFile
+{
+	my ($ObyFileName) = @_;
+	open (OBYFH, ">>$ObyFileName") or die("* Can't open $ObyFileName\n");
+	my $binRef;
+	my $line;
+	my $index;
+	my $new_src_path;
+	my $exec_src_path = &get_epocroot;#This is the Executable source path
+	$exec_src_path .= "epoc32\/release\/";
+	my $abidir = $DefaultDirs{ABI_DIR};
+	my $blddir = $DefaultDirs{BUILD_DIR};
+
+	GenObyHeader(*OBYFH);
+
+	for($index = 0;$index < 8;$index++)
+	{
+		if( !defined $romGeometry[$index] )
+		{
+			next;
+		}
+
+		$line = "rom_image $index ";
+		$line .= $romGeometry[$index]{name} . " ";
+		$line .= "size=" . $romGeometry[$index]{size} . " ";
+		if( $romGeometry[$index]{type} =~ /nonxip/)
+		{
+			$line .= " non-xip ";
+		}
+		else
+		{
+			$line .= " xip ";
+		}
+
+		$line .= $romGeometry[$index]{compression} . " ";
+		if($romGeometry[$index]{extension} eq "yes")
+		{
+			$line .= " extension ";
+		}
+
+		$line .= "\n";
+
+		print OBYFH $line;
+
+		$line = "ROM_IMAGE[$index] {\n";	#Start of contents of this image
+		print OBYFH $line;
+
+		foreach my $binary (@{$ImageBinaryList[$index]}) {
+			$binRef = &cdfparser::GetBinaryInfo($binary);
+			if( defined ($binRef) and $binRef->{IsFoundInCDF})
+			{
+				if(exists $binRef->{default})
+				{
+					$line = "DEFAULT_LANGUAGE $binRef->{default} \n";
+					print OBYFH "$line";
+				}
+				
+				if(exists $binRef->{language})
+				{
+					my $langCodes = $binRef->{language};
+ 					foreach my $lang (@$langCodes)
+					{
+						$line = "LANGUAGE_CODE $lang \n";
+						print OBYFH "$line";
+					}
+				}
+
+#				Replace the BUILD_DIR with udeb or urel
+#				Default BUILD_DIR is urel and can be overridden by using cmd line option '_FULL_DEBUG'
+#				If a binary is to be picked always from udeb, then the src path in CDF must be mentioned
+#				as udeb e.g. <source>abi_dir\udeb\drtaeabi.dll</source>, in which case, the mentioned dir
+#				is picked as it is.
+
+				$new_src_path = $binRef->{source};
+
+				$new_src_path =~ s/ABI_DIR/$abidir/i;
+				$new_src_path =~ s/BUILD_DIR/$blddir/i;
+				$new_src_path =~ s/DEBUG_DIR/udeb/i;
+
+				$new_src_path =~ s/epocroot/EPOCROOT/;
+				$new_src_path =~ s/zresource/ZRESOURCE/;
+				$new_src_path =~ s/zprivate/ZPRIVATE/;
+				$new_src_path =~ s/zsystem/ZSYSTEM/;
+
+				
+				my $FileFound = 0;
+				
+				if($binRef->{IsExecutable})
+				{
+					$new_src_path = $exec_src_path . $new_src_path;
+					if(!-f $new_src_path)
+					{
+						foreach my $newAbiDir (@binarySelectionArray)
+						{
+							$new_src_path =~ s/$abidir/$newAbiDir/i;
+							if(-f $new_src_path)
+							{
+								$FileFound = 1;
+								last;
+							}
+							$abidir = $newAbiDir;
+						}
+
+						if( !$FileFound )
+						{
+							$FileFound = fallback($abidir, \$new_src_path);
+  							if( !$FileFound )
+							{
+								print "Missing file $binRef->{source} \n";
+								$new_src_path = $binRef->{source};
+							}
+
+						}
+					}
+#					compress options
+					if(exists $binRef->{compress} and ($binRef->{compress} eq "uncompress") )
+					{
+						$line = "fileuncompress=";
+					}
+					elsif($binRef->{compress} eq "compress")
+					{
+						$line = "filecompress=";
+					}
+					elsif( exists $binRef->{dll})
+					{
+						$line = "dll=";
+					}
+#					Checks the plugin type
+					elsif( exists $binRef->{type} and $binRef->{type} eq "plugin")
+					{
+						if (exists $binRef->{plugin_name})
+						{
+							$isEcomPlugin=1;
+							$line = "__$binRef->{plugin_name}_PLUGIN(ABI_DIR\/BUILD_DIR,ECOM_BIN_DIR,DATAZ_,ECOM_RSC_DIR,$binRef->{id},$binRef->{id})\n";
+						}
+					}
+					else
+					{
+						$isEcomPlugin=0;
+						$line = "file=";
+					}
+
+					if (!$isEcomPlugin)
+					{
+						$line .= $new_src_path . " ";
+						$line .= $binRef->{destination};
+					}
+
+
+#					stack,heap,fixed,priority,uid,dll,dlldatatop
+					if( exists $binRef->{stack})
+					{
+						$line .= " stack " . $binRef->{stack};
+					}
+					if( exists $binRef->{heapmin})
+					{
+						$line .= " heapmin " . $binRef->{heapmin};
+					}
+					if( exists $binRef->{heapmax})
+					{
+						$line .= " heapmax " . $binRef->{heapmax};
+					}
+					if( exists $binRef->{fixed})
+					{
+						$line .= " fixed";
+					}
+					if( exists $binRef->{priority})
+					{
+						$line .= " priority " . $binRef->{priority};
+					}
+					if( exists $binRef->{uid1})
+					{
+						$line .= " uid1 " . $binRef->{uid1};
+					}
+					if( exists $binRef->{uid2})
+					{
+						$line .= " uid2 " . $binRef->{uid2};
+					}
+					if( exists $binRef->{uid3})
+					{
+						$line .= " uid3 " . $binRef->{uid3};
+					}
+					if( exists $binRef->{dlldatatop})
+					{
+						$line .= " dlldatatop ". $binRef->{dlldatatop}; 
+					}
+					if( exists $binRef->{customisable} and $binRef->{customisable} eq "true")
+					{
+						$line .= " patched ";
+					}
+				}
+				else
+				{
+					my $type = $binRef->{type};
+					if($type =~ /normal/i)
+					{
+						$line = "data=";
+					}
+					if($type =~ /aif/i)
+					{
+						$line = "aif=";
+					}
+					elsif($type =~ /compressedbitmap/i)
+					{
+						$line = "compressed-bitmap=";
+					}
+					elsif($type =~ /autobitmap/i)
+					{
+						$line = "auto-bitmap=";
+					}
+					elsif($type =~ /bitmap/i)
+					{
+						$line = "bitmap=";
+					}
+
+					if(exists $binRef->{multilinguify})
+					{
+						my $extension;
+						my $srcNameWithoutExt;
+						my $dstNameWithoutExt;
+
+						if($new_src_path =~ /(.*)\.(.*)/)
+						{
+							$srcNameWithoutExt = $1;
+							$extension = $2;
+						}
+						if($binRef->{destination} =~ /(.*)\.(.*)/)
+						{
+							$dstNameWithoutExt = $1;
+						}
+
+						$line .= "MULTI_LINGUIFY(";
+						$line .= $extension . " ";
+						$line .= $srcNameWithoutExt . " ";
+						$line .= $dstNameWithoutExt;
+						$line .= ") ";
+					}
+					else
+					{
+						$line .= $new_src_path . " ";
+						$line .= $binRef->{destination};
+					}
+				}
+
+				$line .= "\n";
+				print OBYFH $line;
+			}
+			else
+			{
+				#Check if the binary is from ImageContent XML file.
+				my $imagecontentbin = 0;
+				foreach my $bin (@ImageContentBinaries) {
+					my $source;
+					if( $bin->{source} =~ /.*[\\\/](\S+)/)
+					{
+						$source = $1;
+					}
+					if (grep /$binary/i, $source) {#Skip the binary that is already included in the OBY Header
+						$imagecontentbin = 1;
+						next;
+					}
+				}
+
+				if ($imagecontentbin) {
+					next;
+				}
+				my $obyInfo = &ImageContentHandler::GetObyBinaryInfo($binary);
+				if(!defined $obyInfo)
+				{
+					$line = "file=" . $exec_src_path. $DefaultDirs{ABI_DIR}. "\/" . $DefaultDirs{BUILD_DIR}. "\/". $binary. " ";
+					$line .= $DefaultDirs{DEST_DIR}. "\/". $binary;
+					$line .= "\n";
+					print OBYFH $line;
+				}
+			}
+		}
+		$line = "\n}\n";
+		print OBYFH $line;
+	}
+	close OBYFH;
+}
+
+#Sets default target to ARMV5 directory if the requested binary is not found
+sub fallback{
+	
+	my ($abidir, $abiFileRef) = @_;
+	my $foundFile=0;
+	foreach my $BpabiPlat (@BPABIPlats)
+	{
+		if ($$abiFileRef =~ /^(.*)[\/\\]$BpabiPlat[\/\\](.*)$/)
+		{
+			$$abiFileRef =~ s/$abidir/ARMV5/i;
+			if(-f $$abiFileRef)
+			{
+				$foundFile = 1;
+				last;
+			}
+		}
+	}
+	return $foundFile;
+}
+
+# This subroutine generates the Rom configuration details like, 'bootbinary', 'romlinearbase', romalign,
+#   'kerneldataaddress', 'kernelheapmin' etc.
+sub GenObyHeader
+{
+	my ($fh) = @_;
+	my $line;
+
+#	version
+	if( defined @{$ImageContent{version}{vals}})
+	{
+		my $ver = @{$ImageContent{version}{vals}}[0];
+		if(defined $ver)
+		{
+			$line = "version=$ver\n";
+			print $fh $line;
+		}
+	}
+
+#	romchecksum
+	if( defined @{$ImageContent{romchecksum}{vals}})
+	{
+		my $cksum = @{$ImageContent{romchecksum}{vals}}[0];
+		if(defined $cksum)
+		{
+			$line = "romchecksum=$cksum\n";
+			print $fh $line;
+		}
+	}
+
+#	time
+	if( defined @{$ImageContent{time}{vals}})
+	{
+		my $time = @{$ImageContent{time}{vals}}[0];
+		if(defined $time)
+		{
+			$line = "time=ROMDATE $time\n";
+			print $fh $line;
+		}
+	}
+
+
+#	The Binary selection order
+	if(scalar @binarySelectionArray )
+	{
+		my $abilist = join (',', @binarySelectionArray);
+		$line = "\nBINARY_SELECTION_ORDER $abilist\n";
+		print $fh $line;
+	}
+
+#	trace
+	if( defined @{$ImageContent{options}{trace}{vals}})
+	{
+		my @traceFlags = @{$ImageContent{options}{trace}{vals}};
+		if(scalar @traceFlags)
+		{
+			$line = "trace $traceFlags[0]\n";
+			print $fh $line;
+		}
+	}
+
+#	The bootbinary
+	if( defined @{$ImageContent{options}{bootbinary}{vals}})
+	{
+		my $binary;
+		my @bootbin = @{$ImageContent{options}{bootbinary}{vals}};
+		if(scalar @bootbin)
+		{
+			$binary = $bootbin[0];
+			$binary =~ s/abi_dir/ABI_DIR/;
+ 			$line = "bootbinary=$binary\n";
+			print $fh $line;
+		}
+	}
+
+
+#	dataaddress
+	if( defined @{$ImageContent{options}{dataaddress}{vals}})
+	{
+		my @dataAddr = @{$ImageContent{options}{dataaddress}{vals}};
+		if(scalar @dataAddr)
+		{
+			$line = "dataaddress=$dataAddr[0]\n";
+			print $fh $line;
+		}
+	}
+
+#	debugport
+	if( defined @{$ImageContent{options}{debugport}{vals}})
+	{
+		my @dgbPort = @{$ImageContent{options}{debugport}{vals}};
+		if(scalar @dgbPort)
+		{
+			$line = "debugport=$dgbPort[0]\n";
+			print $fh $line;
+		}
+	}
+
+#	defaultstackreserve
+	if( defined @{$ImageContent{options}{defaultstackreserve}{vals}})
+	{
+		my @defStackRes = @{$ImageContent{options}{defaultstackreserve}{vals}};
+		if(scalar @defStackRes)
+		{
+			$line = "defaultstackreserve=$defStackRes[0]\n";
+			print $fh $line;
+		}
+	}
+
+#	wrapper
+	if( defined @{$ImageContent{options}{wrapper}{vals}})
+	{
+		my %tbl = @{$ImageContent{options}{wrapper}{vals}}[0];
+		if(exists $tbl{epoc})
+		{
+			$line = "epocwrapper\n";
+			print $fh $line;
+		}
+		elsif(exists $tbl{coff})
+		{
+			$line = "coffwrapper\n";
+			print $fh $line;
+		}
+		elsif(exists $tbl{none})
+		{
+			$line = "nowrapper\n";
+			print $fh $line;
+		}
+	}
+
+#	kernel options
+	my $val;
+	if( defined @{$ImageContent{options}{kernel}{name}{vals}})
+	{
+		$val = @{$ImageContent{options}{kernel}{name}{vals}}[0];
+		$line = "kernelromname=$val\n";
+		print $fh $line;
+	}
+	if( defined @{$ImageContent{options}{kernel}{dataaddress}{vals}})
+	{
+		$val = @{$ImageContent{options}{kernel}{dataaddress}{vals}}[0];
+		$line = "kerneldataaddress=$val\n";
+		print $fh $line;
+	}
+	if( defined @{$ImageContent{options}{kernel}{trace}{vals}})
+	{
+		$val = @{$ImageContent{options}{kernel}{trace}{vals}}[0];
+		$line = "kerneltrace $val\n";
+		print $fh $line;
+	}
+	if( defined @{$ImageContent{options}{kernel}{heapmin}{vals}})
+	{
+		$val = @{$ImageContent{options}{kernel}{heapmin}{vals}}[0];
+		$line = "kernelheapmin=$val\n";
+		print $fh $line;
+	}
+	if( defined @{$ImageContent{options}{kernel}{heapmax}{vals}})
+	{
+		$val = @{$ImageContent{options}{kernel}{heapmax}{vals}}[0];
+		$line = "kernelheapmax=$val\n";
+		print $fh $line;
+	}
+#	romlinearbase
+	if( defined @{$ImageContent{options}{romlinearbase}{vals}})
+	{
+		my @romLinBase = @{$ImageContent{options}{romlinearbase}{vals}};
+		if(scalar @romLinBase)
+		{
+			$line = "romlinearbase=$romLinBase[0]\n";
+			print $fh $line;
+		}
+	}
+
+#   romalign
+	if( defined @{$ImageContent{options}{romalign}{vals}})
+	{
+		my @romAlign = @{$ImageContent{options}{romalign}{vals}};
+		if(scalar @romAlign )
+		{
+			$line = "romalign=$romAlign[0]\n";
+			print $fh $line;
+		}
+	}
+
+
+
+
+#	autosize keyword with the block size
+	if( defined @{$ImageContent{options}{autosize}{vals}})
+	{
+		my @autoSz = @{$ImageContent{options}{autosize}{vals}};
+		if(scalar @autoSz )
+		{
+			$line = "autosize=$autoSz[0]\n";
+			print $fh $line;
+		}
+	}
+
+#	coreimage keyword with the coreimage name.
+	if( defined @{$ImageContent{options}{coreimage}{vals}})
+	{
+		my @coreImg = @{$ImageContent{options}{coreimage}{vals}};
+		if(scalar @coreImg)
+		{
+			$line = "coreimage=$coreImg[0]\n";
+			print $fh $line;
+		}
+	}
+
+
+
+	foreach my $imgBin (@ImageContentBinaries)
+	{
+		$line = $imgBin->{keyword};
+		my $srcPath = $imgBin->{source};
+		$srcPath =~ s/abi_dir/ABI_DIR/;
+		$srcPath =~ s/kernel_dir/KERNEL_DIR/;
+		$srcPath =~ s/debug_dir/DEBUG_DIR/;
+		$srcPath =~ s/build_dir/BUILD_DIR/;
+		if(! ($imgBin->{keyword} =~ /secondary/i) )
+		{
+#			VARID mentioned for primary, device, extension and variant keywords.
+			$line .= "[VARID]" ;
+		}
+		$line .= "=" . $srcPath . "\t\t" .  $imgBin->{destination};
+		for my $key (keys %$imgBin)
+		{
+			if( ($key =~ /keyword/i) ||
+				($key =~ /source/i) ||
+				($key =~ /destination/i))
+			{
+#				These keys are already taken care.
+				next;
+			}
+
+#			Write the rest of the keywords if any, (e.g., 'fixed' or HEAPMAX(0x40000) ) to the oby line.
+			$line .= " ".($key);
+			if( defined $imgBin->{$key})
+			{
+				$line .= "(". $imgBin->{$key}. ") ";
+			}
+		}
+		print $fh "$line\n";
+	}
+}
+
+sub GetObyFiles
+{
+	return \@ObyFileList;
+}
+
+sub GetBinarySelectionOrder
+{
+	return \@binarySelectionArray;
+}
+
+sub GetFeatures()
+{
+	my %FeatureMap = ();
+	my @FeatList;
+	my $featRef;
+	my $uid;
+	foreach my $feat (@Includes)
+	{
+		if($feat->{name})
+		{
+			$uid = &featureparser::getFeatureUID($feat->{name});
+			if(!defined $uid)
+			{
+				print "Error: Feature $feat->{name} not found in feature list XML\n";
+				next;
+			}
+			$feat->{uid} = $uid;
+		}
+		else
+		{
+			$uid = $feat->{uid};
+			if(!&featureparser::getFeatureInfo($uid))
+			{
+				print "Error: Feature Uid $uid not found in feature list XML\n";
+				next;
+			}
+		}
+
+		$featRef = $FeatureMap{$uid};
+		if( $featRef->{include} == 1 )
+		{
+#			Already added to the final feature list
+		}
+		else
+		{
+			$FeatureMap{$uid} = $feat;
+			push @FeatList, $feat;
+		}
+	}
+
+	foreach my $feat (@Excludes)
+	{
+		if($feat->{name})
+		{
+			$uid = &featureparser::getFeatureUID($feat->{name});
+			if(!defined $uid)
+			{
+				print "Error: Feature $feat->{name} not found in feature list XML\n";
+				next;
+			}
+			$feat->{uid} = $uid;
+		}
+		else
+		{
+			$uid = $feat->{uid};
+			if(!&featureparser::getFeatureInfo($uid))
+			{
+				print "Error: Feature Uid $uid not found in feature list XML\n";
+				next;
+			}
+		}
+
+		$featRef = $FeatureMap{$uid};
+		if( $featRef->{include} == 1 )
+		{
+			print "Error:The feature Uid $uid was added into the include as well as exclude list\n";
+			next;
+		}
+		elsif($featRef->{exclude} == 1)
+		{
+#			Already added to the final feature list
+			next;
+		}
+		else
+		{
+			$FeatureMap{$uid} = $feat;
+			push @FeatList, $feat;
+		}
+	}
+	return \@FeatList;
+}
+
+sub AddBinaryFromOby
+{
+		my $aBinary = lc shift;
+	my $aFullPath = lc shift;
+
+	my $bin = \%{$obyFileInfo{$aBinary}};
+	$bin->{IsFoundInOby}  = 1;
+	$bin->{fullpath} = $aFullPath;
+}
+
+sub GetObyBinaryInfo
+{
+	my $aBinary = lc shift;
+
+	my $aBinaryInfoHash = \%{$obyFileInfo{$aBinary}};
+
+	if( $aBinaryInfoHash->{IsFoundInOby} == 1)
+	{
+		return $aBinaryInfoHash;
+	}
+	return undef;
+}
+
+sub UpdateObyBinaryStaticDep
+{
+#	Go through the files added from Oby to see if any of their static
+#	dependencies need to be resolved.
+
+	foreach my $obyBin (keys %obyFileInfo)
+	{
+		if(!defined (&VisitedBinaryInfo($obyBin)) )
+		{
+			&ProcessStaticDep($obyFileInfo{$obyBin}{fullpath});
+		}
+	} 
+}
+
+sub SaveImageContentBinaries
+{
+	my ($binaryListRef, $aKeyword) = @_;
+	
+	foreach my $node (@$binaryListRef)
+	{
+		my %binInfo = ();
+
+#		The keywords being primary, secondary, extension, variant and device
+		$binInfo{keyword} = $aKeyword;
+
+		my @children = &genericparser::getChildElements($node);
+
+		foreach my $child (@children)
+		{
+			my $name = &genericparser::getElementName($child);
+			my $val = &genericparser::getElementValue($child);
+			$binInfo{$name} = $val;
+		}
+		push @ImageContentBinaries, \%binInfo;
+	}
+}
+
+my %VisitedBinaries = ();
+my @RomIncludeList;
+
+sub ProcessCDFList {
+
+	my ($CDFListRef) = @_;
+
+	foreach my $cdf (@$CDFListRef)
+	{
+		&LoadFromCDF($cdf);
+	}
+
+}
+
+my @padding ;
+sub LoadFromCDF
+{
+	my $cdf;
+	my $binFile;
+
+	my @BinList;
+	($cdf, $binFile) = @_;
+
+#Load the XML and get its contents
+	cdfparser::LoadCDF($cdf);
+
+#Get all binaries from the mdf
+	(@BinList) = &cdfparser::GetBinaries($cdf);
+
+	my $DynBinListRef;
+	my $aBinary;
+	my $aFile;
+
+	my $VisitedBinaryInfoHash;
+	my $indent = join('', @padding);
+	my $binInfo;
+	foreach $aBinary (@BinList)
+	{
+		$VisitedBinaryInfoHash = &VisitedBinaryInfo($aBinary);
+		if($VisitedBinaryInfoHash)
+		{
+			next;
+		}
+		else
+		{
+			$VisitedBinaryInfoHash = \%{$VisitedBinaries{$aBinary}};
+		}
+
+		&ImageContentHandler::AddBinary($aBinary);
+
+		$VisitedBinaryInfoHash->{Marked} = 1;
+		push @RomIncludeList, $aBinary;
+
+#		Include the dynamic dependencies.
+		($DynBinListRef) = cdfparser::GetDynamicDependencies($aBinary);
+		foreach $aFile (@$DynBinListRef)
+		{
+			if(grep $aFile, @BinList)
+			{
+#				the dynamic dependency is found in the same cdf file which
+#				is already loaded.
+				next;
+			}
+
+			my $new_cdf = cdfparser::GetCDFFileName($aFile);
+#			In case there is no cdf describing this binary, ignore it.
+			if( defined $new_cdf )
+			{
+				push @padding, ".";
+				LoadFromCDF($new_cdf, $aFile);
+			}
+		}
+		$binInfo = cdfparser::GetBinaryInfo($aBinary);
+		&ProcessStaticDep($binInfo->{source}, $aBinary);
+	}
+}
+
+sub ProcessStaticDep
+{
+	my ($aBinary) = @_;
+
+	my $aAbsFile;
+#	Include the static dependencies.
+
+	my $dir = &get_epocroot()."epoc32\/release\/";
+	my $abidir = &ImageContentHandler::GetBldRomOpts("ABI_DIR");
+	my $blddir = &ImageContentHandler::GetBldRomOpts("BUILD_DIR"); 
+
+	if($aBinary =~ /(.*)[\\\/].*/)
+	{
+		$aBinary =~ s/ABI_DIR/$abidir/i;
+		$aBinary =~ s/BUILD_DIR/$blddir/i;
+		$aBinary =~ s/DEBUG_DIR/udeb/i;
+	}
+	else
+	{
+		$dir .= $abidir . "\/";
+		$dir .= $blddir. "\/";
+	}
+	$aAbsFile = $dir. $aBinary;
+
+	if(!-f $aAbsFile)
+	{
+#		While evaluating the static dependency, check if the file is found in the 
+#		default abi directory. Otherwise, look into the binary selection order.
+		my $binSelOrderRef = &ImageContentHandler::GetBinarySelectionOrder();
+		my $foundFile = 0;
+		foreach my $newAbiDir (@$binSelOrderRef)
+		{
+			$aAbsFile =~ s/$abidir/$newAbiDir/i;
+			if(-f $aAbsFile)
+			{
+				$foundFile = 1;
+				last;
+			}
+			$abidir = $newAbiDir;
+		}
+		if($foundFile == 0)
+		{
+#While evaluating the static dependency, check if the file is found in the 
+#default abi directory. Otherwise, fallback to the default ARMV5 directory.
+			$foundFile = fallback($abidir, \$aAbsFile);
+			if($foundFile == 0)
+			{
+				return;
+			}
+
+		}
+	}
+
+#	Collect the static dependencies of this binary.
+	my (@StatDepsList) = &Dep_Lister::StaticDeps($aAbsFile);
+
+#	Remove the path portion from the file name if found to get the filename.
+#	This is the key into the BinaryInfo map maintained by cdfparser.
+	my $filename;
+
+	if( $aBinary =~ /.*[\\\/](\S+)/)
+	{
+		$filename = $1;
+	}
+	else
+	{
+		$filename = $aBinary;
+	}
+
+	my $binaryInfoRef = cdfparser::GetBinaryInfo($filename);
+
+	if( defined $binaryInfoRef)
+	{
+#		Mark the binary it it is a valid E32 executable.
+		if(defined @StatDepsList)
+		{
+			$binaryInfoRef->{IsExecutable} = 1;
+		}
+		else
+		{
+			$binaryInfoRef->{IsExecutable} = 0;
+		}
+	}
+
+	my $VisitedBinaryInfoHash;
+	foreach my $aFile (@StatDepsList)
+	{
+		my $new_cdf = cdfparser::GetCDFFileName($aFile);
+
+		if(defined($new_cdf))
+		{
+			LoadFromCDF($new_cdf, $aFile);
+		}
+		else
+		{
+#			Include the static dependencies even if there is no mdf describing this binary
+
+			$VisitedBinaryInfoHash = &VisitedBinaryInfo($aFile);
+			if( !defined ($VisitedBinaryInfoHash) )
+			{
+				$VisitedBinaryInfoHash = \%{$VisitedBinaries{$aFile}};
+				$VisitedBinaryInfoHash->{Marked} = 1;
+				&ImageContentHandler::AddBinary($aFile);
+				&ProcessStaticDep($aFile);
+			}
+			else
+			{
+			}
+		}
+	}
+}
+
+sub VisitedBinaryInfo
+{
+	my ($aBinary) = @_;
+	my $VisitedBinaryInfoHash = \%{$VisitedBinaries{$aBinary}};
+	if($VisitedBinaryInfoHash->{Marked} == 1)
+	{
+		return $VisitedBinaryInfoHash;
+	}
+	return undef;
+}
+
+1;
--- a/imgtools/buildrom/tools/buildrom.pl	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/buildrom.pl	Tue Jun 29 14:52:54 2010 +0800
@@ -1,118 +1,130 @@
-#
-# Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-#
-
-
-use FindBin;		# for FindBin::Bin
-my $PerlLibPath;    # fully qualified pathname of the directory containing our Perl modules
-
-BEGIN {
-# check user has a version of perl that will cope
-	require 5.005_03;
-# establish the path to the Perl libraries
-    $PerlLibPath = $FindBin::Bin;	# X:/epoc32/tools
-    $PerlLibPath =~ s/\//\\/g;	# X:\epoc32\tools
-    $PerlLibPath .= "\\";
-}
-
-
-use  lib $PerlLibPath;
-#Includes the validation perl modules for XML validation against the given DTD.
-use lib "$PerlLibPath/build/lib";
-
-use buildrom;	# for buildrom module
-use externaltools; #To support External tool invocation
-
-
-# Main block for buildrom module invocation
-{
-	# Processes the buildrom command line parameters.
-	&process_cmdline_arguments;
-	
-	&image_content_processing_phase;
-
-	#Processes intermediate oby files.  Also processes any new option added to the buildrom in future.
-	&processobyfiles;
-
-	# Suppress ROM/ROFS/DataDrive Image creation if "-noimage" option is provided.
-	&suppress_image_generation;
-	
-	#Invokes ROMBUILD and ROFSBUILD
-	&invoke_rombuild;
-	
-	&create_smrimage;
-
-	#Process data drive image.
-	&processData;
-}
-
-
-sub processobyfiles {
-
-	
-	# Creates intermediate tmp1.oby file. Preprocessing phase
-	&preprocessing_phase;
-
-	# Creates intermediate tmp2.oby file.  Predefined substitutions
-	&substitution_phase;
-
-	# Creates intermediate tmp3.oby file. Reorganises the ROM IMAGE[<ID>]
-	&reorganize_phase;
-
-	# Creates feature registry configuration file/features data file.
-	&featurefile_creation_phase;
-
-	# Run single Invocation external tool at InvocationPoint1
-
-	&externaltools::runExternalTool("InvocationPoint1", &getOBYDataRef);
-	
-	# Creates intermediate tmp4.oby file. Avoids processing of REM ECOM_PLUGIN(xxx,yyy)
-	&plugin_phase;
-	
-	# Creates intermediate tmp5.oby file. Multilinguify phase
-	&multlinguify_phase;
-	
-	# Creates intermediate tmp6.oby file. SPI file creation phase
-	&spi_creation_phase;
-
-	# Run single Invocation external tool at InvocationPoint2
-	&externaltools::runExternalTool("InvocationPoint2",&getOBYDataRef);
-	
-	# Creates intermediate tmp7.oby file. Problem Suppression phase
-	&suppress_phase;
-
-	#Process the patched dll data
-	&process_dlldata;
-
-	# Creates intermediate tmp8.oby file. For xip and non-xip images
-	&bitmap_aif_converison_phase;
-	
-	# Creates intermediate tmp9.oby file. Cleaning unnecessary data for ROM image creation.
-	&cleaning_phase;
-	
-	# Run single Invocation external tool at InvocationPoint2.5
-	&externaltools::runExternalTool("InvocationPoint2.5",&getOBYDataRef);
-
-	#Creates dump OBY file for final oby file
-	&create_dumpfile;
-
-	# Run single Invocation external tool at InvocationPoint3
-	&externaltools::runExternalTool("InvocationPoint3",&getOBYDataRef);
-
-	#ROM directory listing
-	&create_dirlisting;
-
-}
-
+#!/usr/bin/perl 
+#
+# Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+#
+
+
+use FindBin;		# for FindBin::Bin
+my $PerlLibPath;    # fully qualified pathname of the directory containing our Perl modules
+my $PerlEPOCPath;
+
+BEGIN {
+# check user has a version of perl that will cope
+	require 5.005_03;
+# establish the path to the Perl libraries
+    $PerlLibPath = $FindBin::Bin;	
+#    $PerlLibPath =~ s/\//\\/g;
+    $PerlLibPath .= "\\";
+    $PerlLibPath =~ s/\\/\//g;
+    
+    $PerlEPOCPath = $ENV{EPOCROOT};
+    $PerlEPOCPath =~ s/\\/\//g;
+    $PerlEPOCPath .= "\/" unless $PerlEPOCPath =~ /\/$/;
+    $PerlEPOCPath .= "epoc32\/tools\/";
+}
+use lib $PerlEPOCPath."build/lib/";
+use lib $PerlEPOCPath;
+use lib $PerlLibPath;
+
+use buildrom;	# for buildrom module
+use externaltools; #To support External tool invocation
+use romutl;
+use romosvariant;
+
+# add current path and SDK tool path to the begining of environment path
+my $epocroot=&get_epocroot;
+my $delimiter=&env_delimiter;
+$ENV{PATH}="${PerlLibPath}$delimiter${epocroot}epoc32\/tools$delimiter${epocroot}epoc32\/gcc\/bin$delimiter${epocroot}epoc32\/gcc_mingw\/bin$delimiter".$ENV{PATH};
+
+# Main block for buildrom module invocation
+{    
+	# Processes the buildrom command line parameters.
+	&process_cmdline_arguments;
+	
+	&image_content_processing_phase;
+
+	#Processes intermediate oby files.  Also processes any new option added to the buildrom in future.
+	&processobyfiles;
+
+	# Suppress ROM/ROFS/DataDrive Image creation if "-noimage" option is provided.
+	&suppress_image_generation;
+	
+	#Invokes ROMBUILD and ROFSBUILD
+	&invoke_rombuild;
+	
+	&create_smrimage;
+
+	#Process data drive image.
+	&processData;
+}
+
+
+sub processobyfiles {
+
+	
+	# Creates intermediate tmp1.oby file. Preprocessing phase
+	&preprocessing_phase;
+
+	# Creates intermediate tmp2.oby file.  Predefined substitutions
+	&substitution_phase;
+
+	# Creates intermediate tmp3.oby file. Reorganises the ROM IMAGE[<ID>]
+	&reorganize_phase;
+
+	# Creates feature registry configuration file/features data file.
+	&featurefile_creation_phase;
+
+	# Run single Invocation external tool at InvocationPoint1
+
+	&externaltools::runExternalTool("InvocationPoint1", &getOBYDataRef);
+	
+	# Creates intermediate tmp4.oby file. Avoids processing of REM ECOM_PLUGIN(xxx,yyy)
+	&plugin_phase;
+	
+	# Creates intermediate tmp5.oby file. Multilinguify phase
+	&multlinguify_phase;
+	
+	# Creates intermediate tmp6.oby file. SPI file creation phase
+	&spi_creation_phase;
+
+	# Run single Invocation external tool at InvocationPoint2
+	&externaltools::runExternalTool("InvocationPoint2",&getOBYDataRef);
+	
+	# Creates intermediate tmp7.oby file. Problem Suppression phase
+	&suppress_phase;
+
+	#Process the patched dll data
+	&process_dlldata;
+
+	# Creates intermediate tmp8.oby file. For xip and non-xip images
+	&bitmap_aif_converison_phase;
+	
+	# Creates intermediate tmp9.oby file. Cleaning unnecessary data for ROM image creation.
+	&cleaning_phase;
+	
+	# Run single Invocation external tool at InvocationPoint2.5
+	&externaltools::runExternalTool("InvocationPoint2.5",&getOBYDataRef);
+
+	#Creates dump OBY file for final oby file
+	&create_dumpfile;
+
+	# Run single Invocation external tool at InvocationPoint3
+	&externaltools::runExternalTool("InvocationPoint3",&getOBYDataRef);
+
+	#ROM directory listing
+	&create_dirlisting;
+
+}
+
--- a/imgtools/buildrom/tools/buildrom.pm	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/buildrom.pm	Tue Jun 29 14:52:54 2010 +0800
@@ -1,4654 +1,5177 @@
-#
-# Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-# This package is to build rom image
-#
-
-package buildrom;
-
-require Exporter;
-@ISA=qw(Exporter);
-@EXPORT=qw(
-	image_content_processing_phase
-	process_cmdline_arguments
-	preprocessing_phase
-	substitution_phase
-	reorganize_phase
-	plugin_phase
-	multlinguify_phase
-	spi_creation_phase
-	suppress_phase
-	bitmap_aif_converison_phase
-	cleaning_phase
-	create_dumpfile
-	create_dirlisting
-	suppress_image_generation
-	invoke_rombuild
-	getOBYDataRef
-	isobystatement
-	isdatastatement
-	isspidatastatement
-	isexecutablefile
-	isdirectorymetadata
-	isbitmap
-	isaif
-	isresource
-	hardwarevariant
-	executableextension
-	executabletype
-	getSourceFile
-	getDestFile
-	getOBYAttributes
-	getHardwareVariant
-	getObyCommand
-	process_dlldata
-	featurefile_creation_phase
-	processData
-	create_smrimage
-);
-
-my $enforceFeatureManager = 0; # Flag to make Feature Manager mandatory if SYMBIAN_FEATURE_MANAGER macro is defined. 
-
-my $BuildromMajorVersion = 3 ;
-my $BuildromMinorVersion = 17;
-my $BuildromPatchVersion = 0;
-
-sub print_usage
-{
-
-	# Option "-fm" will be supported instead of option "-f|fr" if SYMBIAN_FEATURE_MANAGER macro is defined.
-	my $featuresOptionUsage = "-ffeatureuids or -fr=featureuids -- feature registry database XML file name";
-	if ($enforceFeatureManager) 
-	{
-		$featuresOptionUsage = "-fm=featuredatabasefile          -- feature manager/feature registry database XML file name.\n".
-							   "\t\t\t\t    Multiple XML files can be passed seperated by commas.\n".
-							   "   -nofm=featuresdatafile           -- don't generate features data file.".
-							   " Instead use pre-built features data file.";
-	}
-
-#........1.........2.........3.........4.........5.........6.........7.....
-	print <<USAGE_EOF;
-
-BUILDROM - ROM configuration tool V$BuildromMajorVersion.$BuildromMinorVersion.$BuildromPatchVersion
-
-Usage:
-  buildrom [options] obyfile [obyfile2 ...]   
-
-Build a ROM according to the specification defined by concatenating the
-specified obyfiles.
-
-The initial specification is modified by C++ preprocessor directives,
-and subsequently adjusted by statements in the ROM specification language.
-The final specification is in the subset of the specification language
-which is understood directly by ROMBUILD.
-
-Each obyfile parameter specifies a file via a search path: if the
-filename is not matched then buildrom will look in \\epoc32\\rom\\include.
-
-Buildrom invokes ROMBUILD to generate the ROM image, and produces a
-number of related files such as the ROM symbol file. The name of the
-image file is specified directly by the -o option, or determined by 
-scanning the final specification for the "romname" keyword. If there is 
-more than one "romname" statement, the last one takes precedence.
-
-The available options are
-
-   -Dxxx                            -- C++ preprocessor arguments
-   -oimagename                      -- ROM image name, overriding any ROMNAME statement
-   -s                               -- strict option, any missing files will stop buildrom 
-   -p                               -- preserves the intermediate files pertaining to data drive, Z drive and BMCONV
-   -spi                             -- enable producing SPI files
-   -spiplacement                    -- enable positioning of spi file
-   -w                               -- warn if file has been selected from a different directory 
-   $featuresOptionUsage
-   -etool                           -- external tool specification (xx is tool's perl module)
-   -compress                        -- compression type of ROM image:
-                                       -compress compress whole ROM image.
-                                       -compress=paged compress paged section in the ROM image only.
-                                       -compress=unpaged compress unpaged section in the ROM image only. 
-   -ccomprmethod                    -- compression method: none|inflate|bytepair
-   -geninc                          -- generate INC file
-   -gendep                          -- generate dependence graph for rom image
-   -nosymbols                       -- disable creation of symbol file
-   -noimage                         -- disable creation of ROM/ROFS/DataDrive Image
-   -fastcompress                    -- compress files with faster bytepair and tradeoff of compress ratio
-   -j<digit>                        -- do the main job with <digit> threads
-   -loglevel<level>                 -- Level of information logging where loglevel is 0,1,2
-                                       0 default level of information
-                                       1 host/ROM filenames, file size and the hidden attribute along with level0 log
-                                       2 E32 file header attributes along with level1 log
-   -z=xxx or -zdrivepath=xxx        -- specify a location to create Z drive directory. 
-   -d=xxx or -datadrivepath=xxx     -- specify a location to create data drive directory.
-   -k or -keepgoing                 -- enable keepgoing,continue to create the data drive image even
-                                    if the non-sis, sis or zdrive image file(s) are missing or corrupt.
-   -r or -retainfolder              -- enable retainfolder,would retain pre-existence of z & data drive folder. 
-   -zdriveimage=xxx                 -- specify Z drive image (ROM, CORE, ROFS or Ext-ROFS image).
-   -pfile=xxx                       -- specify a parameter file for interpretsis to take additional parameters.
-   -argforinterpretsis=xxx          -- specify command line argument(s) for interpretsis which will override the 
-                                    parameter file contents.
-   -l=xxx or -logimagecontents=xxx  -- extract all stub-sis and SWI certificate store file(s) only 
-                                    and log all the file(s) that are part of the Z drive image on to a log file.  
-   -I<directory>                    -- Use <directory> for the referenced IBY/OBY files
-   -argfile=xxx                     -- specify argument-file name containing list of command-line arguments to buildrom   
-   -lowmem                          -- use memory-mapped file for image build to reduce physical memory consumption   
-
-Popular -D defines to use include
-
-   -D_DEBUG         -- select debug versions of some files
-   -D_FULL_DEBUG    -- select debug versions of all files
-   -D_ARM4          -- specify the target platform
-
-   -D_EABI=xxxx     -- specify target for all files (e.g. ARMV5)
-   -D_KABI=xxxx     -- specify the target platform for the Kernel (e.g. ARMV5)
-
-Other defines may be useful for particular OBY files.
-
-USAGE_EOF
-}
-
-use strict;
-my $PerlLibPath;    # fully qualified pathname of the directory containing our Perl modules
-# establish the path to the Perl libraries
-$PerlLibPath = $FindBin::Bin;	# X:/epoc32/tools
-$PerlLibPath =~ s/\//\\/g;	# X:\epoc32\tools
-$PerlLibPath .= "\\";
-sub ExportDirs ($);
-
-use BPABIutl; # for BPABIutl::BPABIutl_Plat_List
-
-my $xmlrequired = 0; # assume xml required is false. Used to determine if xml
-                     # modules should be loaded.
-
-use Modload;	     # To load modules dynamically
-
-# Work out the relative path to the epoc32 directory
-use spitool qw(&createSpi);
-use Cwd;
-use Pathutl;
-use E32Variant;
-use E32Plat;
-use Genutl;
-use BPABIutl;		# for BPABIutl::BPABIutl_Plat_List
-use externaltools; 	#To invoke External Tools
-
-my @tempfiles;  	
-my $preserve = 0; 	#flag to indicate if temporary files should be preserved
-my $uppath="x";	    	# will be initialised when first needed
-
-my $epocroot = $ENV{EPOCROOT};
-die "ERROR: Must set the EPOCROOT environment variable\n" if (!defined($epocroot));
-$epocroot =~ s-/-\\-go;	# for those working with UNIX shells
-die "ERROR: EPOCROOT must not include a drive letter\n" if ($epocroot =~ /^.:/);
-die "ERROR: EPOCROOT must be an absolute path without a drive letter\n" if ($epocroot !~ /^\\/);
-die "ERROR: EPOCROOT must not be a UNC path\n" if ($epocroot =~ /^\\\\/);
-die "ERROR: EPOCROOT must end with a backslash\n" if ($epocroot !~ /\\$/);
-die "ERROR: EPOCROOT must specify an existing directory\n" if (!-d $epocroot);
-
-my $epoc32 = relative_path("${epocroot}epoc32");
-$epoc32 =~ s-\\-/-go;
-
-my @obyfiles;
-my $cppargs = "-nostdinc -undef";
-my $opt_v = 0;
-my $opt_o = "";
-my $strict = 0;
-my $warnSelection = 0; # default is not warn about selecting files from 
-		       # different directories when the file is missing from
-		       # the specified directory
-
-my $createspi = 0; # don't create SPI files by default
-my $spiset=0;
-my $spiplacement = 0; # enable the placement of spi file
-my %spipositionflag = (); # map of Image index at which the keyword SPI_POSITION is used.
-
-use constant NONE => 0;
-use constant INFLATE => 1;
-use constant BYTEPAIR => 2;
-my $opt_compression;  # Default compression method parameter undefined
-
-use constant UNCOMPRESSED   => 0;        # Indicates the ROM image will not be compressed.
-use constant ALLSECTIONS    => 1;        # Indicates both paged section and unpaged section will be compressed.
-use constant PAGEDSECTION   => 2;        # Indicates only paged section will be compressed.
-use constant UNPAGEDSECTION => 3;        # Indicates only unpaged section will be compressed.
-my $opt_compression_type = UNCOMPRESSED; # Leave the ROM image uncompressed by default.
-
-my $thisdir=cwd;
-$thisdir=~s-/-\\-go;		    # separator from Perl 5.005_02+ is forward slash
-$thisdir=~s-^(.*[^\\])$-$1\\-o;	    # ensure path ends with a backslash
-$thisdir=~s-^.:\\--o;		    # remove drive letter and leading backslash
-
-my $rominclude = "$epoc32/rom/include";
-my %plugintypes; #hash of plugin types and their SPI files' destinations in ROM
-$plugintypes{"ECOM"} = "\\private\\10009d8f\\"; #ECOM SPI files' destination in ROM image
-
-my @obydata;
-my @newobydata;
-my %substitutionData;
-my @substitutionOrder;
-my %languageCodes;
-my $defaultLanguageCode;
-my %multiLinguifyAlias;  # to by-pass the 'mustbesysbin' option for multilinguify 'alias'es. 
-my $abiDowngrade;
-my @binarySelectionOrder;
-my $fromDIR;
-my %rombuildOptions = ("-type-safe-link" => 1 );
-my $enforceSysBin = 0;
-
-my $line;
-my $errors = 0;
-my @romimage;
-my $rombasename;
-
-my $sourcefile;
-my $sourceline;
-my ($line);
-my %romfiles;
-
-# To handle BINARY_SELECTION_ORDER macro.
-my $firstDIR;
-my $binarySelectionOrderFlag = 0;
-
-my %DllDataMap = ();	#Map to keep track of DLL Data patch statements.
-my $patchDataStmtFlag = 0;
-
-my $featuremanager = 0; #Flag to enable support for feature manager database XML file and to generate  
-			# features data file.
-my $noFeatureManager = 0; # Flag to stop the generation of features.dat file and use pre-built features.dat if provided.
-my $preBuiltFeaturesDataFile  = ''; # To store the name of pre-built features.dat file provided with "-nofm" option.
-
-#Image Content XML file that supports specific feature to be added
-my $image_content = undef;
-#Feature list XML file that acts as database containing all features details
-my $featureXml = undef;
-my $geninc = "";
-my $gendep = "";
-my $nosymbols = "";
-my $noimage = "";
-my $customizedPlat = undef;
-my $opt_fastcompress = "";
-my $opt_jobs= "";
-
-#Summary of files(both executables and data files) currently includes 
-#	host and ROM file names, 
-#	size of the file in ROM
-#	whether the file is hidden
-# This option is added so that the above additional information is emitted by rombuild/rofsbuild tools
-# only when supplied with this option so that the existing tools don't get affected.
-my $logLevel="";
-
-# This option is used to pass -lowmem argument to rombuild/rofsbuild tools
-my $lowMem="";
-
-# Feature Variation modules and data
-use featurevariantparser;
-use featurevariantmap;
-my %featureVariant;
-
-# global variables specific to data drive image generation. 
-use File::Path;					# Module to provide functions to remove or create directories in a convenient way.
-use File::Copy;					# Module to provide functions to copy file(s) from source to destination.
-use File::Find;
-use datadriveimage;				# module which provides all necessary functions to create data drive image.
-my $ZDirloc = "";				# location of Z drive directory.
-my $DataDriveDirloc = "";		# location of data drive directory.
-my @sisfilelist;				# an array to hold sis file(s).
-my @zDriveImageList;			# an array to hold z drive image name.
-my @datadiveobydata;			# an array to hold data drive oby data.
-my @datadriveimage;				# array which holds data drive image attribute.
-my $rootdir = "";				# which holds root directory information.
-my @datadrivedata;				# array to maintain list of lines taken from processed data drive oby file.
-my @nonsisFilelist;				# array to maintain list of nonsis file(s). 
-my @sisobydata;					# array to maintain all list of files(s) got by installing sis files. 
-my @renameList;					# array to maintain list of file(s) that has to be renamed.
-my @aliaslist;					# array to maintain list of file(s) that has to be made alias.
-my @hideList;					# array to maintain list of file(s) that has to be made hidden.
-my $sisfilepresent = 0;			# enable if sis file(s) are present.
-my $stubsisfilepresent = 0;		# enable if stub-sis file(s) are present.
-my $opt_k = 0;					# enable if keepgoing option is specified by the user.
-my $opt_r = 0;					# enable if retain pre-existence of folder is specified by the user.
-my $dataImageCount = 0;			# no of data drive image that has to generated.
-my @zdriveImageName;			# list of Z drive image name(s) specified using zdriveimagename in oby/iby file.
-my $opt_zimage = 0;				# enable if z drive image is found.
-my $zDrivePresent = 0;			# flag to check whether Z drive needs to be created.
-my @dataDriveFileList;			# list of processed data drive related files.
-my $paraFile = undef;			# parameter file for interpretsis.
-my @romImages;					# list of generated z drive image(s)(rom/rofs). 
-my $imageEntryLogFile = undef;	# a log file to log all the z drive image contents.
-my $opt_logFile = 0;			# enable if z drive entries has to be logged on to a log file.
-my %dataIndexHash = ();			# a hash which holds key-value pair between datadrive index and datadrive image count.
-my $interpretsisOpt = undef;	# enable if command line arguments are specified by the user to INTERPRETSIS.
-my @interpretsisOptList;		# an array which holds all the list of option(s) that needs to passed to INTERPRETSIS. 
-my @Global_BPABIPlats;
-my @Global_PlatList;
-my @smrImageFileList;
-my $needSmrImage = 0;
-my %smrPartitions;
-my %smrNameInfo;
-my @obeyFileList;
-my $smrNoImageName = 0;
-my $onlysmrimage = 1;
-
-sub match_obyfile
-{
-	my ($obyfile) = @_;
-	if (-f $obyfile)
-	{
-		push @obyfiles, $obyfile;
-		return 1;
-	}
-
-	# search for the oby file in the list of include directories
-	my @otherDirs = ($rominclude);
-
-	if ($featureVariant{'VALID'})
-	{
-		my $dirRef = $featureVariant{'ROM_INCLUDES'};
-
-		@otherDirs = @$dirRef if ($dirRef);
-	}
-	foreach my $dir (@otherDirs)
-	{
-		if (-f "$dir/$obyfile")
-		{
-		    push @obyfiles, "$dir/$obyfile";
-		    return 1;
-		}
-	}
-	return 0;
-}
-
-
-# This function invokes ROFSBUILD tool with appropriate parameters to generate data drive image.
-# It also deletes zdrive and datadrive folder after all the image has been processed and generated
-# if and only if preserve(-p) option is disabled.
-sub create_datadriveImage
-{
-	for (my $dataidx=0; $dataidx < $dataImageCount; $dataidx++)
-	{
-		my $driveIndex = $dataIndexHash{$dataidx};
-
-		if(defined($driveIndex))
-		{
-			my $obeyfile=$datadriveimage[$driveIndex]{obeyfile};
-			my $compress=$datadriveimage[$driveIndex]{compress};
-			my $uncompress=$datadriveimage[$driveIndex]{uncompress};
-
-			if ($obeyfile)
-			{
-				if(!defined $opt_compression)
-				{
-					if ($compress ne 0)
-					{
-						$compress=" -compress";
-					}
-					elsif($uncompress ne 0)
-					{
-						$compress=" -uncompress";
-					}
-					elsif($compress eq 0)
-					{
-						$compress=" ";
-					}
-				}
-				else
-				{
-					$compress = $opt_compression;
-					$compress =~m/\s-(compression)(method)\s(none|inflate|bytepair)/;
-					print "* ".$1." ".$2.": ".$3;
-				}
-				my $command = "rofsbuild -slog".$compress." -datadrive=$obeyfile.oby";
-				print "* Executing $command\n" if ($opt_v);
-				system($command);
-				if ($? != 0)
-				{
-					&datadriveimage::reportError("* ROFSBUILD failed to generate data drive image",$opt_k);
-				}
-				else
-				{
-					push(@dataDriveFileList,$obeyfile.".img");
-				}
-			}
-		}
-	}
-	# after processing all the data drive image(s) delete zdrive and datadrive directory 
-	# if and only if preserve(-p) option is disabled.
-	if($dataImageCount)
-	{
-		# delete Z drive directory if and only if preserve(-p) option is disabled.
-		my $retVal = &deleteDirectory($ZDirloc,$opt_v)if(!($preserve));
-		if($retVal)
-		{
-			&datadriveimage::reportError("* Warning could not delete $ZDirloc",$opt_k);
-		}
-		# delete data drive directory if and only if preserve(-p) option is disabled.
-		my $retVal = &deleteDirectory($DataDriveDirloc,$opt_v)if(!($preserve));
-		if($retVal)
-		{
-			&datadriveimage::reportError("* Warning could not delete $DataDriveDirloc",$opt_k);
-		}
-		# reset image count to zero.
-		$dataImageCount = 0;
-		# reset z drive present to zero.
-		$zDrivePresent = 0;
-	}
-}
-
-sub tidy_exit
-{
-	#-------------------------------------------------------
-	# Tidy and exit
-	
-	if (!$preserve)
-	{
-	    foreach my $tempfiles (@tempfiles)
-	    {
-			unlink "$tempfiles";
-	    }
-	}
-	if($rombasename)
-	{
-		system("dir $rombasename.*");
-	}
-	if(@dataDriveFileList)
-	{
-		print "\n";
-		print " ----------------------------------------------------------\n";
-		print "| List of file(s) generated pertaining to data drive image |\n";
-		print " ----------------------------------------------------------\n";
-		my $arraySize = scalar(@dataDriveFileList);
-		for( my $i=0; $i < $arraySize; $i++ )
-		{
-			# remove the first element from an array and return it 
-			my $element = shift(@dataDriveFileList);
-			# get the size of the file.
-			my $size = -s $element;
-			print "Size = ".$size." bytes"."\t"."File = ".$element."\n";
-		}
-	}
-	exit(0);
-}
-
-# This is the main function which is responsible for processing data drive image.
-# This function internally calls other functions to create datadrive folder,zdrive folder
-# and external tools such as INTERPRETSIS, READIMAGE and finally ROFSBUILD to generate 
-# appropriate data drive image.
-sub processData		
-{
-	if($dataImageCount)
-	{
-		# set the default path for Z drive and Data drive directory,
-		# if and only if, path is not specified by the user. 
-		$ZDirloc = &datadriveimage::setPath("zdrive") unless ($ZDirloc);
-		$DataDriveDirloc = &datadriveimage::setPath("datadrive") unless ($DataDriveDirloc);
-		#delete any existing Z drive directory.
-		my $retVal = &datadriveimage::deleteDirectory($ZDirloc,$opt_v)if(!$opt_r);
-		if($retVal)
-		{
-			exit(1) if(!$opt_k);
-		}
-		# delete pre-existence of data drive folder, if and only if -r option is not enabled.
-		my $retVal = &datadriveimage::deleteDirectory($DataDriveDirloc,$opt_v) if(!$opt_r);
-		if($retVal)
-		{
-			exit(1) if(!$opt_k);
-		}
-		if($opt_logFile)
-		{
-			# clean any pre-existance of log file.
-			unlink($ZDirloc."\\".$imageEntryLogFile);
-		}
-		
-		for (my $datadriveidx=0; $datadriveidx < $dataImageCount; $datadriveidx++)
-		{
-			my $driveIndex = $dataIndexHash{$datadriveidx};
-			# get the data drive name.
-			if( defined( $driveIndex ) )
-			{
-				my $datadrivename=$datadriveimage[$driveIndex]{obeyfile};
-				# get the size of the data drive.
-				my $size = $datadriveimage[$driveIndex]{size};
-				if( $datadrivename )
-				{
-					# set data drive oby file.
-					my $datadriveobyfile = $datadrivename.".oby";
-					# final location of prototype data drive.
-					my $proDataDriveDirloc;
-					# Location of stub-sis file(s) inside Z Drive folder.
-					my $zDriveSisFileLoc;
-					# check if more than one data drive image needs to be generated. 
-					if( $dataImageCount > 1 )
-					{
-						# if yes, then set the location of prototype data drive folder as 
-						# DataDriveDirloc + datadrivename
-						$proDataDriveDirloc = $DataDriveDirloc."\\".$datadrivename;
-					}
-					else
-					{
-						# else, then set the location of prototype data drive folder as DataDriveDirloc 
-						$proDataDriveDirloc = $DataDriveDirloc;
-					}
-
-					# create prototype data drive folder.
-					print "creating data drive folder\n" if ($opt_v);
-					&datadriveimage::createDirectory($proDataDriveDirloc);
-
-					# check for sis file keyword in ROM description file.
-					# if found,then locate for stub-sisfile.
-					# create Z drive( if and only if stub-sis files are present in ROM description file )
-					# and dump all the non-sis files on to the Z drive folder. 
-					if(&datadriveimage::checkForSisFile($datadriveobyfile,\@sisfilelist,\$sisfilepresent))
-					{
-						my $zDriveImagePresent = 0; # flag to check whether z drive image is Present;
-						if(&datadriveimage::checkForZDriveImageKeyword($datadriveobyfile,\@zDriveImageList,\$zDriveImagePresent) )
-						{
-							# find out size of the array
-							my $arraysize = scalar(@zDriveImageList);
-							for( my $i=0; $i < $arraysize; $i++ )
-							{
-								$zDriveSisFileLoc =  $ZDirloc."\\".$datadrivename;
-								&datadriveimage::invokeReadImage(pop(@zDriveImageList),$zDriveSisFileLoc,$opt_v,$imageEntryLogFile,$opt_k);
-							}
-						}
-						else
-						{
-							$zDriveSisFileLoc = $ZDirloc;
-							# locate and copy stub-sis file(s),for the first time.
-							if( !$zDrivePresent )
-							{
-								# check for image file.
-								if( $opt_zimage )
-								{
-									# image(s)supplied to BUILDROM(like rom,rofs,extrofs or core) using "-zdriveimage" option, 
-									# are maintained in a seperate array and the element from the array is fetched one by one and is 
-									# fed to READIMAGE as an input.
-									foreach my $element (@zdriveImageName)
-									{
-										# invoke READIMAGE to extract all /swi stub sis file(s) from the given image.
-										$zDrivePresent = &datadriveimage::invokeReadImage($element,$zDriveSisFileLoc,$opt_v,$imageEntryLogFile,$opt_k);
-									}
-								}
-								else
-								{
-									# if zdrive image(s) such as (rom,core,rofs or extrofs) are generated ealier to the data drive image processing
-									# then these images are maintained in an array and the element from the array is fetched one by one and is 
-									# fed to READIMAGE as an input.
-									foreach my $element (@romImages)
-									{
-										# invoke READIMAGE to extract all /swi stub sis file(s) from the given image.
-										$zDrivePresent = &datadriveimage::invokeReadImage($element,$zDriveSisFileLoc,$opt_v,$imageEntryLogFile,$opt_k);
-									}
-								}
-							}
-						}
-						# invoke INTERPRETSIS tool with z drive folder location.
-						&datadriveimage::invokeInterpretsis( \@sisfilelist,$proDataDriveDirloc,$opt_v,$zDriveSisFileLoc,$paraFile,$opt_k,\@interpretsisOptList)if($sisfilepresent);
-					}
-
-					# create an oby file by traversing through upated prototype data drive directory.
-					&datadriveimage::dumpDatadriveObydata( $proDataDriveDirloc,$datadriveobyfile,$size,\@nonsisFilelist,
-										\@renameList,\@aliaslist,\@hideList,\@sisobydata,\@datadrivedata,$opt_k,$opt_v );
-					#reset sisfilepresent flag to zero;
-					$sisfilepresent =0;
-				}
-			}
-		}
-		create_datadriveImage();
-	}
-	tidy_exit;
-}
-#Parse and process image content xml file
-#Gets the oby files listed in the xml file
-# Pushes all the oby files found to an array
-
-sub image_content_processing_phase
-{
-	if(!defined ($image_content))
-	{
-		return;
-	}
-	&ImageContentHandler::ParseImageContentXML($image_content);
-	&ImageContentHandler::ProcessImageContent;
-
-	if(defined ($image_content) )
-	{
-#		Collect the oby files if any in the Image content file
-		my $files = &ImageContentHandler::GetObyFiles;
-		foreach my $obeyfile (@$files)
-		{
-			next if match_obyfile($obeyfile);
-			next if (match_obyfile("$obeyfile.oby"));
-		}
-	}
-}
-
-# Subroutine to process parameter-file
-sub parameterFileProcessor
-{
-	my $paramFile = shift(@_);	
-	my @paramFileParamaters = ();	
-
-	my $fileOpenFlag = 1;
-	open FILE,"<", $paramFile or $fileOpenFlag = 0;
-	
-	if(!$fileOpenFlag)
-	{
-		print "Error: Could not open parameter-file \"$paramFile\" for reading.\n";
-		return;
-	}
-	
-	# Parse parameter-file and collect all the parameters in an array
-	while(my $line = <FILE>)
-	{
-		# Read the line till character ';'(used for providing comments in the file) or EOL
-		$line = $1 if ($line =~ /(.*);/); 
-		
-		# Split the parameters specified in a line based on white-spaces		
-		my @paramaters = split(/(\s)/,$line);	
-		
-		my $flag = 0;
-		my $argWithQuotes='';
-
-		foreach my $value (@paramaters) 
-		{	
-			# If the parameter doesn't conatian double quotes then push it 
-			# to the list of parameters.
-			if(($value !~ /\"/) && (!$argWithQuotes)) 
-			{
-				if ($value !~ /^\s*$/) 
-				{
-					push @paramFileParamaters,$value;
-				}		
-			}
-			# If the parameter is in the form  -fm="faturedb.xml" then remove
-			# double quotes and push it to the list of parameters.
-			elsif(($value =~ /\".*\"/))
-			{
-				$value =~ s/\"//g;
-				push @paramFileParamaters,$value;
-			}
-			# If the parameter is in the form  -fm="fature  db.xml" then read
-			# the parameter starting from opening quote till the closing quote.
-			elsif( ($value =~ /\"/) && $argWithQuotes) 
-			{
-				$argWithQuotes .= $value;
-				$argWithQuotes =~ s/\"//g;
-				push @paramFileParamaters,$argWithQuotes;
-				$argWithQuotes='';		
-			}
-			else
-			{
-				$argWithQuotes .= $value;
-			}
-		}		
-	}
-
-	close FILE;	
-
-	if (!@paramFileParamaters)
-	{
-		print "Warning: No parameters specified in paramer-file \"$paramFile\".\n";		
-		return;
-	}
-	
-	my $paramFileFlag = 1;
-
-	# Invoke subroutine "process_cmdline_arguments" to process the parameters read from
-	# the parameter file.
-	&process_cmdline_arguments($paramFileFlag, @paramFileParamaters);
-
-}
-
-# Processes the command line arguments passed to buildrom tool
-
-sub process_cmdline_arguments
-{
-   	my %tmpBldRomOpts;
-
-	my ($paramFileFlag, @argList); 
-
-	if (defined @_)
-	{
-		($paramFileFlag, @argList) = @_;
-	}
-	else
-	{
-		@argList = @ARGV;
-	}
-
-	if (!defined $paramFileFlag) 
-	{
-		# Enforce Feature Manager if macro SYMBIAN_FEATURE_MANAGER is defined in the HRH file.
-		my @hrhMacros = &Variant_GetMacroList;	
-		if (grep /^SYMBIAN_FEATURE_MANAGER\s*$/, @hrhMacros)
-		{
-			$enforceFeatureManager = 1;
-		}
-		
-		# Process the parameters of parameter-file if passed.
-		foreach my $arg (@argList)
-		{
-			if ($arg =~ /^-argfile=(.*)/) 
-			{
-				&parameterFileProcessor($1);				
-			}
-		}
-	}
-
-	foreach my $arg (@argList)
-	{
-	    if ($arg =~ /^-argfile=(.*)/) 
-		{
-			&parameterFileProcessor($1) if (defined $paramFileFlag);						
-			next;			
-		}
-		if ($arg =~ /^-[DI]/)
-	    {
-		$cppargs .= " $arg";
-		#Set 'udeb' for debug option 
-		if($arg =~ /^-D_FULL_DEBUG/)
-		{
-		    $tmpBldRomOpts{"BUILD_DIR"} = "udeb";
-		}
-		#Set specific platform supplied from the command option 
-		elsif($arg =~ /^-D_PLAT=(.*)/)
-		{
-		    $tmpBldRomOpts{"ABI_DIR"} = $1;
-		}
-		# Check for a Feature Variant
-		elsif ($arg =~ /^-DFEATUREVARIANT=(.*)/)
-		{
-			my $varname = $1;
-			
-			if ($varname =~ /^\.(.*)$/)
-			{
-				# for testing, locate the VAR file in the current directory
-				%featureVariant = featurevariantparser->GetVariant($1, ".");
-			}
-			else
-			{
-				%featureVariant = featurevariantparser->GetVariant($varname);
-			}
-			if (!$featureVariant{'VALID'})
-			{
-			    print "FEATUREVARIANT $varname is not VALID\n";
-				$errors++;
-			}
-			if ($featureVariant{'VIRTUAL'})
-			{
-			    print "FEATUREVARIANT $varname is VIRTUAL\n";
-				$errors++;
-			}
-			addDrivesToFeatureVariantPaths();
-		}
-		next;
-	    }
-	    if ($arg =~ /^-o(.*)/i)
-	    {
-		$opt_o = $1;
-		next;
-	    }
-	    if ($arg =~ /^-fastcompress$/i)
-	    {
-		    $opt_fastcompress = "-fastcompress";
-		    next;
-	    }
-	    if ($arg =~ /^-j(\d+)$/i)
-	    {
-		    $opt_jobs = "-j".$1;
-		    next;
-	    }
-	    if ($arg =~ /^-v$/)
-	    {
-		$opt_v =1;
-		next;
-	    }
-	    if ($arg =~ /^-s$/)
-	    {
-		$strict = 1;
-		next;
-	    }
-	    if ($arg =~ /^-w$/)
-	    {
-		$warnSelection = 1;
-		next;
-	    }
-	    if ($arg =~ /^-p$/)
-	    {
-		$preserve = 1;
-		next;
-	    }
-	    if ($arg =~ /^-nospi$/)
-	    {
-		$createspi=0;
-		$spiset=1;
-		next;
-	    }
-	    if ($arg =~ /^-spi$/)
-	    {
-		$createspi=1;
-		$spiset=1;
-		next;
-	    }	
-	    #Process External Tool
-	    if ($arg =~/^-e(.*)/)#Match to get the tool perl module files
-	    {
-		&externaltools::loadTools($1);
-		next;
-	    }
-   		#Process imagecontent file 
-	    if( $arg =~ /^-i(.*)/)
-	    {
-# Disabling -i option
-		print "Warning: Ignoring invalid Option $arg \n";
-		next;
-	    }
-		#Process feature manager database xml file 
-	    if($arg =~ /^-fm=(.*)/)
-	    {
-			if (!$enforceFeatureManager) 
-			{
-				print "Unknown arg: $arg\n";
-				$errors++;
-				next;
-			}
-			$featureXml = $1;
-			$xmlrequired = 1;
-			$featuremanager = 1;
-			if ($featureXml =~ /^$/) 
-			{
-				print "Error: No filename specified with \"-fm=\" option.\n";
-			}			
-			next;
-	    }
-	    #Process ROM image compression type if it's specified through command line option.
-	    if($arg =~ /^-compress(.*)/)
-	    {
-	    	if($1 eq '')
-	    	{
-	    		$opt_compression_type = ALLSECTIONS;
-	    		print "Whole ROM image will be compressed.\n";
-	    	}
-	    	elsif($1 eq '=paged')
-	    	{
-	    		$opt_compression_type = PAGEDSECTION;
-	    		print "Paged section of the ROM image will be compressed.\n";
-	    	}
-	    	elsif($1 eq '=unpaged')
-	    	{
-	    		$opt_compression_type = UNPAGEDSECTION;
-	    		print "Unpaged section of the ROM image will be compressed.\n";
-	    	}
-	    	else
-	    	{
-	    		print "Unknown compression type: $1\n";
-	    		$errors++;
-	    	}
-	    	next;
-	    }
-		if ($arg =~ /^-nofm(=(.*))?$/)
-		{
-			if (!$enforceFeatureManager) 
-			{
-				print "Unknown arg: $arg\n";
-				$errors++;
-				next;
-			}
-   			$noFeatureManager = 1;
-            #DEF125375 If caller is simply giving -nofm without any parameter, a warning message will be given.
-            if(!$2)
-            {
-                print "Warning: No filename specified with \"-nofm=\" option, feature data file might not be included.\n";
-            }
-            else
-            {
-                $preBuiltFeaturesDataFile = $2;						
-            }
-			next;	
-		}
-		#Process feature registry database xml file 
-	    if($arg =~ /^-fr=(.*)/ || $arg =~ /^-f(.*)/)
-	    {
-			if ($enforceFeatureManager)
-			{
-				print "Error: Option \"-f|-fr\" is no longer supported.\n";
-				$errors++;
-				next;
-			}			
-			$featureXml = $1;
-			$xmlrequired = 1;			
-			if ($featureXml =~ /^$/) 
-			{
-				print "Error: No filename specified with \"-f|-fr\" option.\n";				
-			}
-			next;
-	    }
-	    if ($arg =~ /^-spiplacement$/)
-	    {
-			$spiplacement = 1;
-			next;
-	    }
-		if ($arg =~ /^-noimage$/)
-		{
-			$noimage=1;
-			next;	
-		}
-		if ($arg =~ /^-nosymbols$/)
-		{
-			$nosymbols=1;
-			next;	
-		}
-		if ($arg =~ /^-geninc$/)
-		{
-			$geninc=1;
-			next;	
-		}
-		if($arg =~ /^-gendep$/)
-		{
-			$gendep=1;
-			next;
-		}
-        if($arg =~/^-c(.*)/)
-        {
-          if($1 eq 'none' )
-          {
-              $opt_compression = " -compressionmethod none";
-          }
-          elsif($1 eq 'inflate' )
-          {
-              $opt_compression = " -compressionmethod inflate";
-          }
-          elsif($1 eq 'bytepair' )
-          {
-              $opt_compression = " -compressionmethod bytepair";
-          }
-          else
-          {
-              print "Unknown compression method: $1\n";
-              $errors++;
-          }
-          next;
-        }
-		if( $arg =~ /^-loglevel\d+$/)
-		{
-			$logLevel= $arg;
-			next;
-		}
-		# get Z directory location if specified by the user.
-		# if yes, then extract directory location from the given array element. 
-		if( $arg =~ /^-z=(.*)/  || $arg =~ /^-zdrivepath=(.*)/i )
-		{
-			# check for white space in the specified folder path
-			# if "yes" then warn the user saying folder will be created under default location.
-			# else set the path specified by the user.
-			if(&datadriveimage::checkForWhiteSpace($1,"zdrive"))
-			{
-				next;
-			}
-			else
-			{
-				$ZDirloc  = $1;
-				if( $ZDirloc !~ m/\\(\Z)/)
-				{ 
-					$ZDirloc .= "\\"; 
-				}
-				if( $ZDirloc !~ m/:/)
-				{
-					print "drive letter not specified\n";
-					$ZDirloc = &datadriveimage::setPath($ZDirloc);
-				}
-				print "Z Drive directory location = $ZDirloc\n";
-				#set the location of Z Drive directory.
-				$ZDirloc .= "zdrive";
-			}
-			next;
-		}
-		# get data directory location if specified by the user.
-		# if yes, then extract directory location from the given array element. 
-		if( $arg =~ /^-d=(.*)/ || $arg =~ /^-datadrivepath=(.*)/i )
-		{
-			# check for white space in the specified folder path
-			# if "yes" then warn the user saying folder will be created under default location.
-			# else set the path specified by the user.
-			if(&datadriveimage::checkForWhiteSpace($1,"datadrive"))
-			{
-				next;
-			}
-			else
-			{
-				$DataDriveDirloc = $1;
-				if( $DataDriveDirloc !~ m/\\(\Z)/)
-				{ 
-					$DataDriveDirloc .= "\\"; 
-				}
-				if( $DataDriveDirloc !~ m/:/)
-				{
-					print "drive not specified\n";
-					$DataDriveDirloc = &datadriveimage::setPath($DataDriveDirloc);
-				}
-				print "Data Drive directory location = $DataDriveDirloc\n";
-				#set the location of Data Drive directory.
-				$DataDriveDirloc .= "datadrive";
-			}
-			next;
-		}
-		# get Z dive image if specified by the user.
-		if( $arg =~ /^-zdriveimage=(.*)/i )	
-		{
-			my $imageName = $1;
-			if( $imageName =~ m/\,/)
-			{
-				@zdriveImageName = split(/\,/,$imageName);
-			}
-			else
-			{
-				push(@zdriveImageName,$imageName);
-			}
-			$opt_zimage = 1;
-			next;
-		}
-		# get command line arguments which needs to be passed to INTERPRETSIS, if specified by the user.
-		if( $arg =~ /^-argforinterpretsis=(.*)/i )	
-		{
-			my $interpretsisOpt = $1;
-			if( $interpretsisOpt =~ m/\,/)
-			{
-				@interpretsisOptList = split(/\,/,$interpretsisOpt);
-			}
-			else
-			{
-				push(@interpretsisOptList,$interpretsisOpt);
-			}
-			next;
-		}
-		if ( $arg =~ /^-k$/i || $arg =~ /^-keepgoing$/i )
-	    {
-			$opt_k = 1;
-			next;
-	    }
-		if ( $arg =~ /^-r$/i || $arg =~ /^-retainfolder$/i )
-	    {
-			$opt_r = 1;
-			next;
-	    }
-		if ( $arg =~ /^-pfile=(.*)/i )
-	    {
-			$paraFile = $1;
-			next;
-	    }
-		if ( $arg =~ /^-l=(.*)/i || $arg =~ /^-logimageentry=(.*)/i )
-	    {
-			if( $1 =~/\\/ || $1 =~ m/:/)
-			{
-				print "* Warning: Invalid log file extension try filename.txt\n";
-				next;
-			}
-			else
-			{
-				$opt_logFile = 1;
-				$imageEntryLogFile = $1;
-			}
-			next;
-	    }
-		if ( $arg =~ /^-lowmem/i )
-		{
-			$lowMem = $arg;
-			next;
-		}
-	    if ($arg =~ /^-/)
-	    {
-		print "Unknown arg: $arg\n";
-		$errors++;
-		next;
-	    }
-	    # It's an OBY file
-	    next if (match_obyfile($arg));
-	    next if (match_obyfile("$arg.oby"));
-
-	    print "Cannot find oby file: $arg\n";
-	    $errors++;
-	}
-
-	if (defined $paramFileFlag) 
-	{
-		return;
-	}
-	
-	if (@obyfiles<1)
-	{
-	    print "Missing obyfile argument\n";
-	    $errors++;
-	}
-
-	if ($errors)
-	{
-	    print_usage();
-	    exit 1;
-	}
-	
-	if ($noFeatureManager && $featuremanager) 
-	{
-		print "Warning: Ignoring \"-nofm\" option, as both \"-nofm\" and \"-fm\" options are provided.\n";			
-		$noFeatureManager = 0;
-	}
-
-	# Adding variant specific macros by including a HRH file
-	# (only required if no Feature Variant is used)
-	if (!$featureVariant{'VALID'})
-	{
-	    my $variantMacroHRHFile = Variant_GetMacroHRHFile();
-	    if($variantMacroHRHFile){
-
-	        my $variantFilePath = Path_Split('Path',$variantMacroHRHFile);
-	        $cppargs .= " -I \"" . &Path_RltToWork($variantFilePath) . "\" -include \"" . &Path_RltToWork($variantMacroHRHFile) . "\""; 
-	    }
-	}
-	# load the required modules if xml is required
-	if ($xmlrequired == 1)
-	{
-	    my $epocToolsPath = $ENV{EPOCROOT}."epoc32\\tools\\";
-	    Load_SetModulePath($epocToolsPath);
-	    if (defined ($featureXml))
-	    {
-			load_featuresutil();
-	    }
-	
-	    if ($image_content)
-	    {
-	    	&Load_ModuleL("ImageContentHandler");
-	    	# some variables for ImageContentHandler may have been setup
-	    	my ($key, $value);
-	    	&ImageContentHandler::SetBldRomOpts; # Defaults to ARMV5 platform
-	    	while (($key,$value) = each %tmpBldRomOpts)
-	    	{
-			&ImageContentHandler::SetBldRomOpts($key, $value);
-	    	}
-	    }
-	    
-	}
-}
-
-#----------------------------------------------------------------------------------
-# Preprocessing phase
-#
-# Concatentate the specified .oby files and pass them through cpp
-# to get the raw ROM specification in tmp1.oby
-
-sub preprocessing_phase
-{
-	unlink "tmp1.oby";
-
-#	Macro "ROM_FEATURE_MANAGEMENT" is defined when "-f|fr" or "-fm" is used
-	if (defined ($featureXml))
-	{
-		$cppargs .= " -DROM_FEATURE_MANAGEMENT ";
-	}
-
-	# add pre-include file and include directories for feature variants
-	if ($featureVariant{'VALID'})
-	{
-		$cppargs .= " -I.";
-		my $incRef = $featureVariant{'ROM_INCLUDES'};
-		if ($incRef)
-		{
-			foreach (@$incRef)
-			{
-		    	$cppargs .= " -I \"$_\"";
-			}
-		}
-		my $HRH = $featureVariant{'VARIANT_HRH'};
-		if ($HRH)
-		{
-		    $cppargs .= " -include \"$HRH\"";
-		}
-	}
-	else
-	{
-		# no feature variant so use the standard includes
-		$cppargs .= " -I. -I$rominclude";
-	}
-
-	print "* cpp -o tmp1.oby $cppargs\n" if ($opt_v);
-	
-	$errors = 0;
-	open CPP, "| cpp -o tmp1.oby $cppargs" or die "* Can't execute cpp";
-	foreach my $arg (@obyfiles)
-	{
-		print CPP "\n#line 1 \"$arg\"\n";
-	
-		open OBY, $arg or die "* Can't open $arg";
-		print "* reading $arg\n" if ($opt_v);
-		while ($line=<OBY>)
-		{
-			print CPP $line;
-		}
-		close OBY;
-	}
-	close CPP;
-	my $cpp_status = $?;
-	die "* cpp failed\n" if ($cpp_status != 0 || !-f "tmp1.oby");
-
-	my $temp1OBYFile = "tmp1.oby";
-	if( defined ($image_content))
-	{
-		#Read the OBY file that was generated by the pre-processor
-		&ReadPreprocessedFile($temp1OBYFile);
-
-#		Check if the static dependencies of the OBY binaries are resolved.
-		&ImageContentHandler::UpdateObyBinaryStaticDep();
-		
-		#Now append the files collected from cdfs.
-		&ImageContentHandler::GenObyFile($temp1OBYFile);
-	}
-
-	# Setup default rom configuration
-	$romimage[0] = {xip=>1, compress=>0, extension=>0, composite=>"none",uncompress=>0 };
-}
-
-sub ReadPreprocessedFile
-{
-#	Read the OBY file that was generated by the pre-processor. This OBY is a conglomeration of all the OBYs
-#	passed directly to buildrom and/or the ones passed through Image Content XML.
-#	It marks the binaries coming from OBY. This is required to be able to point out the binaries that are 
-#	mentioned neither in the OBY nor in the CDF. Such binaries are arrived at through static dependencies
-#	and need to be included in ROM.
-
-	my $temp1OBYFile = shift;
-	my $tmpline;
-	my $srcFileName;
-	my $srcFilePath;
-	my $dstFileName;
-	my $dstFilePath;
-	open (OBYFH, "$temp1OBYFile") or die("* Can't open $temp1OBYFile\n");
-	while($tmpline =<OBYFH>) {
-		if ($tmpline=~/(\S+)\s*=\s*(\S+)\s+(\S+)/) {#Get the first parameter (source File path) from oby line
-			$srcFilePath = $2;
-			$dstFilePath = $3;
-
-			if ($srcFilePath=~/.*\\(\S+)/) {
-				$srcFileName = $1;
-			}
-			if ($dstFilePath=~/.*\\(\S+)/) {
-				$dstFileName = $1;
-			}
-			my $binaryInfoRef = &cdfparser::GetBinaryInfo($dstFileName);
-
-			if(defined($binaryInfoRef)) 
-			{
-				#Found in CDF file
-				if($binaryInfoRef->{IsFoundInCDF})
-				{
-					print "Warning: File $srcFileName mentioned in OBY as well as CDF file\n";
-				}
-			}
-			else
-			{
-				#Found in OBY file
-				&ImageContentHandler::AddBinaryFromOby($dstFileName, $srcFilePath);
-			}
-		}
-	}
-	close OBYFH;
-}
-
-
-#----------------------------------------------------------------------------------
-# Substitution phase
-#
-# Handle the "define XXX YYY" lines, perform the substitutions.
-# Print out any ECHO lines or ERROR lines. 
-#
-
-# Predefined substitutions: 
-#   TODAY means todays' date
-#   RIGHT_NOW means the exact time
-#   EPOCROOT taken from the environment
-
-sub substitution_phase
-{
-	{
-		my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
-		$substitutionData{"TODAY"} = sprintf("%02d/%02d/%04d", $mday, $mon+1, $year+1900);
-		$substitutionData{"RIGHT_NOW"} = sprintf("%02d/%02d/%04d %02d:%02d:%02d", $mday, $mon+1, $year+1900, $hour, $min, $sec);
-		$substitutionData{"EPOCROOT"} = $epocroot;
-		@substitutionOrder = ("TODAY", "RIGHT_NOW", "EPOCROOT");
-	}
-
-	
-	open TMP1, "tmp1.oby" or die("* Can't open tmp1.oby\n");
-	while ($line=<TMP1>)
-	{
-
-		if(($line =~ /^\s*romsize\s*=/i) || ( $line=~ /^\s*rom_image/i) || ($line =~ /^\s*data_image/i))
-		{
-			$onlysmrimage = 0;
-			last;
-		}
-	}
-	close TMP1;	
-	if ($enforceFeatureManager && (!$featuremanager) && (!$noFeatureManager) )
-	{
-		my $defaultFeatureDbFlag = 0;
-		open TMP1, "tmp1.oby" or die("* Can't open tmp1.oby\n");
-		while ($line=<TMP1>)
-		{
-			if ($line=~/^\s*defaultfeaturedb\s*=?\s*(\S+)/i)
-			{	
-				# Get the default value for featuredatabasefile
-                
-				$featureXml = "$epocroot$1";
-				$featuremanager = 1;				
-				$defaultFeatureDbFlag = 1;
-				load_featuresutil();				
-				last;
-			}
-		}
-		close TMP1;
-
-		if(!$defaultFeatureDbFlag && !$onlysmrimage)
-		{
-			print "Error: Neither option \"-fm|-nofm\" nor default value for featuredatabase file is provided.\n";
-			exit(1);			
-		}
-	}
-
-	open TMP1, "tmp1.oby" or die("* Can't open tmp1.oby\n");
-	while ($line=<TMP1>)
-	{
-		track_source($line);
-		#
-		# Recognise keywords in lines that we process before substitution
-		#
-		# # lineno "file" flagno
-		# DEFINE name replacement-with-0-spaces
-		#
-		if($line=~/^\s*$/)
-		{
-			next;
-		}
-		if ($line=~/^# (\d+) "(.*)" (\d+)/)
-		{
-			push @obydata, $line;
-			next;
-		}
-
-		if ($line=~/^\s*defaultfeaturedb\s*=?\s*(\S+)/i)
-		{	
-			push @obydata, "REM $line";
-			next;
-		}		
-		#process the External tool invocation using IBY file
-		if ($line=~/externaltool=(.*),?/i)
-		{
-			&externaltools::loadTools($1);
-			next;
-		}
-
-		#Process the patch statement
-		if($line =~ /^\s*patchdata\s*(.*)/i)
-		{
-			$patchDataStmtFlag = 1;
-			my $new_line = $1;
- 			# syntax "<DLLnamewithpath> addr <variableaddress> <variablesize> <newvalue>"
- 			# If the line matches with above syntax, just add the line into oby file.
- 			if($new_line !~ /^\s*(\S+)\s+addr\s+(\S+)\s+(\S+)\s+(\S+)\s*$/i)
- 			{
- 				if(AddDllDataInfo($new_line))
- 				{
- 					$line = "REM $line";
- 				}
- 			}
-		}
-
-		if($line =~ /^\s*FEATURE\s*(.*)/i || $line =~ /^\s*EXCLUDE_FEATURE\s*(.*)/i)
-		{
-			# Process the feature keywords only when "-f|fr" or "-fm" is passed to buildrom
-			if(defined ($featureXml))
-			{
-				push @obydata, "$line";
-			}
-			else
-			{
-				push @obydata, "REM handled $line";
-			}
-			next;
-		}
-
-		if ($line=~/^\s*DEFINE\s+(\w+)\s+(\S+)/i)
-		{
-			my $key=$1;
-			my $value=$2;
-			foreach my $wordToSubstitute (@substitutionOrder)
-			{
-				my $whatToSubstituteItWith=$substitutionData{$wordToSubstitute};
-				$value=~s/$wordToSubstitute/$whatToSubstituteItWith/g;
-			}
-			$value=~s/##//g;
-			if (defined $substitutionData{$key})
-			{
-				# If the key is redefined, apply it at the new position rather
-				# than the old one.
-				push @obydata, "REM redefined $key as $value\n";# Leave a record of the definition
-				@substitutionOrder = grep !/^$key$/, @substitutionOrder;
-			}
-			else
-			{
-				push @obydata, "REM defined $key as $value\n";	# Leave a record of the definition
-			}
-			$substitutionData{$key}=$value;
-			
-			foreach my $wordToSubstitute (@substitutionOrder)
-		    {
-	   	        if ($key =~ /$wordToSubstitute/)
-	   	        {
-				   print_source_error("Warning: $key is masked by earlier definition of $wordToSubstitute");
-			 	}
-			}
-	
-			push @substitutionOrder, $key;
-			next;
-		}
-		#
-		# Do the substitutions in strict order of definition, 
-		# then eliminate any old-fashioned ## things which may be left
-		#
-		foreach my $wordToSubstitute (@substitutionOrder)
-		{
-			my $whatToSubstituteItWith=$substitutionData{$wordToSubstitute};
-			$line=~s/$wordToSubstitute/$whatToSubstituteItWith/g;
-		}
-		$line=~s/##//g;
-		#
-		# Recognise keywords in lines that we process after substitution
-		#
-		# ECHO  anything at all
-		# WARNING anything at all
-		# ERROR anything at all
-		# LANGUAGE_CODE nnn
-		# DEFAULT_LANGUAGE nnn
-		# ABI_DOWNGRADE from to
-		# ROMBUILD_OPTION command-line-option
-		# ROM_IMAGE
-		# PlatSecEnforceSysBin on|off
-		# ENABLE_SPI/DISABLE_SPI
-		#
-		if ($line=~/^\s*ECHO\s+(.*?)\s*$/i)
-		{
-			print "$1\n";
-			push @obydata, "REM handled $line";
-			next;
-		}
-		if ($line=~/^\s*(ERROR|WARNING)\s+(.*?)\s*$/i)
-		{
-			print_source_error("$1 $2");
-			$errors++ if ($1 =~ /ERROR/i);
-			push @obydata, "REM handled $line";
-			next;
-		}
-		if ($line=~/^\s*(PlatSecEnforceSysBin)\s+(\S+)\s*$/i)
-		{
-			$enforceSysBin = ($2 =~ /ON/i);
-			push @obydata, $line;
-			next;
-		}
-		if ($line=~/^\s*LANGUAGE_CODE\s+(\S+)\s*/i)
-		{
-			my $code = $1;
-			if ($code !~ /^\d\d+$/)
-			{
-				print_source_error("bad language code $code");
-				$errors++;
-			}
-			else
-			{
-				$languageCodes{$code} = 1;
-			}
-			push @obydata, "REM handled $line";
-			next;
-		}
-		if ($line=~/^\s*DEFAULT_LANGUAGE\s+(\S+)\s*/i)
-		{
-			my $code = $1;
-			if ($code !~ /^\d\d+$/)
-			{
-				print_source_error("bad default language code $code");
-				$errors++;
-			}
-			else
-			{
-				$defaultLanguageCode = $code;
-			}
-			push @obydata, "REM handled $line";
-			next;
-		}
-		
-		if ($line=~/^\s*ABI_DOWNGRADE\s*/i)
-		{
-			if ($line =~ /\s(.+)\s*->\s*(.+)\s*$/)
-			{
-				$abiDowngrade = "$1 $2";
-			}
-			else
-			{
-				print_source_error("bad ABI downgrade : $line");
-				$errors++;
-			}
-			push @obydata, "REM handled $line";
-			next;
-		}
-		if ($line=~/^\s*BINARY_SELECTION_ORDER\s*/i)
-		{
-	 		if ($line =~ /\s([^,]+)\s*,\s*(.+)\s*$/)
-   			{
-  				$binarySelectionOrderFlag = 1;
- 				$firstDIR = $1;
-   				# remove whitespaces
- 				$firstDIR = trim($firstDIR); 
-   				@binarySelectionOrder = split(',', $2);
-   				@binarySelectionOrder = trim(@binarySelectionOrder);
-
-			}
-			else
-			{
-				print_source_error("bad order specified: $line");
-				$errors++;
-			}
-			push @obydata, "REM handled $line";
-			next;
-		}
-		
-		if ($line=~/^\s*ROMBUILD_OPTION\s+(\S+)\s*/i)
-		{
-			$rombuildOptions{$1} = 1;
-			push @obydata, "REM handled $line";
-			next;
-		}
-		
-		if ($line=~/^\s*enable_spi\s*$/i)
-		{
-			if(!($spiset)) {
-				$createspi=1;
-			}
-			push @obydata, "REM handled $line";
-			next;
-		}
-		
-		if ($line=~/^\s*disable_spi\s*/i)
-		{
-			if(!($spiset)) {
-				$createspi=0;
-			}
-			push @obydata, "REM handled $line";
-			next;
-		}
-
-		if ($line=~/^\s*DATA_IMAGE\s+/i)
-		{
-			if ($line =~ /\s+(\d+)\s+(\S+)\s+/i)
-			{
-				my $datadriveidx = $1;
-				my $datadriveimagename = $2;
-				# have a count on number of data drive images that needs to be created
-				print "data drive partion name = $datadriveimagename\n " if($opt_v);
-				my $dataimagesize = 0;
-				if ($line =~ /\s+size=(\S+)\s*/i)
-				{ 
-					$dataimagesize=$1; 
-				}
-				my $fstype = "";
-				my $compress=0;
-				my $uncompress=0;
-				if ($line =~ /\s+compress\s*/i)
-				{ 
-					$compress=1;
-				}
-				elsif($line =~ /\s+uncompress\s*/i)
-				{ 
-					$uncompress=1;
-				}
-				if ($line =~ /\s+fat16\s*/i)
-				{ 
-					$fstype = "fat16"; 
-				}
-				if ($line =~ /\s+fat32\s*/i)
-				{ 
-					$fstype = "fat32"; 
-				}
-				
-				$datadriveimage[$datadriveidx] = {name=>$datadriveimagename, size=>$dataimagesize, compress=>$compress, uncompress=>$uncompress, fstype=>$fstype};
-				print "DATA_IMAGE[$datadriveidx] $datadriveimage[$datadriveidx]{name} size=$datadriveimage[$datadriveidx]{size} compress=$compress uncompress=$uncompress fstype=$fstype\n" if ($opt_v);
-			}
-			else
-			{
-				print_source_error("bad DATA_IMAGE specification : $line");
-				$errors++;
-			}
-			push @obydata, "REM handled $line";
-			next;
-		}
-		if ($line=~/^\s*ROM_IMAGE\s+/i)
-		{
-			if ($line =~ /\s+(\d+)\s+(\S+)\s+/i)
-			{
-				my $romidx=$1;
-				my $rompartitionname=$2;
-				my $rompartitionsize=0;
-				if ($line =~ /\s+size=(\S+)\s*/i)
-					{ $rompartitionsize=$1; }
-				my $xip=1;
-				my $compress=0;
-				my $uncompress=0;
-				my $extend=0;
-				my $composite="none";
-				if ($line =~ /\s+non-xip\s*/i)
-					{ $xip=0; }
-				if ($line =~ /\s+compress\s*/i)
-					{ $compress=1; }
-				elsif($line =~ /\s+uncompress\s*/i)
-					{ $uncompress=1;} # This option is passed to rofsbuild. For rombuild, not saying --compress means to uncompress
-				if ($line =~ /\s+extension\s*/i)
-					{ $extend=1; }
-				if ($line =~ /\s+composite_primary\s*/i) # added to support new composite_primary keyword in obey files
-				{	if (!($extend))
-						{ $composite="composite_primary"; }
-					else
-						{ print "Error: composite_primary keyword must be used with a core image\n"; }
-				}
-				if ($line =~ /\s+composite_secondary\s*/i) # added to support new composite_secondary keyword in obey files
-				{ if (!($extend))
-						{ $composite="composite_secondary"; }
-					else
-						{ print "Error: composite_secondary keyword must be used with core image\n"; }
-				}
-	
-				#	Compress and Uncompress are 2 different options and
-				#	not mentioning one of them doesn't necessarily mean the other.
-	
-				$romimage[$romidx] = {name=>$rompartitionname, size=>$rompartitionsize, xip=>$xip, compress=>$compress, extension=>$extend, composite=>$composite, uncompress=>$uncompress};
-				print "ROM_IMAGE[$romidx] $romimage[$romidx]{name} size=$romimage[$romidx]{size} xip=$xip compress=$compress extension=$extend composite=$composite uncompress=$uncompress \n" if ($opt_v);
-				check_romimage($romidx, $line);
-			}
-			else
-			{
-				print_source_error("bad ROM_IMAGE specification : $line");
-				$errors++;
-			}
-			push @obydata, "REM handled $line";
-			next;
-		}
-	
-		push @obydata, $line;
-	}
-
-	close TMP1;
-	exit(1) if ($errors);
-	
-	dump_obydata("tmp2.oby", "result of substitution phase") if ($opt_v);
-}
-
-sub check_romimage
-{
-	my ($idx, $line) = @_;
-	if ($idx gt 7)
-	{
-		print_source_error("too many roms : $line");
-		$errors++;
-	}
-	if ($romimage[$idx]{xip} eq 0)
-	{
-		if ($romimage[$idx]{size} eq 0)
-		{
-			print_source_error("must specify a size for non-xip ROM : $line");
-			$errors++;
-		}
-	}
-	if ($romimage[$idx]{extension} ne 0)
-	{
-		if ($romimage[$idx-1]{extension} ne 0)
-		{
-			print_source_error("cannot extend ROM image multiple times : $line");
-			$errors++;
-		}
-	}
-}
-
-sub dump_obydata
-{
-	my ($dumpfile, $comment) = @_;
-	unlink($dumpfile);
-	open DUMPFILE, ">$dumpfile" or die("* Can't create $dumpfile\n");
-	print "* Writing $dumpfile - $comment\n";
-	my $line;
-	foreach $line (@obydata)
-	{
-		print DUMPFILE $line;
-	}
-	close DUMPFILE;
-}
-
-sub track_source
-{
-	my ($line) = @_;
-	if ($line=~/^# (\d+) "(.*)"/)
-	{
-		$sourceline=$1-1;
-		$sourcefile=$2;
-		$sourcefile=~ s/\//\\/g;
-		$sourcefile=~ s/\\\\/\\/g;
-		return;
-	}
-	$sourceline++;
-}
-
-sub print_source_error
-{
-	my ($message) = @_;
-	print "$sourcefile($sourceline): $message\n";
-}
-
-sub reassert_sourceline
-{
-	my ($offset) = @_;
-	return sprintf "# %d \"$sourcefile\" \n", $sourceline+1+$offset;
-}
-
-
-#----------------------------------------------------------------------------------
-# Reorganisation phase
-#
-# Group lines beginning with "rom_image[<id>]" and deposit them in the appropriate
-# order.  Truncate the description at the "stop" line, if there is one.
-
-sub reorganize_phase
-{
-	
-	undef @newobydata;
-	my @section2;
-	my @part3;
-	my @part4;
-	my @part5;
-	my @part6;
-	my @part7;
-	my @part8;
-	my @partitions = ( \@newobydata, \@section2, \@part3, \@part4, \@part5, \@part6, \@part7, \@part8 );
-	my @currentpartition;	# partition stack
-
-	my @processedImageIdx;		# list of proccesed data drive image index. 
-	my $dataDriveStartRegion = 0;
-	my $dataDriveEndRegion = 0;
-	my $dataDriveIdx;
-	my @datapartition;
-	my @linesArray;
-	my $curlyBraceShouldFollow;
-
-	my $collect_section2=1;
-	my $smrImageStartRegion = 0;
-	my $smrImageEndRegion = 0;
-	my $smrImageIndex = 0;
-	
-	foreach $line (@obydata)
-	{
-		track_source($line);
-		if ($line=~/^\s*stop/i)
-		{
-			last;
-		}
-		if ($line =~ /^\s*ROM_IMAGE\[(\S+)\]\s+\{(.*)$/i)
-		{
-			# ROM_IMAGE[n] {
-			my $idx=$1;
-			my $partition=$partitions[$idx];
-			push @currentpartition, $partition;
-			$line="REM handled $line";
-		}
-		elsif( ($line =~ /^\s*DATA_IMAGE\[(\S+)\]\s*$/i) || ($line =~ /^\s*DATA_IMAGE\[(\S+)\]\s*\{\s*$/i))
-		{
-			# DATA_IMAGE[n] or DATA_IMAGE[n] {  is specified.
-			# get the index.
-			$dataDriveIdx=$1;
- 			if($line !~ /\s*\{\s*/i)
- 			{
- 				$curlyBraceShouldFollow = 1;
- 			}
-			# make a check if dataDriveIdx exists in the processedImageIdx array.
-			# if no, then push the dataDriveIdx on the processedImageIdx array.
-			# if yes,then dont execute the loop.
-			if(&datadriveimage::checkInArray(\@processedImageIdx,$dataDriveIdx))
-			{
-				# push the index on to the array.
-				push(@processedImageIdx,$dataDriveIdx);
-				# increment the image count. 
-				++$dataImageCount;
-			}
-
-			$dataIndexHash{($dataImageCount-1)} = $dataDriveIdx;
-			# set start of the image section.
-			$dataDriveStartRegion = 1;
-			# set end of image section to zero.
-			$dataDriveEndRegion = 0;
-			push (@linesArray,"\n");
-			$line="REM handled $line";
-		}
-		elsif( $line =~ /^\s*SMR_IMAGE\s*\{\s*$/i)
-		{
-			$smrImageStartRegion = 1;
-			$smrImageEndRegion = 0;
-			$needSmrImage = 1;
-			push (@linesArray, "\n");
-			$line="REM handled $line";
-		}
- 		elsif((defined $curlyBraceShouldFollow) && ($line !~ /^\s*$/i))
- 		{
-			undef $curlyBraceShouldFollow;
- 			if($line !~ /^\s*\{\s*/i)
- 			{
- 				print "Error: Symbol '{' not followed after the keyword DATA_IMAGE\[".$dataDriveIdx."\]\n";
- 				$errors++;
- 			}
- 			next;
- 		}
-		# data drive specific keywords.
-		elsif( $line =~/^\s*dataimagename\s*\=\s*(\S+)/i )
-		{
-			# set the name for the image, if image name is specified using driveimagename keyword.
-			$datadriveimage[$dataDriveIdx]{name} = $1 if($dataDriveStartRegion && !$dataDriveEndRegion);
-			print"datadriveimagename = $datadriveimage[$dataDriveIdx]{name}\n" if($dataDriveStartRegion && !$dataDriveEndRegion && $opt_v);
-			# skip the line.
-			next;
-		}
-		elsif( $line =~/^\s*dataimagesize\s*\=\s*(\S+)/i )
-		{
-			# set the size for the image, if image size is specified using driveimagesize keyword.
-			$datadriveimage[$dataDriveIdx]{size} = $1 if($dataDriveStartRegion && !$dataDriveEndRegion);
-			print"datadriveimagesize = $datadriveimage[$dataDriveIdx]{size}\n" if($dataDriveStartRegion && !$dataDriveEndRegion && $opt_v);
-			# skip the line.
-			next;
-		}
-		elsif( $line =~/^\s*dataimagefilesystem\s*\=\s*(\S+)/i )
-		{
-			# set the file system type for the image, if image file system is specified using dataimagefilesystem keyword.
-			$datadriveimage[$dataDriveIdx]{fstype} = $1 if($dataDriveStartRegion && !$dataDriveEndRegion);
-			print"datadriveimagefstype = $datadriveimage[$dataDriveIdx]{fstype}\n" if($dataDriveStartRegion && !$dataDriveEndRegion && $opt_v);
-			# skip the line.
-			next;
-		}
-		elsif( $line =~/^\s*compress/i )
-		{
-			# Compresses the resulting data drive image using the Deflate, Huffman+LZ77 algorithm.
-			if($dataDriveStartRegion && !$dataDriveEndRegion)
-			{
-				$datadriveimage[$dataDriveIdx]{compress} = 1;
-				$datadriveimage[$dataDriveIdx]{uncompress} = 0;
-				print"datadriveimage[$dataDriveIdx] compress = $datadriveimage[$dataDriveIdx]{compress}\n" if($opt_v);
-			}
-		}
-		elsif( $line =~/^\s*uncompress/i )
-		{
-			# Uncompresses the resulting data drive image.
-			if($dataDriveStartRegion && !$dataDriveEndRegion)
-			{
-				$datadriveimage[$dataDriveIdx]{uncompress} = 1;
-				$datadriveimage[$dataDriveIdx]{compress} = 0;
-				print"datadriveimage[$dataDriveIdx] uncompress = $datadriveimage[$dataDriveIdx]{uncompress}\n" if($opt_v);
-			}
-		}
-		elsif ($line =~ /^\s*ROM_IMAGE\[(\S+)\](.*)$/i)
-		{
-			# ROM_IMAGE[n] file=...
-			my $origline=$line;
-			$line="$2\n";	# remove the ROM_IMAGE[.] keyword
-			my $idx=$1;
-			my $partition=$partitions[$idx];
-			push @$partition, reassert_sourceline(-1);
-			push @$partition, $line;
-			$line="REM handled $origline";
-		}
-		elsif ($line =~ /^\s*DATA_IMAGE\[(\S+)\](.*)$/i)
-		{
-			# DATA_IMAGE[n] file=...
-			my $origline=$line;
-			# remove the DATA_IMAGE[.] keyword
-			$line="$2\n";
-			# get the index value
-			my $idx=$1;
-			# iterate through the hash to get corresponding 
-			# key from the value(i.e idx) 
-			while (my($key, $value) = each(%dataIndexHash))
-			{
-				if ($value eq $idx ) 
-				{
-					$idx = $key;
-				}
-			}
-			push @{$datapartition[$idx]}, reassert_sourceline(-1);
-			push @{$datapartition[$idx]}, $line;
-			$line="REM handled $origline";
-		}
-		elsif ($line =~ /^\s*\}.*$/i)
-		{
-			if($dataDriveStartRegion)
-			{
-				# since "}" brace is encountered
-				# reset the start of DATA_IMAGE to zero.
-				$dataDriveStartRegion = 0;
-				# mark the the end of the DATA_IMAGE.
-				$dataDriveEndRegion = 1;
-				if(!$datadriveimage[$dataDriveIdx]{name})
-				{
-					# image name is not defined, define a default name.
-					$datadriveimage[$dataDriveIdx]{name} = "dataImage".$dataDriveIdx;
-				}
-				if(!$datadriveimage[$dataDriveIdx]{fstype})
-				{
-					# image name is not defined, define a default name.
-					$datadriveimage[$dataDriveIdx]{fstype} = "fat16";
-				}
-				foreach my $file (@linesArray)
-				{
-					push @{$datapartition[($dataImageCount-1)]},$file;
-				}
-				## if end of the DATA_IMAGE is true,
-				## make room for next DATA_IMAGE if any.
-				undef(@linesArray); 
-				#un define $dataDriveIdx;
-				undef($dataDriveIdx);
-			}
-			elsif($smrImageStartRegion)
-			{
-				$smrImageStartRegion = 0;
-				$smrImageEndRegion = 1;
-				foreach my $file (@linesArray)
-				{
-					push @{$smrPartitions{$smrImageIndex}}, $file;
-				}
-				undef(@linesArray);
-				$smrImageIndex++;
-			}
-			elsif (scalar @currentpartition > 0)
-			{ 
-				pop @currentpartition; 
-			}
-			else
-			{ 
-				print "WARNING: closing '}' found with no matching 'ROM_IMAGE[<n>]/DATA_IMAGE[<n>] {'\n";
-			}
-			$line="REM handled $line";
-		}
-		elsif ($line=~/^\s*section2(.*)$/i)
-		{
-			my $origline=$line;
-			$line="$1\n";	# remove the section2 keyword
-			if ($collect_section2)
-			{
-				push @section2, reassert_sourceline(-1);
-				push @section2, $line;
-				$line="REM handled $origline";
-			}
-		}
-		elsif ($line=~/^\s*section/i)
-		{
-			push @newobydata, $line;		# insert the section statement
-			if (@section2 != 0)
-			{
-				push @newobydata, "REM accumulated section2 lines\n";
-			}
-			foreach $line (@section2)
-			{
-				push @newobydata, $line;	# insert accumulated section2 lines
-			}
-			$collect_section2=0;
-			$line = reassert_sourceline();
-		}
-		
-		elsif ($line=~/^\s*extensionrom/i)
-		{
-			# end of ROM description, so deposit accumulated lines
-			if (@section2 != 0)
-			{
-				push @newobydata, "REM accumulated section2 lines\n";
-			}
-			foreach $line (@section2)
-			{
-				push @newobydata, $line;	# insert accumulated section2 lines
-			}
-			$collect_section2=0;
-			push @newobydata, reassert_sourceline();
-		}
-		
-		elsif ( scalar(@linesArray) )
-		{
-			if($dataDriveStartRegion && !$dataDriveEndRegion)
-			{
-				my $modifiedLine = $line;
-				push @linesArray, $modifiedLine;
-				$line = "REM handled $line";
-			}
-			elsif($smrImageStartRegion && !$smrImageEndRegion)
-			{
-				if($line =~ /^\s*IMAGENAME\s*=\s*(\S+)/i)
-				{
-					my $smrimagename = $1;
-					$smrimagename =~s/(\.img)//i;
-					if(exists($smrNameInfo{$smrimagename}))
-					{
-						$smrNameInfo{$smrimagename}++;
-					}
-					else
-					{
-						$smrNameInfo{$smrimagename} = 1;
-					}
-					$line =~s/(\.img)//i;
-				}
-				push @linesArray, $line;
-				$line = "REM handled $line";
-			}
-		}
-		elsif (scalar @currentpartition)
-		{
-			my $modifiedLine = $line;
-			if ($line =~ /^\s*SPI_POSITION/i)
-			{
-				if(!($createspi && $spiplacement))
-				{
-					# comment the line if the spi placement flag is not enabled or if the spi creation is not enabled.
-					$modifiedLine = "REM SPI creation/placement flag not enabled. Ignoring SPI_POSITION\n";
-					print ("Warning: SPI creation/placement flag not enabled. Ignoring SPI_POSITION\n" ) if ($opt_v);
-				}
-			}
-			# a partition is specified
-			# push this line into the currently selected partition
-			my $partition=@currentpartition[-1];
-			push @$partition, $modifiedLine;
-			$line="REM handled $line";
-		}
-		elsif ($line =~ /^\s*SPI_POSITION/i)
-		{
-			if(!($createspi && $spiplacement))
-			{
-                # comment the line if the spi placement flag is not enabled or if the spi creation is not enabled.
-                $line = "REM SPI creation/placement flag not enabled. Ignoring SPI_POSITION\n";
-                print ("Warning: SPI creation/placement flag not enabled. Ignoring SPI_POSITION\n" ) if ($opt_v);
-			}
-		}
-		push @newobydata, $line;
-	}
-
-	# output the grouped data
-	my $partitionidx=2;
-	if ($collect_section2)
-		{ $partitionidx=1; } # output old "section2" if not done already
-	for (; $partitionidx<8; $partitionidx++)
-	{
-		my $partition=$partitions[$partitionidx];
-		if (@$partition != 0)
-		{
-			push @newobydata, "REM ROM_IMAGE[$partitionidx]\n";
-			foreach $line (@$partition)
-			{
-				push @newobydata, $line;	# insert accumulated section2 lines
-			}
-		}
-	}
-	
-	for ( my $datapartitionidx=0; $datapartitionidx < $dataImageCount; $datapartitionidx++ )
-	{
-		if( defined( @{ $datapartition[$datapartitionidx] } ) )
-		{
-			push @newobydata, "REM DATA_IMAGE[$dataIndexHash{$datapartitionidx}]\n" ;
-			foreach my $file (@{$datapartition[$datapartitionidx]})
-			{
-				push @newobydata, $file;
-			}
-		}
-	}
-
-	
-	foreach my $imageIndex (keys(%smrPartitions))
-	{
-		my $imagename;
-		my @obeyfile;
-
-		foreach (@{$smrPartitions{$imageIndex}})
-		{
-			if(/^\s*imagename\s*=\s*(\S+)/i)
-			{
-				$imagename = $1;
-			}
-			push @obeyfile, $_;
-		}
-		if($smrNameInfo{$imagename} == 1)
-		{
-			push @obeyFileList, $imagename;
-			push @newobydata, "REM SMR_IMAGE \n";
-			push @newobydata, @obeyfile;
-		}
-		if(! defined($imagename))
-		{
-			$smrNoImageName = 1;
-		}
-		undef $imagename;
-		undef @obeyfile;
-	}
-
-	@obydata = @newobydata;
-	exit(1) if ($errors);
-	dump_obydata("tmp3.oby", "result of reorganisation phase") if ($opt_v);
-}
-
-
-#----------------------------------------------------------------------------------
-# Plugin phase
-#
-# Process any plugin annotation lines
-# Note: This expands resource lines to include MULTI_LINGUIFY so must be done before
-# the Multilinguify phase
-
-# hash of SPI file target directories is located near the start of this file, before sub match_obyfile
-
-sub plugin_phase
-{
-	undef @newobydata;
-	foreach $line (@obydata)
-	{
-		track_source($line);
-	 	if ($line =~ /^\s*REM/i)
-		{
-		# ignore REM statements, to avoid processing "REM ECOM_PLUGIN(xxx,yyy)"
-		}
-		elsif(plugin_match($line)) {
-			$line = reassert_sourceline();		
-		}
-		push @newobydata, $line;
-	}
-		
-	@obydata = @newobydata;
-	dump_obydata("tmp4.oby", "result of Plugin stage") if ($opt_v);
-}
-
-sub plugin_match ()
-{
-	my ($line) = @_;
-	foreach my $plugintype (keys(%plugintypes)) {
-	  if ($line =~ m/^.*__$plugintype\_PLUGIN\(\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*\)/i)
-	  	# __<plugin-type>_PLUGIN(emulator directory, file rom dir, dataz_, resource rom dir, filename, resource filename)
-	  {
-		    my $emulatorDir=$1;
-		    my $fileRomDir=$2;
-		    my $dataz_= $3;
-		    my $resourceDir=$4;
-		    my $pluginFileName=$5;
-		    my $pluginResourceName=$6;
-		    my $spidatahide = 0;
-			my $paged_data = "";
-  
-			if ($line =~ m/paged\s*$/i)
-			{
-				$line =~ m/\s+(\S+)\s*$/;
-				$paged_data = $1;
-			}
-
-		    if ($line =~ m/^\s*(_hide)/i )
-		    {
-		    	$spidatahide = 1;
-		    }
-
-		    # for resource files strip the .rsc or .dll from the end   (will be .dll where we use
-		    # SYMBIAN_SECURE_ECOM and are building resources to  the same name as ecom plugin dlls)
-		    
-		    if ($pluginResourceName =~ m/^(.+)\./)
-		    {
-		      $pluginResourceName = $1;
-		    }
-		    else
-		    {
-		      print_source_error("Invalid Resource name: $pluginResourceName in " . $plugintype . "_PLUGIN :$line");
-		      #treat as error if strict option selected;
-		      $errors++ if ($strict);
-		    }
-
-		    if ($spidatahide)
-		    {
-			push @newobydata, "hide=$fileRomDir\\$pluginFileName\n";
-		    }
-		    else
-		    {
-		    	push @newobydata, "file=$emulatorDir\\$pluginFileName $fileRomDir\\$pluginFileName $paged_data\n";
-		    }
-
-		    if($createspi) {
-		    	    if ($spidatahide)
-			    {
-			    	push @newobydata, "spidatahide=MULTI_LINGUIFY(RSC $dataz_\\$resourceDir\\$pluginResourceName $resourceDir\\$pluginResourceName) " . lc($plugintype) . "\.spi " . $plugintypes{$plugintype} . "\n";      
-			    }
-			    else
-			    {
-			    	push @newobydata, "spidata=MULTI_LINGUIFY(RSC $dataz_\\$resourceDir\\$pluginResourceName $resourceDir\\$pluginResourceName) " . lc($plugintype) . "\.spi " . $plugintypes{$plugintype} . "\n";      
-			    }
-		  	} else {
-		    	    if ($spidatahide)
-			    {
-			    	push @newobydata, "hide=MULTI_LINGUIFY(RSC $dataz_\\$resourceDir\\$pluginResourceName $resourceDir\\$pluginResourceName)\n";
-			    }
-			    else
-			    {
-			    	push @newobydata, "data=MULTI_LINGUIFY(RSC $dataz_\\$resourceDir\\$pluginResourceName $resourceDir\\$pluginResourceName)\n";
-			    }
-			}
-				return 1; #successful match
-	   }
-     }
-}
-
-
-#----------------------------------------------------------------------------------
-# Multilinguify phase
-#
-# Process the MULTILINGUIFY() lines
-
-sub multlinguify_phase
-{
-	if ((scalar keys %languageCodes) == 0)
-	{
-		print "* No language codes specified, defaulting to 01\n";
-		$defaultLanguageCode = "01";
-	}
-	$languageCodes{$defaultLanguageCode} = 1;
-	
-	undef @newobydata;
-	foreach $line (@obydata)
-	{
-		track_source($line);
-		if ($line =~ /^\s*REM/i)
-		{
-			# ignore REM statements, to avoid processing "REM data=xxx yyy"
-		}
-		elsif ($line=~/^(.*?)\bMULTI_LINGUIFY\s*\(\s*(\S+)\s+(\S+)\s+(\S+)\s*\)(.*)$/i)
-		{
-			my $initialStuff=$1;
-			my $defaultFileNameExtension=$2;
-			my $sourceFileNameWithoutExtension=$3;
-			my $targetFileNameWithoutExtension=$4;
-			my $finalStuff=$5;
-			my $spidataflag = 0;
-			my $spidatahide = 0;
-			my $datahide = 0;
-
-			if ($initialStuff=~/\w$/)
-			{
-				$initialStuff.=" ";
-			}
-			if ($finalStuff=~/^\w/)
-			{
-				$finalStuff=" ".$finalStuff;
-			}
-			if ($initialStuff =~ /^\s*spidata/i)
-			{
-				$spidataflag = 1;
-			}
-			if ($initialStuff =~ /^\s*spidatahide/i)
-			{
-				$spidataflag = 1;
-				$spidatahide = 1;
-			}
-			if ($initialStuff =~ /^\s*hide/i)
-			{
-				$datahide = 1;
-			}
-
-
-# ecom.spi should contain the .RSC files
-			if ($spidataflag)
-			{
-				my $sourceFileNameExtension = $defaultFileNameExtension;
-				my $targetFileNameExtension = $defaultFileNameExtension;
-				if (-e "$sourceFileNameWithoutExtension.$sourceFileNameExtension")
-				{
-					if ($spidatahide)
-					{
-						push @newobydata, "$initialStuff$sourceFileNameWithoutExtension.$sourceFileNameExtension$finalStuff\n";
-					}
-					else
-					{
-						push @newobydata, "$initialStuff$sourceFileNameWithoutExtension.$sourceFileNameExtension $targetFileNameWithoutExtension.$targetFileNameExtension$finalStuff\n";
-					}
-				}
-			}
-			my $useDefaultFileNameExtension=1;
-			foreach my $languageCode (keys %languageCodes) {
-				my $sourceFileNameExtension=$defaultFileNameExtension;
-				$sourceFileNameExtension=~s/^(.*).{2}$/$1$languageCode/;
-				if (! -e "$sourceFileNameWithoutExtension.$sourceFileNameExtension")
-				{
-					if (!$spidataflag)
-					{
-						next if (!$useDefaultFileNameExtension);
-						next if (defined $defaultLanguageCode and !($languageCode eq $defaultLanguageCode));
-						$useDefaultFileNameExtension=0;
-						if (!$datahide)
-						{
-							print "Converting >$sourceFileNameWithoutExtension.$sourceFileNameExtension< to $defaultFileNameExtension\n";
-							$sourceFileNameExtension=$defaultFileNameExtension;
-						}
-					}
-					else
-					{
-						next;
-					}
-				}
-
-				my $targetFileNameExtension;
-# ecom.sNN should contain the corresponding language code .RNN files
-				if(!$spidataflag and (defined $defaultLanguageCode and ($languageCode eq $defaultLanguageCode)))
-				{
-					$targetFileNameExtension = $defaultFileNameExtension;
-				}
-				else
-				{
-					$targetFileNameExtension = $sourceFileNameExtension;
-				}
-				my $modifiedfinalStuff = $finalStuff;
-				$modifiedfinalStuff =~ s/\.spi/\.s$languageCode/i;
-
-				if ($spidatahide)
-				{
-					push @newobydata, "$initialStuff$sourceFileNameWithoutExtension.$sourceFileNameExtension$modifiedfinalStuff\n";
-				}
-				elsif ($datahide)
-				{
-					push @newobydata, "$initialStuff$targetFileNameWithoutExtension.$targetFileNameExtension$modifiedfinalStuff\n";
-					if(!($sourceFileNameExtension eq $targetFileNameExtension))
-					{
-						push @newobydata, "$initialStuff$targetFileNameWithoutExtension.$sourceFileNameExtension$modifiedfinalStuff\n";
-					}
-				}
-				else
-				{
-					push @newobydata, "$initialStuff$sourceFileNameWithoutExtension.$sourceFileNameExtension $targetFileNameWithoutExtension.$sourceFileNameExtension$modifiedfinalStuff\n";
-					if(!($sourceFileNameExtension eq $targetFileNameExtension))
-					{
-						push @newobydata, "alias $targetFileNameWithoutExtension.$sourceFileNameExtension $targetFileNameWithoutExtension.$targetFileNameExtension $modifiedfinalStuff\n";
-						$multiLinguifyAlias{"$targetFileNameWithoutExtension.$sourceFileNameExtension"} = 1;
-					}
-				}
-			}
-			$line = reassert_sourceline();
-		}
-		push @newobydata, $line;
-	}
-		
-	@obydata = @newobydata;
-	dump_obydata("tmp5.oby", "result of choosing language-specific files") if ($opt_v);
-	undef @newobydata;
-
-}
-
-my @featurefilearray; #2d array storing names and locations of feature files in each rom image
-my @featureslist; #array of hashes, stores all the features which are to go into the feature files
-my $featurefilecount=0; #counts number of feature files in each rom image
-my $featurescount=0; #counts number of features
-my $dir; # Stores the ROM image location of features.dat/featreg.cfg files
-my $featurefilename; # Stores the name of feature file to be generated(i.e. "features.dat" or "featreg.cfg")
-my @spiarray; #2d array storing names and locations of spi files in each rom image
-my @datafiles; #array of hashes, stores all the data files which are to go into the spi files
-my @hidedatafiles; #array of hashes, stores all the data files which are to be hidden in the spi files
-my $spicount=0; #counts number of spi files in each rom image
-my $filescount=0; #counts number of data files
-my $hidefilescount=0; #counts number of data files to be hidden
-my $romimage=0; #number of rom image currently working with
-
-sub locateexisting 
-{ # if an SPI file of this type exists in a base image then returns name of SPI file from the array
-	my ($romimage, $spifile, $base) =@_;
-	my $i=0;
-	while(defined $spiarray[$base][$i]) {
-		if($spiarray[$base][$i]{spi} eq $spiarray[$romimage][$spifile]{spi}) {
-			my $spiname;
-			my $spiextension;
-			if($spiarray[$base][$i]{spifile} =~ /(.*)\.(.*)$/) {
-				$spiname=$1;
-				$spiextension=$2;
-			}
-			if(-e "$spiname-$base-$i\.$spiextension") {
-					return "$spiname-$base-$i\.$spiextension";
-			}
-		}
-		$i++;
-	}
-	return "";
-}
-
-sub create 
-{ #called to create SPI file and store in specified directory
-	my ($romimage, $spifile, $base) =@_; #$romimage = current rom image number, $spifile = current spifile number, $base=number of rom image basing on
-	my $existingspi = "";
-	if(defined($base)) { # checks core image for an existing SPI file of this type, if an existing file exists then $existingspi is set to -i<name of existing spi file> which will later be passed to spitool.pm
-		$existingspi = locateexisting($romimage, $spifile, $base);
-		if($existingspi ne "") {
-			$existingspi = "-i$existingspi";
-			
-		}
-	}
-	if($spiarray[$romimage][$spifile]{spifile} =~ /(.+)\.(.*)$/) {
-		my $targetspi="$1-$romimage-$spifile\.$2"; #add romimage number and identifier for spi file to spi file name to distinguish from other spi files
-		my @dataforspi; # array to store names of data files to include in spi file
-		my @hidedatainspi; # array to store names of data files that are to be hidden in spi file
-		for(my $k=0;$k<scalar @datafiles;$k++) {
-			if($datafiles[$k]{rom}==$romimage && $datafiles[$k]{spifile} == $spifile) {
-				push @dataforspi, $datafiles[$k]{data}; #push name of data file onto array if correct romimage and spi type
-			}
-		}
-
-		for(my $j=0;$j<scalar @hidedatafiles;$j++) {
-			if($hidedatafiles[$j]{rom}==$romimage && $hidedatafiles[$j]{spifile} == $spifile)
-			{
-				push @hidedatainspi, $hidedatafiles[$j]{data}; #push name of data file to be hidden onto array if correct romimage and spi type
-			}
-		}
-		my @spiargs; #arguments passed to createSpi
-		push @spiargs, ("-t$targetspi", "-d\\$thisdir", "-hide@hidedatainspi");
-		if($existingspi ne "") { push @spiargs, $existingspi; }
-		&spitool::createSpi(@spiargs, @dataforspi); # external call to 
-	}
-}
-
-#----------------------------------------------------------------------------------
-# SPI file creation phase
-#
-# If SPI files for resource (.rsc) are required then creates SPI files for each ROM image
-#
-sub spi_creation_phase
-{
-	my $composite_secondary=-1;
-	if($createspi) { 
-		my $secondary=0;
-		for (my $i=1; $i<8; $i++)
-		{
-			if($romimage[$i]{composite} eq "composite_secondary") 
-				{ $secondary++; }
-		}
-		if(!$secondary) 
-			{ $romimage[0]{composite} = "composite_secondary"; }
-		if($secondary>1)
-			{ print "Warning, more than one composite_primary specified, using image with lowest ROM_IMAGE number\n"; }
-	
-		foreach $line (@obydata)
-		{
-			if ($line=~/^\s*REM \s*ROM_IMAGE\[(\d)\]/) # specify which romimage following lines are part of
-			{
-				$romimage=$1;
-				$spicount=0;
-			}	elsif ($line =~ /^\s*REM/i)
-			{
-				# ignore any other REM statements
-			} elsif ($line=~/^\s*spidata\s*=\s*(\S+)\s+(\S+)\s+(\S+)\s(\S+)\s*$/)	{
-				#spidata=\epoc32\data\Z\Resource\Plugins\Obexclasscontroller.RSC Resource\Plugins\Obexclasscontroller.RSC ecom.spi \private\10003a3f\
-				my $targetspi=$4.$3;
-				my $flag=1;
-				my $i;
-				for($i=0;$i<$spicount && $flag;$i++) { #loop to see if name of spi file already added to this romimage in array
-					if($spiarray[$romimage][$i]{spi} eq $targetspi) {
-						$flag=0;
-					}
-				}
-			
-				if($flag) { # adds spi file if not yet listed for this romimage in array
-					$spiarray[$romimage][$spicount++]={spifile=>$3, spidir=>$4, spi=>$4.$3};
-					$i=$spicount;
-				}
-					$datafiles[$filescount++]= {data=>$1, rom=>$romimage, spifile=>$i-1}; 
-                        } elsif ($spiplacement && $line =~/^\s*SPI_POSITION/i){
-        			# mark the image index at which the SPI_POSITION keyword has occured in order to avoid writing duplicate
-        			# entries of the spi file.
-        			$spipositionflag{$romimage} = 1;
-        		} elsif ($line=~/^\s*spidatahide\s*=\s*(\S+)\s+(\S+)\s(\S+)\s*$/)	{
-				#spidatahide=\epoc32\data\Z\Resource\Plugins\Obexclasscontroller.RSC ecom.spi \private\10003a3f\
-				my $targetspi=$3.$2;
-				my $flag=1;
-				my $i;
-				for($i=0;$i<$spicount && $flag;$i++) { #loop to see if name of spi file already added to this romimage in array
-					if($spiarray[$romimage][$i]{spi} eq $targetspi) {
-						$flag=0;
-					}
-				}
-			
-				if($flag) { # adds spi file if not yet listed for this romimage in array
-					$spiarray[$romimage][$spicount++]={spifile=>$2, spidir=>$3, spi=>$3.$2};
-					$i=$spicount;
-				}
-					$hidedatafiles[$hidefilescount++]= {data=>$1, rom=>$romimage, spifile=>$i-1}; 
-			}
-
-		}
-		
-		for(my $i=0;$i<8 && $composite_secondary<0;$i++) { # loop to set $composite_secondary value
-			if($romimage[$i]{composite} eq "composite_secondary") {
-				$composite_secondary=$i;
-			}
-		}	
-	
-		for(my $i=0;$i<8;$i++) { #loop to add any spi files to composite_primary roms which are present in composite_secondary rom. spi files in secondary ROMs must be present in primary ROMS, this check rules out the possibility of the spi file in the primary rom not being created because it has no data files to add
-			if($romimage[$i]{composite} eq "composite_primary") {
-				my $j=0;
-				while(defined $spiarray[$composite_secondary][$j]) {
-					my $flag=1;
-					my $k=0;
-					while(defined $spiarray[$i][$k] && $flag) {
-						if($spiarray[$composite_secondary][$j]{spi} eq $spiarray[$i][$k]{spi}) {
-							$flag=0;
-						}
-						$k++;
-					}
-					if($flag) {
-						$spiarray[$i][$k]{spifile}=$spiarray[$composite_secondary][$j]{spifile};
-						$spiarray[$i][$k]{spidir}=$spiarray[$composite_secondary][$j]{spidir};
-						$spiarray[$i][$k]{spi}=$spiarray[$composite_secondary][$j]{spi};
-					}
-					$j++;
-				}
-			}
-		}
-		
-		for(my $i=0;$i<8;$i++) { #loop to add any spi files to extension roms which are present in core rom, same situation as in previous loop could potentially occur here
-			if($romimage[$i]{extension}) {
-				my $j=0;
-				while(defined $spiarray[$i-1][$j]) {
-					my $flag=1;
-					my $k=0;
-					while(defined $spiarray[$i][$k] && $flag) {
-						if($spiarray[$i-1][$j]{spi} eq $spiarray[$i][$k]{spi}) {
-							$flag=0;
-						}
-						$k++;
-					}
-					if($flag) {
-						$spiarray[$i][$k]{spifile}=$spiarray[$i-1][$j]{spifile};
-						$spiarray[$i][$k]{spidir}=$spiarray[$i-1][$j]{spidir};
-						$spiarray[$i][$k]{spi}=$spiarray[$i-1][$j]{spi};
-					}
-					$j++;
-				}
-			}
-		}
-	
-		for(my $i=0;$i<scalar @spiarray;$i++) { #create SPI files for ROMs which are neither composite_primary nor extensions
-			if(!($romimage[$i]{extension}) && $romimage[$i]{composite} ne "composite_primary") {
-				my $j=0;
-				while(defined $spiarray[$i][$j]) { 
-					create($i,$j++);
-				}
-			}
-		}	
-	
-		for(my $i=0;$i<8;$i++) { #create SPI files for ROMs marked as composite_primary
-			if($romimage[$i]{composite} eq "composite_primary") {
-				my $j=0;
-				while(defined $spiarray[$i][$j]) {
-					create($i,$j++,$composite_secondary);
-				}
-			}
-		}	
-		for(my $i=0;$i<8;$i++) { #create SPI files for ROMs marked as extension
-			if($romimage[$i]{extension}) {
-				my $j=0;
-				while(defined $spiarray[$i][$j]) {
-					create($i,$j++,$i-1);
-				}
-			}
-		}
-			
-		undef @newobydata;
-		my $flag=1;
-        	my $imageIdx=0;
-		foreach $line (@obydata) { #add SPI files to ROM image, adds lines to obey file to specify existing locations of SPI files and target locations.
-
-                        if($spiplacement){
-                                $flag = 0;	# Reset the flag since the spi file must be added to the final OBY only on finding SPI_POSITION 
-                                                        # keyword when the spiplacement flag is set. If the spiplacement flag is set but SPI_POSITION
-                                                        # is not found in the oby files, then no spi entry is emitted.
-                                if($line =~ /^\s*SPI_POSITION/i){
-                                        next if (!$spipositionflag{$imageIdx});#This spi has already been entered into OBY.
-                                        my $spiIdx=0;
-                                        while(defined $spiarray[$imageIdx][$spiIdx]) {
-                                                if($spiarray[$imageIdx][$spiIdx]{spifile} =~ /(.+)\.(.*)$/) {
-                                                        my $targetspi="$1-$imageIdx-$spiIdx\.$2";
-                                                        push @newobydata, "data=" . "\\$thisdir" . $targetspi . " \"" . $spiarray[$imageIdx][$spiIdx]{spi} . "\"\n";
-                                                }
-                                                $spiIdx++;
-                                        }
-                                        if($spiIdx == 0){
-                                                # If there is no plugin in this image, the SPI_POSITION statement is ignore.
-                                                print ("Warning: statement SPI_POSTION ignored as no plugin was found at ROM_IMAGE[${imageIdx}]\n");
-                                        }
-                                        $spipositionflag{$imageIdx} = 0;
-                                }
-                                elsif( $line =~ /REM ROM_IMAGE\[(\d)\]/i){
-                                        $imageIdx = $1;
-                                        push @newobydata, $line;
-                                }
-                                elsif($line =~ /^\s*spidata/i) {
-                                } else {
-                                        push @newobydata, $line;
-                                }
-                        }
-			elsif($line =~/REM ROM_IMAGE\[(\d)\]/) {
-				my $romimage=$1;
-				if($flag) { #put in SPI files for ROM_IMAGE[0]
-					$flag=0;
-					my $k=0;
-					while(defined $spiarray[0][$k]) {
-						if($spiarray[0][$k]{spifile} =~ /(.+)\.(.*)$/) {
-							my $targetspi="$1-0-$k\.$2";
-							push @newobydata, "data=" . "\\$thisdir" . $targetspi . " \"" . $spiarray[0][$k]{spidir} . $targetspi .  "\"\n";
-						}
-						$k++;
-					}
-				}
-				my $j=0;
-				push @newobydata, "\n" . $line . "\n";			
-				while(defined $spiarray[$romimage][$j]) { #put in SPI files for current ROM_IMAGE
-					if($spiarray[$romimage][$j]{spifile} =~ /(.+)\.(.*)$/) {
-						my $targetspi="$1-$romimage-$j\.$2";
-						push @newobydata, "data=" . "\\$thisdir" . $targetspi . " \"" . $spiarray[$romimage][$j]{spidir} . $targetspi .  "\"\n";
-					}
-					$j++;
-				}
-			} elsif($line =~ /^\s*extensionrom/i) {
-				if($flag) { #put in SPI files
-					my $k=0;
-					while(defined $spiarray[0][$k]) {
-						if($spiarray[0][$k]{spifile} =~ /(.+)\.(.*)$/) {
-							my $targetspi="$1-0-$k\.$2";
-							push @newobydata, "data=" . "\\$thisdir" . $targetspi . " \"" . $spiarray[0][$k]{spidir} . $targetspi . "\"\n";
-						}
-						$k++;
-					}
-					$flag = 0;
-				}
-				push @newobydata, $line;
-			} elsif($line =~ /^\s*spidata/i) {;
-			} else {
-				push @newobydata, $line;
-			}
-		}
-		if($flag) { #put in SPI files for ROM_IMAGE[0] if it is the only ROM_IMAGE
-			my $k=0;
-			while(defined $spiarray[0][$k]) {
-				if($spiarray[0][$k]{spifile} =~ /(.+)\.(.*)$/) {
-					my $targetspi="$1-0-$k\.$2";
-					push @newobydata, "data=" . "\\$thisdir" . $targetspi . " \"" . $spiarray[0][$k]{spidir} . $targetspi . "\"\n";
-				}
-				$k++;
-			}
-		}
-		@obydata=@newobydata;
-	}	
-	dump_obydata("tmp6.oby", "result of SPI stage") if ($opt_v);
-}
-
-sub load_featuresutil
-{
-	&Load_ModuleL("featuresutil");
-			
-	# Parse the feature database XML file
-	if(!&featuresutil::parseXMLDatabase($featureXml, $featuremanager, $strict))
-	{
-		$featureXml = undef;
-		exit(1) if($strict);
-	}
-}
-
-#----------------------------------------------------------------------------------
-# Feature registry configuration file/Features data file generation phase
-#
-# If feature registry configuration files/features data files are required then creates these files for
-# each ROM/ROFS image
-#
-sub featurefile_creation_phase
-{
-	if($onlysmrimage)
-	{
-		return;
-	}
-	# Set the name and Rom Image location of feature file.
-	if ($enforceFeatureManager) 
-	{
-		# features data file location
-		$dir = "private\\10205054\\";
-		$featurefilename = "features.dat";
-	}
-	else
-	{
-		# feature registry configuration file location
-		$dir = "private\\102744CA\\"; 
-		$featurefilename = "featreg.cfg";
-	}		
-	if (defined ($featureXml)) 
-	{
-		my $featurefilecount=0;
-		my $romimage=0;
-
-		foreach $line (@obydata)
-		{
-			# specify which romimage following lines are part of
-			if ($line=~/^\s*REM \s*ROM_IMAGE\[(\d)\]/) 
-			{
-				$romimage=$1;
-				$featurefilecount=0;
-			}
-			elsif ($line =~ /^\s*REM/i)
-			{
-				# ignore any other REM statements
-			}
-			elsif($line =~ /^\s*(FEATURE)\s*(\S*)\s*(.*)/i
-					|| $line =~ /^\s*(EXCLUDE_FEATURE)\s*(\S*)\s*(.*)/i)
-			{				
-				# FEATURE  <feature_name>  [ SF  <status falgs> ] [ UD  <user data> ]
-				my $feature = $1;
-				my $featurevalue = $2;
-				my $featureargs = $3;
-				my $reservedbit = 0;
-				my %featureflags=();				
-				
-				# Options 'SF' and 'UD' will be supported only for "-fm" option
-				if ($featuremanager) 
-				{
-					# [ SF  <status falgs> ] [ UD  <user data> ]
-					$featureargs =~	/(\S*)\s*(\S*)\s*(\S*)\s*(\S*)\s*/ ;
-
-					# Store the values of 'SF' and 'UD', or any invalid option, if provided					
-					if ($1) 
-					{	
-						$featureflags{uc($1)} = $2;						
-					}
-					if ($3) 
-					{
-						$featureflags{uc($3)} = $4;									
-					}
-
-					# Generate a warning if the option provided with Feature/Exclude_Feature keyword is  
-					# not 'SF' or 'UD'.
-					foreach my $Key (keys %featureflags)
-					{						
-						if ($Key !~ /^(SF|UD)$/)
-						{
-							print "Warning: Invalid argument \"$Key\" specified for feature $featurevalue\n";
-							delete $featureflags{$Key};
-							next;
-						}						
-					}							
-				}				
-				# In verbose mode, generate warning if "SF|UD" arguments or invalid arguments are specified
-				# for "-f|fr" option.
-				elsif ($featureargs && $opt_v)
-				{
-					print "Invalid argument(s) \"$featureargs\" provided for feature \"$featurevalue\"\n";
-					foreach my $Key (keys %featureflags)
-					{
-						delete $featureflags{$Key};
-					}
-				}				
-				
-				# The feature file name is of the format featreg.cfg[x-y] or features.dat[x-y] 
-				# where x is the romimage id, y is always 0, reserved for future use.
-				my $targetfeaturefile;
-				if (($romimage == 0) && ($reservedbit == 0))
-				{
-
-					# Core image will not have the mangled name
-				 	$targetfeaturefile = $featurefilename;
-				}
-				else
-				{
-				 	$targetfeaturefile = $featurefilename . "\[". $romimage . "\-$reservedbit\]";
-				}
-				my $flag=1;
-				my $featureflag;
-				if ($feature =~ /^FEATURE$/i)
-				{
-					$featureflag = 1;
-				}
-				else
-				{
-					$featureflag = 0;
-				}
-
-				my $i;
- 				# loop to see if name of feature file already added to this romimage in array
-				for($i=0;$i<$featurefilecount && $flag;$i++)
-				{
-					if($featurefilearray[$romimage][$i]{cfgfile} eq $targetfeaturefile)
-					{
-						$flag=0;
-					}
-				}
-			
-				if($flag) { # adds feature file if not yet listed for this romimage in array
-					$featurefilearray[$romimage][$featurefilecount++]={cfgfile=>$targetfeaturefile, cfgdir=>$dir};
-					$i=$featurefilecount;
-				}
-
-				$featureslist[$featurescount]= {feature=>$featurevalue, include=>$featureflag, rom=>$romimage, cfgfile=>$i-1};
-				
-				# Store the value of 'SF' in 'featureslist' array
-				if (defined $featureflags{SF}) 
-				{
-					$featureslist[$featurescount]->{SF} = $featureflags{SF};						
-				}
-				# Store the value of 'UD' in 'featureslist' array
-				if (defined $featureflags{UD}) 
-				{
-					$featureslist[$featurescount]->{UD} = $featureflags{UD};
-				}				
-				$featurescount++;
-			}
-		}
-
-		# Create Feature File
-		for(my $i=0;$i<scalar @featurefilearray;$i++)
-		{
-			my $j=0;
-			while(defined $featurefilearray[$i][$j])
-			{
-				my $targetfeaturefile = $featurefilearray[$i][$j]{cfgfile};
-				if (!(&featuresutil::createFeatureFile($i,$j,$targetfeaturefile,\@featureslist,$featuremanager))) 
-				{
-					$featurefilearray[$i][$j]{cfgfile}= undef;
-					exit(1) if($strict);					
-				}
-				$j++;
-			}
-		}
-	
-		undef @newobydata;
-		my $flag=1;
-        	my $imageIdx=0;
-
-		# Add feature files to ROM image, adds lines to obey file to specify existing locations
-		# of feature files and target locations.
-		foreach $line (@obydata)
-		{
-			if($line =~/REM ROM_IMAGE\[(\d)\]/i)
-			{
-				my $romimage=$1;
-				if($flag)
-				{
-					# Put in feature files for ROM_IMAGE[0]
-					$flag=0;
-					my $k=0;
-					while(defined $featurefilearray[0][$k])
-					{
-						my $targetfeaturefile=$featurefilearray[0][$k]{cfgfile};
-						if (defined $targetfeaturefile) 
-						{
-							push @newobydata, "data=" . "\\$thisdir" . $targetfeaturefile . " \"" . $featurefilearray[0][$k]{cfgdir} . $targetfeaturefile .  "\"\n";							
-						}
-						$k++;
-					}
-				}
-				push @newobydata, "\n" . $line . "\n";			
-
-				my $j=0;
-				while(defined $featurefilearray[$romimage][$j])
-				{
-					# Put in feature files for current ROM_IMAGE
-					my $targetfeaturefile=$featurefilearray[$romimage][$j]{cfgfile};
-					
-					# Rom images will not have mangled name for feature files
-				 	my $destinationfeaturefile = $featurefilename;
-					
-					# Rofsbuild will set attribute 'exattrib=U' in the entry record when this field is used.
-					# File Server when asked for a directory listing would notice the attribute and will return the 
-					# list with mangled names. Hence, mangled name for feature files should not be put in ROM_IMAGE.
-					my $exattribute = "exattrib=U";
-
-					if (defined $targetfeaturefile)
-					{
-						push @newobydata, "data=" . "\\$thisdir" . $targetfeaturefile . " \"" . $featurefilearray[$romimage][$j]{cfgdir} . $destinationfeaturefile .  "\"\t\t" . $exattribute . "\n";
-					}
-					$j++;
-				}
-			}
-			elsif($line !~ /^\s*(FEATURE)\s*/i && $line !~ /^\s*(EXCLUDE_FEATURE)\s*/i)
-			{
-				# Put in all other lines except the FEATURE and EXCLUDE_FEATURE keywords
-				push @newobydata, $line;
-			}
-		}
-
-		if($flag)
-		{ 
-			# Put in feature files for ROM_IMAGE[0] if it is the only ROM_IMAGE
-			my $k=0;
-			while(defined $featurefilearray[0][$k])
-			{
-				my $targetfeaturefile = $featurefilearray[0][$k]{cfgfile};
-				if (defined $targetfeaturefile)
-				{
-					push @newobydata, "data=" . "\\$thisdir" . $targetfeaturefile . " \"" . $featurefilearray[0][$k]{cfgdir} . $targetfeaturefile . "\"\n";
-				}
-				$k++;
-			}
-		}
-		@obydata=@newobydata;
-	}
-	elsif ($enforceFeatureManager && $noFeatureManager && $preBuiltFeaturesDataFile)
-	{
-        print "Valid: $preBuiltFeaturesDataFile\n";
-		if (-e $preBuiltFeaturesDataFile) 
-		{			
-			my @newobydata = ();
-			my $flag = 1;
-			foreach my $line (@obydata)
-			{
-				# Put in the pre-built features data file in ROM_IMAGE[0] 
-				if($line =~/REM ROM_IMAGE\[1\]/i)
-				{
-					push @newobydata, "data=$preBuiltFeaturesDataFile" . " \"" . $dir . $featurefilename . "\"\n";
-					$flag =0;
-				}
-				push @newobydata, $line;
-			}
-			if($flag)
-			{ 
-				# Put in the pre-built features data file in ROM_IMAGE[0] if it is the only ROM_IMAGE
-				push @newobydata, "data=$preBuiltFeaturesDataFile" . " \"" . $dir . $featurefilename . "\"\n";
-			}
-			@obydata =  @newobydata;
-		}
-		else
-		{
-			print "Error: File \"$preBuiltFeaturesDataFile\" doesn't exist.\n";
-			exit(1);
-		}
-	}
-	elsif ($enforceFeatureManager)
-	{
-	    print "Error: no feature data file or pre-built feature data file is provided!";
-	    exit(1);
-	}
-}
-my ($fromABI,$toABI) = split / /,$abiDowngrade;
-
-#----------------------------------------------------------------------------------
-# Problem suppression phase
-#
-# Downgrade files which don't exist for the ABI (if a downgrade path is specified)
-# Comment out missing files or report errors if strict option enabled
-#
-# Detect any references to Feature Variant binaries and substitute in the
-# correct source binary name using the VMAP file mechanism.
-
-sub suppress_phase
-{
-	undef @newobydata;
-	Plat_Init($PerlLibPath);
-
-	# use the "default" feature variant by default.
-	my $varname = $featureVariant{'VALID'} ? $featureVariant{'NAME'} : "default";
-
-	foreach $line (@obydata)
-	{
-		track_source($line);
-		if ($line =~ /^\s*REM/i)
-		{
-			# ignore REM statements, to avoid processing "REM data=xxx yyy"
-		}
-		# 
-		# thing=some\file 
-		#
-		elsif ($line =~ /(\S+)\s*=\s*"?(\S+\\\S+)"?/)
-		{
-			my $what = $1;
-			my $filename = $2;
-			if ($line =~ /(\S+)\s*=\s*"([^"]+)"/)
-			{
-				$filename = $2;
-			}
-			my $normedFilename = &Genutl_NormaliseVersionedName($filename);
-
-			# find all the alternative file locations
-			my @alternatives = fallback($normedFilename);
-			# test the original location first
-			unshift(@alternatives, $normedFilename);
-
-			# choose the first file location that actually exists
-			my $fileExists = 0;
-			foreach my $altFile (@alternatives)
-			{
-			    my $tmpPath;
-			    my $tmpFile;
-				if($altFile =~ /"?(.*\\arm\w+_?\w+)\\([^"]+)/i)
-				{
-					$tmpPath = $1;
-					$tmpFile = $2;
-				}
-				$tmpPath .= "\.$varname";
-				if (-d $tmpPath){
-				  if (-e $tmpPath ."\\$tmpFile"){
-				   $fileExists = $tmpPath . "\\$tmpFile";
-				  }
-				  elsif (-e $altFile){
-				   $fileExists = $altFile;
-				  }
-				}
-				else {
-				  $fileExists = featurevariantmap->Find($altFile, $varname);
-				}
-				last if $fileExists;
-			}
-
-			# edit the OBY line to use the actual file name which we found.
-			# (maybe) warn if an alternative to the original was selected.
-			if ($fileExists)
-			{
-				my $from = $filename;
-				$from =~ s/\\/\\\\/g;		# need to escape backslashes
-				$from =~ s/(\[|\])/\\$1/g;	# need to escape square brackets for file names like "featreg.cfg[x-y]",etc.
-				my $into = $fileExists;
-
- 				$line =~ s/$from/$into/;
-
- 				if ($warnSelection && ($fileExists ne $normedFilename))
-				{
-			    	print "replaced $filename with $fileExists\n";
-				}
-			}
-			else
-			{
-   				# No suitable alternative was found, so comment out the line unless
-				# it is a manatory ROMBUILD keyword, in which case it is better
-				# to let ROMBUILD report the missing file rather than report the
-				# missing keyword.
-   				if ($what !~ /^bootbinary|variant|primary|secondary|hide/i)
-				{
-   					$line = "REM MISSING " . $line;
-   					print_source_error("Missing file: '$filename' in statement '$what='");
-					print "\ttried @alternatives\n"  if ($opt_v && @alternatives > 1);
-   					# treat as an error if the strict option is selected.
-   					$errors++ if ($strict);
-				}
-			}
-
-			# Once the binary is located in the appropriate ABI directory (e.g.,following the binary 
-			# selection order), check if the binary has been used in a patch dll statement. This is
-			# required to find out the source file. In ABIv1, the source file is required to find the
-			# .map file, while, in ABIv2, the destination file gives the dso file name.
-			if($line =~ /(\S+)\s*=\s*(\S+)\s+(\S+)\s*(.*)?/)
-			{
-				my $aSrcfile = $2;
-				my $dstFile = $3;
-				my $dstPath = "";
-
-				if($aSrcfile =~ /"?([^"]+)/){
-				$aSrcfile = $1;
-				}
-
-				$aSrcfile = &Genutl_NormaliseVersionedName($aSrcfile);
-				if($dstFile =~ /"?(.*)\\([^"]+)/)
-				{
-					$dstPath = $1;
-					$dstFile = $2;
-				}
-				my $dllMapKey = lc ($dstFile);
-				if(exists $DllDataMap{$dllMapKey}) {
-					my $dllSymInfo = \%{$DllDataMap{$dllMapKey}};
-					$dllSymInfo->{srcfile} = $aSrcfile;
-					$dllSymInfo->{dstpath} = $dstPath;
-				}
-			}
-
-		}
-		push @newobydata, $line;
-	}
-	@obydata = @newobydata;
-	dump_obydata("tmp7.oby", "result of problem-suppression phase") if ($opt_v);
-	die "ERROR: $errors missing file(s) detected\n" if ($strict && $errors );
-}
-
-# Remove leading and trailing whitespaces from a list of strings or a single string
-sub trim 
-{
-	my @out = @_;
-	for (@out) {
-		s/^\s+//;
-		s/\s+$//;
-	}
-	return wantarray ? @out : $out[0];
-}
-
-# Generate a list of alternative locations for the given filename
-sub fallback
-{
-   	my $file = shift;
-   	my @alternatives = CheckCustomization($file);
- 
- 	# If BINARY_SELECTION_ORDER macro is specified in the oby file
- 	if ($binarySelectionOrderFlag)
-   	{
- 		# Search in the specified binary order 
- 		if(!defined(@Global_PlatList))
-		{
-			@Global_PlatList = Plat_List();
-		}
- 		my $b;
- 		my $e;
- 		foreach my $plat (@Global_PlatList) 
-  		{
-  			if ($file =~ /^(.*)\\$plat\\(.*)$/i) 
-  			{
-  				$b = $1;
-  				$e = $2;
- 				last;
- 			}
- 		}
- 		push(@alternatives, "$b\\$firstDIR\\$e");
- 			
- 		foreach my $toDIR (@binarySelectionOrder)
-   		{
- 			push(@alternatives, "$b\\$toDIR\\$e");
-   		}
-   	}
-  	
- 	# If the file is not found in the specified ABIV2 platform, then select from ARMV5 directory.
- 	# This is necessary as some of the runtime DLLs will be present only in ARMV5 directory. 
-	# Add the BPABI Platforms to be added
-	if(!defined(@Global_BPABIPlats))
-	{
-		@Global_BPABIPlats = &BPABIutl_Plat_List;
-	}
-
- 	foreach my $BpabiPlat (@Global_BPABIPlats)
- 	{
- 		if ($fromABI eq "" && $file =~ /^(.*)\\$BpabiPlat\\(.*)$/)
-   		{
- 			push(@alternatives, "$1\\armv5\\$2");
-   		}
-   	}
-
-	if ($customizedPlat && $fromABI eq "" && $file =~ /^(.*)\\$customizedPlat\\(.*)$/)
-	{
-		my $b = $1;
-		my $e = $2;
-		# if platform customization 
-		my $rootPlat = Plat_Root($customizedPlat);		
-        
-   		#Check in ARMV7 folder for binaries in case GCCEV7 is used [DEF128457 ]
-   		if($customizedPlat == "GCCEV7")
-   		{
-   			push(@alternatives,"$b\\armv7\\$e");
-   		}
-
-		if( grep /$rootPlat/, @Global_BPABIPlats)
-		{
- 			push(@alternatives, "$b\\armv5\\$e");
-		}
-	}
-
-	if ($fromABI eq "" && $file =~ /^(.*)\\ARMV5_ABIV1\\(.*)$/i)
-   	{
- 		push(@alternatives, "$1\\armv5\\$2");
-   	}
-  		
-   	if ($fromABI ne "" && $file =~ /^(.*)\\$fromABI\\(.*)$/)
-	{
- 		push(@alternatives, "$1\\$toABI\\$2");
-	}
-   
-   	return @alternatives;
-}
-
-# Generate a list of alternative locations for the given filename which
-# result from the possible platform customizations.
-sub CheckCustomization
-{
- 	my $file = shift;
- 	my @alternatives;
-	$customizedPlat = undef;	# global (used in feedback)
-
- 	if(!defined(@Global_PlatList))
-	{
-		@Global_PlatList = Plat_List();
-	}
- 	foreach my $plat (@Global_PlatList) 
-	{
- 		if ($file =~ /^(.*)\\$plat\\(.*)$/i) 
-		{
- 			my $b = $1;
- 			my $e = $2;
- 			my $root = Plat_Customizes($plat);
- 			if ($root) 
-			{
-				# Preserve the plat that is customized
-				$customizedPlat = $plat;
-
-				# If a BSF platform customizes another BSF platform (i.e. a
-				# BSF hierarchy exists), look for the file starting from the
-				# child BSF platform and working back to the root BSF platform
-				while ($root)
-				{
-					push(@alternatives, "$b\\$root\\$e");
-
-					# Temporary special case for ARMV5_ABIV1 and ARMV5_ABIV2
-					if ($root =~ /^armv5_abiv[12]$/i)
-					{
-						push(@alternatives, "$b\\armv5\\$e");
- 					}
-
-					$root = Plat_Customizes($root);
-				}
- 			}
-			return @alternatives;
- 		}
- 	}
-	return @alternatives;
-}		
-   
-#----------------------------------------------------------------------------------
-# Bitmap and aif conversion phase
-#
-# Convert any "bitmap=" or "compressed-bitmap=" files into ROM format bitmaps
-# Convert any "auto-bitmap=" to handle bitmap appropriately for xip and non-xip images
-# Convert "aif=" files appropriately for xip and non-xip images
-sub bitmap_aif_converison_phase
-{
-	my $is_xip=1;
-	undef @newobydata;
-	foreach $line (@obydata)
-	{
-		track_source($line);
-		# keep track of the XIP-ness of this rom partition
-		if ($line =~ /^\s*REM ROM_IMAGE\[(\d+)\]\s+(.*)$/i)
-		{ $is_xip=$romimage[$1]{xip}; }
-		#
-		# aif=source dest 
-		# include aif file - use XIP version for XIP roms if it exists, otherwise use the file specified
-		#
-		if ($line =~ /^\s*aif=/i)
-		{
-			my $xip="_xip";
-			my @aif= split(/\s+/,$line);
-			my $path=Path_Split('Path',"$aif[0]");
-			my $base=Path_Split('Base',"$aif[0]");
-			$path =~ s/^....//;
-			my $ext=Path_Split('Ext',"$aif[0]");
-			if ($is_xip && (-e "$path$base$xip$ext"))
-			{ $line="data=$path$base$xip$ext\t\t$aif[1]\n"; }
-			else
-			{ $line="data=$path$base$ext\t\t$aif[1]\n"; }
-		}
-		#
-		# auto-bitmap=
-		#
-		# if currently in XIP image, then use a compressed-bitmap
-		# otherwise use a RAM format bitmap
-		#
-		if ($line =~ /^\s*auto-bitmap=/i)
-		{
-			if ($is_xip)
-			{ $line =~ s/auto-bitmap=/compressed-bitmap=/i }
-			else
-			{ $line =~ s/auto-bitmap=/data=/i }
-		}
-		#
-		# uncompressed-bitmap
-		#
-		# this is currently just a synonym for 'bitmap'
-		$line =~ s/uncompressed-bitmap=/bitmap=/i;
-	
-		# 
-		# bitmap=source dest 
-		#
-		if ($line =~ /^\s*bitmap=\s*"?(\S+)"?\s+"?(\S+)"?/i)
-		{
-			my $mbm = $1;
-			my $dest = $2;
-			my $rom_mbm = "$1_rom";
-			if ($is_xip eq 0)
-			{
-				# non-XIP rom - just include the mbm file
-				$line = "data=\"$mbm\"\t\"$dest\"\n";
-			}
-			else
-			{	
-		        if (! -e $rom_mbm || -M $rom_mbm >= -M $mbm)
-			    {
-				    system "bmconv /q /r $rom_mbm /m$mbm";
-				    my $bmconv_status = $?;
-				    die "* bmconv failed\n" if ($bmconv_status != 0 || !-f $rom_mbm);
-			    }
-				$line = "data=\"$rom_mbm\"\t\"$dest\"\n";
-				push @tempfiles, $rom_mbm;
-			}
-		}
-		#
-		# compressed-bitmap=
-		#
-		# if file is a compressed ROM image file
-		elsif ($line =~ /^\s*compressed-bitmap=\s*"?(\S+)"?\s+"?(\S+)"?/i)
-		{
-			my $mbm = $1;
-			my $dest = $2;
-			my $cmprssd_rom_mbm = "$1_rom";
-			if ($is_xip eq 0)
-			{
-				# non-XIP rom - just include the mbm file
-				$line = "data=\"$mbm\"\t\"$dest\"\n";
-			}
-			else
-			{
-				if (! -e $cmprssd_rom_mbm || -M $cmprssd_rom_mbm >= -M $mbm)
-			    {
-				    system "bmconv /q /s $cmprssd_rom_mbm /m$mbm";
-				    my $bmconv_status = $?;
-				    die "* bmconv failed\n" if ($bmconv_status != 0 || !-f $cmprssd_rom_mbm);
-				}
-				$line = "data=\"$cmprssd_rom_mbm\"\t\"$dest\"\n";
-				push @tempfiles, $cmprssd_rom_mbm;			    
-			}
-		}
-		push @newobydata, $line;
-	}
-	@obydata = @newobydata;
-	dump_obydata("tmp8.oby", "result of bitmap conversion phase") if ($opt_v);
-}
-
-
-sub reformat_line($)
-{
-	my ($line) = @_;
-	my $type = "";
-	my $variant = "";
-	my $pcfile = "";
-	my $romfile = "";
-	my $tail = "";
-	
-	# time=21/07/1999 12:00:00
-	# primary[0x09080004]   =\epoc32\release\misa\udeb\ekern.exe
-	# data=\epoc32\wins\C\System\Alarms\churchbell.snd    "System\Alarms\Church bell"
-	# file[0x07060001]=\epoc32\release\MAWD\urel\cAkyb1.dll          System\Libs\EKeyb.dll
-	# file=\epoc32\release\marm\urel\eikcore.dll 			System\Libs\Eikcore.dll
-	# alias \System\Bin\DRTRVCT2_2.dll 			\System\Bin\DRTRVCT2_1.dll
-	#
-	if ($line =~ /^\s*TIME\s*=\s*/i)
-	{
-		return $line;
-	}
-  	elsif($line =~ /^\s*volume\s*=.*/i)
-  	{
-  		return $line;		
-  	}
-	elsif($line =~ /^\s*kerneltrace\s*=.*/i)
-	{
-		return $line;
-	}
-	if ($line =~ /^\s*(\S+)\s*=\s*(\S+)\s+"\\?(.*)"(.*)$/)
-	{
-		$type = $1;
-		$variant = "";
-		$pcfile = $2;
-		$romfile = $3;
-		$tail = $4;
-	}
-	elsif ($line =~ /^\s*(\S+)(\[\S+\])\s*=\s*(\S+)\s+\\?(\S+)(.*)$/)
-	{
-		$type = $1;
-		$variant = $2;
-		$pcfile = $3;
-		$romfile = $4;
-		$tail = $5;
-	}
-	elsif ($line =~ /(\S+)\s*=\s*"([^"]+)"\s+"\\?(.*)"(.*)$/)
-	{
-		if ($line !~ /^REM MISSING/i)
-		{
-			$type = $1;
-			$variant = "";
-			$pcfile = "\"$2\"";
-			$romfile = $3;
-			$tail = $4;
-		}
-		else{
-			return $line;
-		}
-	}
-	elsif ($line =~ /^\s*(\S+)\s*=\s*(\S+)\s+\\?(\S+)(.*)$/)
-	{
-		$type = $1;
-		$variant = "";
-		$pcfile = $2;
-		$romfile = $3;
-		$tail = $4;
-	}
-	elsif($line =~ /^\s*(patchdata)\s*(\S+)\s*\@\s*(\S+)\s+(\S+)/i)
-	{
-		# Reformat the patchdata statement
-		my $romfilename = $2;
-		my $patchdlldatamap_key = lc ($romfilename);
-		my $symbolname = $3;
-		my $value = $4;
-		my ($index, $elementSize);		# For when the symbol is an array, and we're patching one element
-		my $scalarSize;
-		
-		if(!defined $DllDataMap{$patchdlldatamap_key}->{dstpath}){
-			print_source_error(" File $romfilename has not been included into ROM image");
-			$errors++ if($strict);
-			$line = "REM $line\n";
-			return $line;
-		}
-	
-		if ($enforceSysBin)
-		{
-			if ($DllDataMap{$patchdlldatamap_key}->{dstpath} !~ /^sys\\bin/i 
-			 && $DllDataMap{$patchdlldatamap_key}->{dstpath} !~ /^sys\/bin/i)
-			{
-				$DllDataMap{$patchdlldatamap_key}->{dstpath} = "sys\\bin";
-			}
-		}
-		
-		my $dllfile = $DllDataMap{$patchdlldatamap_key}->{dstpath} . "\\". $romfilename;
-		
-		$line = "$1  ";
-		$line .= "$dllfile ";
- 
-		# Convert value into decimal (used to be done in AddDllDataInfo, but that limited us to
-		# one value per symbol, and we now support patching arrays, e.g. the Hal's InitialValue[],
-		# so we can't do it that way any more.)
-		if ($value =~ /^0x([0-9a-f]+)$/i) {
-			$value = hex($1);
-		}
-		elsif ($value =~ /^(-?\d+)$/) {
-			$value = $1;
-		}
-		else {
-			print_source_error("Attempt to set $symbolname to illegal value $value");
-			$errors++ if($strict);
-			$line = "REM $line\n";
-			return $line;
-		}
-
-		if ($symbolname =~ s/:(\d+)\[((0x)?[0-9a-f]+)\]$//i) {
-			($index, $elementSize) = ($2, $1);
-			$index = hex($index) if $index =~ /^0x/i;
-		}
-
-		my $DllSymInfoRef = $DllDataMap{$patchdlldatamap_key}->{$symbolname};
- 
-		if (!defined($DllSymInfoRef->{size})) {
-			print_source_error("Size for symbol $symbolname not found");
-			$errors++ if($strict);
-			$line = "REM $line\n";
-			return $line;
-		}
-
-		if (defined($elementSize)) {
-			$scalarSize = $elementSize / 8;
-			if ($scalarSize != 1 && $scalarSize != 2 && $scalarSize != 4) {
-				print_source_error("Invalid bit size $elementSize for array $symbolname in $romfilename");
-				$errors++ if($strict);
-				$line = "REM $line\n";
-				return $line;
-			}
-			if (($index + 1) * $scalarSize > $DllSymInfoRef->{size}) {
-				print_source_error("Invalid index $index into array $symbolname in $romfilename");
-				$errors++ if($strict);
-				$line = "REM $line\n";
-				return $line;
-			}
-		} else {
-			$scalarSize = $DllSymInfoRef->{size};
-		}
-
-		my $max_value = 0xffffffff;
-
-		if ($scalarSize == 1) {
-			$max_value = 0xff;
-		}
-		elsif ($scalarSize == 2) {
-			$max_value = 0xffff;
-		}
-
-		if ($value > $max_value) {
-			$value &= $max_value;
-			print "$DllSymInfoRef->{obyfilename}($DllSymInfoRef->{lineno}): Warning:Value overflow of $symbolname\n";
-			$errors++ if($strict);
-		}
-
-		if(defined $DllSymInfoRef->{ordinal}) {
-			if (defined($elementSize)) {
-				my $ord = $DllSymInfoRef->{ordinal};
-				my $offset = $index * $scalarSize;
-				$line .= "ordinal $ord+$offset ";
-			} else {
-				$line .= "ordinal ";
-				$line .= $DllSymInfoRef->{ordinal} . " ";
-			}
-		}
-		elsif(defined $DllSymInfoRef->{dataAddr}) {
-			if (defined($elementSize)) {
-				my $addr = $DllSymInfoRef->{dataAddr};
-				$addr = hex($addr) if $addr =~ /^0x/i;
-				$addr = sprintf("0x%08x", $addr + $index * $scalarSize);
-				$line .= "addr $addr ";
-			} else {
-				$line .= "addr ";
-				$line .= $DllSymInfoRef->{dataAddr} . " ";
-			}
-		}
-		else
-		{
-			print_source_error("Ordinal or Address for exported symbol $symbolname in $romfilename couldn't be located");
-			$errors++ if($strict);
-			$line = "REM $line\n";
-			return $line;
-		};
-		
-		$line .= "$scalarSize $value\n";
-
-		return $line;
-	}
-	elsif ($line =~ /^\s*(\S+)\s*(\S+)\s+\\?(\S+)(.*)$/)
-	{
-		$type = $1;
-		$variant = "";
-		$pcfile = $2;
-		$romfile = $3;
-		$tail = $4;
-
-		if ($type !~ /^(alias)$/i)
-		{
-			# Return now, if it is not an 'alias'.
-			return $line;
-		}
-		else
-		{
-			# There is no substitution needed for SysBin 'alias'es.
-			if ($romfile =~ /^sys\\bin\\/i
-			  ||$romfile =~ /^sys\/bin/i)
-			{
-				return $line;
-			}
-		}
-	}
-	else
-	{
-		return $line;
-	}
- 	# Buildrom should generate warning when destination path provided for a file 
- 	# is not a standard path(as per platsec) and "PlatSecEnforceSysBin" is turned off. 
- 	my $warnFlag = 1;
-	my $mustBeSysBin = $enforceSysBin;
-	if ($type =~ /^(data|compress|nocompress)$/i
-		&& $romfile !~ /^system\\(bin|libs|programs)\\/i)
-	{
-		$mustBeSysBin = 0;
- 		$warnFlag = 0;
-	}
-	
-	if ($mustBeSysBin)
-	{
-		if ($type =~ /^(alias)$/i
-			&& $romfile !~ /^sys\\bin\\/i
-			&& $romfile !~ /^sys\/bin/i)
-		{
-			# for multilinguify 'alias'es (generally resource files) 'MustBeSysBin' should not be enforced.
-			if(defined($multiLinguifyAlias{$pcfile})) {
-				return $line;  
-			}
-
-			my $filename = "\\$romfile";	# in case no path is specified
-			$filename = substr $filename, rindex($filename, "\\");
-			$romfile = "sys\\bin".$filename;
-
-			if ($pcfile !~ /^sys\\bin\\/i
-			    && $pcfile !~ /^sys\/bin/i)
-			{
-				my $pcfilename = "\\$pcfile";	# in case no path is specified
-				$pcfilename = substr $pcfilename, rindex($pcfilename, "\\");
-				$pcfile = "sys\\bin".$pcfilename;
-			}
-			return "$type$variant $pcfile \t$romfile$tail\n";
-		}
-
-		if ($romfile !~ /^sys\\bin\\/i
-		    && $romfile !~ /^sys\/bin/i)
-		{
-			my $filename = "\\$romfile";	# in case no path is specified
-			$filename = substr $filename, rindex($filename, "\\");
-			$romfile = "sys\\bin".$filename;
-		}
-	}
-	else
-	{
- 		if ($warnFlag && $romfile !~ /^sys\\bin\\/i && $romfile !~ /^sys\/bin/i)
- 		{
- 			print "Warning: Outside standard path at \"$line\"\n";
- 		}
-		if ($type =~ /^(alias)$/i)
-		{
-			# Return the line as it is for non-MustBeSysBin 'alias'es.
-			return $line;
-		}
-	}
-	$romfiles{$romfile} = $variant.$pcfile;
-	return "$type$variant=$pcfile \t\"$romfile\"$tail\n";
-}
-
-my @hidearray;
-
-sub mark
-{ # function to mark files in ROMs as hidden
-	my ($base,$ext) = @_;
-	my $i=0;
-	my @coreimagerange = (-1,-1); #coreimagerange stores the places within @hidearray where the $base files start and end
-	my @extensionimagerange = (-1,-1); #extensionimagerange stores the places within @hidearray where the $ext files start and end
-	for(my $i=0;$i<scalar @hidearray;$i++) { #loop sets values in @coreimagerange and in @extensionimagerange
-		if($hidearray[$i]{rom}==$base) {
-			if($coreimagerange[0]<0) {
-				$coreimagerange[0]=$i;
-				$coreimagerange[1]=$i;
-			} else {
-				$coreimagerange[1]=$i;
-			}
-		} elsif($hidearray[$i]{rom}==$ext) {
-			if($extensionimagerange[0]<0) {
-				$extensionimagerange[0]=$i;
-				$extensionimagerange[1]=$i;
-			} else {
-				$extensionimagerange[1]=$i;
-			}
-		}
-	}
-	
-	for(my $i=$extensionimagerange[0];$i<=$extensionimagerange[1];$i++) { #loop marks files which need to be hidden based on the values in @coreimagerange and in @extensionimagerange
-		for(my $j=$coreimagerange[0];$j<=$coreimagerange[1];$j++) {
-			if($hidearray[$i]{dest} eq $hidearray[$j]{dest}) {
-				$hidearray[$i]{hide}=1;
-			}
-		}
-	}
-}
-
-
-#----------------------------------------------------------------------------------
-# Cleaning phase
-#
-# Remove "REM defined", "REM handled"
-# Remove the "# lineno" information
-# Collapse multiple blank lines
-# Apply the PlatSecEnforceSysBin setting
-# Produce ROM directory listing
-# Identify the ROM image name
-sub cleaning_phase
-{	
-	my $romname;
-	my $skippingBlanks=0;
-	undef @newobydata;
-	
-    if($opt_v)
-    {
-	  my $logWin = "logwin.oby";
-	  my $logLinux = "loglinux.oby";
-	  unlink($logWin);
-	  unlink($logLinux);
-	  open LOGWIN, ">$logWin" or die("* Can't create $logWin\n");
-	  open LOGLINUX, ">$logLinux" or die("* Can't create $logLinux\n");
-    }	
-
-	foreach $line (@obydata)
-	{
-		track_source($line);
-		if ($line=~/^REM (defined|handled)/)
-		{
-			next;
-		}
-		if ($line=~/^# (\d+) "(.*)"/)
-		{
-			next;
-		}
-		#
-		# Blank line compression
-		#
-		if ($line=~/^\s*$/)
-		{
-			if ($skippingBlanks==1)
-			{
-				next;
-			}
-			$skippingBlanks=1;
-		}
-		else
-		{
-			$skippingBlanks=0;
-		}
-		#
-		# Track ROMNAME, allowing overrides
-		#
-		if ($line=~/romname\s*=\s*"?(\S+)\.(\S+)"?\s*/i)
-		{
-			if ($romname ne "" && $opt_o eq "")
-			{
-				print_source_error("Overrides previous ROM name $romname");
-			}
-			$rombasename = $1;
-			$romname = "$1.$2";
-			next;
-		}
-		#
-		# ROM directory listing
-		#
-		    my $newline = reformat_line($line);
-	    if( ($newline !~ /^\s*TIME\s*=\s*/i)
-  	      &&($newline !~ /^\s*volume\s*=.*/i)
-	      &&($newline !~ /^\s*kerneltrace\s*=.*/i))
-	    {
-	        my $tmpline = $newline;
-	        if($^O =~ /^MSWin32$/i)
-	        {
-	          $newline =~ s-\/-\\-go;
-	          if($opt_v)
-	          {
-                print LOGWIN $newline;
-	            $tmpline =~ s-\\-\/-go;
-	            print LOGLINUX $tmpline;
-	          }
-	        }else #unix os
-	        {
-	          $newline =~ s-\\-\/-go;
-	          if($opt_v)
-	          {
-	            print LOGLINUX $newline;
-	            $tmpline =~ s-\/-\\-go;
-	            print LOGWIN $tmpline;
-	          }
-	        }
-	    }
-	    
-		push @newobydata, $newline;
-	}
-	if($opt_v)
-	{
-	  close LOGWIN;
-	  close LOGLINUX;
-	}
-	
-	exit(1) if($errors && $strict);
-
-	# Handle ROMNAME and possible -o override
-	if ($opt_o ne "")
-	{
-		$romname=$opt_o;
-		if ($opt_o=~/(\S+)\.(\S+)/)
-		{
-			$rombasename=$1;
-		}
-		else
-		{
-			$rombasename=$romname;
-		}
-	}
-	if(!$onlysmrimage)
-	{
-		unshift @newobydata, "romname=$romname\n";	# first line of final OBY file
-	}
-	@obydata = @newobydata;
-	
-	print "* Removing previous image and logs...\n";
-	unlink glob("$rombasename.*");
-	
-	my $obyrecordline;
-	if($createspi) {# section added to mark SPI files in core images as hidden (if appropriate) if extension ROMs are being produced
-		my $imagenum=0;
-		my $count=0;
-		foreach my $line (@obydata) { # fill @hidearray with all file= or data= entries from @obydata, recording which image they are in and their target destination
-			if($line =~/^\s*(file|data)\s*=\s*(\S+)\s+(\S+)\s*$/gi) {
-				$hidearray[$count] = {rom=>$imagenum, type=>$1, dest=>$3};
-				$hidearray[$count]{dest} =~s/\"//g;
-				$count++;
-			} elsif($line =~/^\s*REM\s+ROM_IMAGE\[(\d)\]\s*$/i ) {
-				$imagenum=$1;
-			}
-		}
-		for(my $i=0;$i<8;$i++) { #loop to mark files in @hidearray as hidden, does not add the hide= lines to the obey files
-			if($romimage[$i]{extension}) {
-				mark($i-1,$i);
-			}
-		}
-		undef @newobydata;
-	
-		my $hideflag=0; # is set to 1 if there are files which need to be hidden, determines whether to run next section of code 
-		for(my $i=0;$i<scalar @hidearray;$i++) {
-			if($hidearray[$i]{hide}==1) {
-				$hideflag=1;
-			}
-		}
-	
-		my $obeyrom=0;	
-		if($hideflag) { #if there exist files which need hiding
-			my $i=0;
-			my $exitflag=0;
-			$obyrecordline=0;
-			for(;$obyrecordline<scalar @obydata && !$exitflag;) { # nested for loops produce new obey file in @newobydata, including hide= lines
-				print "Line = $obyrecordline $i " . scalar @hidearray . "\n";
-				if($i==scalar @hidearray) {
-					$exitflag=1;
-				}
-				for(;$i<scalar @hidearray;$i++) {
-					if($hidearray[$i]{hide}==1) {
-						my $rom=$hidearray[$i]{rom};
-						my $destination=$hidearray[$i]{dest};
-						while($obeyrom<$rom && $obyrecordline<scalar @obydata) { #pushes lines to @newobydata until specified rom is reached
-							push @newobydata, $obydata[$obyrecordline];
-							if($obydata[$obyrecordline] =~/^\s*REM\s+ROM_IMAGE\[(\d)\]\s*$/i){
-								$obeyrom=$1;
-							}
-							$obyrecordline++;
-						}
-						my $flag=1; #get to here when $obeyrom==$rom
-						while($flag && $obyrecordline<scalar @obydata) {
-							$destination=~s|\\|/|g;
-							my $obyline=$obydata[$obyrecordline];
-							$obyline=~s|\\|/|g;			
-							if($obyline=~m/$destination/) { # if the line in the obeyfile matches the destination of the specified spi file then a hide= line is added before the spi file's data= line
-								push @newobydata, "hide=$hidearray[$i]{dest}\n$obydata[$obyrecordline]";
-								$obyrecordline++;
-								$flag=0;
-							} else {
-								push @newobydata, $obydata[$obyrecordline++];
-							}
-						}
-					}
-				}
-			}		
-		}		
-		while($obyrecordline< scalar @obydata) { # add the rest of the lines from @obydata to @newobydata
-			push @newobydata, $obydata[$obyrecordline++];
-		}
-		@obydata=@newobydata;
-		undef @newobydata;	
-	}
-	dump_obydata("tmp9.oby", "result of cleaning phase") if ($opt_v);
-}
-
-
-#----------------------------------------------------------------------------------
-#
-# Divide the oby file into multiple sections - one for each rom image - ready
-# for the appropriate rom builder.
-#
-
-sub generate_romheader
-{
-	my ($idx) = @_;
-	if ($romimage[$idx]{xip} ne 0)
-	{ 
-		my $header = "\n";
-		if ($romimage[$idx]{extension})
-		{
-			$header = "extensionrom=$rombasename.$romimage[$idx]{name}.img\n";
-			$header .= "romsize=$romimage[$idx]{size}\n\n";
-		}
-		return $header; 
-	}
-	# non-xip
-	my $header;
-	if ($romimage[$idx]{extension})
-	{
-		$header =  "extensionrofs=$rombasename.$romimage[$idx]{name}.img\n";
-		$header .= "rofssize=$romimage[$idx]{size}\n\n";
-	}
-	else
-	{
-		$header="rofsname=$rombasename.$romimage[$idx]{name}.img\n";
-		$header .= "rofssize=$romimage[$idx]{size}\n\n";
-	}
-	return $header;
-}
-
-#----------------------------------------------------------------------------------
-# Dump OBY file.
-#
-# Creates final OBY file.
-#
-sub create_dumpfile
-{
-	my $romimageidx;
-	my $smrimageidx = 0;
-	my $dumpfile="$rombasename";
-	$romimage[0]{obeyfile}=$dumpfile;
-	$dumpfile .= ".oby";
-	unlink($dumpfile);
-	if($rombasename && !$onlysmrimage)
-	{
-		open DUMPFILE, ">$dumpfile" or die("* Can't create $dumpfile\n");
-		print "* Writing $dumpfile - final OBY file\n";
-		$romimageidx=0;
-		print DUMPFILE generate_romheader($romimageidx);
-	}
-	foreach $line (@obydata)
-	{
-		if ($line =~ /^\s*REM ROM_IMAGE\[(\d+)\]\s+(.*)$/i)
-		{
-			$romimageidx=$1;
-			if ($romimage[$romimageidx]{extension} eq '0')
-			{ # next rom oby file
-				close DUMPFILE;
-				$dumpfile="$rombasename.$romimage[$romimageidx]{name}";
-				$romimage[$romimageidx]{obeyfile}=$dumpfile;
-				$dumpfile .= ".oby";
-				open DUMPFILE, ">$dumpfile" or die("* Can't create $dumpfile\n");		
-				print "* Writing $dumpfile - final OBY file\n";
-				# header
-				print DUMPFILE $line;
-				print DUMPFILE generate_romheader($romimageidx);
-				next;
-			}
-			else
-			{ # extension
-				# header
-				print DUMPFILE $line;
-				print DUMPFILE generate_romheader($romimageidx);
-				next;
-			}
-		}
-		# write data drive oby file.
-		elsif ($line =~ /^\s*REM DATA_IMAGE\[(\d+)\]\s+(.*)$/i)
-		{
-				my $dataimageidx=$1;
-				close DUMPFILE;
-				$dumpfile="$datadriveimage[$dataimageidx]{name}";
-				$datadriveimage[$dataimageidx]{obeyfile}=$dumpfile;
-				$dumpfile .= ".oby";
-				open DUMPFILE, ">$dumpfile" or die("* Can't create $dumpfile\n");		
-				print "* Writing $dumpfile - intermediate OBY file\n";
-				# header
-				print DUMPFILE $line;
-				print DUMPFILE generate_datadriveheader($dataimageidx,\@datadriveimage);
-				push(@dataDriveFileList,$dumpfile);
-				next;
-		}
-		elsif ($line =~ /^\s*REM SMR_IMAGE\s*$/i)
-		{
-			close DUMPFILE;
-			$dumpfile = $obeyFileList[$smrimageidx];
-			$smrimageidx++;
-			$dumpfile .= ".oby";
-			open DUMPFILE, ">$dumpfile" or die("* Can't create $dumpfile\n");
-			print "*Writing $dumpfile - intermediate OBY file\n";
-			print DUMPFILE $line;
-			push(@smrImageFileList, $dumpfile);
-			next;
-		}
-		print DUMPFILE $line;
-	}
-	close DUMPFILE;
-}
-
-#----------------------------------------------------------------------------------
-#
-# Full ROM directory listing - use case-insensitive sort
-#
-sub create_dirlisting
-{
-	if($rombasename)
-	{
-		print "* Writing $rombasename.dir - ROM directory listing\n";
-		open DIRFILE, ">$rombasename.dir" or die("* Can't create ROM directory listing\n");
-	
-		my $file;
-		my $prevdir = "";
-		foreach $file (sort {uc($a) cmp uc($b)} keys %romfiles)
-		{
-			my $dir = substr $file,0,rindex($file, "\\");
-			if (uc $dir ne uc $prevdir)
-			{
-				$prevdir = $dir;
-				print DIRFILE "\n";
-			}
-	
-			my @sources = split /\n/,$romfiles{$file};
-			printf DIRFILE "%-40s\t%s\n", $file, shift @sources;
-			while (@sources)
-			{
-				printf DIRFILE "%39s+\t%s\n", "", shift @sources;
-			}
-		}
-		close DIRFILE;
-	}
-}
-
-#----------------------------------------------------------------------------------
-#
-# Suppress Rom/Rofs/DataDrive Image creation if "-noimage" option is provided.
-#
-
-sub suppress_image_generation
-{
-	if($noimage) 
-	{
-		&tidy_exit;		
-	}
-}
-
-#----------------------------------------------------------------------------------
-# Execute rombuild & maksym for each final XIP OBY file
-# Execute rofsbuild for each non-XIP oby file
-#
-
-sub run_rombuilder
-{
-	my ($command, $obeyfile, $logfile) = @_;
-	$command .= " $obeyfile.oby";
-	#CR1258 test cases are depending on the following output.
-	print "* Executing $command\n" if ($opt_v);
-
-	open DATA, "$command 2>&1 |"   or die "Couldn't execute command: $command";
-	while ( defined( my $line = <DATA> ) ) {
-	chomp($line);
-	print "$line\n";
-	}
-	close DATA;
-
-	if ($? != 0)
-	{
-		$errors++;
-		$command =~ /^\s*(\S+)\s+-slog/;
-		print "* $1 failed\n";
-	}
-	else
-	{
-		push(@romImages,$obeyfile.".img");
-	}
-	print "\n";
-	rename "$logfile","$obeyfile.log" or die("* Can't rename $logfile\n");
-	exit(1) if ($errors);
-}
-
-#----------------------------------------------------------------------------------
-# ROMBUILD AND ROFSBUILD
-#
-# Invokes rombuild and rofsbuild.
-# Creates .log, .symbol files.
-#
-sub invoke_rombuild
-{
-	#For CR1258, -compress command line option is introduced, and it's being handled as following
-	my $rom_compression_type;
-	if($opt_compression_type eq ALLSECTIONS)
-	{
-		$rom_compression_type = "-compress";
-	}
-	elsif($opt_compression_type eq PAGEDSECTION)
-	{
-		$rom_compression_type = "-compress=paged";
-	}
-	elsif($opt_compression_type eq UNPAGEDSECTION)
-	{
-		$rom_compression_type = "-compress=unpaged";
-	}
-	else
-	{
-		$rom_compression_type = "";
-	}
-	
-	my $rombuild;
-	if(!$geninc)
-	{
-		$rombuild = "rombuild -slog $rom_compression_type $logLevel $lowMem $opt_fastcompress $opt_jobs";
-	}
-	else
-	{
-		$rombuild = "rombuild -slog $rom_compression_type -geninc $logLevel $lowMem $opt_fastcompress $opt_jobs";
-	}
-	if($gendep)
-	{
-		$rombuild .= " -gendep";
-	}
-	my $rofsbuild = "rofsbuild -slog $logLevel $lowMem $opt_fastcompress $opt_jobs";
-	foreach my $arg (keys %rombuildOptions)
-	{
-		$rombuild .= " $arg";
-	}
-	        
-	for (my $romidx=0; $romidx<8; $romidx++)
-	{
-		my $obeyfile=$romimage[$romidx]{obeyfile};
-		my $xip=$romimage[$romidx]{xip};
-		my $compress=$romimage[$romidx]{compress};
-		my $uncompress=$romimage[$romidx]{uncompress};
-		if ($obeyfile)
-		{
-			if(!defined $opt_compression)
-			{
-				if ($compress ne 0)
-				{
-					$compress=" -compress";
-				}
-				elsif($uncompress ne 0)
-				{
-					$compress=" -uncompress";
-				}
- 				elsif($compress eq 0)
- 				{
- 					$compress=" ";
-				}
-			}
-			else
-			{
-				$compress = $opt_compression;
-				$compress =~m/\s-(compression)(method)\s(none|inflate|bytepair)/;
-				print "* ".$1." ".$2.": ".$3;
-			}                        
-			if ($xip)
-			{
-				run_rombuilder($rombuild.$compress, $obeyfile, "ROMBUILD.LOG");
-				if(!$nosymbols){
-				print "* Writing $obeyfile.symbol - ROM symbol file\n";
-				print "* Executing maksym $obeyfile.log $obeyfile.symbol\n" if ($opt_v);
-				system("maksym $obeyfile.log $obeyfile.symbol >maksym.out");
-				exit(1) if (!-e "$obeyfile.symbol");
-				}
-			}
-			else
-			{
-				# efficient_rom_paging.pm can move everything to core rom.
-				# If that is the case, don't run rofsbuild at all to avoid errors.
-				use constant TRUE => 1;
-				use constant FALSE => 0;
-				my $run_rofs_build = FALSE;
-				
-				open OBYFILE, "$obeyfile.oby";
-				for (<OBYFILE>)
-				{
-					if (is_oby_statement($_))
-					{
-						$run_rofs_build = TRUE;
-						last;
-					}
-				}
-				close OBYFILE;
-				if ($run_rofs_build)
-				{
-					run_rombuilder($rofsbuild.$compress, $obeyfile, "ROFSBUILD.LOG");
-					if(!$nosymbols){
-					print "* Writing $obeyfile.symbol - ROFS symbol file\n";
-					print "* Executing maksymrofs $obeyfile.log $obeyfile.symbol\n" if ($opt_v);
-					system("maksymrofs $obeyfile.log $obeyfile.symbol >maksym.out");
-					exit(1) if (!-e "$obeyfile.symbol" );
-					}			
-				}
-			}
-			unlink "rombuild.log";
-			unlink "maksym.out";
-		}
-	}
-}
-
-#-------------------------------------------------------
-# Subroutine: check if current statement is a valid oby statement
-#
-sub is_oby_statement
-{
-	my ($li) = @_;
-	if ($li =~ /\s*data\s*=/) { return 1;}
-	if ($li =~ /\s*file\s*=/) { return 1;}
-	if ($li =~ /\s*dll\s*=/) { return 1;}
-	if ($li =~ /\s*secondary\s*=/) { return 1;}
-
-	return 0;
-}
-
-#-------------------------------------------------------
-# Subroutine: convert possibly absolute path into relative path
-#
-
-sub relative_path
-{
-    my ($arg) = @_;
-    return $arg if ($arg !~ /^\\/);	# not an absolute path
-    if ($uppath eq "x")
-	{
-		$uppath=cwd;
-		$uppath=~s-/-\\-go;		    # separator from Perl 5.005_02+ is forward slash
-		$uppath=~s-^(.*[^\\])$-$1\\-o;	    # ensure path ends with a backslash
-		$uppath=~s-\\([^\\]+)-\\..-og;	    # convert directories into ..
-		$uppath=~s-^.:\\--o;		    # remove drive letter and leading backslash
-	}
-    $arg=~s-^\\--o;	# remove leading backslash from original path
-    return "$uppath$arg";
-}
-
-# Returns the global @obydata reference to support external tool invocation.
-sub getOBYDataRef{
-	return \@obydata;
-}
-
-#Match the blank or the comment
-sub isobystatement
-{
-	my ($l) = @_;
-	if ($l !~ /=/) { 
-		return 0;
-	}
-	return 1;
-}
-
-#Match the data statements
-sub isdatastatement {
-	my ($l) = @_;
-	if ($l !~ /data=/) 
-	{ 
-		return 0;
-	}
-	return 1;
-}
-
-#Match the spidata statements
-sub isspidatastatement {
-	my ($l) = @_;
-	if ($l !~ /spidata=/) { 
-		return 0;
-	}
-	return 1;
-}
-
-#Match the executable statements
-sub isexecutablefile {
-	my ($l) = @_;
-	if (($l=~/file=/)||($l=~/dll=/)||($l=~/primary=/)||($l=~/secondary=/)||($l=~/variant=/)||($l=~/device=/)||($l=~/extension=/)){ 
-		return 1;
-	}
-	return 0;
-}
-
-#Match the directory metadata statements
-sub isdirectorymetadata {
-	my ($l) = @_;
-	if (($l=~/hide=/) || ($l=~/rename=/) || ($l=~/alias=/)){ 
-		return 1;
-	}
-	return 0;
-}
-
-#Match the bitmap statements
-sub isbitmap {
-	my ($l) = @_;
-	if ($l=~/bitmap=/){ 
-		return 1;
-	}
-	return 0;
-}
-
-
-#Match the aif file
-sub isaif {
-	my ($l) = @_;
-	if ($l=~/(.*)\.aif/){ 
-		return 1;
-	}
-	return 0;
-}
-
-
-#Match the resource file
-sub isresource {
-	my ($l) = @_;
-	if ($l=~/(.*)\.rsc/){ 
-		return 1;
-	}
-	return 0;
-}
-
-#Returns the executable extensions
-sub executableextension {
-	my ($l) = @_;
-	if ($l=~/file=(.*)\.exe$/){ 
-		return "exe";
-	}
-	elsif ($l=~/file=(.*)\.dll$/){ 
-		return "dll";
-	}
-	elsif ($l=~/file=(.*)\.ldd$/){ 
-		return "ldd";
-	}
-	elsif ($l=~/file=(.*)\.fsy$/){ 
-		return "fsy";
-	}
-}
-
-
-#Returns all 3 UIDS
-sub executabletype {
-	my ($l) = @_;
-	my $uid1;
-	my $uid2;
-	my $uid3;
-	if ($l=~/uid1\s(0x[\d]*)/){ 
-		$uid1=$1;
-	}
-	if ($l=~/uid2\s(0x[\d]*)/){ 
-		$uid2=$1;
-	}
-	if ($l=~/uid3\s(0x[\d]*)/){ 
-		$uid3=$1;
-	}
-	
-	return $uid1." ".$uid2." ".$uid3."\n";
-}
-
-
-#Return source file name
-sub getSourceFile {
-	my ($line) = shift;
-	if ($line=~/(\w*=)(\S*\s+\S*)\s+(\S*)\s+(\S*)?/) {
-		return $2;
-	}
-}
-
-#Return destination file name
-sub getDestFile{
-	my ($line) = shift;
-	if ($line=~/(\w*=)(\S*\s+\S*)\s+(\S*)\s+(\S*)?/) {
-		return $3;
-	}
-}
-
-#Return the obycommand attributes
-sub getOBYAttributes{
-	my ($line) = shift;
-	if ($line=~/(\w*=)(\S*\s+\S*)\s+(\S*)\s+(\S*)?/) {
-		return $4;
-	}
-}
-
-#Return the hardware variant delimiter
-sub getHardwareVariant{
-	my ($line) = shift;
-	if ($line=~/(\w*[0x[\d]*]=)/) {
-		return $1;
-	}
-}
-
-#Return the hardware variant delimiter
-sub getObyCommand{
-	my ($line) = shift;
-	if ($line=~/^[data=]/) {
-		return "data";
-	}
-
-	if ($line=~/^[file=]/) {
-		return "file";
-	}
-
-	if ($line=~/^[dll=]/) {
-		return "dll";
-	}
-}
-
-# Initialize the symbol info within the given DLL.
-sub AddDllDataInfo
-{
-	my ($line) = @_;
-	# syntax "<DLLname>@<symbolname> <newvalue>"
-	if($line =~ /^\s*(\S+)\s*\@\s*(\S+)\s+(\S+)\s*$/)
-	{
-		my $dllName = lc ($1);
-		my $symbolname = $2;
-		my $intVal = $3;
-		my $newVal = 0;
-		if($intVal =~ /^0x([0-9a-fA-F]+)$/){
-		$newVal = hex($1);
-		}
-		elsif($intVal =~ /^(-\d+)$/ or $intVal =~ /^(\d+)$/){		
-			$newVal = $1;
-		}
-		else{
- 			print "ERROR: Invalid patchable value at \"$line\"\n";
- 			$errors++ if($strict);
- 			return 1;
-		}
-		$symbolname =~ s/:(\d+)\[(0x)?[0-9a-f]+\]$//i;	# Remove array element specification (:ELEMENT_BIT_SIZE[INDEX]) to get symbol name
-
-		my $DllMapRef = \%{$DllDataMap{$dllName}};
-
-		my %DllSymInfo = ();
-		$DllSymInfo{ordinal}	= undef;
-		$DllSymInfo{dataAddr}	= undef;
-		$DllSymInfo{size}		= undef;
-		# We don't store the value here, since patchdata can be used on an array,
-		# in which case we'll create another one of these, and lose the value.
-		# Instead, the value is retrieved by re-parsing the command line later.
-		$DllSymInfo{lineno}		= $sourceline;
-		$DllSymInfo{obyfilename}= $sourcefile;
-
-		$DllMapRef->{$symbolname} = \%DllSymInfo;
-		return 0;
-	}
-		return 1;
-}
-
-sub process_dlldata
-{
-	if(!$patchDataStmtFlag){
-		return;
-	}
-	my $symbolTblEntry;
-
-	foreach my $dll (keys %DllDataMap){
-		my $DllMapRef = $DllDataMap{$dll};
-		if(!$DllMapRef->{srcfile}){
-		next;
-		}
-		my $aDllFile = $DllMapRef->{srcfile};
-		my $SymbolCount = scalar ( keys %{$DllMapRef}) - 2; #The map has 'srcfile' and 'dstpath' special keys besides the symbols.
-
-		my $DllSymMapRef;
-
-		my @BPABIPlats = &BPABIutl_Plat_List;
-		my $matchedSymbols = 0;
-		my $globalSyms = 0;
-		my @platlist = &Plat_List();
-		my $platName;
-		my $rootPlatName;
-		my $plat = "ARMV5";				
-		$plat = &Variant_GetMacro() ? $plat."_ABIV1" : $plat."_ABIV2";		
-
-		foreach my $plat(@platlist) 
-		{
-			if(($aDllFile =~ /\\($plat)\\/i) or ($aDllFile =~ /\\($plat\.\w+)\\/i ))
-			{
-				$platName = $1;
-				last;
-			}
-		}		
-		$rootPlatName =	&Plat_Customizes($platName) ? &Plat_Root($platName) : $platName;
-		
-		# Map files will be referred for all ARM platforms, 
-		# and for BSF platforms which cutomizes ARM platforms.
-		if($rootPlatName =~ /^ARMV5|$plat$/i){
-			my $mapfile = "${aDllFile}.map";
-			
-			open MAPFILE, "$mapfile" or die "Can't open $mapfile\n";
-			while(<MAPFILE>){
-			my $line = $_;
-
-				#Ignore Local symbols.
-				if(!$globalSyms){
-					if($line =~ /Global Symbols/){
-						$globalSyms = 1;
-						next;
-					}
-					else{
-						next;
-					}
-				}
-
-				$symbolTblEntry = $line;
-				if($symbolTblEntry =~ /\s*(\S+)(?:\s+\(EXPORTED\))?\s+(\S+)\s+(\S+)\s+(\S+)\s+(.*)/){
-					my $symbol		= $1;
-					my $symbolValue = $2;
-					my $data		= $3;
-					my $symbolSz	= $4;
-					if(!exists $DllMapRef->{$symbol}){
-						next;
-					}
-					$DllSymMapRef = $DllMapRef->{$symbol};
-					if($data =~ /Data/){
-					# Valid
-					}
-					else {
-					#	Invalid to patch a code symbol.
-						print( "$DllSymMapRef->{obyfilename}($DllSymMapRef->{lineno}): Warning: $symbol is not a data Symbol.Ignoring patch statement.\n");
-						$errors++ if($strict);
-						$DllMapRef->{$symbol} = undef;
-						next;
-					}
-
-					
-					# Record the address and the size of the symbol.
-					$DllSymMapRef->{dataAddr} = $symbolValue;
-					$DllSymMapRef->{size} = $symbolSz;
-
-					$matchedSymbols++;
-					if( $matchedSymbols >= $SymbolCount){
-						last;
-					}
-				}
-			}
-			close MAPFILE;
-		}
-		# DSO files will be referred for BPABI platforms(excluding ARM platforms),
-		# and for BSF platforms which cutomizes BPABI platforms.
-		else {
-			my $abiDir = undef;
-			foreach my $bpabi (@BPABIPlats){
-				if($rootPlatName =~ /^$bpabi$/i){
-					$abiDir = $platName;
-					last;
-				}
-			}
-
-			if(!defined $abiDir){
-				print("Can't locate the map or proxy dso file for $aDllFile\n");
-				$errors++ if($strict);
-				next; #go to the next patch dll data statement
-			}
-			if( $aDllFile =~ /(.*)\.[^.]+$/ ){
-				my $proxydsofile = "$1.dso";
-				$proxydsofile =~ s/$abiDir\\(.*)\\/ARMV5\\LIB\\/ig;
-				open PIPE, "getexports -d $proxydsofile|" or die "Can't open file $proxydsofile\n";
-				while (<PIPE>){
-					my $line = $_;
-					if($line =~ /\s*(\S+)\s+(\d+)\s+((\S+)\s+(\d+))?/){
-						my $symbol = $1;
-						my $ordinal = $2;
-						my $data = $3;
-						my $symbolSz = $5;
-
-						if(!$data){
-							next;
-						}
-						if(!exists $DllMapRef->{$symbol}){
-							next;
-						}
-
-						$DllSymMapRef = $DllMapRef->{$symbol};
-
-						# Record the ordinal and the size of the symbol.
-						$DllSymMapRef->{ordinal} = $ordinal;
-						$DllSymMapRef->{size} = $symbolSz;
-						$matchedSymbols++;
-						if( $matchedSymbols >= $SymbolCount){
-						last;
-						}
-					}
-				}
-
-				close PIPE;
-			}
-		}
-	}
-	exit(1) if ($errors && $strict ) ;
-}
-
-# make sure that all the absolute feature variant paths include a
-# drive letter. This is required because cpp will not work with
-# absolute paths starting with slashes.
-sub addDrivesToFeatureVariantPaths
-{
-	return unless $featureVariant{'VALID'};
-
-	my $current = cwd();
-	my $drive = $1 if ($current =~ /^(.:)/);
-
-	# pre-include file
-	my $HRH = $featureVariant{'VARIANT_HRH'};
-	$featureVariant{'VARIANT_HRH'} = $drive . $HRH if ($HRH =~ /^[\\\/]/);
-
-	# ROM include path
-	my $dirRef = $featureVariant{'ROM_INCLUDES'};
-	return unless $dirRef;
-	my $i = 0;
-
-	foreach my $dir (@$dirRef)
-	{
-		$$dirRef[$i] = $drive . $dir if ($dir =~ /^[\\\/]/);
-		$i++;
-	}
-}
-sub create_smrimage
-{
-	if($needSmrImage)
-	{
-		foreach my $oby (@obeyFileList)
-		{
-			my $command = "rofsbuild -slog -smr=$oby.oby";
-			print "* Executing $command\n" if($opt_v);
-			system($command);
-			if($? != 0)
-			{
-				print("* ROFSBUILD failed to generate SMR IMAGE\n") if($opt_v);
-			}
-			else
-			{
-				push(@smrImageFileList, $oby.".img");
-			}
-		}
-	}
-	if(@smrImageFileList)
-	{
-		print "\n";
-		print "-------------------------------------------------------\n";
-		print "| List of file(s) generated pertaining to SMR image |\n";
-		print "-------------------------------------------------------\n";
-		my $arraySize = scalar(@smrImageFileList);
-		for(my $i=0; $i < $arraySize; $i++)
-		{
-			my $element = shift(@smrImageFileList);
-			my $size = -s $element;
-			print "Size = ".$size." bytes"."\t"."File = ".$element."\n";
-		}
-	}
-	foreach my $errSmr (keys(%smrNameInfo))
-	{
-		if($smrNameInfo{$errSmr} > 1)
-		{
-			print "\n SMR image: $errSmr.img creating error for duplicated names!\n";
-		}
-	}
-	if($smrNoImageName)
-	{
-		print "\n SMR image creating error for empty image name!\n";
-	}
-}
-
-1;
+#
+# Copyright (c) 2006-2010 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+# This package is to build rom image
+#
+
+package buildrom;
+
+require Exporter;
+@ISA=qw(Exporter);
+@EXPORT=qw(
+	image_content_processing_phase
+	process_cmdline_arguments
+	preprocessing_phase
+	substitution_phase
+	reorganize_phase
+	plugin_phase
+	multlinguify_phase
+	spi_creation_phase
+	suppress_phase
+	bitmap_aif_converison_phase
+	cleaning_phase
+	create_dumpfile
+	create_dirlisting
+	suppress_image_generation
+	invoke_rombuild
+	getOBYDataRef
+	isobystatement
+	isdatastatement
+	isspidatastatement
+	isexecutablefile
+	isdirectorymetadata
+	isbitmap
+	isaif
+	isresource
+	hardwarevariant
+	executableextension
+	executabletype
+	getSourceFile
+	getDestFile
+	getOBYAttributes
+	getHardwareVariant
+	getObyCommand
+	process_dlldata
+	featurefile_creation_phase
+	processData
+	create_smrimage
+);
+
+my $useinterpretsis = 1;
+if ($^O !~ /^MSWin32$/i){
+	$useinterpretsis = 0;
+}
+my $enforceFeatureManager = 0; # Flag to make Feature Manager mandatory if SYMBIAN_FEATURE_MANAGER macro is defined. 
+
+my $BuildromMajorVersion = 3 ;
+my $BuildromMinorVersion = 26;
+my $BuildromPatchVersion = 0;
+
+
+sub print_usage
+{
+
+	# Option "-fm" will be supported instead of option "-f|fr" if SYMBIAN_FEATURE_MANAGER macro is defined.
+	my $featuresOptionUsage = "-ffeatureuids or -fr=featureuids -- feature registry database XML file name";
+	if ($enforceFeatureManager) 
+	{
+		$featuresOptionUsage = "-fm=featuredatabasefile          -- feature manager/feature registry database XML file name.\n".
+							   "\t\t\t\t    Multiple XML files can be passed seperated by commas.\n".
+							   "   -nofm=featuresdatafile           -- don't generate features data file.".
+							   " Instead use pre-built features data file.";
+	}
+
+#........1.........2.........3.........4.........5.........6.........7.....
+	print <<USAGE_EOF;
+
+BUILDROM - ROM configuration tool V$BuildromMajorVersion.$BuildromMinorVersion.$BuildromPatchVersion
+
+Usage:
+  buildrom [options] obyfile [obyfile2 ...]   
+
+Build a ROM according to the specification defined by concatenating the
+specified obyfiles.
+
+The initial specification is modified by C++ preprocessor directives,
+and subsequently adjusted by statements in the ROM specification language.
+The final specification is in the subset of the specification language
+which is understood directly by ROMBUILD.
+
+Each obyfile parameter specifies a file via a search path: if the
+filename is not matched then buildrom will look in \/epoc32\/rom\/include.
+
+Buildrom invokes ROMBUILD to generate the ROM image, and produces a
+number of related files such as the ROM symbol file. The name of the
+image file is specified directly by the -o option, or determined by 
+scanning the final specification for the "romname" keyword. If there is 
+more than one "romname" statement, the last one takes precedence.
+
+The available options are
+
+   -Dxxx                            -- C++ preprocessor arguments
+   -oimagename                      -- ROM image name, overriding any ROMNAME statement
+   -s                               -- strict option, any missing files will stop buildrom 
+   -p                               -- preserves the intermediate files pertaining to data drive, Z drive and BMCONV
+   -spi                             -- enable producing SPI files
+   -spiplacement                    -- enable positioning of spi file
+   -w                               -- warn if file has been selected from a different directory 
+   $featuresOptionUsage
+   -etool                           -- external tool specification (xx is tool's perl module)
+   -compress                        -- compression type of ROM image:
+                                       -compress compress whole ROM image.
+                                       -compress=paged compress paged section in the ROM image only.
+                                       -compress=unpaged compress unpaged section in the ROM image only. 
+   -ccomprmethod                    -- compression method: none|inflate|bytepair
+   -geninc                          -- generate INC file
+   -gendep                          -- generate dependence graph for rom image
+   -nosymbols                       -- disable creation of symbol file
+   -noimage                         -- disable creation of ROM/ROFS/DataDrive Image
+   -j<digit>                        -- do the main job with <digit> threads
+   -cache                           -- allow the ROFSBUILD to reuse/generate cached executable files
+   -nocache                         -- force the ROFSBUILD not to reuse/generate cached executable files
+   -cleancache                      -- permanently remove all cached executable files
+   -loglevel<level>                 -- Level of information logging where loglevel is 0,1,2
+                                       0 default level of information
+                                       1 host/ROM filenames, file size and the hidden attribute along with level0 log
+                                       2 E32 file header attributes along with level1 log
+   -z=xxx or -zdrivepath=xxx        -- specify a location to create Z drive directory. 
+   -d=xxx or -datadrivepath=xxx     -- specify a location to create data drive directory.
+   -k or -keepgoing                 -- enable keepgoing,continue to create the data drive image even
+                                    if the non-sis, sis or zdrive image file(s) are missing or corrupt; create rom/rofs
+									image even some oby files missing and/or duplicated definitions in oby files .
+   -r or -retainfolder              -- enable retainfolder,would retain pre-existence of z & data drive folder. 
+   -zdriveimage=xxx                 -- specify Z drive image (ROM, CORE, ROFS or Ext-ROFS image).
+   -pfile=xxx                       -- specify a parameter file for interpretsis to take additional parameters.
+   -argforinterpretsis=xxx          -- specify command line argument(s) for interpretsis which will override the 
+                                    parameter file contents.
+   -l=xxx or -logimagecontents=xxx  -- extract all stub-sis and SWI certificate store file(s) only 
+                                    and log all the file(s) that are part of the Z drive image on to a log file.  
+   -I<directory>                    -- Use <directory> for the referenced IBY/OBY files
+   -argfile=xxx                     -- specify argument-file name containing list of command-line arguments to buildrom   
+   -lowmem                          -- use memory-mapped file for image build to reduce physical memory consumption   
+   -checkcase                       -- check character case of path/name in oby/iby files, 
+                                    the result will be checkcase.log, this option is only valid on windows.
+   -workdir=xxx                     -- specify a directory to contain generated files.   
+
+Popular -D defines to use include
+
+   -D_DEBUG         -- select debug versions of some files
+   -D_FULL_DEBUG    -- select debug versions of all files
+   -D_ARM4          -- specify the target platform
+
+   -D_EABI=xxxx     -- specify target for all files (e.g. armv5)
+   -D_KABI=xxxx     -- specify the target platform for the Kernel (e.g. armv5)
+
+Other defines may be useful for particular OBY files.
+
+USAGE_EOF
+}
+
+use strict;
+use romutl;
+use romosvariant;
+
+my $PerlEPOCPath = &get_epocroot()."epoc32\/tools\/";   # fully qualified pathname of the directory containing EPOC Perl modules
+
+sub ExportDirs ($);
+
+my $xmlrequired = 0; # assume xml required is false. Used to determine if xml
+                     # modules should be loaded.
+
+use flexmodload;	     # To load modules dynamically
+
+# Work out the relative path to the epoc32 directory
+use spitool qw(&createSpi);
+use Cwd;
+use externaltools; 	#To invoke External Tools
+use File::Basename;
+
+my @tempfiles;  	
+my $preserve = 0; 	#flag to indicate if temporary files should be preserved
+my $uppath="x";	    	# will be initialised when first needed
+
+my $epocroot = &get_epocroot;
+
+my @obyfiles;
+my $cppargs = "-nostdinc -undef";
+my $opt_v = 0;
+my $opt_o = "";
+my $strict = 0;
+my $warnSelection = 0; # default is not warn about selecting files from 
+		       # different directories when the file is missing from
+		       # the specified directory
+
+my $createspi = 0; # don't create SPI files by default
+my $spiset=0;
+my $spiplacement = 0; # enable the placement of spi file
+my %spipositionflag = (); # map of Image index at which the keyword SPI_POSITION is used.
+
+use constant NONE => 0;
+use constant INFLATE => 1;
+use constant BYTEPAIR => 2;
+my $opt_compression;  # Default compression method parameter undefined
+
+use constant UNCOMPRESSED   => 0;        # Indicates the ROM image will not be compressed.
+use constant ALLSECTIONS    => 1;        # Indicates both paged section and unpaged section will be compressed.
+use constant PAGEDSECTION   => 2;        # Indicates only paged section will be compressed.
+use constant UNPAGEDSECTION => 3;        # Indicates only unpaged section will be compressed.
+my $opt_compression_type = UNCOMPRESSED; # Leave the ROM image uncompressed by default.
+
+#Variables to store cache command line options
+my $opt_cache      = 0;
+my $opt_nocache    = 0;
+my $opt_cleancache = 0;
+
+my $thisdir=cwd;
+$thisdir=~s-\\-\/-go;		    # separator from Perl 5.005_02+ is forward slash
+$thisdir.= "\/" unless $thisdir =~ /\/$/;
+$thisdir =~ s-\/-\\-g if (&is_windows);
+
+my $rominclude = $epocroot."epoc32\/rom\/include\/";
+$rominclude = &get_epocdrive().$rominclude unless $rominclude =~ /^.:/;
+$rominclude =~s-\\-\/-g;
+
+my %plugintypes; #hash of plugin types and their SPI files' destinations in ROM
+$plugintypes{"ECOM"} = "\/private\/10009d8f\/"; #ECOM SPI files' destination in ROM image
+
+my @obydata;
+my @newobydata;
+my %substitutionData;
+my @substitutionOrder;
+my %languageCodes;
+my $defaultLanguageCode;
+my %multiLinguifyAlias;  # to by-pass the 'mustbesysbin' option for multilinguify 'alias'es. 
+my $abiDowngrade = "";
+my @binarySelectionOrder;
+my $fromDIR;
+my %rombuildOptions = ("-type-safe-link" => 1 );
+my $enforceSysBin = 0;
+
+my $line;
+my $errors = 0;
+my @romimage;
+my $rombasename;
+
+my $sourcefile;
+my $sourceline;
+#my $line;
+my %romfiles;
+
+# To handle BINARY_SELECTION_ORDER macro.
+my $firstDIR;
+my $binarySelectionOrderFlag = 0;
+
+my %DllDataMap = ();	#Map to keep track of DLL Data patch statements.
+my $patchDataStmtFlag = 0;
+
+my $featuremanager = 0; #Flag to enable support for feature manager database XML file and to generate  
+			# features data file.
+my $noFeatureManager = 0; # Flag to stop the generation of features.dat file and use pre-built features.dat if provided.
+my $preBuiltFeaturesDataFile  = ''; # To store the name of pre-built features.dat file provided with "-nofm" option.
+
+#Image Content XML file that supports specific feature to be added
+my $image_content = undef;
+#Feature list XML file that acts as database containing all features details
+my $featureXml = undef;
+my $geninc = "";
+my $gendep = "";
+my $nosymbols = "";
+my $noimage = "";
+my $customizedPlat = undef;
+my $opt_jobs= "";
+
+#Summary of files(both executables and data files) currently includes 
+#	host and ROM file names, 
+#	size of the file in ROM
+#	whether the file is hidden
+# This option is added so that the above additional information is emitted by rombuild/rofsbuild tools
+# only when supplied with this option so that the existing tools don't get affected.
+my $logLevel="";
+
+# This option is used to pass -lowmem argument to rombuild/rofsbuild tools
+my $lowMem="";
+
+# Feature Variation modules and data
+my %featureVariant;
+
+# global variables specific to data drive image generation. 
+use File::Path;					# Module to provide functions to remove or create directories in a convenient way.
+use File::Copy;					# Module to provide functions to copy file(s) from source to destination.
+use File::Find;
+use datadriveimage;				# module which provides all necessary functions to create data drive image.
+my $ZDirloc = "";				# location of Z drive directory.
+my $DataDriveDirloc = "";		# location of data drive directory.
+my @sisfilelist;				# an array to hold sis file(s).
+my @zDriveImageList;			# an array to hold z drive image name.
+my @datadiveobydata;			# an array to hold data drive oby data.
+my @datadriveimage;				# array which holds data drive image attribute.
+my $rootdir = "";				# which holds root directory information.
+my @datadrivedata;				# array to maintain list of lines taken from processed data drive oby file.
+my @nonsisFilelist;				# array to maintain list of nonsis file(s). 
+my @sisobydata;					# array to maintain all list of files(s) got by installing sis files. 
+my @renameList;					# array to maintain list of file(s) that has to be renamed.
+my @aliaslist;					# array to maintain list of file(s) that has to be made alias.
+my @hideList;					# array to maintain list of file(s) that has to be made hidden.
+my $sisfilepresent = 0;			# enable if sis file(s) are present.
+my $stubsisfilepresent = 0;		# enable if stub-sis file(s) are present.
+my $opt_k = 0;					# enable if keepgoing option is specified by the user.
+my $opt_r = 0;					# enable if retain pre-existence of folder is specified by the user.
+my $dataImageCount = 0;			# no of data drive image that has to generated.
+my @zdriveImageName;			# list of Z drive image name(s) specified using zdriveimagename in oby/iby file.
+my $opt_zimage = 0;				# enable if z drive image is found.
+my $zDrivePresent = 0;			# flag to check whether Z drive needs to be created.
+my @dataDriveFileList;			# list of processed data drive related files.
+my $paraFile = undef;			# parameter file for interpretsis.
+my @romImages;					# list of generated z drive image(s)(rom/rofs). 
+my $imageEntryLogFile = undef;	# a log file to log all the z drive image contents.
+my $opt_logFile = 0;			# enable if z drive entries has to be logged on to a log file.
+my %dataIndexHash = ();			# a hash which holds key-value pair between datadrive index and datadrive image count.
+my $interpretsisOpt = undef;	# enable if command line arguments are specified by the user to INTERPRETSIS.
+my @interpretsisOptList;		# an array which holds all the list of option(s) that needs to passed to INTERPRETSIS. 
+my @Global_BPABIPlats;
+my @Global_PlatList;
+my @smrImageFileList;
+my $needSmrImage = 0;
+my %smrPartitions;
+my %smrNameInfo;
+my @obeyFileList;
+my $smrNoImageName = 0;
+my $onlysmrimage = 1;
+my $checkcase = 0;
+my $checkcase_platform = "";
+my $checkcase_test = 0;
+my $opt_workdir = 0;
+
+sub match_obyfile
+{
+	my ($obyfile) = @_;
+	if (-f $obyfile)
+	{
+		push @obyfiles, $obyfile;
+		return 1;
+	}
+
+	# search for the oby file in the list of include directories
+	my @otherDirs = ($rominclude);
+
+	if ($featureVariant{'VALID'})
+	{
+		my $dirRef = $featureVariant{'ROM_INCLUDES'};
+
+		@otherDirs = @$dirRef if ($dirRef);
+	}
+	foreach my $dir (@otherDirs)
+	{
+		print "$dir/$obyfile\n" if ($opt_v);
+		if (-f "$dir/$obyfile")
+		{
+		    push @obyfiles, "$dir/$obyfile";
+		    return 1;
+		}
+	}
+	return 0;
+}
+
+
+# This function invokes ROFSBUILD tool with appropriate parameters to generate data drive image.
+# It also deletes zdrive and datadrive folder after all the image has been processed and generated
+# if and only if preserve(-p) option is disabled.
+sub create_datadriveImage
+{
+	for (my $dataidx=0; $dataidx < $dataImageCount; $dataidx++)
+	{
+		my $driveIndex = $dataIndexHash{$dataidx};
+
+		if(defined($driveIndex))
+		{
+			my $obeyfile=$datadriveimage[$driveIndex]{obeyfile};
+			my $compress=$datadriveimage[$driveIndex]{compress};
+			my $uncompress=$datadriveimage[$driveIndex]{uncompress};
+
+			if ($obeyfile)
+			{
+				if(!defined $opt_compression)
+				{
+					if ($compress ne 0)
+					{
+						$compress=" -compress";
+					}
+					elsif($uncompress ne 0)
+					{
+						$compress=" -uncompress";
+					}
+					elsif($compress eq 0)
+					{
+						$compress=" ";
+					}
+				}
+				else
+				{
+					$compress = $opt_compression;
+					$compress =~m/\s-(compression)(method)\s(none|inflate|bytepair)/;
+					print "* ".$1." ".$2.": ".$3;
+				}
+				my $command = "rofsbuild -slog".$compress." -datadrive=$obeyfile.oby";
+				print "* Executing $command\n" if ($opt_v);
+				system($command);
+				if ($? != 0)
+				{
+					&datadriveimage::reportError("* ROFSBUILD failed to generate data drive image",$opt_k);
+				}
+				else
+				{
+					push(@dataDriveFileList,$obeyfile.".img");
+				}
+			}
+		}
+	}
+	# after processing all the data drive image(s) delete zdrive and datadrive directory 
+	# if and only if preserve(-p) option is disabled.
+	if($dataImageCount)
+	{
+		# delete Z drive directory if and only if preserve(-p) option is disabled.
+		my $retVal = &deleteDirectory($ZDirloc,$opt_v)if(!($preserve));
+		if($retVal)
+		{
+			&datadriveimage::reportError("* Warning could not delete $ZDirloc",$opt_k);
+		}
+		# delete data drive directory if and only if preserve(-p) option is disabled.
+		$retVal = &deleteDirectory($DataDriveDirloc,$opt_v)if(!($preserve));
+		if($retVal)
+		{
+			&datadriveimage::reportError("* Warning could not delete $DataDriveDirloc",$opt_k);
+		}
+		# reset image count to zero.
+		$dataImageCount = 0;
+		# reset z drive present to zero.
+		$zDrivePresent = 0;
+	}
+}
+
+sub tidy_exit
+{
+	#-------------------------------------------------------
+	# Tidy and exit
+	
+	if (!$preserve)
+	{
+	    foreach my $tempfiles (@tempfiles)
+	    {
+	    print "remove $tempfiles\n" if ($opt_v);
+			unlink "$tempfiles";
+	    }
+	}
+	if($rombasename)
+	{
+		system("dir $rombasename.*");
+	}
+	if(@dataDriveFileList)
+	{
+		print "\n";
+		print " ----------------------------------------------------------\n";
+		print "| List of file(s) generated pertaining to data drive image |\n";
+		print " ----------------------------------------------------------\n";
+		my $arraySize = scalar(@dataDriveFileList);
+		for( my $i=0; $i < $arraySize; $i++ )
+		{
+			# remove the first element from an array and return it 
+			my $element = shift(@dataDriveFileList);
+			# get the size of the file.
+			my $size = -s $element;
+			print "Size = ".$size." bytes"."\t"."File = ".$element."\n";
+		}
+	}
+	exit(0);
+}
+
+# This is the main function which is responsible for processing data drive image.
+# This function internally calls other functions to create datadrive folder,zdrive folder
+# and external tools such as INTERPRETSIS, READIMAGE and finally ROFSBUILD to generate 
+# appropriate data drive image.
+sub processData		
+{
+	if($dataImageCount)
+	{
+		# set the default path for Z drive and Data drive directory,
+		# if and only if, path is not specified by the user. 
+		$ZDirloc = &datadriveimage::setPath("zdrive") unless ($ZDirloc);
+		$DataDriveDirloc = &datadriveimage::setPath("datadrive") unless ($DataDriveDirloc);
+		#delete any existing Z drive directory.
+		my $retVal = &datadriveimage::deleteDirectory($ZDirloc,$opt_v)if(!$opt_r);
+		if($retVal)
+		{
+			exit(1) if(!$opt_k);
+		}
+		# delete pre-existence of data drive folder, if and only if -r option is not enabled.
+		$retVal = &datadriveimage::deleteDirectory($DataDriveDirloc,$opt_v) if(!$opt_r);
+		if($retVal)
+		{
+			exit(1) if(!$opt_k);
+		}
+		if($opt_logFile)
+		{
+			# clean any pre-existance of log file.
+			unlink($ZDirloc."\/".$imageEntryLogFile);
+		}
+		
+		for (my $datadriveidx=0; $datadriveidx < $dataImageCount; $datadriveidx++)
+		{
+			my $driveIndex = $dataIndexHash{$datadriveidx};
+			# get the data drive name.
+			if( defined( $driveIndex ) )
+			{
+				my $datadrivename=$datadriveimage[$driveIndex]{obeyfile};
+				# get the size of the data drive.
+				my $size = $datadriveimage[$driveIndex]{size};
+				if( $datadrivename )
+				{
+					# set data drive oby file.
+					my $datadriveobyfile = $datadrivename.".oby";
+					# final location of prototype data drive.
+					my $proDataDriveDirloc;
+					# Location of stub-sis file(s) inside Z Drive folder.
+					my $zDriveSisFileLoc;
+					# check if more than one data drive image needs to be generated. 
+					if( $dataImageCount > 1 )
+					{
+						# if yes, then set the location of prototype data drive folder as 
+						# DataDriveDirloc + datadrivename
+						$proDataDriveDirloc = $DataDriveDirloc."\/".$datadrivename;
+					}
+					else
+					{
+						# else, then set the location of prototype data drive folder as DataDriveDirloc 
+						$proDataDriveDirloc = $DataDriveDirloc;
+					}
+
+					# create prototype data drive folder.
+					print "creating data drive folder\n" if ($opt_v);
+					&datadriveimage::createDirectory($proDataDriveDirloc);
+
+					# check for sis file keyword in ROM description file.
+					# if found,then locate for stub-sisfile.
+					# create Z drive( if and only if stub-sis files are present in ROM description file )
+					# and dump all the non-sis files on to the Z drive folder. 
+					if(&datadriveimage::checkForSisFile($datadriveobyfile,\@sisfilelist,\$sisfilepresent))
+					{
+						my $zDriveImagePresent = 0; # flag to check whether z drive image is Present;
+						if(&datadriveimage::checkForZDriveImageKeyword($datadriveobyfile,\@zDriveImageList,\$zDriveImagePresent) )
+						{
+							# find out size of the array
+							my $arraysize = scalar(@zDriveImageList);
+							for( my $i=0; $i < $arraysize; $i++ )
+							{
+								$zDriveSisFileLoc =  $ZDirloc."\/".$datadrivename;
+								&datadriveimage::invokeReadImage(pop(@zDriveImageList),$zDriveSisFileLoc,$opt_v,$imageEntryLogFile,$opt_k);
+							}
+						}
+						else
+						{
+							$zDriveSisFileLoc = $ZDirloc;
+							# locate and copy stub-sis file(s),for the first time.
+							if( !$zDrivePresent )
+							{
+								# check for image file.
+								if( $opt_zimage )
+								{
+									# image(s)supplied to BUILDROM(like rom,rofs,extrofs or core) using "-zdriveimage" option, 
+									# are maintained in a seperate array and the element from the array is fetched one by one and is 
+									# fed to READIMAGE as an input.
+									foreach my $element (@zdriveImageName)
+									{
+										# invoke READIMAGE to extract all /swi stub sis file(s) from the given image.
+										$zDrivePresent = &datadriveimage::invokeReadImage($element,$zDriveSisFileLoc,$opt_v,$imageEntryLogFile,$opt_k);
+									}
+								}
+								else
+								{
+									# if zdrive image(s) such as (rom,core,rofs or extrofs) are generated ealier to the data drive image processing
+									# then these images are maintained in an array and the element from the array is fetched one by one and is 
+									# fed to READIMAGE as an input.
+									foreach my $element (@romImages)
+									{
+										# invoke READIMAGE to extract all /swi stub sis file(s) from the given image.
+										$zDrivePresent = &datadriveimage::invokeReadImage($element,$zDriveSisFileLoc,$opt_v,$imageEntryLogFile,$opt_k);
+									}
+								}
+							}
+						}
+						# invoke INTERPRETSIS tool with z drive folder location.
+						if ($useinterpretsis)
+						{
+							&datadriveimage::invokeInterpretsis( \@sisfilelist,$proDataDriveDirloc,$opt_v,$zDriveSisFileLoc,$paraFile,$opt_k,\@interpretsisOptList)if($sisfilepresent);
+						}else
+						{
+							print "Warning: interpretsis is not ready on linux.\n";
+						}	
+					}
+
+					# create an oby file by traversing through upated prototype data drive directory.
+					&datadriveimage::dumpDatadriveObydata( $proDataDriveDirloc,$datadriveobyfile,$size,\@nonsisFilelist,
+										\@renameList,\@aliaslist,\@hideList,\@sisobydata,\@datadrivedata,$opt_k,$opt_v );
+					#reset sisfilepresent flag to zero;
+					$sisfilepresent =0;
+				}
+			}
+		}
+		create_datadriveImage();
+	}
+	tidy_exit;
+}
+#Parse and process image content xml file
+#Gets the oby files listed in the xml file
+# Pushes all the oby files found to an array
+
+sub image_content_processing_phase
+{
+	if(!defined ($image_content))
+	{
+		return;
+	}
+	&ImageContentHandler::ParseImageContentXML($image_content);
+	&ImageContentHandler::ProcessImageContent;
+
+	if(defined ($image_content) )
+	{
+#		Collect the oby files if any in the Image content file
+		my $files = &ImageContentHandler::GetObyFiles;
+		foreach my $obeyfile (@$files)
+		{
+			next if match_obyfile($obeyfile);
+			next if (match_obyfile("$obeyfile.oby"));
+		}
+	}
+}
+
+# Subroutine to process parameter-file
+sub parameterFileProcessor
+{
+	my $paramFile = shift(@_);	
+	my @paramFileParamaters = ();	
+
+	my $fileOpenFlag = 1;
+	open FILE,"<", $paramFile or $fileOpenFlag = 0;
+	
+	if(!$fileOpenFlag)
+	{
+		print "Error: Could not open parameter-file \"$paramFile\" for reading.\n";
+		return;
+	}
+	
+	# Parse parameter-file and collect all the parameters in an array
+	while(my $line = <FILE>)
+	{
+		# Read the line till character ';'(used for providing comments in the file) or EOL
+		$line = $1 if ($line =~ /(.*);/); 
+		
+		# Split the parameters specified in a line based on white-spaces		
+		my @paramaters = split(/(\s)/,$line);	
+		
+		my $flag = 0;
+		my $argWithQuotes='';
+
+		foreach my $value (@paramaters) 
+		{	
+			# If the parameter doesn't conatian double quotes then push it 
+			# to the list of parameters.
+			if(($value !~ /\"/) && (!$argWithQuotes)) 
+			{
+				if ($value !~ /^\s*$/) 
+				{
+					push @paramFileParamaters,$value;
+				}		
+			}
+			# If the parameter is in the form  -fm="faturedb.xml" then remove
+			# double quotes and push it to the list of parameters.
+			elsif(($value =~ /\".*\"/))
+			{
+				$value =~ s/\"//g;
+				push @paramFileParamaters,$value;
+			}
+			# If the parameter is in the form  -fm="fature  db.xml" then read
+			# the parameter starting from opening quote till the closing quote.
+			elsif( ($value =~ /\"/) && $argWithQuotes) 
+			{
+				$argWithQuotes .= $value;
+				$argWithQuotes =~ s/\"//g;
+				push @paramFileParamaters,$argWithQuotes;
+				$argWithQuotes='';		
+			}
+			else
+			{
+				$argWithQuotes .= $value;
+			}
+		}		
+	}
+
+	close FILE;	
+
+	if (!@paramFileParamaters)
+	{
+		print "Warning: No parameters specified in paramer-file \"$paramFile\".\n";		
+		return;
+	}
+	
+	my $paramFileFlag = 1;
+
+	# Invoke subroutine "process_cmdline_arguments" to process the parameters read from
+	# the parameter file.
+	&process_cmdline_arguments($paramFileFlag, @paramFileParamaters);
+
+}
+
+# Processes the command line arguments passed to buildrom tool
+
+sub process_cmdline_arguments
+{
+   	my %tmpBldRomOpts;
+
+	my ($paramFileFlag, @argList); 
+
+	if (defined @_)
+	{
+		($paramFileFlag, @argList) = @_;
+	}
+	else
+	{
+		@argList = @ARGV;
+	}
+
+	if (!defined $paramFileFlag) 
+	{
+		# Enforce Feature Manager if macro SYMBIAN_FEATURE_MANAGER is defined in the HRH file.
+		my @hrhMacros = &get_variantmacrolist;	
+		if (grep /^SYMBIAN_FEATURE_MANAGER\s*$/, @hrhMacros)
+		{
+			$enforceFeatureManager = 1;
+		}
+		
+		# Process the parameters of parameter-file if passed.
+		foreach my $arg (@argList)
+		{
+			if ($arg =~ /^-argfile=(.*)/) 
+			{
+				&parameterFileProcessor($1);				
+			}
+		}
+	}
+	# first searching argList for keepgoing option
+	foreach my $arg (@argList) {
+		if ( $arg =~ /^-k$/i || $arg =~ /^-keepgoing$/i )
+	  {
+			$opt_k = 1;		
+  		last;	
+		}
+	}
+	foreach my $arg (@argList)
+	{
+	    if ($arg =~ /^-argfile=(.*)/) 
+		{
+			&parameterFileProcessor($1) if (defined $paramFileFlag);						
+			next;			
+		}
+		if ($arg =~ /^-[DI]/)
+	    {
+		$cppargs .= " $arg";
+		#Set 'udeb' for debug option 
+		if($arg =~ /^-D_FULL_DEBUG/)
+		{
+		    $tmpBldRomOpts{"BUILD_DIR"} = "udeb";
+		}
+		#Set specific platform supplied from the command option 
+		elsif($arg =~ /^-D_PLAT=(.*)/)
+		{
+		    $tmpBldRomOpts{"ABI_DIR"} = $1;
+		}
+		# Check for a Feature Variant
+		elsif ($arg =~ /^-DFEATUREVARIANT=(.*)/)
+		{
+			my $varname = $1;
+			
+			if ($varname =~ /^\.(.*)$/)
+			{
+				# for testing, locate the VAR file in the current directory
+				%featureVariant = get_variant($1, ".");
+			}
+			else
+			{
+				%featureVariant = get_variant($varname);
+			}
+			if (!$featureVariant{'VALID'})
+			{
+			    print "FEATUREVARIANT $varname is not VALID\n";
+				$errors++;
+			}
+			if ($featureVariant{'VIRTUAL'})
+			{
+			    print "FEATUREVARIANT $varname is VIRTUAL\n";
+				$errors++;
+			}
+			addDrivesToFeatureVariantPaths();
+		}
+		next;
+	    }
+	    if ($arg =~ /^-o(.*)/i)
+	    {
+		$opt_o = $1;
+		next;
+	    }
+	    if ($arg =~ /^-j(\d+)$/i)
+	    {
+		    $opt_jobs = "-j".$1;
+		    next;
+	    }
+	    if ($arg =~ /^-v$/)
+	    {
+		$opt_v =1;
+		next;
+	    }
+	    if ($arg =~ /^-s$/)
+	    {
+		$strict = 1;
+		next;
+	    }
+	    if ($arg =~ /^-w$/)
+	    {
+		$warnSelection = 1;
+		next;
+	    }
+	    if ($arg =~ /^-p$/)
+	    {
+		$preserve = 1;
+		next;
+	    }
+	    if ($arg =~ /^-nospi$/)
+	    {
+		$createspi=0;
+		$spiset=1;
+		next;
+	    }
+	    if ($arg =~ /^-spi$/)
+	    {
+		$createspi=1;
+		$spiset=1;
+		next;
+	    }	
+	    #Process External Tool
+	    if ($arg =~/^-e(.*)/)#Match to get the tool perl module files
+	    {
+		&externaltools::loadTools($1);
+		next;
+	    }
+   		#Process imagecontent file 
+	    if( $arg =~ /^-i(.*)/)
+	    {
+# Disabling -i option
+		print "Warning: Ignoring invalid Option $arg \n";
+		next;
+	    }
+		#Process feature manager database xml file 
+	    if($arg =~ /^-fm=(.*)/)
+	    {
+			if (!$enforceFeatureManager) 
+			{
+				print "Unknown arg: $arg\n";
+				$errors++;
+				next;
+			}
+			$featureXml = $1;
+			$xmlrequired = 1;
+			$featuremanager = 1;
+			if ($featureXml =~ /^$/) 
+			{
+				print "Error: No filename specified with \"-fm=\" option.\n";
+			}			
+			next;
+	    }
+		#Process Cache command line options.
+		if($arg =~ /^-cache/)
+		{
+			$opt_cache = 1;
+			next;
+		}
+		if($arg =~ /^-nocache/)
+		{
+			$opt_nocache = 1;
+			next;
+		}
+		if($arg =~ /^-cleancache/)
+		{
+			$opt_cleancache = 1;
+			next;
+		}
+
+	    #Process ROM image compression type if it's specified through command line option.
+	    if($arg =~ /^-compress(.*)/)
+	    {
+	    	if($1 eq '')
+	    	{
+	    		$opt_compression_type = ALLSECTIONS;
+	    		print "Whole ROM image will be compressed.\n";
+	    	}
+	    	elsif($1 eq '=paged')
+	    	{
+	    		$opt_compression_type = PAGEDSECTION;
+	    		print "Paged section of the ROM image will be compressed.\n";
+	    	}
+	    	elsif($1 eq '=unpaged')
+	    	{
+	    		$opt_compression_type = UNPAGEDSECTION;
+	    		print "Unpaged section of the ROM image will be compressed.\n";
+	    	}
+	    	else
+	    	{
+	    		print "Unknown compression type: $1\n";
+	    		$errors++;
+	    	}
+	    	next;
+	    }
+		if ($arg =~ /^-nofm(=(.*))?$/)
+		{
+			if (!$enforceFeatureManager) 
+			{
+				print "Unknown arg: $arg\n";
+				$errors++;
+				next;
+			}
+   			$noFeatureManager = 1;
+            #DEF125375 If caller is simply giving -nofm without any parameter, a warning message will be given.
+            if(!$2)
+            {
+                print "Warning: No filename specified with \"-nofm=\" option, feature data file might not be included.\n";
+            }
+            else
+            {
+                $preBuiltFeaturesDataFile = $2;						
+            }
+			next;	
+		}
+		#Process feature registry database xml file 
+	    if($arg =~ /^-fr=(.*)/ || $arg =~ /^-f(.*)/)
+	    {
+			if ($enforceFeatureManager)
+			{
+				print "Error: Option \"-f|-fr\" is no longer supported.\n";
+				$errors++;
+				next;
+			}			
+			$featureXml = $1;
+			$xmlrequired = 1;			
+			if ($featureXml =~ /^$/) 
+			{
+				print "Error: No filename specified with \"-f|-fr\" option.\n";				
+			}
+			next;
+	    }
+	    if ($arg =~ /^-spiplacement$/)
+	    {
+			$spiplacement = 1;
+			next;
+	    }
+		if ($arg =~ /^-noimage$/)
+		{
+			$noimage=1;
+			next;	
+		}
+		if ($arg =~ /^-nosymbols$/)
+		{
+			$nosymbols=1;
+			next;	
+		}
+		if ($arg =~ /^-geninc$/)
+		{
+			$geninc=1;
+			next;	
+		}
+		if($arg =~ /^-gendep$/)
+		{
+			$gendep=1;
+			next;
+		}
+		if ($arg =~ /^-checkcase$/)
+		{
+			$checkcase=1;
+			next;	
+		}
+		if ($arg =~ /^-checkcase_test$/)
+		{
+			$checkcase_test=1;
+			next;	
+		}
+		if ($arg =~ /^-workdir=(.*)/)
+		{
+			my $workdir = $1;
+			if (!-d $workdir)
+			{
+				die "directory $workdir does not exist\n";
+			}
+			my $currentdir = cwd;
+			chdir "$workdir" or die "cannot change to directory $workdir\n";
+			$thisdir=cwd;
+			$thisdir=~s-\\-\/-go;		    # separator from Perl 5.005_02+ is forward slash
+			$thisdir.= "\/" unless $thisdir =~ /\/$/;
+			if(&is_windows)
+			{
+				$thisdir =~ s-\/-\\-g;
+			}
+			$opt_workdir = 1;
+			chdir "$currentdir";
+			next;	
+		}
+        if($arg =~/^-c(.*)/)
+        {
+          if($1 eq 'none' )
+          {
+              $opt_compression = " -compressionmethod none";
+          }
+          elsif($1 eq 'inflate' )
+          {
+              $opt_compression = " -compressionmethod inflate";
+          }
+          elsif($1 eq 'bytepair' )
+          {
+              $opt_compression = " -compressionmethod bytepair";
+          }
+          else
+          {
+              print "Unknown compression method: $1\n";
+              $errors++;
+          }
+          next;
+        }
+		if( $arg =~ /^-loglevel\d+$/)
+		{
+			$logLevel= $arg;
+			next;
+		}
+		# get Z directory location if specified by the user.
+		# if yes, then extract directory location from the given array element. 
+		if( $arg =~ /^-z=(.*)/  || $arg =~ /^-zdrivepath=(.*)/i )
+		{
+			# check for white space in the specified folder path
+			# if "yes" then warn the user saying folder will be created under default location.
+			# else set the path specified by the user.
+			if(&datadriveimage::checkForWhiteSpace($1,"zdrive"))
+			{
+				next;
+			}
+			else
+			{
+				$ZDirloc  = $1;
+				$ZDirloc =~ s-\\-\/-g;
+				if( $ZDirloc !~ m/\/(\Z)/)
+				{ 
+					$ZDirloc .= "\/"; 
+				}
+				if( $ZDirloc !~ m/:/)
+				{
+					print "drive letter not specified\n";
+					$ZDirloc = &datadriveimage::setPath($ZDirloc);
+				}
+				print "Z Drive directory location = $ZDirloc\n";
+				#set the location of Z Drive directory.
+				$ZDirloc .= "zdrive";
+			}
+			next;
+		}
+		# get data directory location if specified by the user.
+		# if yes, then extract directory location from the given array element. 
+		if( $arg =~ /^-d=(.*)/ || $arg =~ /^-datadrivepath=(.*)/i )
+		{
+			# check for white space in the specified folder path
+			# if "yes" then warn the user saying folder will be created under default location.
+			# else set the path specified by the user.
+			if(&datadriveimage::checkForWhiteSpace($1,"datadrive"))
+			{
+				next;
+			}
+			else
+			{
+				$DataDriveDirloc = $1;
+				$DataDriveDirloc =~ s-\\-\/-g;
+				if( $DataDriveDirloc !~ m/\/(\Z)/)
+				{ 
+					$DataDriveDirloc .= "\/"; 
+				}
+				if( $DataDriveDirloc !~ m/:/)
+				{
+					print "drive not specified\n";
+					$DataDriveDirloc = &datadriveimage::setPath($DataDriveDirloc);
+				}
+				print "Data Drive directory location = $DataDriveDirloc\n";
+				#set the location of Data Drive directory.
+				$DataDriveDirloc .= "datadrive";
+			}
+			next;
+		}
+		# get Z dive image if specified by the user.
+		if( $arg =~ /^-zdriveimage=(.*)/i )	
+		{
+			my $imageName = $1;
+			if( $imageName =~ m/\,/)
+			{
+				@zdriveImageName = split(/\,/,$imageName);
+			}
+			else
+			{
+				push(@zdriveImageName,$imageName);
+			}
+			$opt_zimage = 1;
+			next;
+		}
+		# get command line arguments which needs to be passed to INTERPRETSIS, if specified by the user.
+		if( $arg =~ /^-argforinterpretsis=(.*)/i )	
+		{
+			my $interpretsisOpt = $1;
+			if( $interpretsisOpt =~ m/\,/)
+			{
+				@interpretsisOptList = split(/\,/,$interpretsisOpt);
+			}
+			else
+			{
+				push(@interpretsisOptList,$interpretsisOpt);
+			}
+			next;
+		}
+		if ( $arg =~ /^-k$/i || $arg =~ /^-keepgoing$/i )
+	    {
+			$opt_k = 1;
+			next;
+	    }
+		if ( $arg =~ /^-r$/i || $arg =~ /^-retainfolder$/i )
+	    {
+			$opt_r = 1;
+			next;
+	    }
+		if ( $arg =~ /^-pfile=(.*)/i )
+	    {
+			$paraFile = $1;
+			next;
+	    }
+		if ( $arg =~ /^-l=(.*)/i || $arg =~ /^-logimageentry=(.*)/i )
+	    {
+			if( $1 =~/[\/\\]/ || $1 =~ m/:/)
+			{
+				print "* Warning: Invalid log file extension try filename.txt\n";
+				next;
+			}
+			else
+			{
+				$opt_logFile = 1;
+				$imageEntryLogFile = $1;
+			}
+			next;
+	    }
+		if ( $arg =~ /^-lowmem/i )
+		{
+			$lowMem = $arg;
+			next;
+		}
+	    if ($arg =~ /^-/)
+	    {
+		print "Unknown arg: $arg\n";
+		$errors++;
+		next;
+	    }
+	    # It's an OBY file
+	    next if (match_obyfile($arg));
+	    next if (match_obyfile("$arg.oby"));
+
+	    print "Cannot find oby file: $arg\n";
+	    $errors++ if(!$opt_k);
+	}
+
+	if (defined $paramFileFlag) 
+	{
+		return;
+	}
+	
+	if (@obyfiles<1)
+	{
+	    print "Missing obyfile argument\n";
+	    $errors++ if(!$opt_k);
+	}
+
+	if ($errors)
+	{
+	    print_usage();
+	    exit 1;
+	}
+	
+	if ($noFeatureManager && $featuremanager) 
+	{
+		print "Warning: Ignoring \"-nofm\" option, as both \"-nofm\" and \"-fm\" options are provided.\n";			
+		$noFeatureManager = 0;
+	}
+
+	# Adding variant specific macros by including a HRH file
+	# (only required if no Feature Variant is used)
+	if (!$featureVariant{'VALID'})
+	{
+	    my $variantMacroHRHFile = get_variantmacroHRHfile();
+	    if($variantMacroHRHFile){
+	        my $variantFilePath = split_path('Path',$variantMacroHRHFile);
+	        $cppargs .= " -I " . &append_driveandquote($variantFilePath) . " -include " . &append_driveandquote($variantMacroHRHFile); 
+	        print "in cmd process $cppargs\n" if ($opt_v);
+	    }
+	}
+	# load the required modules if xml is required
+	if ($xmlrequired == 1)
+	{
+	    if (defined ($featureXml))
+	    {
+			load_featuresutil();
+	    }
+	
+	    if ($image_content)
+	    {
+	    	&FlexLoad_ModuleL("ImageContentHandler");
+	    	# some variables for ImageContentHandler may have been setup
+	    	my ($key, $value);
+	    	&ImageContentHandler::SetBldRomOpts; # Defaults to armv5 platform
+	    	while (($key,$value) = each %tmpBldRomOpts)
+	    	{
+			&ImageContentHandler::SetBldRomOpts($key, $value);
+	    	}
+	    }
+	    
+	}
+}
+
+#----------------------------------------------------------------------------------
+# Preprocessing phase
+#
+# Concatentate the specified .oby files and pass them through cpp
+# to get the raw ROM specification in tmp1.oby
+
+sub preprocessing_phase
+{
+	my $temp1OBYFile = $thisdir."tmp1.oby";
+	unlink "$temp1OBYFile";
+
+#	Macro "ROM_FEATURE_MANAGEMENT" is defined when "-f|fr" or "-fm" is used
+	if (defined ($featureXml))
+	{
+		$cppargs .= " -DROM_FEATURE_MANAGEMENT ";
+	}
+
+	# add pre-include file and include directories for feature variants
+	if ($featureVariant{'VALID'})
+	{
+		$cppargs .= " -I.";
+		my $incRef = $featureVariant{'ROM_INCLUDES'};
+		if ($incRef)
+		{
+			foreach (@$incRef)
+			{
+		    	$cppargs .= " -I \"$_\"";
+			}
+		}
+		my $HRH = $featureVariant{'VARIANT_HRH'};
+		if ($HRH)
+		{
+		    $cppargs .= " -include \"$HRH\"";
+		}
+	}
+	else
+	{
+		# no feature variant so use the standard includes
+		$cppargs .= " -I. -I \"$rominclude\"";
+	}
+
+	print "* cpp -Wno-endif-labels -o $temp1OBYFile $cppargs\n" if ($opt_v);
+	
+	is_existinpath("cpp", romutl::DIE_NOT_FOUND);
+	$errors = 0;
+	open CPP, "| cpp -Wno-endif-labels -o $temp1OBYFile $cppargs" or die "* Can't execute cpp";
+	foreach my $arg (@obyfiles)
+	{
+		print CPP "\n#line 1 \"$arg\"\n";
+	
+		if(open(OBY, $arg)) {
+			print "* reading $arg\n" if ($opt_v);
+			while ($line=<OBY>) {
+				print CPP $line;
+			}
+			close OBY;
+		}
+		else {
+			print STDERR "* Can't open $arg\n";
+			if(!$opt_k){			
+				close CPP;
+				exit(1);
+			}
+		}
+	}
+	close CPP;
+	my $cpp_status = $?;
+	die "* cpp failed\n" if ($cpp_status != 0 || !-f "$temp1OBYFile");
+
+	if( defined ($image_content))
+	{
+		#Read the OBY file that was generated by the pre-processor
+		&ReadPreprocessedFile($temp1OBYFile);
+
+#		Check if the static dependencies of the OBY binaries are resolved.
+		&ImageContentHandler::UpdateObyBinaryStaticDep();
+		
+		#Now append the files collected from cdfs.
+		&ImageContentHandler::GenObyFile($temp1OBYFile);
+	}
+
+	# Setup default rom configuration
+	$romimage[0] = {xip=>1, compress=>0, extension=>0, composite=>"none",uncompress=>0 };
+}
+
+sub ReadPreprocessedFile
+{
+#	Read the OBY file that was generated by the pre-processor. This OBY is a conglomeration of all the OBYs
+#	passed directly to buildrom and/or the ones passed through Image Content XML.
+#	It marks the binaries coming from OBY. This is required to be able to point out the binaries that are 
+#	mentioned neither in the OBY nor in the CDF. Such binaries are arrived at through static dependencies
+#	and need to be included in ROM.
+
+	my $temp1OBYFile = shift;
+	my $tmpline;
+	my $srcFileName;
+	my $srcFilePath;
+	my $dstFileName;
+	my $dstFilePath;
+	open (OBYFH, "$temp1OBYFile") or die("* Can't open $temp1OBYFile\n");
+	while($tmpline =<OBYFH>) {
+		if ($tmpline=~/(\S+)\s*=\s*(\S+)\s+(\S+)/) {#Get the first parameter (source File path) from oby line
+			$srcFilePath = $2;
+			$dstFilePath = $3;
+
+			if ($srcFilePath=~/.*[\/\\](\S+)/) {
+				$srcFileName = $1;
+			}
+			if ($dstFilePath=~/.*[\/\\](\S+)/) {
+				$dstFileName = $1;
+			}
+			my $binaryInfoRef = &cdfparser::GetBinaryInfo($dstFileName);
+
+			if(defined($binaryInfoRef)) 
+			{
+				#Found in CDF file
+				if($binaryInfoRef->{IsFoundInCDF})
+				{
+					print "Warning: File $srcFileName mentioned in OBY as well as CDF file\n";
+				}
+			}
+			else
+			{
+				#Found in OBY file
+				&ImageContentHandler::AddBinaryFromOby($dstFileName, $srcFilePath);
+			}
+		}
+	}
+	close OBYFH;
+}
+
+
+#----------------------------------------------------------------------------------
+# Substitution phase
+#
+# Handle the "define XXX YYY" lines, perform the substitutions.
+# Print out any ECHO lines or ERROR lines. 
+#
+
+# Predefined substitutions: 
+#   TODAY means todays' date
+#   RIGHT_NOW means the exact time
+#   EPOCROOT taken from the environment
+
+sub substitution_phase
+{
+	{
+		my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
+		$substitutionData{"TODAY"} = sprintf("%02d/%02d/%04d", $mday, $mon+1, $year+1900);
+		$substitutionData{"RIGHT_NOW"} = sprintf("%02d/%02d/%04d %02d:%02d:%02d", $mday, $mon+1, $year+1900, $hour, $min, $sec);
+		$substitutionData{"EPOCROOT"} = $epocroot;
+		@substitutionOrder = ("TODAY", "RIGHT_NOW", "EPOCROOT");
+	}
+
+	my $temp1OBYFile = $thisdir."tmp1.oby";
+	
+	open TMP1, "$temp1OBYFile" or die("* Can't open $temp1OBYFile\n");
+	while ($line=<TMP1>)
+	{
+		if(($line =~ /^\s*romsize\s*=/i) || ( $line=~ /^\s*rom_image/i) || ($line =~ /^\s*data_image/i))
+		{
+			$onlysmrimage = 0;
+			last;
+		}
+	}
+	close TMP1;	
+	if ($enforceFeatureManager && (!$featuremanager) && (!$noFeatureManager) )
+	{
+		my $defaultFeatureDbFlag = 0;
+		open TMP1, "$temp1OBYFile" or die("* Can't open $temp1OBYFile\n");
+		while ($line=<TMP1>)
+		{
+			if ($line=~/^\s*defaultfeaturedb\s*=?\s*(\S+)/i)
+			{	
+				# Get the default value for featuredatabasefile
+                
+				$featureXml = "$epocroot$1";
+				$featureXml =~ s-\\-\/-g;
+				$featuremanager = 1;				
+				$defaultFeatureDbFlag = 1;
+				load_featuresutil();				
+				last;
+			}
+		}
+		close TMP1;
+
+		if(!$defaultFeatureDbFlag && !$onlysmrimage)
+		{
+			print "Error: Neither option \"-fm|-nofm\" nor default value for featuredatabase file is provided.\n";
+			exit(1);			
+		}
+	}
+
+	open TMP1, "$temp1OBYFile" or die("* Can't open $temp1OBYFile\n");
+	while ($line=<TMP1>)
+	{
+		track_source($line);
+		$line =~ s-\\-\/-g;
+
+		my $tempstring = $epocroot."epoc32";
+		if(($line !~ /^\s*\#/) && ($line =~ /\/epoc32/i) 
+		 && ($line !~ /EPOCROOT##\/?epoc32/i) && ($line !~ /$tempstring/i))
+		{
+			print "add EPOCROOT for line: $line\n" if ($opt_v);
+	  	$line =~ s-\/epoc32-EPOCROOT##epoc32-ig;
+		}
+
+		#
+		# Recognise keywords in lines that we process before substitution
+		#
+		# # lineno "file" flagno
+		# DEFINE name replacement-with-0-spaces
+		#
+		if($line=~/^\s*$/)
+		{
+			next;
+		}
+		if ($line=~/^# (\d+) "(.*)" (\d+)/)
+		{
+			push @obydata, $line;
+			next;
+		}
+
+		if ($line=~/^\s*defaultfeaturedb\s*=?\s*(\S+)/i)
+		{	
+			push @obydata, "REM $line";
+			next;
+		}		
+		#process the External tool invocation using IBY file
+		if ($line=~/externaltool=(.*),?/i)
+		{
+			&externaltools::loadTools($1);
+			next;
+		}
+
+		#Process the patch statement
+		if($line =~ /^\s*patchdata\s*(.*)/i)
+		{
+			$patchDataStmtFlag = 1;
+			my $new_line = $1;
+ 			# syntax "<DLLnamewithpath> addr <variableaddress> <variablesize> <newvalue>"
+ 			# If the line matches with above syntax, just add the line into oby file.
+ 			if($new_line !~ /^\s*(\S+)\s+addr\s+(\S+)\s+(\S+)\s+(\S+)\s*$/i)
+ 			{
+ 				if(AddDllDataInfo($new_line))
+ 				{
+ 					$line = "REM $line";
+ 				}
+ 			}
+		}
+
+		if($line =~ /^\s*FEATURE\s*(.*)/i || $line =~ /^\s*EXCLUDE_FEATURE\s*(.*)/i)
+		{
+			# Process the feature keywords only when "-f|fr" or "-fm" is passed to buildrom
+			if(defined ($featureXml))
+			{
+				push @obydata, "$line";
+			}
+			else
+			{
+				push @obydata, "REM handled $line";
+			}
+			next;
+		}
+
+		if ($line=~/^\s*DEFINE\s+(\w+)\s+(\S+)/i)
+		{
+			my $key=$1;
+			my $value=$2;
+			foreach my $wordToSubstitute (@substitutionOrder)
+			{
+				my $whatToSubstituteItWith=$substitutionData{$wordToSubstitute};
+				$value=~s/$wordToSubstitute/$whatToSubstituteItWith/g;
+			}
+			$value=~s/##//g;
+			if (defined $substitutionData{$key})
+			{
+				# If the key is redefined, apply it at the new position rather
+				# than the old one.
+				push @obydata, "REM redefined $key as $value\n";# Leave a record of the definition
+				@substitutionOrder = grep !/^$key$/, @substitutionOrder;
+			}
+			else
+			{
+				push @obydata, "REM defined $key as $value\n";	# Leave a record of the definition
+			}
+			$substitutionData{$key}=$value;
+			
+			foreach my $wordToSubstitute (@substitutionOrder)
+		    {
+	   	        if ($key =~ /$wordToSubstitute/)
+	   	        {
+				   print_source_error("Warning: $key is masked by earlier definition of $wordToSubstitute");
+			 	}
+			}
+	
+			push @substitutionOrder, $key;
+			next;
+		}
+		#
+		# Do the substitutions in strict order of definition, 
+		# then eliminate any old-fashioned ## things which may be left
+		#
+		foreach my $wordToSubstitute (@substitutionOrder)
+		{
+			my $whatToSubstituteItWith=$substitutionData{$wordToSubstitute};
+			$line=~s/$wordToSubstitute/$whatToSubstituteItWith/g;
+		}
+		$line=~s/##//g;
+		#
+		# Recognise keywords in lines that we process after substitution
+		#
+		# ECHO  anything at all
+		# WARNING anything at all
+		# ERROR anything at all
+		# LANGUAGE_CODE nnn
+		# DEFAULT_LANGUAGE nnn
+		# ABI_DOWNGRADE from to
+		# ROMBUILD_OPTION command-line-option
+		# ROM_IMAGE
+		# PlatSecEnforceSysBin on|off
+		# ENABLE_SPI/DISABLE_SPI
+		#
+		if ($line=~/^\s*ECHO\s+(.*?)\s*$/i)
+		{
+			print "$1\n";
+			push @obydata, "REM handled $line";
+			next;
+		}
+		if ($line=~/^\s*(ERROR|WARNING)\s+(.*?)\s*$/i)
+		{
+			print_source_error("$1 $2");
+			$errors++ if ($1 =~ /ERROR/i);
+			push @obydata, "REM handled $line";
+			next;
+		}
+		if ($line=~/^\s*(PlatSecEnforceSysBin)\s+(\S+)\s*$/i)
+		{
+			$enforceSysBin = ($2 =~ /ON/i);
+			push @obydata, $line;
+			next;
+		}
+		if ($line=~/^\s*LANGUAGE_CODE\s+(\S+)\s*/i)
+		{
+			my $code = $1;
+			if ($code !~ /^\d\d+$/)
+			{
+				print_source_error("bad language code $code");
+				$errors++;
+			}
+			else
+			{
+				$languageCodes{$code} = 1;
+			}
+			push @obydata, "REM handled $line";
+			next;
+		}
+		if ($line=~/^\s*DEFAULT_LANGUAGE\s+(\S+)\s*/i)
+		{
+			my $code = $1;
+			if ($code !~ /^\d\d+$/)
+			{
+				print_source_error("bad default language code $code");
+				$errors++;
+			}
+			else
+			{
+				$defaultLanguageCode = $code;
+			}
+			push @obydata, "REM handled $line";
+			next;
+		}
+		
+		if ($line=~/^\s*ABI_DOWNGRADE\s*/i)
+		{
+			if ($line =~ /\s(.+)\s*->\s*(.+)\s*$/)
+			{
+				$abiDowngrade = "$1 $2";
+			}
+			else
+			{
+				print_source_error("bad ABI downgrade : $line");
+				$errors++;
+			}
+			push @obydata, "REM handled $line";
+			next;
+		}
+		if ($line=~/^\s*BINARY_SELECTION_ORDER\s*/i)
+		{
+	 		if ($line =~ /\s([^,]+)\s*,\s*(.+)\s*$/)
+   			{
+  				$binarySelectionOrderFlag = 1;
+ 				$firstDIR = $1;
+   				# remove whitespaces
+ 				$firstDIR = trim($firstDIR); 
+   				@binarySelectionOrder = split(',', $2);
+   				@binarySelectionOrder = trim(@binarySelectionOrder);
+
+			}
+			else
+			{
+				print_source_error("bad order specified: $line");
+				$errors++;
+			}
+			push @obydata, "REM handled $line";
+			next;
+		}
+		
+		if ($line=~/^\s*ROMBUILD_OPTION\s+(\S+)\s*/i)
+		{
+			$rombuildOptions{$1} = 1;
+			push @obydata, "REM handled $line";
+			next;
+		}
+		
+		if ($line=~/^\s*enable_spi\s*$/i)
+		{
+			if(!($spiset)) {
+				$createspi=1;
+			}
+			push @obydata, "REM handled $line";
+			next;
+		}
+		
+		if ($line=~/^\s*disable_spi\s*/i)
+		{
+			if(!($spiset)) {
+				$createspi=0;
+			}
+			push @obydata, "REM handled $line";
+			next;
+		}
+
+		if ($line=~/^\s*DATA_IMAGE\s+/i)
+		{
+			if ($line =~ /\s+(\d+)\s+(\S+)\s+/i)
+			{
+				my $datadriveidx = $1;
+				my $datadriveimagename = $2;
+				# have a count on number of data drive images that needs to be created
+				print "data drive partion name = $datadriveimagename\n " if($opt_v);
+				my $dataimagesize = 0;
+				if ($line =~ /\s+size=(\S+)\s*/i)
+				{ 
+					$dataimagesize=$1; 
+				}
+				my $fstype = "";
+				my $compress=0;
+				my $uncompress=0;
+				if ($line =~ /\s+compress\s*/i)
+				{ 
+					$compress=1;
+				}
+				elsif($line =~ /\s+uncompress\s*/i)
+				{ 
+					$uncompress=1;
+				}
+				if ($line =~ /\s+fat16\s*/i)
+				{ 
+					$fstype = "fat16"; 
+				}
+				if ($line =~ /\s+fat32\s*/i)
+				{ 
+					$fstype = "fat32"; 
+				}
+				
+				$datadriveimage[$datadriveidx] = {name=>$datadriveimagename, size=>$dataimagesize, compress=>$compress, uncompress=>$uncompress, fstype=>$fstype};
+				print "DATA_IMAGE[$datadriveidx] $datadriveimage[$datadriveidx]{name} size=$datadriveimage[$datadriveidx]{size} compress=$compress uncompress=$uncompress fstype=$fstype\n" if ($opt_v);
+			}
+			else
+			{
+				print_source_error("bad DATA_IMAGE specification : $line");
+				$errors++;
+			}
+			push @obydata, "REM handled $line";
+			next;
+		}
+		if ($line=~/^\s*ROM_IMAGE\s+/i)
+		{
+			if ($line =~ /\s+(\d+)\s+(\S+)\s+/i)
+			{
+				my $romidx=$1;
+				my $rompartitionname=$2;
+				my $rompartitionsize=0;
+				if ($line =~ /\s+size=(\S+)\s*/i)
+					{ $rompartitionsize=$1; }
+				my $xip=1;
+				my $compress=0;
+				my $uncompress=0;
+				my $extend=0;
+				my $composite="none";
+				if ($line =~ /\s+non-xip\s*/i)
+					{ $xip=0; }
+				if ($line =~ /\s+compress\s*/i)
+					{ $compress=1; }
+				elsif($line =~ /\s+uncompress\s*/i)
+					{ $uncompress=1;} # This option is passed to rofsbuild. For rombuild, not saying --compress means to uncompress
+				if ($line =~ /\s+extension\s*/i)
+					{ $extend=1; }
+				if ($line =~ /\s+composite_primary\s*/i) # added to support new composite_primary keyword in obey files
+				{	if (!($extend))
+						{ $composite="composite_primary"; }
+					else
+						{ print "Error: composite_primary keyword must be used with a core image\n"; }
+				}
+				if ($line =~ /\s+composite_secondary\s*/i) # added to support new composite_secondary keyword in obey files
+				{ if (!($extend))
+						{ $composite="composite_secondary"; }
+					else
+						{ print "Error: composite_secondary keyword must be used with core image\n"; }
+				}
+	
+				#	Compress and Uncompress are 2 different options and
+				#	not mentioning one of them doesn't necessarily mean the other.
+	
+				$romimage[$romidx] = {name=>$rompartitionname, size=>$rompartitionsize, xip=>$xip, compress=>$compress, extension=>$extend, composite=>$composite, uncompress=>$uncompress};
+				print "ROM_IMAGE[$romidx] $romimage[$romidx]{name} size=$romimage[$romidx]{size} xip=$xip compress=$compress extension=$extend composite=$composite uncompress=$uncompress \n" if ($opt_v);
+				check_romimage($romidx, $line);
+			}
+			else
+			{
+				print_source_error("bad ROM_IMAGE specification : $line");
+				$errors++;
+			}
+			push @obydata, "REM handled $line";
+			next;
+		}
+	
+		push @obydata, $line;
+	}
+
+	close TMP1;
+	exit(1) if ($errors);
+	dump_obydata("tmp2.oby", "result of substitution phase") if ($opt_v);
+}
+
+sub check_romimage
+{
+	my ($idx, $line) = @_;
+	if ($idx gt 7)
+	{
+		print_source_error("too many roms : $line");
+		$errors++;
+	}
+	if ($romimage[$idx]{xip} eq 0)
+	{
+		if ($romimage[$idx]{size} eq 0)
+		{
+			print_source_error("must specify a size for non-xip ROM : $line");
+			$errors++;
+		}
+	}
+	if ($romimage[$idx]{extension} ne 0)
+	{
+		if ($romimage[$idx-1]{extension} ne 0)
+		{
+			print_source_error("cannot extend ROM image multiple times : $line");
+			$errors++;
+		}
+	}
+}
+
+sub dump_obydata
+{
+	my ($dumpfile, $comment) = @_;
+	$dumpfile = $thisdir.$dumpfile;
+	unlink($dumpfile);
+	open DUMPFILE, ">$dumpfile" or die("* Can't create $dumpfile\n");
+	print "* Writing $dumpfile - $comment\n";
+	my $line;
+	foreach $line (@obydata)
+	{
+		print DUMPFILE $line;
+	}
+	close DUMPFILE;
+}
+
+sub track_source
+{
+	my ($line) = @_;
+	if ($line=~/^# (\d+) "(.*)"/)
+	{
+		$sourceline=$1-1;
+		$sourcefile=$2;
+		$sourcefile=~ s/\\\\/\\/g;
+		$sourcefile=~ s/\\/\//g;
+		return;
+	}
+	$sourceline++;
+}
+
+sub print_source_error
+{
+	my ($message) = @_;
+	print "$sourcefile($sourceline): $message\n";
+}
+
+sub reassert_sourceline
+{
+	my ($offset) = @_;
+	return sprintf "# %d \"$sourcefile\" \n", $sourceline+1+$offset;
+}
+
+
+#----------------------------------------------------------------------------------
+# Reorganisation phase
+#
+# Group lines beginning with "rom_image[<id>]" and deposit them in the appropriate
+# order.  Truncate the description at the "stop" line, if there is one.
+
+sub reorganize_phase
+{
+	
+	undef @newobydata;
+	my @section2;
+	my @part3;
+	my @part4;
+	my @part5;
+	my @part6;
+	my @part7;
+	my @part8;
+	my @partitions = ( \@newobydata, \@section2, \@part3, \@part4, \@part5, \@part6, \@part7, \@part8 );
+	my @currentpartition;	# partition stack
+
+	my @processedImageIdx;		# list of proccesed data drive image index. 
+	my $dataDriveStartRegion = 0;
+	my $dataDriveEndRegion = 0;
+	my $dataDriveIdx;
+	my @datapartition;
+	my @linesArray;
+	my $curlyBraceShouldFollow;
+
+	my $collect_section2=1;
+	my $smrImageStartRegion = 0;
+	my $smrImageEndRegion = 0;
+	my $smrImageIndex = 0;
+	
+	foreach $line (@obydata)
+	{
+		track_source($line);
+		if ($line=~/^\s*stop/i)
+		{
+			last;
+		}
+		if ($line =~ /^\s*ROM_IMAGE\[(\S+)\]\s+\{(.*)$/i)
+		{
+			# ROM_IMAGE[n] {
+			my $idx=$1;
+			my $partition=$partitions[$idx];
+			push @currentpartition, $partition;
+			$line="REM handled $line";
+		}
+		elsif( ($line =~ /^\s*DATA_IMAGE\[(\S+)\]\s*$/i) || ($line =~ /^\s*DATA_IMAGE\[(\S+)\]\s*\{\s*$/i))
+		{
+			# DATA_IMAGE[n] or DATA_IMAGE[n] {  is specified.
+			# get the index.
+			$dataDriveIdx=$1;
+ 			if($line !~ /\s*\{\s*/i)
+ 			{
+ 				$curlyBraceShouldFollow = 1;
+ 			}
+			# make a check if dataDriveIdx exists in the processedImageIdx array.
+			# if no, then push the dataDriveIdx on the processedImageIdx array.
+			# if yes,then dont execute the loop.
+			if(&datadriveimage::checkInArray(\@processedImageIdx,$dataDriveIdx))
+			{
+				# push the index on to the array.
+				push(@processedImageIdx,$dataDriveIdx);
+				# increment the image count. 
+				++$dataImageCount;
+			}
+
+			$dataIndexHash{($dataImageCount-1)} = $dataDriveIdx;
+			# set start of the image section.
+			$dataDriveStartRegion = 1;
+			# set end of image section to zero.
+			$dataDriveEndRegion = 0;
+			push (@linesArray,"\n");
+			$line="REM handled $line";
+		}
+		elsif( $line =~ /^\s*SMR_IMAGE\s*\{\s*$/i)
+		{
+			$smrImageStartRegion = 1;
+			$smrImageEndRegion = 0;
+			$needSmrImage = 1;
+			push (@linesArray, "\n");
+			$line="REM handled $line";
+		}
+ 		elsif((defined $curlyBraceShouldFollow) && ($line !~ /^\s*$/i))
+ 		{
+			undef $curlyBraceShouldFollow;
+ 			if($line !~ /^\s*\{\s*/i)
+ 			{
+ 				print "Error: Symbol '{' not followed after the keyword DATA_IMAGE\[".$dataDriveIdx."\]\n";
+ 				$errors++;
+ 			}
+ 			next;
+ 		}
+		# data drive specific keywords.
+		elsif( $line =~/^\s*dataimagename\s*\=\s*(\S+)/i )
+		{
+			# set the name for the image, if image name is specified using driveimagename keyword.
+			$datadriveimage[$dataDriveIdx]{name} = $1 if($dataDriveStartRegion && !$dataDriveEndRegion);
+			print"datadriveimagename = $datadriveimage[$dataDriveIdx]{name}\n" if($dataDriveStartRegion && !$dataDriveEndRegion && $opt_v);
+			# skip the line.
+			next;
+		}
+		elsif( $line =~/^\s*dataimagesize\s*\=\s*(\S+)/i )
+		{
+			# set the size for the image, if image size is specified using driveimagesize keyword.
+			$datadriveimage[$dataDriveIdx]{size} = $1 if($dataDriveStartRegion && !$dataDriveEndRegion);
+			print"datadriveimagesize = $datadriveimage[$dataDriveIdx]{size}\n" if($dataDriveStartRegion && !$dataDriveEndRegion && $opt_v);
+			# skip the line.
+			next;
+		}
+		elsif( $line =~/^\s*dataimagefilesystem\s*\=\s*(\S+)/i )
+		{
+			# set the file system type for the image, if image file system is specified using dataimagefilesystem keyword.
+			$datadriveimage[$dataDriveIdx]{fstype} = $1 if($dataDriveStartRegion && !$dataDriveEndRegion);
+			print"datadriveimagefstype = $datadriveimage[$dataDriveIdx]{fstype}\n" if($dataDriveStartRegion && !$dataDriveEndRegion && $opt_v);
+			# skip the line.
+			next;
+		}
+		elsif( $line =~/^\s*compress/i )
+		{
+			# Compresses the resulting data drive image using the Deflate, Huffman+LZ77 algorithm.
+			if($dataDriveStartRegion && !$dataDriveEndRegion)
+			{
+				$datadriveimage[$dataDriveIdx]{compress} = 1;
+				$datadriveimage[$dataDriveIdx]{uncompress} = 0;
+				print"datadriveimage[$dataDriveIdx] compress = $datadriveimage[$dataDriveIdx]{compress}\n" if($opt_v);
+			}
+		}
+		elsif( $line =~/^\s*uncompress/i )
+		{
+			# Uncompresses the resulting data drive image.
+			if($dataDriveStartRegion && !$dataDriveEndRegion)
+			{
+				$datadriveimage[$dataDriveIdx]{uncompress} = 1;
+				$datadriveimage[$dataDriveIdx]{compress} = 0;
+				print"datadriveimage[$dataDriveIdx] uncompress = $datadriveimage[$dataDriveIdx]{uncompress}\n" if($opt_v);
+			}
+		}
+		elsif ($line =~ /^\s*ROM_IMAGE\[(\S+)\](.*)$/i)
+		{
+			# ROM_IMAGE[n] file=...
+			my $origline=$line;
+			$line="$2\n";	# remove the ROM_IMAGE[.] keyword
+			my $idx=$1;
+			my $partition=$partitions[$idx];
+			push @$partition, reassert_sourceline(-1);
+			push @$partition, $line;
+			$line="REM handled $origline";
+		}
+		elsif ($line =~ /^\s*DATA_IMAGE\[(\S+)\](.*)$/i)
+		{
+			# DATA_IMAGE[n] file=...
+			my $origline=$line;
+			# remove the DATA_IMAGE[.] keyword
+			$line="$2\n";
+			# get the index value
+			my $idx=$1;
+			# iterate through the hash to get corresponding 
+			# key from the value(i.e idx) 
+			while (my($key, $value) = each(%dataIndexHash))
+			{
+				if ($value eq $idx ) 
+				{
+					$idx = $key;
+				}
+			}
+			push @{$datapartition[$idx]}, reassert_sourceline(-1);
+			push @{$datapartition[$idx]}, $line;
+			$line="REM handled $origline";
+		}
+		elsif ($line =~ /^\s*\}.*$/i)
+		{
+			if($dataDriveStartRegion)
+			{
+				# since "}" brace is encountered
+				# reset the start of DATA_IMAGE to zero.
+				$dataDriveStartRegion = 0;
+				# mark the the end of the DATA_IMAGE.
+				$dataDriveEndRegion = 1;
+				if(!$datadriveimage[$dataDriveIdx]{name})
+				{
+					# image name is not defined, define a default name.
+					$datadriveimage[$dataDriveIdx]{name} = "dataImage".$dataDriveIdx;
+				}
+				if(!$datadriveimage[$dataDriveIdx]{fstype})
+				{
+					# image name is not defined, define a default name.
+					$datadriveimage[$dataDriveIdx]{fstype} = "fat16";
+				}
+				foreach my $file (@linesArray)
+				{
+					push @{$datapartition[($dataImageCount-1)]},$file;
+				}
+				## if end of the DATA_IMAGE is true,
+				## make room for next DATA_IMAGE if any.
+				undef(@linesArray); 
+				#un define $dataDriveIdx;
+				undef($dataDriveIdx);
+			}
+			elsif($smrImageStartRegion)
+			{
+				$smrImageStartRegion = 0;
+				$smrImageEndRegion = 1;
+				foreach my $file (@linesArray)
+				{
+					push @{$smrPartitions{$smrImageIndex}}, $file;
+				}
+				undef(@linesArray);
+				$smrImageIndex++;
+			}
+			elsif (scalar @currentpartition > 0)
+			{ 
+				pop @currentpartition; 
+			}
+			else
+			{ 
+				print "WARNING: closing '}' found with no matching 'ROM_IMAGE[<n>]/DATA_IMAGE[<n>] {'\n";
+			}
+			$line="REM handled $line";
+		}
+		elsif ($line=~/^\s*section2(.*)$/i)
+		{
+			my $origline=$line;
+			$line="$1\n";	# remove the section2 keyword
+			if ($collect_section2)
+			{
+				push @section2, reassert_sourceline(-1);
+				push @section2, $line;
+				$line="REM handled $origline";
+			}
+		}
+		elsif ($line=~/^\s*section/i)
+		{
+			push @newobydata, $line;		# insert the section statement
+			if (@section2 != 0)
+			{
+				push @newobydata, "REM accumulated section2 lines\n";
+			}
+			foreach $line (@section2)
+			{
+				push @newobydata, $line;	# insert accumulated section2 lines
+			}
+			$collect_section2=0;
+			$line = reassert_sourceline();
+		}
+		
+		elsif ($line=~/^\s*extensionrom/i)
+		{
+			# end of ROM description, so deposit accumulated lines
+			if (@section2 != 0)
+			{
+				push @newobydata, "REM accumulated section2 lines\n";
+			}
+			foreach $line (@section2)
+			{
+				push @newobydata, $line;	# insert accumulated section2 lines
+			}
+			$collect_section2=0;
+			push @newobydata, reassert_sourceline();
+		}
+		
+		elsif ( scalar(@linesArray) )
+		{
+			if($dataDriveStartRegion && !$dataDriveEndRegion)
+			{
+				my $modifiedLine = $line;
+				push @linesArray, $modifiedLine;
+				$line = "REM handled $line";
+			}
+			elsif($smrImageStartRegion && !$smrImageEndRegion)
+			{
+				if($line =~ /^\s*IMAGENAME\s*=\s*(\S+)/i)
+				{
+					my $smrimagename = $1;
+					$smrimagename =~s/(\.img)//i;
+					if(exists($smrNameInfo{$smrimagename}))
+					{
+						$smrNameInfo{$smrimagename}++;
+					}
+					else
+					{
+						$smrNameInfo{$smrimagename} = 1;
+					}
+					$line =~s/(\.img)//i;
+				}
+				push @linesArray, $line;
+				$line = "REM handled $line";
+			}
+		}
+		elsif (scalar @currentpartition)
+		{
+			my $modifiedLine = $line;
+			if ($line =~ /^\s*SPI_POSITION/i)
+			{
+				if(!($createspi && $spiplacement))
+				{
+					# comment the line if the spi placement flag is not enabled or if the spi creation is not enabled.
+					$modifiedLine = "REM SPI creation/placement flag not enabled. Ignoring SPI_POSITION\n";
+					print ("Warning: SPI creation/placement flag not enabled. Ignoring SPI_POSITION\n" ) if ($opt_v);
+				}
+			}
+			# a partition is specified
+			# push this line into the currently selected partition
+			my $partition=$currentpartition[-1];
+			push @$partition, $modifiedLine;
+			$line="REM handled $line";
+		}
+		elsif ($line =~ /^\s*SPI_POSITION/i)
+		{
+			if(!($createspi && $spiplacement))
+			{
+                # comment the line if the spi placement flag is not enabled or if the spi creation is not enabled.
+                $line = "REM SPI creation/placement flag not enabled. Ignoring SPI_POSITION\n";
+                print ("Warning: SPI creation/placement flag not enabled. Ignoring SPI_POSITION\n" ) if ($opt_v);
+			}
+		}
+		push @newobydata, $line;
+	}
+
+	# output the grouped data
+	my $partitionidx=2;
+	if ($collect_section2)
+		{ $partitionidx=1; } # output old "section2" if not done already
+	for (; $partitionidx<8; $partitionidx++)
+	{
+		my $partition=$partitions[$partitionidx];
+		if (@$partition != 0)
+		{
+			push @newobydata, "REM ROM_IMAGE[$partitionidx]\n";
+			foreach $line (@$partition)
+			{
+				push @newobydata, $line;	# insert accumulated section2 lines
+			}
+		}
+	}
+	
+	for ( my $datapartitionidx=0; $datapartitionidx < $dataImageCount; $datapartitionidx++ )
+	{
+		if( defined( @{ $datapartition[$datapartitionidx] } ) )
+		{
+			push @newobydata, "REM DATA_IMAGE[$dataIndexHash{$datapartitionidx}]\n" ;
+			foreach my $file (@{$datapartition[$datapartitionidx]})
+			{
+				push @newobydata, $file;
+			}
+		}
+	}
+
+	
+	foreach my $imageIndex (keys(%smrPartitions))
+	{
+		my $imagename;
+		my @obeyfile;
+
+		foreach (@{$smrPartitions{$imageIndex}})
+		{
+			if(/^\s*imagename\s*=\s*(\S+)/i)
+			{
+				$imagename = $1;
+			}
+			push @obeyfile, $_;
+		}
+		if($smrNameInfo{$imagename} == 1)
+		{
+			push @obeyFileList, $imagename;
+			push @newobydata, "REM SMR_IMAGE \n";
+			push @newobydata, @obeyfile;
+		}
+		if(! defined($imagename))
+		{
+			$smrNoImageName = 1;
+		}
+		undef $imagename;
+		undef @obeyfile;
+	}
+
+	@obydata = @newobydata;
+	exit(1) if ($errors);
+	dump_obydata("tmp3.oby", "result of reorganisation phase") if ($opt_v);
+}
+
+
+#----------------------------------------------------------------------------------
+# Plugin phase
+#
+# Process any plugin annotation lines
+# Note: This expands resource lines to include MULTI_LINGUIFY so must be done before
+# the Multilinguify phase
+
+# hash of SPI file target directories is located near the start of this file, before sub match_obyfile
+
+sub plugin_phase
+{
+	undef @newobydata;
+	foreach $line (@obydata)
+	{
+		track_source($line);
+	 	if ($line =~ /^\s*REM/i)
+		{
+		# ignore REM statements, to avoid processing "REM ECOM_PLUGIN(xxx,yyy)"
+		}
+		elsif(plugin_match($line)) {
+			$line = reassert_sourceline();		
+		}
+		push @newobydata, $line;
+	}
+		
+	@obydata = @newobydata;
+	dump_obydata("tmp4.oby", "result of Plugin stage") if ($opt_v);
+}
+
+sub plugin_match ()
+{
+	my ($line) = @_;
+	foreach my $plugintype (keys(%plugintypes)) {
+	  if ($line =~ m/^.*__$plugintype\_PLUGIN\(\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*\)/i)
+	  	# __<plugin-type>_PLUGIN(emulator directory, file rom dir, dataz_, resource rom dir, filename, resource filename)
+	  {
+		    my $emulatorDir=$1;
+		    my $fileRomDir=$2;
+		    my $dataz_= $3;
+		    my $resourceDir=$4;
+		    my $pluginFileName=$5;
+		    my $pluginResourceName=$6;
+		    my $spidatahide = 0;
+			my $paged_data = "";
+  
+			if ($line =~ m/paged\s*$/i)
+			{
+				$line =~ m/\s+(\S+)\s*$/;
+				$paged_data = $1;
+			}
+
+		    if ($line =~ m/^\s*(_hide)/i )
+		    {
+		    	$spidatahide = 1;
+		    }
+
+		    # for resource files strip the .rsc or .dll from the end   (will be .dll where we use
+		    # SYMBIAN_SECURE_ECOM and are building resources to  the same name as ecom plugin dlls)
+		    
+		    if ($pluginResourceName =~ m/^(.+)\./)
+		    {
+		      $pluginResourceName = $1;
+		    }
+		    else
+		    {
+		      print_source_error("Invalid Resource name: $pluginResourceName in " . $plugintype . "_PLUGIN :$line");
+		      #treat as error if strict option selected;
+		      $errors++ if ($strict);
+		    }
+
+		    if ($spidatahide)
+		    {
+			push @newobydata, "hide=$fileRomDir\/$pluginFileName\n";
+		    }
+		    else
+		    {
+		    	push @newobydata, "file=$emulatorDir\/$pluginFileName $fileRomDir\/$pluginFileName $paged_data\n";
+		    }
+
+		    if($createspi) {
+		    	    if ($spidatahide)
+			    {
+			    	push @newobydata, "spidatahide=MULTI_LINGUIFY(RSC $dataz_\/$resourceDir\/$pluginResourceName $resourceDir\/$pluginResourceName) " . lc($plugintype) . "\.spi " . $plugintypes{$plugintype} . "\n";      
+			    }
+			    else
+			    {
+			    	push @newobydata, "spidata=MULTI_LINGUIFY(RSC $dataz_\/$resourceDir\/$pluginResourceName $resourceDir\/$pluginResourceName) " . lc($plugintype) . "\.spi " . $plugintypes{$plugintype} . "\n";      
+			    }
+		  	} else {
+		    	    if ($spidatahide)
+			    {
+			    	push @newobydata, "hide=MULTI_LINGUIFY(RSC $dataz_\/$resourceDir\/$pluginResourceName $resourceDir\/$pluginResourceName)\n";
+			    }
+			    else
+			    {
+			    	push @newobydata, "data=MULTI_LINGUIFY(RSC $dataz_\/$resourceDir\/$pluginResourceName $resourceDir\/$pluginResourceName)\n";
+			    }
+			}
+				return 1; #successful match
+	   }
+     }
+}
+
+
+#----------------------------------------------------------------------------------
+# Multilinguify phase
+#
+# Process the MULTILINGUIFY() lines
+
+sub multlinguify_phase
+{
+	if ((scalar keys %languageCodes) == 0)
+	{
+		print "* No language codes specified, defaulting to 01\n";
+		$defaultLanguageCode = "01";
+	}
+	$languageCodes{$defaultLanguageCode} = 1;
+	
+	undef @newobydata;
+	foreach $line (@obydata)
+	{
+		track_source($line);
+		if ($line =~ /^\s*REM/i)
+		{
+			# ignore REM statements, to avoid processing "REM data=xxx yyy"
+		}
+		elsif ($line=~/^(.*?)\bMULTI_LINGUIFY\s*\(\s*(\S+)\s+(\S+)\s+(\S+)\s*\)(.*)$/i)
+		{
+			my $initialStuff=$1;
+			$initialStuff = lc ($initialStuff);# if ($enableLowercaseTransfer);
+			my $defaultFileNameExtension=$2;
+			$defaultFileNameExtension = lc ($defaultFileNameExtension);# if ($enableLowercaseTransfer);
+			my $sourceFileNameWithoutExtension=$3;
+			$sourceFileNameWithoutExtension = ($sourceFileNameWithoutExtension);# if ($enableLowercaseTransfer);
+			my $targetFileNameWithoutExtension=$4;
+			my $finalStuff=$5;
+			my $spidataflag = 0;
+			my $spidatahide = 0;
+			my $datahide = 0;
+
+			if ($initialStuff=~/\w$/)
+			{
+				$initialStuff.=" ";
+			}
+			if ($finalStuff=~/^\w/)
+			{
+				$finalStuff=" ".$finalStuff;
+			}
+			if ($initialStuff =~ /^\s*spidata/i)
+			{
+				$spidataflag = 1;
+			}
+			if ($initialStuff =~ /^\s*spidatahide/i)
+			{
+				$spidataflag = 1;
+				$spidatahide = 1;
+			}
+			if ($initialStuff =~ /^\s*hide/i)
+			{
+				$datahide = 1;
+			}
+
+
+# ecom.spi should contain the .RSC files
+			if ($spidataflag)
+			{
+				my $sourceFileNameExtension = $defaultFileNameExtension;
+				my $targetFileNameExtension = $defaultFileNameExtension;
+				if (-e ("$sourceFileNameWithoutExtension.$sourceFileNameExtension"))
+				{
+					if ($spidatahide)
+					{
+						push @newobydata, "$initialStuff$sourceFileNameWithoutExtension.$sourceFileNameExtension$finalStuff\n";
+					}
+					else
+					{
+						push @newobydata, "$initialStuff$sourceFileNameWithoutExtension.$sourceFileNameExtension $targetFileNameWithoutExtension.$targetFileNameExtension$finalStuff\n";
+					}
+				}
+			}
+			my $useDefaultFileNameExtension=1;
+			foreach my $languageCode (keys %languageCodes) {
+				my $sourceFileNameExtension=$defaultFileNameExtension;
+				$sourceFileNameExtension=~s/^(.*).{2}$/$1$languageCode/;
+				if (! -e ("$sourceFileNameWithoutExtension.$sourceFileNameExtension"))
+				{
+					if (!$spidataflag)
+					{
+						next if (!$useDefaultFileNameExtension);
+						next if (defined $defaultLanguageCode and !($languageCode eq $defaultLanguageCode));
+						$useDefaultFileNameExtension=0;
+						if (!$datahide)
+						{
+							print "Converting >$sourceFileNameWithoutExtension.$sourceFileNameExtension< to $defaultFileNameExtension\n";
+							$sourceFileNameExtension=$defaultFileNameExtension;
+						}
+					}
+					else
+					{
+						next;
+					}
+				}
+
+				my $targetFileNameExtension;
+# ecom.sNN should contain the corresponding language code .RNN files
+				if(!$spidataflag and (defined $defaultLanguageCode and ($languageCode eq $defaultLanguageCode)))
+				{
+					$targetFileNameExtension = $defaultFileNameExtension;
+				}
+				else
+				{
+					$targetFileNameExtension = $sourceFileNameExtension;
+				}
+				my $modifiedfinalStuff = $finalStuff;
+				$modifiedfinalStuff =~ s/\.spi/\.s$languageCode/i;
+
+				if ($spidatahide)
+				{
+					push @newobydata, "$initialStuff$sourceFileNameWithoutExtension.$sourceFileNameExtension$modifiedfinalStuff\n";
+				}
+				elsif ($datahide)
+				{
+					push @newobydata, "$initialStuff$targetFileNameWithoutExtension.$targetFileNameExtension$modifiedfinalStuff\n";
+					if(!($sourceFileNameExtension eq $targetFileNameExtension))
+					{
+						push @newobydata, "$initialStuff$targetFileNameWithoutExtension.$sourceFileNameExtension$modifiedfinalStuff\n";
+					}
+				}
+				else
+				{
+					push @newobydata, "$initialStuff$sourceFileNameWithoutExtension.$sourceFileNameExtension $targetFileNameWithoutExtension.$sourceFileNameExtension$modifiedfinalStuff\n";
+					if(!($sourceFileNameExtension eq $targetFileNameExtension))
+					{
+						push @newobydata, "alias $targetFileNameWithoutExtension.$sourceFileNameExtension $targetFileNameWithoutExtension.$targetFileNameExtension $modifiedfinalStuff\n";
+						$targetFileNameWithoutExtension =~ s-\\-\/-g;
+						$multiLinguifyAlias{"$targetFileNameWithoutExtension.$sourceFileNameExtension"} = 1;
+					}
+				}
+			}
+			$line = reassert_sourceline();
+		}
+		push @newobydata, $line;
+	}
+		
+	@obydata = @newobydata;
+	dump_obydata("tmp5.oby", "result of choosing language-specific files") if ($opt_v);
+	undef @newobydata;
+
+}
+
+my @featurefilearray; #2d array storing names and locations of feature files in each rom image
+my @featureslist; #array of hashes, stores all the features which are to go into the feature files
+my $featurefilecount=0; #counts number of feature files in each rom image
+my $featurescount=0; #counts number of features
+my $dir; # Stores the ROM image location of features.dat/featreg.cfg files
+my $featurefilename; # Stores the name of feature file to be generated(i.e. "features.dat" or "featreg.cfg")
+my @spiarray; #2d array storing names and locations of spi files in each rom image
+my @datafiles; #array of hashes, stores all the data files which are to go into the spi files
+my @hidedatafiles; #array of hashes, stores all the data files which are to be hidden in the spi files
+my $spicount=0; #counts number of spi files in each rom image
+my $filescount=0; #counts number of data files
+my $hidefilescount=0; #counts number of data files to be hidden
+my $romimage=0; #number of rom image currently working with
+
+sub locateexisting 
+{ # if an SPI file of this type exists in a base image then returns name of SPI file from the array
+	my ($romimage, $spifile, $base) =@_;
+	my $i=0;
+	while(defined $spiarray[$base][$i]) {
+		if($spiarray[$base][$i]{spi} eq $spiarray[$romimage][$spifile]{spi}) {
+			my $spiname;
+			my $spiextension;
+			if($spiarray[$base][$i]{spifile} =~ /(.*)\.(.*)$/) {
+				$spiname=$1;
+				$spiextension=$2;
+			}
+			if(-e "$spiname-$base-$i\.$spiextension") {
+					return "$spiname-$base-$i\.$spiextension";
+			}
+		}
+		$i++;
+	}
+	return "";
+}
+
+sub create 
+{ #called to create SPI file and store in specified directory
+	my ($romimage, $spifile, $base) =@_; #$romimage = current rom image number, $spifile = current spifile number, $base=number of rom image basing on
+	my $existingspi = "";
+	if(defined($base)) { # checks core image for an existing SPI file of this type, if an existing file exists then $existingspi is set to -i<name of existing spi file> which will later be passed to spitool.pm
+		$existingspi = locateexisting($romimage, $spifile, $base);
+		if($existingspi ne "") {
+			$existingspi = "-i$existingspi";
+			
+		}
+	}
+	if($spiarray[$romimage][$spifile]{spifile} =~ /(.+)\.(.*)$/) {
+		my $targetspi="$1-$romimage-$spifile\.$2"; #add romimage number and identifier for spi file to spi file name to distinguish from other spi files
+		my @dataforspi; # array to store names of data files to include in spi file
+		my @hidedatainspi; # array to store names of data files that are to be hidden in spi file
+		for(my $k=0;$k<scalar @datafiles;$k++) {
+			if($datafiles[$k]{rom}==$romimage && $datafiles[$k]{spifile} == $spifile) {
+				push @dataforspi, $datafiles[$k]{data}; #push name of data file onto array if correct romimage and spi type
+			}
+		}
+
+		for(my $j=0;$j<scalar @hidedatafiles;$j++) {
+			if($hidedatafiles[$j]{rom}==$romimage && $hidedatafiles[$j]{spifile} == $spifile)
+			{
+				push @hidedatainspi, $hidedatafiles[$j]{data}; #push name of data file to be hidden onto array if correct romimage and spi type
+			}
+		}
+		my @spiargs; #arguments passed to createSpi
+		push @spiargs, ("-t$targetspi", "-d$thisdir", "-hide@hidedatainspi");
+		if($existingspi ne "") { push @spiargs, $existingspi; }
+		&spitool::createSpi(@spiargs, @dataforspi); # external call to 
+	}
+}
+
+#----------------------------------------------------------------------------------
+# SPI file creation phase
+#
+# If SPI files for resource (.rsc) are required then creates SPI files for each ROM image
+#
+sub spi_creation_phase
+{
+	my $composite_secondary=-1;
+	if($createspi) { 
+		my $secondary=0;
+		for (my $i=1; $i<8; $i++)
+		{
+			if($romimage[$i]{composite} eq "composite_secondary") 
+				{ $secondary++; }
+		}
+		if(!$secondary) 
+			{ $romimage[0]{composite} = "composite_secondary"; }
+		if($secondary>1)
+			{ print "Warning, more than one composite_primary specified, using image with lowest ROM_IMAGE number\n"; }
+	
+		foreach $line (@obydata)
+		{
+			if ($line=~/^\s*REM \s*ROM_IMAGE\[(\d)\]/) # specify which romimage following lines are part of
+			{
+				$romimage=$1;
+				$spicount=0;
+			}	elsif ($line =~ /^\s*REM/i)
+			{
+				# ignore any other REM statements
+			} elsif ($line=~/^\s*spidata\s*=\s*(\S+)\s+(\S+)\s+(\S+)\s(\S+)\s*$/)	{
+				#spidata=\epoc32\data\Z\Resource\Plugins\Obexclasscontroller.RSC Resource\Plugins\Obexclasscontroller.RSC ecom.spi \private\10003a3f\
+				my $targetspi=$4.$3;
+				my $flag=1;
+				my $i;
+				for($i=0;$i<$spicount && $flag;$i++) { #loop to see if name of spi file already added to this romimage in array
+					if($spiarray[$romimage][$i]{spi} eq $targetspi) {
+						$flag=0;
+					}
+				}
+			
+				if($flag) { # adds spi file if not yet listed for this romimage in array
+					$spiarray[$romimage][$spicount++]={spifile=>$3, spidir=>$4, spi=>$4.$3};
+					$i=$spicount;
+				}
+					$datafiles[$filescount++]= {data=>$1, rom=>$romimage, spifile=>$i-1}; 
+                        } elsif ($spiplacement && $line =~/^\s*SPI_POSITION/i){
+        			# mark the image index at which the SPI_POSITION keyword has occured in order to avoid writing duplicate
+        			# entries of the spi file.
+        			$spipositionflag{$romimage} = 1;
+        		} elsif ($line=~/^\s*spidatahide\s*=\s*(\S+)\s+(\S+)\s(\S+)\s*$/)	{
+				#spidatahide=\epoc32\data\Z\Resource\Plugins\Obexclasscontroller.RSC ecom.spi \private\10003a3f\
+				my $targetspi=$3.$2;
+				my $flag=1;
+				my $i;
+				for($i=0;$i<$spicount && $flag;$i++) { #loop to see if name of spi file already added to this romimage in array
+					if($spiarray[$romimage][$i]{spi} eq $targetspi) {
+						$flag=0;
+					}
+				}
+			
+				if($flag) { # adds spi file if not yet listed for this romimage in array
+					$spiarray[$romimage][$spicount++]={spifile=>$2, spidir=>$3, spi=>$3.$2};
+					$i=$spicount;
+				}
+					$hidedatafiles[$hidefilescount++]= {data=>$1, rom=>$romimage, spifile=>$i-1}; 
+			}
+
+		}
+		
+		for(my $i=0;$i<8 && $composite_secondary<0;$i++) { # loop to set $composite_secondary value
+			if($romimage[$i]{composite} eq "composite_secondary") {
+				$composite_secondary=$i;
+			}
+		}	
+	
+		for(my $i=0;$i<8;$i++) { #loop to add any spi files to composite_primary roms which are present in composite_secondary rom. spi files in secondary ROMs must be present in primary ROMS, this check rules out the possibility of the spi file in the primary rom not being created because it has no data files to add
+			if($romimage[$i]{composite} eq "composite_primary") {
+				my $j=0;
+				while(defined $spiarray[$composite_secondary][$j]) {
+					my $flag=1;
+					my $k=0;
+					while(defined $spiarray[$i][$k] && $flag) {
+						if($spiarray[$composite_secondary][$j]{spi} eq $spiarray[$i][$k]{spi}) {
+							$flag=0;
+						}
+						$k++;
+					}
+					if($flag) {
+						$spiarray[$i][$k]{spifile}=$spiarray[$composite_secondary][$j]{spifile};
+						$spiarray[$i][$k]{spidir}=$spiarray[$composite_secondary][$j]{spidir};
+						$spiarray[$i][$k]{spi}=$spiarray[$composite_secondary][$j]{spi};
+					}
+					$j++;
+				}
+			}
+		}
+		
+		for(my $i=0;$i<8;$i++) { #loop to add any spi files to extension roms which are present in core rom, same situation as in previous loop could potentially occur here
+			if($romimage[$i]{extension}) {
+				my $j=0;
+				while(defined $spiarray[$i-1][$j]) {
+					my $flag=1;
+					my $k=0;
+					while(defined $spiarray[$i][$k] && $flag) {
+						if($spiarray[$i-1][$j]{spi} eq $spiarray[$i][$k]{spi}) {
+							$flag=0;
+						}
+						$k++;
+					}
+					if($flag) {
+						$spiarray[$i][$k]{spifile}=$spiarray[$i-1][$j]{spifile};
+						$spiarray[$i][$k]{spidir}=$spiarray[$i-1][$j]{spidir};
+						$spiarray[$i][$k]{spi}=$spiarray[$i-1][$j]{spi};
+					}
+					$j++;
+				}
+			}
+		}
+	
+		for(my $i=0;$i<scalar @spiarray;$i++) { #create SPI files for ROMs which are neither composite_primary nor extensions
+			if(!($romimage[$i]{extension}) && $romimage[$i]{composite} ne "composite_primary") {
+				my $j=0;
+				while(defined $spiarray[$i][$j]) { 
+					create($i,$j++);
+				}
+			}
+		}	
+	
+		for(my $i=0;$i<8;$i++) { #create SPI files for ROMs marked as composite_primary
+			if($romimage[$i]{composite} eq "composite_primary") {
+				my $j=0;
+				while(defined $spiarray[$i][$j]) {
+					create($i,$j++,$composite_secondary);
+				}
+			}
+		}	
+		for(my $i=0;$i<8;$i++) { #create SPI files for ROMs marked as extension
+			if($romimage[$i]{extension}) {
+				my $j=0;
+				while(defined $spiarray[$i][$j]) {
+					create($i,$j++,$i-1);
+				}
+			}
+		}
+			
+		undef @newobydata;
+		my $flag=1;
+        	my $imageIdx=0;
+		foreach $line (@obydata) { #add SPI files to ROM image, adds lines to obey file to specify existing locations of SPI files and target locations.
+
+                        if($spiplacement){
+                                $flag = 0;	# Reset the flag since the spi file must be added to the final OBY only on finding SPI_POSITION 
+                                                        # keyword when the spiplacement flag is set. If the spiplacement flag is set but SPI_POSITION
+                                                        # is not found in the oby files, then no spi entry is emitted.
+                                if($line =~ /^\s*SPI_POSITION/i){
+                                        next if (!$spipositionflag{$imageIdx});#This spi has already been entered into OBY.
+                                        my $spiIdx=0;
+                                        while(defined $spiarray[$imageIdx][$spiIdx]) {
+                                                if($spiarray[$imageIdx][$spiIdx]{spifile} =~ /(.+)\.(.*)$/) {
+                                                        my $targetspi="$1-$imageIdx-$spiIdx\.$2";
+                                                        push @newobydata, "data=" . "$thisdir" . $targetspi . " \"" . $spiarray[$imageIdx][$spiIdx]{spi} . "\"\n";
+                                                }
+                                                $spiIdx++;
+                                        }
+                                        if($spiIdx == 0){
+                                                # If there is no plugin in this image, the SPI_POSITION statement is ignore.
+                                                print ("Warning: statement SPI_POSTION ignored as no plugin was found at ROM_IMAGE[${imageIdx}]\n");
+                                        }
+                                        $spipositionflag{$imageIdx} = 0;
+                                }
+                                elsif( $line =~ /REM ROM_IMAGE\[(\d)\]/i){
+                                        $imageIdx = $1;
+                                        push @newobydata, $line;
+                                }
+                                elsif($line =~ /^\s*spidata/i) {
+                                } else {
+                                        push @newobydata, $line;
+                                }
+                        }
+			elsif($line =~/REM ROM_IMAGE\[(\d)\]/) {
+				my $romimage=$1;
+				if($flag) { #put in SPI files for ROM_IMAGE[0]
+					$flag=0;
+					my $k=0;
+					while(defined $spiarray[0][$k]) {
+						if($spiarray[0][$k]{spifile} =~ /(.+)\.(.*)$/) {
+							my $targetspi="$1-0-$k\.$2";
+							push @newobydata, "data=" . "$thisdir" . $targetspi . " \"" . $spiarray[0][$k]{spidir} . $targetspi .  "\"\n";
+						}
+						$k++;
+					}
+				}
+				my $j=0;
+				push @newobydata, "\n" . $line . "\n";			
+				while(defined $spiarray[$romimage][$j]) { #put in SPI files for current ROM_IMAGE
+					if($spiarray[$romimage][$j]{spifile} =~ /(.+)\.(.*)$/) {
+						my $targetspi="$1-$romimage-$j\.$2";
+						push @newobydata, "data=" . "$thisdir" . $targetspi . " \"" . $spiarray[$romimage][$j]{spidir} . $targetspi .  "\"\n";
+					}
+					$j++;
+				}
+			} elsif($line =~ /^\s*extensionrom/i) {
+				if($flag) { #put in SPI files
+					my $k=0;
+					while(defined $spiarray[0][$k]) {
+						if($spiarray[0][$k]{spifile} =~ /(.+)\.(.*)$/) {
+							my $targetspi="$1-0-$k\.$2";
+							push @newobydata, "data=" . "$thisdir" . $targetspi . " \"" . $spiarray[0][$k]{spidir} . $targetspi . "\"\n";
+						}
+						$k++;
+					}
+					$flag = 0;
+				}
+				push @newobydata, $line;
+			} elsif($line =~ /^\s*spidata/i) {;
+			} else {
+				push @newobydata, $line;
+			}
+		}
+		if($flag) { #put in SPI files for ROM_IMAGE[0] if it is the only ROM_IMAGE
+			my $k=0;
+			while(defined $spiarray[0][$k]) {
+				if($spiarray[0][$k]{spifile} =~ /(.+)\.(.*)$/) {
+					my $targetspi="$1-0-$k\.$2";
+					push @newobydata, "data=" . "$thisdir" . $targetspi . " \"" . $spiarray[0][$k]{spidir} . $targetspi . "\"\n";
+				}
+				$k++;
+			}
+		}
+		@obydata=@newobydata;
+	}	
+	dump_obydata("tmp6.oby", "result of SPI stage") if ($opt_v);
+}
+
+sub load_featuresutil
+{
+	&FlexLoad_ModuleL("featuresutil");
+			
+	# Parse the feature database XML file
+	if(!&featuresutil::parseXMLDatabase($featureXml, $featuremanager, $strict))
+	{
+		$featureXml = undef;
+		exit(1) if($strict);
+	}
+}
+
+#----------------------------------------------------------------------------------
+# Feature registry configuration file/Features data file generation phase
+#
+# If feature registry configuration files/features data files are required then creates these files for
+# each ROM/ROFS image
+#
+sub featurefile_creation_phase
+{
+	if($onlysmrimage)
+	{
+		return;
+	}
+	# Set the name and Rom Image location of feature file.
+	if ($enforceFeatureManager) 
+	{
+		# features data file location
+		$dir = "private\/10205054\/";
+		$featurefilename = "features.dat";
+	}
+	else
+	{
+		# feature registry configuration file location
+		$dir = "private\/102744CA\/"; 
+		$featurefilename = "featreg.cfg";
+	}		
+	if (defined ($featureXml)) 
+	{
+		my $featurefilecount=0;
+		my $romimage=0;
+
+		foreach $line (@obydata)
+		{
+			# specify which romimage following lines are part of
+			if ($line=~/^\s*REM \s*ROM_IMAGE\[(\d)\]/) 
+			{
+				$romimage=$1;
+				$featurefilecount=0;
+			}
+			elsif ($line =~ /^\s*REM/i)
+			{
+				# ignore any other REM statements
+			}
+			elsif($line =~ /^\s*(FEATURE)\s*(\S*)\s*(.*)/i
+					|| $line =~ /^\s*(EXCLUDE_FEATURE)\s*(\S*)\s*(.*)/i)
+			{				
+				# FEATURE  <feature_name>  [ SF  <status falgs> ] [ UD  <user data> ]
+				my $feature = $1;
+				my $featurevalue = $2;
+				my $featureargs = $3;
+				my $reservedbit = 0;
+				my %featureflags=();				
+				
+				# Options 'SF' and 'UD' will be supported only for "-fm" option
+				if ($featuremanager) 
+				{
+					# [ SF  <status falgs> ] [ UD  <user data> ]
+					$featureargs =~	/(\S*)\s*(\S*)\s*(\S*)\s*(\S*)\s*/ ;
+
+					# Store the values of 'SF' and 'UD', or any invalid option, if provided					
+					if ($1) 
+					{	
+						$featureflags{uc($1)} = $2;						
+					}
+					if ($3) 
+					{
+						$featureflags{uc($3)} = $4;									
+					}
+
+					# Generate a warning if the option provided with Feature/Exclude_Feature keyword is  
+					# not 'SF' or 'UD'.
+					foreach my $Key (keys %featureflags)
+					{						
+						if ($Key !~ /^(SF|UD)$/)
+						{
+							print "Warning: Invalid argument \"$Key\" specified for feature $featurevalue\n";
+							delete $featureflags{$Key};
+							next;
+						}						
+					}							
+				}				
+				# In verbose mode, generate warning if "SF|UD" arguments or invalid arguments are specified
+				# for "-f|fr" option.
+				elsif ($featureargs && $opt_v)
+				{
+					print "Invalid argument(s) \"$featureargs\" provided for feature \"$featurevalue\"\n";
+					foreach my $Key (keys %featureflags)
+					{
+						delete $featureflags{$Key};
+					}
+				}				
+				
+				# The feature file name is of the format featreg.cfg[x-y] or features.dat[x-y] 
+				# where x is the romimage id, y is always 0, reserved for future use.
+				my $targetfeaturefile;
+				if (($romimage == 0) && ($reservedbit == 0))
+				{
+
+					# Core image will not have the mangled name
+				 	$targetfeaturefile = $featurefilename;
+				}
+				else
+				{
+				 	$targetfeaturefile = $featurefilename . "\[". $romimage . "\-$reservedbit\]";
+				}
+				my $flag=1;
+				my $featureflag;
+				if ($feature =~ /^FEATURE$/i)
+				{
+					$featureflag = 1;
+				}
+				else
+				{
+					$featureflag = 0;
+				}
+
+				my $i;
+ 				# loop to see if name of feature file already added to this romimage in array
+				for($i=0;$i<$featurefilecount && $flag;$i++)
+				{
+					if($featurefilearray[$romimage][$i]{cfgfile} eq $targetfeaturefile)
+					{
+						$flag=0;
+					}
+				}
+			
+				if($flag) { # adds feature file if not yet listed for this romimage in array
+					$featurefilearray[$romimage][$featurefilecount++]={cfgfile=>$targetfeaturefile, cfgdir=>$dir};
+					$i=$featurefilecount;
+				}
+
+				$featureslist[$featurescount]= {feature=>$featurevalue, include=>$featureflag, rom=>$romimage, cfgfile=>$i-1};
+				
+				# Store the value of 'SF' in 'featureslist' array
+				if (defined $featureflags{SF}) 
+				{
+					$featureslist[$featurescount]->{SF} = $featureflags{SF};						
+				}
+				# Store the value of 'UD' in 'featureslist' array
+				if (defined $featureflags{UD}) 
+				{
+					$featureslist[$featurescount]->{UD} = $featureflags{UD};
+				}				
+				$featurescount++;
+			}
+		}
+
+		# Create Feature File
+		for(my $i=0;$i<scalar @featurefilearray;$i++)
+		{
+			my $j=0;
+			while(defined $featurefilearray[$i][$j])
+			{
+				my $targetfeaturefile = $thisdir.$featurefilearray[$i][$j]{cfgfile};
+				if (!(&featuresutil::createFeatureFile($i,$j,$targetfeaturefile,\@featureslist,$featuremanager))) 
+				{
+					$featurefilearray[$i][$j]{cfgfile}= undef;
+					exit(1) if($strict);					
+				}
+				$j++;
+			}
+		}
+	
+		undef @newobydata;
+		my $flag=1;
+        	my $imageIdx=0;
+
+		# Add feature files to ROM image, adds lines to obey file to specify existing locations
+		# of feature files and target locations.
+		foreach $line (@obydata)
+		{
+			if($line =~/REM ROM_IMAGE\[(\d)\]/i)
+			{
+				my $romimage=$1;
+				if($flag)
+				{
+					# Put in feature files for ROM_IMAGE[0]
+					$flag=0;
+					my $k=0;
+					while(defined $featurefilearray[0][$k])
+					{
+						my $targetfeaturefile=$featurefilearray[0][$k]{cfgfile};
+						if (defined $targetfeaturefile) 
+						{
+							push @newobydata, "data=" . "$thisdir" . $targetfeaturefile . " \"" . $featurefilearray[0][$k]{cfgdir} . $targetfeaturefile .  "\"\n";							
+						}
+						$k++;
+					}
+				}
+				push @newobydata, "\n" . $line . "\n";			
+
+				my $j=0;
+				while(defined $featurefilearray[$romimage][$j])
+				{
+					# Put in feature files for current ROM_IMAGE
+					my $targetfeaturefile=$featurefilearray[$romimage][$j]{cfgfile};
+					
+					# Rom images will not have mangled name for feature files
+				 	my $destinationfeaturefile = $featurefilename;
+					
+					# Rofsbuild will set attribute 'exattrib=U' in the entry record when this field is used.
+					# File Server when asked for a directory listing would notice the attribute and will return the 
+					# list with mangled names. Hence, mangled name for feature files should not be put in ROM_IMAGE.
+					my $exattribute = "exattrib=U";
+
+					if (defined $targetfeaturefile)
+					{
+						push @newobydata, "data=" . "$thisdir" . $targetfeaturefile . " \"" . $featurefilearray[$romimage][$j]{cfgdir} . $destinationfeaturefile .  "\"\t\t" . $exattribute . "\n";
+					}
+					$j++;
+				}
+			}
+			elsif($line !~ /^\s*(FEATURE)\s*/i && $line !~ /^\s*(EXCLUDE_FEATURE)\s*/i)
+			{
+				# Put in all other lines except the FEATURE and EXCLUDE_FEATURE keywords
+				push @newobydata, $line;
+			}
+		}
+
+		if($flag)
+		{ 
+			# Put in feature files for ROM_IMAGE[0] if it is the only ROM_IMAGE
+			my $k=0;
+			while(defined $featurefilearray[0][$k])
+			{
+				my $targetfeaturefile = $featurefilearray[0][$k]{cfgfile};
+				if (defined $targetfeaturefile)
+				{
+					push @newobydata, "data=" . "$thisdir" . $targetfeaturefile . " \"" . $featurefilearray[0][$k]{cfgdir} . $targetfeaturefile . "\"\n";
+				}
+				$k++;
+			}
+		}
+		@obydata=@newobydata;
+	}
+	elsif ($enforceFeatureManager && $noFeatureManager && $preBuiltFeaturesDataFile)
+	{
+        print "Valid: $preBuiltFeaturesDataFile\n";
+		if (-e $preBuiltFeaturesDataFile) 
+		{			
+			my @newobydata = ();
+			my $flag = 1;
+			foreach my $line (@obydata)
+			{
+				# Put in the pre-built features data file in ROM_IMAGE[0] 
+				if($line =~/REM ROM_IMAGE\[1\]/i)
+				{
+					push @newobydata, "data=$preBuiltFeaturesDataFile" . " \"" . $dir . $featurefilename . "\"\n";
+					$flag =0;
+				}
+				push @newobydata, $line;
+			}
+			if($flag)
+			{ 
+				# Put in the pre-built features data file in ROM_IMAGE[0] if it is the only ROM_IMAGE
+				push @newobydata, "data=$preBuiltFeaturesDataFile" . " \"" . $dir . $featurefilename . "\"\n";
+			}
+			@obydata =  @newobydata;
+		}
+		else
+		{
+			print "Error: File \"$preBuiltFeaturesDataFile\" doesn't exist.\n";
+			exit(1);
+		}
+	}
+	elsif ($enforceFeatureManager)
+	{
+	    print "Error: no feature data file or pre-built feature data file is provided!";
+	    exit(1);
+	}
+	
+	checkcase() if ($checkcase);
+}
+my ($fromABI,$toABI) = split / /,$abiDowngrade;
+
+#----------------------------------------------------------------------------------
+# Problem suppression phase
+#
+# Downgrade files which don't exist for the ABI (if a downgrade path is specified)
+# Comment out missing files or report errors if strict option enabled
+#
+# Detect any references to Feature Variant binaries and substitute in the
+# correct source binary name using the VMAP file mechanism.
+
+sub suppress_phase
+{
+	undef @newobydata;
+
+	init_plat($PerlEPOCPath);
+
+	# use the "default" feature variant by default.
+	my $varname = $featureVariant{'VALID'} ? $featureVariant{'NAME'} : "default";
+
+	foreach $line (@obydata)
+	{
+		track_source($line);
+		if ($line =~ /^\s*REM/i || $line =~ /^\s*TIME\s*=\s*/i)
+		{
+			# ignore REM statements, to avoid processing "REM data=xxx yyy"
+		}
+		# 
+		# thing=some\file 
+		#
+		elsif ($line =~ /(\S+)\s*=\s*"?(\S+[\/\\]\S+)"?/)
+		{
+			my $what = $1;
+			my $filename = $2;
+			if ($line =~ /(\S+)\s*=\s*"([^"]+)"/)
+			{
+				$filename = $2;
+			}
+			my $normedFilename = &get_versionedname($filename);
+
+			# find all the alternative file locations
+			my @alternatives = fallback($normedFilename);
+			# test the original location first
+			unshift(@alternatives, $normedFilename);
+
+			# choose the first file location that actually exists
+			my $fileExists = 0;
+			foreach my $altFile (@alternatives)
+			{
+			    my $tmpPath;
+			    my $tmpFile;
+				if($altFile =~ /"?(.*[\/\\]arm\w+_?\w+)[\/\\]([^"]+)/i)
+				{
+					$tmpPath = $1;
+					$tmpFile = $2;
+				}
+				$tmpPath .= "\.$varname";
+				
+				if (-e $tmpPath ."\/$tmpFile"){
+                  # SBSv2 variant binary exists
+				  $fileExists = $tmpPath . "\/$tmpFile";
+				}
+				else {
+                  # SBSv1 variant binary or invariant binary
+				  $fileExists = get_BVbinname($altFile, $varname);
+				}
+				last if $fileExists;
+			}
+			
+			# edit the OBY line to use the actual file name which we found.
+			# (maybe) warn if an alternative to the original was selected.
+			if ($fileExists)
+			{
+				my $from = $filename;
+				$from =~ s/\\/\\\\/g;	
+				$from =~ s/\//\\\//g;		# need to escape backslashes
+				$from =~ s/(\[|\])/\\$1/g;	# need to escape square brackets for file names like "featreg.cfg[x-y]",etc.
+				my $into = $fileExists;
+
+ 				$line =~ s/$from/$into/i;
+
+ 				if ($warnSelection && ($fileExists ne $normedFilename))
+				{
+			    	print "replaced $filename with $fileExists\n";
+				}
+			}
+			else
+			{
+   				# No suitable alternative was found, so comment out the line unless
+				# it is a manatory ROMBUILD keyword, in which case it is better
+				# to let ROMBUILD report the missing file rather than report the
+				# missing keyword.
+   				if ($what !~ /^bootbinary|variant|primary|secondary|hide|dir/i)
+				{
+   					$line = "REM MISSING " . $line;
+   					print_source_error("Missing file: '$filename' in statement '$what='");
+					print "\ttried @alternatives\n"  if ($opt_v && @alternatives > 1);
+   					# treat as an error if the strict option is selected.
+   					$errors++ if ($strict);
+				}
+			}
+
+			# Once the binary is located in the appropriate ABI directory (e.g.,following the binary 
+			# selection order), check if the binary has been used in a patch dll statement. This is
+			# required to find out the source file. In ABIv1, the source file is required to find the
+			# .map file, while, in ABIv2, the destination file gives the dso file name.
+			if($line =~ /(\S+)\s*=\s*(\S+)\s+(\S+)\s*(.*)?/)
+			{
+				my $aSrcfile = $2;
+				my $dstFile = $3;
+				my $dstPath = "";
+
+				if($aSrcfile =~ /"?([^"]+)/){
+				$aSrcfile = $1;
+				}
+
+				$aSrcfile = &get_versionedname($aSrcfile);
+				if($dstFile =~ /"?(.*)[\/\\]([^"]+)/)
+				{
+					$dstPath = $1;
+					$dstFile = $2;
+				}
+				my $dllMapKey = lc ($dstFile);
+				if(exists $DllDataMap{$dllMapKey}) {
+					my $dllSymInfo = \%{$DllDataMap{$dllMapKey}};
+					$dllSymInfo->{srcfile} = $aSrcfile;
+					$dllSymInfo->{dstpath} = $dstPath;
+				}
+			}
+
+		}
+		push @newobydata, $line;
+	}
+	
+	@obydata = @newobydata;
+	dump_obydata("tmp7.oby", "result of problem-suppression phase") if ($opt_v);
+	die "ERROR: $errors missing file(s) detected\n" if ($strict && $errors );
+}
+
+# Remove leading and trailing whitespaces from a list of strings or a single string
+sub trim 
+{
+	my @out = @_;
+	for (@out) {
+		s/^\s+//;
+		s/\s+$//;
+	}
+	return wantarray ? @out : $out[0];
+}
+
+# Generate a list of alternative locations for the given filename
+sub fallback
+{
+   	my $file = shift;
+   	my @alternatives = CheckCustomization($file);
+ 
+ 	# If BINARY_SELECTION_ORDER macro is specified in the oby file
+ 	if ($binarySelectionOrderFlag)
+   	{
+ 		# Search in the specified binary order 
+ 		if(scalar(@Global_PlatList) == 0)
+		{
+			@Global_PlatList = get_platlist();
+		}
+ 		my $b;
+ 		my $e;
+ 		foreach my $plat (@Global_PlatList) 
+  		{
+  			if ($file =~ /^(.*)[\/\\]$plat[\/\\](.*)$/i) 
+  			{
+  				$b = $1;
+  				$e = $2;
+ 				last;
+ 			}
+ 		}
+ 		push(@alternatives, "$b\/$firstDIR\/$e");
+ 			
+ 		foreach my $toDIR (@binarySelectionOrder)
+   		{
+ 			push(@alternatives, "$b\/$toDIR\/$e");
+   		}
+   	}
+  	
+ 	# If the file is not found in the specified ABIV2 platform, then select from armv5 directory.
+ 	# This is necessary as some of the runtime DLLs will be present only in armv5 directory. 
+	# Add the BPABI Platforms to be added
+	if(scalar(@Global_BPABIPlats) == 0)
+	{
+		@Global_BPABIPlats = &get_bpabiplatlist;
+	}
+
+ 	foreach my $BpabiPlat (@Global_BPABIPlats)
+ 	{
+ 		if ($fromABI eq "" && $file =~ /^(.*)[\/\\]$BpabiPlat[\/\\](.*)$/i)
+   		{
+ 			push(@alternatives, "$1\/armv5\/$2");
+   		}
+   	}
+
+	if ($customizedPlat && $fromABI eq "" && $file =~ /^(.*)[\/\\]$customizedPlat[\/\\](.*)$/i)
+	{
+		my $b = $1;
+		my $e = $2;
+		# if platform customization 
+		my $rootPlat = get_platroot($customizedPlat);		
+        
+   		#Check in ARMV7 folder for binaries in case GCCEV7 is used [DEF128457 ]
+   		if($customizedPlat == "GCCEV7")
+   		{
+   			push(@alternatives,"$b\/armv7\/$e");
+   		}
+
+		if( grep /$rootPlat/, @Global_BPABIPlats)
+		{
+ 			push(@alternatives, "$b\/armv5\/$e");
+		}
+	}
+
+	if ($fromABI eq "" && $file =~ /^(.*)[\/\\]armv5_abiv1[\/\\](.*)$/i)
+   	{
+ 		push(@alternatives, "$1\/armv5\/$2");
+   	}
+  		
+   	if ($fromABI ne "" && $file =~ /^(.*)[\/\\]$fromABI[\/\\](.*)$/)
+	{
+ 		push(@alternatives, "$1\/$toABI\/$2");
+	}
+   
+   	return @alternatives;
+}
+
+# Generate a list of alternative locations for the given filename which
+# result from the possible platform customizations.
+sub CheckCustomization
+{
+ 	my $file = shift;
+ 	my @alternatives;
+	$customizedPlat = undef;	# global (used in feedback)
+
+ 	if(scalar(@Global_PlatList) == 0)
+	{
+		@Global_PlatList = get_platlist();
+	}
+ 	foreach my $plat (@Global_PlatList) 
+	{
+ 		if ($file =~ /^(.*)[\/\\]$plat[\/\\](.*)$/i) 
+		{
+ 			my $b = $1;
+ 			my $e = $2;
+ 			my $root = get_platcustomizes($plat);
+ 			if ($root) 
+			{
+				# Preserve the plat that is customized
+				$customizedPlat = $plat;
+
+				# If a BSF platform customizes another BSF platform (i.e. a
+				# BSF hierarchy exists), look for the file starting from the
+				# child BSF platform and working back to the root BSF platform
+				while ($root)
+				{
+					push(@alternatives, "$b\/$root\/$e");
+
+					# Temporary special case for armv5_abiv1 and armv5_abiv2
+					if ($root =~ /^armv5_abiv[12]$/i)
+					{
+						push(@alternatives, "$b\/armv5\/$e");
+ 					}
+
+					$root = get_platcustomizes($root);
+				}
+ 			}
+			return @alternatives;
+ 		}
+ 	}
+	return @alternatives;
+}		
+   
+#----------------------------------------------------------------------------------
+# Bitmap and aif conversion phase
+#
+# Convert any "bitmap=" or "compressed-bitmap=" files into ROM format bitmaps
+# Convert any "auto-bitmap=" to handle bitmap appropriately for xip and non-xip images
+# Convert "aif=" files appropriately for xip and non-xip images
+sub bitmap_aif_converison_phase
+{
+	my $is_xip=1;
+	undef @newobydata;
+	foreach $line (@obydata)
+	{
+		track_source($line);
+		# keep track of the XIP-ness of this rom partition
+		if ($line =~ /^\s*REM ROM_IMAGE\[(\d+)\]\s+(.*)$/i)
+		{ $is_xip=$romimage[$1]{xip}; }
+		#
+		# aif=source dest 
+		# include aif file - use XIP version for XIP roms if it exists, otherwise use the file specified
+		#
+		if ($line =~ /^\s*aif=/i)
+		{
+			my $xip="_xip";
+			my @aif= split(/\s+/,$line);
+			my $path=Path_Split('Path',"$aif[0]");
+			my $base=Path_Split('Base',"$aif[0]");
+			$path =~ s/^....//;
+			my $ext=Path_Split('Ext',"$aif[0]");
+			if ($is_xip && (-e "$path$base$xip$ext"))
+			{ $line="data=$path$base$xip$ext\t\t$aif[1]\n"; }
+			else
+			{ $line="data=$path$base$ext\t\t$aif[1]\n"; }
+		}
+		#
+		# auto-bitmap=
+		#
+		# if currently in XIP image, then use a compressed-bitmap
+		# otherwise use a RAM format bitmap
+		#
+		if ($line =~ /^\s*auto-bitmap=/i)
+		{
+			if ($is_xip)
+			{ $line =~ s/auto-bitmap=/compressed-bitmap=/i }
+			else
+			{ $line =~ s/auto-bitmap=/data=/i }
+		}
+		#
+		# uncompressed-bitmap
+		#
+		# this is currently just a synonym for 'bitmap'
+		$line =~ s/uncompressed-bitmap=/bitmap=/i;
+	
+		# 
+		# bitmap=source dest 
+		#
+		if ($line =~ /^\s*bitmap=\s*"?(\S+)"?\s+"?(\S+)"?/i)
+		{
+			my $mbm = $1;
+			my $dest = $2;            
+			my $rom_mbm = "$1_rom";
+			if ($is_xip eq 0)
+			{
+				# non-XIP rom - just include the mbm file
+				$line = "data=\"$mbm\"\t\"$dest\"\n";
+			}
+			else
+			{	
+		        if (! -e $rom_mbm || -M $rom_mbm >= -M $mbm)
+			    {
+					is_existinpath("bmconv", romutl::DIE_NOT_FOUND);
+                    
+                    my $rom_mbm_tmp = $rom_mbm;
+                    my $mbm_tmp = $mbm;
+                    if ($^O =~ /^MSWIN32$/i){
+                        $mbm_tmp =~ s-\/-\\-g;
+                        $rom_mbm_tmp =~ s-\/-\\-g;
+                    }
+                    
+				    system "bmconv -q -r $rom_mbm_tmp -m$mbm_tmp";
+	  		    my $bmconv_status = $?;
+				    die "* bmconv failed\n" if ($bmconv_status != 0 || !-f $rom_mbm);
+			    }
+				$line = "data=\"$rom_mbm\"\t\"$dest\"\n";
+				push @tempfiles, $rom_mbm;
+			}
+		}
+		#
+		# compressed-bitmap=
+		#
+		# if file is a compressed ROM image file
+		elsif ($line =~ /^\s*compressed-bitmap=\s*"?(\S+)"?\s+"?(\S+)"?/i)
+		{
+			my $mbm = $1;
+			my $dest = $2;            
+			my $cmprssd_rom_mbm = "$1_rom";
+			if ($is_xip eq 0)
+			{
+				# non-XIP rom - just include the mbm file
+				$line = "data=\"$mbm\"\t\"$dest\"\n";
+			}
+			else
+			{
+				if (! -e $cmprssd_rom_mbm || -M $cmprssd_rom_mbm >= -M $mbm)
+			    {
+					is_existinpath("bmconv", romutl::DIE_NOT_FOUND);
+                    
+                    my $cmprssd_rom_mbm_tmp = $cmprssd_rom_mbm;
+                    my $mbm_tmp = $mbm;
+                    if ($^O =~ /^MSWIN32$/i){
+                        $mbm_tmp =~ s-\/-\\-g;
+                        $cmprssd_rom_mbm_tmp =~ s-\/-\\-g;
+                    }
+                    
+				    system "bmconv -q -s $cmprssd_rom_mbm_tmp -m$mbm_tmp";
+				    my $bmconv_status = $?;
+				    die "* bmconv failed\n" if ($bmconv_status != 0 || !-f $cmprssd_rom_mbm);
+				}
+				$line = "data=\"$cmprssd_rom_mbm\"\t\"$dest\"\n";
+				push @tempfiles, $cmprssd_rom_mbm;			    
+			}
+		}
+		push @newobydata, $line;
+	}
+	@obydata = @newobydata;
+	dump_obydata("tmp8.oby", "result of bitmap conversion phase") if ($opt_v);
+}
+
+
+sub reformat_line($)
+{
+	my ($line) = @_;
+	my $type = "";
+	my $variant = "";
+	my $pcfile = "";
+	my $romfile = "";
+	my $tail = "";
+	
+	# time=21/07/1999 12:00:00
+	# primary[0x09080004]   =\epoc32\release\misa\udeb\ekern.exe
+	# data=\epoc32\wins\C\System\Alarms\churchbell.snd    "System\Alarms\Church bell"
+	# file[0x07060001]=\epoc32\release\MAWD\urel\cAkyb1.dll          System\Libs\EKeyb.dll
+	# file=\epoc32\release\marm\urel\eikcore.dll 			System\Libs\Eikcore.dll
+	# alias \System\Bin\DRTRVCT2_2.dll 			\System\Bin\DRTRVCT2_1.dll
+	#
+	$line =~ s-\\-\/-g;
+	if ($line =~ /^\s*TIME\s*=\s*/i)
+	{
+		return $line;
+	}
+  	elsif($line =~ /^\s*volume\s*=.*/i)
+  	{
+  		return $line;		
+  	}
+	elsif($line =~ /^\s*kerneltrace\s*=.*/i)
+	{
+		return $line;
+	}
+	elsif($line =~ /^\s*dir\s*=.*/i)
+	{
+		return $line;
+	}
+	elsif($line =~ /^\s*bootbinary\s*=(.*)/i)
+	{
+	}
+	if ($line =~ /^\s*(\S+)\s*=\s*(\S+)\s+"\/?(.*)"(.*)$/)
+	{
+		$type = $1;
+		$variant = "";
+		$pcfile = $2;
+		$romfile = $3;
+		$tail = $4;
+	}
+	elsif ($line =~ /^\s*(\S+)(\[\S+\])\s*=\s*(\S+)\s+\/?(\S+)(.*)$/)
+	{
+		$type = $1;
+		$variant = $2;
+		$pcfile = $3;
+		$romfile = $4;
+		$tail = $5;
+	}
+	elsif ($line =~ /(\S+)\s*=\s*"([^"]+)"\s+"\/?(.*)"(.*)$/ 
+			|| $line =~ /(\S+)\s*=\s*"([^"]+)"\s+\/?(\S+)(.*)$/)
+	{
+		if ($line !~ /^REM MISSING/i)
+		{
+			$type = $1;
+			$variant = "";
+			$pcfile = "\"$2\"";
+			$romfile = $3;
+			$tail = $4;
+		}
+		else{
+			return $line;
+		}
+	}
+	elsif ($line =~ /^\s*(\S+)\s*=\s*(\S+)\s+\/?(\S+)(.*)$/)
+	{
+		$type = $1;
+		$variant = "";
+		$pcfile = $2;
+		$romfile = $3;
+		$tail = $4;
+	}
+	elsif($line =~ /^\s*(patchdata)\s*(\S+)\s*\@\s*(\S+)\s+(\S+)/i)
+	{
+		# Reformat the patchdata statement
+		my $romfilename = $2;
+		my $patchdlldatamap_key = lc ($romfilename);
+		my $symbolname = $3;
+		my $value = $4;
+		my ($index, $elementSize);		# For when the symbol is an array, and we're patching one element
+		my $scalarSize;
+		
+		if(!defined $DllDataMap{$patchdlldatamap_key}->{dstpath}){
+			print_source_error(" File $romfilename has not been included into ROM image");
+			$errors++ if($strict);
+			$line = "REM $line\n";
+			return $line;
+		}
+	
+		if ($enforceSysBin)
+		{
+			if ($DllDataMap{$patchdlldatamap_key}->{dstpath} !~ /^sys\\bin/i 
+			 && $DllDataMap{$patchdlldatamap_key}->{dstpath} !~ /^sys\/bin/i)
+			{
+				$DllDataMap{$patchdlldatamap_key}->{dstpath} = "sys\/bin";
+			}
+		}
+		
+		my $dllfile = $DllDataMap{$patchdlldatamap_key}->{dstpath} . "\/". $romfilename;
+		
+		$line = "$1  ";
+		$line .= "$dllfile ";
+ 
+		# Convert value into decimal (used to be done in AddDllDataInfo, but that limited us to
+		# one value per symbol, and we now support patching arrays, e.g. the Hal's InitialValue[],
+		# so we can't do it that way any more.)
+		if ($value =~ /^0x([0-9a-f]+)$/i) {
+			$value = hex($1);
+		}
+		elsif ($value =~ /^(-?\d+)$/) {
+			$value = $1;
+		}
+		else {
+			print_source_error("Attempt to set $symbolname to illegal value $value");
+			$errors++ if($strict);
+			$line = "REM $line\n";
+			return $line;
+		}
+
+		if ($symbolname =~ s/:(\d+)\[((0x)?[0-9a-f]+)\]$//i) {
+			($index, $elementSize) = ($2, $1);
+			$index = hex($index) if $index =~ /^0x/i;
+		}
+
+		my $DllSymInfoRef = $DllDataMap{$patchdlldatamap_key}->{$symbolname};
+ 
+		if (!defined($DllSymInfoRef->{size})) {
+			print_source_error("Size for symbol $symbolname not found");
+			$errors++ if($strict);
+			$line = "REM $line\n";
+			return $line;
+		}
+
+		if (defined($elementSize)) {
+			$scalarSize = $elementSize / 8;
+			if ($scalarSize != 1 && $scalarSize != 2 && $scalarSize != 4) {
+				print_source_error("Invalid bit size $elementSize for array $symbolname in $romfilename");
+				$errors++ if($strict);
+				$line = "REM $line\n";
+				return $line;
+			}
+			if (($index + 1) * $scalarSize > $DllSymInfoRef->{size}) {
+				print_source_error("Invalid index $index into array $symbolname in $romfilename");
+				$errors++ if($strict);
+				$line = "REM $line\n";
+				return $line;
+			}
+		} else {
+			$scalarSize = $DllSymInfoRef->{size};
+		}
+
+		my $max_value = 0xffffffff;
+
+		if ($scalarSize == 1) {
+			$max_value = 0xff;
+		}
+		elsif ($scalarSize == 2) {
+			$max_value = 0xffff;
+		}
+
+		if ($value > $max_value) {
+			$value &= $max_value;
+			print "$DllSymInfoRef->{obyfilename}($DllSymInfoRef->{lineno}): Warning:Value overflow of $symbolname\n";
+			$errors++ if($strict);
+		}
+
+		if(defined $DllSymInfoRef->{ordinal}) {
+			if (defined($elementSize)) {
+				my $ord = $DllSymInfoRef->{ordinal};
+				my $offset = $index * $scalarSize;
+				$line .= "ordinal $ord+$offset ";
+			} else {
+				$line .= "ordinal ";
+				$line .= $DllSymInfoRef->{ordinal} . " ";
+			}
+		}
+		elsif(defined $DllSymInfoRef->{dataAddr}) {
+			if (defined($elementSize)) {
+				my $addr = $DllSymInfoRef->{dataAddr};
+				$addr = hex($addr) if $addr =~ /^0x/i;
+				$addr = sprintf("0x%08x", $addr + $index * $scalarSize);
+				$line .= "addr $addr ";
+			} else {
+				$line .= "addr ";
+				$line .= $DllSymInfoRef->{dataAddr} . " ";
+			}
+		}
+		else
+		{
+			print_source_error("Ordinal or Address for exported symbol $symbolname in $romfilename couldn't be located");
+			$errors++ if($strict);
+			$line = "REM $line\n";
+			return $line;
+		};
+		
+		$line .= "$scalarSize $value\n";
+
+		return $line;
+	}
+	elsif ($line =~ /^\s*(\S+)\s*(\S+)\s+\/?(\S+)(.*)$/)
+	{
+		$type = $1;
+		$variant = "";
+		$pcfile = $2;
+		$romfile = $3;
+		$tail = $4;
+
+		if ($type !~ /^(alias)$/i)
+		{
+			# Return now, if it is not an 'alias'.
+			return $line;
+		}
+		else
+		{
+			# There is no substitution needed for SysBin 'alias'es.
+			if ($romfile =~ /^sys\\bin\\/i
+			  ||$romfile =~ /^sys\/bin/i)
+			{
+				return $line;
+			}
+		}
+	}
+	else
+	{
+		return $line;
+	}
+ 	# Buildrom should generate warning when destination path provided for a file 
+ 	# is not a standard path(as per platsec) and "PlatSecEnforceSysBin" is turned off. 
+ 	my $warnFlag = 1;
+	my $mustBeSysBin = $enforceSysBin;
+	if ($type =~ /^(data|compress|nocompress)$/i
+		&& $romfile !~ /^system\/(bin|libs|programs)\//i)
+	{
+		$mustBeSysBin = 0;
+ 		$warnFlag = 0;
+	}
+	
+	if ($mustBeSysBin)
+	{
+		if ($type =~ /^(alias)$/i
+			&& $romfile !~ /^sys\\bin\\/i
+			&& $romfile !~ /^sys\/bin/i)
+		{
+			# for multilinguify 'alias'es (generally resource files) 'MustBeSysBin' should not be enforced.
+			if(defined($multiLinguifyAlias{$pcfile})) {
+				return $line;  
+			}
+
+			my $filename = "\/$romfile";	# in case no path is specified
+			$filename = substr $filename, rindex($filename, "\/");
+			$romfile = "sys\/bin".$filename;
+
+			if ($pcfile !~ /^sys\\bin\\/i
+			    && $pcfile !~ /^sys\/bin/i)
+			{
+				my $pcfilename = "\/$pcfile";	# in case no path is specified
+				$pcfilename = substr $pcfilename, rindex($pcfilename, "\/");
+				$pcfile = "sys\/bin".$pcfilename;
+			}
+			return "$type$variant $pcfile \t$romfile$tail\n";
+		}
+
+		if ($romfile !~ /^sys\\bin\\/i
+		    && $romfile !~ /^sys\/bin/i)
+		{
+			my $filename = "\/$romfile";	# in case no path is specified
+			$filename = substr $filename, rindex($filename, "\/");
+			$romfile = "sys\/bin".$filename;
+		}
+	}
+	else
+	{
+ 		if ($warnFlag && $romfile !~ /^sys\\bin\\/i && $romfile !~ /^sys\/bin/i)
+ 		{
+ 			print "Warning: Outside standard path at \"$line\"\n";
+ 		}
+		if ($type =~ /^(alias)$/i)
+		{
+			# Return the line as it is for non-MustBeSysBin 'alias'es.
+			return $line;
+		}
+	}
+	$romfiles{$romfile} = $variant.$pcfile;
+	return "$type$variant=$pcfile \t\"$romfile\"$tail\n";
+}
+
+my @hidearray;
+
+sub mark
+{ # function to mark files in ROMs as hidden
+	my ($base,$ext) = @_;
+	my $i=0;
+	my @coreimagerange = (-1,-1); #coreimagerange stores the places within @hidearray where the $base files start and end
+	my @extensionimagerange = (-1,-1); #extensionimagerange stores the places within @hidearray where the $ext files start and end
+	for(my $i=0;$i<scalar @hidearray;$i++) { #loop sets values in @coreimagerange and in @extensionimagerange
+		if($hidearray[$i]{rom}==$base) {
+			if($coreimagerange[0]<0) {
+				$coreimagerange[0]=$i;
+				$coreimagerange[1]=$i;
+			} else {
+				$coreimagerange[1]=$i;
+			}
+		} elsif($hidearray[$i]{rom}==$ext) {
+			if($extensionimagerange[0]<0) {
+				$extensionimagerange[0]=$i;
+				$extensionimagerange[1]=$i;
+			} else {
+				$extensionimagerange[1]=$i;
+			}
+		}
+	}
+	
+	for(my $i=$extensionimagerange[0];$i<=$extensionimagerange[1];$i++) { #loop marks files which need to be hidden based on the values in @coreimagerange and in @extensionimagerange
+		for(my $j=$coreimagerange[0];$j<=$coreimagerange[1];$j++) {
+			if($hidearray[$i]{dest} eq $hidearray[$j]{dest}) {
+				$hidearray[$i]{hide}=1;
+			}
+		}
+	}
+}
+
+
+#----------------------------------------------------------------------------------
+# Cleaning phase
+#
+# Remove "REM defined", "REM handled"
+# Remove the "# lineno" information
+# Collapse multiple blank lines
+# Apply the PlatSecEnforceSysBin setting
+# Produce ROM directory listing
+# Identify the ROM image name
+sub cleaning_phase
+{	
+	my $romname;
+	my $skippingBlanks=0;
+	undef @newobydata;
+	
+    if($opt_v)
+    {
+	  my $logWin = $thisdir."logwin.oby";
+	  my $logLinux = $thisdir."loglinux.oby";
+	  unlink($logWin);
+	  unlink($logLinux);
+	  open LOGWIN, ">$logWin" or die("* Can't create $logWin\n");
+	  open LOGLINUX, ">$logLinux" or die("* Can't create $logLinux\n");
+    }	
+
+	foreach $line (@obydata)
+	{
+		track_source($line);
+		if ($line=~/^REM (defined|handled)/)
+		{
+			next;
+		}
+		if ($line=~/^# (\d+) "(.*)"/)
+		{
+			next;
+		}
+		#
+		# Blank line compression
+		#
+		if ($line=~/^\s*$/)
+		{
+			if ($skippingBlanks==1)
+			{
+				next;
+			}
+			$skippingBlanks=1;
+		}
+		else
+		{
+			$skippingBlanks=0;
+		}
+		#
+		# Track ROMNAME, allowing overrides
+		#
+		if ($line=~/romname\s*[=\s]\s*"?(\S+)\.(\S+)"?\s*/i)
+		{
+			if ($romname ne "" && $opt_o eq "")
+			{
+				print_source_error("Overrides previous ROM name $romname");
+			}
+			$rombasename = $1;
+			$romname = "$1.$2";
+			if ($opt_workdir)
+			{
+				$rombasename = $thisdir.$rombasename;
+				$romname = $thisdir.$romname;
+			}
+			next;
+		}
+		#
+		# ROM directory listing
+		#
+		    my $newline = reformat_line($line);
+	    if( ($newline !~ /^\s*TIME\s*=\s*/i)
+  	      &&($newline !~ /^\s*volume\s*=.*/i)
+	      &&($newline !~ /^\s*kerneltrace\s*=.*/i))
+	    {
+	        my $tmpline = $newline;
+	        if(&is_windows)
+	        {
+	          $newline =~ s-\/-\\-go;
+	          if($opt_v)
+	          {
+                print LOGWIN $newline;
+	            $tmpline =~ s-\\-\/-go;
+	            print LOGLINUX $tmpline;
+	          }
+	        }else #unix os
+	        {
+	          $newline =~ s-\\-\/-go;
+	          if($opt_v)
+	          {
+	            print LOGLINUX $newline;
+	            $tmpline =~ s-\/-\\-go;
+	            print LOGWIN $tmpline;
+	          }
+	        }
+	    }
+	    
+		push @newobydata, $newline;
+	}
+	if($opt_v)
+	{
+	  close LOGWIN;
+	  close LOGLINUX;
+	}
+	
+	exit(1) if($errors && $strict);
+	# Handle ROMNAME and possible -o override
+	if ($opt_o ne "")
+	{
+		if ($opt_workdir && $opt_o !~ /^[\\\/]/ && $opt_o !~ /^.:/)
+		{
+			$opt_o = $thisdir.$opt_o;
+		}
+		if (&is_windows)
+		{
+			$opt_o =~ s-\/-\\-g;
+		}else
+		{
+			$opt_o =~ s-\\-\/-g;
+		}
+		$romname=$opt_o;
+		if ($opt_o=~/(\S+)\.(\S+)/)
+		{
+			$rombasename=$1;
+		}
+		else
+		{
+			$rombasename=$romname;
+		}
+	}
+	if(!$onlysmrimage)
+	{
+		unshift @newobydata, "romname=$romname\n";	# first line of final OBY file
+	}
+	@obydata = @newobydata;
+	
+	print "* Removing previous image and logs...\n";
+	unlink glob("$rombasename.*");
+	
+	my $obyrecordline;
+	if($createspi) {# section added to mark SPI files in core images as hidden (if appropriate) if extension ROMs are being produced
+		my $imagenum=0;
+		my $count=0;
+		foreach my $line (@obydata) { # fill @hidearray with all file= or data= entries from @obydata, recording which image they are in and their target destination
+			if($line =~/^\s*(file|data)\s*=\s*(\S+)\s+(\S+)\s*$/gi) {
+				$hidearray[$count] = {rom=>$imagenum, type=>$1, dest=>$3};
+				$hidearray[$count]{dest} =~s/\"//g;
+				$count++;
+			} elsif($line =~/^\s*REM\s+ROM_IMAGE\[(\d)\]\s*$/i ) {
+				$imagenum=$1;
+			}
+		}
+		for(my $i=0;$i<8;$i++) { #loop to mark files in @hidearray as hidden, does not add the hide= lines to the obey files
+			if($romimage[$i]{extension}) {
+				mark($i-1,$i);
+			}
+		}
+		undef @newobydata;
+	
+		my $hideflag=0; # is set to 1 if there are files which need to be hidden, determines whether to run next section of code 
+		for(my $i=0;$i<scalar @hidearray;$i++) {
+			if($hidearray[$i]{hide}==1) {
+				$hideflag=1;
+			}
+		}
+	
+		my $obeyrom=0;	
+		if($hideflag) { #if there exist files which need hiding
+			my $i=0;
+			my $exitflag=0;
+			$obyrecordline=0;
+			for(;$obyrecordline<scalar @obydata && !$exitflag;) { # nested for loops produce new obey file in @newobydata, including hide= lines
+				print "Line = $obyrecordline $i " . scalar @hidearray . "\n";
+				if($i==scalar @hidearray) {
+					$exitflag=1;
+				}
+				for(;$i<scalar @hidearray;$i++) {
+					if($hidearray[$i]{hide}==1) {
+						my $rom=$hidearray[$i]{rom};
+						my $destination=$hidearray[$i]{dest};
+						while($obeyrom<$rom && $obyrecordline<scalar @obydata) { #pushes lines to @newobydata until specified rom is reached
+							push @newobydata, $obydata[$obyrecordline];
+							if($obydata[$obyrecordline] =~/^\s*REM\s+ROM_IMAGE\[(\d)\]\s*$/i){
+								$obeyrom=$1;
+							}
+							$obyrecordline++;
+						}
+						my $flag=1; #get to here when $obeyrom==$rom
+						while($flag && $obyrecordline<scalar @obydata) {
+							$destination=~s|\\|/|g;
+							my $obyline=$obydata[$obyrecordline];
+							$obyline=~s|\\|/|g;			
+							if($obyline=~m/$destination/) { # if the line in the obeyfile matches the destination of the specified spi file then a hide= line is added before the spi file's data= line
+								push @newobydata, "hide=$hidearray[$i]{dest}\n$obydata[$obyrecordline]";
+								$obyrecordline++;
+								$flag=0;
+							} else {
+								push @newobydata, $obydata[$obyrecordline++];
+							}
+						}
+					}
+				}
+			}		
+		}		
+		while($obyrecordline< scalar @obydata) { # add the rest of the lines from @obydata to @newobydata
+			push @newobydata, $obydata[$obyrecordline++];
+		}
+		@obydata=@newobydata;
+		undef @newobydata;	
+	}
+	dump_obydata("tmp9.oby", "result of cleaning phase") if ($opt_v);
+}
+
+
+#----------------------------------------------------------------------------------
+#
+# Divide the oby file into multiple sections - one for each rom image - ready
+# for the appropriate rom builder.
+#
+
+sub generate_romheader
+{
+	my ($idx) = @_;
+	if ($romimage[$idx]{xip} ne 0)
+	{ 
+		my $header = "\n";
+		if ($romimage[$idx]{extension})
+		{
+			$header = "extensionrom=$rombasename.$romimage[$idx]{name}.img\n";
+			$header .= "romsize=$romimage[$idx]{size}\n\n";
+		}
+		return $header; 
+	}
+	# non-xip
+	my $header;
+	if ($romimage[$idx]{extension})
+	{
+		$header =  "extensionrofs=$rombasename.$romimage[$idx]{name}.img\n";
+		$header .= "rofssize=$romimage[$idx]{size}\n\n";
+	}
+	else
+	{
+		$header="rofsname=$rombasename.$romimage[$idx]{name}.img\n";
+		$header .= "rofssize=$romimage[$idx]{size}\n\n";
+	}
+	return $header;
+}
+
+#----------------------------------------------------------------------------------
+# Dump OBY file.
+#
+# Creates final OBY file.
+#
+sub create_dumpfile
+{
+	my $romimageidx;
+	my $smrimageidx = 0;
+	my $dumpfile="$rombasename";
+	$romimage[0]{obeyfile}=$dumpfile;
+	$dumpfile .= ".oby";
+	unlink($dumpfile);
+	if($rombasename && !$onlysmrimage)
+	{
+		open DUMPFILE, ">$dumpfile" or die("* Can't create $dumpfile\n");
+		print "* Writing $dumpfile - final OBY file\n";
+		$romimageidx=0;
+		print DUMPFILE generate_romheader($romimageidx);
+	}
+	foreach $line (@obydata)
+	{
+		if ($line =~ /^\s*REM ROM_IMAGE\[(\d+)\]\s+(.*)$/i)
+		{
+			$romimageidx=$1;
+			if ($romimage[$romimageidx]{extension} eq '0')
+			{ # next rom oby file
+				close DUMPFILE;
+				$dumpfile="$rombasename.$romimage[$romimageidx]{name}";
+				$romimage[$romimageidx]{obeyfile}=$dumpfile;
+				$dumpfile .= ".oby";
+				open DUMPFILE, ">$dumpfile" or die("* Can't create $dumpfile\n");		
+				print "* Writing $dumpfile - final OBY file\n";
+				# header
+				print DUMPFILE $line;
+				print DUMPFILE generate_romheader($romimageidx);
+				next;
+			}
+			else
+			{ # extension
+				# header
+				print DUMPFILE $line;
+				print DUMPFILE generate_romheader($romimageidx);
+				next;
+			}
+		}
+		# write data drive oby file.
+		elsif ($line =~ /^\s*REM DATA_IMAGE\[(\d+)\]\s+(.*)$/i)
+		{
+				my $dataimageidx=$1;
+				close DUMPFILE;
+				$dumpfile="$datadriveimage[$dataimageidx]{name}";
+				$datadriveimage[$dataimageidx]{obeyfile}=$dumpfile;
+				$dumpfile .= ".oby";
+				open DUMPFILE, ">$dumpfile" or die("* Can't create $dumpfile\n");		
+				print "* Writing $dumpfile - intermediate OBY file\n";
+				# header
+				print DUMPFILE $line;
+				print DUMPFILE generate_datadriveheader($dataimageidx,\@datadriveimage);
+				push(@dataDriveFileList,$dumpfile);
+				next;
+		}
+		elsif ($line =~ /^\s*REM SMR_IMAGE\s*$/i)
+		{
+			close DUMPFILE;
+			$dumpfile = $obeyFileList[$smrimageidx];
+			$smrimageidx++;
+			$dumpfile .= ".oby";
+			open DUMPFILE, ">$dumpfile" or die("* Can't create $dumpfile\n");
+			print "*Writing $dumpfile - intermediate OBY file\n";
+			print DUMPFILE $line;
+			push(@smrImageFileList, $dumpfile);
+			next;
+		}
+		print DUMPFILE $line;
+	}
+	close DUMPFILE;
+}
+
+#----------------------------------------------------------------------------------
+#
+# Full ROM directory listing - use case-insensitive sort
+#
+sub create_dirlisting
+{
+	if($rombasename)
+	{
+		print "* Writing $rombasename.dir - ROM directory listing\n";
+		open DIRFILE, ">$rombasename.dir" or die("* Can't create ROM directory listing\n");
+	
+		my $file;
+		my $prevdir = "";
+		foreach $file (sort {uc($a) cmp uc($b)} keys %romfiles)
+		{
+			my $dir = substr $file,0,rindex($file, "\/");
+			if (uc $dir ne uc $prevdir)
+			{
+				$prevdir = $dir;
+				print DIRFILE "\n";
+			}
+	
+			my @sources = split /\n/,$romfiles{$file};
+			printf DIRFILE "%-40s\t%s\n", $file, shift @sources;
+			while (@sources)
+			{
+				printf DIRFILE "%39s+\t%s\n", "", shift @sources;
+			}
+		}
+		close DIRFILE;
+	}
+}
+
+#----------------------------------------------------------------------------------
+#
+# Suppress Rom/Rofs/DataDrive Image creation if "-noimage" option is provided.
+#
+
+sub suppress_image_generation
+{
+	if($noimage) 
+	{
+		&tidy_exit;		
+	}
+}
+
+#----------------------------------------------------------------------------------
+# Execute rombuild & maksym for each final XIP OBY file
+# Execute rofsbuild for each non-XIP oby file
+#
+
+sub run_rombuilder
+{
+	my ($command, $obeyfile, $logfile) = @_;
+	$command .= " $obeyfile.oby";
+	#CR1258 test cases are depending on the following output.
+	print "* Executing $command\n" if ($opt_v);
+
+	open DATA, "$command 2>&1 |"   or die "Couldn't execute command: $command";
+	while ( defined( my $line = <DATA> ) ) {
+	chomp($line);
+	print "$line\n";
+	}
+	close DATA;
+
+	if ($? != 0)
+	{
+		$errors++;
+		$command =~ /^\s*(\S+)\s+-slog/;
+		print "* $1 failed\n";
+	}
+	else
+	{
+		push(@romImages,$obeyfile.".img");
+	}
+	print "\n";
+	rename "$logfile","$obeyfile.log" or die("* Can't rename $logfile\n");
+	exit(1) if ($errors);
+}
+
+#----------------------------------------------------------------------------------
+# ROMBUILD AND ROFSBUILD
+#
+# Invokes rombuild and rofsbuild.
+# Creates .log, .symbol files.
+#
+sub invoke_rombuild
+{
+	#For CR1258, -compress command line option is introduced, and it's being handled as following
+	my $rom_compression_type;
+	if($opt_compression_type eq ALLSECTIONS)
+	{
+		$rom_compression_type = "-compress";
+	}
+	elsif($opt_compression_type eq PAGEDSECTION)
+	{
+		$rom_compression_type = "-compress=paged";
+	}
+	elsif($opt_compression_type eq UNPAGEDSECTION)
+	{
+		$rom_compression_type = "-compress=unpaged";
+	}
+	else
+	{
+		$rom_compression_type = "";
+	}
+
+	#Compose command line options for Cache.
+	my $cache_options;
+	if($opt_cache == 1)
+	{
+		$cache_options = "-cache ";
+	}
+	if($opt_nocache == 1)
+	{
+		$cache_options .= "-nocache ";
+	}
+	if($opt_cleancache == 1)
+	{
+		$cache_options .= "-cleancache";
+	}
+	
+	my $rombuild;
+	if(!$geninc)
+	{
+		$rombuild = "rombuild -slog $rom_compression_type $logLevel $lowMem $opt_jobs";
+	}
+	else
+	{
+		$rombuild = "rombuild -slog $rom_compression_type -geninc $logLevel $lowMem $opt_jobs";
+	}
+	if($gendep)
+	{
+		$rombuild .= " -gendep";
+	}
+	$rombuild .= " -k" if($opt_k);
+	my $rofsbuild = "rofsbuild -slog $logLevel $lowMem $opt_jobs $cache_options";
+	foreach my $arg (keys %rombuildOptions)
+	{
+		$rombuild .= " $arg";
+	}
+	$rofsbuild .= " -k" if($opt_k);        
+	for (my $romidx=0; $romidx<8; $romidx++)
+	{
+		my $obeyfile=$romimage[$romidx]{obeyfile};
+		my $xip=$romimage[$romidx]{xip};
+		my $compress=$romimage[$romidx]{compress};
+		my $uncompress=$romimage[$romidx]{uncompress};
+		if ($obeyfile)
+		{
+			if(!defined $opt_compression)
+			{
+				if ($compress ne 0)
+				{
+					$compress=" -compress";
+				}
+				elsif($uncompress ne 0)
+				{
+					$compress=" -uncompress";
+				}
+ 				elsif($compress eq 0)
+ 				{
+ 					$compress=" ";
+				}
+			}
+			else
+			{
+				$compress = $opt_compression;
+				$compress =~m/\s-(compression)(method)\s(none|inflate|bytepair)/;
+				print "* ".$1." ".$2.": ".$3;
+			}                        
+			if ($xip)
+			{
+				is_existinpath("rombuild", romutl::DIE_NOT_FOUND);
+				$rombuild .= " -symbols" unless($nosymbols) ;
+				run_rombuilder($rombuild.$compress, $obeyfile, "ROMBUILD.LOG");
+			}
+			else
+			{
+				# efficient_rom_paging.pm can move everything to core rom.
+				# If that is the case, don't run rofsbuild at all to avoid errors.
+			#	use constant TRUE => 1;
+			#	use constant FALSE => 0;
+				my $run_rofs_build = 0;
+				
+				open OBYFILE, "$obeyfile.oby";
+				for (<OBYFILE>)
+				{
+					if (is_oby_statement($_))
+					{
+						$run_rofs_build = 1;
+						last;
+					}
+				}
+				close OBYFILE;
+				if ($run_rofs_build)
+				{
+					is_existinpath("rofsbuild", romutl::DIE_NOT_FOUND);
+					if(!$nosymbols)
+					{
+						$rofsbuild .= " -symbols";
+					}			
+					run_rombuilder($rofsbuild.$compress, $obeyfile, "ROFSBUILD.LOG");
+				}
+			}
+			unlink "rombuild.log";
+			unlink "maksym.out";
+		}
+	}
+}
+
+#-------------------------------------------------------
+# Subroutine: check if current statement is a valid oby statement
+#
+sub is_oby_statement
+{
+	my ($li) = @_;
+	if ($li =~ /\s*data\s*=/) { return 1;}
+	if ($li =~ /\s*file\s*=/) { return 1;}
+	if ($li =~ /\s*dll\s*=/) { return 1;}
+	if ($li =~ /\s*secondary\s*=/) { return 1;}
+
+	return 0;
+}
+
+#-------------------------------------------------------
+# Subroutine: convert possibly absolute path into relative path
+#
+
+sub relative_path
+{
+    my ($arg) = @_;
+    return $arg if ($arg !~ /^\//);	# not an absolute path
+    if ($uppath eq "x")
+	{
+		$uppath=cwd;
+		$uppath=~s-\\-\/-go;		    # separator from Perl 5.005_02+ is forward slash
+		$uppath=~s-^(.*[^\/])$-$1\/-o;	    # ensure path ends with a backslash
+		$uppath=~s-\/([^\/]+)-\/..-og;	    # convert directories into ..
+		$uppath=~s-^.:\/--o;		    # remove drive letter and leading backslash
+	}
+    $arg=~s-^\/--o;	# remove leading backslash from original path
+    return "$uppath$arg";
+}
+
+# Returns the global @obydata reference to support external tool invocation.
+sub getOBYDataRef{
+	return \@obydata;
+}
+
+#Match the blank or the comment
+sub isobystatement
+{
+	my ($l) = @_;
+	if ($l !~ /=/) { 
+		return 0;
+	}
+	return 1;
+}
+
+#Match the data statements
+sub isdatastatement {
+	my ($l) = @_;
+	if ($l !~ /data=/) 
+	{ 
+		return 0;
+	}
+	return 1;
+}
+
+#Match the spidata statements
+sub isspidatastatement {
+	my ($l) = @_;
+	if ($l !~ /spidata=/) { 
+		return 0;
+	}
+	return 1;
+}
+
+#Match the executable statements
+sub isexecutablefile {
+	my ($l) = @_;
+	if (($l=~/file=/)||($l=~/dll=/)||($l=~/primary=/)||($l=~/secondary=/)||($l=~/variant=/)||($l=~/device=/)||($l=~/extension=/)){ 
+		return 1;
+	}
+	return 0;
+}
+
+#Match the directory metadata statements
+sub isdirectorymetadata {
+	my ($l) = @_;
+	if (($l=~/hide=/) || ($l=~/rename=/) || ($l=~/alias=/)){ 
+		return 1;
+	}
+	return 0;
+}
+
+#Match the bitmap statements
+sub isbitmap {
+	my ($l) = @_;
+	if ($l=~/bitmap=/){ 
+		return 1;
+	}
+	return 0;
+}
+
+
+#Match the aif file
+sub isaif {
+	my ($l) = @_;
+	if ($l=~/(.*)\.aif/){ 
+		return 1;
+	}
+	return 0;
+}
+
+
+#Match the resource file
+sub isresource {
+	my ($l) = @_;
+	if ($l=~/(.*)\.rsc/){ 
+		return 1;
+	}
+	return 0;
+}
+
+#Returns the executable extensions
+sub executableextension {
+	my ($l) = @_;
+	if ($l=~/file=(.*)\.exe$/){ 
+		return "exe";
+	}
+	elsif ($l=~/file=(.*)\.dll$/){ 
+		return "dll";
+	}
+	elsif ($l=~/file=(.*)\.ldd$/){ 
+		return "ldd";
+	}
+	elsif ($l=~/file=(.*)\.fsy$/){ 
+		return "fsy";
+	}
+}
+
+
+#Returns all 3 UIDS
+sub executabletype {
+	my ($l) = @_;
+	my $uid1;
+	my $uid2;
+	my $uid3;
+	if ($l=~/uid1\s(0x[\d]*)/){ 
+		$uid1=$1;
+	}
+	if ($l=~/uid2\s(0x[\d]*)/){ 
+		$uid2=$1;
+	}
+	if ($l=~/uid3\s(0x[\d]*)/){ 
+		$uid3=$1;
+	}
+	
+	return $uid1." ".$uid2." ".$uid3."\n";
+}
+
+
+#Return source file name
+sub getSourceFile {
+	my ($line) = shift;
+	if ($line=~/(\w*=)(\S*\s+\S*)\s+(\S*)\s+(\S*)?/) {
+		return $2;
+	}
+}
+
+#Return destination file name
+sub getDestFile{
+	my ($line) = shift;
+	if ($line=~/(\w*=)(\S*\s+\S*)\s+(\S*)\s+(\S*)?/) {
+		return $3;
+	}
+}
+
+#Return the obycommand attributes
+sub getOBYAttributes{
+	my ($line) = shift;
+	if ($line=~/(\w*=)(\S*\s+\S*)\s+(\S*)\s+(\S*)?/) {
+		return $4;
+	}
+}
+
+#Return the hardware variant delimiter
+sub getHardwareVariant{
+	my ($line) = shift;
+	if ($line=~/(\w*[0x[\d]*]=)/) {
+		return $1;
+	}
+}
+
+#Return the hardware variant delimiter
+sub getObyCommand{
+	my ($line) = shift;
+	if ($line=~/^[data=]/) {
+		return "data";
+	}
+
+	if ($line=~/^[file=]/) {
+		return "file";
+	}
+
+	if ($line=~/^[dll=]/) {
+		return "dll";
+	}
+}
+
+# Initialize the symbol info within the given DLL.
+sub AddDllDataInfo
+{
+	my ($line) = @_;
+	# syntax "<DLLname>@<symbolname> <newvalue>"
+	if($line =~ /^\s*(\S+)\s*\@\s*(\S+)\s+(\S+)\s*$/)
+	{
+		my $dllName = lc ($1);
+		my $symbolname = $2;
+		my $intVal = $3;
+		my $newVal = 0;
+		if($intVal =~ /^0x([0-9a-fA-F]+)$/){
+		$newVal = hex($1);
+		}
+		elsif($intVal =~ /^(-\d+)$/ or $intVal =~ /^(\d+)$/){		
+			$newVal = $1;
+		}
+		else{
+ 			print "ERROR: Invalid patchable value at \"$line\"\n";
+ 			$errors++ if($strict);
+ 			return 1;
+		}
+		$symbolname =~ s/:(\d+)\[(0x)?[0-9a-f]+\]$//i;	# Remove array element specification (:ELEMENT_BIT_SIZE[INDEX]) to get symbol name
+
+		my $DllMapRef = \%{$DllDataMap{$dllName}};
+
+		my %DllSymInfo = ();
+		$DllSymInfo{ordinal}	= undef;
+		$DllSymInfo{dataAddr}	= undef;
+		$DllSymInfo{size}		= undef;
+		# We don't store the value here, since patchdata can be used on an array,
+		# in which case we'll create another one of these, and lose the value.
+		# Instead, the value is retrieved by re-parsing the command line later.
+		$DllSymInfo{lineno}		= $sourceline;
+		$DllSymInfo{obyfilename}= $sourcefile;
+
+		$DllMapRef->{$symbolname} = \%DllSymInfo;
+		return 0;
+	}
+		return 1;
+}
+
+sub process_dlldata
+{
+	if(!$patchDataStmtFlag){
+		return;
+	}
+	my $symbolTblEntry;
+
+	foreach my $dll (keys %DllDataMap){
+		my $DllMapRef = $DllDataMap{$dll};
+		if(!$DllMapRef->{srcfile}){
+		next;
+		}
+		my $aDllFile = $DllMapRef->{srcfile};
+		my $SymbolCount = scalar ( keys %{$DllMapRef}) - 2; #The map has 'srcfile' and 'dstpath' special keys besides the symbols.
+
+		my $DllSymMapRef;
+
+		my @BPABIPlats = &get_bpabiplatlist;
+		my $matchedSymbols = 0;
+		my $globalSyms = 0;
+		my @platlist = &get_platlist;
+		my $platName;
+		my $rootPlatName;
+		my $plat = "armv5";				
+		$plat = &get_abiv2mode() ? $plat."_abiv1" : $plat."_abiv2";		
+
+		foreach my $plat(@platlist) 
+		{
+			if(($aDllFile =~ /[\/\\]($plat)[\/\\]/i) or ($aDllFile =~ /[\/\\]($plat\.\w+)[\/\\]/i ))
+			{
+				$platName = $1;
+				last;
+			}
+		}		
+		$rootPlatName =	&get_platcustomizes($platName) ? &get_platroot($platName) : $platName;
+		
+		# Map files will be referred for all ARM platforms, 
+		# and for BSF platforms which cutomizes ARM platforms.
+		if($rootPlatName =~ /^armv5|$plat$/i){
+			my $mapfile = "${aDllFile}.map";
+			
+			open MAPFILE, "$mapfile" or die "Can't open $mapfile\n";
+			while(<MAPFILE>){
+			my $line = $_;
+
+				#Ignore Local symbols.
+				if(!$globalSyms){
+					if($line =~ /Global Symbols/){
+						$globalSyms = 1;
+						next;
+					}
+					else{
+						next;
+					}
+				}
+
+				$symbolTblEntry = $line;
+				if($symbolTblEntry =~ /\s*(\S+)(?:\s+\(EXPORTED\))?\s+(\S+)\s+(\S+)\s+(\S+)\s+(.*)/){
+					my $symbol		= $1;
+					my $symbolValue = $2;
+					my $data		= $3;
+					my $symbolSz	= $4;
+					if(!exists $DllMapRef->{$symbol}){
+						next;
+					}
+					$DllSymMapRef = $DllMapRef->{$symbol};
+					if($data =~ /Data/){
+					# Valid
+					}
+					else {
+					#	Invalid to patch a code symbol.
+						print( "$DllSymMapRef->{obyfilename}($DllSymMapRef->{lineno}): Warning: $symbol is not a data Symbol.Ignoring patch statement.\n");
+						$errors++ if($strict);
+						$DllMapRef->{$symbol} = undef;
+						next;
+					}
+
+					
+					# Record the address and the size of the symbol.
+					$DllSymMapRef->{dataAddr} = $symbolValue;
+					$DllSymMapRef->{size} = $symbolSz;
+
+
+					$matchedSymbols++;
+					if( $matchedSymbols >= $SymbolCount){
+						last;
+					}
+				}
+			}
+			close MAPFILE;
+		}
+		# DSO files will be referred for BPABI platforms(excluding ARM platforms),
+		# and for BSF platforms which cutomizes BPABI platforms.
+		else {
+			my $abiDir = undef;
+			foreach my $bpabi (@BPABIPlats){
+				if($rootPlatName =~ /^$bpabi$/i){
+					$abiDir = $platName;
+					last;
+				}
+			}
+
+			if(!defined $abiDir){
+				print("Can't locate the map or proxy dso file for $aDllFile\n");
+				$errors++ if($strict);
+				next; #go to the next patch dll data statement
+			}
+			if( $aDllFile =~ /(.*)\.[^.]+$/ ){
+				my $proxydsofile = "$1.dso";
+				$proxydsofile =~ s-$abiDir\/(.*)\/-armv5\/lib\/-ig;
+				open PIPE, "getexports -d $proxydsofile|" or die "Can't open file $proxydsofile\n";
+				while (<PIPE>){
+					my $line = $_;
+					if($line =~ /\s*(\S+)\s+(\d+)\s+((\S+)\s+(\d+))?/){
+						my $symbol = $1;
+						my $ordinal = $2;
+						my $data = $3;
+						my $symbolSz = $5;
+
+						if(!$data){
+							next;
+						}
+						if(!exists $DllMapRef->{$symbol}){
+							next;
+						}
+
+						$DllSymMapRef = $DllMapRef->{$symbol};
+
+						# Record the ordinal and the size of the symbol.
+						$DllSymMapRef->{ordinal} = $ordinal;
+						$DllSymMapRef->{size} = $symbolSz;
+						$matchedSymbols++;
+						if( $matchedSymbols >= $SymbolCount){
+						last;
+						}
+					}
+				}
+
+				close PIPE;
+			}
+		}
+	}
+	exit(1) if ($errors && $strict ) ;
+}
+
+# make sure that all the absolute feature variant paths include a
+# drive letter. This is required because cpp will not work with
+# absolute paths starting with slashes.
+sub addDrivesToFeatureVariantPaths
+{
+	return unless $featureVariant{'VALID'};
+
+	my $current = &get_epocdrive;
+	my $drive = $1 if ($current =~ /^(.:)/);
+
+	# pre-include file
+	my $HRH = $featureVariant{'VARIANT_HRH'};
+	$featureVariant{'VARIANT_HRH'} = $drive . $HRH if ($HRH =~ /^[\\\/]/);
+
+	# ROM include path
+	my $dirRef = $featureVariant{'ROM_INCLUDES'};
+	return unless $dirRef;
+	my $i = 0;
+
+	foreach my $dir (@$dirRef)
+	{
+		$$dirRef[$i] = $drive . $dir if ($dir =~ /^[\\\/]/);
+		$i++;
+	}
+}
+sub create_smrimage
+{
+	if($needSmrImage)
+	{
+		foreach my $oby (@obeyFileList)
+		{
+			is_existinpath("rofsbuild", romutl::ERROR_NOT_FOUND);
+			my $command = "rofsbuild -slog -smr=$oby.oby";
+			print "* Executing $command\n" if($opt_v);
+			system($command);
+			if($? != 0)
+			{
+				print("* ROFSBUILD failed to generate SMR IMAGE\n") if($opt_v);
+			}
+			else
+			{
+				push(@smrImageFileList, $oby.".img");
+			}
+		}
+	}
+	if(@smrImageFileList)
+	{
+		print "\n";
+		print "-------------------------------------------------------\n";
+		print "| List of file(s) generated pertaining to SMR image |\n";
+		print "-------------------------------------------------------\n";
+		my $arraySize = scalar(@smrImageFileList);
+		for(my $i=0; $i < $arraySize; $i++)
+		{
+			my $element = shift(@smrImageFileList);
+			my $size = -s $element;
+			print "Size = ".$size." bytes"."\t"."File = ".$element."\n";
+		}
+	}
+	foreach my $errSmr (keys(%smrNameInfo))
+	{
+		if($smrNameInfo{$errSmr} > 1)
+		{
+			print "\n SMR image: $errSmr.img creating error for duplicated names!\n";
+		}
+	}
+	if($smrNoImageName)
+	{
+		print "\n SMR image creating error for empty image name!\n";
+	}
+}
+
+sub checkcase()
+{
+	if (&is_windows)
+	{
+		my @checkcase_obydatatemp = @obydata;
+
+		# call the phase without external tools.
+		plugin_phase();
+		multlinguify_phase();
+		#spi_creation_phase(); #spi creation phase will delete some lines, so do not call this phase
+		suppress_phase();
+		process_dlldata();
+		bitmap_aif_converison_phase();
+
+		my $checkcase_log = "checkcase.log";
+		unlink $checkcase_log;
+		
+		open CHECKCASELOG, ">$checkcase_log" or die("* Can't create $checkcase_log\n");
+		my @checkcase_lines = @obydata;
+		my %checkcase_macro;
+		my @checkcase_macrodir;
+		my $checkcase_line;
+		print CHECKCASELOG "======================Macro check part:======================\n";
+		foreach $checkcase_line (@checkcase_lines)
+		{
+			track_source($checkcase_line);
+			$checkcase_line =~ s-\/-\\-g;
+			$checkcase_line =~ s-\\\\-\\-g;
+			if ($checkcase_line =~ /^\s*REM\s*(re)?defined\s*(\w*)\s*as\s*(\S+)/)
+			{
+				my $checkcase_macrocontent = $3;
+				my $checkcase_macroname = $2;
+				if ($checkcase_macrocontent =~ /[a-zA-Z]/)
+				{
+					$checkcase_macro{$checkcase_macroname} = $checkcase_macrocontent;
+					checkcase_macro(\@checkcase_macrodir, $checkcase_macroname, $checkcase_macrocontent);
+				}
+			}
+		}
+		print CHECKCASELOG "======================Macro check part end======================\n\n";
+		print CHECKCASELOG "======================File check part:======================\n";
+		foreach $checkcase_line (@checkcase_lines)
+		{
+			if ($checkcase_line =~ /^\s*REM\s*.*/)
+			{
+				next;
+			}
+			if ($checkcase_line =~ /^\s*#\s*\d+\s*\"(\S+)\"\s*\d*\s*$/) #oby filename
+			{
+				my $checkcase_whichfile = $1;
+				checkcase_obyfilename($checkcase_whichfile);
+				track_source($checkcase_line);
+			}elsif ($checkcase_line =~ /^\s*\S+\s*=\s*"([^"]+)"\s+\S*\s*/ 
+					 || $checkcase_line =~ /^\s*\S+\s*=\s*(\S+)\s+\S*\s*/) #oby content file name
+			{
+				my $checkcase_pcsidefile = $1;
+				checkcase_pcsidefilename(\@checkcase_macrodir, $checkcase_pcsidefile);
+			}
+		}
+		print CHECKCASELOG "======================File check part end======================\n";
+		close CHECKCASELOG;
+		
+		@obydata = @checkcase_obydatatemp;
+	}else
+	{
+		print "WARNING: checkcase option is only valid on windows.\n";
+	}
+}
+
+sub checkcase_macro()
+{
+	my $macrodir = shift;
+	my $name = shift;
+	my $content = shift;
+	
+	if ($content =~ /epoc32/i && (-d $content))
+	{
+		my $realdir = `directory.bat $content`;
+		$realdir =~ s/\s+$//g;
+		$realdir =~ s/^\s*\w://g if ($content !~ /^\w:/);
+		$realdir =~ s/\\$//g if ($content !~ /\\$/);
+		$realdir .= "\\" if ($content =~ /\\$/ && $realdir !~ /\\$/);
+		$sourcefile =~ s/\//\\/g;
+		$sourcefile =~ s/\\\\/\\/g;
+		if ($realdir ne $content)
+		{
+			print CHECKCASELOG "check case: macro name is $name\n";
+			print CHECKCASELOG "WARNING: macro case is not equal to real.\n";
+			print CHECKCASELOG "file name is $sourcefile\n";
+			print CHECKCASELOG "current is $content\n";
+			print CHECKCASELOG "expect  is $realdir\n\n";
+			checkcase_convert($sourcefile, $content, $realdir);
+		}
+		$content =~ s-\\-\\\\-g;
+		push @$macrodir, $content;
+	}else
+	{
+		if($name eq "PLATFORM_NAME")
+		{
+			$content =~ s-\\-\\\\-g;
+			$content =~ s-\.-\\\.-g;
+			$checkcase_platform = $content;
+		}
+	}
+}
+
+sub checkcase_obyfilename()
+{
+	my $checkfile = shift;
+	if (-e $checkfile)
+	{
+		while ($checkfile=~s-[\\](?!\.{2}\\)[^\\]*\\\.{2}(?=\\)--go){};
+		$sourcefile =~ s/\//\\/g;
+		if ($checkfile eq $sourcefile)
+		{
+			return;		
+		}
+		my($filename, $dir, $suffix) = fileparse($checkfile);
+		
+		my $realdir = `directory.bat $dir`;
+		$realdir =~ s/\s+$//g;
+		$realdir .= "\\" if ($realdir !~ /\\$/);
+		if ($realdir ne $dir)
+		{
+			print CHECKCASELOG "check case: oby file name is $checkfile\n";
+			print CHECKCASELOG "WARNING: dir case is not equal to real.\n";
+			my $tempsrcfile = $sourcefile;
+			$tempsrcfile =~ s/\\\\/\\/g;
+			print CHECKCASELOG "file name is $tempsrcfile\n";
+			print CHECKCASELOG "current is $dir\n";
+			print CHECKCASELOG "expect  is $realdir\n\n";
+			checkcase_convert($sourcefile, $dir, $realdir);
+		}
+		
+		my $currentdir = cwd;
+		chdir "$dir";
+		my @realfile = `dir "$filename" 2>&1`;
+		my $line;
+		foreach $line (@realfile)
+		{
+			if ($line =~ /^\s*(\S+)\s+(\d{2}:\d{2})\s+(PM|AM)?\s+([\d\,])+\s+([\S]+)\s*/)
+			{
+				my $realfilename = $5;
+				my $filetemp = lc $filename;
+				my $realtemp = lc $realfilename;
+				if ($filetemp eq $realtemp && $realfilename ne $filename)
+				{
+					print CHECKCASELOG "check case: oby file name is $checkfile\n";
+					print CHECKCASELOG "WARNING: filename case is not equal to real.\n";
+					my $tempsrcfile = $sourcefile;
+					$tempsrcfile =~ s/\\\\/\\/g;
+					print CHECKCASELOG "file name is $tempsrcfile\n";
+					print CHECKCASELOG "current is $filename\n";
+					print CHECKCASELOG "expect  is $realfilename\n\n";
+					checkcase_convert($sourcefile, $filename, $realfilename);
+				}
+			}
+		}
+		chdir "$currentdir";
+	}
+}
+
+sub checkcase_pcsidefilename()
+{
+	my $macrodirs = shift;
+	my $checkfile = shift;
+	$checkfile =~ s/^\"//g;
+	$checkfile =~ s/\"$//g;
+	if (-e $checkfile)
+	{
+		while ($checkfile=~s-[\\](?!\.{2}\\)[^\\]*\\\.{2}(?=\\)--go){};
+		$sourcefile =~ s/\//\\/g;
+		my($filename, $dir, $suffix) = fileparse($checkfile);
+		if ($dir eq "\.\\")
+		{
+			$dir = cwd;
+			$dir =~ s/\//\\/g;
+			$dir .= "\\" if ($dir !~ /\\$/);
+		}
+		
+		my $realdir = `directory.bat $dir`;
+		$realdir =~ s/\s+$//g;
+		$realdir =~ s/^\s*\w://g if ($dir !~ /^\w:/);
+		$realdir .= "\\" if ($realdir !~ /\\$/);
+		my $dirtemp = $dir;
+		if ($checkcase_test)
+		{
+			my $macrodirtemp = "";
+			foreach my $macrodir (@$macrodirs)
+			{
+				if ($dirtemp =~ /^$macrodir(.*)$/)
+				{
+					$macrodirtemp = $macrodir if (length($macrodirtemp) < length($macrodir));
+				}
+			}
+			if ($macrodirtemp ne "")
+			{
+				$dirtemp =~ s/^$macrodirtemp//g;
+				$realdir =~ s/^$macrodirtemp//ig;
+			}
+		}
+		if ($realdir ne $dirtemp)
+		{
+			print CHECKCASELOG "check case: pc side file name is $checkfile\n";
+			print CHECKCASELOG "WARNING: dir case is not equal to real.\n";
+			my $tempsrcfile = $sourcefile;
+			$tempsrcfile =~ s/\\\\/\\/g;
+			print CHECKCASELOG "file name is $tempsrcfile\n";
+			print CHECKCASELOG "current is $dirtemp\n";
+			print CHECKCASELOG "expect  is $realdir\n\n";
+			checkcase_convert($sourcefile, $dirtemp, $realdir);
+		}
+		
+		my $currentdir = cwd;
+		chdir "$dir";
+		my @realfile = `dir "$filename" 2>&1`;
+		my $line;
+		foreach $line (@realfile)
+		{
+			if ($line =~ /^\s*(\S+)\s+(\d{2}:\d{2})\s+(PM|AM)?\s+([\d\,])+\s+(.+)\s*/)
+			{
+				my $realfilename = $5;
+				my $filetemp = lc $filename;
+				my $realtemp = lc $realfilename;
+				if ($filetemp eq $realtemp && $realfilename ne $filename)
+				{
+					print CHECKCASELOG "check case: pc side file name is $checkfile\n";
+					print CHECKCASELOG "WARNING: filename case is not equal to real.\n";
+					my $tempsrcfile = $sourcefile;
+					$tempsrcfile =~ s/\\\\/\\/g;
+					print CHECKCASELOG "file name is $tempsrcfile\n";
+					print CHECKCASELOG "current is $filename\n";
+					print CHECKCASELOG "expect  is $realfilename\n\n";
+					checkcase_convert($sourcefile, $filename, $realfilename);
+				}
+			}
+		}
+		chdir "$currentdir";
+	}
+}
+
+sub checkcase_convert()
+{
+	return if (!$checkcase_test);
+	
+	my $file = shift;
+	my $origin = shift;
+	my $real = shift;
+	
+	my @realfile = `dir "$file"  2>&1`;
+	my $line;
+	foreach $line (@realfile)
+	{
+		if ($line =~ /^\s*(\S+)\s+(\d{2}:\d{2})\s+(PM|AM)?\s+([\d\,])+\s+([\S]+)\s*/)
+		{
+			my $realfilename = $5;
+			$realfilename =~ s-\.-\\\.-g;
+			$file =~ s-$realfilename$--ig;
+			$realfilename =~ s-\\\.-\.-g;
+			$file .= $realfilename;
+		}
+	}
+
+	my $tempfile = $file.".temp";
+	my $usemultimacro = 0;
+	my $uses60macro_aifrsc = 0;
+	my $uses60macro_exe = 0;
+	my $uses60macro_aificon = 0;
+	my $uses60macro_resource = 0;
+	my $originwithoutext = $origin;
+	my $realwithoutext = $real;
+	if ($origin =~ /epoc32/i)
+	{
+		my $tempepocroot = $ENV{EPOCROOT};
+		$tempepocroot =~ s-\\-\\\\-g;
+		$origin =~ s/^$tempepocroot//g;
+		$real =~ s/^$tempepocroot//g;
+	}elsif ($checkcase_platform ne "" && $origin =~ /^_$checkcase_platform\_(.*)/)
+	{
+		$origin =~ s/^_$checkcase_platform\_/_PLATFORM_NAME_/g;
+		$real =~ s/^_$checkcase_platform\_/_PLATFORM_NAME_/g;
+	}elsif ($origin =~ /\S+\_reg\.rsc$/)
+	{
+		$originwithoutext =~ s/\_reg\.rsc$//g;
+		$realwithoutext =~ s/\_reg\.rsc$//ig;
+		$uses60macro_aifrsc = 1;
+	}elsif ($origin =~ /\S+\.rsc$/)
+	{
+		$originwithoutext =~ s/\.rsc$//g;
+		$realwithoutext =~ s/\.rsc$//ig;
+		$usemultimacro = 1;
+		$uses60macro_resource = 1;
+	}elsif ($origin =~ /\S+\.r01$/)
+	{
+		$originwithoutext =~ s/\.r01$//g;
+		$realwithoutext =~ s/\.r01$//ig;
+		$usemultimacro = 1;
+	}elsif ($origin =~ /\S+\.exe$/)
+	{
+		$originwithoutext =~ s/\.exe$//g;
+		$realwithoutext =~ s/\.exe$//ig;
+		$uses60macro_exe = 1;
+	}elsif ($origin =~ /\S+\_aif\.mif$/)
+	{
+		$originwithoutext =~ s/\_aif\.mif$//g;
+		$realwithoutext =~ s/\_aif\.mif$//ig;
+		$uses60macro_aificon = 1;
+	}elsif ($origin =~ /\S+\.mif$/)
+	{
+		$originwithoutext =~ s/\.mif$//g;
+		$realwithoutext =~ s/\.mif$//ig;
+		$uses60macro_aificon = 1;
+	}
+	$origin =~ s-\\-\\\\-g;
+	$origin =~ s-\.-\\\.-g;
+	
+	open (SRC, "<$file");
+	open (DST, ">$tempfile");
+	my $line;
+	while($line = <SRC>)
+	{
+		my $flag = 0;
+
+		if ($line =~ /$origin/)
+		{
+			$originwithoutext = $origin;
+			$realwithoutext = $real;
+			$flag = 1;
+		}elsif ($usemultimacro)
+		{
+			if ($line =~ /^.*=\s*MULTI_LINGUIFY\s*\(.*$originwithoutext/)
+			{
+				$flag = 1;
+			}elsif ($line =~ /^\s*S60_APP_RESOURCE\s*\(\s*$originwithoutext\s*\)/ && $uses60macro_resource)
+			{
+				$flag = 1;
+			}
+		}elsif ($uses60macro_exe)
+		{
+			if ($line =~ /^\s*S60_APP_EXE\s*\(\s*$originwithoutext\s*\)/)
+			{
+				$flag = 1;
+			}
+		}elsif ($uses60macro_aificon)
+		{
+			if ($line =~ /^\s*S60_APP_AIF_ICONS\s*\(\s*$originwithoutext\s*\)/)
+			{
+				$flag = 1;
+			}elsif ($line =~ /^\s*SCALABLE_IMAGE\s*\(.*$originwithoutext\s*\)/)
+			{
+				$flag = 1;
+			}elsif ($line =~ /^\s*S60_APP_BITMAP\s*\(\s*$originwithoutext\s*\)/)
+			{
+				$flag = 1;
+			}
+		}elsif ($uses60macro_aifrsc)
+		{
+			if ($line =~ /^\s*S60_APP_AIF_RSC\s*\(\s*$originwithoutext\s*\)/)
+			{
+				$flag = 1;
+			}elsif ($line =~ /^\s*S60_UPGRADABLE_APP_REG_RSC\s*\(\s*$originwithoutext\s*\)/)
+			{
+				$flag = 1;
+			}
+		}
+		if ($flag)
+		{
+			print CHECKCASELOG "it has been converted automatically\n";
+			print CHECKCASELOG "original  line is $line";
+			$line =~ s-$originwithoutext-$realwithoutext-;
+			print CHECKCASELOG "converted line is $line\n";
+		}
+		print DST $line;
+	}
+	close SRC;
+	close DST;
+	
+  unlink "$file";
+  rename ("$file.temp", "$file");
+}
+
+1;
--- a/imgtools/buildrom/tools/cdfparser.pm	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/cdfparser.pm	Tue Jun 29 14:52:54 2010 +0800
@@ -1,439 +1,439 @@
-#
-# Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-#
-
-# This package contains routines to read the information from the Component Description Files.
-package cdfparser;
-
-# Include Module package to use APIs to parse an XML file.
-use genericparser;
-
-require Exporter;
-@ISA=qw(Exporter);
-@EXPORT=qw(
-	CreateCDFFileBinaryMapFromDir
-	GetBinaries
-	GetCDFFileName
-	LoadCDF
-	GetDynamicDependencies
-	GetBinaryInfo
-	GetIncludedFeatureList
-	GetExcludedFeatureList
-);
-
-use strict;
-
-# Map between the CDF File Name and the corresponding list of binaries
-# This is required so that one can fetch the list of binaries for a particular CDF file.
-my %binaryCDFFileMap=();
-
-# Include Feature List
-# The list of features to be included for a given binary.
-my @includeFeatureList;
-
-# Exclude Feature List
-# The list of features to be excluded for a given binary.
-my @excludeFeatureList;
-
-# List that contains the complete information of each binary
-my %binaryInfo=();
-
-my $warning_level = 0;
-
-# Absolute path that contains the CDF Files
-my @cdfDirectories;
-
-# To extract the cdf files from the directory specified as input. The default directory is chosen if no 
-# input is specified.
-sub CreateCDFFileBinaryMapFromDir
-{
-
-	my @acdfDirList = @_;
-	# To store the list of cdf file names specified under the directory
-	my @cdfFileList;
-
-	if ((scalar @acdfDirList) != 0)
-	{
-		foreach my $acdfDir (@acdfDirList)
-		{
-			opendir DIR, "$acdfDir";
-			if(not grep /$acdfDir/i, @cdfDirectories)
-			{
-				push @cdfDirectories, $acdfDir;
-			}
-
-			push (@cdfFileList, (grep /\.cdf/i, readdir DIR));
-			foreach my $filename (@cdfFileList)
-			{
-				&CreateCDFFileBinaryMap(lc($filename), $acdfDir);
-				$binaryCDFFileMap{$filename}{path} = $acdfDir;
-			}
-		}
-	}
-}
-
-# To create a mapping between the CDF file name and the corresponding list of binaries
-sub CreateCDFFileBinaryMap
-{
-	my ($cdffilename, $aCdfDir) = @_;
-
-	if( defined $binaryCDFFileMap{$cdffilename} )
-	{
-		return;
-	}
-
-	my $path;
-	if( defined $aCdfDir)
-	{
-		$path = "$aCdfDir\\$cdffilename";
-	}
-	else
-	{
-		$path = $cdffilename;
-	}
-
-	my $rootNode = &genericparser::getRootElement($path);
-	$binaryCDFFileMap{$cdffilename}{root} = $rootNode;
-
-	my @binaryList = &genericparser::getChildElements($rootNode);
-
-	my $binaryInfoRef;
-	foreach my $binary (@binaryList)
-	{
-		my $filename = &genericparser::getAttrValue($binary, "id");
-		push @{$binaryCDFFileMap{$cdffilename}{binaries}}, $filename;
-# This is required so that one can fetch the CDF file name in which the binary is present
-		$binaryInfoRef = \%{$binaryInfo{$filename}};
-		$binaryInfoRef->{"filename"} = $cdffilename;
-	}
-}
-
-# To get the complete list of binaries present in a given CDF file
-# Input Parameter : CDF filename
-# Returns the complete list of binaries
-sub GetBinaries
-{
-	my $cdffilename = shift;
-	if (exists $binaryCDFFileMap{$cdffilename})
-	{
-		return @{$binaryCDFFileMap{$cdffilename}{binaries}};
-	}
-	else
-	{
-		return undef;
-	}
-}
-
-
-# To get the name of the CDF file that contains the input binary
-# Input Parameter : Binary Name
-# Returns the CDF file name
-sub GetCDFFileName
-{
-	my $aBinary = lc(shift);
-
-	if (exists $binaryInfo{$aBinary})
-	{
-		my $binInfo = \%{$binaryInfo{$aBinary}};
-		return $binInfo->{filename};
-	}
-	else
-	{
-		return undef;
-	}
-
-}
-
-#Loads all the specified CDF files.
-sub LoadCDF
-{
-	my @cdfFileList = @_;
-
-	foreach my $afile (@cdfFileList)
-	{
-		CreateCDFFileBinaryMap($afile);
-		my $rootNode = $binaryCDFFileMap{$afile}{root};
-
-		# Get the total list of files present in the cdf file.
-		my @binaryList = &genericparser::getChildElements($rootNode);
-
-		# Hash Reference to the hash map binaryInfo
-		my $binaryInfoHashRef;
-
-		foreach my $binaryNode (@binaryList)
-		{
-			my $fileId = &genericparser::getAttrValue($binaryNode, "id");
-			$binaryInfoHashRef = \%{$binaryInfo{$fileId}};
-			&setBinaryInfo($binaryInfoHashRef, $binaryNode);
-		}
-	}
-
-}
-
-#Sets the information of the CDF file to a hash map
-sub setBinaryInfo
-{
-	my ($aBinaryInfoRef, $aBinaryNode) = @_;
-
-	# Set the File attributes
-	$aBinaryInfoRef->{"id"}		  = &genericparser::getAttrValue($aBinaryNode, "id");
-	$aBinaryInfoRef->{"customisable"} = &genericparser::getAttrValue($aBinaryNode, "customisable");
-	$aBinaryInfoRef->{"addressable"}  = &genericparser::getAttrValue($aBinaryNode, "addressable");
-	$aBinaryInfoRef->{"compress"}	  = &genericparser::getAttrValue($aBinaryNode, "compress");
-	$aBinaryInfoRef->{"type"}	  = &genericparser::getAttrValue($aBinaryNode, "type");
-  	$aBinaryInfoRef->{"plugin_name"}  = &genericparser::getAttrValue($aBinaryNode, "plugin_name");
-  
-  	# Check for the plugin, setting the plugin type as ECOM_PLUGIN
-   
-  	if (defined $aBinaryInfoRef->{"plugin_name"})
-  	{
-  		$aBinaryInfoRef->{"IsFoundInCDF"} = 1;
-  		$aBinaryInfoRef->{"source"} = "ABI_DIR\\BUILD_DIR\\$aBinaryInfoRef->{id}";
-  		$aBinaryInfoRef->{"plugin_name"} =~ s/$aBinaryInfoRef->{plugin_name}/ECOM/;
-  	}
-  
-  	else {
-
-		# Get all the nodes of element 'file'
-		my @children = &genericparser::getChildElements($aBinaryNode);
-
-		foreach my $childNode (@children)
-		{
-			$aBinaryInfoRef->{"IsFoundInCDF"} = 1;
-
-			if (&genericparser::getElementName($childNode) eq "source")
-			{
-				$aBinaryInfoRef->{"source"} = &genericparser::getElementValue($childNode);
-			}
-
-			if (&genericparser::getElementName($childNode) eq "destination")
-			{
-				$aBinaryInfoRef->{"destination"} = &genericparser::getElementValue($childNode);
-			}
-
-			if (&genericparser::getElementName($childNode) eq "features")
-			{
-				# The children nodes will specify the list of features
-				my @aFeatureNodes = &genericparser::getChildElements($childNode);
-				foreach my $aFeatureChildNode (@aFeatureNodes)
-				{
-					# A list of features can be listed out either for supported case or for the prevented case.
-					if (&genericparser::getElementName($aFeatureChildNode) eq "supports")
-					{
-						my @aSupportedFeatureNodes = &genericparser::getChildElements($aFeatureChildNode);
-						foreach my $aSuppChildNode (@aSupportedFeatureNodes)
-						{
-							my %feat = ();
-							my $featureName = &genericparser::getAttrValue($aSuppChildNode, "name");
-							my $featureUID = &genericparser::getAttrValue($aSuppChildNode, "uid");
-							if (defined ($featureName) and ($featureName ne ""))
-							{
-								$feat{name} = $featureName ;
-								$feat{uid} = undef;
-							}
-							elsif(defined ($featureUID) and ($featureUID ne ""))
-							{
-								if(&featureparser::ValidateUIDValue($featureUID))
-								{
-									$featureUID = &featureparser::ConvertHexToDecimal($featureUID);
-									$feat{uid} = $featureUID;
-									$feat{name} = undef;
-								}
-								else
-								{
-									print "The uid value $featureUID specified for the Include feature list for the Binary, $aBinaryInfoRef->{id}, is not a valid number\n";
-								}
-							}
-							else
-							{
-								print ("Warning: Feature $featureName has both name and Uid mentioned\n") if ($warning_level < 2);
-								next;
-							}
-
-							$feat{include} = 1;
-							push @includeFeatureList, \%feat;
-					 
-						}
-					}
-					if (&genericparser::getElementName($aFeatureChildNode) eq "prevents")
-					{
-						my @aPreventedFeatureNodes = &genericparser::getChildElements($aFeatureChildNode);
-						foreach my $aPreventedChildNode (@aPreventedFeatureNodes)
-						{
-							my %feat = ();
-							my $featureName = &genericparser::getAttrValue($aPreventedChildNode, "name");
-							my $featureUID = &genericparser::getAttrValue($aPreventedChildNode, "uid");
-							if (defined ($featureName) and ($featureName ne ""))
-							{
-								$feat{name} = $featureName ;
-								$feat{uid} = undef;
-							}
-							elsif(defined ($featureUID) and ($featureUID ne ""))
-							{
-								if(&featureparser::ValidateUIDValue($featureUID))
-								{
-									$featureUID = &featureparser::ConvertHexToDecimal($featureUID);
-									$feat{uid} = $featureUID;
-									$feat{name} = undef;
-								}
-								else
-								{
-									print "The uid value $featureUID specified for the Exclude feature list for the Binary, $aBinaryInfoRef->{id}, is not a valid number\n";
-								}
-							}
-							else
-							{
-								print "Warning: Feature $featureName has both name and Uid mentioned\n" if ($warning_level < 2);
-								next;
-							}
-
-							$feat{exclude} = 1;
-							push @excludeFeatureList, \%feat;
-					 
-						}
-						push @{$aBinaryInfoRef->{"prevents"}}, (&genericparser::getElementValue($aFeatureChildNode));
-					}
-				}
-			}
-
-			if (&genericparser::getElementName($childNode) eq "dynamicdependencies")
-			{
-				# The children nodes will contain the file name.
-				my @aDynDependNodes = &genericparser::getChildElements($childNode);
-				
-				foreach my $aDynDependChildNode (@aDynDependNodes)
-				{
-					# There can be a list of binaries for dynamic dependencies
-					if (&genericparser::getElementName($aDynDependChildNode) eq "depend")
-					{
-						push @{$aBinaryInfoRef->{"depend"}}, (&genericparser::getElementValue($aDynDependChildNode));
-					}
-				}
-			}
-
-			if (&genericparser::getElementName($childNode) eq "localisation")
-			{
-				# The children nodes will contain the language code
-				my @aLocalisationNodes = &genericparser::getChildElements($childNode);
-				
-				foreach my $aLocalisationChildNode (@aLocalisationNodes)
-				{
-					# There can be a list of binaries for dynamic dependencies
-					if (&genericparser::getElementName($aLocalisationChildNode) eq "default")
-					{
-						$aBinaryInfoRef->{"default"} = &genericparser::getElementValue($aLocalisationChildNode);
-					}
-					if (&genericparser::getElementName($aLocalisationChildNode) eq "language")
-					{
-						push @{$aBinaryInfoRef->{"language"}}, (&genericparser::getElementValue($aLocalisationChildNode));
-					}
-				}
-			}
-
-			if (&genericparser::getElementName($childNode) eq "options")
-			{
-				# The children nodes will contain the option details
-				my @aOptionNodes = &genericparser::getChildElements($childNode);
-				foreach my $aOptionChildNode (@aOptionNodes)
-				{
-					if (&genericparser::getElementName($aOptionChildNode) eq "multilinguify")
-					{
-						$aBinaryInfoRef->{"multilinguify"} = &genericparser::getElementValue($aOptionChildNode);
-					}
-					if (&genericparser::getElementName($aOptionChildNode) eq "stack")
-					{
-						$aBinaryInfoRef->{"stack"} = &genericparser::getElementValue($aOptionChildNode);
-					}
-					if (&genericparser::getElementName($aOptionChildNode) eq "heapmin")
-					{
-						$aBinaryInfoRef->{"heapmin"} = &genericparser::getElementValue($aOptionChildNode);
-					}
-					if (&genericparser::getElementName($aOptionChildNode) eq "heapmax")
-					{
-						$aBinaryInfoRef->{"heapmax"} = &genericparser::getElementValue($aOptionChildNode);
-					}
-					if (&genericparser::getElementName($aOptionChildNode) eq "fixed")
-					{
-						$aBinaryInfoRef->{"fixed"} = &genericparser::getElementValue($aOptionChildNode);
-					}
-					if (&genericparser::getElementName($aOptionChildNode) eq "priority")
-					{
-						$aBinaryInfoRef->{"priority"} = &genericparser::getElementValue($aOptionChildNode);
-					}
-					if (&genericparser::getElementName($aOptionChildNode) eq "uid1")
-					{
-						$aBinaryInfoRef->{"uid1"} = &genericparser::getElementValue($aOptionChildNode);
-					}
-					if (&genericparser::getElementName($aOptionChildNode) eq "uid2")
-					{
-						$aBinaryInfoRef->{"uid2"} = &genericparser::getElementValue($aOptionChildNode);
-					}
-					if (&genericparser::getElementName($aOptionChildNode) eq "uid3")
-					{
-						$aBinaryInfoRef->{"uid3"} = &genericparser::getElementValue($aOptionChildNode);
-					}
-					if (&genericparser::getElementName($aOptionChildNode) eq "dll")
-					{
-						$aBinaryInfoRef->{"dll"} = &genericparser::getElementValue($aOptionChildNode);
-					}
-					if (&genericparser::getElementName($aOptionChildNode) eq "dlldatatop")
-					{
-						$aBinaryInfoRef->{"dlldatatop"} = &genericparser::getElementValue($aOptionChildNode);
-					}
-				}
-			}
-		}
-	}
-}
-
-# To get the complete list of information for a given binary
-# Input Parameter : Binary
-# Returns the detailed information for each binary
-sub GetBinaryInfo
-{
-	my $aBinary = shift;
-	my $aBinaryInfoHash = \%{$binaryInfo{$aBinary}};
-	if ($aBinaryInfoHash->{IsFoundInCDF})
-	{
-		return $aBinaryInfoHash;
-	}
-	return undef;
-}
-
-# To get the complete list of dynamic dependencies for a given binary
-# Input Parameter : Binary
-# Returns the complete list of dynamic dependencies
-sub GetDynamicDependencies
-{
-	my $aBinary = shift;
-
-	my $bin = \%{$binaryInfo{$aBinary}};
-
-	return \@{$bin->{"depend"}};
-}
-
-#Returns the included feature list
-sub GetIncludedFeatureList
-{
-	return \@includeFeatureList;
-}
-
-#Returns the excluded feature list
-sub GetExcludedFeatureList
-{
-	return \@excludeFeatureList;
-}
-
-1;
+#
+# Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+#
+
+# This package contains routines to read the information from the Component Description Files.
+package cdfparser;
+
+# Include Module package to use APIs to parse an XML file.
+use genericparser;
+
+require Exporter;
+@ISA=qw(Exporter);
+@EXPORT=qw(
+	CreateCDFFileBinaryMapFromDir
+	GetBinaries
+	GetCDFFileName
+	LoadCDF
+	GetDynamicDependencies
+	GetBinaryInfo
+	GetIncludedFeatureList
+	GetExcludedFeatureList
+);
+
+use strict;
+
+# Map between the CDF File Name and the corresponding list of binaries
+# This is required so that one can fetch the list of binaries for a particular CDF file.
+my %binaryCDFFileMap=();
+
+# Include Feature List
+# The list of features to be included for a given binary.
+my @includeFeatureList;
+
+# Exclude Feature List
+# The list of features to be excluded for a given binary.
+my @excludeFeatureList;
+
+# List that contains the complete information of each binary
+my %binaryInfo=();
+
+my $warning_level = 0;
+
+# Absolute path that contains the CDF Files
+my @cdfDirectories;
+
+# To extract the cdf files from the directory specified as input. The default directory is chosen if no 
+# input is specified.
+sub CreateCDFFileBinaryMapFromDir
+{
+
+	my @acdfDirList = @_;
+	# To store the list of cdf file names specified under the directory
+	my @cdfFileList;
+
+	if ((scalar @acdfDirList) != 0)
+	{
+		foreach my $acdfDir (@acdfDirList)
+		{
+			opendir DIR, "$acdfDir";
+			if(not grep /$acdfDir/i, @cdfDirectories)
+			{
+				push @cdfDirectories, $acdfDir;
+			}
+
+			push (@cdfFileList, (grep /\.cdf/i, readdir DIR));
+			foreach my $filename (@cdfFileList)
+			{
+				&CreateCDFFileBinaryMap(lc($filename), $acdfDir);
+				$binaryCDFFileMap{$filename}{path} = $acdfDir;
+			}
+		}
+	}
+}
+
+# To create a mapping between the CDF file name and the corresponding list of binaries
+sub CreateCDFFileBinaryMap
+{
+	my ($cdffilename, $aCdfDir) = @_;
+
+	if( defined $binaryCDFFileMap{$cdffilename} )
+	{
+		return;
+	}
+
+	my $path;
+	if( defined $aCdfDir)
+	{
+		$path = "$aCdfDir\/$cdffilename";
+	}
+	else
+	{
+		$path = $cdffilename;
+	}
+
+	my $rootNode = &genericparser::getRootElement($path);
+	$binaryCDFFileMap{$cdffilename}{root} = $rootNode;
+
+	my @binaryList = &genericparser::getChildElements($rootNode);
+
+	my $binaryInfoRef;
+	foreach my $binary (@binaryList)
+	{
+		my $filename = &genericparser::getAttrValue($binary, "id");
+		push @{$binaryCDFFileMap{$cdffilename}{binaries}}, $filename;
+# This is required so that one can fetch the CDF file name in which the binary is present
+		$binaryInfoRef = \%{$binaryInfo{$filename}};
+		$binaryInfoRef->{"filename"} = $cdffilename;
+	}
+}
+
+# To get the complete list of binaries present in a given CDF file
+# Input Parameter : CDF filename
+# Returns the complete list of binaries
+sub GetBinaries
+{
+	my $cdffilename = shift;
+	if (exists $binaryCDFFileMap{$cdffilename})
+	{
+		return @{$binaryCDFFileMap{$cdffilename}{binaries}};
+	}
+	else
+	{
+		return undef;
+	}
+}
+
+
+# To get the name of the CDF file that contains the input binary
+# Input Parameter : Binary Name
+# Returns the CDF file name
+sub GetCDFFileName
+{
+	my $aBinary = lc(shift);
+
+	if (exists $binaryInfo{$aBinary})
+	{
+		my $binInfo = \%{$binaryInfo{$aBinary}};
+		return $binInfo->{filename};
+	}
+	else
+	{
+		return undef;
+	}
+
+}
+
+#Loads all the specified CDF files.
+sub LoadCDF
+{
+	my @cdfFileList = @_;
+
+	foreach my $afile (@cdfFileList)
+	{
+		CreateCDFFileBinaryMap($afile);
+		my $rootNode = $binaryCDFFileMap{$afile}{root};
+
+		# Get the total list of files present in the cdf file.
+		my @binaryList = &genericparser::getChildElements($rootNode);
+
+		# Hash Reference to the hash map binaryInfo
+		my $binaryInfoHashRef;
+
+		foreach my $binaryNode (@binaryList)
+		{
+			my $fileId = &genericparser::getAttrValue($binaryNode, "id");
+			$binaryInfoHashRef = \%{$binaryInfo{$fileId}};
+			&setBinaryInfo($binaryInfoHashRef, $binaryNode);
+		}
+	}
+
+}
+
+#Sets the information of the CDF file to a hash map
+sub setBinaryInfo
+{
+	my ($aBinaryInfoRef, $aBinaryNode) = @_;
+
+	# Set the File attributes
+	$aBinaryInfoRef->{"id"}		  = &genericparser::getAttrValue($aBinaryNode, "id");
+	$aBinaryInfoRef->{"customisable"} = &genericparser::getAttrValue($aBinaryNode, "customisable");
+	$aBinaryInfoRef->{"addressable"}  = &genericparser::getAttrValue($aBinaryNode, "addressable");
+	$aBinaryInfoRef->{"compress"}	  = &genericparser::getAttrValue($aBinaryNode, "compress");
+	$aBinaryInfoRef->{"type"}	  = &genericparser::getAttrValue($aBinaryNode, "type");
+  	$aBinaryInfoRef->{"plugin_name"}  = &genericparser::getAttrValue($aBinaryNode, "plugin_name");
+  
+  	# Check for the plugin, setting the plugin type as ECOM_PLUGIN
+   
+  	if (defined $aBinaryInfoRef->{"plugin_name"})
+  	{
+  		$aBinaryInfoRef->{"IsFoundInCDF"} = 1;
+  		$aBinaryInfoRef->{"source"} = "ABI_DIR\/BUILD_DIR\/$aBinaryInfoRef->{id}";
+  		$aBinaryInfoRef->{"plugin_name"} =~ s/$aBinaryInfoRef->{plugin_name}/ECOM/;
+  	}
+  
+  	else {
+
+		# Get all the nodes of element 'file'
+		my @children = &genericparser::getChildElements($aBinaryNode);
+
+		foreach my $childNode (@children)
+		{
+			$aBinaryInfoRef->{"IsFoundInCDF"} = 1;
+
+			if (&genericparser::getElementName($childNode) eq "source")
+			{
+				$aBinaryInfoRef->{"source"} = &genericparser::getElementValue($childNode);
+			}
+
+			if (&genericparser::getElementName($childNode) eq "destination")
+			{
+				$aBinaryInfoRef->{"destination"} = &genericparser::getElementValue($childNode);
+			}
+
+			if (&genericparser::getElementName($childNode) eq "features")
+			{
+				# The children nodes will specify the list of features
+				my @aFeatureNodes = &genericparser::getChildElements($childNode);
+				foreach my $aFeatureChildNode (@aFeatureNodes)
+				{
+					# A list of features can be listed out either for supported case or for the prevented case.
+					if (&genericparser::getElementName($aFeatureChildNode) eq "supports")
+					{
+						my @aSupportedFeatureNodes = &genericparser::getChildElements($aFeatureChildNode);
+						foreach my $aSuppChildNode (@aSupportedFeatureNodes)
+						{
+							my %feat = ();
+							my $featureName = &genericparser::getAttrValue($aSuppChildNode, "name");
+							my $featureUID = &genericparser::getAttrValue($aSuppChildNode, "uid");
+							if (defined ($featureName) and ($featureName ne ""))
+							{
+								$feat{name} = $featureName ;
+								$feat{uid} = undef;
+							}
+							elsif(defined ($featureUID) and ($featureUID ne ""))
+							{
+								if(&featureparser::ValidateUIDValue($featureUID))
+								{
+									$featureUID = &featureparser::ConvertHexToDecimal($featureUID);
+									$feat{uid} = $featureUID;
+									$feat{name} = undef;
+								}
+								else
+								{
+									print "The uid value $featureUID specified for the Include feature list for the Binary, $aBinaryInfoRef->{id}, is not a valid number\n";
+								}
+							}
+							else
+							{
+								print ("Warning: Feature $featureName has both name and Uid mentioned\n") if ($warning_level < 2);
+								next;
+							}
+
+							$feat{include} = 1;
+							push @includeFeatureList, \%feat;
+					 
+						}
+					}
+					if (&genericparser::getElementName($aFeatureChildNode) eq "prevents")
+					{
+						my @aPreventedFeatureNodes = &genericparser::getChildElements($aFeatureChildNode);
+						foreach my $aPreventedChildNode (@aPreventedFeatureNodes)
+						{
+							my %feat = ();
+							my $featureName = &genericparser::getAttrValue($aPreventedChildNode, "name");
+							my $featureUID = &genericparser::getAttrValue($aPreventedChildNode, "uid");
+							if (defined ($featureName) and ($featureName ne ""))
+							{
+								$feat{name} = $featureName ;
+								$feat{uid} = undef;
+							}
+							elsif(defined ($featureUID) and ($featureUID ne ""))
+							{
+								if(&featureparser::ValidateUIDValue($featureUID))
+								{
+									$featureUID = &featureparser::ConvertHexToDecimal($featureUID);
+									$feat{uid} = $featureUID;
+									$feat{name} = undef;
+								}
+								else
+								{
+									print "The uid value $featureUID specified for the Exclude feature list for the Binary, $aBinaryInfoRef->{id}, is not a valid number\n";
+								}
+							}
+							else
+							{
+								print "Warning: Feature $featureName has both name and Uid mentioned\n" if ($warning_level < 2);
+								next;
+							}
+
+							$feat{exclude} = 1;
+							push @excludeFeatureList, \%feat;
+					 
+						}
+						push @{$aBinaryInfoRef->{"prevents"}}, (&genericparser::getElementValue($aFeatureChildNode));
+					}
+				}
+			}
+
+			if (&genericparser::getElementName($childNode) eq "dynamicdependencies")
+			{
+				# The children nodes will contain the file name.
+				my @aDynDependNodes = &genericparser::getChildElements($childNode);
+				
+				foreach my $aDynDependChildNode (@aDynDependNodes)
+				{
+					# There can be a list of binaries for dynamic dependencies
+					if (&genericparser::getElementName($aDynDependChildNode) eq "depend")
+					{
+						push @{$aBinaryInfoRef->{"depend"}}, (&genericparser::getElementValue($aDynDependChildNode));
+					}
+				}
+			}
+
+			if (&genericparser::getElementName($childNode) eq "localisation")
+			{
+				# The children nodes will contain the language code
+				my @aLocalisationNodes = &genericparser::getChildElements($childNode);
+				
+				foreach my $aLocalisationChildNode (@aLocalisationNodes)
+				{
+					# There can be a list of binaries for dynamic dependencies
+					if (&genericparser::getElementName($aLocalisationChildNode) eq "default")
+					{
+						$aBinaryInfoRef->{"default"} = &genericparser::getElementValue($aLocalisationChildNode);
+					}
+					if (&genericparser::getElementName($aLocalisationChildNode) eq "language")
+					{
+						push @{$aBinaryInfoRef->{"language"}}, (&genericparser::getElementValue($aLocalisationChildNode));
+					}
+				}
+			}
+
+			if (&genericparser::getElementName($childNode) eq "options")
+			{
+				# The children nodes will contain the option details
+				my @aOptionNodes = &genericparser::getChildElements($childNode);
+				foreach my $aOptionChildNode (@aOptionNodes)
+				{
+					if (&genericparser::getElementName($aOptionChildNode) eq "multilinguify")
+					{
+						$aBinaryInfoRef->{"multilinguify"} = &genericparser::getElementValue($aOptionChildNode);
+					}
+					if (&genericparser::getElementName($aOptionChildNode) eq "stack")
+					{
+						$aBinaryInfoRef->{"stack"} = &genericparser::getElementValue($aOptionChildNode);
+					}
+					if (&genericparser::getElementName($aOptionChildNode) eq "heapmin")
+					{
+						$aBinaryInfoRef->{"heapmin"} = &genericparser::getElementValue($aOptionChildNode);
+					}
+					if (&genericparser::getElementName($aOptionChildNode) eq "heapmax")
+					{
+						$aBinaryInfoRef->{"heapmax"} = &genericparser::getElementValue($aOptionChildNode);
+					}
+					if (&genericparser::getElementName($aOptionChildNode) eq "fixed")
+					{
+						$aBinaryInfoRef->{"fixed"} = &genericparser::getElementValue($aOptionChildNode);
+					}
+					if (&genericparser::getElementName($aOptionChildNode) eq "priority")
+					{
+						$aBinaryInfoRef->{"priority"} = &genericparser::getElementValue($aOptionChildNode);
+					}
+					if (&genericparser::getElementName($aOptionChildNode) eq "uid1")
+					{
+						$aBinaryInfoRef->{"uid1"} = &genericparser::getElementValue($aOptionChildNode);
+					}
+					if (&genericparser::getElementName($aOptionChildNode) eq "uid2")
+					{
+						$aBinaryInfoRef->{"uid2"} = &genericparser::getElementValue($aOptionChildNode);
+					}
+					if (&genericparser::getElementName($aOptionChildNode) eq "uid3")
+					{
+						$aBinaryInfoRef->{"uid3"} = &genericparser::getElementValue($aOptionChildNode);
+					}
+					if (&genericparser::getElementName($aOptionChildNode) eq "dll")
+					{
+						$aBinaryInfoRef->{"dll"} = &genericparser::getElementValue($aOptionChildNode);
+					}
+					if (&genericparser::getElementName($aOptionChildNode) eq "dlldatatop")
+					{
+						$aBinaryInfoRef->{"dlldatatop"} = &genericparser::getElementValue($aOptionChildNode);
+					}
+				}
+			}
+		}
+	}
+}
+
+# To get the complete list of information for a given binary
+# Input Parameter : Binary
+# Returns the detailed information for each binary
+sub GetBinaryInfo
+{
+	my $aBinary = shift;
+	my $aBinaryInfoHash = \%{$binaryInfo{$aBinary}};
+	if ($aBinaryInfoHash->{IsFoundInCDF})
+	{
+		return $aBinaryInfoHash;
+	}
+	return undef;
+}
+
+# To get the complete list of dynamic dependencies for a given binary
+# Input Parameter : Binary
+# Returns the complete list of dynamic dependencies
+sub GetDynamicDependencies
+{
+	my $aBinary = shift;
+
+	my $bin = \%{$binaryInfo{$aBinary}};
+
+	return \@{$bin->{"depend"}};
+}
+
+#Returns the included feature list
+sub GetIncludedFeatureList
+{
+	return \@includeFeatureList;
+}
+
+#Returns the excluded feature list
+sub GetExcludedFeatureList
+{
+	return \@excludeFeatureList;
+}
+
+1;
--- a/imgtools/buildrom/tools/datadriveimage.pm	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/datadriveimage.pm	Tue Jun 29 14:52:54 2010 +0800
@@ -1,727 +1,742 @@
-#
-# Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-# This package contains fuctions specific to data drive image generation
-#
-
-
-package datadriveimage;
-
-require Exporter;
-@ISA=qw(Exporter);
-@EXPORT=qw(
-			createDirectory 
-			deleteDirectory 
-			checkInArray 
-			setPath 
-			locateStubsisfiles 
-			copyFilesToFolders 
-			checkForSisFile 
-			copyNonSisFiles
-			invokeInterpretsis
-			invokeReadImage
-			compareArrays
-			dumpDatadriveObydata
-			TraverseDir
-			writeDataToFile
-			generate_datadriveheader
-			checkForWhiteSpace
-			reportError
-);
-
-use strict;
-use File::Path;		# Module to provide functions to remove or create directories in a convenient way.
-use File::Copy;		# Module to provide functions to copy file(s) from source to destination.
-
-use Pathutl;
-use Cwd;			# Module to provide functions for determining the pathname of the current working directory.
-
-# This fuction is used primiarly to check for whitespace in the location for "zdrive" / "datadrive" folder creation,
-# specified by the user, if yes then it returns one, else zero
-sub checkForWhiteSpace
-{
-	my ($dirLoc,$dirName) = @_;
-	if( $dirLoc =~ m/ / )
-	{
-		print "* Warning: $dirLoc contains whitespace, hence $dirName will be created in default location \n";
-		return 1;
-	}
-	else
-	{
-		return 0;
-	}
-}
-
-
-# This function reports the appropriate meassage supplied to it
-# and does a exit if and only if keepgoing option is disabled.
-sub reportError
-{
-	my( $message,$keepgoingOpt ) = @_;
-	# print the specified meassage.
-	print STDERR "$message \n";
-	# bail out, if keepgoing option is not set.
-	exit(1) if (!$keepgoingOpt);
-}
-
-# generate header for final datadrive oby file.
-sub generate_datadriveheader
-{
-	my ($idx,$datadriveimage) = @_;
-	my $header;
-	$header =  "dataimagename=$$datadriveimage[$idx]{name}.img\n";
-	$header .= "dataimagefilesystem=$$datadriveimage[$idx]{fstype}\n";
-
-	# check whether the size of the image has been mentioned
-	if(defined($$datadriveimage[$idx]{size}))
-	{
-		$header .= "dataimagesize=$$datadriveimage[$idx]{size}\n\n";
-	}
-	return $header;
-}
-
-# Create the specified directory by making use of mkpath function 
-# from File::Path module.
-sub createDirectory
-{
-	my($dir) = @_;
-	if( !-d $dir )
-	{
-		mkpath($dir);
-		if (! -e $dir) 
-		{
-			print ("ERROR: Couldn't create $dir\n");
-		}
-	}
-}
-
-# check if the given file is a reg file or ctl file or a txt file
-# if it is any of these files then return true else false.
-# This check is need since these three files or not valid not valid e32 file 
-# and hence needs to be placed as an data file inside the image.
-sub checkRegCtlFiles
-{
-	my ($fileName) = @_;
-
-	# check whether the file has "reg","ctl" or "txt" extension.
-	if( $fileName =~/\.(reg|ctl|txt)$/i )
-	{
-		return 1;		
-	}
-	else
-	{
-		return 0;
-	}
-}
-
-# delete the given directory by making use of rmtree function 
-# from File::Path module.
-sub deleteDirectory
-{
-	my($dir,$verboseOpt) = @_;
-	# check whether the directory exists.
-	if( -d $dir )
-	{
-		print("found $dir directory \n") if($verboseOpt);
-		if(rmtree($dir))
-		{
-			print("$dir directory deleted \n") if($verboseOpt);
-			return 0;
-		}
-		else
-		{
-			print("$dir directory could'nt be deleted \n") if($verboseOpt);
-			return 1;
-		}
-	}
-}
-
-# check for processed data drive image index.
-# if there is a match return one else return zero.
-# this check is done in order to ensure data drive image index is not repeated.
-sub checkInArray
-{
-	my($array, $value) = @_;
-	foreach my $aLine(@$array)
-	{
-		if( $aLine eq $value )
-		{
-			return 0;
-		}
-	}
-	return 1;
-}
-
-# set the path for the given directory.
-sub setPath
-{
-	my($dirName) = @_;
-	# get the working directory.
-	my $curWorkingDir = getcwd;
-	# substitute slash with double backward slash.
-	$curWorkingDir =~ s/\//\\/g;
- 	#if $curWorkingDir already has trailing '\', don't include it again 
- 	if( $curWorkingDir =~ /\\$/)
- 	{
- 		return $curWorkingDir.$dirName;
- 	}
- 	else
- 	{
- 		return $curWorkingDir."\\".$dirName;
- 	}
-}
-
-# create directory and copy respective file on to that directory.
-# is there is a problem while copying files from source to destination
-# then bail out if and only if keep going option is disabled.
-sub copyFilesToFolders
-{
-	my ($source,$dest,$dir,$verboseOpt) = @_;
-	$source =~ s/\"//g; # remove double quotes from the string. 
-	my $destFileName = "";	# name of the destination file.
-	$dest =~ s/\"//g;	# remove double quotes from the string. 
-	my $destDirectory = $dest;
-	# strip the last substring to get destination file 
-	if ($dest=~/.*\\(\S+)/) 
-	{
-		$destFileName = $1;
-	}
-	else
-	{
-		$destFileName = $dest;
-	}
-	#get the destination directory along with full path
-	#when "[" and "]" appear in the file name we need add "\" before "[" or "]"
-	#like this: [filename].exe translate to \[filename\].exe 
-	if($destFileName =~ /\[|\]/)
-	{
-		my $tempFileName = $destFileName;
-		$tempFileName =~ s/(\[|\])/\\$1/g;
-		$destDirectory =~ s/$tempFileName//;
-	}
-	else
-	{	
-		$destDirectory =~ s/$destFileName//;
-	}
-	my $destfile = $dir."\\".$dest;
-	my $createdir = $dir."\\".$destDirectory ;
-
-	# create the specified directory.
-	&createDirectory($createdir);
-	if (!copy($source,$destfile))
-	{
-		warn "warning : $source file could not found \n";
-		return 0;
-	}
-	else
-	{
-		print "$source copied to $destfile\n" if($verboseOpt);
-		return $destfile;
-	}
-}
-
-# Make a check for sisfile keyword by reading the specified iby/oby file,
-# if sisfile keyword is found then push the respective image on to the respective array 
-# and return true.
-sub checkForSisFile 
-{
-	my($obyfile,$sisFileArray,$sisFilePrestent) = @_;
-	# open the oby file in read only mode. 
-	open (DATA, "< $obyfile") or die("* Can't open $obyfile\n");
-	while  (my $line =<DATA>)
-	{
-		if($line =~ /^\s*sisfile\s*=\s*(\S+)/i )
-		{
-			# found a sis file.
-			$$sisFilePrestent = 1;
-			# push sis file on to stack.
-			push(@$sisFileArray,$1);
-			next;
-		}
-	}
-	close(DATA);
-	return $$sisFilePrestent;
-}
-
-# Make a check for zdriveimagename keyword by reading the specified iby/oby file,
-# if zdriveimagename keyword is found then push the respective image on to the respective array 
-# and return true.
-sub checkForZDriveImageKeyword 
-{
-	#$ZDriveImageFilePresent
-	my($obyfile,$ZDriveImageKeywordArray,$ImageFilePresent) = @_;
-	# open the oby file in read only mode. 
-	open (DATA, "< $obyfile") or die("* Can't open $obyfile\n");
-	while  (my $line =<DATA>)
-	{
-		if($line =~ /^\s*zdriveimagename\s*=\s*(\S+)/i )
-		{
-			# found a Z Drive Image file.
-			$$ImageFilePresent = 1;
-			# push sis file on to stack.
-			push(@$ZDriveImageKeywordArray,$1);
-			next;
-		}
-	}
-	close(DATA);
-	return $$ImageFilePresent;
-}
-
-# copy all non-sis file(s) on to prototype data drive folder 
-# which are mentioned under input data drive iby/oby file.
-sub copyNonSisFiles
-{
-	my($dir,$obyfile,$nonsisFileArray,$renameArray,$aliasArray,$hideArray,$verboseOpt,$keepgoingOpt) = @_;
-	open (OBEY ,$obyfile) or die($obyfile."\n");
-	while(my $line =<OBEY>) 
-	{
-		if( $line =~ /^(file|data)\s*=\s*(\S+)\s+(\S+)/i )
-		{
-			my $keyWord=$1;
-			my $source=$2;
-			my $dest=$3;
-
-			if( $source !~ /(\S+):(\S+)/ )
-			{ 
-				$source = Path_Drive().$2;
-			}
-			my $var = &copyFilesToFolders( $source,$dest,$dir,$verboseOpt);
-			if($var)
-			{
-				$var = $keyWord."=".$var;
-				$line =~ s/^(\S+)=(\S+)/$var/;
-				push(@$nonsisFileArray,$line);
-			}
-			else
-			{
-				exit(1)if(!$keepgoingOpt);
-			}
-		}
-		elsif($line =~ /^rename\s+(\S+)\s+(\S+)/i)
-		{
-			my $oldFile = $dir.$1;	# existing-file
-			my $newFile = $dir.$2;	# destination-file
-			print"found rename keyword\nrenaming $oldFile to $newFile\n" if ($verboseOpt);
-			if ( rename($oldFile, $newFile) )
-			{
-				# push the line on to the stack.
-				push(@$renameArray,$1."\t".$2."\n");
-			}
-			else
-			{
-				&datadriveimage::reportError("* Warning : can't rename $oldFile to $newFile: $!",$keepgoingOpt);
-			}
-		}
-		elsif($line =~ /^alias\s+(\S+)\s+(\S+)/i)
-		{
-			my $exFile = $dir.$1;	# existing-file
-			my $destFile = $dir.$2;	# destination-file
-			print"found alias keyword\n" if ($verboseOpt);
-			if(!copy($exFile,$destFile))
-			{
-				&datadriveimage::reportError("* warning : couldnt create alias of $1 to $2 ",$keepgoingOpt);
-			}
-			else
-			{
-				# push the line on to the stack.
-				push(@$aliasArray,$1."\t".$2."\n");
-			}
-		}
-		elsif($line =~ /^hide\s+(\S+)/i)
-		{
-			print"found hide keyword\n" if ($verboseOpt);
-			print "$1 is marked as hidden, hence will not be part of the image\n" if($verboseOpt);
-			if( unlink($dir.$1) )
-			{
-				# push the line on to the stack.
-				push(@$hideArray,$1);
-			}
-			else 
-			{ 
-				&datadriveimage::reportError("* Warning : Can't delete $1: $! ",$keepgoingOpt);
-			}
-		}
-	}
-	close(OBEY);
-}
-
-# invoke the INTERPRETSIS tool with appropriate parameters.
-sub invokeInterpretsis
-{
-	my($sisFileArray,$dataDrivePath,$verboseOpt,$zDrivePath,$parafile,$keepgoingOpt,$interpretsisOptList) = @_;
-	my $sisfile = ""; 
-	# default system drive letter is specified since interpretsis doesnt allow overloading of options unless default 
-	# options are specified.
-	my $basicOption = "-d C: ";	# default system drive letter
-	my $command = "interpretsis ";
-	my $vOption = "-w info" if ($verboseOpt);
-
-	# do a check if the path has a white space.
-	if( $dataDrivePath =~ m/ /)
-	{
-		$dataDrivePath = '"'.$dataDrivePath.'"';
-	}
-
-	# find out size of the array
-	my $sisarraysize = scalar(@$sisFileArray);
-	for( my $i=0; $i<$sisarraysize; $i++ )
-	{
-		if($sisfile ne "")
-		{
-			$sisfile = pop(@$sisFileArray).",".$sisfile;
-		}
-		else
-		{
-			$sisfile = pop(@$sisFileArray);
-		}
-	}
-
-	# check whether the directory exists or not 
-	if( -d $zDrivePath )
-	{ 
-		# do a check if the path has a white space.
-		if( $zDrivePath =~ m/ /)
-		{
-			$zDrivePath = '"'.$zDrivePath.'"';
-		}
-		$basicOption .= "-z $zDrivePath "; 
-	}
-
-	$basicOption .= "-c $dataDrivePath -s $sisfile $vOption";
-
-	# if parameter file is specified then invoke the INTERPRETSIS
-	# with the specified parameter file with "-p" option.
-	if( defined($parafile) )
-	{ 
-		# do a check if the path has a white space.
-		if( $parafile =~ m/ /)
-		{
-			$parafile = '"'.$parafile.'"';
-		}
-		$command .= "-p $parafile "; 
-	}
-	# else invoke the INTERPRETSIS with default parameter file with "-p" option. 
-	else
-	{
-		# Truncate and open the parameter file for writing..
-		open( OPTDATA, "> parameterfile.txt" )  or die "can't open parameterfile.txt";
-		print OPTDATA $basicOption."\n";
-		close( OPTDATA );
-		$command .= "-p parameterfile.txt ";
-	}
-
-	if( $interpretsisOptList )
-	{
-		# find out size of the array
-		my $arraysize = scalar( @$interpretsisOptList );
-		for( my $i = 0; $i < $arraysize; $i++ )
-		{
-			$command .= $$interpretsisOptList[$i]." ";
-		}
-	}
-
-	print "* Executing $command\n" if ( $verboseOpt );
-	system ( $command );
-
-	if ($? != 0)
-	{
-		&datadriveimage::reportError("* ERROR: INTERPRETSIS failed",$keepgoingOpt);
-	}
-}
-
-# invoke the READIMAGE tool with appropriate parameters.
-sub invokeReadImage
-{
-	my($imageName,$loc,$verboseOpt,$logFile,$keepgoingOpt) = @_;
-	my $command = "readimage ";
-	# check if log file has been supplied.
-	if(defined($logFile))
-	{
-		if( $logFile =~ m/ /)
-		{
-			$logFile = '"'.$logFile.'"';
-		}
-		$command .= "-l $logFile ";
-	}
-	
-	# do a check if the path has a white space.
-	if( $loc =~ m/ /)
-	{
-		$loc = '"'.$loc.'"';
-	}
-	$command .= "-z ".$loc." ".$imageName;
-	print "* Executing $command\n" if ($verboseOpt);
-	system ($command);
-	if ($? != 0)
-	{
-		&datadriveimage::reportError("* ERROR: READIMAGE failed to read the image",$keepgoingOpt);
-		return 0;
-	}
-	return 1;
-}
-
-# Each line from the OBY file is read and if any of the line contains "rename"/ "alias" keyword
-# then that corresponding line source and line destination is obtained and is passed to this function as one of the parameters.
-# This fuction compares given array with non-sis file(s) array, when an given line destination matches with the destination of an
-# element in the rename array/alias array(array holding list of file(s) that are renamed / made alias) then,
-# that respective element is removed from the rename array and a further check is made to see whether the given
-# line source matches with the destination of an element in the rename array/alias array.If a match is found then
-# a keyword check is done,if the keyword is "rename" then corresponding element's source and destination file is replaced
-# with given line destination file and if the keyword is "alias" then a new element will be added to non sis file array
-# with line destination file as the source and destination file.
-sub compareArrays
-{
-	my ( $firstarray,$nonsisArray,$linesource,$linedest,$linekeyword ) = @_;
-	# count of array element(s).
-	my $firstArrayCount = 0;
-	# source file.
-	my $linesourceFile;
-	# destination file.
-	my $linedestFile;
-	# get source file.
-
-	# strip first occurrence of back slash
-	$linesource =~ s/\\//; 
-
-	# get source file.
-	if ($linesource =~ /.*\\(\S+)/ ) 
-	{
-		$linesourceFile = $1;
-	}
-	# get destination file.
-	if ($linedest =~ /.*\\(\S+)/ )
-	{
-		$linedestFile = $1;
-	}
-	# iterate trough all
-	foreach my $firstarrayEntry (@$firstarray) 
-	{
-		if( $firstarrayEntry =~ /(\S+)\s+(\S+)/ )
-		{
-			my $firstarrayEntrydest = $2;
-
-			if( $linedest eq $firstarrayEntrydest )
-			{
-				# remove the specified element from the array.
-				splice(@$firstarray,$firstArrayCount,1);
-				# initialize the nonsisFileListCount to zero.
-				my $nonsisFileListCount = 0;
-				foreach my $nonsisEntry ( @$nonsisArray )
-				{
-					if( $nonsisEntry =~ /^(\S+)=(\S+)\s+(\S+)/ )
-					{
-						my $nonsisEntryDest = $3;
-						# remove double quotes.
-						$nonsisEntryDest =~ s/\"//g;
-						my $nonsisEntryDestFile;
-						if ($nonsisEntryDest =~ /.*\\(\S+)/ ) 
-						{ 
-							$nonsisEntryDestFile = $1;
-						}
-						if( $nonsisEntryDest eq $linesource )
-						{
-							if($linekeyword eq "rename")
-							{
-								# remove the specified element from the array.
-								splice(@$nonsisArray,$nonsisFileListCount,1);
-								$nonsisEntry =~ s/$nonsisEntryDestFile/$linedestFile/g;
-								push(@$nonsisArray,$nonsisEntry);
-							}
-							elsif($linekeyword eq "alias")
-							{
-								my $newLine = $nonsisEntry;
-								$newLine =~ s/$nonsisEntryDestFile/$linedestFile/g;
-								push(@$nonsisArray,$newLine);
-							}
-						}
-					 }
-					$nonsisFileListCount++;
-				 }#end of loop foreach my $newLine ( @nonsisArray )
-			}
-			$firstArrayCount++;
-		}#end of loop foreach my $newLine ( @firstarray) 
-	}
-}
-
-# Traverse the entire directory and log the folder contents on to a file.
-sub dumpDatadriveObydata
-{
-	#assign a temporary name and extension to the new oby file.
-	my $newobyfile = "temp.$$";
-	my ($datadir,$oldobyfile,$size,$nonsisFileArray,$renameArray,$aliasArray,
-		$hideArray,$sisobyArray,$datadriveArray,$keepgoingOpt,$verboseOpt) = @_;
-	# get the working directory.
-	my $curWorkingDir = getcwd;
-	# traverse the updated data drive directory structure.
-	&TraverseDir($datadir,"",$sisobyArray,$datadir);
-	# change the directrory to the Working directory.
-	chdir($curWorkingDir);
-	# copy non-sis file(s) on to prototype data drive folder.
-	copyNonSisFiles($datadir,$oldobyfile,$nonsisFileArray,$renameArray,$aliasArray,$hideArray,$verboseOpt,$keepgoingOpt);
-	#open the oby file in read-only mode. 
-	open (OLDDATA, "< $oldobyfile") or die("* Can't open $oldobyfile\n");
-	# Truncate and open the new oby file for writing..
-	open(NEWDATA, "> $newobyfile")  or die "can't open $newobyfile";
-	while  (my $line =<OLDDATA>)
-	{
-		if( $line =~ /^hide\s+(\S+)/i)
-		{
-			my $lineToSearch = $1; 
-			my $hideListCount = 0;
-			foreach my $newLine ( @$hideArray ) 
-			{
-				if( $newLine eq $lineToSearch )
-				{
-					splice(@$hideArray,$hideListCount,1);
-					my $nonsisFileListCount = 0;
-					foreach my $newLine ( @$nonsisFileArray )
-					{
-						if( $newLine =~ /^(\S+)=(\S+)\s+(\S+)/ )
-						{
-							my $newLineKeyword = $1;
-							my $newLinesource = $2;
-							my $newLinedest = $3;
-							$newLinedest =~ s/\"//g;
-							$newLinedest = "\\".$newLinedest;
-							if( $newLinedest eq $lineToSearch )
-							{
-								# remove the specified element from the array.
-								splice(@$nonsisFileArray,$nonsisFileListCount,1);
-							}
-						}
-						# increment the non sis file list count.
-						$nonsisFileListCount++;
-					}
-				}
-				# increment the  hide file list count.
-				$hideListCount++;
-			}
-		}
-		elsif( $line =~ /^rename\s+(\S+)\s+(\S+)/i) 
-		{ 
-			my $linesource = $1 ;
-			my $linedest = $2;
-			my $linekeyword = "rename";
-			&compareArrays($renameArray,$nonsisFileArray,$linesource,$linedest,$linekeyword);
-		}
-		elsif( $line =~ /^alias\s+(\S+)\s+(\S+)/i )
-		{
-			my $linesource = $1 ;
-			my $linedest = $2;
-			my $linekeyword = "alias";
-			&compareArrays($aliasArray,$nonsisFileArray,$linesource,$linedest,$linekeyword);
-		}
-		elsif(	$line =~ /^(file|data)\s*=\s*/i || $line =~ /^\s*(zdriveimagename|sisfile)\s*=\s*/i )
-		{
-			# skip to next line. 
-			next;
-		}
-		else
-		{ 
-			# push it on to the array.
-			unshift(@$datadriveArray,$line); 
-		}
-		next;
-	}
-	# close the old oby files.
-	close(OLDDATA)or die "can't close $oldobyfile";
-	#write the array contents on to the file
-	print"* Updating $oldobyfile - final OBY file\n";
-	&writeDataToFile( $datadriveArray );
-	&writeDataToFile( $sisobyArray );
-	&writeDataToFile( $nonsisFileArray );
-	# close the new oby file.
-	close(NEWDATA)or die "can't close $newobyfile";
-	#rename the file.
-	rename( $newobyfile, $oldobyfile )or die "can't rename $newobyfile to $oldobyfile: $!";
-}
-
-
-# Traverse the entire given directory 
-# push all the folder contents on to an array.
-sub  TraverseDir
-{
-	my($dir,$folderList,$sisFileContent,$rootdir) = @_;
-	#check the specified directory
-	chdir($dir) || die "Cannot chdir to $dir\n";
-	local(*DIR);
-	opendir(DIR, ".");#open current directory.
-	my $sourcedir;
-	my $destdir;
-	while (my $entry=readdir(DIR)) 
-	{
-		#skip, parent directory and current directory.
-		next if ($entry eq "." || $entry eq "..");
-		#check if it is a file 
-		if( -f $entry )
-		{
-			my $sourcedir = $rootdir."\\".$folderList.$entry;
-			my $destdir	= "$folderList".$entry;
-			my $sisSource;
-			my $sisdestination;
-			if(&checkRegCtlFiles($entry))
-			{
-				# check for any whitespace
-				if($sourcedir =~ m/ /)
-				{
-					# if yes, then append double quotes
-					$sisSource = "data="."\"".$sourcedir."\"";
-				}
-				else
-				{
-					# else dont append any double quotes for destination
-					$sisSource = "data=".$sourcedir;
-				}
-				# push the line on to the array.
-				push(@$sisFileContent,$sisSource."\t".'"'.$destdir.'"');
-			}
-			else
-			{
-				# check for any white space
-				if($sourcedir =~ m/ /)
-				{
-					# if yes, then append double quotes
-					$sisSource = "file="."\"".$sourcedir."\"";
-				}
-				else
-				{
-					# else dont append any double quotes for destination
-					$sisSource = "file=".$sourcedir;
-				}
-				# push the line on to the array.
-				push(@$sisFileContent,$sisSource."\t".'"'.$destdir.'"');
-			}
-		}
-		#else it's a directory
-		else
-		{
-			&TraverseDir($entry,$folderList.$entry."\\",$sisFileContent,$rootdir);
-		}
-	}
-	closedir(DIR);
-	chdir("..");
-}
-
-# write the data in to oby file by accessing appropriate array.
-sub writeDataToFile
-{
-	my ($array) = @_; 
-	#get the array size.
-	my $arraySize = scalar(@$array);
-	for(my $i=0; $i<$arraySize ; $i++ )
-	{
-		#pop out the element to the respective obey file.
-		 print NEWDATA pop(@$array)."\n";
-	}
-}
\ No newline at end of file
+#
+# Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+# This package contains fuctions specific to data drive image generation
+#
+
+
+package datadriveimage;
+
+require Exporter;
+@ISA=qw(Exporter);
+@EXPORT=qw(
+			createDirectory 
+			deleteDirectory 
+			checkInArray 
+			setPath 
+			locateStubsisfiles 
+			copyFilesToFolders 
+			checkForSisFile 
+			copyNonSisFiles
+			invokeInterpretsis
+			invokeReadImage
+			compareArrays
+			dumpDatadriveObydata
+			TraverseDir
+			writeDataToFile
+			generate_datadriveheader
+			checkForWhiteSpace
+			reportError
+);
+
+use strict;
+use File::Path;		# Module to provide functions to remove or create directories in a convenient way.
+use File::Copy;		# Module to provide functions to copy file(s) from source to destination.
+
+use Cwd;			# Module to provide functions for determining the pathname of the current working directory.
+
+use romutl;
+use romosvariant;
+
+# This fuction is used primiarly to check for whitespace in the location for "zdrive" / "datadrive" folder creation,
+# specified by the user, if yes then it returns one, else zero
+sub checkForWhiteSpace
+{
+	my ($dirLoc,$dirName) = @_;
+	if( $dirLoc =~ m/ / )
+	{
+		print "* Warning: $dirLoc contains whitespace, hence $dirName will be created in default location \n";
+		return 1;
+	}
+	else
+	{
+		return 0;
+	}
+}
+
+
+# This function reports the appropriate meassage supplied to it
+# and does a exit if and only if keepgoing option is disabled.
+sub reportError
+{
+	my( $message,$keepgoingOpt ) = @_;
+	# print the specified meassage.
+	print STDERR "$message \n";
+	# bail out, if keepgoing option is not set.
+	exit(1) if (!$keepgoingOpt);
+}
+
+# generate header for final datadrive oby file.
+sub generate_datadriveheader
+{
+	my ($idx,$datadriveimage) = @_;
+	my $header;
+	$header =  "dataimagename=$$datadriveimage[$idx]{name}.img\n";
+	$header .= "dataimagefilesystem=$$datadriveimage[$idx]{fstype}\n";
+
+	# check whether the size of the image has been mentioned
+	if(defined($$datadriveimage[$idx]{size}))
+	{
+		$header .= "dataimagesize=$$datadriveimage[$idx]{size}\n\n";
+	}
+	return $header;
+}
+
+# Create the specified directory by making use of mkpath function 
+# from File::Path module.
+sub createDirectory
+{
+	my($dir) = @_;
+	if( !-d $dir )
+	{
+		mkpath($dir);
+		if (! -e $dir) 
+		{
+			print ("ERROR: Couldn't create $dir\n");
+		}
+	}
+}
+
+# check if the given file is a reg file or ctl file or a txt file
+# if it is any of these files then return true else false.
+# This check is need since these three files or not valid not valid e32 file 
+# and hence needs to be placed as an data file inside the image.
+sub checkRegCtlFiles
+{
+	my ($fileName) = @_;
+
+	# check whether the file has "reg","ctl" or "txt" extension.
+	if( $fileName =~/\.(reg|ctl|txt)$/i )
+	{
+		return 1;		
+	}
+	else
+	{
+		return 0;
+	}
+}
+
+# delete the given directory by making use of rmtree function 
+# from File::Path module.
+sub deleteDirectory
+{
+	my($dir,$verboseOpt) = @_;
+	# check whether the directory exists.
+	if( -d $dir )
+	{
+		print("found $dir directory \n") if($verboseOpt);
+		if(rmtree($dir))
+		{
+			print("$dir directory deleted \n") if($verboseOpt);
+			return 0;
+		}
+		else
+		{
+			print("$dir directory could'nt be deleted \n") if($verboseOpt);
+			return 1;
+		}
+	}
+}
+
+# check for processed data drive image index.
+# if there is a match return one else return zero.
+# this check is done in order to ensure data drive image index is not repeated.
+sub checkInArray
+{
+	my($array, $value) = @_;
+	foreach my $aLine(@$array)
+	{
+		if( $aLine eq $value )
+		{
+			return 0;
+		}
+	}
+	return 1;
+}
+
+# set the path for the given directory.
+sub setPath
+{
+	my($dirName) = @_;
+	# get the working directory.
+	my $curWorkingDir = getcwd;
+	# substitute slash with double backward slash.
+	$curWorkingDir =~ s/\\/\//g;
+ 	#if $curWorkingDir already has trailing '\', don't include it again 
+ 	if( $curWorkingDir =~ /\/$/)
+ 	{
+ 		return $curWorkingDir.$dirName;
+ 	}
+ 	else
+ 	{
+ 		return $curWorkingDir."\/".$dirName;
+ 	}
+}
+
+# create directory and copy respective file on to that directory.
+# is there is a problem while copying files from source to destination
+# then bail out if and only if keep going option is disabled.
+sub copyFilesToFolders
+{
+	my ($source,$dest,$dir,$verboseOpt) = @_;
+	$source =~ s/\"//g; # remove double quotes from the string. 
+	my $destFileName = "";	# name of the destination file.
+	$dest =~ s/\"//g;	# remove double quotes from the string. 
+	my $destDirectory = $dest;
+	# strip the last substring to get destination file 
+	if ($dest=~/.*[\/\\](\S+)/) 
+	{
+		$destFileName = $1;
+	}
+	else
+	{
+		$destFileName = $dest;
+	}
+	#get the destination directory along with full path
+	#when "[" and "]" appear in the file name we need add "\" before "[" or "]"
+	#like this: [filename].exe translate to \[filename\].exe 
+	if($destFileName =~ /\[|\]/)
+	{
+		my $tempFileName = $destFileName;
+		$tempFileName =~ s/(\[|\])/\\$1/g;
+		$destDirectory =~ s/$tempFileName//;
+	}
+	else
+	{	
+		$destDirectory =~ s/$destFileName//;
+	}
+	my $destfile = $dir."\/".$dest;
+	my $createdir = $dir."\/".$destDirectory ;
+
+	# create the specified directory.
+	&createDirectory($createdir);
+	if (!copy($source,$destfile))
+	{
+		warn "warning : $source file could not found \n";
+		return 0;
+	}
+	else
+	{
+		print "$source copied to $destfile\n" if($verboseOpt);
+		return "\"".$destfile."\"";
+	}
+}
+
+# Make a check for sisfile keyword by reading the specified iby/oby file,
+# if sisfile keyword is found then push the respective image on to the respective array 
+# and return true.
+sub checkForSisFile 
+{
+	my($obyfile,$sisFileArray,$sisFilePrestent) = @_;
+	# open the oby file in read only mode. 
+	open (DATA, "< $obyfile") or die("* Can't open $obyfile\n");
+	while  (my $line =<DATA>)
+	{
+		if($line =~ /^\s*sisfile\s*=\s*(\S+)/i )
+		{
+			# found a sis file.
+			$$sisFilePrestent = 1;
+			# push sis file on to stack.
+			push(@$sisFileArray,$1);
+			next;
+		}
+	}
+	close(DATA);
+	return $$sisFilePrestent;
+}
+
+# Make a check for zdriveimagename keyword by reading the specified iby/oby file,
+# if zdriveimagename keyword is found then push the respective image on to the respective array 
+# and return true.
+sub checkForZDriveImageKeyword 
+{
+	#$ZDriveImageFilePresent
+	my($obyfile,$ZDriveImageKeywordArray,$ImageFilePresent) = @_;
+	# open the oby file in read only mode. 
+	open (DATA, "< $obyfile") or die("* Can't open $obyfile\n");
+	while  (my $line =<DATA>)
+	{
+		if($line =~ /^\s*zdriveimagename\s*=\s*(\S+)/i )
+		{
+			# found a Z Drive Image file.
+			$$ImageFilePresent = 1;
+			# push sis file on to stack.
+			push(@$ZDriveImageKeywordArray,$1);
+			next;
+		}
+	}
+	close(DATA);
+	return $$ImageFilePresent;
+}
+
+# copy all non-sis file(s) on to prototype data drive folder 
+# which are mentioned under input data drive iby/oby file.
+sub copyNonSisFiles
+{
+	my($dir,$obyfile,$nonsisFileArray,$renameArray,$aliasArray,$hideArray,$verboseOpt,$keepgoingOpt) = @_;
+	open (OBEY ,$obyfile) or die($obyfile."\n");
+	while(my $line =<OBEY>) 
+	{
+		if( $line =~ /^(file|data)\s*=\s*(\"[^"]+\")\s+(\"[^"]+\")/i || 
+				$line =~ /^(file|data)\s*=\s*(\"[^"]+\")\s+(\S+)/i || 
+				$line =~ /^(file|data)\s*=\s*(\S+)\s+(\"[^"]+\")/i || 
+				$line =~ /^(file|data)\s*=\s*(\S+)\s+(\S+)/i )
+		{
+			my $keyWord=$1;
+			my $source=$2;
+			my $dest=$3;
+
+			if( $source !~ /(\S+):([^"]+)/ )
+			{ 
+				$source = get_drive().$2;
+			}
+			my $var = &copyFilesToFolders( $source,$dest,$dir,$verboseOpt);
+			if($var)
+			{
+				$line = $keyWord."=".$var."\t".$dest."\n";
+				push(@$nonsisFileArray,$line);
+			}
+			else
+			{
+				exit(1)if(!$keepgoingOpt);
+			}
+		}
+		elsif($line =~ /^rename\s+(\S+)\s+(\S+)/i)
+		{
+			my $oldFile = $dir.$1;	# existing-file
+			my $newFile = $dir.$2;	# destination-file
+			print"found rename keyword\nrenaming $oldFile to $newFile\n" if ($verboseOpt);
+			if ( rename($oldFile, $newFile) )
+			{
+				# push the line on to the stack.
+				push(@$renameArray,$1."\t".$2."\n");
+			}
+			else
+			{
+				&datadriveimage::reportError("* Warning : can't rename $oldFile to $newFile: $!",$keepgoingOpt);
+			}
+		}
+		elsif($line =~ /^alias\s+(\S+)\s+(\S+)/i)
+		{
+			my $exFile = $dir.$1;	# existing-file
+			my $destFile = $dir.$2;	# destination-file
+			print"found alias keyword\n" if ($verboseOpt);
+			if(!copy($exFile,$destFile))
+			{
+				&datadriveimage::reportError("* warning : couldnt create alias of $1 to $2 ",$keepgoingOpt);
+			}
+			else
+			{
+				# push the line on to the stack.
+				push(@$aliasArray,$1."\t".$2."\n");
+			}
+		}
+		elsif($line =~ /^hide\s+(\S+)/i)
+		{
+			print"found hide keyword\n" if ($verboseOpt);
+			print "$1 is marked as hidden, hence will not be part of the image\n" if($verboseOpt);
+			if( unlink($dir.$1) )
+			{
+				# push the line on to the stack.
+				push(@$hideArray,$1);
+			}
+			else 
+			{ 
+				&datadriveimage::reportError("* Warning : Can't delete $1: $! ",$keepgoingOpt);
+			}
+		}
+	}
+	close(OBEY);
+}
+
+# invoke the INTERPRETSIS tool with appropriate parameters.
+sub invokeInterpretsis
+{
+	my($sisFileArray,$dataDrivePath,$verboseOpt,$zDrivePath,$parafile,$keepgoingOpt,$interpretsisOptList) = @_;
+	my $sisfile = ""; 
+	# default system drive letter is specified since interpretsis doesnt allow overloading of options unless default 
+	# options are specified.
+	my $basicOption = "-d C: ";	# default system drive letter
+	my $command = "interpretsis ";
+	my $vOption = "-w info" if ($verboseOpt);
+	
+	is_existinpath("interpretsis", romutl::DIE_NOT_FOUND);
+
+	# do a check if the path has a white space.
+	if( $dataDrivePath =~ m/ /)
+	{
+		$dataDrivePath = '"'.$dataDrivePath.'"';
+	}
+
+	# find out size of the array
+	my $sisarraysize = scalar(@$sisFileArray);
+	for( my $i=0; $i<$sisarraysize; $i++ )
+	{
+		if($sisfile ne "")
+		{
+			$sisfile = pop(@$sisFileArray).",".$sisfile;
+		}
+		else
+		{
+			$sisfile = pop(@$sisFileArray);
+		}
+	}
+
+	# check whether the directory exists or not 
+	if( -d $zDrivePath )
+	{ 
+		# do a check if the path has a white space.
+		if( $zDrivePath =~ m/ /)
+		{
+			$zDrivePath = '"'.$zDrivePath.'"';
+		}
+		$basicOption .= "-z $zDrivePath "; 
+	}
+
+	$basicOption .= "-c $dataDrivePath -s $sisfile $vOption";
+
+	# if parameter file is specified then invoke the INTERPRETSIS
+	# with the specified parameter file with "-p" option.
+	if( defined($parafile) )
+	{ 
+		# do a check if the path has a white space.
+		if( $parafile =~ m/ /)
+		{
+			$parafile = '"'.$parafile.'"';
+		}
+		$command .= "-p $parafile "; 
+	}
+	# else invoke the INTERPRETSIS with default parameter file with "-p" option. 
+	else
+	{
+		# Truncate and open the parameter file for writing..
+		open( OPTDATA, "> parameterfile.txt" )  or die "can't open parameterfile.txt";
+		print OPTDATA $basicOption."\n";
+		close( OPTDATA );
+		$command .= "-p parameterfile.txt ";
+	}
+
+	if( $interpretsisOptList )
+	{
+		# find out size of the array
+		my $arraysize = scalar( @$interpretsisOptList );
+		for( my $i = 0; $i < $arraysize; $i++ )
+		{
+			$command .= $$interpretsisOptList[$i]." ";
+		}
+	}
+	
+	print "* Executing $command\n" if ( $verboseOpt );
+	system ( $command );
+
+	if ($? != 0)
+	{
+		&datadriveimage::reportError("* ERROR: INTERPRETSIS failed",$keepgoingOpt);
+	}
+}
+
+# invoke the READIMAGE tool with appropriate parameters.
+sub invokeReadImage
+{
+	my($imageName,$loc,$verboseOpt,$logFile,$keepgoingOpt) = @_;
+	my $command = "readimage ";
+	
+	is_existinpath("readimage", romutl::DIE_NOT_FOUND);
+	
+	# check if log file has been supplied.
+	if(defined($logFile))
+	{
+		if( $logFile =~ m/ /)
+		{
+			$logFile = '"'.$logFile.'"';
+		}
+		$command .= "-l $logFile ";
+	}
+	
+	# do a check if the path has a white space.
+	if( $loc =~ m/ /)
+	{
+		$loc = '"'.$loc.'"';
+	}
+	$command .= "-z ".$loc." ".$imageName;
+	print "* Executing $command\n" if ($verboseOpt);
+	system ($command);
+	if ($? != 0)
+	{
+		&datadriveimage::reportError("* ERROR: READIMAGE failed to read the image",$keepgoingOpt);
+		return 0;
+	}
+	return 1;
+}
+
+# Each line from the OBY file is read and if any of the line contains "rename"/ "alias" keyword
+# then that corresponding line source and line destination is obtained and is passed to this function as one of the parameters.
+# This fuction compares given array with non-sis file(s) array, when an given line destination matches with the destination of an
+# element in the rename array/alias array(array holding list of file(s) that are renamed / made alias) then,
+# that respective element is removed from the rename array and a further check is made to see whether the given
+# line source matches with the destination of an element in the rename array/alias array.If a match is found then
+# a keyword check is done,if the keyword is "rename" then corresponding element's source and destination file is replaced
+# with given line destination file and if the keyword is "alias" then a new element will be added to non sis file array
+# with line destination file as the source and destination file.
+sub compareArrays
+{
+	my ( $firstarray,$nonsisArray,$linesource,$linedest,$linekeyword ) = @_;
+	# count of array element(s).
+	my $firstArrayCount = 0;
+	# source file.
+	my $linesourceFile;
+	# destination file.
+	my $linedestFile;
+	# get source file.
+
+	# strip first occurrence of back slash
+	$linesource =~ s/[\/\\]//; 
+
+	# get source file.
+	if ($linesource =~ /.*[\/\\](\S+)/ ) 
+	{
+		$linesourceFile = $1;
+	}
+	# get destination file.
+	if ($linedest =~ /.*[\/\\](\S+)/ )
+	{
+		$linedestFile = $1;
+	}
+	# iterate trough all
+	foreach my $firstarrayEntry (@$firstarray) 
+	{
+		if( $firstarrayEntry =~ /(\S+)\s+(\S+)/ )
+		{
+			my $firstarrayEntrydest = $2;
+
+			if( $linedest eq $firstarrayEntrydest )
+			{
+				# remove the specified element from the array.
+				splice(@$firstarray,$firstArrayCount,1);
+				# initialize the nonsisFileListCount to zero.
+				my $nonsisFileListCount = 0;
+				foreach my $nonsisEntry ( @$nonsisArray )
+				{
+					if( $nonsisEntry =~ /^(\S+)=(\S+)\s+(\S+)/ )
+					{
+						my $nonsisEntryDest = $3;
+						# remove double quotes.
+						$nonsisEntryDest =~ s/\"//g;
+						my $nonsisEntryDestFile;
+						if ($nonsisEntryDest =~ /.*[\/\\](\S+)/ ) 
+						{ 
+							$nonsisEntryDestFile = $1;
+						}
+						if( $nonsisEntryDest eq $linesource )
+						{
+							if($linekeyword eq "rename")
+							{
+								# remove the specified element from the array.
+								splice(@$nonsisArray,$nonsisFileListCount,1);
+								$nonsisEntry =~ s/$nonsisEntryDestFile/$linedestFile/g;
+								push(@$nonsisArray,$nonsisEntry);
+							}
+							elsif($linekeyword eq "alias")
+							{
+								my $newLine = $nonsisEntry;
+								$newLine =~ s/$nonsisEntryDestFile/$linedestFile/g;
+								push(@$nonsisArray,$newLine);
+							}
+						}
+					 }
+					$nonsisFileListCount++;
+				 }#end of loop foreach my $newLine ( @nonsisArray )
+			}
+			$firstArrayCount++;
+		}#end of loop foreach my $newLine ( @firstarray) 
+	}
+}
+
+# Traverse the entire directory and log the folder contents on to a file.
+sub dumpDatadriveObydata
+{
+	#assign a temporary name and extension to the new oby file.
+	my $newobyfile = "temp.$$";
+	my ($datadir,$oldobyfile,$size,$nonsisFileArray,$renameArray,$aliasArray,
+		$hideArray,$sisobyArray,$datadriveArray,$keepgoingOpt,$verboseOpt) = @_;
+	# get the working directory.
+	my $curWorkingDir = getcwd;
+	# traverse the updated data drive directory structure.
+	&TraverseDir($datadir,"",$sisobyArray,$datadir);
+	# change the directrory to the Working directory.
+	chdir($curWorkingDir);
+	# copy non-sis file(s) on to prototype data drive folder.
+	copyNonSisFiles($datadir,$oldobyfile,$nonsisFileArray,$renameArray,$aliasArray,$hideArray,$verboseOpt,$keepgoingOpt);
+	#open the oby file in read-only mode. 
+	open (OLDDATA, "< $oldobyfile") or die("* Can't open $oldobyfile\n");
+	# Truncate and open the new oby file for writing..
+	open(NEWDATA, "> $newobyfile")  or die "can't open $newobyfile";
+	while  (my $line =<OLDDATA>)
+	{
+		if( $line =~ /^hide\s+(\S+)/i)
+		{
+			my $lineToSearch = $1; 
+			my $hideListCount = 0;
+			foreach my $newLine ( @$hideArray ) 
+			{
+				if( $newLine eq $lineToSearch )
+				{
+					splice(@$hideArray,$hideListCount,1);
+					my $nonsisFileListCount = 0;
+					foreach my $newLine ( @$nonsisFileArray )
+					{
+						if( $newLine =~ /^(\S+)=(\S+)\s+(\S+)/ )
+						{
+							my $newLineKeyword = $1;
+							my $newLinesource = $2;
+							my $newLinedest = $3;
+							$newLinedest =~ s/\"//g;
+							$newLinedest = "\/".$newLinedest;
+							if( $newLinedest eq $lineToSearch )
+							{
+								# remove the specified element from the array.
+								splice(@$nonsisFileArray,$nonsisFileListCount,1);
+							}
+						}
+						# increment the non sis file list count.
+						$nonsisFileListCount++;
+					}
+				}
+				# increment the  hide file list count.
+				$hideListCount++;
+			}
+		}
+		elsif( $line =~ /^rename\s+(\S+)\s+(\S+)/i) 
+		{ 
+			my $linesource = $1 ;
+			my $linedest = $2;
+			my $linekeyword = "rename";
+			&compareArrays($renameArray,$nonsisFileArray,$linesource,$linedest,$linekeyword);
+		}
+		elsif( $line =~ /^alias\s+(\S+)\s+(\S+)/i )
+		{
+			my $linesource = $1 ;
+			my $linedest = $2;
+			my $linekeyword = "alias";
+			&compareArrays($aliasArray,$nonsisFileArray,$linesource,$linedest,$linekeyword);
+		}
+		elsif(	$line =~ /^(file|data)\s*=\s*/i || $line =~ /^\s*(zdriveimagename|sisfile)\s*=\s*/i )
+		{
+			# skip to next line. 
+			next;
+		}
+		else
+		{ 
+			# push it on to the array.
+			unshift(@$datadriveArray,$line); 
+		}
+		next;
+	}
+	# close the old oby files.
+	close(OLDDATA)or die "can't close $oldobyfile";
+	#write the array contents on to the file
+	print"* Updating $oldobyfile - final OBY file\n";
+	&writeDataToFile( $datadriveArray );
+	&writeDataToFile( $sisobyArray );
+	&writeDataToFile( $nonsisFileArray );
+	# close the new oby file.
+	close(NEWDATA)or die "can't close $newobyfile";
+	#rename the file.
+	rename( $newobyfile, $oldobyfile )or die "can't rename $newobyfile to $oldobyfile: $!";
+}
+
+
+# Traverse the entire given directory 
+# push all the folder contents on to an array.
+sub  TraverseDir
+{
+	my($dir,$folderList,$sisFileContent,$rootdir) = @_;
+	#check the specified directory
+	chdir($dir) || die "Cannot chdir to $dir\n";
+	local(*DIR);
+	opendir(DIR, ".");#open current directory.
+	my $sourcedir;
+	my $destdir;
+	while (my $entry=readdir(DIR)) 
+	{
+		#skip, parent directory and current directory.
+		next if ($entry eq "." || $entry eq "..");
+		#check if it is a file 
+		if( -f $entry )
+		{
+			my $sourcedir = $rootdir."\/".$folderList.$entry;
+			my $destdir	= "$folderList".$entry;
+			my $sisSource;
+			my $sisdestination;
+			if(&checkRegCtlFiles($entry))
+			{
+				# check for any whitespace
+				if($sourcedir =~ m/ /)
+				{
+					# if yes, then append double quotes
+					$sisSource = "data="."\"".$sourcedir."\"";
+				}
+				else
+				{
+					# else dont append any double quotes for destination
+					$sisSource = "data=".$sourcedir;
+				}
+				# push the line on to the array.
+				push(@$sisFileContent,$sisSource."\t".'"'.$destdir.'"');
+			}
+			else
+			{
+				# check for any white space
+				if($sourcedir =~ m/ /)
+				{
+					# if yes, then append double quotes
+					$sisSource = "file="."\"".$sourcedir."\"";
+				}
+				else
+				{
+					# else dont append any double quotes for destination
+					$sisSource = "file=".$sourcedir;
+				}
+				# push the line on to the array.
+				push(@$sisFileContent,$sisSource."\t".'"'.$destdir.'"');
+			}
+		}
+		#else it's a directory
+		else
+		{
+			&TraverseDir($entry,$folderList.$entry."\/",$sisFileContent,$rootdir);
+		}
+	}
+	closedir(DIR);
+	chdir("..");
+}
+
+# write the data in to oby file by accessing appropriate array.
+sub writeDataToFile
+{
+	my ($array) = @_; 
+	#get the array size.
+	my $arraySize = scalar(@$array);
+	for(my $i=0; $i<$arraySize ; $i++ )
+	{
+		#pop out the element to the respective obey file.
+		my $line=pop(@$array);
+		if (&is_windows){
+			$line =~ s-\/-\\-g;
+		}else{
+			$line =~ s-\\-\/-g;
+		}
+		print NEWDATA $line."\n";
+	}
+}
--- a/imgtools/buildrom/tools/efficient_rom_paging.pm	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/efficient_rom_paging.pm	Tue Jun 29 14:52:54 2010 +0800
@@ -1,474 +1,474 @@
-#
-# Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-# efficent_rom_paging.pm
-# changes the paging/unpaged configuration of binaries a generated
-# OBY file
-# use
-# externaltool=efficient_rom_paging
-# in oby file to enable
-# ## TODO
-# ## keyword alias isn't handled
-#
-
-package efficient_rom_paging;
-use strict;
-
-our @EXPORT=qw(
-    efficient_rom_paging_info
-    efficient_rom_paging_single
-    efficient_rom_paging_multiple
-);
-require Exporter;
-our @ISA = qw(Exporter);
-our @EXPORT_OK = qw();
-
-
-my @moved_entry; # Holds all entries that has been moved without their dependencies
-
-my %seen; # Holds all dependencies to entries in moved_entry
-use File::Basename;
-
-# routine to provide information about the tool
-sub efficient_rom_paging_info ()
-{
-    my %toolinfo;
-    $toolinfo{'name'} = "efficient_rom_paging";
-    $toolinfo{'invocation'} = "InvocationPoint2.5";
-    $toolinfo{'multiple'} = \&efficient_rom_paging_multiple;
-    $toolinfo{'single'} = \&efficient_rom_paging_single;
-    return \%toolinfo;
-}
-
-# routine to handle multiple invocation
-sub efficient_rom_paging_multiple
-{
-    my ($line) = @_;
-    my @args=split /[=\s]/, $line;
-    return "REM efficient_rom_paging.pm";
-}
-
-
-#
-# Hash of all executables and their paged attribute
-#
-my %executables;
-
-
-sub is_oby_statement
-{
-	my ($li) = @_;
-	if ($li =~ /\s*data\s*=/) { return 1;}
-	if ($li =~ /\s*file\s*=/) { return 1;}
-	if ($li =~ /\s*dll\s*=/) { return 1;}
-	if ($li =~ /\s*secondary\s*=/) { return 1;}
-
-	return 0;
-}
-
-# Scan OBY file and move ROM_IMAGE[1] paged executables to ROM_IMAGE[0] part
-sub efficient_rom_paging_single
-{
-	my ($oby) = @_;
-	
-	print "efficient_rom_paging.pm: Making paging more efficient.\n";
-	
-	my $rofs_start = 0;
-	#Find ROFS partition
-	foreach my $line (@$oby)
-	{
-		if ($line =~ /ROM_IMAGE\[1\]/i)
-		{
-			last;
-		}
-		$rofs_start++;
-	}
-
-	my @rom_core_partition = @$oby[0 .. $rofs_start-1];
-	my @rofs_partition = @$oby[$rofs_start .. $#$oby];
-	
-	if (is_pagingoverride_nopaged($oby))
-	{
-		move_all_paged_and_default_nonexecutables_to_core(\@rom_core_partition, \@rofs_partition);
-		move_all_aliases_to_core(\@rom_core_partition, \@rofs_partition);
-		@$oby = (@rom_core_partition, @rofs_partition);
-		print "\n";
-		return;
-	}
-
-	setup_pageable_attribute_array(\@rofs_partition);
-
-	if (is_pagingoverride_defaultpaged($oby))
-	{
-		move_all_default_executables_to_core(\@rom_core_partition, \@rofs_partition);
-	}
-
-	move_all_paged_and_default_nonexecutables_to_core(\@rom_core_partition, \@rofs_partition);
-
-	if (is_pagingoverride_alwayspage($oby))
-	{
-		move_all_executables_to_core(\@rom_core_partition, \@rofs_partition);
-		move_all_aliases_to_core(\@rom_core_partition, \@rofs_partition);
-		@$oby = (@rom_core_partition, @rofs_partition);
-		print "\n";
-		return;
-	}
-	
-	move_all_paged_executables_to_core(\@rom_core_partition, \@rofs_partition);
-	move_all_dependencies_to_core(\@rom_core_partition, \@rofs_partition, $oby);
-	move_all_aliases_to_core(\@rom_core_partition, \@rofs_partition);
-	move_all_renames_to_core(\@rom_core_partition, \@rofs_partition);
-	move_all_patchdata_to_core(\@rom_core_partition, \@rofs_partition);
-	
-	@$oby = (@rom_core_partition, @rofs_partition);
-	print "\n";
-}
-
-sub is_pagingoverride_nopaged
-{
-	my ($oby) = @_;
-	
-	for my $line (@$oby)
-	{
-		if ($line =~ /pagingoverride\s+nopaging/i)
-		{
-			return 1;
-		}
-	}
-	return 0;
-}
-
-sub is_pagingoverride_defaultpaged
-{
-	my ($oby) = @_;
-	
-	for my $line (@$oby)
-	{
-		if ($line =~ /pagingoverride\s+defaultpaged/i)
-		{
-			return 1;
-		}
-	}
-	return 0;
-}
-
-sub is_pagingoverride_alwayspage
-{
-	my ($oby) = @_;
-	
-	for my $line (@$oby)
-	{
-		if ($line =~ /pagingoverride\s+alwayspage/i)
-		{
-			return 1;
-		}
-	}
-	return 0;
-}
-
-
-
-sub setup_pageable_attribute_array
-{
-	my ($rofs_partition) = @_;
-	my $counter = 0;
-	for my $line (@$rofs_partition)
-	{
-		if (is_oby_statement($line))
-		{
-			my $executable;
-			$line =~ /file=(\S+)/i;
-			$executable = $1;
-
-			open DUMP, "ELFTRAN -dump h $executable |" or die "Can't execute ELFTRAN\n";
-			while (my $line=<DUMP>)
-			{
-				if ($line =~ /pageability : (\S+)/i)
-				{
-					$executables{$executable} = $1;
-					print "." if (($counter++ % 10) == 0);
-				}
-			}
-			
-			close DUMP;
-		}
-	}
-}
-
-
-sub move_all_paged_executables_to_core
-{
-	my ($rom_core, $rofs) = @_;
-	
-	my @rofs_execs = grep {$_ =~ /file\s*=/i} @$rofs;
-
-	for my $line (@rofs_execs)
-	{
-		my $executable;
-		$line =~ /file=(\S+) /;
-		$executable = $1;
-
-		if ($line =~ /\s+paged$/i || ($line !~ /\s+unpaged$/i && lc($executables{$executable}) eq 'paged'))
-		{
-
-			push @$rom_core, $line; # Add line to rom core.
-			# Save the executables in a list. Will be used as a cache when dependencies are searched for.
-			push @moved_entry, $executable; 
-			@$rofs = grep {$_ ne $line} @$rofs; # Remove line from rofs partition
-		}
-	}
-}
-
-sub move_all_paged_nonexecutables_to_core
-{
-	my ($rom_core_partition, $rofs_partition) = @_;
-	
-	my @rofs_data = grep {$_ =~ /data\s*=\s*\S+\s+\S*\s+paged/i} @$rofs_partition;
-	
-	for my $line (@rofs_data)
-	{
-		push @$rom_core_partition, $line;
-		@$rofs_partition = grep {$_ ne $line} @$rofs_partition;
-	}
-}
-
-sub move_all_paged_and_default_nonexecutables_to_core
-{
-	my ($rom_core_partition, $rofs_partition) = @_;
-	
-	move_all_paged_nonexecutables_to_core($rom_core_partition, $rofs_partition);
-
-	my @rofs_data = grep {$_ =~ /data=\s*/} @$rofs_partition;
-	@rofs_data = grep {$_ !~ /unpaged/ } @rofs_data;
-	
-	for my $line (@rofs_data)
-	{
-		push @$rom_core_partition, $line;
-		@$rofs_partition = grep {$_ ne $line} @$rofs_partition;
-	}
-}
-
-sub move_all_default_executables_to_core
-{
-	my ($rom_core_partition, $rofs_partition) = @_;
-	
-	my @rofs_execs = grep {$_ =~ /file\s*=/i} @$rofs_partition;
-	
-	# If they have been set to unpaged in the oby file, they shouldn't be moved over.
-	for my $executable (sort keys %executables)
-	{
-		if ($executables{$executable} =~ /default/i)
-		{
-			for my $line (@rofs_execs)
-			{
-				if ($line !~ /unpaged\s*$/i)
-				{
-					my $rofs_executable = $line;
-					$rofs_executable =~ /file\s*=\s*(\S+)/i;
-					$rofs_executable = $1;
-					
-					if ($rofs_executable eq $executable)
-					{
-						push @moved_entry, $executable; 
-						push @$rom_core_partition, $line;
-						@$rofs_partition = grep {$_ ne $line} @$rofs_partition;
-						last;
-					}
-				}
-			}
-		}
-	}
-}
-
-sub move_all_executables_to_core
-{
-	my ($rom_core_partition, $rofs_partition) = @_;
-	
-	my @all_executables = grep {$_ =~ /file\s*=/i} @$rofs_partition;
-	
-	for my $line (@all_executables)
-	{
-		push @$rom_core_partition, $line;
-		push @moved_entry, $line;
-		@$rofs_partition = grep {$_ ne $line} @$rofs_partition;
-	}
-}
-
-sub move_all_aliases_to_core
-{
-	my ($rom_core_partition, $rofs_partition) = @_;
-	
-	my @all_aliases = grep {$_ =~ /^alias\s+\S+\s+\S+/i} @$rofs_partition;
-	
-	for my $line (@all_aliases)
-	{
-		$line =~ /^alias\s+(\S+)\s+\S+/i;
-		my $alias = $1;
-		$alias = basename($alias);
-
-		my @file_stmt = grep {$_ =~ /^\s*(extension|device|file|data)(\[\S+\])?\s*=\s*\S+\s+\S*($alias)(\")?[\s+|\r](\s+\S+)*\s*$/i} @$rom_core_partition;
- 		if(scalar @file_stmt)
-		{
-			push @$rom_core_partition, $line;
-			@$rofs_partition = grep {$_ ne $line} @$rofs_partition;
-		}
-	}
-}
-
-sub move_all_renames_to_core
-{
-	my ($rom_core_partition, $rofs_partition) = @_;
-	
-	my @all_renames = grep {$_ =~ /^rename\s+\S+\s+\S+/i} @$rofs_partition;
-	
-	for my $line (@all_renames)
-	{
-		$line =~ /^rename\s+(\S+)\s+\S+/i;
-		my $rename = $1;
-		$rename = basename($rename);
-
-		for (my $i=0; $i < scalar @$rom_core_partition; $i++)
-		{
-			if ($rename =~ $$rom_core_partition[$i])
-			{
-				splice(@$rom_core_partition, $i+1, 0, $line);
-				@$rofs_partition = grep {$_ ne $line} @$rofs_partition;
-				last;
-			}
-		}
-	}
-}
-
-sub move_all_patchdata_to_core
-{
-	my ($rom_core_partition, $rofs_partition) = @_;
-	
-	my @all_patchdata = grep {$_ =~ /^patchdata\s+\S+\s+\S+\s+/i} @$rofs_partition;
-	
-	for my $line (@all_patchdata)
-	{
-		$line =~ /^patchdata\s+(\S+)\s+\S+\s+/i;
-		my $patchdata = $1;
-		$patchdata = basename($patchdata);
-
-		if (grep($patchdata, @$rom_core_partition))
-		{
-			push @$rom_core_partition, $line;
-			@$rofs_partition = grep {$_ ne $line} @$rofs_partition;
-		}
-	}
-}
-
-sub move_all_dependencies_to_core
-{
-	my ($rom_core_partition, $rofs_partition, $oby) = @_;
-	my $counter = 0;
-	
-	for my $d (@moved_entry) 
-	{
-		if (!exists $seen{$d})
-		{
-			$seen{$d}=();
-			listcomp("", $d, $oby);
-			$counter++;
-			print "." if (($counter % 10) == 0);
-		}
-	}
-	
-	# delete all dependencies that have already been moved to core rom.		
-	for my $exec (@moved_entry)
-	{
-		if (exists $seen{$exec})
-		{
-			delete $seen{$exec};
-		}
-	}
-	# move all dependencies to rom core
-	my @rofs_execs = grep {$_ =~/file\s*=/i} @$rofs_partition;
-	
-	for my $exec (keys %seen)
-	{
-		for my $line (@rofs_execs)
-		{
-			my $rofs_exec = $line;
-			$rofs_exec =~ /file\s*=\s*\S+\s+(\S+)/i;
-			$rofs_exec = $1;
-			$rofs_exec =~ s/"//g;
-			
-			if (basename(lc($exec)) eq basename(lc($rofs_exec)))
-			{
-				push @$rom_core_partition, $line;
-				push @moved_entry, $line;
-				@$rofs_partition = grep {$_ ne $line} @$rofs_partition;
-				last;
-			}
-		}
-	}
-}
-
-# for each exe, list the dependencies
-
-sub listcomp
-{
-	my ($deps, $comp, $oby) = @_;
-	# find dependencies of comp
-	my @ar=getdeps($comp, $oby);
-	# recurse over new dependencies
-	foreach my $d (@ar)
-	{
-		$d=lc($d);
-		if (!exists $seen{$d})
-		{
- 			# recurse
-			$seen{$d}=();
-			listcomp($deps, $d, $oby);
-		}
-	}
-}
-
-sub getdeps
-{
-	my ($comp, $oby) = @_;
-	my @list=();
-	my $hw_base_name = basename($comp);
-	for my $line (@$oby)
-	{
-		if (is_oby_statement($line))
-		{
-			if ($line =~ /\\$hw_base_name/i)
-			{
-				$line =~ /\s*=\s*(\S+)\s*/;
-				$comp = $1;
-				last;
-			}
-		}
-	}
-	
-	open DUMP, "ELFTRAN -dump i $comp |" or die "Can't execute ELFTRAN\n";
-	while (my $line=<DUMP>)
-	{
-		if ($line =~ /imports from (\S+)/i)
-		{
-			my $d = $1;
-			$d =~ s/\{\S{8}\}//; # remove {00000000}
-			$d =~ s/\[\S{8}\]//; # remove [00000000]
-
-			push @list, "$d";
-		}
-	}
-	close DUMP;
-	return @list;
-}
-
-1;
+#
+# Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+# efficent_rom_paging.pm
+# changes the paging/unpaged configuration of binaries a generated
+# OBY file
+# use
+# externaltool=efficient_rom_paging
+# in oby file to enable
+# ## TODO
+# ## keyword alias isn't handled
+#
+
+package efficient_rom_paging;
+use strict;
+
+our @EXPORT=qw(
+    efficient_rom_paging_info
+    efficient_rom_paging_single
+    efficient_rom_paging_multiple
+);
+require Exporter;
+our @ISA = qw(Exporter);
+our @EXPORT_OK = qw();
+
+
+my @moved_entry; # Holds all entries that has been moved without their dependencies
+
+my %seen; # Holds all dependencies to entries in moved_entry
+use File::Basename;
+
+# routine to provide information about the tool
+sub efficient_rom_paging_info ()
+{
+    my %toolinfo;
+    $toolinfo{'name'} = "efficient_rom_paging";
+    $toolinfo{'invocation'} = "InvocationPoint2.5";
+    $toolinfo{'multiple'} = \&efficient_rom_paging_multiple;
+    $toolinfo{'single'} = \&efficient_rom_paging_single;
+    return \%toolinfo;
+}
+
+# routine to handle multiple invocation
+sub efficient_rom_paging_multiple
+{
+    my ($line) = @_;
+    my @args=split /[=\s]/, $line;
+    return "REM efficient_rom_paging.pm";
+}
+
+
+#
+# Hash of all executables and their paged attribute
+#
+my %executables;
+
+
+sub is_oby_statement
+{
+	my ($li) = @_;
+	if ($li =~ /\s*data\s*=/) { return 1;}
+	if ($li =~ /\s*file\s*=/) { return 1;}
+	if ($li =~ /\s*dll\s*=/) { return 1;}
+	if ($li =~ /\s*secondary\s*=/) { return 1;}
+
+	return 0;
+}
+
+# Scan OBY file and move ROM_IMAGE[1] paged executables to ROM_IMAGE[0] part
+sub efficient_rom_paging_single
+{
+	my ($oby) = @_;
+	
+	print "efficient_rom_paging.pm: Making paging more efficient.\n";
+	
+	my $rofs_start = 0;
+	#Find ROFS partition
+	foreach my $line (@$oby)
+	{
+		if ($line =~ /ROM_IMAGE\[1\]/i)
+		{
+			last;
+		}
+		$rofs_start++;
+	}
+
+	my @rom_core_partition = @$oby[0 .. $rofs_start-1];
+	my @rofs_partition = @$oby[$rofs_start .. $#$oby];
+	
+	if (is_pagingoverride_nopaged($oby))
+	{
+		move_all_paged_and_default_nonexecutables_to_core(\@rom_core_partition, \@rofs_partition);
+		move_all_aliases_to_core(\@rom_core_partition, \@rofs_partition);
+		@$oby = (@rom_core_partition, @rofs_partition);
+		print "\n";
+		return;
+	}
+
+	setup_pageable_attribute_array(\@rofs_partition);
+
+	if (is_pagingoverride_defaultpaged($oby))
+	{
+		move_all_default_executables_to_core(\@rom_core_partition, \@rofs_partition);
+	}
+
+	move_all_paged_and_default_nonexecutables_to_core(\@rom_core_partition, \@rofs_partition);
+
+	if (is_pagingoverride_alwayspage($oby))
+	{
+		move_all_executables_to_core(\@rom_core_partition, \@rofs_partition);
+		move_all_aliases_to_core(\@rom_core_partition, \@rofs_partition);
+		@$oby = (@rom_core_partition, @rofs_partition);
+		print "\n";
+		return;
+	}
+	
+	move_all_paged_executables_to_core(\@rom_core_partition, \@rofs_partition);
+	move_all_dependencies_to_core(\@rom_core_partition, \@rofs_partition, $oby);
+	move_all_aliases_to_core(\@rom_core_partition, \@rofs_partition);
+	move_all_renames_to_core(\@rom_core_partition, \@rofs_partition);
+	move_all_patchdata_to_core(\@rom_core_partition, \@rofs_partition);
+	
+	@$oby = (@rom_core_partition, @rofs_partition);
+	print "\n";
+}
+
+sub is_pagingoverride_nopaged
+{
+	my ($oby) = @_;
+	
+	for my $line (@$oby)
+	{
+		if ($line =~ /pagingoverride\s+nopaging/i)
+		{
+			return 1;
+		}
+	}
+	return 0;
+}
+
+sub is_pagingoverride_defaultpaged
+{
+	my ($oby) = @_;
+	
+	for my $line (@$oby)
+	{
+		if ($line =~ /pagingoverride\s+defaultpaged/i)
+		{
+			return 1;
+		}
+	}
+	return 0;
+}
+
+sub is_pagingoverride_alwayspage
+{
+	my ($oby) = @_;
+	
+	for my $line (@$oby)
+	{
+		if ($line =~ /pagingoverride\s+alwayspage/i)
+		{
+			return 1;
+		}
+	}
+	return 0;
+}
+
+
+
+sub setup_pageable_attribute_array
+{
+	my ($rofs_partition) = @_;
+	my $counter = 0;
+	for my $line (@$rofs_partition)
+	{
+		if (is_oby_statement($line))
+		{
+			my $executable;
+			$line =~ /file=(\S+)/i;
+			$executable = $1;
+
+			open DUMP, "ELFTRAN -dump h $executable |" or die "Can't execute ELFTRAN\n";
+			while (my $line=<DUMP>)
+			{
+				if ($line =~ /pageability : (\S+)/i)
+				{
+					$executables{$executable} = $1;
+					print "." if (($counter++ % 10) == 0);
+				}
+			}
+			
+			close DUMP;
+		}
+	}
+}
+
+
+sub move_all_paged_executables_to_core
+{
+	my ($rom_core, $rofs) = @_;
+	
+	my @rofs_execs = grep {$_ =~ /file\s*=/i} @$rofs;
+
+	for my $line (@rofs_execs)
+	{
+		my $executable;
+		$line =~ /file=(\S+) /;
+		$executable = $1;
+
+		if ($line =~ /\s+paged$/i || ($line !~ /\s+unpaged$/i && lc($executables{$executable}) eq 'paged'))
+		{
+
+			push @$rom_core, $line; # Add line to rom core.
+			# Save the executables in a list. Will be used as a cache when dependencies are searched for.
+			push @moved_entry, $executable; 
+			@$rofs = grep {$_ ne $line} @$rofs; # Remove line from rofs partition
+		}
+	}
+}
+
+sub move_all_paged_nonexecutables_to_core
+{
+	my ($rom_core_partition, $rofs_partition) = @_;
+	
+	my @rofs_data = grep {$_ =~ /data\s*=\s*\S+\s+\S*\s+paged/i} @$rofs_partition;
+	
+	for my $line (@rofs_data)
+	{
+		push @$rom_core_partition, $line;
+		@$rofs_partition = grep {$_ ne $line} @$rofs_partition;
+	}
+}
+
+sub move_all_paged_and_default_nonexecutables_to_core
+{
+	my ($rom_core_partition, $rofs_partition) = @_;
+	
+	move_all_paged_nonexecutables_to_core($rom_core_partition, $rofs_partition);
+
+	my @rofs_data = grep {$_ =~ /data=\s*/} @$rofs_partition;
+	@rofs_data = grep {$_ !~ /unpaged/ } @rofs_data;
+	
+	for my $line (@rofs_data)
+	{
+		push @$rom_core_partition, $line;
+		@$rofs_partition = grep {$_ ne $line} @$rofs_partition;
+	}
+}
+
+sub move_all_default_executables_to_core
+{
+	my ($rom_core_partition, $rofs_partition) = @_;
+	
+	my @rofs_execs = grep {$_ =~ /file\s*=/i} @$rofs_partition;
+	
+	# If they have been set to unpaged in the oby file, they shouldn't be moved over.
+	for my $executable (sort keys %executables)
+	{
+		if ($executables{$executable} =~ /default/i)
+		{
+			for my $line (@rofs_execs)
+			{
+				if ($line !~ /unpaged\s*$/i)
+				{
+					my $rofs_executable = $line;
+					$rofs_executable =~ /file\s*=\s*(\S+)/i;
+					$rofs_executable = $1;
+					
+					if ($rofs_executable eq $executable)
+					{
+						push @moved_entry, $executable; 
+						push @$rom_core_partition, $line;
+						@$rofs_partition = grep {$_ ne $line} @$rofs_partition;
+						last;
+					}
+				}
+			}
+		}
+	}
+}
+
+sub move_all_executables_to_core
+{
+	my ($rom_core_partition, $rofs_partition) = @_;
+	
+	my @all_executables = grep {$_ =~ /file\s*=/i} @$rofs_partition;
+	
+	for my $line (@all_executables)
+	{
+		push @$rom_core_partition, $line;
+		push @moved_entry, $line;
+		@$rofs_partition = grep {$_ ne $line} @$rofs_partition;
+	}
+}
+
+sub move_all_aliases_to_core
+{
+	my ($rom_core_partition, $rofs_partition) = @_;
+	
+	my @all_aliases = grep {$_ =~ /^alias\s+\S+\s+\S+/i} @$rofs_partition;
+	
+	for my $line (@all_aliases)
+	{
+		$line =~ /^alias\s+(\S+)\s+\S+/i;
+		my $alias = $1;
+		$alias = basename($alias);
+
+		my @file_stmt = grep {$_ =~ /^\s*(extension|device|file|data)(\[\S+\])?\s*=\s*\S+\s+\S*($alias)(\")?[\s+|\r](\s+\S+)*\s*$/i} @$rom_core_partition;
+ 		if(scalar @file_stmt)
+		{
+			push @$rom_core_partition, $line;
+			@$rofs_partition = grep {$_ ne $line} @$rofs_partition;
+		}
+	}
+}
+
+sub move_all_renames_to_core
+{
+	my ($rom_core_partition, $rofs_partition) = @_;
+	
+	my @all_renames = grep {$_ =~ /^rename\s+\S+\s+\S+/i} @$rofs_partition;
+	
+	for my $line (@all_renames)
+	{
+		$line =~ /^rename\s+(\S+)\s+\S+/i;
+		my $rename = $1;
+		$rename = basename($rename);
+
+		for (my $i=0; $i < scalar @$rom_core_partition; $i++)
+		{
+			if ($rename =~ $$rom_core_partition[$i])
+			{
+				splice(@$rom_core_partition, $i+1, 0, $line);
+				@$rofs_partition = grep {$_ ne $line} @$rofs_partition;
+				last;
+			}
+		}
+	}
+}
+
+sub move_all_patchdata_to_core
+{
+	my ($rom_core_partition, $rofs_partition) = @_;
+	
+	my @all_patchdata = grep {$_ =~ /^patchdata\s+\S+\s+\S+\s+/i} @$rofs_partition;
+	
+	for my $line (@all_patchdata)
+	{
+		$line =~ /^patchdata\s+(\S+)\s+\S+\s+/i;
+		my $patchdata = $1;
+		$patchdata = basename($patchdata);
+
+		if (grep($patchdata, @$rom_core_partition))
+		{
+			push @$rom_core_partition, $line;
+			@$rofs_partition = grep {$_ ne $line} @$rofs_partition;
+		}
+	}
+}
+
+sub move_all_dependencies_to_core
+{
+	my ($rom_core_partition, $rofs_partition, $oby) = @_;
+	my $counter = 0;
+	
+	for my $d (@moved_entry) 
+	{
+		if (!exists $seen{$d})
+		{
+			$seen{$d}=();
+			listcomp("", $d, $oby);
+			$counter++;
+			print "." if (($counter % 10) == 0);
+		}
+	}
+	
+	# delete all dependencies that have already been moved to core rom.		
+	for my $exec (@moved_entry)
+	{
+		if (exists $seen{$exec})
+		{
+			delete $seen{$exec};
+		}
+	}
+	# move all dependencies to rom core
+	my @rofs_execs = grep {$_ =~/file\s*=/i} @$rofs_partition;
+	
+	for my $exec (keys %seen)
+	{
+		for my $line (@rofs_execs)
+		{
+			my $rofs_exec = $line;
+			$rofs_exec =~ /file\s*=\s*\S+\s+(\S+)/i;
+			$rofs_exec = $1;
+			$rofs_exec =~ s/"//g;
+			
+			if (basename(lc($exec)) eq basename(lc($rofs_exec)))
+			{
+				push @$rom_core_partition, $line;
+				push @moved_entry, $line;
+				@$rofs_partition = grep {$_ ne $line} @$rofs_partition;
+				last;
+			}
+		}
+	}
+}
+
+# for each exe, list the dependencies
+
+sub listcomp
+{
+	my ($deps, $comp, $oby) = @_;
+	# find dependencies of comp
+	my @ar=getdeps($comp, $oby);
+	# recurse over new dependencies
+	foreach my $d (@ar)
+	{
+		$d=lc($d);
+		if (!exists $seen{$d})
+		{
+ 			# recurse
+			$seen{$d}=();
+			listcomp($deps, $d, $oby);
+		}
+	}
+}
+
+sub getdeps
+{
+	my ($comp, $oby) = @_;
+	my @list=();
+	my $hw_base_name = basename($comp);
+	for my $line (@$oby)
+	{
+		if (is_oby_statement($line))
+		{
+			if ($line =~ /[\/\\]$hw_base_name/i)
+			{
+				$line =~ /\s*=\s*(\S+)\s*/;
+				$comp = $1;
+				last;
+			}
+		}
+	}
+	
+	open DUMP, "ELFTRAN -dump i $comp |" or die "Can't execute ELFTRAN\n";
+	while (my $line=<DUMP>)
+	{
+		if ($line =~ /imports from (\S+)/i)
+		{
+			my $d = $1;
+			$d =~ s/\{\S{8}\}//; # remove {00000000}
+			$d =~ s/\[\S{8}\]//; # remove [00000000]
+
+			push @list, "$d";
+		}
+	}
+	close DUMP;
+	return @list;
+}
+
+1;
--- a/imgtools/buildrom/tools/externaltools.pm	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/externaltools.pm	Tue Jun 29 14:52:54 2010 +0800
@@ -1,165 +1,189 @@
-#
-# Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-# This package invokes single and multiple external tools
-#
-
-package externaltools;
-
-require Exporter;
-@ISA=qw (Exporter);
-@EXPORT=qw (
-	loadTools
-	runExternalTool
-		
-);
-
-use Modload; # Dynamically loads the module
-my %invocations; # Indexed by invocation name;
-
-#Set the Module path to load perl modules
-{
-	my $epocToolsPath = $ENV{EPOCROOT}."epoc32\\tools\\";
-	Load_SetModulePath($epocToolsPath);
-}
-
-# Get all the external tool perl module files to load them
-sub loadTools{
-	
-	my $toolList = shift;
-	my @toolModules = split(/,/,$toolList);
-	foreach my $tool (@toolModules) {
-		# An optional command line can be passed to the tool if it is of the form "<toolname>[:<cmdline>]"
-		if ($tool !~ /^([^:]+)(:(.*))?$/) {
-			print "No tool specified as parameter for external tool invocation\n";
-		}
-		my $toolName = $1;
-		my $toolCmdLine = $3;
-		&Load_ModuleL($toolName);
-		my $toolDetailsMap = $toolName.'::' . $toolName.'_info';
-		update(&$toolDetailsMap, $toolCmdLine);
-	}
-}
-
-#Initialises information from external tool
-sub update 
-{
-	my ($info, $toolCmdLine) = @_;
-	my $toolName;
-	my $toolStage;
-
-	# name - name of the tool. used to associate with appropriate oby tool
-	#		keyword
-	# invocation - stage when tool shall be invoked.
-	# multiple - routine to invoke for multiple invocation
-	# single - routine to invoke for single invocation
-	# initialize - optional routine to initialize tool before main invocation.
-	# 
-	if (defined ($info->{name})) {
-		$toolName = $info->{name};
-	}
-	if (defined ($info->{invocation})) {
-		$toolStage = lc $info->{invocation};
-	}
-    
-    push @{$invocations{$toolStage}}, $info;
-	
-	if (defined ($info->{initialize}))
-		{
-		&{$$info{'initialize'}}($toolCmdLine);
-		}
-}
-
-# Called between the buildrom stage to invoke single or multiple invocation
-sub runExternalTool {
-	
-	my ($stageName,$OBYData) = @_;
-	$stageName = lc $stageName;
-	my @toolInfoList =  @{$invocations{$stageName}}; # Collect Tools with respect to its stagename.
-	
-	foreach my $tool (@toolInfoList) { # Traverse for the tools
-
-		if (exists($tool->{single})) {#Check if single invocation exists
-			if (defined ($OBYData)) {
-				invoke_single($OBYData, $tool);
-			}				
-			else {
-				print "Empty OBYData array reference in Single Invocation\n";
-			}
-
-		}#End Single if 
-
-		if (exists($tool->{multiple})) { #Check if multiple invocation exists
-			if (defined ($OBYData)) { 
-				# Called from appropriate stage to invoke multiple invocation
-				invoke_multiple($OBYData, $tool);
-			}
-			else {
-				print "Empty OBYData Line in Multiple Invocation\n";
-			}
-
-		}#End Multiple if 
-
-	}#End of tool traversal
-	
-}#End of Method
-
-#Runs Tool for each line of the OBY file
-#Gets modified line and adds to OBY line data reference
-sub invoke_multiple
-{
-    my ($OBYDataRef,$tool) = @_;
-	my $modifiedOBYLine;
-	my $toolName;
-	my $index = 0;# Index each OBY line
-	my $arrayLength = scalar(@$OBYDataRef);
-	my $OBYLineRef;
-
-	while ($index < $arrayLength) {
-
-		$OBYLineRef = \$OBYDataRef->[$index];# Get the line reference
-			
-		if ($$OBYLineRef =~/tool=(\w+)/){ # Match for 'tool' keyword
-			$toolName = $1;
-
-			if ($toolName eq $tool->{name}) {# Match the tool name
-				my $routine=$tool->{multiple};
-				$modifiedOBYLine = &$routine($$OBYLineRef); #Invoke multiple Invocation, get modified line
-			
-				if (defined ($modifiedOBYLine)) { # If line is not empty
-					$$OBYLineRef = $modifiedOBYLine; # Modify the line reference with new line
-				}
-
-			}#End of if toolname match
-
-		}#End of if 'tool' keyword match
-
-		$index++; # For each line of OBY file.
-	
-	}#End of oby line traversal <while>
-
-}
-
-#Runs Tool only once.
-#Add new data to the obydata array reference.
-sub invoke_single {
-
-    my ($OBYDataRef,$tool) = @_;
-    my $routine = $tool->{single};
-    &$routine($OBYDataRef);#Invoke single Invocation, update new data
-}
-
-
-
-1;
\ No newline at end of file
+#
+# Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+# This package invokes single and multiple external tools
+#
+
+package externaltools;
+
+require Exporter;
+@ISA=qw (Exporter);
+@EXPORT=qw (
+	loadTools
+	runExternalTool
+		
+);
+
+use flexmodload; # Dynamically loads the module
+use IPC::Open3;
+my %invocations; # Indexed by invocation name;
+
+# Get all the external tool perl module files to load them
+sub loadTools{
+	
+	my $toolList = shift;
+	my @toolModules = split(/,/,$toolList);
+	foreach my $tool (@toolModules) {
+		# An optional command line can be passed to the tool if it is of the form "<toolname>[:<cmdline>]"
+		if ($tool !~ /^([^:]+)(:(.*))?$/) {
+			print "No tool specified as parameter for external tool invocation\n";
+		}
+		my $toolName = $1;
+		my $toolCmdLine = $3;
+		if($toolName =~ /configpaging/i){			 
+			my %info = (name=>"configpaging", args=>$toolCmdLine ); 
+			push @{$invocations{"invocationpoint2"}}, \%info;
+		}else{
+			&FlexLoad_ModuleL($toolName);
+			my $toolDetailsMap = $toolName.'::' . $toolName.'_info';
+			update(&$toolDetailsMap, $toolCmdLine);
+		}
+		
+	}
+}
+
+#Initialises information from external tool
+sub update 
+{
+	my ($info, $toolCmdLine) = @_;
+	my $toolName;
+	my $toolStage;
+
+	# name - name of the tool. used to associate with appropriate oby tool
+	#		keyword
+	# invocation - stage when tool shall be invoked.
+	# multiple - routine to invoke for multiple invocation
+	# single - routine to invoke for single invocation
+	# initialize - optional routine to initialize tool before main invocation.
+	# 
+	if (defined ($info->{name})) {
+		$toolName = $info->{name};
+	}
+	if (defined ($info->{invocation})) {
+		$toolStage = lc $info->{invocation};
+	}
+    
+    push @{$invocations{$toolStage}}, $info;
+	
+	if (defined ($info->{initialize}))
+		{
+		&{$$info{'initialize'}}($toolCmdLine);
+		}
+}
+
+# Called between the buildrom stage to invoke single or multiple invocation
+sub runExternalTool {
+	
+	my ($stageName,$OBYData) = @_;
+	$stageName = lc $stageName;
+	my @toolInfoList =  @{$invocations{$stageName}}; # Collect Tools with respect to its stagename.
+	
+	foreach my $tool (@toolInfoList) { # Traverse for the tools
+		if($tool->{name} eq "configpaging"){
+			my $pid ; 
+			my $args = $tool->{args};
+		
+			open CONFIG, "| configpaging $args >cfgp_out.oby" or die "* Can't execute cpp";
+	
+			foreach (@$OBYData){
+				chomp ;
+				print CONFIG $_."\n";				 		
+			} 
+			print CONFIG ":q\n";  #terminate the program
+
+			close CONFIG;
+	
+			my $config_status = $?;
+			die "* configpaging failed\n" if ($config_status != 0 || !-f "cfgp_out.oby");
+
+			if(open(INTF,"cfgp_out.oby")){
+				@$OBYData = <INTF>;
+				close INTF;
+			}			
+			unlink("cfgp_out.oby") or die "cannot delete cfgp_out.oby";	
+			next ;
+		}
+		if (exists($tool->{single})) {#Check if single invocation exists
+			if (defined ($OBYData)) {
+				invoke_single($OBYData, $tool);
+			}				
+			else {
+				print "Empty OBYData array reference in Single Invocation\n";
+			}
+
+		}#End Single if 
+
+		if (exists($tool->{multiple})) { #Check if multiple invocation exists
+			if (defined ($OBYData)) { 
+				# Called from appropriate stage to invoke multiple invocation
+				invoke_multiple($OBYData, $tool);
+			}
+			else {
+				print "Empty OBYData Line in Multiple Invocation\n";
+			}
+
+		}#End Multiple if 
+
+	}#End of tool traversal
+	
+}#End of Method
+
+#Runs Tool for each line of the OBY file
+#Gets modified line and adds to OBY line data reference
+sub invoke_multiple
+{
+    my ($OBYDataRef,$tool) = @_;
+	my $modifiedOBYLine;
+	my $toolName;
+	my $index = 0;# Index each OBY line
+	my $arrayLength = scalar(@$OBYDataRef);
+	my $OBYLineRef;
+
+	while ($index < $arrayLength) {
+
+		$OBYLineRef = \$OBYDataRef->[$index];# Get the line reference
+			
+		if ($$OBYLineRef =~/tool=(\w+)/){ # Match for 'tool' keyword
+			$toolName = $1;
+
+			if ($toolName eq $tool->{name}) {# Match the tool name
+				my $routine=$tool->{multiple};
+				$modifiedOBYLine = &$routine($$OBYLineRef); #Invoke multiple Invocation, get modified line
+			
+				if (defined ($modifiedOBYLine)) { # If line is not empty
+					$$OBYLineRef = $modifiedOBYLine; # Modify the line reference with new line
+				}
+
+			}#End of if toolname match
+
+		}#End of if 'tool' keyword match
+
+		$index++; # For each line of OBY file.
+	
+	}#End of oby line traversal <while>
+
+}
+
+#Runs Tool only once.
+#Add new data to the obydata array reference.
+sub invoke_single {
+
+    my ($OBYDataRef,$tool) = @_;
+    my $routine = $tool->{single};
+    &$routine($OBYDataRef);#Invoke single Invocation, update new data
+}
+
+
+
+1;
--- a/imgtools/buildrom/tools/featurefile.pm	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/featurefile.pm	Tue Jun 29 14:52:54 2010 +0800
@@ -1,187 +1,187 @@
-#
-# Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-#
-
-# This package contains common routines required for the creation of feature registry configuration/
-# features data file.
-package featurefile;
-
-# Include Module package
-use FileHandle;
-use WRITER;
-
-use strict;
-
-# Class constructor
-sub new 
-{
-	my ($class,$xmlDBHandle) = @_;
-
-	my $object = {};
-	$object->{_FEATUREFILENAME} = undef;
-	$object->{_FILEHANDLE} = undef;
-	$object->{_FILEVERSION} = undef;
-	$object->{_FEATCOUNT} = 0;
-	$object->{_DEFAULTRANGECOUNT} = 0;
-	$object->{_XMLDBHANDLE} = $xmlDBHandle;
-	
-	bless($object, $class);
-	return $object;
-}
-
-# Subroutine to create feature registry configuration/features data file
-# @param $object					- Object reference which is passed implicitly
-# @param _FEATUREFILENAME			- Feature registry configuration/features data filename
-# @param _FEATURELIST				- The complete List of features which are either to be included or excluded
-sub createFile
-{
-	my $object = shift;
-	$object->{_FEATUREFILENAME} = shift;
-	$object->{_FEATURELIST} = shift;
-		
-	# Open feature file for writing	
-	if (!$object->openFile())
-	{
-		return 0;
-	}
-
-	# Create feauture map
-	$object->createFeatureMap();
-	
-	# Set feature count
-	$object->setFeatureCount();
-
-	# Set Default Range Count
-	$object->setDefaultRangeCount();
-	
-	# Write feature file header
-	$object->writeHeader();	
-
-	# Create feature entry for the listed features
-	$object->writeFeatures();
-
-	# Write Default Supported Range 
-	$object->writeDefault();
-	
-	# Close feature file.
-	$object->closeFile();
-
-	return 1;
-}
-
-# Subroutine to open feature file 
-# @param $object					- Object reference which is passed implicitly
-sub openFile
-{
-	my $object = shift;	
-
-	open (CONFIG_FH, ">$object->{_FEATUREFILENAME}");
-	binmode(CONFIG_FH);
-	$object->{_FILEHANDLE} = *CONFIG_FH;
-
-	if(!defined $object->{_FILEHANDLE})
-	{
-		print "\nError in creating the $object->{_FEATUREFILENAME}, check for the accessability of File / Drive\n";
-		return 0;
-	}
-	return 1;
-}
-
-# Subroutine to write feature file header
-# @param $object					- Object reference which is passed implicitly
-sub writeHeader
-{
-	my $object = shift;
-
-	$object->write2File(0x74616566);
-	$object->write2File($object->{_FILEVERSION});
-	$object->write2File($object->{_FEATCOUNT});
-	$object->write2File($object->{_DEFAULTRANGECOUNT});
-}
-
-# Subroutine to check if the feature is present in feature databse XML file
-# @param $object					- Object reference which is passed implicitly
-sub isPresentInFeatureListXML
-{
-	my $object = shift;
-	my $fidMain= shift;	
-	
-	# If the feature is not found, generate an error message.
-	if(!defined $fidMain->{uid})
-	{
-		print "Error:Feature $fidMain->{name} not found in feature list XML \n";
-		return 0;
-	}	
-	return 1;
-}
-
-# Subroutine to set the count of listed features in feature file
-# @param $object					- Object reference which is passed implicitly
-sub setFeatureCount
-{
-	my $object = shift;
-
-	$object->{_FEATCOUNT} = scalar (keys %{$object->{_FEATUREHASHMAP}});	
-}
-
-# Subroutine to set the count of Default Support Range(D.S.R)
-# @param $object					- Object reference which is passed implicitly
-sub setDefaultRangeCount
-{
-	my $object = shift;
-	
-	$object->{_DEFAULTRANGECOUNT} = ($object->{_XMLDBHANDLE})->defaultIncludeCount();
-}
-
-# Write the default=present featureUID ranges (min/lowerruid,max/higheruid) to the feature file 
-# @param $object					- Object reference which is passed implicitly
-sub writeDefault
-{
-	my $object = shift;
-
-	if ($object->{_DEFAULTRANGECOUNT}) 
-	{
-		my @defaultFeatures = ($object->{_XMLDBHANDLE})->getDefaultIncludeInfo();
-		for my $i ( 0 .. $#defaultFeatures )
-		{
-			my $minuid = $defaultFeatures[$i][0];
-			my $maxuid = $defaultFeatures[$i][1];		
-			$object->write2File($minuid);
-			$object->write2File($maxuid);
-		}
-	}
-}
-
-# Subroutine to close feature file. 
-# @param $object					- Object reference which is passed implicitly
-sub closeFile
-{
-	my $object = shift;
-
-	close $object->{_FILEHANDLE};
-}
-
-# Subroutine to write the bytes to the binary file. 
-# @param $object					- Object reference which is passed implicitly
-# @param $bytes						- 32-bit value which is to be writen in binary file.
-sub write2File
-{
-	my $object = shift;
-	my $bytes = shift;
-
-	&WRITER::write32($object->{_FILEHANDLE}, $bytes);
-}
-
-1;
\ No newline at end of file
+#
+# Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+#
+
+# This package contains common routines required for the creation of feature registry configuration/
+# features data file.
+package featurefile;
+
+# Include Module package
+use FileHandle;
+use romutl;
+
+use strict;
+
+# Class constructor
+sub new 
+{
+	my ($class,$xmlDBHandle) = @_;
+
+	my $object = {};
+	$object->{_FEATUREFILENAME} = undef;
+	$object->{_FILEHANDLE} = undef;
+	$object->{_FILEVERSION} = undef;
+	$object->{_FEATCOUNT} = 0;
+	$object->{_DEFAULTRANGECOUNT} = 0;
+	$object->{_XMLDBHANDLE} = $xmlDBHandle;
+	
+	bless($object, $class);
+	return $object;
+}
+
+# Subroutine to create feature registry configuration/features data file
+# @param $object					- Object reference which is passed implicitly
+# @param _FEATUREFILENAME			- Feature registry configuration/features data filename
+# @param _FEATURELIST				- The complete List of features which are either to be included or excluded
+sub createFile
+{
+	my $object = shift;
+	$object->{_FEATUREFILENAME} = shift;
+	$object->{_FEATURELIST} = shift;
+		
+	# Open feature file for writing	
+	if (!$object->openFile())
+	{
+		return 0;
+	}
+
+	# Create feauture map
+	$object->createFeatureMap();
+	
+	# Set feature count
+	$object->setFeatureCount();
+
+	# Set Default Range Count
+	$object->setDefaultRangeCount();
+	
+	# Write feature file header
+	$object->writeHeader();	
+
+	# Create feature entry for the listed features
+	$object->writeFeatures();
+
+	# Write Default Supported Range 
+	$object->writeDefault();
+	
+	# Close feature file.
+	$object->closeFile();
+
+	return 1;
+}
+
+# Subroutine to open feature file 
+# @param $object					- Object reference which is passed implicitly
+sub openFile
+{
+	my $object = shift;	
+
+	open (CONFIG_FH, ">$object->{_FEATUREFILENAME}");
+	binmode(CONFIG_FH);
+	$object->{_FILEHANDLE} = *CONFIG_FH;
+
+	if(!defined $object->{_FILEHANDLE})
+	{
+		print "\nError in creating the $object->{_FEATUREFILENAME}, check for the accessability of File / Drive\n";
+		return 0;
+	}
+	return 1;
+}
+
+# Subroutine to write feature file header
+# @param $object					- Object reference which is passed implicitly
+sub writeHeader
+{
+	my $object = shift;
+
+	$object->write2File(0x74616566);
+	$object->write2File($object->{_FILEVERSION});
+	$object->write2File($object->{_FEATCOUNT});
+	$object->write2File($object->{_DEFAULTRANGECOUNT});
+}
+
+# Subroutine to check if the feature is present in feature databse XML file
+# @param $object					- Object reference which is passed implicitly
+sub isPresentInFeatureListXML
+{
+	my $object = shift;
+	my $fidMain= shift;	
+	
+	# If the feature is not found, generate an error message.
+	if(!defined $fidMain->{uid})
+	{
+		print "Error:Feature $fidMain->{name} not found in feature list XML \n";
+		return 0;
+	}	
+	return 1;
+}
+
+# Subroutine to set the count of listed features in feature file
+# @param $object					- Object reference which is passed implicitly
+sub setFeatureCount
+{
+	my $object = shift;
+
+	$object->{_FEATCOUNT} = scalar (keys %{$object->{_FEATUREHASHMAP}});	
+}
+
+# Subroutine to set the count of Default Support Range(D.S.R)
+# @param $object					- Object reference which is passed implicitly
+sub setDefaultRangeCount
+{
+	my $object = shift;
+	
+	$object->{_DEFAULTRANGECOUNT} = ($object->{_XMLDBHANDLE})->defaultIncludeCount();
+}
+
+# Write the default=present featureUID ranges (min/lowerruid,max/higheruid) to the feature file 
+# @param $object					- Object reference which is passed implicitly
+sub writeDefault
+{
+	my $object = shift;
+
+	if ($object->{_DEFAULTRANGECOUNT}) 
+	{
+		my @defaultFeatures = ($object->{_XMLDBHANDLE})->getDefaultIncludeInfo();
+		for my $i ( 0 .. $#defaultFeatures )
+		{
+			my $minuid = $defaultFeatures[$i][0];
+			my $maxuid = $defaultFeatures[$i][1];		
+			$object->write2File($minuid);
+			$object->write2File($maxuid);
+		}
+	}
+}
+
+# Subroutine to close feature file. 
+# @param $object					- Object reference which is passed implicitly
+sub closeFile
+{
+	my $object = shift;
+
+	close $object->{_FILEHANDLE};
+}
+
+# Subroutine to write the bytes to the binary file. 
+# @param $object					- Object reference which is passed implicitly
+# @param $bytes						- 32-bit value which is to be writen in binary file.
+sub write2File
+{
+	my $object = shift;
+	my $bytes = shift;
+
+	write_32bit($object->{_FILEHANDLE}, $bytes);
+}
+
+1;
--- a/imgtools/buildrom/tools/featuremanager.pm	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/featuremanager.pm	Tue Jun 29 14:52:54 2010 +0800
@@ -1,852 +1,850 @@
-#
-# Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-#
-
-# This package contains routines to read the information from the Feature manager XML file.
-package featuremanager; # Derived class for the feature manager xml parser
-
-BEGIN {
-	@ISA = qw(featureparser); # Derived from featuerParser
-	require featureparser;
-};
-
-use constant STRICTCASE=>1; # To suppress the case conversion in genericparser routine
-
-# Parse the featuredatabase XML file and generate the maps and counts
-#
-#featureset:
-# {namespace}<namespace> - optional
-# {ibyname}<ibyname> - optional
-# {hfilename}<hfilename> - optional
-# {hfileheader}<fileheader> - optional
-# {interfacestatus}<interfacestatus> -optional
-# {interfacevisibility}<interfacevisibility> - optional
-# {feature_list}<nameuidmap>
-# {feature} {<uid1>}{statusflags}<statusflag>
-#					{name}<name>
-#					{userdata}<userdata> - optional
-#					{includemacro}<macro>
-#					{excludemacro}<macro>
-#					{infeaturesetiby}<yes/no> - optional
-#					{comment}<comment> - optional
-#			{<uid2>}{statusflags}<statusflag>
-#					{name}<name>
-#					{userdata}<userdata> - optional
-#					{includemacro}<macro>
-#					{excludemacro}<macro>
-#					{infeaturesetiby}<yes/no> - optional
-#					{comment}<comment>
-#
-
-#
-# Class constructor
-#
-sub new
-{
-	my $class = shift;
-	my $object = $class->SUPER::new();
-	
-	# Class members
-	$object->{_OBJNAME} = "FeatureManager"; # Name of the object
-	$object->{_FEAT_SET_LIST} = [];  # Array of <featureset> hash maps
-	$object->{_FEAT_LIST} = {};      # Hash map of all feature name with uid
-	$object->{_ALIAS_FEAT_LIST} = {}; # Hash map of all alias feature name with uid
-	return $object;
-}
-
-#
-# Private methods
-#
-
-# Private method to Get/Set the _FEAT_SET_LIST member value of this class
-# @param : reference to the array of <featureset> hash maps (optional for GET)
-#
-my $featuresetList = sub 
-{
-	my $object = shift; 
-	return 0 if(!&featureparser::ISREF($object,"featuresetList"));
-	
-	if (@_) 
-	{ 
-		$object->{_FEAT_SET_LIST} = shift; 
-	}
-	return $object->{_FEAT_SET_LIST};
-};
-
-# Private method to Get/Set the _FEAT_LIST member value of this class
-# @param : reference to the fash map of feature name with uid (optional for GET)
-#
-my $featureList = sub 
-{
-	my $object = shift; 
-	return 0 if(!&featureparser::ISREF($object,"featureList"));
-	
-	if (@_) 
-	{ 
-		$object->{_FEAT_LIST} = shift; 
-	}
-	return $object->{_FEAT_LIST};
-};
-# Private method ot Get/Set the _ALIAS_FEAT_LIST member value of this class
-# @param: reference to the hash map of alias feature name with uid
-my $aliasfeatureList = sub
-{
-	my $object = shift;
-	return 0 if(!&featureparser::ISREF($object, "aliasfeatureList"));
-
-	if(@_)
-	{
-		$object->{_ALIAS_FEAT_LIST} = shift;
-	}
-	return $object->{_ALIAS_FEAT_LIST};
-};
-
-# Read the attributes of <featureset> element
-# @param : reference to the featureset
-# @param : reference to the attributemap
-#
-my $fillFeatureSetAttributes = sub 
-{
-	my  $node = shift;
-	my  $map = shift;
-	$map->{ibyname} = &featureparser::getattrValue($node, "ibyname", STRICTCASE);
-	$map->{hfilename} = &featureparser::getattrValue($node, "hfilename", STRICTCASE);
-	$map->{namespace} = &featureparser::getattrValue($node, "namespace", STRICTCASE);
-};
-
-# Read the attributes of <hfileheader> element
-# @param : reference to the featureset
-# @param : reference to the attributemap
-#
-my $fillFileHeaderAttributes = sub 
-{
-	my $node = shift;
-	my $map = shift;
-	my @attribSet =  &featureparser::getnodefromTree($node, "hfileheader");
-	
-	foreach my $att_node (@attribSet) 
-	{
-		$map->{interfacestatus} = &featureparser::getattrValue($att_node, "interfacestatus",STRICTCASE);
-		$map->{interfacevisibility} = &featureparser::getattrValue($att_node, "interfacevisibility",STRICTCASE);
-		$map->{hfileheader} = &featureparser::getelementValue($att_node,STRICTCASE);
-	}
-};
-
-# Read the attributes of <feature> element
-# @param : reference to the featureset
-# @param : reference to the attributemap
-#
-my $fillFeatureAttributes = sub 
-{
-	my $node = shift; my $map = shift;
-	
-	my @attribSet =  &featureparser::getnodefromTree($node, "feature");
-	
-	my %nameUidMap = ();
-	foreach my $att_node (@attribSet)
-	{
-		my ($uid_value, $feat_name, $attval);
-		my (@macroSet, @commentSet);
-		my %featureHash = ();
-		
-		#Read the feature name and its other attributes
-		$feat_name = &featureparser::getattrValue($att_node, "name",STRICTCASE);
-		
-		# Validate Name
-		if(!$feat_name) {
-			&featureparser::ERROR("Feature name attribute is empty");
-			return 0;
-		}
-		if(exists $nameUidMap{lc($feat_name)}) {
-			&featureparser::ERROR("Feature entry \"".$feat_name."\" already exists");
-			return 0;
-		}
-		
-		#Read the uid value
-		$uid_value = &featureparser::getattrValue($att_node, "uid");
-		if(!&featureparser::IsValidNum($uid_value)) {
-			&featureparser::ERROR("Valid hexadecimal or decimal value expected in UID entry for \"$feat_name\"");
-			return 0;
-		}
-		$uid_value = &featureparser::ConvertHexToDecimal($uid_value);
-		if((defined $map->{feature}) && (exists $map->{feature}{$uid_value})) {
-			&featureparser::ERROR("UID entry for \"".$feat_name."\" already exists");
-			return 0;
-		}
-		
-		$attval = &featureparser::getattrValue($att_node, "statusflags");
-		if(!&featureparser::IsValidNum($attval)) {
-			&featureparser::ERROR("Valid hexadecimal or decimal value expected in STATUS_FLAGS entry for \"$feat_name\"");
-			return 0;
-		}
-		$featureHash{statusflags} = $attval;
-		
-		$attval = &featureparser::getattrValue($att_node, "userdata");
-		if(defined $attval) {
-			if(!&featureparser::IsValidNum($attval)) {
-				&featureparser::ERROR("Valid hexadecimal or decimal value expected in USER_DATA entry for \"$feat_name\"");
-				return 0;
-			}
-		}
-		$featureHash{name} = $feat_name;
-		$featureHash{userdata} = $attval;
-		
-		#Read the attributes of <hrhmacro> element
-		@macroSet = &featureparser::getnodefromTree($att_node, "hrhmacro");
-		foreach my $nodeMac (@macroSet) {
-			$featureHash{includemacro} = &featureparser::getattrValue($nodeMac,"include",STRICTCASE);
-			$featureHash{excludemacro} = &featureparser::getattrValue($nodeMac,"exclude",STRICTCASE);
-			
-			#Read the attribute infeaturesetiby
-			$attval = &featureparser::getattrValue($nodeMac,"infeaturesetiby");
-			if(($attval eq undef) or (lc($attval) eq "yes")) {
-				$featureHash{infeaturesetiby} = 1;
-			}
-			elsif(lc($attval) eq "no") {
-				$featureHash{infeaturesetiby} = 0;
-			}
-			else {
-				&featureparser::ERROR("(yes|no) value expected in infeaturesetiby attribute for \"$feat_name\"");
-				return 0;
-			}
-		}
-		
-		#Read the <comment> element value
-		@commentSet = &featureparser::getnodefromTree($att_node, "comment");
-		foreach my $nodeCmt (@commentSet) {
-			$featureHash{comment} =  &featureparser::getelementValue($nodeCmt,STRICTCASE);
-		}
-		
-		#Add an entry to name->uid map for this feature
-		$nameUidMap{lc($feat_name)} = $uid_value;
-		#Add an entry to the global hash map with all the attributes of this feature
-		$map->{feature}{$uid_value} = \%featureHash;
-	}
-	
-	$map->{feature_list} = \%nameUidMap;
-	
-	return 1;
-};
-my $fillAliasAttributes = sub
-{
-	my $node = shift;
-	my $map = shift;
-	my %aliasnameUidMap = ();
-	my $featureList = $map->{feature_list};
-	my @attribSet = &featureparser::getnodefromTree($node, "featureoverride");
-	foreach my $att_node (@attribSet)
-	{
-		my ($uid_value, $alias_name, $feat_name, $attval);
-		my (@macroSet, @commentSet);
-		my %featureHash = ();
-		#read the alias name 
-		$alias_name = &featureparser::getattrValue($att_node, "name", STRICTCASE);
-		if(!$alias_name)
-		{
-			&featureparser::ERROR("Featureoverride name attribute is empty");
-			return 0;
-		}
-		if(exists $featureList->{lc($alias_name)})
-		{
-			&featureparser::ERROR("Can't override <feature> \"".sprintf("0x%08x", $featureList->{lc($alias_name)})."\" in the same <featureset>");
-			return 0;
-		}
-		if(exists $aliasnameUidMap{lc($alias_name)})
-		{
-			&featureparser::ERROR("Can't override <featureoverride> \"".sprintf("0x%08x", $aliasnameUidMap{lc($alias_name)})."\" in the same <featureset>");
-			return 0;
-		}
-		$uid_value = &featureparser::getattrValue($att_node, "uid");
-		if(!&featureparser::IsValidNum($uid_value))
-		{
-			&featureparser::ERROR("Valid hexadecimal or decimal value expected in UID entry for \"$alias_name\"");
-			return 0;
-		}
-		$uid_value = &featureparser::ConvertHexToDecimal($uid_value);
-		if((defined $map->{alias_feature}) && (exists $map->{alias_feature}{$uid_value}))
-		{
-			&featureparser::ERROR("Can't override <featureoverride> \"".sprintf("0x%08x", $uid_value)."\" in the same <featureset>");
-			return 0;
-		}
-		if((defined $map->{feature}) && (exists $map->{feature}{$uid_value}))
-		{
-			&featureparser::ERROR("Can't override <feature> \"".sprintf("0x%08x", $uid_value)."\" in the same <featureset>");
-			return 0;
-		}
-		$attval = &featureparser::getattrValue($att_node, "statusflags");
-		if(defined $attval)
-		{
-			if(!&featureparser::IsValidNum($attval))
-			{
-				&featureparser::ERROR("Valid hexadecimal or decimal value expected in STATUS_FLAGS entry for \"$alias_name\"");
-				return 0;
-			}
-		}
-		$featureHash{statusflags} = $attval;
-
-		$attval = &featureparser::getattrValue($att_node, "userdata");
-		if(defined $attval)
-		{
-			if(!&featureparser::IsValidNum($attval))
-			{
-				&featureparser::ERROR("Valid hexadecimal or decimal value expected in USER_DATA entry for \"$alias_name\"");
-				return 0;
-			}
-		}
-
-		$featureHash{uid} = $uid_value;
-		$featureHash{name} = $alias_name;
-		$featureHash{userdata} = $attval;
-		#read the attributes of <hrhmacro> element
-		@macroSet = &featureparser::getnodefromTree($att_node,"hrhmacro");
-		foreach my $nodeMac (@macroSet) 
-		{
-			$featureHash{includemacro} = &featureparser::getattrValue($nodeMac, "include", STRICTCASE);
-			$featureHash{excludemacro} = &featureparser::getattrValue($nodeMac, "exclude", STRICTCASE);
-			#read the attribute infeaturesetiby
-			$attval = &featureparser::getattrValue($nodeMac, "infeaturesetiby");
-			if(($attval eq undef) or (lc($attval) eq "yes"))
-			{
-				$featureHash{infeaturesetiby} = 1;
-			}
-			elsif(lc($attval) eq "no")
-			{
-				$featureHash{infeaturesetiby} = 0;
-			}
-			else
-			{
-				&featureparser::ERROR("(yes|no) value expected in infeaturesetiby attribute for \"$feat_name\"");
-				return 0;
-			}
-		}
-		#read the <comment> element value
-		@commentSet = &featureparser::getnodefromTree($att_node, "comment");
-		foreach my $nodeCmt (@commentSet)
-		{
-			$featureHash{comment} = &featureparser::getelementValue($nodeCmt, STRICTCASE);
-		}
-		#add an entry to alias->uid map for this feature
-		$aliasnameUidMap{lc($alias_name)} = $uid_value;
-		#add an entry to the global hash map with all the attributes of this alias feature
-		$map->{alias_feature}{$uid_value} = \%featureHash;
-	}
-	$map->{alias_feature_list} = \%aliasnameUidMap;
-
-	return 1;
-};
-
-#
-# Public methods
-#
-
-sub getAliasFeatureList
-{
-	my $object = shift; 
-	return 0 if(!&featureparser::ISREF($object,"getAliasFeatureList"));
-	
-	my $aliasfeatlist = $object->$aliasfeatureList();
-	return $aliasfeatlist;
-}
-# To get the status flag attribute value of the given feature
-# @param : feature name
-#
-sub getStatusFlag
-{
-	my $object = shift; 
-	return 0 if(!&featureparser::ISREF($object,"getStausFlag"));
-	
-	my $name = shift;
-	my $namespace = shift;
-	my $uid = $object->getFeatureUID($name, $namespace);
-	if($uid)
-	{
-		my $feature = $object->getFeatureInfo($uid, $namespace);
-		
-		return ($feature->{statusflags}) if(exists $feature->{statusflags});
-	}
-	
-	return undef;
-}
-
-# To get the user data attribute value of the given feature
-# @param : feature name
-#
-sub getUserData
-{
-	my $object = shift; 
-	return 0 if(!&featureparser::ISREF($object,"getUserData"));
-	
-	my $name = shift;
-	my $namespace = shift;
-	my $uid = $object->getFeatureUID($name, $namespace);
-	if($uid)
-	{
-		my $feature = $object->getFeatureInfo($uid, $namespace);
-		
-		return ($feature->{userdata}) if(exists $feature->{userdata});
-	}
-	
-	return undef;
-}
-
-# To get the include macro attribute value of the given feature
-# @param : feature name
-#
-sub getIncludeMacro
-{
-	my $object = shift; 
-	return 0 if(!&featureparser::ISREF($object,"getIncludeMacro"));
-	
-	my $name = shift;
-	my $uid = $object->getfeatureUID($name);
-	if($uid)
-	{
-		my $feature = $object->getfeatureInfo($uid);
-		return $feature->{includemacro};
-	}
-	
-	return undef;
-}
-
-# To get the exclude macro attribute value of the given feature
-# @param : feature name
-#
-sub getExcludeMacro
-{
-	my $object = shift; 
-	return 0 if(!&featureparser::ISREF($object,"getExcludeMacro"));
-	
-	my $name = shift;
-	my $uid = $object->getfeatureUID($name);
-	if($uid)
-	{
-		my $feature = $object->getfeatureInfo($uid);
-		return $feature->{excludemacro};
-	}
-	
-	return undef;
-}
-
-# Return the feature uid for the given feature name.
-# @param : Feature Name
-# @param : namespace of the featureset (optional)
-#
-sub getFeatureUID
-{
-	my $object = shift; 
-	return 0 if(!&featureparser::ISREF($object,"getFeatureUID"));
-	
-	my $feature = shift;
-	my $namespace = shift;
-	my $featuresetList = $object->$featuresetList;
-	
-	$feature = lc($feature);
-	if($namespace eq undef)	{
-		if(exists $$featuresetList[0]->{feature_list}{$feature}) {
-			return $$featuresetList[0]->{feature_list}{$feature};
-		}
-		if(exists $$featuresetList[0]->{alias_feature_list}{$feature}) {
-			return $$featuresetList[0]->{alias_feature_list}{$feature};
-		}
-	}
-	else {
-		foreach my $node (@$featuresetList)
-		{
-			if((lc($node->{namespace}) eq lc($namespace)) && ((exists $node->{feature_list}{$feature})||(exists $node->{alias_feature_list}{$feature}))) {
-				return $node->{feature_list}{$feature} if (exists $node->{feature_list}{$feature});
-				return $node->{alias_feature_list}{$feature} if (exists $node->{alias_feature_list}{$feature});
-			}
-		}
-	}
-	foreach my $node (@$featuresetList) {
-		return $node->{feature_list}{$feature} if(exists $node->{feature_list}{$feature});
-		return $node->{alias_feature_list}{$feature} if(exists $node->{alias_feature_list}{$feature});
-	}
-	return undef;
-}
-
-# Get the details of feature with given featureuid and other parameters
-# This function only consider the feature UID only and that UID should be in decimal
-# @param : Feature UID
-# @param : namespace of the featureset (optional)
-#
-sub getFeatureInfo
-{
-	my $object = shift; 
-	return 0 if(!&featureparser::ISREF($object,"getFeatureInfo"));
-	
-	my $uid = shift;
-	my $namespace = shift;
-	my $featuresetList = $object->$featuresetList;
-
-	if($namespace eq undef)	{
-		foreach my $node (@$featuresetList) {
-			return $node->{alias_feature}{$uid} if(exists $node->{alias_feature}{$uid});
-		}
-		if(exists $$featuresetList[0]->{feature}{$uid}) {
-			return $$featuresetList[0]->{feature}{$uid};
-		}
-		if(exists $$featuresetList[0]->{alias_feature}{$uid}) {
-			return $$featuresetList[0]->{alias_feature}{$uid};
-		}
-	}
-	else {
-		foreach my $node (@$featuresetList)
-		{
-			if((lc($node->{namespace}) eq lc($namespace)) && ((exists $node->{feature}{$uid})||(exists $node->{alias_feature}{$uid}))) {
-				return $node->{feature}{$uid} if (exists $node->{feature}{$uid});
-				return $node->{alias_feature}{$uid} if (exists $node->{alias_feature}{$uid});
-			}
-		}
-	}
-	foreach my $node (@$featuresetList) {
-		return $node->{feature}{$uid} if(exists $node->{feature}{$uid});
-	}
-	return undef;
-}
-
-
-# Get the Feature set info as a hash
-# @param: namespace of the featureset
-#
-sub getFeaturesetInfo 
-{
-	my $object = shift; 
-	return 0 if(!&featureparser::ISREF($object,"getFeaturesetInfo"));
-	
-	my $namespace = shift;
-	
-	my $featuresetList = $object->$featuresetList;
-	if($namespace eq undef)	{
-		if(exists $$featuresetList[0]) {
-			return $$featuresetList[0];
-		}
-	}
-	else {
-		foreach my $node (@$featuresetList)
-		{
-			if((lc($node->{namespace}) eq lc($namespace))) {
-				return $node;
-			}
-		}
-	}
-	return undef;
-}
-
-# Get the Featureset namespaces as an array
-#
-sub getFeatureset
-{
-	my $object = shift; 
-	return 0 if(!&featureparser::ISREF($object,"getFeatureset"));
-	
-	my @featureSet=();
-	
-	my $featuresetList = $object->$featuresetList;
-	foreach my $node (@$featuresetList) {
-		push @featureSet, $node;
-	}
-	return \@featureSet;
-}
-
-# Add feature registry object contents to feature manager object
-# @param : feature registry object
-#
-sub addFeatureRegistry
-{
-	my $object = shift; 
-	return 0 if(!&featureparser::ISREF($object,"addFeatureRegistry"));
-	
-	my $registryobj = shift;
-	my %attribHash = ();
-	my $nameuidmap;
-	my $newRangeList;
-	my $rangeList;
-	
-	# Adding default range list
-	$newRangeList = $registryobj->defaultRangeList();
-	$rangeList = $object->defaultRangeList();
-
-	foreach my $newnode (@$newRangeList) {
-		my $include = 1;
-		foreach my $node (@$rangeList) { #Check if the range is already exists
-			if(($node->{min} == $newnode->{min}) && ($node->{max} == $newnode->{max}) 
-				&& ($node->{support} eq $newnode->{support})) {
-				$include = 0;
-			}
-		}
-		
-		if($include) { # Add it if it is new range
-			push @$rangeList, $newnode;
-			$object->defaultIncludeCount($object->defaultIncludeCount()+1) if(lc($newnode->{support}) eq "include");
-			$object->defaultExcludeCount($object->defaultExcludeCount()+1) if(lc($newnode->{support}) eq "exclude");
-		}
-	}
-	
-	# Adding feature list
-	$nameuidmap = $registryobj->featureNameUidMap();
-	$attribHash{namespace} = undef;
-	$attribHash{feature_list} = $nameuidmap;
-	
-	foreach my $name (keys %$nameuidmap) {
-		my $uid = $nameuidmap->{$name};
-		my %featureinfo = ();
-		
-		$featureinfo{name} = $name;
-		# Default values for statusflags and userdata
-		$featureinfo{statusflags} = "0x00000001";
-		$featureinfo{userdata} = "0x00000000";
-		
-		$attribHash{feature}{$uid} = \%featureinfo;
-	}
-	
-	# add the featureset into the feature manager object
-	return 0 if(! &addFeatureSet($object, \%attribHash));
-
-	return 1;
-}
-
-#
-# Utility functions
-#
-# Add the featureset into the hash map
-# @param : reference to the atrribute hash map of featureset
-#
-sub addFeatureSet
-{
-	my $object = shift; 
-	return 0 if(!&featureparser::ISREF($object,"addFeatureSet"));
-	
-	my $newSet = shift;
-	my $featSetList = $object->$featuresetList();
-	my $newfeatList = $newSet->{feature_list};
-	my $newaliasfeatList = $newSet->{alias_feature_list};
-
-	# Check for the duplicate featue names in the existing list
-	foreach my $name (keys %$newfeatList)
-	{
-		if(exists $object->$featureList()->{$name})
-		{
-			&featureparser::ERROR("\(".$object->fileName()."\) Feature \"".uc($name)."\" already exists");
-			return 0;
-		}
-		else
-		{
-			my $uid = $newfeatList->{$name};
-			$object->$featureList()->{$name} = $uid; #Add it to global featue name list
-		}
-	}
-	
-	# Check for the duplicate UIDs in the existing list
-	if(@$featSetList) 
-	{	
-		foreach my $set (@$featSetList)
-		{
-			foreach my $name (keys %$newfeatList)
-			{
-				my $uid = $newfeatList->{$name};
-				if(exists $set->{feature}{$uid})
-				{
-					&featureparser::ERROR("\(".$object->fileName()."\) UID \"".sprintf("0x%08x",$uid)."\" for the feature \"".uc($name)."\" already exists");
-					return 0;
-				}
-			}
-		}
-	}
-	#check for the duplicate alias feature names in the existing list
-	foreach my $alias_name (keys %$newaliasfeatList)
-	{
-		if(exists $object->$featureList()->{$alias_name})
-		{
-			&featureparser::ERROR("\(".$object->fileName."\) Can't override <feature> \"".sprintf("0x%08x", $newaliasfeatList->{$alias_name})."\" with the same feature name ".$alias_name);
-			return 0;
-
-		}
-		if(exists $object->$aliasfeatureList()->{$alias_name})
-		{
-			&featureparser::ERROR("\(".$object->fileName."\) Can't override <featureoverride> \"".sprintf("0x%08x", $newaliasfeatList->{$alias_name})."\" with the same feature name ".$alias_name);
-			return 0;
-		}
-		else
-		{
-			my $uid = $newaliasfeatList->{$alias_name};
-			# add it to global alias feature name list
-			$object->$aliasfeatureList()->{$alias_name} = $uid;
-		}
-	}
-	#check if the original feature has existed in other feature set.
-	foreach my $alias_name (keys %$newaliasfeatList)
-	{
-		my $featHash;
-		my $uid = $newaliasfeatList->{$alias_name};
-		foreach my $set (@$featSetList)
-		{
-			if(exists $set->{feature}{$uid})
-			{
-				$featHash = $set->{feature}{$uid};
-				last;
-			}
-			if(exists $set->{alias_feature}{$uid})
-			{
-				$featHash = $set->{alias_feature}{$uid};
-				last;
-			}
-		}
-		if(!$featHash)
-		{
-			&featureparser::ERROR("original feature definition does not exist.");
-			return 0;
-		}
-
-		my $aliasfeatHash = $newSet->{alias_feature}{$uid};
-
-		if(($aliasfeatHash->{includemacro}) || ($aliasfeatHash->{excludemacro}))
-		{
-			if(($featHash->{includemacro}) || ($featHash->{excludemacro}))
-			{
-				&featureparser::WARN("the value of attribute hrhmacro has been overrided in ogrinal feature ".sprintf("0x%08x", $uid));
-				undef $featHash->{includemacro};
-				undef $featHash->{excludemacro};
-			}
-		}
-		elsif($featHash->{includemacro} || $featHash->{excludemacro})
-		{
-			&featureparser::WARN("the original value of attribute hrhmacro will be used for featureoverride ".sprintf("0x%08x", $uid));
-			$aliasfeatHash->{includemacro} = $featHash->{includemacro};
-			$aliasfeatHash->{excludemacro} = $featHash->{excludemacro};
-		}
-		if($aliasfeatHash->{statusflags})
-		{
-			if(($featHash->{statusflags}) && !($aliasfeatHash->{statusflags} eq $featHash->{statusflags}))
-			{
-				&featureparser::WARN("the value of attribute statusflags has been overrided in ogrinal feature ".sprintf("0x%08x", $uid));
-			}
-		}
-		elsif($featHash->{statusflags})
-		{
-			$aliasfeatHash->{statusflags} = $featHash->{statusflags};
-			&featureparser::WARN("the original value of attribute statusflags will be used for featureoverride ".sprintf("0x%08x", $uid));
-		}
-		if($aliasfeatHash->{userdata})
-		{
-			if(($featHash->{userdata}) && !($aliasfeatHash->{userdata} eq $featHash->{userdata}))
-			{
-				&featureparser::WARN("the value of attribute userdata has been overrided in ogrinal feature ".sprintf("0x%08x", $uid));
-			}
-		}
-		elsif($featHash->{userdata})
-		{
-			$aliasfeatHash->{userdata} = $featHash->{userdata};
-			&featureparser::WARN("the original value of attribute userdata will be used for featureoverride ".sprintf("0x%08x", $uid));
-		}
-		if($aliasfeatHash->{infeaturesetiby})
-		{
-			if(($featHash->{infeaturesetiby}) && ($aliasfeatHash->{infeaturesetiby} != $featHash->{infeaturesetiby}))
-			{
-				&featureparser::WARN("the value of attribute infeautresetiby has been overrided in ogrinal feature ".sprintf("0x%08x", $uid));
-			}
-		}
-		elsif(defined($featHash->{infeaturesetiby}))
-		{
-			$aliasfeatHash->{infeaturesetiby} = $featHash->{infeaturesetiby};
-			&featureparser::WARN("the original value of attribute infewaturesetiby will be used for featureoverride ".sprintf("0x%08x", $uid));
-		}
-	}
-	# Add the unique featureset into the list
-	push @$featSetList, $newSet;
-	return 1;
-}
-
-# Read the <featureset> element
-# 
-sub createFeatureMap
-{
-	my $object = shift; 
-	return 0 if(!&featureparser::ISREF($object,"createFeatureMap"));
-	
-	# Return error if the rootelement reference is NULL
-	return 0 if($object->rootElement() < 0);
-	
-	# Get all the <featureset> elements
-	my @attrSet =  &featureparser::getnodefromTree($object->rootElement(), "featureset");
-	
-	if(@attrSet)
-	{
-		foreach my $currNode (@attrSet)
-		{
-			my %attrHashMap = ();
-			
-			# Get the <featureset> attributes
-			$fillFeatureSetAttributes->($currNode,\%attrHashMap);
-			# Get the <hfileheader> attributes
-			$fillFileHeaderAttributes->($currNode,\%attrHashMap);
-			
-			# Get the <feature> attributes
-			return 0 if( !($fillFeatureAttributes->($currNode,\%attrHashMap)) );
-			# Get the <alias> attributes
-			return 0 if( !($fillAliasAttributes->($currNode, \%attrHashMap)) );
-			
-			# Add the featureset into the object
-			if(! &addFeatureSet($object,\%attrHashMap))
-			{
-				return 0;
-			}
-		}
-		return 1;
-	}
-	return 0;
-}
-
-# Read the <defaultfeaturerange> element
-#
-sub createDefaultRangeMap
-{
-	my $object = shift; 
-	return 0 if(!&featureparser::ISREF($object,"createDefaultRangeMap"));
-	
-	# Return error if the rootelement reference is NULL
-	return 0 if($object->rootElement() < 0);
-	
-	# Get all the <defaultfeaturerange> elements
-	my @attrSet =  &featureparser::getnodefromTree($object->rootElement(), "defaultfeaturerange");
-	
-	# Add the defaultfeaturerange elements into the object
-	return &featureparser::createDefaultRangeMap($object,@attrSet);
-}
-
-# Read the attributes of the <defaultfeaturerange> element
-# @param - <defaultfeaturerange> node reference
-# @param - reference to the range attributes
-#
-sub readRangeAttributes
-{
-	my ($object, $currNode, $range) = @_; 
-	my @commentSet;
-	return 0 if(!&featureparser::ISREF($object,"readRangeAttributes"));	
-	
-	#Get the lower and higher uids
-	$range->{min} = &featureparser::getattrValue($currNode, "loweruid");
-	$range->{max} = &featureparser::getattrValue($currNode, "higheruid");
-
- 	#Always supported/included for FM. Keep this value for compatible with FR
- 	$range->{support} = "include";
-	#Read the <comment> element
-	@commentSet = &featureparser::getnodefromTree($currNode, "comment");
-	foreach my $node (@commentSet) {
-		$range->{comment} =  &featureparser::getelementValue($node,STRICTCASE);
-	}
-}
-
-1;
+#
+# Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+#
+
+# This package contains routines to read the information from the Feature manager XML file.
+package featuremanager; # Derived class for the feature manager xml parser
+
+BEGIN {
+	@ISA = qw(featureparser); # Derived from featuerParser
+	require featureparser;
+};
+
+use constant STRICTCASE=>1; # To suppress the case conversion in genericparser routine
+
+# Parse the featuredatabase XML file and generate the maps and counts
+#
+#featureset:
+# {namespace}<namespace> - optional
+# {ibyname}<ibyname> - optional
+# {hfilename}<hfilename> - optional
+# {hfileheader}<fileheader> - optional
+# {interfacestatus}<interfacestatus> -optional
+# {interfacevisibility}<interfacevisibility> - optional
+# {feature_list}<nameuidmap>
+# {feature} {<uid1>}{statusflags}<statusflag>
+#					{name}<name>
+#					{userdata}<userdata> - optional
+#					{includemacro}<macro>
+#					{excludemacro}<macro>
+#					{infeaturesetiby}<yes/no> - optional
+#					{comment}<comment> - optional
+#			{<uid2>}{statusflags}<statusflag>
+#					{name}<name>
+#					{userdata}<userdata> - optional
+#					{includemacro}<macro>
+#					{excludemacro}<macro>
+#					{infeaturesetiby}<yes/no> - optional
+#					{comment}<comment>
+#
+
+#
+# Class constructor
+#
+sub new
+{
+	my $class = shift;
+	my $object = $class->SUPER::new();
+	
+	# Class members
+	$object->{_OBJNAME} = "FeatureManager"; # Name of the object
+	$object->{_FEAT_SET_LIST} = [];  # Array of <featureset> hash maps
+	$object->{_FEAT_LIST} = {};      # Hash map of all feature name with uid
+	$object->{_ALIAS_FEAT_LIST} = {}; # Hash map of all alias feature name with uid
+	return $object;
+}
+
+#
+# Private methods
+#
+
+# Private method to Get/Set the _FEAT_SET_LIST member value of this class
+# @param : reference to the array of <featureset> hash maps (optional for GET)
+#
+my $featuresetList = sub 
+{
+	my $object = shift; 
+	return 0 if(!&featureparser::ISREF($object,"featuresetList"));
+	
+	if (@_) 
+	{ 
+		$object->{_FEAT_SET_LIST} = shift; 
+	}
+	return $object->{_FEAT_SET_LIST};
+};
+
+# Private method to Get/Set the _FEAT_LIST member value of this class
+# @param : reference to the fash map of feature name with uid (optional for GET)
+#
+my $featureList = sub 
+{
+	my $object = shift; 
+	return 0 if(!&featureparser::ISREF($object,"featureList"));
+	
+	if (@_) 
+	{ 
+		$object->{_FEAT_LIST} = shift; 
+	}
+	return $object->{_FEAT_LIST};
+};
+# Private method ot Get/Set the _ALIAS_FEAT_LIST member value of this class
+# @param: reference to the hash map of alias feature name with uid
+my $aliasfeatureList = sub
+{
+	my $object = shift;
+	return 0 if(!&featureparser::ISREF($object, "aliasfeatureList"));
+
+	if(@_)
+	{
+		$object->{_ALIAS_FEAT_LIST} = shift;
+	}
+	return $object->{_ALIAS_FEAT_LIST};
+};
+
+# Read the attributes of <featureset> element
+# @param : reference to the featureset
+# @param : reference to the attributemap
+#
+my $fillFeatureSetAttributes = sub 
+{
+	my  $node = shift;
+	my  $map = shift;
+	$map->{ibyname} = &featureparser::getattrValue($node, "ibyname", STRICTCASE);
+	$map->{hfilename} = &featureparser::getattrValue($node, "hfilename", STRICTCASE);
+	$map->{namespace} = &featureparser::getattrValue($node, "namespace", STRICTCASE);
+};
+
+# Read the attributes of <hfileheader> element
+# @param : reference to the featureset
+# @param : reference to the attributemap
+#
+my $fillFileHeaderAttributes = sub 
+{
+	my $node = shift;
+	my $map = shift;
+	my @attribSet =  &featureparser::getnodefromTree($node, "hfileheader");
+	
+	foreach my $att_node (@attribSet) 
+	{
+		$map->{interfacestatus} = &featureparser::getattrValue($att_node, "interfacestatus",STRICTCASE);
+		$map->{interfacevisibility} = &featureparser::getattrValue($att_node, "interfacevisibility",STRICTCASE);
+		$map->{hfileheader} = &featureparser::getelementValue($att_node,STRICTCASE);
+	}
+};
+
+# Read the attributes of <feature> element
+# @param : reference to the featureset
+# @param : reference to the attributemap
+#
+my $fillFeatureAttributes = sub 
+{
+	my $node = shift; my $map = shift;
+	
+	my @attribSet =  &featureparser::getnodefromTree($node, "feature");
+	
+	my %nameUidMap = ();
+	foreach my $att_node (@attribSet)
+	{
+		my ($uid_value, $feat_name, $attval);
+		my (@macroSet, @commentSet);
+		my %featureHash = ();
+		
+		#Read the feature name and its other attributes
+		$feat_name = &featureparser::getattrValue($att_node, "name",STRICTCASE);
+		
+		# Validate Name
+		if(!$feat_name) {
+			&featureparser::ERROR("Feature name attribute is empty");
+			return 0;
+		}
+		if(exists $nameUidMap{lc($feat_name)}) {
+			&featureparser::ERROR("Feature entry \"".$feat_name."\" already exists");
+			return 0;
+		}
+		
+		#Read the uid value
+		$uid_value = &featureparser::getattrValue($att_node, "uid");
+		if(!&featureparser::IsValidNum($uid_value)) {
+			&featureparser::ERROR("Valid hexadecimal or decimal value expected in UID entry for \"$feat_name\"");
+			return 0;
+		}
+		$uid_value = &featureparser::ConvertHexToDecimal($uid_value);
+		if((defined $map->{feature}) && (exists $map->{feature}{$uid_value})) {
+			&featureparser::ERROR("UID entry for \"".$feat_name."\" already exists");
+			return 0;
+		}
+		
+		$attval = &featureparser::getattrValue($att_node, "statusflags");
+		if(!&featureparser::IsValidNum($attval)) {
+			&featureparser::ERROR("Valid hexadecimal or decimal value expected in STATUS_FLAGS entry for \"$feat_name\"");
+			return 0;
+		}
+		$featureHash{statusflags} = $attval;
+		
+		$attval = &featureparser::getattrValue($att_node, "userdata");
+		if(defined $attval) {
+			if(!&featureparser::IsValidNum($attval)) {
+				&featureparser::ERROR("Valid hexadecimal or decimal value expected in USER_DATA entry for \"$feat_name\"");
+				return 0;
+			}
+		}
+		$featureHash{name} = $feat_name;
+		$featureHash{userdata} = $attval;
+		
+		#Read the attributes of <hrhmacro> element
+		@macroSet = &featureparser::getnodefromTree($att_node, "hrhmacro");
+		foreach my $nodeMac (@macroSet) {
+			$featureHash{includemacro} = &featureparser::getattrValue($nodeMac,"include",STRICTCASE);
+			$featureHash{excludemacro} = &featureparser::getattrValue($nodeMac,"exclude",STRICTCASE);
+			
+			#Read the attribute infeaturesetiby
+			$attval = &featureparser::getattrValue($nodeMac,"infeaturesetiby");
+			if(!defined($attval) or (lc($attval) eq "yes")) {
+				$featureHash{infeaturesetiby} = 1;
+			}
+			elsif(lc($attval) eq "no") {
+				$featureHash{infeaturesetiby} = 0;
+			}
+			else {
+				&featureparser::ERROR("(yes|no) value expected in infeaturesetiby attribute for \"$feat_name\"");
+				return 0;
+			}
+		}
+		
+		#Read the <comment> element value
+		@commentSet = &featureparser::getnodefromTree($att_node, "comment");
+		foreach my $nodeCmt (@commentSet) {
+			$featureHash{comment} =  &featureparser::getelementValue($nodeCmt,STRICTCASE);
+		}
+		
+		#Add an entry to name->uid map for this feature
+		$nameUidMap{lc($feat_name)} = $uid_value;
+		#Add an entry to the global hash map with all the attributes of this feature
+		$map->{feature}{$uid_value} = \%featureHash;
+	}
+	
+	$map->{feature_list} = \%nameUidMap;
+	
+	return 1;
+};
+my $fillAliasAttributes = sub
+{
+	my $node = shift;
+	my $map = shift;
+	my %aliasnameUidMap = ();
+	my $featureList = $map->{feature_list};
+	my @attribSet = &featureparser::getnodefromTree($node, "featureoverride");
+	foreach my $att_node (@attribSet)
+	{
+		my ($uid_value, $alias_name, $feat_name, $attval);
+		my (@macroSet, @commentSet);
+		my %featureHash = ();
+		#read the alias name 
+		$alias_name = &featureparser::getattrValue($att_node, "name", STRICTCASE);
+		if(!$alias_name)
+		{
+			&featureparser::ERROR("Featureoverride name attribute is empty");
+			return 0;
+		}
+		if(exists $featureList->{lc($alias_name)})
+		{
+			&featureparser::ERROR("Can't override <feature> \"".sprintf("0x%08x", $featureList->{lc($alias_name)})."\" in the same <featureset>");
+			return 0;
+		}
+		if(exists $aliasnameUidMap{lc($alias_name)})
+		{
+			&featureparser::ERROR("Can't override <featureoverride> \"".sprintf("0x%08x", $aliasnameUidMap{lc($alias_name)})."\" in the same <featureset>");
+			return 0;
+		}
+		$uid_value = &featureparser::getattrValue($att_node, "uid");
+		if(!&featureparser::IsValidNum($uid_value))
+		{
+			&featureparser::ERROR("Valid hexadecimal or decimal value expected in UID entry for \"$alias_name\"");
+			return 0;
+		}
+		$uid_value = &featureparser::ConvertHexToDecimal($uid_value);
+		if((defined $map->{alias_feature}) && (exists $map->{alias_feature}{$uid_value}))
+		{
+			&featureparser::ERROR("Can't override <featureoverride> \"".sprintf("0x%08x", $uid_value)."\" in the same <featureset>");
+			return 0;
+		}
+		if((defined $map->{feature}) && (exists $map->{feature}{$uid_value}))
+		{
+			&featureparser::ERROR("Can't override <feature> \"".sprintf("0x%08x", $uid_value)."\" in the same <featureset>");
+			return 0;
+		}
+		$attval = &featureparser::getattrValue($att_node, "statusflags");
+		if(defined $attval)
+		{
+			if(!&featureparser::IsValidNum($attval))
+			{
+				&featureparser::ERROR("Valid hexadecimal or decimal value expected in STATUS_FLAGS entry for \"$alias_name\"");
+				return 0;
+			}
+		}
+		$featureHash{statusflags} = $attval;
+
+		$attval = &featureparser::getattrValue($att_node, "userdata");
+		if(defined $attval)
+		{
+			if(!&featureparser::IsValidNum($attval))
+			{
+				&featureparser::ERROR("Valid hexadecimal or decimal value expected in USER_DATA entry for \"$alias_name\"");
+				return 0;
+			}
+		}
+
+		$featureHash{uid} = $uid_value;
+		$featureHash{name} = $alias_name;
+		$featureHash{userdata} = $attval;
+		#read the attributes of <hrhmacro> element
+		@macroSet = &featureparser::getnodefromTree($att_node,"hrhmacro");
+		foreach my $nodeMac (@macroSet) 
+		{
+			$featureHash{includemacro} = &featureparser::getattrValue($nodeMac, "include", STRICTCASE);
+			$featureHash{excludemacro} = &featureparser::getattrValue($nodeMac, "exclude", STRICTCASE);
+			#read the attribute infeaturesetiby
+			$attval = &featureparser::getattrValue($nodeMac, "infeaturesetiby");
+			if(!defined($attval) or (lc($attval) eq "yes"))
+			{
+				$featureHash{infeaturesetiby} = 1;
+			}
+			elsif(lc($attval) eq "no")
+			{
+				$featureHash{infeaturesetiby} = 0;
+			}
+			else
+			{
+				&featureparser::ERROR("(yes|no) value expected in infeaturesetiby attribute for \"$feat_name\"");
+				return 0;
+			}
+		}
+		#read the <comment> element value
+		@commentSet = &featureparser::getnodefromTree($att_node, "comment");
+		foreach my $nodeCmt (@commentSet)
+		{
+			$featureHash{comment} = &featureparser::getelementValue($nodeCmt, STRICTCASE);
+		}
+		#add an entry to alias->uid map for this feature
+		$aliasnameUidMap{lc($alias_name)} = $uid_value;
+		#add an entry to the global hash map with all the attributes of this alias feature
+		$map->{alias_feature}{$uid_value} = \%featureHash;
+	}
+	$map->{alias_feature_list} = \%aliasnameUidMap;
+
+	return 1;
+};
+
+#
+# Public methods
+#
+
+sub getAliasFeatureList
+{
+	my $object = shift; 
+	return 0 if(!&featureparser::ISREF($object,"getAliasFeatureList"));
+	
+	my $aliasfeatlist = $object->$aliasfeatureList();
+	return $aliasfeatlist;
+}
+# To get the status flag attribute value of the given feature
+# @param : feature name
+#
+sub getStatusFlag
+{
+	my $object = shift; 
+	return 0 if(!&featureparser::ISREF($object,"getStausFlag"));
+	
+	my $name = shift;
+	my $namespace = shift;
+	my $uid = $object->getFeatureUID($name, $namespace);
+	if($uid)
+	{
+		my $feature = $object->getFeatureInfo($uid, $namespace);
+		
+		return ($feature->{statusflags}) if(exists $feature->{statusflags});
+	}
+	
+	return undef;
+}
+
+# To get the user data attribute value of the given feature
+# @param : feature name
+#
+sub getUserData
+{
+	my $object = shift; 
+	return 0 if(!&featureparser::ISREF($object,"getUserData"));
+	
+	my $name = shift;
+	my $namespace = shift;
+	my $uid = $object->getFeatureUID($name, $namespace);
+	if($uid)
+	{
+		my $feature = $object->getFeatureInfo($uid, $namespace);
+		
+		return ($feature->{userdata}) if(exists $feature->{userdata});
+	}
+	
+	return undef;
+}
+
+# To get the include macro attribute value of the given feature
+# @param : feature name
+#
+sub getIncludeMacro
+{
+	my $object = shift; 
+	return 0 if(!&featureparser::ISREF($object,"getIncludeMacro"));
+	
+	my $name = shift;
+	my $uid = $object->getfeatureUID($name);
+	if($uid)
+	{
+		my $feature = $object->getfeatureInfo($uid);
+		return $feature->{includemacro};
+	}
+	
+	return undef;
+}
+
+# To get the exclude macro attribute value of the given feature
+# @param : feature name
+#
+sub getExcludeMacro
+{
+	my $object = shift; 
+	return 0 if(!&featureparser::ISREF($object,"getExcludeMacro"));
+	
+	my $name = shift;
+	my $uid = $object->getfeatureUID($name);
+	if($uid)
+	{
+		my $feature = $object->getfeatureInfo($uid);
+		return $feature->{excludemacro};
+	}
+	
+	return undef;
+}
+
+# Return the feature uid for the given feature name.
+# @param : Feature Name
+# @param : namespace of the featureset (optional)
+#
+sub getFeatureUID
+{
+	my $object = shift; 
+	return 0 if(!&featureparser::ISREF($object,"getFeatureUID"));
+	
+	my $feature = shift;
+	my $namespace = shift;
+	my $featuresetList = $object->$featuresetList;
+	
+	$feature = lc($feature);
+	if(!defined ($namespace))	{
+		if(exists $$featuresetList[0]->{feature_list}{$feature}) {
+			return $$featuresetList[0]->{feature_list}{$feature};
+		}
+		if(exists $$featuresetList[0]->{alias_feature_list}{$feature}) {
+			return $$featuresetList[0]->{alias_feature_list}{$feature};
+		}
+	}
+	else {
+		foreach my $node (@$featuresetList)
+		{
+			if((lc($node->{namespace}) eq lc($namespace)) && ((exists $node->{feature_list}{$feature})||(exists $node->{alias_feature_list}{$feature}))) {
+				return $node->{feature_list}{$feature} if (exists $node->{feature_list}{$feature});
+				return $node->{alias_feature_list}{$feature} if (exists $node->{alias_feature_list}{$feature});
+			}
+		}
+	}
+	foreach my $node (@$featuresetList) {
+		return $node->{feature_list}{$feature} if(exists $node->{feature_list}{$feature});
+		return $node->{alias_feature_list}{$feature} if(exists $node->{alias_feature_list}{$feature});
+	}
+	return undef;
+}
+
+# Get the details of feature with given featureuid and other parameters
+# This function only consider the feature UID only and that UID should be in decimal
+# @param : Feature UID
+# @param : namespace of the featureset (optional)
+#
+sub getFeatureInfo
+{
+	my $object = shift; 
+	return 0 if(!&featureparser::ISREF($object,"getFeatureInfo"));
+	
+	my $uid = shift;
+	my $namespace = shift;
+	my $featuresetList = $object->$featuresetList;
+
+	if(!defined($namespace))	{
+		foreach my $node (@$featuresetList) {
+			return $node->{alias_feature}{$uid} if(exists $node->{alias_feature}{$uid});
+		}
+		if(exists $$featuresetList[0]->{feature}{$uid}) {
+			return $$featuresetList[0]->{feature}{$uid};
+		}
+		if(exists $$featuresetList[0]->{alias_feature}{$uid}) {
+			return $$featuresetList[0]->{alias_feature}{$uid};
+		}
+	}
+	else {
+		foreach my $node (@$featuresetList)
+		{
+			if((lc($node->{namespace}) eq lc($namespace)) && ((exists $node->{feature}{$uid})||(exists $node->{alias_feature}{$uid}))) {
+				return $node->{feature}{$uid} if (exists $node->{feature}{$uid});
+				return $node->{alias_feature}{$uid} if (exists $node->{alias_feature}{$uid});
+			}
+		}
+	}
+	foreach my $node (@$featuresetList) {
+		return $node->{feature}{$uid} if(exists $node->{feature}{$uid});
+	}
+	return undef;
+}
+
+
+# Get the Feature set info as a hash
+# @param: namespace of the featureset
+#
+sub getFeaturesetInfo 
+{
+	my $object = shift; 
+	return 0 if(!&featureparser::ISREF($object,"getFeaturesetInfo"));
+	
+	my $namespace = shift;
+	
+	my $featuresetList = $object->$featuresetList;
+	if(!defined ($namespace))	{
+		if(exists $$featuresetList[0]) {
+			return $$featuresetList[0];
+		}
+	}
+	else {
+		foreach my $node (@$featuresetList)
+		{
+			if((lc($node->{namespace}) eq lc($namespace))) {
+				return $node;
+			}
+		}
+	}
+	return undef;
+}
+
+# Get the Featureset namespaces as an array
+#
+sub getFeatureset
+{
+	my $object = shift; 
+	return 0 if(!&featureparser::ISREF($object,"getFeatureset"));
+	
+	my @featureSet=();
+	
+	my $featuresetList = $object->$featuresetList;
+	foreach my $node (@$featuresetList) {
+		push @featureSet, $node;
+	}
+	return \@featureSet;
+}
+
+# Add feature registry object contents to feature manager object
+# @param : feature registry object
+#
+sub addFeatureRegistry
+{
+	my $object = shift; 
+	return 0 if(!&featureparser::ISREF($object,"addFeatureRegistry"));
+	
+	my $registryobj = shift;
+	my %attribHash = ();
+	my $nameuidmap;
+	my $newRangeList;
+	my $rangeList;
+	
+	# Adding default range list
+	$newRangeList = $registryobj->defaultRangeList();
+	$rangeList = $object->defaultRangeList();
+
+	foreach my $newnode (@$newRangeList) {
+		my $include = 1;
+		foreach my $node (@$rangeList) { #Check if the range is already exists
+			if(($node->{min} == $newnode->{min}) && ($node->{max} == $newnode->{max}) 
+				&& ($node->{support} eq $newnode->{support})) {
+				$include = 0;
+			}
+		}
+		
+		if($include) { # Add it if it is new range
+			push @$rangeList, $newnode;
+			$object->defaultIncludeCount($object->defaultIncludeCount()+1) if(lc($newnode->{support}) eq "include");
+			$object->defaultExcludeCount($object->defaultExcludeCount()+1) if(lc($newnode->{support}) eq "exclude");
+		}
+	}
+	
+	# Adding feature list
+	$nameuidmap = $registryobj->featureNameUidMap();
+	$attribHash{namespace} = undef;
+	$attribHash{feature_list} = $nameuidmap;
+	
+	foreach my $name (keys %$nameuidmap) {
+		my $uid = $nameuidmap->{$name};
+		my %featureinfo = ();
+		
+		$featureinfo{name} = $name;
+		# Default values for statusflags and userdata
+		$featureinfo{statusflags} = "0x00000001";
+		$featureinfo{userdata} = "0x00000000";
+		
+		$attribHash{feature}{$uid} = \%featureinfo;
+	}
+	
+	# add the featureset into the feature manager object
+	return 0 if(! &addFeatureSet($object, \%attribHash));
+
+	return 1;
+}
+
+#
+# Utility functions
+#
+# Add the featureset into the hash map
+# @param : reference to the atrribute hash map of featureset
+#
+sub addFeatureSet
+{
+	my $object = shift; 
+	return 0 if(!&featureparser::ISREF($object,"addFeatureSet"));
+	
+	my $newSet = shift;
+	my $featSetList = $object->$featuresetList();
+	my $newfeatList = $newSet->{feature_list};
+	my $newaliasfeatList = $newSet->{alias_feature_list};
+
+	# Check for the duplicate featue names in the existing list
+	foreach my $name (keys %$newfeatList)
+	{
+		if(exists $object->$featureList()->{$name})
+		{
+			&featureparser::ERROR("\(".$object->fileName()."\) Feature \"".uc($name)."\" already exists");
+			return 0;
+		}
+		else
+		{
+			my $uid = $newfeatList->{$name};
+			$object->$featureList()->{$name} = $uid; #Add it to global featue name list
+		}
+	}
+	
+	# Check for the duplicate UIDs in the existing list
+	if(@$featSetList) 
+	{	
+		foreach my $set (@$featSetList)
+		{
+			foreach my $name (keys %$newfeatList)
+			{
+				my $uid = $newfeatList->{$name};
+				if(exists $set->{feature}{$uid})
+				{
+					&featureparser::ERROR("\(".$object->fileName()."\) UID \"".sprintf("0x%08x",$uid)."\" for the feature \"".uc($name)."\" already exists");
+					return 0;
+				}
+			}
+		}
+	}
+	#check for the duplicate alias feature names in the existing list
+	foreach my $alias_name (keys %$newaliasfeatList)
+	{
+		if(exists $object->$featureList()->{$alias_name})
+		{
+			&featureparser::ERROR("\(".$object->fileName."\) Can't override <feature> \"".sprintf("0x%08x", $newaliasfeatList->{$alias_name})."\" with the same feature name ".$alias_name);
+			return 0;
+
+		}
+		if(exists $object->$aliasfeatureList()->{$alias_name})
+		{
+			&featureparser::ERROR("\(".$object->fileName."\) Can't override <featureoverride> \"".sprintf("0x%08x", $newaliasfeatList->{$alias_name})."\" with the same feature name ".$alias_name);
+			return 0;
+		}
+		else
+		{
+			my $uid = $newaliasfeatList->{$alias_name};
+			# add it to global alias feature name list
+			$object->$aliasfeatureList()->{$alias_name} = $uid;
+		}
+	}
+	#check if the original feature has existed in other feature set.
+	foreach my $alias_name (keys %$newaliasfeatList)
+	{
+		my $featHash;
+		my $uid = $newaliasfeatList->{$alias_name};
+		foreach my $set (@$featSetList)
+		{
+			if(exists $set->{feature}{$uid})
+			{
+				$featHash = $set->{feature}{$uid};
+				last;
+			}
+			if(exists $set->{alias_feature}{$uid})
+			{
+				$featHash = $set->{alias_feature}{$uid};
+				last;
+			}
+		}
+		if(!$featHash)
+		{
+			&featureparser::ERROR("Original feature definition does not exist for feature ".sprintf("0x%08x", $uid));
+			return 0;
+		}
+
+		my $aliasfeatHash = $newSet->{alias_feature}{$uid};
+
+		if(($aliasfeatHash->{includemacro}) || ($aliasfeatHash->{excludemacro}))
+		{
+			if (($featHash->{includemacro} || $featHash->{excludemacro}) && (!(($featHash->{includemacro} && ($featHash->{includemacro} eq $aliasfeatHash->{includemacro})) || ($featHash->{excludemacro} && ($featHash->{excludemacro} eq $aliasfeatHash->{excludemacro})))))
+			{
+				&featureparser::WARN("the value of attribute hrhmacro has been overridden in original feature ".sprintf("0x%08x", $uid));
+			}
+			undef $featHash->{includemacro};
+			undef $featHash->{excludemacro};
+		}
+		elsif($featHash->{includemacro} || $featHash->{excludemacro})
+		{
+			$aliasfeatHash->{includemacro} = $featHash->{includemacro};
+			$aliasfeatHash->{excludemacro} = $featHash->{excludemacro};
+			undef $featHash->{includemacro};
+			undef $featHash->{excludemacro};
+		}
+		if($aliasfeatHash->{statusflags})
+		{
+			if(($featHash->{statusflags}) && !($aliasfeatHash->{statusflags} eq $featHash->{statusflags}))
+			{
+				&featureparser::WARN("the value of attribute statusflags has been overridden in original feature ".sprintf("0x%08x", $uid));
+			}
+		}
+		elsif($featHash->{statusflags})
+		{
+			$aliasfeatHash->{statusflags} = $featHash->{statusflags};
+		}
+		if($aliasfeatHash->{userdata})
+		{
+			if(($featHash->{userdata}) && !($aliasfeatHash->{userdata} eq $featHash->{userdata}))
+			{
+				&featureparser::WARN("the value of attribute userdata has been overridden in original feature ".sprintf("0x%08x", $uid));
+			}
+		}
+		elsif($featHash->{userdata})
+		{
+			$aliasfeatHash->{userdata} = $featHash->{userdata};
+		}
+		if($aliasfeatHash->{infeaturesetiby})
+		{
+			if(($featHash->{infeaturesetiby}) && ($aliasfeatHash->{infeaturesetiby} != $featHash->{infeaturesetiby}))
+			{
+				&featureparser::WARN("the value of attribute infeautresetiby has been overridden in original feature ".sprintf("0x%08x", $uid));
+			}
+		}
+		elsif(defined($featHash->{infeaturesetiby}))
+		{
+			$aliasfeatHash->{infeaturesetiby} = $featHash->{infeaturesetiby};
+		}
+	}
+	# Add the unique featureset into the list
+	push @$featSetList, $newSet;
+	return 1;
+}
+
+# Read the <featureset> element
+# 
+sub createFeatureMap
+{
+	my $object = shift; 
+	return 0 if(!&featureparser::ISREF($object,"createFeatureMap"));
+	
+	# Return error if the rootelement reference is NULL
+	return 0 if($object->rootElement() < 0);
+	
+	# Get all the <featureset> elements
+	my @attrSet =  &featureparser::getnodefromTree($object->rootElement(), "featureset");
+	
+	if(@attrSet)
+	{
+		foreach my $currNode (@attrSet)
+		{
+			my %attrHashMap = ();
+			
+			# Get the <featureset> attributes
+			$fillFeatureSetAttributes->($currNode,\%attrHashMap);
+			# Get the <hfileheader> attributes
+			$fillFileHeaderAttributes->($currNode,\%attrHashMap);
+			
+			# Get the <feature> attributes
+			return 0 if( !($fillFeatureAttributes->($currNode,\%attrHashMap)) );
+			# Get the <alias> attributes
+			return 0 if( !($fillAliasAttributes->($currNode, \%attrHashMap)) );
+			
+			# Add the featureset into the object
+			if(! &addFeatureSet($object,\%attrHashMap))
+			{
+				return 0;
+			}
+		}
+		return 1;
+	}
+	return 0;
+}
+
+# Read the <defaultfeaturerange> element
+#
+sub createDefaultRangeMap
+{
+	my $object = shift; 
+	return 0 if(!&featureparser::ISREF($object,"createDefaultRangeMap"));
+	
+	# Return error if the rootelement reference is NULL
+	return 0 if($object->rootElement() < 0);
+	
+	# Get all the <defaultfeaturerange> elements
+	my @attrSet =  &featureparser::getnodefromTree($object->rootElement(), "defaultfeaturerange");
+	
+	# Add the defaultfeaturerange elements into the object
+	return &featureparser::createDefaultRangeMap($object,@attrSet);
+}
+
+# Read the attributes of the <defaultfeaturerange> element
+# @param - <defaultfeaturerange> node reference
+# @param - reference to the range attributes
+#
+sub readRangeAttributes
+{
+	my ($object, $currNode, $range) = @_; 
+	my @commentSet;
+	return 0 if(!&featureparser::ISREF($object,"readRangeAttributes"));	
+	
+	#Get the lower and higher uids
+	$range->{min} = &featureparser::getattrValue($currNode, "loweruid");
+	$range->{max} = &featureparser::getattrValue($currNode, "higheruid");
+
+ 	#Always supported/included for FM. Keep this value for compatible with FR
+ 	$range->{support} = "include";
+	#Read the <comment> element
+	@commentSet = &featureparser::getnodefromTree($currNode, "comment");
+	foreach my $node (@commentSet) {
+		$range->{comment} =  &featureparser::getelementValue($node,STRICTCASE);
+	}
+}
+
+1;
--- a/imgtools/buildrom/tools/featureparser.pm	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/featureparser.pm	Tue Jun 29 14:52:54 2010 +0800
@@ -1,465 +1,465 @@
-#
-# Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-#
-
-# This package contains routines to read the information from the Feature List XML file.
-package featureparser;  # Base class implementation of feature list xml parser
-
-# Include the genericparser to use API to read from XML file.
-use genericparser;
-use strict;
-
-#
-# Class constructor
-#
-sub new {
-	my $class = shift;
-
-	my $object = {};
-	
-	# Class members
-	$object->{_DEFAULT_RANGE} = [];        # Array of default ranges
-	$object->{_DEFAULT_INCLUDE_COUNT} = 0;       # Default include range count
-	$object->{_DEFAULT_EXCLUDE_COUNT} = 0;       # Default exclude range count
-	
-	$object->{_FILENAME} = undef;      # Current xml file parsing
-	$object->{_ROOT_ELEMENT} = undef;  # Root element pointer of current xml file
-	
-	bless($object, $class);
-	return $object;
-}
-
-#
-# Public methods
-#
-
-# Get/Set the _DEFAULT_RANGE member value of this class
-# @param : array of default ranges (optional for GET)
-#
-sub defaultRangeList 
-{
-	my $object = shift; 
-	return 0 if(!&ISREF($object,qw(defaultRangeList)));
-	
-	if (@_)
-	{ 
-		$object->{_DEFAULT_RANGE} = shift; 
-	}
-	return $object->{_DEFAULT_RANGE};
-}
-
-# Get/Set the _DEFAULT_INCLUDE_COUNT member value of this class
-# @param : default include feature count (optional for GET)
-#
-sub defaultIncludeCount
-{
-	my $object = shift; 
-	return 0 if(!&ISREF($object,qw(defaultIncludeCount)));
-	
-	if (@_)
-	{ 
-		$object->{_DEFAULT_INCLUDE_COUNT} = shift; 
-	}
-	return $object->{_DEFAULT_INCLUDE_COUNT};
-}
-
-# Get/Set the _DEFAULT_EXCLUDE_COUNT member value of this class
-# @param : default exclude feature count (optional for GET)
-#
-sub defaultExcludeCount 
-{
-	my $object = shift; 
-	return 0 if(!&ISREF($object,qw(defaultExcludeCount)));
-	
-	if (@_) 
-	{ 
-		$object->{_DEFAULT_EXCLUDE_COUNT} = shift; 
-	}
-	return $object->{_DEFAULT_EXCLUDE_COUNT};
-}
-
-# Get/Set the _FILENAME member value of this class
-# @param : xml file name (optional for GET)
-#
-sub fileName 
-{
-	my $object = shift; 
-	return 0 if(!&ISREF($object,qw(fileName)));
-	
-	if (@_) 
-	{ 
-		$object->{_FILENAME} = shift; 
-	}
-	return $object->{_FILENAME};
-}
-
-# Get/Set the _ROOT_ELEMENT member value of this class
-# @param : root element document pointer (optional for GET)
-#
-sub rootElement 
-{
-	my $object = shift; 
-	return 0 if(!&ISREF($object,qw(rootElement)));
-	
-	if (@_) 
-	{ 
-		$object->{_ROOT_ELEMENT} = shift; 
-	}
-	return $object->{_ROOT_ELEMENT};
-}
-
-# Parse the feature xml file
-# @param : xml file name to parse
-#
-sub parseXMLFile 
-{
-	my $object = shift; 
-	return 0 if(!&ISREF($object,qw(parseXMLFile)));
-	
-	my $file = shift; # Get the featuredatabase XML filename
-	$object->fileName($file);
-	
-	# Check for the existence of xml file
-	if(!(-e $file)) 
-	{
-		ERROR($file." doesn\'t exist");
-		return 0;
-	}
-	
-	#Parse the file and Get root Element
-	my $root = &genericparser::getRootElement($file);
-	$object->rootElement($root);
-	
-	if($root)
-	{
-		#Read the <featureset>/<feature> elements
-		if( !($object->createFeatureMap()) ) 
-		{
-			return 0;
-		}
-		#Read the <defaultfeaturerange> elements
-		if( !($object->createDefaultRangeMap()) ) 
-		{
-			return 0;
-		}
-		
-		return 1;
-	}
-
-	return -1;
-}
-
-# Read the <defaultfeaturerange> elements
-# @param - input range attribute set
-#
-sub createDefaultRangeMap
-{
-	my ($object, @attrSet) = @_; 
-	return 0 if(!&ISREF($object,"createDefaultRangeMap"));
-	
-	# Get the reference to the default feature range list from the object
-	my $rangeList = $object->defaultRangeList();
-	foreach my $currNode (@attrSet)
-	{
-		my ($min, $max);
-		my %attrHashMap = ();
-
-		# Get the range attributes
-		$object->readRangeAttributes($currNode, \%attrHashMap);
-		
-		#Get the lower and higher uids
-		$min = $attrHashMap{min};
-		$max = $attrHashMap{max};
-		
-		#Validate it
-		if((!&IsValidNum($min)) or (!&IsValidNum($max))) {
-			&ERROR("Valid hexadecimal or decimal value expected in default range");
-			return 0;
-		}
-
-		#Convert it to decimal
-		$attrHashMap{min} = &ConvertHexToDecimal($min);
-		$attrHashMap{max} = &ConvertHexToDecimal($max);
-		if( $attrHashMap{min} > $attrHashMap{max} ) {
-			&ERROR("Mininum/Lower UID value ".$min." is greater than Maximum/Higher UID value ".$max);
-			return 0;
-		}
-	
-		#Add it to the existing range list
-		my $include = 1;
-		foreach my $node (@$rangeList) { #Check the range already exists
-			if(($node->{min} == $attrHashMap{min}) && ($node->{max} == $attrHashMap{max}) 
-				&& ($node->{support} eq $attrHashMap{support})) {
-				$include = 0;
-			}
-		}
-		if($include) { # If it is a new range attribute then add it to the list
-			push @$rangeList, \%attrHashMap;
-			$object->defaultIncludeCount($object->defaultIncludeCount()+1) if(lc($attrHashMap{support}) eq "include");
-			$object->defaultExcludeCount($object->defaultExcludeCount()+1) if(lc($attrHashMap{support}) eq "exclude");
-		}
-	}
-
-	return 1;
-}
-
-# Get the default include ranges of min and max values in 2dimensional array
-#
-sub getDefaultIncludeInfo()
-{
-	my $object = shift; 
-	return 0 if(!&ISREF($object,qw(getDefaultIncludeInfo)));
-	
-	my @result;	
-	my %tempHash=();
-	
-	my $rangeList = $object->defaultRangeList();
-	foreach my $range (@$rangeList)
-	{
-		if(lc($range->{"support"}) eq "include" )
-		{
-			my $min_value=$range->{"min"};
-			my $max_value=$range->{"max"};
-			$tempHash{$min_value} = $max_value;
-		}				
-	}
-
-	my $index = 0;
-	my @sortedHash = sort keys %tempHash;
-
-	foreach my $key (@sortedHash)
-	{
-		push @{$result[$index]},$key;
-		push @{$result[$index]},$tempHash{$key};	
-		$index++;
-	}	
-	return @result;
-}
-
-# Get the default exclude ranges of min and max values in 2dimensional array
-#
-sub getDefaultExcludeInfo()
-{
-	my $object = shift; 
-	return 0 if(!&ISREF($object,qw(getDefaultExcludeInfo)));
-	
-	my @result;
-	my %tempHash=();
-	
-	my $rangeList = $object->defaultRangeList();
-	foreach my $range (@$rangeList)
-	{
-		if(lc($range->{"support"}) eq "exclude" )
-		{
-			my $min_value=$range->{"min"};
-			my $max_value=$range->{"max"};
-			$tempHash{$min_value} = $max_value;
-		}				
-	}
-
-	my $index = 0;
-	my @sortedHash = sort {$a <=> $b}(keys %tempHash);
-	foreach my $key (@sortedHash){
-		push @{$result[$index]},$key;
-		push @{$result[$index]},$tempHash{$key};
-		$index++;
-	}
-	return @result;
-}
-
-# Get the count of total number of ranges that are either included or excluded on the device as default
-# 
-sub getDefaultTotalCount()
-{
-	my $object = shift; 
-	return 0 if(!&ISREF($object,qw(getDefaultTotalCount)));
-	
-	return ($object->defaultIncludeCount() + $object->defaultExcludeCount());
-}
-
-# For a given uid value, this function checks if the given uid is within the default=present range.
-# @param : UID to check
-#
-sub getRangeEntry
-{
-	my $object = shift; 
-	return 0 if(!&ISREF($object,qw(getRangeEntry)));
-	
-	my $aUid = shift;
-	my $length = $object->getDefaultTotalCount();
-	my $pos = 0;
-	my $rangeRef;
-
-	my $rangeList = $object->defaultRangeList();
-	foreach my $range (@$rangeList)
-	{
-		if ( (lc($range->{"support"}) eq "include") and ($range->{"min"} <= $aUid) and ($range->{"max"} >= $aUid) )
-		{
-			return $range;
-		}
-	}
-	return undef;
-}
-
-# Get the list of features
-#
-sub getFeatures($$)
-{
-	my ($includeFeatureRef, $excludeFeatureRef) = @_;
-	my %FeatureMap = ();
-	my @FeatList = ();
-	my $featRef;
-	my $uid;
-
-	foreach my $feat (@$excludeFeatureRef)
-	{
-		$uid = $feat->{uid};
-
-		$featRef = $FeatureMap{$uid};
-
-		if( $featRef->{include} == 1 )
-		{
-			&ERROR("The feature $feat->{name} was added into the exclude as well as include list");
-			return 0;
-		}
-		elsif($featRef->{exclude} == 1)
-		{
-#			Already added to the final feature list
-			next;
-		}
-		else
-		{
-			$FeatureMap{$uid} = $feat;
-			push @FeatList, $feat;
-		}
-	}
-
-	foreach my $feat (@$includeFeatureRef)
-	{
-		$uid = $feat->{uid};
-
-		$featRef = $FeatureMap{$uid};
-
-		if( $featRef->{exclude} == 1 )
-		{
-			&ERROR("The feature $feat->{name} was added into the exclude as well as include list");
-			return 0;
-		}
-		elsif($featRef->{include} == 1)
-		{
-#			Already added to the final feature list
-			next;
-		}
-		else
-		{
-			$FeatureMap{$uid} = $feat;
-			push @FeatList, $feat;
-		}
-	}
-
-	return \@FeatList;
-}
-
-# ========================================================================
-# Wrappers for generic xml parser
-# ========================================================================
-sub featureparser::getnodefromTree 
-{ 
-	&genericparser::getNodeFromTree(@_); 
-}
-
-sub getattrValue 
-{ 
-	&genericparser::getAttrValue(@_); 
-}
-
-sub getelementValue 
-{ 
-	&genericparser::getElementValue(@_); 
-}
-
-# ========================================================================
-# Utility sub routines
-# ========================================================================
-# Check whether the object is reference type
-# @param : the object reference
-#
-sub ISREF 
-{
-	my ($object, $method) = @_;
-	if(!ref($object)) 
-	{ 
-		&ERROR("**Object is not reference-type for the method($method)");
-		return 0;
-	}
-	return 1;
-}
-
-# Parser debugging routines
-#
-sub WARN 
-{ 
-	print "WARNING: ".$_[0]."\n";
-}
-sub ERROR 
-{ 
-	print "ERROR: ".$_[0]."\n";
-}
-
-# Return Decimal value for the given Hexadecimal number.
-# @param : HexaDecimal Value
-#
-sub ConvertHexToDecimal 
-{
-	my $val = shift;
-	if(grep /^0x/i, $val) 
-	{
-		# Input is Hexadecimal value, convert to Decimal
-		return hex($val);	 
-	}
-	else 
-	{
-		# Decimal value
-		return $val;
-	}
-}
-
-# Validate if the given value is a valid number
-#
-sub IsValidNum 
-{
-	my $num = shift;
-	return 1 if($num =~ /^\d+$|^0[x][\da-f]+/i);
-	return 0;
-}
-
-# Validate if the given UID value is a valid number (either decimal or hexadecimal number)
-#
-sub ValidateUIDValue 
-{
-	my $fuid = shift;
-	# check to ensure that uid value contains only valid digits (decimal/hexadecimal)
-	if(IsValidNum $fuid) 
-	{
-		return 1;
-	}
-	else 
-	{
-		&ERROR("Invalid UID value".$fuid."\n");
-		return 0;
-	}
-}
-
+#
+# Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+#
+
+# This package contains routines to read the information from the Feature List XML file.
+package featureparser;  # Base class implementation of feature list xml parser
+
+# Include the genericparser to use API to read from XML file.
+use genericparser;
+use strict;
+
+#
+# Class constructor
+#
+sub new {
+	my $class = shift;
+
+	my $object = {};
+	
+	# Class members
+	$object->{_DEFAULT_RANGE} = [];        # Array of default ranges
+	$object->{_DEFAULT_INCLUDE_COUNT} = 0;       # Default include range count
+	$object->{_DEFAULT_EXCLUDE_COUNT} = 0;       # Default exclude range count
+	
+	$object->{_FILENAME} = undef;      # Current xml file parsing
+	$object->{_ROOT_ELEMENT} = undef;  # Root element pointer of current xml file
+	
+	bless($object, $class);
+	return $object;
+}
+
+#
+# Public methods
+#
+
+# Get/Set the _DEFAULT_RANGE member value of this class
+# @param : array of default ranges (optional for GET)
+#
+sub defaultRangeList 
+{
+	my $object = shift; 
+	return 0 if(!&ISREF($object,qw(defaultRangeList)));
+	
+	if (@_)
+	{ 
+		$object->{_DEFAULT_RANGE} = shift; 
+	}
+	return $object->{_DEFAULT_RANGE};
+}
+
+# Get/Set the _DEFAULT_INCLUDE_COUNT member value of this class
+# @param : default include feature count (optional for GET)
+#
+sub defaultIncludeCount
+{
+	my $object = shift; 
+	return 0 if(!&ISREF($object,qw(defaultIncludeCount)));
+	
+	if (@_)
+	{ 
+		$object->{_DEFAULT_INCLUDE_COUNT} = shift; 
+	}
+	return $object->{_DEFAULT_INCLUDE_COUNT};
+}
+
+# Get/Set the _DEFAULT_EXCLUDE_COUNT member value of this class
+# @param : default exclude feature count (optional for GET)
+#
+sub defaultExcludeCount 
+{
+	my $object = shift; 
+	return 0 if(!&ISREF($object,qw(defaultExcludeCount)));
+	
+	if (@_) 
+	{ 
+		$object->{_DEFAULT_EXCLUDE_COUNT} = shift; 
+	}
+	return $object->{_DEFAULT_EXCLUDE_COUNT};
+}
+
+# Get/Set the _FILENAME member value of this class
+# @param : xml file name (optional for GET)
+#
+sub fileName 
+{
+	my $object = shift; 
+	return 0 if(!&ISREF($object,qw(fileName)));
+	
+	if (@_) 
+	{ 
+		$object->{_FILENAME} = shift; 
+	}
+	return $object->{_FILENAME};
+}
+
+# Get/Set the _ROOT_ELEMENT member value of this class
+# @param : root element document pointer (optional for GET)
+#
+sub rootElement 
+{
+	my $object = shift; 
+	return 0 if(!&ISREF($object,qw(rootElement)));
+	
+	if (@_) 
+	{ 
+		$object->{_ROOT_ELEMENT} = shift; 
+	}
+	return $object->{_ROOT_ELEMENT};
+}
+
+# Parse the feature xml file
+# @param : xml file name to parse
+#
+sub parseXMLFile 
+{
+	my $object = shift; 
+	return 0 if(!&ISREF($object,qw(parseXMLFile)));
+	
+	my $file = shift; # Get the featuredatabase XML filename
+	$object->fileName($file);
+	
+	# Check for the existence of xml file
+	if(!(-e $file)) 
+	{
+		ERROR($file." doesn\'t exist");
+		return 0;
+	}
+	
+	#Parse the file and Get root Element
+	my $root = &genericparser::getRootElement($file);
+	$object->rootElement($root);
+	
+	if($root)
+	{
+		#Read the <featureset>/<feature> elements
+		if( !($object->createFeatureMap()) ) 
+		{
+			return 0;
+		}
+		#Read the <defaultfeaturerange> elements
+		if( !($object->createDefaultRangeMap()) ) 
+		{
+			return 0;
+		}
+		
+		return 1;
+	}
+
+	return -1;
+}
+
+# Read the <defaultfeaturerange> elements
+# @param - input range attribute set
+#
+sub createDefaultRangeMap
+{
+	my ($object, @attrSet) = @_; 
+	return 0 if(!&ISREF($object,"createDefaultRangeMap"));
+	
+	# Get the reference to the default feature range list from the object
+	my $rangeList = $object->defaultRangeList();
+	foreach my $currNode (@attrSet)
+	{
+		my ($min, $max);
+		my %attrHashMap = ();
+
+		# Get the range attributes
+		$object->readRangeAttributes($currNode, \%attrHashMap);
+		
+		#Get the lower and higher uids
+		$min = $attrHashMap{min};
+		$max = $attrHashMap{max};
+		
+		#Validate it
+		if((!&IsValidNum($min)) or (!&IsValidNum($max))) {
+			&ERROR("Valid hexadecimal or decimal value expected in default range");
+			return 0;
+		}
+
+		#Convert it to decimal
+		$attrHashMap{min} = &ConvertHexToDecimal($min);
+		$attrHashMap{max} = &ConvertHexToDecimal($max);
+		if( $attrHashMap{min} > $attrHashMap{max} ) {
+			&ERROR("Mininum/Lower UID value ".$min." is greater than Maximum/Higher UID value ".$max);
+			return 0;
+		}
+	
+		#Add it to the existing range list
+		my $include = 1;
+		foreach my $node (@$rangeList) { #Check the range already exists
+			if(($node->{min} == $attrHashMap{min}) && ($node->{max} == $attrHashMap{max}) 
+				&& ($node->{support} eq $attrHashMap{support})) {
+				$include = 0;
+			}
+		}
+		if($include) { # If it is a new range attribute then add it to the list
+			push @$rangeList, \%attrHashMap;
+			$object->defaultIncludeCount($object->defaultIncludeCount()+1) if(lc($attrHashMap{support}) eq "include");
+			$object->defaultExcludeCount($object->defaultExcludeCount()+1) if(lc($attrHashMap{support}) eq "exclude");
+		}
+	}
+
+	return 1;
+}
+
+# Get the default include ranges of min and max values in 2dimensional array
+#
+sub getDefaultIncludeInfo()
+{
+	my $object = shift; 
+	return 0 if(!&ISREF($object,qw(getDefaultIncludeInfo)));
+	
+	my @result;	
+	my %tempHash=();
+	
+	my $rangeList = $object->defaultRangeList();
+	foreach my $range (@$rangeList)
+	{
+		if(lc($range->{"support"}) eq "include" )
+		{
+			my $min_value=$range->{"min"};
+			my $max_value=$range->{"max"};
+			$tempHash{$min_value} = $max_value;
+		}				
+	}
+
+	my $index = 0;
+	my @sortedHash = sort keys %tempHash;
+
+	foreach my $key (@sortedHash)
+	{
+		push @{$result[$index]},$key;
+		push @{$result[$index]},$tempHash{$key};	
+		$index++;
+	}	
+	return @result;
+}
+
+# Get the default exclude ranges of min and max values in 2dimensional array
+#
+sub getDefaultExcludeInfo()
+{
+	my $object = shift; 
+	return 0 if(!&ISREF($object,qw(getDefaultExcludeInfo)));
+	
+	my @result;
+	my %tempHash=();
+	
+	my $rangeList = $object->defaultRangeList();
+	foreach my $range (@$rangeList)
+	{
+		if(lc($range->{"support"}) eq "exclude" )
+		{
+			my $min_value=$range->{"min"};
+			my $max_value=$range->{"max"};
+			$tempHash{$min_value} = $max_value;
+		}				
+	}
+
+	my $index = 0;
+	my @sortedHash = sort {$a <=> $b}(keys %tempHash);
+	foreach my $key (@sortedHash){
+		push @{$result[$index]},$key;
+		push @{$result[$index]},$tempHash{$key};
+		$index++;
+	}
+	return @result;
+}
+
+# Get the count of total number of ranges that are either included or excluded on the device as default
+# 
+sub getDefaultTotalCount()
+{
+	my $object = shift; 
+	return 0 if(!&ISREF($object,qw(getDefaultTotalCount)));
+	
+	return ($object->defaultIncludeCount() + $object->defaultExcludeCount());
+}
+
+# For a given uid value, this function checks if the given uid is within the default=present range.
+# @param : UID to check
+#
+sub getRangeEntry
+{
+	my $object = shift; 
+	return 0 if(!&ISREF($object,qw(getRangeEntry)));
+	
+	my $aUid = shift;
+	my $length = $object->getDefaultTotalCount();
+	my $pos = 0;
+	my $rangeRef;
+
+	my $rangeList = $object->defaultRangeList();
+	foreach my $range (@$rangeList)
+	{
+		if ( (lc($range->{"support"}) eq "include") and ($range->{"min"} <= $aUid) and ($range->{"max"} >= $aUid) )
+		{
+			return $range;
+		}
+	}
+	return undef;
+}
+
+# Get the list of features
+#
+sub getFeatures($$)
+{
+	my ($includeFeatureRef, $excludeFeatureRef) = @_;
+	my %FeatureMap = ();
+	my @FeatList = ();
+	my $featRef;
+	my $uid;
+
+	foreach my $feat (@$excludeFeatureRef)
+	{
+		$uid = $feat->{uid};
+
+		$featRef = $FeatureMap{$uid};
+
+		if( defined ($featRef) && defined ($featRef->{include}) && $featRef->{include} == 1 )
+		{
+			&ERROR("The feature $feat->{name} was added into the exclude as well as include list");
+			return 0;
+		}
+		elsif($featRef->{exclude} == 1)
+		{
+#			Already added to the final feature list
+			next;
+		}
+		else
+		{
+			$FeatureMap{$uid} = $feat;
+			push @FeatList, $feat;
+		}
+	}
+
+	foreach my $feat (@$includeFeatureRef)
+	{
+		$uid = $feat->{uid};
+
+		$featRef = $FeatureMap{$uid};
+
+		if( defined ($featRef) && defined ($featRef->{exclude}) && $featRef->{exclude} == 1 )
+		{
+			&ERROR("The feature $feat->{name} was added into the exclude as well as include list");
+			return 0;
+		}
+		elsif($featRef->{include} == 1)
+		{
+#			Already added to the final feature list
+			next;
+		}
+		else
+		{
+			$FeatureMap{$uid} = $feat;
+			push @FeatList, $feat;
+		}
+	}
+
+	return \@FeatList;
+}
+
+# ========================================================================
+# Wrappers for generic xml parser
+# ========================================================================
+sub featureparser::getnodefromTree 
+{ 
+	&genericparser::getNodeFromTree(@_); 
+}
+
+sub getattrValue 
+{ 
+	&genericparser::getAttrValue(@_); 
+}
+
+sub getelementValue 
+{ 
+	&genericparser::getElementValue(@_); 
+}
+
+# ========================================================================
+# Utility sub routines
+# ========================================================================
+# Check whether the object is reference type
+# @param : the object reference
+#
+sub ISREF 
+{
+	my ($object, $method) = @_;
+	if(!ref($object)) 
+	{ 
+		&ERROR("**Object is not reference-type for the method($method)");
+		return 0;
+	}
+	return 1;
+}
+
+# Parser debugging routines
+#
+sub WARN 
+{ 
+	print "WARNING: ".$_[0]."\n";
+}
+sub ERROR 
+{ 
+	print "ERROR: ".$_[0]."\n";
+}
+
+# Return Decimal value for the given Hexadecimal number.
+# @param : HexaDecimal Value
+#
+sub ConvertHexToDecimal 
+{
+	my $val = shift;
+	if(defined ($val) && grep /^0x/i, $val) 
+	{
+		# Input is Hexadecimal value, convert to Decimal
+		return hex($val);	 
+	}
+	else 
+	{
+		# Decimal value
+		return $val;
+	}
+}
+
+# Validate if the given value is a valid number
+#
+sub IsValidNum 
+{
+	my $num = shift;
+	return 1 if($num =~ /^\d+$|^0[x][\da-f]+/i);
+	return 0;
+}
+
+# Validate if the given UID value is a valid number (either decimal or hexadecimal number)
+#
+sub ValidateUIDValue 
+{
+	my $fuid = shift;
+	# check to ensure that uid value contains only valid digits (decimal/hexadecimal)
+	if(IsValidNum $fuid) 
+	{
+		return 1;
+	}
+	else 
+	{
+		&ERROR("Invalid UID value".$fuid."\n");
+		return 0;
+	}
+}
+
 1;
\ No newline at end of file
--- a/imgtools/buildrom/tools/features.pl	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/features.pl	Tue Jun 29 14:52:54 2010 +0800
@@ -1,303 +1,315 @@
-#
-# Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-#
-
-# features tool version
-use constant TOOL_VERSION=>"0.2";
-
-# global variables
-my $PerlLibPath;    # fully qualified pathname of the directory containing our Perl modules
-my $ibyPath; # destination path for the iby files
-my $hdrPath; # destination path for the header files
-my $datPath; # destination path for the features.DAT file
-my $convPath; # destination path for the feature registry database convertion
-my $epocroot = $ENV{EPOCROOT}; # epcoroot directory
-
-#
-# xml database file name(s)
-#
-my @xmlDBFile;
-
-#
-# flags to suppress the output files
-# 0x01 = generate header files only
-# 0x02 = genereate iby files only
-# 0x04 = generate dat files only
-# 0x08 = convert feature registry database to feature manager database
-#
-use constant FLG_GENHDR=>0x01;
-use constant FLG_GENIBY=>0x02;
-use constant FLG_GENDAT=>0x04;
-use constant FLG_CONVFR=>0x08;
-my $flagOut = 0;
-
-use FindBin;		# for FindBin::Bin
-BEGIN {
-# check user has a version of perl that will cope
-	require 5.005_03;
-# establish the path to the Perl libraries
-    $PerlLibPath = $FindBin::Bin;	# X:/epoc32/tools
-    $PerlLibPath .= "/";
-}
-use  lib $PerlLibPath;
-# Includes the validation perl modules for XML validation against the given DTD.
-use lib "$PerlLibPath/build/lib";
-# Include routines to create the feature header and iby files.
-use features;
-
-#
-# main - Tool entry function
-#
-{
-	# Default path settings
-	&processPath(\$epocroot);
-	&features::set_DefaultPath($epocroot, \$hdrPath, \$ibyPath, \$datPath, \$convPath);
-	
-	# Process the command line arguments
-	if(&process_cmdline_arguments()) {
-		# Open the xml database
-		if(&features::open_Database(@xmlDBFile)) {
-		
-			# Generate the header file in the appropriate format with the featureset attributes
-			&features::generate_Headerfile($hdrPath) if($flagOut&FLG_GENHDR);
-			
-			# Generate the obey file in the appropriate format with the featureset attributes
-			&features::generate_Obeyfile($ibyPath) if($flagOut&FLG_GENIBY);
-			
-			# Generate the feature dat file
-			&features::generate_DATfile($datPath) if($flagOut&FLG_GENDAT);
-			
-			# Convert the feature registry database to feature manager database
-			&features::convert_FeatRegToFeatMgr($convPath,@xmlDBFile) if($flagOut&FLG_CONVFR);
-		}
-	}
-}
-
-#
-# Process the command line arguments
-# 
-sub process_cmdline_arguments
-{
-	my $helpCmd = 0;
-	
-	foreach my $arg (@ARGV)
-	{
-		if( ($arg =~ /^--(\S+)$/)  or ($arg =~ /^-([ridc]=.+)$/) )
-		{
-			$arg = $1;
-			if( (($arg =~ /^hdrfile$/i) || ($arg =~ /^hdrfile=(.+)/i)) or ($arg =~ /^r=(.+)/) ) {
-				# option to generate only header files
-				if($1) {
-					$hdrPath = $1;
-					processPath(\$hdrPath);
-				}
-				$flagOut |= FLG_GENHDR;
-			}
-			elsif( (($arg =~ /^ibyfile$/i) || ($arg =~ /^ibyfile=(.+)/i)) or ($arg =~ /^i=(.+)/) ) {
-				# option to generate only iby files
-				if($1) {
-					$ibyPath = $1;
-					processPath(\$ibyPath);
-				}
-				$flagOut |= FLG_GENIBY;
-			}
-			elsif( (($arg =~ /^datfile$/i) || ($arg =~ /^datfile=(.+)/i)) or ($arg =~ /^d=(.+)/) ) {
-				# option to generate only dat files
-				if($1) {
-					$datPath = $1;
-					processPath(\$datPath);
-				}
-				$flagOut |= FLG_GENDAT;
-			}
-			elsif( (($arg =~ /^convert$/i) || ($arg =~ /^convert=(.+)/i)) or ($arg =~ /^c=(.+)/) ) {
-				# option to convert feature registry database
-				if($1) {
-					$convPath = $1;
-					processPath(\$convPath);
-				}
-				$flagOut |= FLG_CONVFR;
-			}
-			elsif( $arg =~ /^verbose$/i ) {
-				# option to enable verbose mode
-				&printTitle(); 
-				&features::set_VerboseMode();
-			}
-			elsif( $arg =~ /^strict$/i ) {
-				# option to enable strict mode
-				&features::set_StrictMode();
-			}
-			elsif( $arg =~ /^help$/i ) {
-				# print the usage on console
-				$helpCmd = 1;
-			}
-			elsif( $arg =~ /^version$/i ) {
-				# print the title on console
-				&printTitle();
-				return 1 if(scalar(@ARGV) == 1); # if this is the only option
-			}
-			else
-			{
-				print "Error: Unknown parameter $arg\n";
-				return 0;
-			}
-			next;
-		}
-		elsif( $arg =~ /^-(\S+)$/ )
-		{
-			my @flags = split("",$1);
-			
-			foreach my $opt (@flags) {
-				if( $opt =~ /^r/i ) {
-					# option to generate only header files
-					$flagOut |= FLG_GENHDR;
-				}
-				elsif( $opt =~ /^i/i ) {
-					# option to generate only iby files
-					$flagOut |= FLG_GENIBY;
-				}
-				elsif( $opt =~ /^d/i ) {
-					# option to generate only dat files
-					$flagOut |= FLG_GENDAT;
-				}
-				elsif( $opt =~ /^c/i ) {
-					# option to convert feature registry database
-					$flagOut |= FLG_CONVFR;
-				}
-				elsif( $opt =~ /^v/i ) {
-					# option to enable verbose mode
-					&printTitle(); 
-					&features::set_VerboseMode();
-				}
-				elsif( $opt =~ /^s/i ) {
-					# option to enable strict mode
-					&features::set_StrictMode();
-				}
-				elsif( $opt =~ /^h/i ) {
-					# print the usage on console
-					$helpCmd = 1;
-				}
-				else
-				{
-					print "Error: Unknown option $opt\n";
-					return 0;
-				}
-			}
-			next;
-		}
-	
-		next if(xmlfile($arg));
-		next if(xmlfile("$arg.xml"));
-		next if(xmlfile("$epocroot"."epoc32/rom/include/$arg"));
-		
-		print "Error: Cannot find xml file: $arg\n";
-	}
-
-	# process the help command
-	if($helpCmd) {
-		&print_usage();
-		return 1 if(scalar(@ARGV) == 1); # if this is the only option
-	}
-	
-	if(!@xmlDBFile) {
-		# xml database is must here
-		print "Error: No xml database given\n";
-		&print_usage() if(!$helpCmd);
-		return 0;
-	}
-	
-	# if the suppress output option is not passed then generate both
-	$flagOut = (FLG_GENHDR|FLG_GENIBY|FLG_GENDAT|FLG_CONVFR) if(!$flagOut);
-	
-	return 1;
-}
-
-# --Utility Functions
-
-#
-# check whether the given file exists
-# @param - file name for the existance check
-#
-sub xmlfile
-{
-	my ($file) = shift;
-	
-	if(-e $file) {
-		push @xmlDBFile, $file;
-		return 1;
-	}
-	return 0;
-}
-
-#
-# Process the given absolute path
-# Add backslash at the end if required
-# @param - path to be processed
-#
-sub processPath
-{
-	my ($path) = shift;
-	
-	return if( $$path =~ /(\\$)/ );
-	return if( $$path =~ /(\/$)/ );
-	$$path .= "/";
-}
-
-#
-# Print the title
-#
-sub printTitle
-{
-	print "FEATURES - Features manager tool V".TOOL_VERSION."\n";
-	print "Copyright (c) 2009 Nokia Corporation.\n\n"
-}
-
-#
-# print the usage of this tool
-#
-sub print_usage
-{
-#........1.........2.........3.........4.........5.........6.........7.....
-	&printTitle();
-	print <<USAGE_EOF;
-Usage:
-  features [options] <xml database> [<xml database> <xml database> ...]
-
-Generation of C++ header file and IBY file for the given featuremanger 
-database file. It also generates features DAT file for the given 
-featuemanager/featureregistry database file
-
-Options:
-   -r or --hdrfile[=<destination path>] - generates only header file
-   -i or --ibyfile[=<destination path>] - generates only IBY file
-   -d or --datfile[=<destination path>] - generates only features.DAT file
-   -c or --convert[=<destination path>] - converts feature registry database
-   
-   -s or --strict        - enable strict mode
-   -v or --verbose       - enable verbose mode
-   -h or --help          - displays this help
-   
-   --version             - displays the tools version
-
-Ex: option combination \"-ri\" generates header and IBY files
-   
-Default destination paths:
-   <header file>         - $EPOCROOT\\epoc32\\include\\
-   <iby file>            - $EPOCROOT\\epoc32\\rom\\include\\
-   <features.dat file>   - generates in current directory
-   
-Note: The conversion(--convert) of feature registry database requires the 
-feature registry dtd file(featureuids.dtd) in $EPOCROOT\\epoc32\\tools\\
-USAGE_EOF
-}
+#!/usr/bin/perl
+#
+# Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+#
+
+# features tool version
+use constant TOOL_VERSION=>"0.3";
+
+# global variables
+my $PerlLibPath;    # fully qualified pathname of the directory containing our Perl modules
+my $PerlEPOCPath;   # fully qualified pathname of the directory containing epoc tools
+my $ibyPath; # destination path for the iby files
+my $hdrPath; # destination path for the header files
+my $datPath; # destination path for the features.DAT file
+my $convPath; # destination path for the feature registry database convertion
+my $epocroot = &get_epocroot; # epcoroot directory
+
+#
+# xml database file name(s)
+#
+my @xmlDBFile;
+
+#
+# flags to suppress the output files
+# 0x01 = generate header files only
+# 0x02 = genereate iby files only
+# 0x04 = generate dat files only
+# 0x08 = convert feature registry database to feature manager database
+#
+use constant FLG_GENHDR=>0x01;
+use constant FLG_GENIBY=>0x02;
+use constant FLG_GENDAT=>0x04;
+use constant FLG_CONVFR=>0x08;
+my $flagOut = 0;
+
+use FindBin;		# for FindBin::Bin
+BEGIN {
+# check user has a version of perl that will cope
+	require 5.005_03;
+# establish the path to the Perl libraries
+    $PerlLibPath = $FindBin::Bin;
+    $PerlLibPath =~ s/\\/\//g;
+    $PerlLibPath .= "\/" unless $PerlLibPath =~ /\/$/;
+    
+    $PerlEPOCPath = $ENV{EPOCROOT};
+    $PerlEPOCPath =~ s/\\/\//g;
+    $PerlEPOCPath .= "\/" unless $PerlEPOCPath =~ /\/$/;
+    $PerlEPOCPath .= "epoc32\/tools\/";
+}
+
+# Includes the validation perl modules for XML validation against the given DTD.
+use lib "${PerlEPOCPath}build/lib";
+use lib $PerlEPOCPath;
+use lib $PerlLibPath;
+
+# Include routines to create the feature header and iby files.
+use features;
+
+use romutl;
+#
+# main - Tool entry function
+#
+{
+	# Default path settings
+	&processPath(\$epocroot);
+	&features::set_DefaultPath($epocroot, \$hdrPath, \$ibyPath, \$datPath, \$convPath);
+	
+	# Process the command line arguments
+	if(&process_cmdline_arguments()) {
+		# Open the xml database
+		if(&features::open_Database(@xmlDBFile)) {
+		
+			# Generate the header file in the appropriate format with the featureset attributes
+			&features::generate_Headerfile($hdrPath) if($flagOut&FLG_GENHDR);
+			
+			# Generate the obey file in the appropriate format with the featureset attributes
+			&features::generate_Obeyfile($ibyPath) if($flagOut&FLG_GENIBY);
+			
+			# Generate the feature dat file
+			&features::generate_DATfile($datPath) if($flagOut&FLG_GENDAT);
+			
+			# Convert the feature registry database to feature manager database
+			&features::convert_FeatRegToFeatMgr($convPath,@xmlDBFile) if($flagOut&FLG_CONVFR);
+		}
+	}
+}
+
+#
+# Process the command line arguments
+# 
+sub process_cmdline_arguments
+{
+	my $helpCmd = 0;
+	
+	foreach my $arg (@ARGV)
+	{
+		if( ($arg =~ /^--(\S+)$/)  or ($arg =~ /^-([ridc]=.+)$/) )
+		{
+			$arg = $1;
+			if( (($arg =~ /^hdrfile$/i) || ($arg =~ /^hdrfile=(.+)/i)) or ($arg =~ /^r=(.+)/) ) {
+				# option to generate only header files
+				if($1) {
+					$hdrPath = $1;
+					processPath(\$hdrPath);
+				}
+				$flagOut |= FLG_GENHDR;
+			}
+			elsif( (($arg =~ /^ibyfile$/i) || ($arg =~ /^ibyfile=(.+)/i)) or ($arg =~ /^i=(.+)/) ) {
+				# option to generate only iby files
+				if($1) {
+					$ibyPath = $1;
+					processPath(\$ibyPath);
+				}
+				$flagOut |= FLG_GENIBY;
+			}
+			elsif( (($arg =~ /^datfile$/i) || ($arg =~ /^datfile=(.+)/i)) or ($arg =~ /^d=(.+)/) ) {
+				# option to generate only dat files
+				if($1) {
+					$datPath = $1;
+					processPath(\$datPath);
+				}
+				$flagOut |= FLG_GENDAT;
+			}
+			elsif( (($arg =~ /^convert$/i) || ($arg =~ /^convert=(.+)/i)) or ($arg =~ /^c=(.+)/) ) {
+				# option to convert feature registry database
+				if($1) {
+					$convPath = $1;
+					processPath(\$convPath);
+				}
+				$flagOut |= FLG_CONVFR;
+			}
+			elsif( $arg =~ /^verbose$/i ) {
+				# option to enable verbose mode
+				&printTitle(); 
+				&features::set_VerboseMode();
+			}
+			elsif( $arg =~ /^strict$/i ) {
+				# option to enable strict mode
+				&features::set_StrictMode();
+			}
+			elsif( $arg =~ /^help$/i ) {
+				# print the usage on console
+				$helpCmd = 1;
+			}
+			elsif( $arg =~ /^version$/i ) {
+				# print the title on console
+				&printTitle();
+				return 1 if(scalar(@ARGV) == 1); # if this is the only option
+			}
+			else
+			{
+				print "Error: Unknown parameter $arg\n";
+				return 0;
+			}
+			next;
+		}
+		elsif( $arg =~ /^-(\S+)$/ )
+		{
+			my @flags = split("",$1);
+			
+			foreach my $opt (@flags) {
+				if( $opt =~ /^r/i ) {
+					# option to generate only header files
+					$flagOut |= FLG_GENHDR;
+				}
+				elsif( $opt =~ /^i/i ) {
+					# option to generate only iby files
+					$flagOut |= FLG_GENIBY;
+				}
+				elsif( $opt =~ /^d/i ) {
+					# option to generate only dat files
+					$flagOut |= FLG_GENDAT;
+				}
+				elsif( $opt =~ /^c/i ) {
+					# option to convert feature registry database
+					$flagOut |= FLG_CONVFR;
+				}
+				elsif( $opt =~ /^v/i ) {
+					# option to enable verbose mode
+					&printTitle(); 
+					&features::set_VerboseMode();
+				}
+				elsif( $opt =~ /^s/i ) {
+					# option to enable strict mode
+					&features::set_StrictMode();
+				}
+				elsif( $opt =~ /^h/i ) {
+					# print the usage on console
+					$helpCmd = 1;
+				}
+				else
+				{
+					print "Error: Unknown option $opt\n";
+					return 0;
+				}
+			}
+			next;
+		}
+	
+		next if(xmlfile($arg));
+		next if(xmlfile("$arg.xml"));
+		next if(xmlfile("$epocroot"."epoc32/rom/include/$arg"));
+		
+		print "Error: Cannot find xml file: $arg\n";
+	}
+
+	# process the help command
+	if($helpCmd) {
+		&print_usage();
+		return 1 if(scalar(@ARGV) == 1); # if this is the only option
+	}
+	
+	if(!@xmlDBFile) {
+		# xml database is must here
+		print "Error: No xml database given\n";
+		&print_usage() if(!$helpCmd);
+		return 0;
+	}
+	
+	# if the suppress output option is not passed then generate both
+	$flagOut = (FLG_GENHDR|FLG_GENIBY|FLG_GENDAT|FLG_CONVFR) if(!$flagOut);
+	
+	return 1;
+}
+
+# --Utility Functions
+
+#
+# check whether the given file exists
+# @param - file name for the existance check
+#
+sub xmlfile
+{
+	my ($file) = shift;
+	
+	if(-e $file) {
+		push @xmlDBFile, $file;
+		return 1;
+	}
+	return 0;
+}
+
+#
+# Process the given absolute path
+# Add backslash at the end if required
+# @param - path to be processed
+#
+sub processPath
+{
+	my ($path) = shift;
+	
+	return if( $$path =~ /(\\$)/ );
+	return if( $$path =~ /(\/$)/ );
+	$$path .= "/";
+}
+
+#
+# Print the title
+#
+sub printTitle
+{
+	print "FEATURES - Features manager tool V".TOOL_VERSION."\n";
+	print "Copyright (c) 2009 Nokia Corporation.\n\n"
+}
+
+#
+# print the usage of this tool
+#
+sub print_usage
+{
+#........1.........2.........3.........4.........5.........6.........7.....
+	&printTitle();
+	print <<USAGE_EOF;
+Usage:
+  features [options] <xml database> [<xml database> <xml database> ...]
+
+Generation of C++ header file and IBY file for the given featuremanger 
+database file. It also generates features DAT file for the given 
+featuemanager/featureregistry database file
+
+Options:
+   -r or --hdrfile[=<destination path>] - generates only header file
+   -i or --ibyfile[=<destination path>] - generates only IBY file
+   -d or --datfile[=<destination path>] - generates only features.DAT file
+   -c or --convert[=<destination path>] - converts feature registry database
+   
+   -s or --strict        - enable strict mode
+   -v or --verbose       - enable verbose mode
+   -h or --help          - displays this help
+   
+   --version             - displays the tools version
+
+Ex: option combination \"-ri\" generates header and IBY files
+   
+Default destination paths:
+   <header file>         - ${epocroot}epoc32\/include\/
+   <iby file>            - ${epocroot}epoc32\/rom\/include\/
+   <features.dat file>   - generates in current directory
+   
+Note: The conversion(--convert) of feature registry database requires the 
+feature registry dtd file(featureuids.dtd) in ${epocroot}epoc32\/tools\/
+USAGE_EOF
+}
--- a/imgtools/buildrom/tools/features.pm	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/features.pm	Tue Jun 29 14:52:54 2010 +0800
@@ -1,538 +1,538 @@
-#
-# Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-#
-
-# This package contains routines to create the feature header and iby files.
-package features;
-
-require Exporter;
-@ISA=qw(Exporter);
-@EXPORT=qw(
-	open_Database
-	generate_Headerfile
-	generate_Obeyfile
-	generate_DATfile
-	set_DefaultPath
-	set_VerboseMode
-	set_StrictMode
-);
-
-use strict;
-
-# Include the featureutil module to use API to read from XML file.
-use featuresutil;
-
-# Object of featureparser
-my $xmlDBHandle = undef;
-
-# Mask value for supported feature flag
-use constant BIT_SUPPORTED=>0x00000001;
-
-# Feature dat file name
-use constant DAT_FILE=>"features.dat";
-
-# Feature manager support flag
-use constant FM_FLG=>0x01;
-
-# Feature registry support flag
-use constant FR_FLG=>0x02;
-
-# single dat file generation
-use constant SINGLE_DATFILE=>1;
-
-# none value
-use constant NONE=>-1;
-
-# verbose mode flag
-my $verboseMode = 0;
-
-# strict mode flag
-my $strictMode = 0;
-
-#
-# Open and parse the given xml database
-# @param - xml file name
-#
-sub open_Database
-{
-	my ($xmlDBFile) = join(',',@_);
-	
-	$xmlDBHandle = &featuresutil::parseXMLDatabase($xmlDBFile,FM_FLG,$strictMode,$verboseMode);
-	
-	return 0 if(!$xmlDBHandle);
-	return 1;
-}
-
-#
-# set the default path settings for header and iby files
-#
-sub set_DefaultPath
-{
-	my ($epocroot, $hdrpath, $ibypath, $datpath, $convpath) = @_;
-	
-	$$hdrpath = $epocroot."epoc32/include/";
-	$$ibypath = $epocroot."epoc32/rom/include/";
-	$$datpath = "./"; # current folder
-	$$convpath = "./"; # current folder
-}
-
-#
-# Generate the header file for each featureset
-# @param - destination path for the header file(s)
-#
-sub generate_Headerfile
-{
-	my $featureList=(); 
-	my $featureSetList = ();
-	my $hdrpath = shift;
-	my $aliasfeatureList = ();
-	
-	# Get the list of featuresets exists in the xml database
-	$featureSetList = $xmlDBHandle->getFeatureset();
-	foreach my $featureSet (@$featureSetList) {
-		my @defPresent=();
-		my @defNotPresent=();
-		my @defPresentAlias = ();
-		my @defNotPresentAlias = ();
-		my $tab = "\t";
-		
-		# if the headerfile name is not there then just return
-		if(!defined $featureSet->{hfilename}) {
-			MSG("No header file generated for the featureset $featureSet->{namespace}");
-			next;
-		}
-		
-		# Get the filename
-		my $hfile = $featureSet->{hfilename};
-		
-		# Create directory if it doesn't exists
-		return if(!createDirectory($hdrpath));
-		
-		my $hfileHandle = openFile($hdrpath.$hfile);
-		if(!$hfileHandle) {
-			print "ERROR: Cannot open file $hdrpath$hfile\n";
-			next;
-		}
-		
-		MSG("Creating headerfile $hdrpath$hfile");
-		
-		# Get the name->uid map for the features given in the selected featureset
-		$featureList = $featureSet->{feature_list};
-		# Create two sets of feature name list for the default present and notpresent
-		foreach my $name (keys %$featureList)
-		{
-			if(defaultPresent($featureList->{$name})){
-				push @defPresent, $name;
-			}
-			else {
-				push @defNotPresent, $name;
-			}
-		}
-		#for alias
-		$aliasfeatureList = $featureSet->{alias_feature_list};
-		foreach my $alias_name (keys %$aliasfeatureList)
-		{
-			if(defaultPresent($aliasfeatureList->{$alias_name}))
-			{
-				push @defPresentAlias, $alias_name;
-			}
-			else
-			{
-				push @defNotPresent, $alias_name;
-			}
-		}
-
-		# sort them
-		@defPresent = sort(@defPresent);
-		@defNotPresent = sort(@defNotPresent);
-		
-		# insert the file header attribute value
-		my $comment = $featureSet->{hfileheader};
-		if($comment) {
-			trimString(\$comment);
-			
-			# insert the interfacevisibility and interfacestatus attribute values
-			writeFile($hfileHandle, $comment."\n/**\n".$featureSet->{interfacevisibility}."\n".
-						 $featureSet->{interfacestatus}."\n*/\n");
-		}
-					 
-		if(defined $featureSet->{namespace}) {
-			writeFile($hfileHandle, "namespace ".$featureSet->{namespace}." {\n");
-		}
-		else {
-			$tab = "";
-		}
-		
-		# for each feature list insert an entry in the current namespace
-		writeFile($hfileHandle,$tab."// default present\n") if(@defPresent);
-		foreach my $name (@defPresent) {
-			$comment = $featureSet->{feature}{$featureList->{$name}}{comment};
-			if(defined $comment) {
-				trimString(\$comment);
-				$comment =~ s/\n/\n$tab/mg;
-				chop($comment) if($tab eq "\t");
-				writeFile($hfileHandle, $tab.$comment);
-			}
-			
-			writeFile($hfileHandle,$tab."const TUid K", $featureSet->{feature}{$featureList->{$name}}{name},
-						 sprintf(" = {0x%X};\n", $featureList->{$name}));
-			writeFile($hfileHandle,"\n") if(defined $comment);
-		}
-
-		foreach my $alias_name (@defPresentAlias)
-		{
-			$comment = $featureSet->{alias_feature}{$aliasfeatureList->{$alias_name}}{comment};
-			if(defined $comment)
-			{
-				trimString(\$comment);
-				$comment =~ s/\n/\n$tab/mg;
-				chop($comment) if ($tab eq "\t");
-				writeFile($hfileHandle, $tab.$comment);
-			}
-			writeFile($hfileHandle, $tab."const TUid K", $featureSet->{alias_feature}{$aliasfeatureList->{$alias_name}}{name}, sprintf(" = {0x%X};\n", $aliasfeatureList->{$alias_name}));
-			writeFile($hfileHandle, "\n") if(defined $comment);
-		}
-
-		writeFile($hfileHandle, "\n".$tab."// default not present\n") if(@defNotPresent);
-		foreach my $name (@defNotPresent) {
-			$comment = $featureSet->{feature}{$featureList->{$name}}{comment};
-			if(defined $comment) {
-				trimString(\$comment);
-				$comment =~ s/\n/\n$tab/mg;
-				chop($comment) if($tab eq "\t");
-				writeFile($hfileHandle,$tab.$comment);
-			}
-			
-			writeFile($hfileHandle,$tab."const TUid K", $featureSet->{feature}{$featureList->{$name}}{name},
-						 sprintf(" = {0x%X};\n", $featureList->{$name}));
-			writeFile($hfileHandle,"\n") if(defined $comment);
-		}
-		foreach my $alias_name (@defNotPresentAlias)
-		{
-			$comment = $featureSet->{alias_feature}{$aliasfeatureList->{$alias_name}}{comment};
-			if(defined $comment)
-			{
-				trimString(\$comment);
-				$comment =~ s/\n/\n$tab/mg;
-				chop($comment) if ($tab eq "\t");
-				writeFile($hfileHandle, $tab.$comment);
-			}
-			writeFile($hfileHandle, $tab."const TUid K", $featureSet->{alias_feature}{$aliasfeatureList->{$alias_name}}{name}, sprintf(" = {0x%X};\n", $aliasfeatureList->{$alias_name}));
-			writeFile($hfileHandle, "\n") if(defined $comment);
-		}
-		
-		if(defined $featureSet->{namespace}) {
-			writeFile($hfileHandle,"}\n");
-		}
-		
-		closeFile($hfileHandle);
-	}
-}
-
-#
-# Generate the obey file for each featureset
-# @param - destination path for the iby file(s)
-#
-sub generate_Obeyfile
-{
-	my $featureSet=(); my $feature=(); my $featureList=(); my $featureSetList=();
-	my $aliasfeatureList = ();
-	my $ibypath = shift;
-	
-	# Get the list of featuresets exists in the xml database
-	$featureSetList = $xmlDBHandle->getFeatureset();
-	foreach my $featureSet (@$featureSetList) {
-		# if the obey file name is not there then just return
-		if(!defined $featureSet->{ibyname}) {
-			MSG("No IBY file generated for the featureset $featureSet->{namespace}");
-			next;
-		}
-		
-		# Get the file name
-		my $ibyfile = $featureSet->{ibyname};
-		
-		# Create the directory if it doesn't exists
-		return if(!createDirectory($ibypath));
-		
-		my $ibyfilehandle = openFile($ibypath.$ibyfile);
-		if(!$ibyfilehandle) {
-			print "*ERROR: Cannot open file $ibypath$ibyfile\n";
-			next;
-		}
-		
-		MSG("Creating IBY file $ibypath$ibyfile");
-		
-		$ibyfile =~ s/\./\_/g;
-		$ibyfile = uc($ibyfile);
-		
-		# insert the file header
-		writeFile($ibyfilehandle, "#ifndef\t__",$ibyfile,"__\n#define\t__",$ibyfile,"__\n\n");
-
-		# get the name->uid map of features for the given featureset
-		$featureList = $featureSet->{feature_list};
-		$aliasfeatureList = $featureSet->{alias_feature_list};
-		my %combine_list = (%$featureList, %$aliasfeatureList);
-		foreach my $name (sort keys %combine_list)
-		{
-			my $defblock=(); my $flags=(); my $comment=();
-			
-			my $uid = $xmlDBHandle->getFeatureUID($name,$featureSet->{namespace});
-			
-			# get the featureset attributes
-			$feature = $xmlDBHandle->getFeatureInfo($uid,$featureSet->{namespace});
-			
-			# check to see this feature to be included in iby file
-			next if(!$feature->{infeaturesetiby});
-			# get the feature flags
-			$flags = "SF ".$feature->{statusflags} if(defined $feature->{statusflags});
-			if(defined $feature->{userdata}) {
-				$flags .= " "."UD ".$feature->{userdata};
-			}
-			else {
-				$flags .= " "."UD 0x00000000";
-			}
-
-			# get the comment value
-			if(defined $feature->{comment}) {
-				$comment = $feature->{comment};
-				trimString(\$comment);
-			}
-			
-			if(defined $feature->{includemacro}) { # if the include macro is specified
-				$defblock = "\n#ifdef ".$feature->{includemacro}."\n";
-				$defblock .= $comment;
-				$defblock .= "FEATURE ".$feature->{name}." ".$flags."\n";
-				$defblock .= "#else\nEXCLUDE_FEATURE ".$feature->{name}." ".$flags."\n#endif\n"
-			}
-			elsif(defined $feature->{excludemacro}) { # if the exclude macro is specified
-				$defblock = "\n#ifdef ".$feature->{excludemacro}."\n";
-				$defblock .= "EXCLUDE_FEATURE ".$feature->{name}." ".$flags."\n#else\n";
-				$defblock .= $comment;
-				$defblock .= "FEATURE ".$feature->{name}." ".$flags."\n#endif\n"
-			}
-			else {  # default case
-				# No system wide macro defined for this feature
-				next;
-			}
-			
-			# insert #ifdef block
-			writeFile($ibyfilehandle, $defblock);
-		}
-		
-		writeFile($ibyfilehandle, "\n\n#endif //__",$ibyfile,"__");
-		closeFile($ibyfilehandle);
-	}
-}
-
-#
-# Generate the feature DAT file
-# @param - destination path for the features.DAT file
-#
-sub generate_DATfile
-{
-	my $featureSet=(); my $feature=(); my $featureList=(); my $featureSetList=();
-	my @featList=();
-	my $aliasfeatureList = ();
-	my $aliasfeatlist = ();
-	my %uidtoaliasname = ();
-	my $datpath = shift;
-	
-	# Get the list of featuresets exists in the xml database
-	$featureSetList = $xmlDBHandle->getFeatureset();
-	$aliasfeatlist = $xmlDBHandle->getAliasFeatureList();
-	foreach my $aliasname (keys %$aliasfeatlist)
-	{
-		$uidtoaliasname{$aliasfeatlist->{$aliasname}} = $aliasname;
-	}
-	foreach my $featureSet (@$featureSetList) {
-		# get the name->uid map of features for the given featureset
-		$featureList = $featureSet->{feature_list};
-		foreach my $name (keys %$featureList)
-		{
-			if (exists $uidtoaliasname{$featureList->{$name}})
-			{
-				next;
-			}
-			my $statusflag = 0;
-			my %featinfo = ();
-			
-			$featinfo{feature} = $name;
-			$featinfo{SF} = $xmlDBHandle->getStatusFlag($name, $featureSet->{namespace});
-			$featinfo{UD} = $xmlDBHandle->getUserData($name, $featureSet->{namespace});
-			$statusflag = &featureparser::ConvertHexToDecimal($featinfo{SF});
-			if($statusflag & BIT_SUPPORTED) {
-				$featinfo{include} = 1;
-			}
-			else {
-				$featinfo{include} = 0;
-			}
-			
-			push @featList, {%featinfo};
-		}
-		$aliasfeatureList = $featureSet->{alias_feature_list};
-		foreach my $alias_name (keys %$aliasfeatureList)
-		{
-			my $statusflag = 0;
-			my %featinfo = ();
-			
-			$featinfo{feature} = $alias_name;
-			$featinfo{SF} = $xmlDBHandle->getStatusFlag($alias_name, $featureSet->{namespace});
-			$featinfo{UD} = $xmlDBHandle->getUserData($alias_name, $featureSet->{namespace});
-			$statusflag = &featureparser::ConvertHexToDecimal($featinfo{SF});
-			if($statusflag & BIT_SUPPORTED) {
-				$featinfo{include} = 1;
-			}
-			else {
-				$featinfo{include} = 0;
-			}
-			push @featList, {%featinfo};
-		}
-
-
-	}
-	
-	if(@featList) {
-		# Create the directory if doesn't exists
-		return if(!createDirectory($datpath));
-		
-		# Create features.dat file
-		&featuresutil::createFeatureFile(NONE,NONE,$datpath.DAT_FILE,\@featList,FM_FLG,SINGLE_DATFILE);
-	}
-}
-
-#
-# Converts the feature registry object to feature manager xml
-# @param - destination path for the output file
-# @param - input file list as an array
-#
-sub convert_FeatRegToFeatMgr
-{
-	&featuresutil::convert_FeatRegToFeatMgr($strictMode,$verboseMode,@_);
-}
-
-#
-# Enable verbose mode
-# 
-sub set_VerboseMode
-{
-	$verboseMode = 1;
-}
-
-#
-# Enable strict mode
-# 
-sub set_StrictMode
-{
-	$strictMode = 1;
-}
-
-# --Utility Functions
-
-#
-# Check whether the given feature uid is present in default include list
-# @param - feature uid value
-#
-sub defaultPresent
-{
-	my ($uid) = shift;
-	
-	my $defaultRanges = $xmlDBHandle->defaultRangeList();
-	
-	foreach my $range (@$defaultRanges)
-	{
-		if ( (lc($range->{"support"}) eq "include") and ($range->{"min"} <= $uid) and ($range->{"max"} >= $uid) ) {
-			return 1;
-		}
-	}
-	return 0;
-}
-
-#
-# Trim the given string for trailing whitespaces
-# @param - string to be trimmed
-#
-sub trimString
-{
-	my $str = shift;
-	
-	$$str =~ s/^[ \t]+//mg;
-	$$str =~ s/^\n//mg;
-	
-	$$str .= "\n" if($$str !~ /\n$/m);
-}
-
-#
-# Verbose mode output routine
-# @param - Message to be displayed
-#
-sub MSG 
-{
-	print "**".$_[0]."...\n" if($verboseMode);
-}
-
-#
-# Open a text file in write mode
-# @param - name of the file to open
-#
-sub openFile
-{
-	my $file = shift;
-	
-	open(FILEP,">$file") or (return 0);
-	
-	return *FILEP;
-}
-
-#
-# Writes string to the file stream
-# @param filehandle - reference to the file handle
-# @param data - array of string to be written
-#
-sub writeFile
-{
-	my ($filehandle, @data) = @_;
-	
-	printf $filehandle "%s",$_ foreach (@data);
-}
-
-#
-# Closes the file stream
-# @param filehanlde - referece to the file handle
-#
-sub closeFile
-{
-	my $filehandle = shift;
-	
-	close $filehandle;
-}
-
-#
-# Check the existance of the directory and create one if it doesn't exist
-# @param dir - directory name
-#
-sub createDirectory
-{
-	my $dir = shift;
-	
-	if(!(-e $dir)) {
-		if(!mkdir($dir)) {
-			print "ERROR: Failed to create $dir folder\n";
-			return 0;
-		}
-	}
-	return 1;
-}
-
-1;
+#
+# Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+#
+
+# This package contains routines to create the feature header and iby files.
+package features;
+
+require Exporter;
+@ISA=qw(Exporter);
+@EXPORT=qw(
+	open_Database
+	generate_Headerfile
+	generate_Obeyfile
+	generate_DATfile
+	set_DefaultPath
+	set_VerboseMode
+	set_StrictMode
+);
+
+use strict;
+
+# Include the featureutil module to use API to read from XML file.
+use featuresutil;
+
+# Object of featureparser
+my $xmlDBHandle = undef;
+
+# Mask value for supported feature flag
+use constant BIT_SUPPORTED=>0x00000001;
+
+# Feature dat file name
+use constant DAT_FILE=>"features.dat";
+
+# Feature manager support flag
+use constant FM_FLG=>0x01;
+
+# Feature registry support flag
+use constant FR_FLG=>0x02;
+
+# single dat file generation
+use constant SINGLE_DATFILE=>1;
+
+# none value
+use constant NONE=>-1;
+
+# verbose mode flag
+my $verboseMode = 0;
+
+# strict mode flag
+my $strictMode = 0;
+
+#
+# Open and parse the given xml database
+# @param - xml file name
+#
+sub open_Database
+{
+	my ($xmlDBFile) = join(',',@_);
+	
+	$xmlDBHandle = &featuresutil::parseXMLDatabase($xmlDBFile,FM_FLG,$strictMode,$verboseMode);
+	
+	return 0 if(!$xmlDBHandle);
+	return 1;
+}
+
+#
+# set the default path settings for header and iby files
+#
+sub set_DefaultPath
+{
+	my ($epocroot, $hdrpath, $ibypath, $datpath, $convpath) = @_;
+	
+	$$hdrpath = $epocroot."epoc32/include/";
+	$$ibypath = $epocroot."epoc32/rom/include/";
+	$$datpath = "./"; # current folder
+	$$convpath = "./"; # current folder
+}
+
+#
+# Generate the header file for each featureset
+# @param - destination path for the header file(s)
+#
+sub generate_Headerfile
+{
+	my $featureList=(); 
+	my $featureSetList = ();
+	my $hdrpath = shift;
+	my $aliasfeatureList = ();
+	
+	# Get the list of featuresets exists in the xml database
+	$featureSetList = $xmlDBHandle->getFeatureset();
+	foreach my $featureSet (@$featureSetList) {
+		my @defPresent=();
+		my @defNotPresent=();
+		my @defPresentAlias = ();
+		my @defNotPresentAlias = ();
+		my $tab = "\t";
+		
+		# if the headerfile name is not there then just return
+		if(!defined $featureSet->{hfilename}) {
+			MSG("No header file generated for the featureset $featureSet->{namespace}");
+			next;
+		}
+		
+		# Get the filename
+		my $hfile = $featureSet->{hfilename};
+		
+		# Create directory if it doesn't exists
+		return if(!createDirectory($hdrpath));
+		
+		my $hfileHandle = openFile($hdrpath.$hfile);
+		if(!$hfileHandle) {
+			print "ERROR: Cannot open file $hdrpath$hfile\n";
+			next;
+		}
+		
+		MSG("Creating headerfile $hdrpath$hfile");
+		
+		# Get the name->uid map for the features given in the selected featureset
+		$featureList = $featureSet->{feature_list};
+		# Create two sets of feature name list for the default present and notpresent
+		foreach my $name (keys %$featureList)
+		{
+			if(defaultPresent($featureList->{$name})){
+				push @defPresent, $name;
+			}
+			else {
+				push @defNotPresent, $name;
+			}
+		}
+		#for alias
+		$aliasfeatureList = $featureSet->{alias_feature_list};
+		foreach my $alias_name (keys %$aliasfeatureList)
+		{
+			if(defaultPresent($aliasfeatureList->{$alias_name}))
+			{
+				push @defPresentAlias, $alias_name;
+			}
+			else
+			{
+				push @defNotPresent, $alias_name;
+			}
+		}
+
+		# sort them
+		@defPresent = sort(@defPresent);
+		@defNotPresent = sort(@defNotPresent);
+		
+		# insert the file header attribute value
+		my $comment = $featureSet->{hfileheader};
+		if($comment) {
+			trimString(\$comment);
+			
+			# insert the interfacevisibility and interfacestatus attribute values
+			writeFile($hfileHandle, $comment."\n/**\n".$featureSet->{interfacevisibility}."\n".
+						 $featureSet->{interfacestatus}."\n*/\n");
+		}
+					 
+		if(defined $featureSet->{namespace}) {
+			writeFile($hfileHandle, "namespace ".$featureSet->{namespace}." {\n");
+		}
+		else {
+			$tab = "";
+		}
+		
+		# for each feature list insert an entry in the current namespace
+		writeFile($hfileHandle,$tab."// default present\n") if(@defPresent);
+		foreach my $name (@defPresent) {
+			$comment = $featureSet->{feature}{$featureList->{$name}}{comment};
+			if(defined $comment) {
+				trimString(\$comment);
+				$comment =~ s/\n/\n$tab/mg;
+				chop($comment) if($tab eq "\t");
+				writeFile($hfileHandle, $tab.$comment);
+			}
+			
+			writeFile($hfileHandle,$tab."const TUid K", $featureSet->{feature}{$featureList->{$name}}{name},
+						 sprintf(" = {0x%X};\n", $featureList->{$name}));
+			writeFile($hfileHandle,"\n") if(defined $comment);
+		}
+
+		foreach my $alias_name (@defPresentAlias)
+		{
+			$comment = $featureSet->{alias_feature}{$aliasfeatureList->{$alias_name}}{comment};
+			if(defined $comment)
+			{
+				trimString(\$comment);
+				$comment =~ s/\n/\n$tab/mg;
+				chop($comment) if ($tab eq "\t");
+				writeFile($hfileHandle, $tab.$comment);
+			}
+			writeFile($hfileHandle, $tab."const TUid K", $featureSet->{alias_feature}{$aliasfeatureList->{$alias_name}}{name}, sprintf(" = {0x%X};\n", $aliasfeatureList->{$alias_name}));
+			writeFile($hfileHandle, "\n") if(defined $comment);
+		}
+
+		writeFile($hfileHandle, "\n".$tab."// default not present\n") if(@defNotPresent);
+		foreach my $name (@defNotPresent) {
+			$comment = $featureSet->{feature}{$featureList->{$name}}{comment};
+			if(defined $comment) {
+				trimString(\$comment);
+				$comment =~ s/\n/\n$tab/mg;
+				chop($comment) if($tab eq "\t");
+				writeFile($hfileHandle,$tab.$comment);
+			}
+			
+			writeFile($hfileHandle,$tab."const TUid K", $featureSet->{feature}{$featureList->{$name}}{name},
+						 sprintf(" = {0x%X};\n", $featureList->{$name}));
+			writeFile($hfileHandle,"\n") if(defined $comment);
+		}
+		foreach my $alias_name (@defNotPresentAlias)
+		{
+			$comment = $featureSet->{alias_feature}{$aliasfeatureList->{$alias_name}}{comment};
+			if(defined $comment)
+			{
+				trimString(\$comment);
+				$comment =~ s/\n/\n$tab/mg;
+				chop($comment) if ($tab eq "\t");
+				writeFile($hfileHandle, $tab.$comment);
+			}
+			writeFile($hfileHandle, $tab."const TUid K", $featureSet->{alias_feature}{$aliasfeatureList->{$alias_name}}{name}, sprintf(" = {0x%X};\n", $aliasfeatureList->{$alias_name}));
+			writeFile($hfileHandle, "\n") if(defined $comment);
+		}
+		
+		if(defined $featureSet->{namespace}) {
+			writeFile($hfileHandle,"}\n");
+		}
+		
+		closeFile($hfileHandle);
+	}
+}
+
+#
+# Generate the obey file for each featureset
+# @param - destination path for the iby file(s)
+#
+sub generate_Obeyfile
+{
+	my $featureSet=(); my $feature=(); my $featureList=(); my $featureSetList=();
+	my $aliasfeatureList = ();
+	my $ibypath = shift;
+	
+	# Get the list of featuresets exists in the xml database
+	$featureSetList = $xmlDBHandle->getFeatureset();
+	foreach my $featureSet (@$featureSetList) {
+		# if the obey file name is not there then just return
+		if(!defined $featureSet->{ibyname}) {
+			MSG("No IBY file generated for the featureset $featureSet->{namespace}");
+			next;
+		}
+		
+		# Get the file name
+		my $ibyfile = $featureSet->{ibyname};
+		
+		# Create the directory if it doesn't exists
+		return if(!createDirectory($ibypath));
+		
+		my $ibyfilehandle = openFile($ibypath.$ibyfile);
+		if(!$ibyfilehandle) {
+			print "*ERROR: Cannot open file $ibypath$ibyfile\n";
+			next;
+		}
+		
+		MSG("Creating IBY file $ibypath$ibyfile");
+		
+		$ibyfile =~ s/\./\_/g;
+		$ibyfile = uc($ibyfile);
+		
+		# insert the file header
+		writeFile($ibyfilehandle, "#ifndef\t__",$ibyfile,"__\n#define\t__",$ibyfile,"__\n\n");
+
+		# get the name->uid map of features for the given featureset
+		$featureList = $featureSet->{feature_list};
+		$aliasfeatureList = $featureSet->{alias_feature_list};
+		my %combine_list = (%$featureList, %$aliasfeatureList);
+		foreach my $name (sort keys %combine_list)
+		{
+			my $defblock=(); my $flags=(); my $comment=();
+			
+			my $uid = $xmlDBHandle->getFeatureUID($name,$featureSet->{namespace});
+			
+			# get the featureset attributes
+			$feature = $xmlDBHandle->getFeatureInfo($uid,$featureSet->{namespace});
+			
+			# check to see this feature to be included in iby file
+			next if(!$feature->{infeaturesetiby});
+			# get the feature flags
+			$flags = "SF ".$feature->{statusflags} if(defined $feature->{statusflags});
+			if(defined $feature->{userdata}) {
+				$flags .= " "."UD ".$feature->{userdata};
+			}
+			else {
+				$flags .= " "."UD 0x00000000";
+			}
+
+			# get the comment value
+			if(defined $feature->{comment}) {
+				$comment = $feature->{comment};
+				trimString(\$comment);
+			}
+			
+			if(defined $feature->{includemacro}) { # if the include macro is specified
+				$defblock = "\n#ifdef ".$feature->{includemacro}."\n";
+				$defblock .= $comment;
+				$defblock .= "FEATURE ".$feature->{name}." ".$flags."\n";
+				$defblock .= "#else\nEXCLUDE_FEATURE ".$feature->{name}." ".$flags."\n#endif\n"
+			}
+			elsif(defined $feature->{excludemacro}) { # if the exclude macro is specified
+				$defblock = "\n#ifdef ".$feature->{excludemacro}."\n";
+				$defblock .= "EXCLUDE_FEATURE ".$feature->{name}." ".$flags."\n#else\n";
+				$defblock .= $comment;
+				$defblock .= "FEATURE ".$feature->{name}." ".$flags."\n#endif\n"
+			}
+			else {  # default case
+				# No system wide macro defined for this feature
+				next;
+			}
+			
+			# insert #ifdef block
+			writeFile($ibyfilehandle, $defblock);
+		}
+		
+		writeFile($ibyfilehandle, "\n\n#endif //__",$ibyfile,"__\n");
+		closeFile($ibyfilehandle);
+	}
+}
+
+#
+# Generate the feature DAT file
+# @param - destination path for the features.DAT file
+#
+sub generate_DATfile
+{
+	my $featureSet=(); my $feature=(); my $featureList=(); my $featureSetList=();
+	my @featList=();
+	my $aliasfeatureList = ();
+	my $aliasfeatlist = ();
+	my %uidtoaliasname = ();
+	my $datpath = shift;
+	
+	# Get the list of featuresets exists in the xml database
+	$featureSetList = $xmlDBHandle->getFeatureset();
+	$aliasfeatlist = $xmlDBHandle->getAliasFeatureList();
+	foreach my $aliasname (keys %$aliasfeatlist)
+	{
+		$uidtoaliasname{$aliasfeatlist->{$aliasname}} = $aliasname;
+	}
+	foreach my $featureSet (@$featureSetList) {
+		# get the name->uid map of features for the given featureset
+		$featureList = $featureSet->{feature_list};
+		foreach my $name (keys %$featureList)
+		{
+			if (exists $uidtoaliasname{$featureList->{$name}})
+			{
+				next;
+			}
+			my $statusflag = 0;
+			my %featinfo = ();
+			
+			$featinfo{feature} = $name;
+			$featinfo{SF} = $xmlDBHandle->getStatusFlag($name, $featureSet->{namespace});
+			$featinfo{UD} = $xmlDBHandle->getUserData($name, $featureSet->{namespace});
+			$statusflag = &featureparser::ConvertHexToDecimal($featinfo{SF});
+			if($statusflag & BIT_SUPPORTED) {
+				$featinfo{include} = 1;
+			}
+			else {
+				$featinfo{include} = 0;
+			}
+			
+			push @featList, {%featinfo};
+		}
+		$aliasfeatureList = $featureSet->{alias_feature_list};
+		foreach my $alias_name (keys %$aliasfeatureList)
+		{
+			my $statusflag = 0;
+			my %featinfo = ();
+			
+			$featinfo{feature} = $alias_name;
+			$featinfo{SF} = $xmlDBHandle->getStatusFlag($alias_name, $featureSet->{namespace});
+			$featinfo{UD} = $xmlDBHandle->getUserData($alias_name, $featureSet->{namespace});
+			$statusflag = &featureparser::ConvertHexToDecimal($featinfo{SF});
+			if($statusflag & BIT_SUPPORTED) {
+				$featinfo{include} = 1;
+			}
+			else {
+				$featinfo{include} = 0;
+			}
+			push @featList, {%featinfo};
+		}
+
+
+	}
+	
+	if(@featList) {
+		# Create the directory if doesn't exists
+		return if(!createDirectory($datpath));
+		
+		# Create features.dat file
+		&featuresutil::createFeatureFile(NONE,NONE,$datpath.DAT_FILE,\@featList,FM_FLG,SINGLE_DATFILE);
+	}
+}
+
+#
+# Converts the feature registry object to feature manager xml
+# @param - destination path for the output file
+# @param - input file list as an array
+#
+sub convert_FeatRegToFeatMgr
+{
+	&featuresutil::convert_FeatRegToFeatMgr($strictMode,$verboseMode,@_);
+}
+
+#
+# Enable verbose mode
+# 
+sub set_VerboseMode
+{
+	$verboseMode = 1;
+}
+
+#
+# Enable strict mode
+# 
+sub set_StrictMode
+{
+	$strictMode = 1;
+}
+
+# --Utility Functions
+
+#
+# Check whether the given feature uid is present in default include list
+# @param - feature uid value
+#
+sub defaultPresent
+{
+	my ($uid) = shift;
+	
+	my $defaultRanges = $xmlDBHandle->defaultRangeList();
+	
+	foreach my $range (@$defaultRanges)
+	{
+		if ( (lc($range->{"support"}) eq "include") and ($range->{"min"} <= $uid) and ($range->{"max"} >= $uid) ) {
+			return 1;
+		}
+	}
+	return 0;
+}
+
+#
+# Trim the given string for trailing whitespaces
+# @param - string to be trimmed
+#
+sub trimString
+{
+	my $str = shift;
+	
+	$$str =~ s/^[ \t]+//mg;
+	$$str =~ s/^\n//mg;
+	
+	$$str .= "\n" if($$str !~ /\n$/m);
+}
+
+#
+# Verbose mode output routine
+# @param - Message to be displayed
+#
+sub MSG 
+{
+	print "**".$_[0]."...\n" if($verboseMode);
+}
+
+#
+# Open a text file in write mode
+# @param - name of the file to open
+#
+sub openFile
+{
+	my $file = shift;
+	
+	open(FILEP,">$file") or (return 0);
+	
+	return *FILEP;
+}
+
+#
+# Writes string to the file stream
+# @param filehandle - reference to the file handle
+# @param data - array of string to be written
+#
+sub writeFile
+{
+	my ($filehandle, @data) = @_;
+	
+	printf $filehandle "%s",$_ foreach (@data);
+}
+
+#
+# Closes the file stream
+# @param filehanlde - referece to the file handle
+#
+sub closeFile
+{
+	my $filehandle = shift;
+	
+	close $filehandle;
+}
+
+#
+# Check the existance of the directory and create one if it doesn't exist
+# @param dir - directory name
+#
+sub createDirectory
+{
+	my $dir = shift;
+	
+	if(!(-e $dir)) {
+		if(!mkdir($dir)) {
+			print "ERROR: Failed to create $dir folder\n";
+			return 0;
+		}
+	}
+	return 1;
+}
+
+1;
--- a/imgtools/buildrom/tools/featuresutil.pm	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/featuresutil.pm	Tue Jun 29 14:52:54 2010 +0800
@@ -1,534 +1,534 @@
-#
-# Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-#
-
-package featuresutil;
-        
-
-require Exporter;
-@ISA = qw(Exporter);
-@EXPORT = qw(
-	parseXMLDatabase
-	createFeatureFile
-	convert_FeatRegToFeatMgr
-);
-
-use strict;
-use XML::Handler::XMLWriter;
-use IO;
-
-use featureparser;
-use featuremanager;
-use featureregistry;
-use featuresdat;
-use featurecfg;
-
-my $xmlDBHandle = undef; #Object of feature parser
-
-my @includeFeatureList;	#List of included features. The included feature in this list is a hash table giving the 
-			#Uid or the name. These features are collected from the iby/obey files.
-my @excludeFeatureList;	#List of excluded features.The excluded feature in this list is a hash table giving the 
-			#Uid or the name. These features are collected from the iby/obey files.
-
-my $verboseFlg = 0; # verbose mode flag
-my $strictFlg = 1; # strict mode flag
-
-# Subroutine to generate warning messages.
-sub WARN 
-{
-	print "WARNING: ".$_[0]."\n"; 
-}
-
-# Subroutine to generate error messages.
-sub ERROR 
-{ 
-	print "ERROR: ".$_[0]."\n"; 
-}
-
-# Verbose mode output routine
-sub MSG 
-{
-	if($verboseFlg) {
-		print "**".$_[0]."...\n";
-	}
-}
-
-# Subroutine to parse feature list XML database file.
-# @param dbfileList					- List of XML database file names seperated by commas.
-# @param fmFlag						- Flag to generate features data file.
-# @param strictFlg					- Flag to enable strict mode (optional).
-# @param verboseFlg                 - Flag to enable verbose mode (optional).
-sub parseXMLDatabase
-{
-	my $dbfileList = shift;
-	my $fmFlag = shift;
-	$strictFlg = shift;
-	$verboseFlg = shift;
-	
-	# list of xml databases
-	my @filelist = split(/,/,$dbfileList);
-	
-	# return status
-	my $retStatus = 0;
-	
-	# default mode is strict
-	$strictFlg=0 if(!defined $strictFlg);
-	# default mode is nonverbose
-	$verboseFlg=0 if(!defined $verboseFlg);
-	
-	# multiple file support is not applicable for feature registry option
-	if( (@filelist > 1) && (!$fmFlag) ) {
-		&ERROR("Multiple XML database file support is not applicable for featureregistry option");
-		return 0;
-	}
-	
-	if($fmFlag) # Feature manager option handling
-	{
-		# create the object of feature manager class
-		$xmlDBHandle = new featuremanager;
-		
-		if($xmlDBHandle) {
-			foreach my $file (@filelist) 
-			{
-				my $status = 1;
-				if(-e $file) {
-					
-					&MSG("Parsing $file");
-					
-					# parse the feature manager xml file
-					$status = $xmlDBHandle->parseXMLFile($file);
-					if(! $status) {
-					
-						# create the object of feature registry class
-						my $registryObj = new featureregistry;
-						# parse the feature registry xml file
-						$status = $registryObj->parseXMLFile($file);
-						if($status < 0) {
-							if($strictFlg) {
-								&ERROR("Invalid features database $file");
-								$xmlDBHandle = undef;
-								return 0;
-							}
-							else {
-								&WARN("Invalid features database $file");
-							}
-						}
-						elsif(! $status) {
-							# if the xml file is not valid feature list xml file
-							if($strictFlg) {
-								&ERROR("Error in reading features database file \"$file\"");
-								$xmlDBHandle = undef;
-								return 0;
-							}
-							else {
-								&WARN("Error in reading features database file \"$file\"");
-							}
-						}
-						else {
-							MSG("Converting featureregistry database to featuremanager");
-							
-							# add the feature registry file object to the feature manager file object
-							if(! $xmlDBHandle->addFeatureRegistry($registryObj)) {
-								if($strictFlg) {
-									MSG("Error in reading features database file \"$file\"");
-									$xmlDBHandle = undef;
-									return 0;
-								}
-								else {
-									&WARN("Error in reading features database file \"$file\"");
-								}
-							}
-							else {
-								# parsing feature registry database success
-								$retStatus = 1;
-							}
-						}
-					}
-					elsif( $status < 0 ) {
-						if($strictFlg) {
-							&ERROR("Invalid features database $file");
-							$xmlDBHandle = undef;
-							return 0;
-						}
-						else {
-							&WARN("Invalid features database $file");
-						}
-					}
-					else {
-						# parsing feature manager database success
-						$retStatus = 1;
-					}
-				}
-				else {
-					if(!$strictFlg) {
-						&WARN($file." doesn\'t exist");
-						next;
-					}
-					else {
-						&ERROR($file." doesn\'t exist");
-						$xmlDBHandle = undef;
-						return 0;
-					}
-				}
-			}
-		}
-		else {
-			&ERROR("Couldn't create feature parser object");
-		}
-	}
-	else # Feature registry file handling
-	{
-		if(@filelist) {
-			my $file = $filelist[0];
-			$xmlDBHandle = new featureregistry;
-			
-			if($xmlDBHandle) {
-				if(-e $file) {
-				
-					MSG("Parsing $file");
-					
-					my $status = $xmlDBHandle->parseXMLFile($file);
-
-					if($status < 0) {
-						&ERROR($file." is invalid feature registry file");
-						$xmlDBHandle = undef;
-						return 0;
-					}
-					elsif(!$status) {
-						&ERROR("Error in reading feature registry file ".$file);
-						$xmlDBHandle = undef;
-					}
-					else {
-						# parsing feature registry database success
-						$retStatus = 1;
-					}
-				}
-				else {
-					if(!$strictFlg) {
-						&WARN($file." doesn\'t exist -- ");
-					}
-					else {
-						&ERROR($file." doesn\'t exist -- ");
-					}				
-					$xmlDBHandle = undef;
-				}
-			}
-			else {
-				&ERROR("Couldn't create feature parser object");
-			}
-		}
-	}
-	
-	if($retStatus) {
-		return $xmlDBHandle
-	}
-	else {
-		return $retStatus;
-	}
-}
-
-# Subroutine to generate feature manager database file from the given feature registry database
-# @param strictFlg - strict mode flag
-# @param verboseFlg - verbose mode flag
-# @param outpath - destination path for the converted database file(s)
-# @param dblist - list of xml file names
-sub convert_FeatRegToFeatMgr
-{
-	$strictFlg = shift;
-	$verboseFlg = shift;
-	my $outpath = shift;
-	my @dblist = @_;
-	
-	# default mode is strict
-	$strictFlg=0 if(!defined $strictFlg);
-	# default mode is nonverbose
-	$verboseFlg=0 if(!defined $verboseFlg);
-
-	foreach my $file (@dblist)
-	{
-		# Create the object of feature registry
-		my $fileHandle = new featureregistry;
-		
-		if(-e $file) {
-			# Parse the database
-			if($fileHandle->parseXMLFile($file) > 0) {
-				MSG("Converting Feature Registry database $file");
-				
-				# Create directory if it doesn't exists
-				if(!(-e $outpath)) {
-					if(!mkdir($outpath)) {
-						&ERROR("Failed to create $outpath folder");
-						return 0;
-					}
-				}
-				# Emit the contents of feature registry object into an feature manager database file
-				&generateXML($fileHandle, $outpath);
-			}
-		}
-		else {
-			if(!$strictFlg) {
-				&WARN($file." doesn\'t exist -- ");
-				next;
-			}
-			else {
-				&ERROR($file." doesn\'t exist -- ");
-				return 0;
-			}
-		}
-	}
-}
-
-# Subroutine to emit XML output for the given featureregistry object
-# @param frObject - object of feature registry database
-# @param outPath - destination path for the converted database file
-sub generateXML
-{
-	my ($frObject, $outPath) = @_;
-		
-	my $outputFile = $frObject->fileName();
-	
-	# Extract absolute file name
-	if( $outputFile =~ /[\\\/]/) {
-		$outputFile =~ /.*[\\\/](.+)\z/;
-		$outputFile = $1;
-	}
-	
-	# Add suffix _converted
-	$outputFile =~ s/(.*)([\.].+)\z/$1_converted$2/;
-	
-	my $fileHandle = new IO::File(">$outPath$outputFile");
-	
-	if($fileHandle) {
-		my $writer = XML::Handler::XMLWriter->new(Output => $fileHandle);
-		
-		# Header
-		$writer->start_document();
-		$writer->print("<!--Converted from the feature registry ".$frObject->fileName()."-->\n\n");
-		# DOCTYPE
-		$writer->print("<!DOCTYPE featuredatabase SYSTEM \"featuredatabase.dtd\">\n\n");
-		
-		# Root element begin
-		$writer->start_element({Name => 'featuredatabase', Attributes => {}});
-		
-		# FeatureSet element
-		$writer->print("\n\t");
-		$writer->start_element({Name => 'featureset', Attributes => {}});
-		my $nameuidmap = $frObject->featureNameUidMap();
-		foreach my $uid (sort(values %$nameuidmap)) {
-			my $featinfo = $frObject->getFeatureInfo($uid);
-			my %attributes = ();
-			
-			$attributes{uid} = sprintf("0x%08X",$uid);
-			$attributes{statusflags} = "0x00000001";
-			$attributes{name} = $featinfo->{name};
-			
-			$writer->print("\n\t\t");
-			$writer->start_element({Name => 'feature', Attributes => \%attributes});
-			$writer->end_element({Name => 'feature'});
-		}
-		$writer->print("\n\t");
-		$writer->end_element({Name => 'featureset'});
-		
-		# defaultfeaturerange element
-		my $rangeList = $frObject->defaultRangeList();
-		foreach my $range (@$rangeList) {
-			my %attributes = ();
-			
-			next if(lc($range->{support}) eq "exclude");
-			
-			$attributes{higheruid} = sprintf("0x%08X",$range->{max});
-			$attributes{loweruid} = sprintf("0x%08X",$range->{min});
-			
-			$writer->print("\n\t");
-			$writer->start_element({Name => 'defaultfeaturerange', Attributes => \%attributes});
-			$writer->end_element({Name => 'defaultfeaturerange'});
-		}
-		
-		# Root element close
-		$writer->print("\n");
-		$writer->end_element({Name => 'featuredatabase'});
-		
-		# Footer
-		$writer->end_document();
-	}
-	else {
-		&ERROR("Failed to create $outPath$outputFile file");
-	}
-}
-
-# Subroutine to create Feature Registry/Features Data file
-# @param romimage				 - Rom image number.
-# @param featurefile			 - Feature file number.
-# @param featurefilename		 - Name of the feature file to be generated.
-# @param featureslist			 - Reference to array of hashes containing features to included/excluded.
-# @param featuremanager			 - Flag to generate features data file.
-# @param singleDATfile           - Flag to generate single features.dat file.
-sub createFeatureFile
-{
-	if($xmlDBHandle == undef) 
-	{
-		ERROR("No XML Database opened");
-		return 0;
-	}	
-	my ($romimage,$featurefile,$featurefilename,$featureslist,$featuremanager,$singleDATfile) = @_;
-	
-	# Default setting for singleDATfile flag
-	$singleDATfile = 0 if(!defined $singleDATfile);
-	
-	# Clear the global include/exclude feature list.
-	@includeFeatureList = (); 
-	@excludeFeatureList = ();
-
-
-	for(my $k=0;$k<scalar @$featureslist;$k++)
-	{
-		if(($singleDATfile) || ($featureslist->[$k]{rom}==$romimage && $featureslist->[$k]{cfgfile} == $featurefile))
-		{			
-			AddToFeatureList($featureslist->[$k],$featuremanager);
-		}
-	}
-
-	my $features = &featureparser::getFeatures(\@includeFeatureList, \@excludeFeatureList);
-	if (!$features)
-	{
-		ERROR("No feature file generated for ROM_IMAGE[".$romimage."]");
-		return 0;
-	}
-	else
-	{
-		my $object;
-		if ($featuremanager) 
-		{
-			$object = new featuresdat($xmlDBHandle);
-		}
-		else
-		{
-			$object = new featurecfg($xmlDBHandle);
-		}		
-		return $object->createFile($featurefilename, $features , $featuremanager);
-	}	
-}
-
-# Subroutine to add the feature specified to the included/excluded feature list
-# @param featureData				 - Reference to hash containing feature information (i.e. name/uid,
-# 									   included/excluded,SF and UD).  
-# @param featuremanager				 - Flag to generate features data file.
-sub AddToFeatureList
-{
-	my ($featureData, $featuremanager) = @_; 	
-	
-	my %feat = ();
-	my $feature = $featureData->{feature};		
-	
-#	Check if the given value is a feature name.
-	my $value = $xmlDBHandle->getFeatureUID($feature);
-
-#	If not a feature, then may be uid value
-	if(!defined $value)
-	{
-		if (!featureparser::IsValidNum($feature)) 
-		{
-			ERROR("Feature \"".$feature."\" not found in feature list XML");
-			return;
-		}
-		if (&featureparser::ValidateUIDValue($feature))
-		{
-			my $featureUid = $feature;
-			$feature = &featureparser::ConvertHexToDecimal($feature);
-			my $featureInfo = $xmlDBHandle->getFeatureInfo($feature);
-			if (!$featureInfo)
-			{
-				ERROR("Feature \"".$featureUid."\" not found in feature list XML");
-				return;
-			}
-			else
-			{
-				$feat{uid} = $feature;
-				$feat{name} = $featureInfo->{name};				
-			}
-		}
-		else
-		{
-			return;
-		}
-	}
-	else
-	{
-		$feat{name} = $feature;
-		$feat{uid} = $value;		
-	}		
-
-	# Set the values of "SF" and "UD" for feature manager.
-	if ($featuremanager) 
-	{		
-		&setFeatureArguments(\%feat,$featureData->{SF},$featureData->{UD});
-	}	
-
-	if($featureData->{include} == 1)
-	{
-		$feat{include} = 1;
-		push @includeFeatureList, \%feat;
-	}
-	else
-	{
-		$feat{exclude} = 1;
-		push @excludeFeatureList, \%feat;
-	}
-}
-
-# Subroutine to set the values of "SF" and "UD" for the specified feature
-# @param feat						- Reference to hash containing information(i.e. name and uid) 
-#									  of the specified feature.
-# @param SF							- Value of "SF" provided in the iby/oby file. 
-# @param UD							- Value of "UD" provided in the iby/oby file.
-sub setFeatureArguments
-{
-	my($feat,$SF,$UD)= @_;
-	
-	my $featureInfo = $xmlDBHandle->getFeatureInfo($feat->{uid});
-	
-	# If the values of 'SF' and 'UD' are not provided in the iby/oby file, then take the values
-	# from Feature Database XML file.
-	if ($SF && featureparser::IsValidNum($SF))  
-	{
-		$feat->{SF} = &featureparser::ConvertHexToDecimal($SF);
-	}
-	else 
-	{
-		# Generate warning if the value of "SF" provided for the feature in iby/oby file
-		# is invalid.
-		if ($SF) 
-		{
-			WARN("Invalid SF value \"$SF\" provided for feature \"$feat->{name}\". Defaulting to value provided in XML file");
-		}
-		$feat->{SF} = &featureparser::ConvertHexToDecimal($featureInfo->{statusflags});			
-	}
-	if ($UD && featureparser::IsValidNum($UD))  					
-	{			
-		$feat->{UD} = &featureparser::ConvertHexToDecimal($UD);						
-	}
-	else 
-	{
-		# Generate warning if the value of "UD" provided for the feature in iby/oby file
-		# is invalid.
-		if ($UD) 
-		{
-			WARN("Invalid UD value \"$UD\" provided for feature \"$feat->{name}\". Defaulting to value provided in XML file");
-		}
-		$feat->{UD} = &featureparser::ConvertHexToDecimal($featureInfo->{userdata});				
-	}				
-}
-
-1;
+#
+# Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+#
+
+package featuresutil;
+        
+
+require Exporter;
+@ISA = qw(Exporter);
+@EXPORT = qw(
+	parseXMLDatabase
+	createFeatureFile
+	convert_FeatRegToFeatMgr
+);
+
+use strict;
+use XML::Handler::XMLWriter;
+#use IO;
+
+use featureparser;
+use featuremanager;
+use featureregistry;
+use featuresdat;
+use featurecfg;
+
+my $xmlDBHandle = undef; #Object of feature parser
+
+my @includeFeatureList;	#List of included features. The included feature in this list is a hash table giving the 
+			#Uid or the name. These features are collected from the iby/obey files.
+my @excludeFeatureList;	#List of excluded features.The excluded feature in this list is a hash table giving the 
+			#Uid or the name. These features are collected from the iby/obey files.
+
+my $verboseFlg = 0; # verbose mode flag
+my $strictFlg = 1; # strict mode flag
+
+# Subroutine to generate warning messages.
+sub WARN 
+{
+	print "WARNING: ".$_[0]."\n"; 
+}
+
+# Subroutine to generate error messages.
+sub ERROR 
+{ 
+	print "ERROR: ".$_[0]."\n"; 
+}
+
+# Verbose mode output routine
+sub MSG 
+{
+	if($verboseFlg) {
+		print "**".$_[0]."...\n";
+	}
+}
+
+# Subroutine to parse feature list XML database file.
+# @param dbfileList					- List of XML database file names seperated by commas.
+# @param fmFlag						- Flag to generate features data file.
+# @param strictFlg					- Flag to enable strict mode (optional).
+# @param verboseFlg                 - Flag to enable verbose mode (optional).
+sub parseXMLDatabase
+{
+	my $dbfileList = shift;
+	my $fmFlag = shift;
+	$strictFlg = shift;
+	$verboseFlg = shift;
+	
+	# list of xml databases
+	my @filelist = split(/,/,$dbfileList);
+	
+	# return status
+	my $retStatus = 0;
+	
+	# default mode is strict
+	$strictFlg=0 if(!defined $strictFlg);
+	# default mode is nonverbose
+	$verboseFlg=0 if(!defined $verboseFlg);
+	
+	# multiple file support is not applicable for feature registry option
+	if( (@filelist > 1) && (!$fmFlag) ) {
+		&ERROR("Multiple XML database file support is not applicable for featureregistry option");
+		return 0;
+	}
+	
+	if($fmFlag) # Feature manager option handling
+	{
+		# create the object of feature manager class
+		$xmlDBHandle = new featuremanager;
+		
+		if($xmlDBHandle) {
+			foreach my $file (@filelist) 
+			{
+				my $status = 1;
+				if(-e $file) {
+					
+					&MSG("Parsing $file");
+					
+					# parse the feature manager xml file
+					$status = $xmlDBHandle->parseXMLFile($file);
+					if(! $status) {
+					
+						# create the object of feature registry class
+						my $registryObj = new featureregistry;
+						# parse the feature registry xml file
+						$status = $registryObj->parseXMLFile($file);
+						if($status < 0) {
+							if($strictFlg) {
+								&ERROR("Invalid features database $file");
+								$xmlDBHandle = undef;
+								return 0;
+							}
+							else {
+								&WARN("Invalid features database $file");
+							}
+						}
+						elsif(! $status) {
+							# if the xml file is not valid feature list xml file
+							if($strictFlg) {
+								&ERROR("Error in reading features database file \"$file\"");
+								$xmlDBHandle = undef;
+								return 0;
+							}
+							else {
+								&WARN("Error in reading features database file \"$file\"");
+							}
+						}
+						else {
+							MSG("Converting featureregistry database to featuremanager");
+							
+							# add the feature registry file object to the feature manager file object
+							if(! $xmlDBHandle->addFeatureRegistry($registryObj)) {
+								if($strictFlg) {
+									MSG("Error in reading features database file \"$file\"");
+									$xmlDBHandle = undef;
+									return 0;
+								}
+								else {
+									&WARN("Error in reading features database file \"$file\"");
+								}
+							}
+							else {
+								# parsing feature registry database success
+								$retStatus = 1;
+							}
+						}
+					}
+					elsif( $status < 0 ) {
+						if($strictFlg) {
+							&ERROR("Invalid features database $file");
+							$xmlDBHandle = undef;
+							return 0;
+						}
+						else {
+							&WARN("Invalid features database $file");
+						}
+					}
+					else {
+						# parsing feature manager database success
+						$retStatus = 1;
+					}
+				}
+				else {
+					if(!$strictFlg) {
+						&WARN($file." doesn\'t exist");
+						next;
+					}
+					else {
+						&ERROR($file." doesn\'t exist");
+						$xmlDBHandle = undef;
+						return 0;
+					}
+				}
+			}
+		}
+		else {
+			&ERROR("Couldn't create feature parser object");
+		}
+	}
+	else # Feature registry file handling
+	{
+		if(@filelist) {
+			my $file = $filelist[0];
+			$xmlDBHandle = new featureregistry;
+			
+			if($xmlDBHandle) {
+				if(-e $file) {
+				
+					MSG("Parsing $file");
+					
+					my $status = $xmlDBHandle->parseXMLFile($file);
+
+					if($status < 0) {
+						&ERROR($file." is invalid feature registry file");
+						$xmlDBHandle = undef;
+						return 0;
+					}
+					elsif(!$status) {
+						&ERROR("Error in reading feature registry file ".$file);
+						$xmlDBHandle = undef;
+					}
+					else {
+						# parsing feature registry database success
+						$retStatus = 1;
+					}
+				}
+				else {
+					if(!$strictFlg) {
+						&WARN($file." doesn\'t exist -- ");
+					}
+					else {
+						&ERROR($file." doesn\'t exist -- ");
+					}				
+					$xmlDBHandle = undef;
+				}
+			}
+			else {
+				&ERROR("Couldn't create feature parser object");
+			}
+		}
+	}
+	
+	if($retStatus) {
+		return $xmlDBHandle
+	}
+	else {
+		return $retStatus;
+	}
+}
+
+# Subroutine to generate feature manager database file from the given feature registry database
+# @param strictFlg - strict mode flag
+# @param verboseFlg - verbose mode flag
+# @param outpath - destination path for the converted database file(s)
+# @param dblist - list of xml file names
+sub convert_FeatRegToFeatMgr
+{
+	$strictFlg = shift;
+	$verboseFlg = shift;
+	my $outpath = shift;
+	my @dblist = @_;
+	
+	# default mode is strict
+	$strictFlg=0 if(!defined $strictFlg);
+	# default mode is nonverbose
+	$verboseFlg=0 if(!defined $verboseFlg);
+
+	foreach my $file (@dblist)
+	{
+		# Create the object of feature registry
+		my $fileHandle = new featureregistry;
+		
+		if(-e $file) {
+			# Parse the database
+			if($fileHandle->parseXMLFile($file) > 0) {
+				MSG("Converting Feature Registry database $file");
+				
+				# Create directory if it doesn't exists
+				if(!(-e $outpath)) {
+					if(!mkdir($outpath)) {
+						&ERROR("Failed to create $outpath folder");
+						return 0;
+					}
+				}
+				# Emit the contents of feature registry object into an feature manager database file
+				&generateXML($fileHandle, $outpath);
+			}
+		}
+		else {
+			if(!$strictFlg) {
+				&WARN($file." doesn\'t exist -- ");
+				next;
+			}
+			else {
+				&ERROR($file." doesn\'t exist -- ");
+				return 0;
+			}
+		}
+	}
+}
+
+# Subroutine to emit XML output for the given featureregistry object
+# @param frObject - object of feature registry database
+# @param outPath - destination path for the converted database file
+sub generateXML
+{
+	my ($frObject, $outPath) = @_;
+		
+	my $outputFile = $frObject->fileName();
+	
+	# Extract absolute file name
+	if( $outputFile =~ /[\\\/]/) {
+		$outputFile =~ /.*[\\\/](.+)\z/;
+		$outputFile = $1;
+	}
+	
+	# Add suffix _converted
+	$outputFile =~ s/(.*)([\.].+)\z/$1_converted$2/;
+	
+	my $fileHandle = new IO::File(">$outPath$outputFile");
+	
+	if($fileHandle) {
+		my $writer = XML::Handler::XMLWriter->new(Output => $fileHandle);
+		
+		# Header
+		$writer->start_document();
+		$writer->print("<!--Converted from the feature registry ".$frObject->fileName()."-->\n\n");
+		# DOCTYPE
+		$writer->print("<!DOCTYPE featuredatabase SYSTEM \"featuredatabase.dtd\">\n\n");
+		
+		# Root element begin
+		$writer->start_element({Name => 'featuredatabase', Attributes => {}});
+		
+		# FeatureSet element
+		$writer->print("\n\t");
+		$writer->start_element({Name => 'featureset', Attributes => {}});
+		my $nameuidmap = $frObject->featureNameUidMap();
+		foreach my $uid (sort(values %$nameuidmap)) {
+			my $featinfo = $frObject->getFeatureInfo($uid);
+			my %attributes = ();
+			
+			$attributes{uid} = sprintf("0x%08X",$uid);
+			$attributes{statusflags} = "0x00000001";
+			$attributes{name} = $featinfo->{name};
+			
+			$writer->print("\n\t\t");
+			$writer->start_element({Name => 'feature', Attributes => \%attributes});
+			$writer->end_element({Name => 'feature'});
+		}
+		$writer->print("\n\t");
+		$writer->end_element({Name => 'featureset'});
+		
+		# defaultfeaturerange element
+		my $rangeList = $frObject->defaultRangeList();
+		foreach my $range (@$rangeList) {
+			my %attributes = ();
+			
+			next if(lc($range->{support}) eq "exclude");
+			
+			$attributes{higheruid} = sprintf("0x%08X",$range->{max});
+			$attributes{loweruid} = sprintf("0x%08X",$range->{min});
+			
+			$writer->print("\n\t");
+			$writer->start_element({Name => 'defaultfeaturerange', Attributes => \%attributes});
+			$writer->end_element({Name => 'defaultfeaturerange'});
+		}
+		
+		# Root element close
+		$writer->print("\n");
+		$writer->end_element({Name => 'featuredatabase'});
+		
+		# Footer
+		$writer->end_document();
+	}
+	else {
+		&ERROR("Failed to create $outPath$outputFile file");
+	}
+}
+
+# Subroutine to create Feature Registry/Features Data file
+# @param romimage				 - Rom image number.
+# @param featurefile			 - Feature file number.
+# @param featurefilename		 - Name of the feature file to be generated.
+# @param featureslist			 - Reference to array of hashes containing features to included/excluded.
+# @param featuremanager			 - Flag to generate features data file.
+# @param singleDATfile           - Flag to generate single features.dat file.
+sub createFeatureFile
+{
+	if(!defined ($xmlDBHandle)) 
+	{
+		ERROR("No XML Database opened");
+		return 0;
+	}	
+	my ($romimage,$featurefile,$featurefilename,$featureslist,$featuremanager,$singleDATfile) = @_;
+	
+	# Default setting for singleDATfile flag
+	$singleDATfile = 0 if(!defined $singleDATfile);
+	
+	# Clear the global include/exclude feature list.
+	@includeFeatureList = (); 
+	@excludeFeatureList = ();
+
+
+	for(my $k=0;$k<scalar @$featureslist;$k++)
+	{
+		if(($singleDATfile) || ($featureslist->[$k]{rom}==$romimage && $featureslist->[$k]{cfgfile} == $featurefile))
+		{			
+			AddToFeatureList($featureslist->[$k],$featuremanager);
+		}
+	}
+
+	my $features = &featureparser::getFeatures(\@includeFeatureList, \@excludeFeatureList);
+	if (!$features)
+	{
+		ERROR("No feature file generated for ROM_IMAGE[".$romimage."]");
+		return 0;
+	}
+	else
+	{
+		my $object;
+		if ($featuremanager) 
+		{
+			$object = new featuresdat($xmlDBHandle);
+		}
+		else
+		{
+			$object = new featurecfg($xmlDBHandle);
+		}		
+		return $object->createFile($featurefilename, $features , $featuremanager);
+	}	
+}
+
+# Subroutine to add the feature specified to the included/excluded feature list
+# @param featureData				 - Reference to hash containing feature information (i.e. name/uid,
+# 									   included/excluded,SF and UD).  
+# @param featuremanager				 - Flag to generate features data file.
+sub AddToFeatureList
+{
+	my ($featureData, $featuremanager) = @_; 	
+	
+	my %feat = ();
+	my $feature = $featureData->{feature};		
+	
+#	Check if the given value is a feature name.
+	my $value = $xmlDBHandle->getFeatureUID($feature);
+
+#	If not a feature, then may be uid value
+	if(!defined $value)
+	{
+		if (!featureparser::IsValidNum($feature)) 
+		{
+			ERROR("Feature \"".$feature."\" not found in feature list XML");
+			return;
+		}
+		if (&featureparser::ValidateUIDValue($feature))
+		{
+			my $featureUid = $feature;
+			$feature = &featureparser::ConvertHexToDecimal($feature);
+			my $featureInfo = $xmlDBHandle->getFeatureInfo($feature);
+			if (!$featureInfo)
+			{
+				ERROR("Feature \"".$featureUid."\" not found in feature list XML");
+				return;
+			}
+			else
+			{
+				$feat{uid} = $feature;
+				$feat{name} = $featureInfo->{name};				
+			}
+		}
+		else
+		{
+			return;
+		}
+	}
+	else
+	{
+		$feat{name} = $feature;
+		$feat{uid} = $value;		
+	}		
+
+	# Set the values of "SF" and "UD" for feature manager.
+	if ($featuremanager) 
+	{		
+		&setFeatureArguments(\%feat,$featureData->{SF},$featureData->{UD});
+	}	
+
+	if($featureData->{include} == 1)
+	{
+		$feat{include} = 1;
+		push @includeFeatureList, \%feat;
+	}
+	else
+	{
+		$feat{exclude} = 1;
+		push @excludeFeatureList, \%feat;
+	}
+}
+
+# Subroutine to set the values of "SF" and "UD" for the specified feature
+# @param feat						- Reference to hash containing information(i.e. name and uid) 
+#									  of the specified feature.
+# @param SF							- Value of "SF" provided in the iby/oby file. 
+# @param UD							- Value of "UD" provided in the iby/oby file.
+sub setFeatureArguments
+{
+	my($feat,$SF,$UD)= @_;
+	
+	my $featureInfo = $xmlDBHandle->getFeatureInfo($feat->{uid});
+	
+	# If the values of 'SF' and 'UD' are not provided in the iby/oby file, then take the values
+	# from Feature Database XML file.
+	if ($SF && featureparser::IsValidNum($SF))  
+	{
+		$feat->{SF} = &featureparser::ConvertHexToDecimal($SF);
+	}
+	else 
+	{
+		# Generate warning if the value of "SF" provided for the feature in iby/oby file
+		# is invalid.
+		if ($SF) 
+		{
+			WARN("Invalid SF value \"$SF\" provided for feature \"$feat->{name}\". Defaulting to value provided in XML file");
+		}
+		$feat->{SF} = &featureparser::ConvertHexToDecimal($featureInfo->{statusflags});			
+	}
+	if ($UD && featureparser::IsValidNum($UD))  					
+	{			
+		$feat->{UD} = &featureparser::ConvertHexToDecimal($UD);						
+	}
+	else 
+	{
+		# Generate warning if the value of "UD" provided for the feature in iby/oby file
+		# is invalid.
+		if ($UD) 
+		{
+			WARN("Invalid UD value \"$UD\" provided for feature \"$feat->{name}\". Defaulting to value provided in XML file");
+		}
+		$feat->{UD} = &featureparser::ConvertHexToDecimal($featureInfo->{userdata});				
+	}				
+}
+
+1;
--- a/imgtools/buildrom/tools/spitool.pl	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/spitool.pl	Tue Jun 29 14:52:54 2010 +0800
@@ -1,32 +1,33 @@
-#
-# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-#
-use warnings;
-use strict;
-use FindBin;		# for FindBin::Bin
-my $PerlLibPath;	# fully qualified pathname of the directory containing our Perl modules
-
-BEGIN {
-# check user has a version of perl that will cope
-	require 5.005_03;
-# establish the path to the Perl libraries
-    $PerlLibPath = $FindBin::Bin;	# X:/epoc32/tools
-    $PerlLibPath =~ s/\//\\/g;	# X:\epoc32\tools
-    $PerlLibPath .= "\\";
-}
-
-use  lib $PerlLibPath;
-use spitool qw(&createSpi);
-createSpi(@ARGV);
+#!/usr/bin/perl
+#
+# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+#
+use warnings;
+use strict;
+use FindBin;		# for FindBin::Bin
+my $PerlLibPath;	# fully qualified pathname of the directory containing our Perl modules
+
+BEGIN {
+# check user has a version of perl that will cope
+	require 5.005_03;
+# establish the path to the Perl libraries
+    $PerlLibPath = $FindBin::Bin;
+    $PerlLibPath =~ s/\\/\//g;
+    $PerlLibPath .= "\/";
+}
+
+use  lib $PerlLibPath;
+use spitool qw(&createSpi);
+createSpi(@ARGV);
--- a/imgtools/buildrom/tools/spitool.pm	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/buildrom/tools/spitool.pm	Tue Jun 29 14:52:54 2010 +0800
@@ -1,478 +1,478 @@
-#
-# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-#
-
-package spitool;
-
-use strict;
-use Exporter;
-use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
-
-$VERSION     = 1.00;
-@ISA         = qw(Exporter);
-@EXPORT      = ();
-@EXPORT_OK   = qw(createSpi);
-
-sub binarize { #converts decimal number to 4 byte litte endian format
-	my $value = shift;
-	my $remainder;
-	my $returnValue;
-	for(my $i=0;$i<4;$i++) {
-		$remainder=$value % 256;
-		$returnValue.=chr($remainder);
-		$value = ($value-$remainder)/256;
-	}
-	return $returnValue;
-}
-
-sub convertUidFromText { #converts UID from hexadeciaml text value to decimal value, passes decimal value unchanged, returns -1 if invalid UID
-	my $value = shift;
-	if($value =~ /^0x([\da-fA-F]{1,8})$/i) {
-		return hex $1;
-	} elsif ($value =~ /^\d*$/) {
-		return $value;
-	} else {
-		return -1;
-	}
-}
-
-sub bin2hex { #converts 4 byte little endian value to 0x... hex text value
-	my $value=shift;
-	my $byte;
-	my $quotient;
-	my $remainder;
-	my $hexValue="";
-	for(my $i=0;$i<4;$i++) {
-		$byte=ord(substr($value,$i,1));
-		$remainder=$byte%16;
-		$quotient=($byte-$remainder)/16;
-		if($remainder>9) {
-			$remainder= chr($remainder+55);
-		}
-		if($quotient>9) {
-			$quotient= chr($quotient+55);
-		}		
-		$hexValue=$quotient . $remainder . $hexValue;
-	}
-	return "0x" . $hexValue;
-}
-
-sub uidcrc { #returns decimal UID checksum value for the three inputs
-	my $output = `uidcrc $_[0] $_[1] $_[2]`;
-	if($output =~ /([^ ]*)$/i) {
-		$output =$1;
-		chomp $output;
-		return hex($output);
-	}	
-}
-
-sub printZeroes { #prints as many hexadecimal zeroes to OUTPUTFILE as specified by input
-	my $numberOfZeroes=shift;
-	for(my $i=0;$i<$numberOfZeroes;$i++) {
-		print OUTPUTFILE chr(0);
-	}
-}
-
-sub bytes2dec { #calculates decimal value from inputted 4 byte little endian value 
-	my $bytes=shift;
-	my @byteArray;
-	for(my $i=0;$i<length $bytes;$i++) {
-		$byteArray[$i]=ord(substr($bytes,$i,1));
-	}
-	my $decValue;
-	for(my $i=0;$i<scalar @byteArray;$i++) {
-		$decValue+=($byteArray[$i]*(2**($i*8)));
-	}
-	return $decValue;
-}
-
-sub print_usage
-	{
-#........1.........2.........3.........4.........5.........6.........7.....
-	print <<USAGE_EOF;
-
-Usage:
-  spitool.pl [options] files directories   
-
-Create an SPI file by concatenating the files and contents of directories,
-based on the options passed. 
-
-The available options are:
-
--tSPIFileName       -- SPIFileName is the name the produced SPI file will 
-                       have (i.e. ecom-0-0.spi). If not specified, the name 
-                       will be ecom-0-0.spi by default
--dTargetDir         -- TargetDir is the directory where the SPI file should
-                       be created, ending with a \
--iExisting          -- Existing is address and name of existing SPI file to
-                       concatenate specified files to 
--uid<x>=<y>         -- <x> has value 1, 2 or 3, <y> is an UID value in
-                       decimal or 0x... hexadecimal
--existinguid<x>=<y> -- <x> has value 1, 2 or 3, <y> is an UID value in 
-                       decimal or 0x... hexadecimal
--existinguidcrc=<x> -- <x> is an UID value in decimal or 0x.. hexadecimal
--hide<ResourceFileNames> -- <ResourceFileNames> is the list of the resource files
-			    that are to be hidden in the SPI file separated by
-			    space or comma.
-  
-If an existing SPI file is specified with the -i option then this file is
-used as a base and other data files are added to the end of this file,
-otherwise a new SPI file is created. In either case the produced SPI file
-is placed in the directory specified by the -d option and given the name 
-specified with the -t option.
-
-Files which are to be concatenated into the SPI file should be specified
-on the command line by either specifying the file's name (and location), or
-by including a directory name, in which case all files from that directory
-will be included.
-
-The -uid options can be used to filter files for inclusion in the SPI file.
-This option can be included multiple times, so a list of UID1 values can be
-built up, and the same for UID2 and UID3 values. Each file on the command
-line is compared with this list, and if any of its UID values match a
-relevant value in the UID lists then that file will be included in the SPI
-file. If the file does not match any values it will be excluded.
-
-The -existinguid options allow the UID values that an existing SPI file
-should have to be specified. This will allow the possibility of checking
-that the correct type of files are being concatenated together.
-
-The -hide option can be used to mark a resource file as hidden in the SPI file.
-To mark a resource file as a hidden entry in the SPI file, the resource data 
-length will be written as 0.
-
-USAGE_EOF
-	}
-
-sub createSpi 
-	{
-	my @resourceFiles=();
-	my @hideresourceFiles=();
-	my $spiFileName;
-	my $targetDirectory;
-	my $existingSpiFileName;
-	my @uid;
-	my @uidLengths = (0, 0, 0, 0);
-	my @uid1;
-	my @uid2;
-	my @uid3;
-	my @existingUid = (-1,-1,-1,-1);
-	my $uidNumber;
-	my $defaultSpiFileName = "ecom-0-0.spi";
-	my $defaultTargetDirectory = "$ENV{EPOCROOT}epoc32\\tools\\";
-	my @defaultUid = (-1,-1,-1,-1);
-	
-##########################################################################################
-# Reading arguments phase
-##########################################################################################
-
-	foreach my $arg (@_) {
-		if ($arg =~ /^-t(.*)/i) { # set target SPI file
-			$spiFileName = $1;
-			next;
-			}
-		if ($arg =~ /^-d(.*)/i) { # set target ouput directory
-			my $tempDirectory=$1;
-			if((-d $tempDirectory) ) {
-				$targetDirectory = $tempDirectory;
-				next;
-				}
-				else
-				{
-				 print "Output directory \'",$tempDirectory,"\' does not exist.\n";
-				 exit(1);
-				 }				
-			}
-		if ($arg =~ /^-i(.*)/i) { # existing SPI file to use as a base
-			my $tempFileName = $1;
-			if((-e $tempFileName) && (!(-d $tempFileName))) {
-				$existingSpiFileName = $tempFileName;
-				next;
-				}
-			}
-		if ($arg =~ /^-uid([1-3])\=(.*)/i) {
-			$uid[$1-1][$uidLengths[$1-1]++] = $2;
-			next;
-			}
-		if($arg=~/^-existinguidcrc\=(.*)/i) {
-			$existingUid[3]=$1;
-			next;
-			}
-		if ($arg =~ /^-existinguid([1-3])\=(.*)/i) {
-			$existingUid[$1-1]=$2;
-			next;
-			}
-		if ($arg =~ /^-hide(.*)/i) { # Collect the files to be hidden
-			my $line = $1;
-			$line =~ s/,/ /g;
-			my @files = split(' ' , $line);
-			foreach my $file (@files)
-			{
-				push @hideresourceFiles, $file;
-			}
-			next;
-			}
-		if (-d $arg) {
-			if(($arg =~ m-^.:-) && ($arg =~ m-\\$-)) {
-				unless(opendir(DIRECTORY, $arg)) { print "Exiting: $arg"; exit; }
-				while (my $file=readdir(DIRECTORY)) {
-					my $newfile = $arg.$file;
-					if(!(-d $newfile)) {
-						push @resourceFiles, $newfile;
-					}
-				}
-				close(DIRECTORY);
-				next;
-				}
-			}
-		if ((-e $arg) && (!(-d $arg))) {
-			push @resourceFiles, $arg;
-			next;
-			}
-		if ($arg eq "-h") {
-			print_usage;
-			exit(1);
-		}	
-		print "Unknown command: $arg\n";
-	}
-
-#####################################################################################
-# UID phase
-#####################################################################################
-		
-	if(!(defined $spiFileName)) { #use default file name if none passed on command line
-		$spiFileName = $defaultSpiFileName;
-	}
-	if(!(defined $targetDirectory)) { #use default target dir if none passed on command line
-		$targetDirectory = $defaultTargetDirectory;
-	}
-	for(my $i=0;$i<3;$i++) { #if default UIDs specified then added to UID match lists
-		if($defaultUid[$i]>=0) {
-			$uid[$i][$uidLengths[$i]++] = $defaultUid[$i];
-		}
-	}
-	for(my $i=0;$i<3;$i++) { #makes sure UIDs are valid UIDs
-		my @tempUidArray;
-		my $iterator=0;
-		while(defined $uid[$i][$iterator]) {
-			my $convertedUid=convertUidFromText($uid[$i][$iterator]);
-			if ($convertedUid != -1) {
-				push @tempUidArray, binarize($convertedUid);
-			} else {
-				print "Invalid UID: $uid[$i][$iterator]\n";
-			}
-			$iterator++;
-		}
-		for(my $j=0;$i<scalar @tempUidArray;$j++) {
-			$uid[$i][$j]=$tempUidArray[$j];
-		}
-		for(my $j=scalar@tempUidArray;defined $uid[$i][$j];$j++) {
-			undef $uid[$i][$j];
-		}
-	}
-#####################################################################################
-# Phase to split up resource names
-#####################################################################################
-
-	my @resourceFilePaths;
-	my @resourceFileNames;
-	my @resourceExtensions;
-	my @filestobehidden;
-
-# To mark the resource files as hidden in the SPI file by writing the data length as zero
-	foreach my $file (@hideresourceFiles)
-	{
-		my $matchfound =0;
-		my $i=0;
-		for(;$i<scalar @resourceFiles && !$matchfound;$i++)
-		{
-			if (lc($file) eq lc($resourceFiles[$i]))
-			{
-				$filestobehidden[$i] = 1;
-				$matchfound =1;
-			}
-		}
-		if (!$matchfound)
-		{
-# Those files that are to be hidden in the SPI file but not existing in the SPI
-			if (! -e $file)
-			{
-				print "Warning: Hiding non-existent file $file\n";
-			}
-			push @resourceFiles,$file;
-			$filestobehidden[$i] = 1;
-		}
-	}
-	
-	for(my $i=0;$i<scalar @resourceFiles;$i++) {
-		if($resourceFiles[$i]=~m|\\|) {
-			if($resourceFiles[$i]=~m|(.*)\\([^\\]*)$|) {
-				$resourceFilePaths[$i]=$1;
-				$resourceFileNames[$i]=$2;
-			}
-			if($resourceFileNames[$i]=~m|(.*)\.([^\.]*)|) {
-				$resourceFileNames[$i]= $1;
-				$resourceExtensions[$i]=$2;
-			}
-		} else {
-			$resourceFilePaths[$i]="";
-			if($resourceFiles[$i]=~m|(.*)\.([^\.]*)|) {
-				$resourceFileNames[$i]= $1;
-				$resourceExtensions[$i]=$2;
-			}
-		}
-	}
-	
-	my %uid2values; #hash to hold UID2 values for each type of SPI file
-	$uid2values{"ecom"} = 270556204;
-
-##########################################################
-# Existing file stage
-##########################################################
-
-	my @spiUid = (270556203, 0, 0); #holds spi values (including CRC value)
-	foreach my $key (keys(%uid2values)) { #searches through SPI types to match UID2 value
-		if($spiFileName =~/^$key/) {
-			$spiUid[1]=$uid2values{$key};
-		}
-	}
-	$spiUid[3] = uidcrc($spiUid[0], $spiUid[1], $spiUid[2]);
-	my $total=0; #used to keep track of position in SPI file
-	my $buffer;
-	my $spifile=File::Spec->catpath( "", $targetDirectory, $spiFileName );
- 	open OUTPUTFILE, ">$spifile" or die $!;
-	binmode (OUTPUTFILE);
-	if($existingSpiFileName) {
-		open EXISTINGFILE, "$existingSpiFileName" or die $!;
-		binmode (EXISTINGFILE);
-
-		my @fileNameLengths;
-		my @fileLengths;
-		my @fileNames;
-		my @fileContents;
-
-		read(EXISTINGFILE,$buffer,4);
-		read(EXISTINGFILE,$buffer,4);
-		if(bytes2dec($buffer)!=$spiUid[1]) {
-			print "Incompatible SPI files.\n";
-		}
-		read(EXISTINGFILE,$buffer,24);
-		$total=32;
-		my $existingSpiFileSize = (stat(EXISTINGFILE))[7];
-		while($total<$existingSpiFileSize) { #loop to store information from files which are not being replaced
-			read(EXISTINGFILE,$buffer,4);
-			push @fileNameLengths, bytes2dec($buffer);
-			read(EXISTINGFILE,$buffer,4);
-			push @fileLengths, bytes2dec($buffer);
-			read(EXISTINGFILE,$buffer,$fileNameLengths[$#fileNameLengths]);
-			push @fileNames, $buffer;
-			$total=$total+8+$fileNameLengths[$#fileNameLengths]+$fileLengths[$#fileLengths];
-			my $padding = (4-(($fileNameLengths[$#fileNameLengths]+$fileLengths[$#fileLengths])%4))%4;
-			read(EXISTINGFILE,$buffer,$fileLengths[$#fileLengths]+$padding);
-			push @fileContents, $buffer;
-			$total += (4-($total%4))%4;			
-		}
-		close EXISTINGFILE;	
-		#next part prints to OUTPUTFILE the header and files which are not being replaced
-		print OUTPUTFILE binarize($spiUid[0]) . binarize($spiUid[1]) . binarize($spiUid[2]) . binarize($spiUid[3]);
-		printZeroes(16);
-		$total=32;
-		for(my $i=0; $i<scalar @fileNames; $i++) {
-			my $flag=1;
-			for(my $j=0; $j<scalar @resourceFileNames && $flag==1; $j++) {
-				if($fileNames[$i] eq $resourceFileNames[$j]) {
-					$flag=0;
-				}
-			}
-			if($flag) {
-				print OUTPUTFILE binarize($fileNameLengths[$i]) . binarize($fileLengths[$i]) . $fileNames[$i] . $fileContents[$i];
-				$total=$total+8+length($fileNames[$i])+length($fileContents[$i]);
-			}
-		}
-	} else { #prints header for target SPI file if there is no existing SPI file
-		print OUTPUTFILE binarize($spiUid[0]) . binarize($spiUid[1]) . binarize($spiUid[2]) . binarize($spiUid[3]);
-		printZeroes(16);
-		$total=32;
-	}
-
-####################################################################
-# Appending new data files to the SPI file
-####################################################################
-
-	my $resourceFileSize;
-	my $resourceFileSizeInBinary;
-	my $resourceFileNameSize;
-	my $resourceFileNameSizeInBinary;
-	for(my $i=0; $i<scalar @resourceExtensions;$i++) {
-# To mark the resource files as hidden in the SPI file by writing the data length as zero
-	   if ($filestobehidden[$i] == 1)
-	   {
-		$resourceFileNameSize = length($resourceFileNames[$i]);
-		$resourceFileNameSizeInBinary = binarize($resourceFileNameSize);
-		$resourceFileSize = 0;
-		$resourceFileSizeInBinary = binarize($resourceFileSize);
-		print OUTPUTFILE $resourceFileNameSizeInBinary . $resourceFileSizeInBinary . $resourceFileNames[$i];
-		$total+=$resourceFileNameSize;
-		my $padding = (4-(($resourceFileSize + $resourceFileNameSize)%4))%4;
-		printZeroes($padding);
-		$total+=$padding;
-	   }
-	   else
-	   {
-		open RESOURCEFILE, "<$resourceFiles[$i]";
-		binmode(RESOURCEFILE);
-		my @fileUid; #stores UIDs from particular data file
-		my $fileUid1;
-		my $fileUid2;
-		my $fileUid3;
-		read(RESOURCEFILE,$fileUid[0],4);
-		read(RESOURCEFILE,$fileUid[1],4);
-		read(RESOURCEFILE,$fileUid[2],4);
-		my $uidFlag=0; #changes to 1 if a UID value in data file matches a specified UID value
-		my $uidExists=1; #changes to 1 if there are specified UIDs to match to
-		for(my $j=0;$j<3 && (!$uidFlag);$j++) {
-			my $k=0;
-			while(defined $uid[$j][$k] && (!$uidFlag)) {
-				$uidExists=0;
-				if($uid[$j][$k] eq bin2hex($fileUid[$j])) {
-					$uidFlag=1;
-				}
-				$k++;
-			}
-		}	
-		if(($uidFlag) || ($uidExists)) { #if suitable UIDs writes data file to SPI file
-			$resourceFileSize = (stat(RESOURCEFILE))[7];
-			$resourceFileNameSize = length($resourceFileNames[$i]);
-			$resourceFileNameSizeInBinary = binarize($resourceFileNameSize);
-			$resourceFileSizeInBinary = binarize($resourceFileSize);
-			print OUTPUTFILE $resourceFileNameSizeInBinary . $resourceFileSizeInBinary . $resourceFileNames[$i];
-			print OUTPUTFILE "$fileUid[0]$fileUid[1]$fileUid[2]";
-			while(read(RESOURCEFILE,$buffer,1)) {
-				print OUTPUTFILE $buffer;
-			}
-			$total+=$resourceFileSize;
-			$total+=8;
-			$total+=$resourceFileNameSize;
-			my $padding = (4-(($resourceFileSize + $resourceFileNameSize)%4))%4;
-			printZeroes($padding);
-			$total+=$padding;
-		}
-	   }
-	}
-	print "Created $spiFileName\n";
-}
-
-
-1;
+#
+# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+#
+
+package spitool;
+
+use strict;
+use Exporter;
+use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
+use romutl;
+
+$VERSION     = 1.00;
+@ISA         = qw(Exporter);
+@EXPORT      = ();
+@EXPORT_OK   = qw(createSpi);
+
+sub binarize { #converts decimal number to 4 byte litte endian format
+	my $value = shift;
+	my $remainder;
+	my $returnValue;
+	for(my $i=0;$i<4;$i++) {
+		$remainder=$value % 256;
+		$returnValue.=chr($remainder);
+		$value = ($value-$remainder)/256;
+	}
+	return $returnValue;
+}
+
+sub convertUidFromText { #converts UID from hexadeciaml text value to decimal value, passes decimal value unchanged, returns -1 if invalid UID
+	my $value = shift;
+	if($value =~ /^0x([\da-fA-F]{1,8})$/i) {
+		return hex $1;
+	} elsif ($value =~ /^\d*$/) {
+		return $value;
+	} else {
+		return -1;
+	}
+}
+
+sub bin2hex { #converts 4 byte little endian value to 0x... hex text value
+	my $value=shift;
+	my $byte;
+	my $quotient;
+	my $remainder;
+	my $hexValue="";
+	for(my $i=0;$i<4;$i++) {
+		$byte=ord(substr($value,$i,1));
+		$remainder=$byte%16;
+		$quotient=($byte-$remainder)/16;
+		if($remainder>9) {
+			$remainder= chr($remainder+55);
+		}
+		if($quotient>9) {
+			$quotient= chr($quotient+55);
+		}		
+		$hexValue=$quotient . $remainder . $hexValue;
+	}
+	return "0x" . $hexValue;
+}
+
+sub uidcrc { #returns decimal UID checksum value for the three inputs
+	my $output = `uidcrc $_[0] $_[1] $_[2]`;
+	if($output =~ /([^ ]*)$/i) {
+		$output =$1;
+		chomp $output;
+		return hex($output);
+	}	
+}
+
+sub printZeroes { #prints as many hexadecimal zeroes to OUTPUTFILE as specified by input
+	my $numberOfZeroes=shift;
+	for(my $i=0;$i<$numberOfZeroes;$i++) {
+		print OUTPUTFILE chr(0);
+	}
+}
+
+sub bytes2dec { #calculates decimal value from inputted 4 byte little endian value 
+	my $bytes=shift;
+	my @byteArray;
+	for(my $i=0;$i<length $bytes;$i++) {
+		$byteArray[$i]=ord(substr($bytes,$i,1));
+	}
+	my $decValue;
+	for(my $i=0;$i<scalar @byteArray;$i++) {
+		$decValue+=($byteArray[$i]*(2**($i*8)));
+	}
+	return $decValue;
+}
+
+sub print_usage
+	{
+#........1.........2.........3.........4.........5.........6.........7.....
+	print <<USAGE_EOF;
+
+Usage:
+  spitool.pl [options] files directories   
+
+Create an SPI file by concatenating the files and contents of directories,
+based on the options passed. 
+
+The available options are:
+
+-tSPIFileName       -- SPIFileName is the name the produced SPI file will 
+                       have (i.e. ecom-0-0.spi). If not specified, the name 
+                       will be ecom-0-0.spi by default
+-dTargetDir         -- TargetDir is the directory where the SPI file should
+                       be created, ending with a \
+-iExisting          -- Existing is address and name of existing SPI file to
+                       concatenate specified files to 
+-uid<x>=<y>         -- <x> has value 1, 2 or 3, <y> is an UID value in
+                       decimal or 0x... hexadecimal
+-existinguid<x>=<y> -- <x> has value 1, 2 or 3, <y> is an UID value in 
+                       decimal or 0x... hexadecimal
+-existinguidcrc=<x> -- <x> is an UID value in decimal or 0x.. hexadecimal
+-hide<ResourceFileNames> -- <ResourceFileNames> is the list of the resource files
+			    that are to be hidden in the SPI file separated by
+			    space or comma.
+  
+If an existing SPI file is specified with the -i option then this file is
+used as a base and other data files are added to the end of this file,
+otherwise a new SPI file is created. In either case the produced SPI file
+is placed in the directory specified by the -d option and given the name 
+specified with the -t option.
+
+Files which are to be concatenated into the SPI file should be specified
+on the command line by either specifying the file's name (and location), or
+by including a directory name, in which case all files from that directory
+will be included.
+
+The -uid options can be used to filter files for inclusion in the SPI file.
+This option can be included multiple times, so a list of UID1 values can be
+built up, and the same for UID2 and UID3 values. Each file on the command
+line is compared with this list, and if any of its UID values match a
+relevant value in the UID lists then that file will be included in the SPI
+file. If the file does not match any values it will be excluded.
+
+The -existinguid options allow the UID values that an existing SPI file
+should have to be specified. This will allow the possibility of checking
+that the correct type of files are being concatenated together.
+
+The -hide option can be used to mark a resource file as hidden in the SPI file.
+To mark a resource file as a hidden entry in the SPI file, the resource data 
+length will be written as 0.
+
+USAGE_EOF
+	}
+
+sub createSpi 
+	{
+	my @resourceFiles=();
+	my @hideresourceFiles=();
+	my $spiFileName;
+	my $targetDirectory;
+	my $existingSpiFileName;
+	my @uid;
+	my @uidLengths = (0, 0, 0, 0);
+	my @uid1;
+	my @uid2;
+	my @uid3;
+	my @existingUid = (-1,-1,-1,-1);
+	my $uidNumber;
+	my $defaultSpiFileName = "ecom-0-0.spi";
+	my $defaultTargetDirectory = &get_epocroot."epoc32\/tools\/";
+	my @defaultUid = (-1,-1,-1,-1);
+	
+##########################################################################################
+# Reading arguments phase
+##########################################################################################
+
+	foreach my $arg (@_) {
+		if ($arg =~ /^-t(.*)/i) { # set target SPI file
+			$spiFileName = $1;
+			next;
+			}
+		if ($arg =~ /^-d(.*)/i) { # set target ouput directory
+			my $tempDirectory=$1;
+			if((-d $tempDirectory) ) {
+				$targetDirectory = $tempDirectory;
+				next;
+				}
+				else
+				{
+				 print "Output directory \'",$tempDirectory,"\' does not exist.\n";
+				 exit(1);
+				 }				
+			}
+		if ($arg =~ /^-i(.*)/i) { # existing SPI file to use as a base
+			my $tempFileName = $1;
+			if((-e $tempFileName) && (!(-d $tempFileName))) {
+				$existingSpiFileName = $tempFileName;
+				next;
+				}
+			}
+		if ($arg =~ /^-uid([1-3])\=(.*)/i) {
+			$uid[$1-1][$uidLengths[$1-1]++] = $2;
+			next;
+			}
+		if($arg=~/^-existinguidcrc\=(.*)/i) {
+			$existingUid[3]=$1;
+			next;
+			}
+		if ($arg =~ /^-existinguid([1-3])\=(.*)/i) {
+			$existingUid[$1-1]=$2;
+			next;
+			}
+		if ($arg =~ /^-hide(.*)/i) { # Collect the files to be hidden
+			my $line = $1;
+			$line =~ s/,/ /g;
+			my @files = split(' ' , $line);
+			foreach my $file (@files)
+			{
+				push @hideresourceFiles, $file;
+			}
+			next;
+			}
+		if (-d $arg) {
+			if(($arg =~ m-^.:-) && ($arg =~ m-[\\\/]$-)) {
+				unless(opendir(DIRECTORY, $arg)) { print "Exiting: $arg"; exit; }
+				while (my $file=readdir(DIRECTORY)) {
+					my $newfile = $arg.$file;
+					if(!(-d $newfile)) {
+						push @resourceFiles, $newfile;
+					}
+				}
+				close(DIRECTORY);
+				next;
+				}
+			}
+		if ((-e $arg) && (!(-d $arg))) {
+			push @resourceFiles, $arg;
+			next;
+			}
+		if ($arg eq "-h") {
+			print_usage;
+			exit(1);
+		}	
+		print "Unknown command: $arg\n";
+	}
+
+#####################################################################################
+# UID phase
+#####################################################################################
+		
+	if(!(defined $spiFileName)) { #use default file name if none passed on command line
+		$spiFileName = $defaultSpiFileName;
+	}
+	if(!(defined $targetDirectory)) { #use default target dir if none passed on command line
+		$targetDirectory = $defaultTargetDirectory;
+	}
+	for(my $i=0;$i<3;$i++) { #if default UIDs specified then added to UID match lists
+		if($defaultUid[$i]>=0) {
+			$uid[$i][$uidLengths[$i]++] = $defaultUid[$i];
+		}
+	}
+	for(my $i=0;$i<3;$i++) { #makes sure UIDs are valid UIDs
+		my @tempUidArray;
+		my $iterator=0;
+		while(defined $uid[$i][$iterator]) {
+			my $convertedUid=convertUidFromText($uid[$i][$iterator]);
+			if ($convertedUid != -1) {
+				push @tempUidArray, binarize($convertedUid);
+			} else {
+				print "Invalid UID: $uid[$i][$iterator]\n";
+			}
+			$iterator++;
+		}
+		for(my $j=0;$i<scalar @tempUidArray;$j++) {
+			$uid[$i][$j]=$tempUidArray[$j];
+		}
+		for(my $j=scalar@tempUidArray;defined $uid[$i][$j];$j++) {
+			undef $uid[$i][$j];
+		}
+	}
+#####################################################################################
+# Phase to split up resource names
+#####################################################################################
+
+	my @resourceFilePaths;
+	my @resourceFileNames;
+	my @resourceExtensions;
+	my @filestobehidden;
+
+# To mark the resource files as hidden in the SPI file by writing the data length as zero
+	foreach my $file (@hideresourceFiles)
+	{
+		my $matchfound =0;
+		my $i=0;
+		for(;$i<scalar @resourceFiles && !$matchfound;$i++)
+		{
+			if (lc($file) eq lc($resourceFiles[$i]))
+			{
+				$filestobehidden[$i] = 1;
+				$matchfound =1;
+			}
+		}
+		if (!$matchfound)
+		{
+# Those files that are to be hidden in the SPI file but not existing in the SPI
+			if (! -e $file)
+			{
+				print "Warning: Hiding non-existent file $file\n";
+			}
+			push @resourceFiles,$file;
+			$filestobehidden[$i] = 1;
+		}
+	}
+	
+	for(my $i=0;$i<scalar @resourceFiles;$i++) {
+		if($resourceFiles[$i]=~m|\/|) {
+			if($resourceFiles[$i]=~m|(.*)\/([^\/]*)$|) {
+				$resourceFilePaths[$i]=$1;
+				$resourceFileNames[$i]=$2;
+			}
+			if($resourceFileNames[$i]=~m|(.*)\.([^\.]*)|) {
+				$resourceFileNames[$i]= $1;
+				$resourceExtensions[$i]=$2;
+			}
+		} else {
+			$resourceFilePaths[$i]="";
+			if($resourceFiles[$i]=~m|(.*)\.([^\.]*)|) {
+				$resourceFileNames[$i]= $1;
+				$resourceExtensions[$i]=$2;
+			}
+		}
+	}
+	my %uid2values; #hash to hold UID2 values for each type of SPI file
+	$uid2values{"ecom"} = 270556204;
+
+##########################################################
+# Existing file stage
+##########################################################
+
+	my @spiUid = (270556203, 0, 0); #holds spi values (including CRC value)
+	foreach my $key (keys(%uid2values)) { #searches through SPI types to match UID2 value
+		if($spiFileName =~/^$key/) {
+			$spiUid[1]=$uid2values{$key};
+		}
+	}
+	$spiUid[3] = uidcrc($spiUid[0], $spiUid[1], $spiUid[2]);
+	my $total=0; #used to keep track of position in SPI file
+	my $buffer;
+	my $spifile=File::Spec->catpath( "", $targetDirectory, $spiFileName );
+ 	open OUTPUTFILE, ">$spifile" or die $!;
+	binmode (OUTPUTFILE);
+	if($existingSpiFileName) {
+		open EXISTINGFILE, "$existingSpiFileName" or die $!;
+		binmode (EXISTINGFILE);
+
+		my @fileNameLengths;
+		my @fileLengths;
+		my @fileNames;
+		my @fileContents;
+
+		read(EXISTINGFILE,$buffer,4);
+		read(EXISTINGFILE,$buffer,4);
+		if(bytes2dec($buffer)!=$spiUid[1]) {
+			print "Incompatible SPI files.\n";
+		}
+		read(EXISTINGFILE,$buffer,24);
+		$total=32;
+		my $existingSpiFileSize = (stat(EXISTINGFILE))[7];
+		while($total<$existingSpiFileSize) { #loop to store information from files which are not being replaced
+			read(EXISTINGFILE,$buffer,4);
+			push @fileNameLengths, bytes2dec($buffer);
+			read(EXISTINGFILE,$buffer,4);
+			push @fileLengths, bytes2dec($buffer);
+			read(EXISTINGFILE,$buffer,$fileNameLengths[$#fileNameLengths]);
+			push @fileNames, $buffer;
+			$total=$total+8+$fileNameLengths[$#fileNameLengths]+$fileLengths[$#fileLengths];
+			my $padding = (4-(($fileNameLengths[$#fileNameLengths]+$fileLengths[$#fileLengths])%4))%4;
+			read(EXISTINGFILE,$buffer,$fileLengths[$#fileLengths]+$padding);
+			push @fileContents, $buffer;
+			$total += (4-($total%4))%4;			
+		}
+		close EXISTINGFILE;	
+		#next part prints to OUTPUTFILE the header and files which are not being replaced
+		print OUTPUTFILE binarize($spiUid[0]) . binarize($spiUid[1]) . binarize($spiUid[2]) . binarize($spiUid[3]);
+		printZeroes(16);
+		$total=32;
+		for(my $i=0; $i<scalar @fileNames; $i++) {
+			my $flag=1;
+			for(my $j=0; $j<scalar @resourceFileNames && $flag==1; $j++) {
+				if($fileNames[$i] eq $resourceFileNames[$j]) {
+					$flag=0;
+				}
+			}
+			if($flag) {
+				print OUTPUTFILE binarize($fileNameLengths[$i]) . binarize($fileLengths[$i]) . $fileNames[$i] . $fileContents[$i];
+				$total=$total+8+length($fileNames[$i])+length($fileContents[$i]);
+			}
+		}
+	} else { #prints header for target SPI file if there is no existing SPI file
+		print OUTPUTFILE binarize($spiUid[0]) . binarize($spiUid[1]) . binarize($spiUid[2]) . binarize($spiUid[3]);
+		printZeroes(16);
+		$total=32;
+	}
+
+####################################################################
+# Appending new data files to the SPI file
+####################################################################
+
+	my $resourceFileSize;
+	my $resourceFileSizeInBinary;
+	my $resourceFileNameSize;
+	my $resourceFileNameSizeInBinary;
+	for(my $i=0; $i<scalar @resourceExtensions;$i++) {
+# To mark the resource files as hidden in the SPI file by writing the data length as zero
+	   if ($filestobehidden[$i] == 1)
+	   {
+		$resourceFileNameSize = length($resourceFileNames[$i]);
+		$resourceFileNameSizeInBinary = binarize($resourceFileNameSize);
+		$resourceFileSize = 0;
+		$resourceFileSizeInBinary = binarize($resourceFileSize);
+		print OUTPUTFILE $resourceFileNameSizeInBinary . $resourceFileSizeInBinary . $resourceFileNames[$i];
+		$total+=$resourceFileNameSize;
+		my $padding = (4-(($resourceFileSize + $resourceFileNameSize)%4))%4;
+		printZeroes($padding);
+		$total+=$padding;
+	   }
+	   else
+	   {
+		open RESOURCEFILE, "<$resourceFiles[$i]";
+		binmode(RESOURCEFILE);
+		my @fileUid; #stores UIDs from particular data file
+		my $fileUid1;
+		my $fileUid2;
+		my $fileUid3;
+		read(RESOURCEFILE,$fileUid[0],4);
+		read(RESOURCEFILE,$fileUid[1],4);
+		read(RESOURCEFILE,$fileUid[2],4);
+		my $uidFlag=0; #changes to 1 if a UID value in data file matches a specified UID value
+		my $uidExists=1; #changes to 1 if there are specified UIDs to match to
+		for(my $j=0;$j<3 && (!$uidFlag);$j++) {
+			my $k=0;
+			while(defined $uid[$j][$k] && (!$uidFlag)) {
+				$uidExists=0;
+				if($uid[$j][$k] eq bin2hex($fileUid[$j])) {
+					$uidFlag=1;
+				}
+				$k++;
+			}
+		}	
+		if(($uidFlag) || ($uidExists)) { #if suitable UIDs writes data file to SPI file
+			$resourceFileSize = (stat(RESOURCEFILE))[7];
+			$resourceFileNameSize = length($resourceFileNames[$i]);
+			$resourceFileNameSizeInBinary = binarize($resourceFileNameSize);
+			$resourceFileSizeInBinary = binarize($resourceFileSize);
+			print OUTPUTFILE $resourceFileNameSizeInBinary . $resourceFileSizeInBinary . $resourceFileNames[$i];
+			print OUTPUTFILE "$fileUid[0]$fileUid[1]$fileUid[2]";
+			while(read(RESOURCEFILE,$buffer,1)) {
+				print OUTPUTFILE $buffer;
+			}
+			$total+=$resourceFileSize;
+			$total+=8;
+			$total+=$resourceFileNameSize;
+			my $padding = (4-(($resourceFileSize + $resourceFileNameSize)%4))%4;
+			printZeroes($padding);
+			$total+=$padding;
+		}
+	   }
+	}
+	print "Created $spiFileName\n";
+}
+
+
+1;
--- a/imgtools/imgcheck/group/bld.inf	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/group/bld.inf	Tue Jun 29 14:52:54 2010 +0800
@@ -1,32 +1,34 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-PRJ_PLATFORMS
-TOOLS2
-
-// These libraries needs to be exported
-PRJ_EXPORTS
-../libxml/lib/libxml2.a			/epoc32/release/tools2/rel/libxml2.a
-../libxml/lib/libxml2.a			/epoc32/release/tools2/deb/libxml2.a
-../src/imgcheck.xsl			/epoc32/tools/imgcheck.xsl
-./imgcheck.pl				/epoc32/tools/imgcheck.pl
-./imgcheck.cmd				/epoc32/tools/imgcheck.cmd
-
-PRJ_MMPFILES
-imgutils
-imgcheck
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+PRJ_PLATFORMS
+TOOLS2
+
+// These libraries needs to be exported
+PRJ_EXPORTS
+#ifndef TOOLS2_LINUX
+../libxml/lib/libxml2.a			/epoc32/release/tools2/rel/libxml2.a
+../libxml/lib/libxml2.a			/epoc32/release/tools2/deb/libxml2.a
+#endif
+../src/imgcheck.xsl			/epoc32/tools/imgcheck.xsl
+./imgcheck.pl				/epoc32/tools/imgcheck.pl
+./imgcheck.cmd				/epoc32/tools/imgcheck.cmd
+
+PRJ_MMPFILES
+imgutils
+imgcheck
--- a/imgtools/imgcheck/group/imgcheck.mmp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/group/imgcheck.mmp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,42 +1,47 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-TARGET        imgcheck.exe
-TARGETTYPE    exe
-
-SOURCEPATH	../src
-SOURCE		cmdlinehandler.cpp depchecker.cpp hash.cpp main.cpp
-SOURCE		imgcheckmanager.cpp sidchecker.cpp vidchecker.cpp common.cpp checker.cpp reporter.cpp
-SOURCE		exceptionimplementation.cpp exceptionreporter.cpp
-SOURCE 		cmdlinewriter.cpp xmlwriter.cpp dbgflagchecker.cpp
-USERINCLUDE ../libimgutils/inc ../inc ../../imglib/compress
-USERINCLUDE   ../../imglib/boostlibrary
-
-OS_LAYER_SYSTEMINCLUDE_SYMBIAN
-SYSTEMINCLUDE ../libxml ../ 
-
-SYSTEMINCLUDE ../../imglib/inc ../../romtools/rofsbuild
-
-STATICLIBRARY imgutils xml2 wsock32 stlport.5.1 patchdataprocessor
-#ifdef TOOLS2_LINUX
-STATICLIBRARY   boost_thread-mgw34-mt-1_39_linux
-OPTION    GCC -pthread -O2 -Wno-uninitialized
-#else
-STATICLIBRARY   boost_thread-mgw34-mt-1_39_win32
-OPTION    GCC -mthreads -O2 -Wno-uninitialized
-#endif
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+macro _STLP_USE_STATIC_LIB
+TARGET        imgcheck.exe
+TARGETTYPE    exe
+
+SOURCEPATH	../src
+SOURCE		cmdlinehandler.cpp depchecker.cpp hash.cpp main.cpp
+SOURCE		imgcheckmanager.cpp sidchecker.cpp vidchecker.cpp common.cpp checker.cpp reporter.cpp
+SOURCE		exceptionimplementation.cpp exceptionreporter.cpp
+SOURCE 		cmdlinewriter.cpp xmlwriter.cpp dbgflagchecker.cpp
+USERINCLUDE ../libimgutils/inc ../inc ../../imglib/compress
+USERINCLUDE   ../../imglib/boostlibrary
+USERINCLUDE   ../../imglib/boostlibrary/boost
+
+OS_LAYER_SYSTEMINCLUDE_SYMBIAN
+#ifdef TOOL2_LINUX
+SYSTEMINCLUDE /usr/include/libxml2
+#else
+SYSTEMINCLUDE ../libxml ../ 
+#endif
+SYSTEMINCLUDE ../../imglib/inc ../../romtools/rofsbuild
+
+STATICLIBRARY imgutils patchdataprocessor boost_thread-1.39 boost_filesystem-1.39  boost_system-1.39 stlport.5.1
+
+#ifdef TOOLS2_LINUX
+OPTION    GCC -pthread -O2 -Wno-uninitialized -lxml2 -lz -lm 
+//LINKEROPTION GCC -lxml2 -lz -lm 
+#else
+STATICLIBRARY	xml2 wsock32
+OPTION    GCC -mthreads -O2 -Wno-uninitialized
+#endif
+
--- a/imgtools/imgcheck/group/imgcheck.mrp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/group/imgcheck.mrp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,13 +1,13 @@
 component	dev_build_imgtools_imgcheck
 
-source		\src\tools\dev\build\imgtools\imgcheck\inc
-source		\src\tools\dev\build\imgtools\imgcheck\src
-source		\src\tools\dev\build\imgtools\imgcheck\libimgutils
-source		\src\tools\dev\build\imgtools\imgcheck\libxml
-source		\src\tools\dev\build\imgtools\imgcheck\group
-binary		\src\tools\dev\build\imgtools\imgcheck\group all
-exports		\src\tools\dev\build\imgtools\imgcheck\group
+source		\src\tools\build\imgtools\imgcheck\inc
+source		\src\tools\build\imgtools\imgcheck\src
+source		\src\tools\build\imgtools\imgcheck\libimgutils
+source		\src\tools\build\imgtools\imgcheck\libxml
+source		\src\tools\build\imgtools\imgcheck\group
+binary		\src\tools\build\imgtools\imgcheck\group all
+exports		\src\tools\build\imgtools\imgcheck\group
 
-notes_source	\src\tools\dev\build\imgtools\imgcheck\group\release.txt
+notes_source	\src\tools\build\imgtools\imgcheck\group\release.txt
 
 ipr T 
--- a/imgtools/imgcheck/group/imgutils.mmp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/group/imgutils.mmp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,61 +1,64 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-TARGET        libimgutils.a
-TARGETTYPE    lib
-
-SOURCEPATH	..\..\imglib\compress
-SOURCE		byte_pair.cpp pagedcompress.cpp
-USERINCLUDE	..\..\imglib\compress
-
-SOURCEPATH	..\..\imglib\e32image
-SOURCE		e32image.cpp
-USERINCLUDE	..\..\imglib\e32image
-
-SOURCEPATH	..\..\imglib\e32image\deflate
-SOURCE		inflate.cpp compress.cpp decode.cpp deflate.cpp panic.cpp encode.cpp
-USERINCLUDE	..\..\imglib\e32image\deflate
-
-SOURCEPATH	..\..\imglib\host
-SOURCE		h_file.cpp h_mem.cpp h_utl.cpp
-USERINCLUDE	..\..\imglib\inc
-
-SOURCEPATH	..\..\imglib\e32uid
-SOURCE		e32uid.cpp 
-USERINCLUDE	..\..\imglib\e32uid
-
-SOURCEPATH	..\..\romtools\rofsbuild
-SOURCE		r_coreimage.cpp r_build.cpp
-USERINCLUDE	..\..\romtools\rofsbuild ..\..\imglib\patchdataprocessor\include
-
-SOURCEPATH	..\libimgutils\src
-SOURCE		romreader.cpp imagereader.cpp e32reader.cpp rofsreader.cpp romimageheader.cpp
-SOURCE		rofsimage.cpp utils.cpp dirreader.cpp
-USERINCLUDE	..\libimgutils\inc
-USERINCLUDE   ..\..\imglib\boostlibrary
-
-OS_LAYER_SYSTEMINCLUDE_SYMBIAN
-
-SYSTEMINCLUDE ..\libimgutils\inc
-SYSTEMINCLUDE ..\..\imglib\inc ..\..\romtools\rofsbuild
-
-#ifdef TOOLS2_LINUX
-OPTION    GCC -pthread -O2 -Wno-uninitialized
-#else
-OPTION    GCC -mthreads -O2 -Wno-uninitialized
-#endif
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+TARGET        libimgutils.a
+TARGETTYPE    lib
+
+SOURCEPATH	..\..\imglib\compress
+SOURCE		byte_pair.cpp pagedcompress.cpp
+USERINCLUDE	..\..\imglib\compress
+
+SOURCEPATH	..\..\imglib\e32image
+SOURCE		e32image.cpp
+USERINCLUDE	..\..\imglib\e32image
+
+SOURCEPATH	..\..\imglib\e32image\deflate
+SOURCE		inflate.cpp compress.cpp decode.cpp deflate.cpp panic.cpp encode.cpp
+USERINCLUDE	..\..\imglib\e32image\deflate
+
+SOURCEPATH	..\..\imglib\host
+SOURCE		h_file.cpp h_mem.cpp h_utl.cpp utf16string.cpp
+USERINCLUDE	..\..\imglib\inc
+
+SOURCEPATH	..\..\imglib\e32uid
+SOURCE		e32uid.cpp 
+USERINCLUDE	..\..\imglib\e32uid
+
+SOURCEPATH	..\..\romtools\rofsbuild\src\cache
+SOURCE cachemanager.cpp cacheexception.cpp cache.cpp cacheablelist.cpp cachevalidator.cpp cachegenerator.cpp cacheentry.cpp
+
+SOURCEPATH	..\..\romtools\rofsbuild
+SOURCE		r_coreimage.cpp r_build.cpp 
+USERINCLUDE	..\..\romtools\rofsbuild ..\..\imglib\patchdataprocessor\include ..\..\romtools\rofsbuild\inc
+
+SOURCEPATH	..\libimgutils\src
+SOURCE		romreader.cpp imagereader.cpp e32reader.cpp rofsreader.cpp romimageheader.cpp
+SOURCE		rofsimage.cpp utils.cpp dirreader.cpp
+USERINCLUDE	..\libimgutils\inc
+USERINCLUDE   ..\..\imglib\boostlibrary
+USERINCLUDE   ..\..\imglib\boostlibrary\boost
+
+OS_LAYER_SYSTEMINCLUDE_SYMBIAN
+
+SYSTEMINCLUDE ..\libimgutils\inc
+SYSTEMINCLUDE ..\..\imglib\inc ..\..\romtools\rofsbuild ..\..\romtools\rofsbuild\inc
+
+#ifdef TOOLS2_LINUX
+OPTION    GCC -pthread -O2 -Wno-uninitialized
+#else
+OPTION    GCC -mthreads -O2 -Wno-uninitialized  
+#endif
--- a/imgtools/imgcheck/group/release.txt	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/group/release.txt	Tue Jun 29 14:52:54 2010 +0800
@@ -1,35 +1,40 @@
-Version V1.3.5
-===============
-Made by Zhi Dou 19/10/2009
-  1. Minor change for copyright from SPL to EPL.
-
-Version V1.3.4
-===============
-Made by Ross Qin 21/09/2009
-  1. DEF142151 Imgcheck run has failed in MSF00197 vtb92sf build 
-
-Version V1.3.3
-===============
-Made by Ross Qin 14/09/2009
-  1. DPDEF141843 Coverity defects about Resource Leak and Delete Array. 
-
-Version V1.3.1
-===============
-Made by Zhi Dou 19/08/2009
-  1. DPDEF141566 Textshell ROM fails to build due to 'cannot open obey file' 
-
-Version V1.3.0
-===============
-Made by Zhi Dou 31/07/2009
-  1. PREQ2465's REQ12562 Byte-pair compression update
-
-Version V1.2.3
-===============
-Made by Zhi Dou 29/07/2009
-  1. DPDEF141175 - Removal of the "-w" option in imgtools .mmp files results in a lot of warnings 
-
-NOTESRC_RELEASER
-Nokia Corporation.
-
-NOTESRC_RELEASE_REASON
-Imgcheck release.
+version v1.4.0
+===============
+Released by Zheng Shen, 22/02/2010
+	1) DPDEF144562	Build Tools cannot be built in Linux
+
+Version V1.3.5
+===============
+Made by Zhi Dou 19/10/2009
+  1. Minor change for copyright from SPL to EPL.
+
+Version V1.3.4
+===============
+Made by Ross Qin 21/09/2009
+  1. DEF142151 Imgcheck run has failed in MSF00197 vtb92sf build 
+
+Version V1.3.3
+===============
+Made by Ross Qin 14/09/2009
+  1. DPDEF141843 Coverity defects about Resource Leak and Delete Array. 
+
+Version V1.3.1
+===============
+Made by Zhi Dou 19/08/2009
+  1. DPDEF141566 Textshell ROM fails to build due to 'cannot open obey file' 
+
+Version V1.3.0
+===============
+Made by Zhi Dou 31/07/2009
+  1. PREQ2465's REQ12562 Byte-pair compression update
+
+Version V1.2.3
+===============
+Made by Zhi Dou 29/07/2009
+  1. DPDEF141175 - Removal of the "-w" option in imgtools .mmp files results in a lot of warnings 
+
+NOTESRC_RELEASER
+Nokia Corporation.
+
+NOTESRC_RELEASE_REASON
+Imgcheck release.
--- a/imgtools/imgcheck/imagechekunittest/testcode/cmdlinehandletest.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/imagechekunittest/testcode/cmdlinehandletest.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,1469 +1,1469 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* CMDLINEHANDLERTEST.CPP
-* Unittest cases for command line handler file.
-* Note : Tested by passing different images.
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-#include <cppunit/config/SourcePrefix.h>
-#include "cmdlinehandlertest.h"
-
-CPPUNIT_TEST_SUITE_REGISTRATION( CTestCmdHandler );
-
-#include "depchecker.h"
-#include "exceptionreporter.h"
-
-
-/**
-Test the cmdhandler output without providing any arguments.
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestWithEmptyArugument()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "test"};
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(0,argvect);
-		if(val == EQuit)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		status = 0;
-    }
-	delete cmdInput;
-	CPPUNIT_ASSERT(status != 0);
-}
-
-
-/**
-Test the cmdhandler output by providing wrong option.
-Note: Refer the code coverage output for percentage of check.
-      Pass the unknown option. '-l'
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestWithWrongArugument()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker","-s=" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
-		if(val == ESuccess)
-		{
-			status = 0;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 1;
-    }
-	delete cmdInput;
-	CPPUNIT_ASSERT(status != 0);
-}
-
-
-/**
-Test the cmdhandler output by providing invalid image.
-Note: Refer the code coverage output for percentage of check.
-      Pass the invalid image. 'invalid.img'
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestWithInvalidImg()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker","S:/GT0415/cppunit/imgcheck_unittest/imgs/invalid.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
-		int x = 0;
-		if(val == ESuccess)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-	CPPUNIT_ASSERT(status != 0);
-}
-
-
-/**
-Test the cmdhandler output for getting the report flag.
-Note: Refer the code coverage output for percentage of check.
-      Pass the valid images.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestWithGetReportFlag()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker","-a", "-q", "-x", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rom.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(5,argvect);
-		unsigned int flag = cmdInput->ReportFlag();             
-		if((flag & QuietMode) && (flag & KXmlReport) && (flag & KAll))
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-	CPPUNIT_ASSERT(status != 0);
-}
-
-
-/**
-Test the cmdhandler output for getting the xml report name.
-Note: Refer the code coverage output for percentage of check.
-      Pass the valid images.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestWithGetXmlReportName()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker","--all", "-o=test.xml", "--xml","--dep","--vid", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rom.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(7,argvect);
-		String xmlName = cmdInput->XmlReportName();  
-		if(xmlName == String("test.xml"))
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-	CPPUNIT_ASSERT(status != 0);
-}
-
-
-/**
-Test the cmdhandler output by providing valid image without any options.
-Note: Refer the code coverage output for percentage of check.
-      Pass the valid image. 'rom.img'
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestWithValidImg()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker","S:/GT0415/cppunit/imgcheck_unittest/imgs/rom.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
-		if(val == ESuccess)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-	CPPUNIT_ASSERT(status != 0);
-}
-
-
-/**
-Test the cmdhandler output by providing invalid option.
-Note: Refer the code coverage output for percentage of check.
-      Pass the invalid image. 'invalid.img'
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestWithInvalidOption()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker","---q","S:/GT0415/cppunit/imgcheck_unittest/imgs/rom.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == ESuccess)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-
-/**
-Test the cmdhandler output by help option.
-Note: Refer the code coverage output for percentage of check.
-      Pass the valid image. 'rom.img'
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestWithHelpOption()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker","-H" };	
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
-		if(val == EQuit)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-	CPPUNIT_ASSERT(status != 0);
-}
-
-/**
-Test the cmdhandler output by passing vidlist long and suppress short options.
-Note: Refer the code coverage output for percentage of check.
-      Pass the valid image. 'rom.img'
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestWithVidlist_supressOption()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker","-x","--vidlist=0x70000001","-s=sid,dep","--vid","S:/GT0415/cppunit/imgcheck_unittest/imgs/rom.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(6,argvect);
-		if(val == ESuccess)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-	CPPUNIT_ASSERT(status != 0);
-}
-
-/**
-Test the cmdhandler output by passing vidlist short and suppress long option.
-Note: Refer the code coverage output for percentage of check.
-      Pass the valid image. 'rom.img'
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestWithVidlist_supressOption1()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker","--sid", "-x","--vidlist=1879048193","--SUPPRESS=dep","--all", "--vid","--output=tst","S:/GT0415/cppunit/imgcheck_unittest/imgs/rom.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(9,argvect);
-		if(val == ESuccess)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-	CPPUNIT_ASSERT(status != 0);
-}
-
-/**
-Test the cmdhandler output by passing all option.
-Note: Refer the code coverage output for percentage of check.
-      Pass the valid image. 'rom.img'
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestWithAllOption()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker","-x","--vidlist=0x70000001,0","--vid","--sid","--dep","--all","-o=c:\tst","S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img","S:/GT0415/cppunit/imgcheck_unittest/imgs/rom.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(10,argvect);
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output by provinding options but no input image.
-Note: Refer the code coverage output for percentage of check.		
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestForValidateArgumentNoImage()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "-a", "--vidlist=0s20000001" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == ESuccess)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler by provinding quiet option when not generating the XML file.
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestForValidateArgument()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "-q", "-a", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(4,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler by provinding XML file name when not generating the XML report.
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestForValidateArgumentwithoutXMLoutput()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "-a", "-o=c:/report1", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(4,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler by provinding VID value but VID validation is suppressed.
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestForValidateArgumentwithVIDVALandVIDsuppressed()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "-s=vid", "--vidlist=0x70000001", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(4,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding any image.
-Note: Refer the code coverage output for percentage of check.
-		Pass the valid image.(rofs.img).
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestForValidateArgumentwithAllsuppressed()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "-s=dep,sid,vid", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding any image.
-Note: Refer the code coverage output for percentage of check.
-		Pass the valid image.(rofs.img).
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestForValidateArgumentwithValueExpected()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "-s", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding any image.
-Note: Refer the code coverage output for percentage of check.
-		Pass the valid image.(rofs.img).
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestForValidateArgumentwithValueUnExpected()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "-x=xyz", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding any image.
-Note: Refer the code coverage output for percentage of check.
-		Pass the valid image.(rofs.img).
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestForValidateArgumentwithValueExpectedareMore()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "-o=test,test1", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding any image.
-Note: Refer the code coverage output for percentage of check.
-		Pass the valid image.(rofs.img).
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestForwithoutInput()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(1,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding any image.
-Note: Refer the code coverage output for percentage of check.
-		Pass the valid image.(rofs.img).
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestVerbose()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--verbose", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding any image.
-Note: Refer the code coverage output for percentage of check.
-		Pass the valid image.(rofs.img).
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestSIDALLOption()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--sidall", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding any image.
-Note: Refer the code coverage output for percentage of check.
-		Pass the valid image.(rofs.img).
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestSIDALLandSuppressSIDOption()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--sidall", "-s=sid", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(4,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding any image.
-Note: Refer the code coverage output for percentage of check.
-		Pass the valid image.(rofs.img).
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestUnknownOption()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "-j", "-b", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(4,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding any image.
-Note: Refer the code coverage output for percentage of check.
-		Pass the valid image.(rofs.img).
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestInvalidVidListOption()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--vidlist=7000abcd", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding any image for invalid supression value.
-Note: Refer the code coverage output for percentage of check.
-		Pass the valid image.(rofs.img).
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestInvalidSupressOption()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--vid", "-s=abcd", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(4,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding enable option without any image.
-Note: Refer the code coverage output for percentage of check.
-		Pass the valid image.(rofs.img).
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestEnableOption()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--vid" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding vidlist with zero and any image.
-Note: Refer the code coverage output for percentage of check.
-		Pass the valid image.(rofs.img).
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestVidListOptionwithZeroValue()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--vidlist=0x0", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding vidlist with invalid value and any image.
-Note: Refer the code coverage output for percentage of check.
-		Pass the valid image.(rofs.img).
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestVidListOptionwithinvalidValue()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--vidlist=0xfffffffff", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding vidlist with invalid value and any image.
-Note: Refer the code coverage output for percentage of check.
-		Pass the valid image.(rofs.img).
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestVidListOptionwithinvalidValue1()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--vidlist=0x00ag,4294967299", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding dbg with invalid value and any image.
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestDbgOptionwithinvalidValue()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--dbg=xyz", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding dbg with = but no value.
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestDbgOptionwithoutValue()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--dbg=", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding e32input with = 
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::Teste32inputOptionwithValue()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--e32input=", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding e32input a image but not a E32 input.
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::Teste32inputOptionwithimg()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--e32input", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding valid images along with e32input option
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::Teste32inputOptionwithimg1()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rom.img", "--e32input" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(4,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding invalid e32input option.
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::Teste32inputOptionwithinvalidoption()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img", "--e3input" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding invalid e32input option.
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::Teste32inputOptionwithinvalidoption1()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "S:/epoc32/release/armv5/udeb", "--e2input" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding = to -n otpions.
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestnocheckOptionwithinvalidoption()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "S:/epoc32/release/armv5/udeb", "-n=" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding = to --nocheck option.
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestnocheckOptionwithinvalidoption1()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "S:/epoc32/release/armv5/udeb", "--nocheck=" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding nocheck option with single '-'
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestnocheckOptionwithinvalidoption2()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "S:/epoc32/release/armv5/udeb", "-nocheck" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding '--' to nocehck otpion
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestnocheckOptionwithinvalidoption3()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "S:/epoc32/release/armv5/udeb", "--n" };
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding valid E32input but not enabling any validations.
-Note: Refer the code coverage output for percentage of check.
-		Pass the valid image.(rofs.img).
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestnocheckOptionwithNoChecksEnabled()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--e32input", "S:/epoc32/release/armv5/udeb"};
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding valid E32input and ALL option but not enabling any validations
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TestnocheckOptionwithNoChecksEnabled1()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--e32input", "S:/epoc32/release/armv5/udeb", "--all"};
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(4,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding E32input but no directory nor a E32 file.
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TesttocheckOptionwithNoImgandE32input()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--e32input"};
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-/**
-Test the cmdhandler output(xml) by provinding invalid option.
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TesttocheckOptionPrefix()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--"};
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-
-/**
-Test the cmdhandler output(xml) by provinding invalid option and no image.
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TesttocheckInvalidOption()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--sidalll"};
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-
-/**
-Test the cmdhandler output(xml) by provinding invalid option and no image.
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TesttocheckInvalidOption1()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--depp"};
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
-
-
-/**
-Test the cmdhandler output(xml) by provinding invalid option and no image.
-Note: Refer the code coverage output for percentage of check.
-
-@internalComponent
-@released
-*/
-void CTestCmdHandler::TesttocheckInvalidOption2()
-{
-	int status = 0;
-	CmdLineHandler* cmdInput;
-	try
-	{
-		char* argvect[] = { "imgchecker", "--e32inputt"};
-		cmdInput = new CmdLineHandler();
-		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
-		if(val == EXIT_FAILURE)
-		{
-			status = 1;
-		}
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		status = 0;
-    }
-	delete cmdInput;
-}
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* CMDLINEHANDLERTEST.CPP
+* Unittest cases for command line handler file.
+* Note : Tested by passing different images.
+*
+*/
+
+
+/**
+ @file
+ @internalComponent
+ @released
+*/
+#include <cppunit/config/SourcePrefix.h>
+#include "cmdlinehandlertest.h"
+
+CPPUNIT_TEST_SUITE_REGISTRATION( CTestCmdHandler );
+
+#include "depchecker.h"
+#include "exceptionreporter.h"
+
+
+/**
+Test the cmdhandler output without providing any arguments.
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestWithEmptyArugument()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "test"};
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(0,argvect);
+		if(val == EQuit)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		status = 0;
+    }
+	delete cmdInput;
+	CPPUNIT_ASSERT(status != 0);
+}
+
+
+/**
+Test the cmdhandler output by providing wrong option.
+Note: Refer the code coverage output for percentage of check.
+      Pass the unknown option. '-l'
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestWithWrongArugument()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker","-s=" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
+		if(val == ESuccess)
+		{
+			status = 0;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 1;
+    }
+	delete cmdInput;
+	CPPUNIT_ASSERT(status != 0);
+}
+
+
+/**
+Test the cmdhandler output by providing invalid image.
+Note: Refer the code coverage output for percentage of check.
+      Pass the invalid image. 'invalid.img'
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestWithInvalidImg()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker","S:/GT0415/cppunit/imgcheck_unittest/imgs/invalid.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
+		int x = 0;
+		if(val == ESuccess)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+	CPPUNIT_ASSERT(status != 0);
+}
+
+
+/**
+Test the cmdhandler output for getting the report flag.
+Note: Refer the code coverage output for percentage of check.
+      Pass the valid images.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestWithGetReportFlag()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker","-a", "-q", "-x", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rom.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(5,argvect);
+		unsigned int flag = cmdInput->ReportFlag();             
+		if((flag & QuietMode) && (flag & KXmlReport) && (flag & KAll))
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+	CPPUNIT_ASSERT(status != 0);
+}
+
+
+/**
+Test the cmdhandler output for getting the xml report name.
+Note: Refer the code coverage output for percentage of check.
+      Pass the valid images.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestWithGetXmlReportName()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker","--all", "-o=test.xml", "--xml","--dep","--vid", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rom.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(7,argvect);
+		string xmlName = cmdInput->XmlReportName();  
+		if(xmlName == string("test.xml"))
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+	CPPUNIT_ASSERT(status != 0);
+}
+
+
+/**
+Test the cmdhandler output by providing valid image without any options.
+Note: Refer the code coverage output for percentage of check.
+      Pass the valid image. 'rom.img'
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestWithValidImg()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker","S:/GT0415/cppunit/imgcheck_unittest/imgs/rom.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
+		if(val == ESuccess)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+	CPPUNIT_ASSERT(status != 0);
+}
+
+
+/**
+Test the cmdhandler output by providing invalid option.
+Note: Refer the code coverage output for percentage of check.
+      Pass the invalid image. 'invalid.img'
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestWithInvalidOption()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker","---q","S:/GT0415/cppunit/imgcheck_unittest/imgs/rom.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == ESuccess)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+
+/**
+Test the cmdhandler output by help option.
+Note: Refer the code coverage output for percentage of check.
+      Pass the valid image. 'rom.img'
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestWithHelpOption()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker","-H" };	
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
+		if(val == EQuit)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+	CPPUNIT_ASSERT(status != 0);
+}
+
+/**
+Test the cmdhandler output by passing vidlist long and suppress short options.
+Note: Refer the code coverage output for percentage of check.
+      Pass the valid image. 'rom.img'
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestWithVidlist_supressOption()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker","-x","--vidlist=0x70000001","-s=sid,dep","--vid","S:/GT0415/cppunit/imgcheck_unittest/imgs/rom.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(6,argvect);
+		if(val == ESuccess)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+	CPPUNIT_ASSERT(status != 0);
+}
+
+/**
+Test the cmdhandler output by passing vidlist short and suppress long option.
+Note: Refer the code coverage output for percentage of check.
+      Pass the valid image. 'rom.img'
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestWithVidlist_supressOption1()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker","--sid", "-x","--vidlist=1879048193","--SUPPRESS=dep","--all", "--vid","--output=tst","S:/GT0415/cppunit/imgcheck_unittest/imgs/rom.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(9,argvect);
+		if(val == ESuccess)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+	CPPUNIT_ASSERT(status != 0);
+}
+
+/**
+Test the cmdhandler output by passing all option.
+Note: Refer the code coverage output for percentage of check.
+      Pass the valid image. 'rom.img'
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestWithAllOption()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker","-x","--vidlist=0x70000001,0","--vid","--sid","--dep","--all","-o=c:\tst","S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img","S:/GT0415/cppunit/imgcheck_unittest/imgs/rom.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(10,argvect);
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output by provinding options but no input image.
+Note: Refer the code coverage output for percentage of check.		
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestForValidateArgumentNoImage()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "-a", "--vidlist=0s20000001" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == ESuccess)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler by provinding quiet option when not generating the XML file.
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestForValidateArgument()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "-q", "-a", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(4,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler by provinding XML file name when not generating the XML report.
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestForValidateArgumentwithoutXMLoutput()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "-a", "-o=c:/report1", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(4,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler by provinding VID value but VID validation is suppressed.
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestForValidateArgumentwithVIDVALandVIDsuppressed()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "-s=vid", "--vidlist=0x70000001", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(4,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding any image.
+Note: Refer the code coverage output for percentage of check.
+		Pass the valid image.(rofs.img).
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestForValidateArgumentwithAllsuppressed()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "-s=dep,sid,vid", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding any image.
+Note: Refer the code coverage output for percentage of check.
+		Pass the valid image.(rofs.img).
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestForValidateArgumentwithValueExpected()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "-s", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding any image.
+Note: Refer the code coverage output for percentage of check.
+		Pass the valid image.(rofs.img).
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestForValidateArgumentwithValueUnExpected()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "-x=xyz", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding any image.
+Note: Refer the code coverage output for percentage of check.
+		Pass the valid image.(rofs.img).
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestForValidateArgumentwithValueExpectedareMore()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "-o=test,test1", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding any image.
+Note: Refer the code coverage output for percentage of check.
+		Pass the valid image.(rofs.img).
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestForwithoutInput()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(1,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding any image.
+Note: Refer the code coverage output for percentage of check.
+		Pass the valid image.(rofs.img).
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestVerbose()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--verbose", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding any image.
+Note: Refer the code coverage output for percentage of check.
+		Pass the valid image.(rofs.img).
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestSIDALLOption()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--sidall", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding any image.
+Note: Refer the code coverage output for percentage of check.
+		Pass the valid image.(rofs.img).
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestSIDALLandSuppressSIDOption()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--sidall", "-s=sid", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(4,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding any image.
+Note: Refer the code coverage output for percentage of check.
+		Pass the valid image.(rofs.img).
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestUnknownOption()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "-j", "-b", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(4,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding any image.
+Note: Refer the code coverage output for percentage of check.
+		Pass the valid image.(rofs.img).
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestInvalidVidListOption()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--vidlist=7000abcd", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding any image for invalid supression value.
+Note: Refer the code coverage output for percentage of check.
+		Pass the valid image.(rofs.img).
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestInvalidSupressOption()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--vid", "-s=abcd", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(4,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding enable option without any image.
+Note: Refer the code coverage output for percentage of check.
+		Pass the valid image.(rofs.img).
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestEnableOption()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--vid" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding vidlist with zero and any image.
+Note: Refer the code coverage output for percentage of check.
+		Pass the valid image.(rofs.img).
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestVidListOptionwithZeroValue()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--vidlist=0x0", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding vidlist with invalid value and any image.
+Note: Refer the code coverage output for percentage of check.
+		Pass the valid image.(rofs.img).
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestVidListOptionwithinvalidValue()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--vidlist=0xfffffffff", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding vidlist with invalid value and any image.
+Note: Refer the code coverage output for percentage of check.
+		Pass the valid image.(rofs.img).
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestVidListOptionwithinvalidValue1()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--vidlist=0x00ag,4294967299", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding dbg with invalid value and any image.
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestDbgOptionwithinvalidValue()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--dbg=xyz", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding dbg with = but no value.
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestDbgOptionwithoutValue()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--dbg=", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding e32input with = 
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::Teste32inputOptionwithValue()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--e32input=", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding e32input a image but not a E32 input.
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::Teste32inputOptionwithimg()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--e32input", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding valid images along with e32input option
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::Teste32inputOptionwithimg1()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rom.img", "--e32input" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(4,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding invalid e32input option.
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::Teste32inputOptionwithinvalidoption()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "S:/GT0415/cppunit/imgcheck_unittest/imgs/rofs1.img", "--e3input" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding invalid e32input option.
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::Teste32inputOptionwithinvalidoption1()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "S:/epoc32/release/armv5/udeb", "--e2input" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding = to -n otpions.
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestnocheckOptionwithinvalidoption()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "S:/epoc32/release/armv5/udeb", "-n=" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding = to --nocheck option.
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestnocheckOptionwithinvalidoption1()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "S:/epoc32/release/armv5/udeb", "--nocheck=" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding nocheck option with single '-'
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestnocheckOptionwithinvalidoption2()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "S:/epoc32/release/armv5/udeb", "-nocheck" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding '--' to nocehck otpion
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestnocheckOptionwithinvalidoption3()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "S:/epoc32/release/armv5/udeb", "--n" };
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding valid E32input but not enabling any validations.
+Note: Refer the code coverage output for percentage of check.
+		Pass the valid image.(rofs.img).
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestnocheckOptionwithNoChecksEnabled()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--e32input", "S:/epoc32/release/armv5/udeb"};
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(3,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding valid E32input and ALL option but not enabling any validations
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TestnocheckOptionwithNoChecksEnabled1()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--e32input", "S:/epoc32/release/armv5/udeb", "--all"};
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(4,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding E32input but no directory nor a E32 file.
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TesttocheckOptionwithNoImgandE32input()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--e32input"};
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+/**
+Test the cmdhandler output(xml) by provinding invalid option.
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TesttocheckOptionPrefix()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--"};
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+
+/**
+Test the cmdhandler output(xml) by provinding invalid option and no image.
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TesttocheckInvalidOption()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--sidalll"};
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+
+/**
+Test the cmdhandler output(xml) by provinding invalid option and no image.
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TesttocheckInvalidOption1()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--depp"};
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
+
+
+/**
+Test the cmdhandler output(xml) by provinding invalid option and no image.
+Note: Refer the code coverage output for percentage of check.
+
+@internalComponent
+@released
+*/
+void CTestCmdHandler::TesttocheckInvalidOption2()
+{
+	int status = 0;
+	CmdLineHandler* cmdInput;
+	try
+	{
+		char* argvect[] = { "imgchecker", "--e32inputt"};
+		cmdInput = new CmdLineHandler();
+		ReturnType val = cmdInput->ProcessCommandLine(2,argvect);
+		if(val == EXIT_FAILURE)
+		{
+			status = 1;
+		}
+	}
+    catch(ExceptionReporter& aExceptionReport)
+	{
+		aExceptionReport.Report();
+		status = 0;
+    }
+	delete cmdInput;
+}
--- a/imgtools/imgcheck/inc/checker.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/inc/checker.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,90 +1,90 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Checker interface class declaration
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef CHECKER_H
-#define CHECKER_H
-
-#include "cmdlinehandler.h"
-#include "reporter.h"
-#include "imagereader.h"
-
-typedef std::map<std::string, ExeVsIdDataMap> ImgVsExeIdData;
-
-/** 
-Different status of a dependency
-
-@internalComponent
-@released
-*/
-const String KStatusYes("Available");
-const String KStatusNo("Missing");
-const String KStatusHidden("Hidden");
-const String KDependency("Dependency");
-
-/** 
-All SID validation status constants
-
-@internalComponent
-@released
-*/
-const String KUniqueAlias("Unique(alias)");
-const String KUnique("Unique");
-const String KDuplicate("Duplicate");
-const String KSid("SID");
-
-/** 
-VID and Debuggable flag validation status constants
-
-@internalComponent
-@released
-*/
-const String KValid("Valid");
-const String KInValid("Invalid");
-const String KDbgMatching("Matching");
-const String KDbgNotMatching("Not Matching");
-const String KDbgFlag("DBG");
-const String KVid("VID");
-
-/**
-This class is a virtual base. If any new checks or validation needs to be 
-included as part of this tool, the new checker or validator class should be
-derived from this class.
-
-@internalComponent
-@released
-*/
-class Checker
-{
-protected:
-	CmdLineHandler* iCmdLine;
-	ImageReaderPtrList iImageReaderList;
-	//To identify whether missing or all dependency data to be generated
-	bool iAllExecutables;
-	//To disable all checks
-	bool iNoCheck;
-
-public:
-	Checker(CmdLineHandler* aCmdPtr,ImageReaderPtrList& aImageReaderList);
-	virtual ~Checker();
-	virtual void Check(ImgVsExeStatus& imgVsExeStatus)=0;
-	virtual void PrepareAndWriteData(ExeContainer* aExeContainer)=0;
-};
-#endif//CHECKER_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Checker interface class declaration
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef CHECKER_H
+#define CHECKER_H
+
+#include "cmdlinehandler.h"
+#include "reporter.h"
+#include "imagereader.h"
+
+typedef map<string, ExeVsIdDataMap> ImgVsExeIdData;
+
+/** 
+Different status of a dependency
+
+@internalComponent
+@released
+*/
+const char KStatusYes[] = "Available";
+const char KStatusNo[] = "Missing";
+const char KStatusHidden[] = "Hidden";
+const char KDependency[] = "Dependency";
+
+/** 
+All SID validation status constants
+
+@internalComponent
+@released
+*/
+const char KUniqueAlias[] = "Unique(alias)";
+const char KUnique[] = "Unique";
+const char KDuplicate[] = "Duplicate";
+const char KSid[] = "SID";
+
+/** 
+VID and Debuggable flag validation status constants
+
+@internalComponent
+@released
+*/
+const char KValid[] = "Valid";
+const char KInValid[] = "Invalid";
+const char KDbgMatching[] = "Matching";
+const char KDbgNotMatching[] = "Not Matching";
+const char KDbgFlag[] = "DBG";
+const char KVid[] = "VID";
+
+/**
+This class is a virtual base. If any new checks or validation needs to be 
+included as part of this tool, the new checker or validator class should be
+derived from this class.
+
+@internalComponent
+@released
+*/
+class Checker
+{
+protected:
+	CmdLineHandler* iCmdLine;
+	ImageReaderPtrList iImageReaderList;
+	//To identify whether missing or all dependency data to be generated
+	bool iAllExecutables;
+	//To disable all checks
+	bool iNoCheck;
+
+public:
+	Checker(CmdLineHandler* aCmdPtr,ImageReaderPtrList& aImageReaderList);
+	virtual ~Checker();
+	virtual void Check(ImgVsExeStatus& imgVsExeStatus)=0;
+	virtual void PrepareAndWriteData(ExeContainer& aExeContainer)=0;
+};
+#endif//CHECKER_H
--- a/imgtools/imgcheck/inc/cmdlinehandler.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/inc/cmdlinehandler.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,244 +1,243 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* CmdLineHandler class declaration.
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef CMDLINEHANDLER_H
-#define CMDLINEHANDLER_H
-
-#include "common.h"
-#include "exceptionreporter.h"
-#include "version.h"
-#include "hash.h"
-#include <map>
-#include <vector>
-
-/** 
-Tydefs used in this class.
-
-@internalComponent
-@released
-*/
-
-typedef std::map<String,unsigned int> OptionsMap;
-typedef std::map<String,unsigned int> SuppressionsMap;
-typedef std::vector<char*> ArgumentList;
-
-
-/** 
-Long options will be intialized into an MAP, this data is used later to
-validate the received command line arguments.
-
-@internalComponent
-@released
-*/
-const String KLongHelpOption("--help");
-const String KLongXmlOption("--xml");
-const String KLongQuietOption("--quiet");
-const String KLongAllOption("--all");
-const String KLongOutputOption("--output");
-const String KLongVerboseOption("--verbose");
-const String KLongSuppressOption("--suppress");
-const String KLongVidValOption("--vidlist");
-const String KLongSidAllOption("--sidall");
-const String KLongE32InputOption("--e32input");
-
-/** 
-Short options will be intialized into an MAP, this data is used later to
-validate the received command line arguments.
-
-@internalComponent
-@released
-*/
-const String KShortHelpOption("-h");
-const String KShortXmlOption("-x");
-const String KShortQuietOption("-q");
-const String KShortAllOption("-a");
-const String KShortOutputOption("-o");
-const String KShortVerboseOption("-v");
-const String KShortSuppressOption("-s");
-const String KShortNoCheck("-n");
-
-/**
-options to enable required Validation
-
-@internalComponent
-@released
-*/
-const String KLongEnableDepCheck("--dep");
-const String KLongEnableSidCheck("--sid");
-const String KLongEnableVidCheck("--vid");
-const String KLongEnableDbgFlagCheck("--dbg");
-const String KLongNoCheck("--nocheck");
-
-/**
-option values to disable specific Validation.
-
-@internalComponent
-@released
-*/
-const String KSuppressDependency("dep");
-const String KSuppressSid("sid");
-const String KSuppressVid("vid");
-
-/**
-To mark whether validaition is enabled or not
-
-@internalComponent
-@released
-*/
-const unsigned int KMarkEnable = 0x80000000;
-
-/**
-VID value size
-
-@internalComponent
-@released
-*/
-const unsigned int KHexEightByte = 8;
-const unsigned int KDecHighValue = 0xFFFFFFFF;
-
-/**
-Applicable values of option suppress or -s, allocate each bit for every Validation.
-
-@internalComponent
-@released
-*/
-typedef enum Suppress
-{
-    EDep = 0x1,
-    ESid = 0x2,
-    EVid = 0x4,
-	EDbg = 0x8,
-    //While including more checks, define the constants here;
-    EAllValidation = EDep | ESid | EVid //Add the new check over here.
-};
-
-/**
-Constants to define number of values.
-
-@internalComponent
-@released
-*/
-typedef enum NumberOfValue
-{
-    ENone = 0x0,
-    ESingle = 0x1,
-    //Include new number of values here 
-    EMultiple = 0x2,
-	EOptional
-};
-
-/** 
-Prefix to the short option
-
-@internalComponent
-@released
-*/
-const char KShortOptionPrefix = '-';
-
-/** 
-XML file extension, if the extension is not provided as part of report name,
-this string is appended.
-
-@internalComponent
-@released
-*/
-const String KXmlExtension(".xml");
-
-/** 
-Default XML report name, used if the output report name is not passed through 
-command line.
-
-@internalComponent
-@released
-*/
-const String GXmlFileName("imgcheckreport.xml");
-
-/** 
-Tool name
-
-@internalComponent
-@released
-*/
-const String KToolName("imgcheck");
-
-/**
-Constants used validate the input Decimal or Hexadecimal values
-
-@internalComponent
-@released
-*/
-const String KHexNumber("0123456789abcdef");
-const String KDecNumber("0123456789");
-
-/** 
-class command line handler
-
-@internalComponent
-@released
-*/
-class CmdLineHandler
-{
-public:
-	CmdLineHandler(void);
-	~CmdLineHandler(void);
-	void Usage(void);
-	void Version(void);
-	const String& PrintUsage(void) const;
-	const String& PrintVersion(void) const;
-	String NextImageName(void);
-	unsigned int NoOfImages(void) const;
-	const unsigned int ReportFlag(void) const;
-	const String& XmlReportName(void) const;
-	ReturnType ProcessCommandLine(unsigned int aArgc, char* aArgv[]);
-	void ValidateArguments(void) const;
-	const unsigned int EnabledValidations(void) const;
-	UnIntList& VidValueList(void);
-	const String& Command(void) const;
-	bool DebuggableFlagVal(void);
-	void ValidateImageNameList(void);
-	void ValidateE32NoCheckArguments(void);
-
-private:
-	bool IsOption(const String& aName, int& aLongOptionFlag);
-	bool Validate(const String& aName, bool aOptionValue, unsigned int aNoOfVal);
-	void NormaliseName(void);
-	void ParseOption(const String& aFullName, String& aOptionName, StringList& aOptionValues, bool& aOptionValue);
-	void HandleImage(const String& aImageName);
-	void StringListToUnIntList(StringList& aStrList, UnIntList& aUnIntList);
-	bool AlreadyReceived(String& aName);
-
-private:
-	StringList iImageNameList;
-	OptionsMap iOptionMap;
-	SuppressionsMap iSuppressVal;
-	UnIntList iVidValList;
-	bool iDebuggableFlagVal;
-	String iInputCommand;
-	String iXmlFileName;
-	bool iNoImage;
-	unsigned int iCommmandFlag;
-	unsigned int iValidations;
-	unsigned int iSuppressions;
-	String iVersion;
-	String iUsage;
-};
-
-#endif //CMDLINEHANDLER_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* CmdLineHandler class declaration.
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef CMDLINEHANDLER_H
+#define CMDLINEHANDLER_H
+
+#include "common.h"
+#include "exceptionreporter.h"
+#include "version.h"
+#include "hash.h"
+ 
+#include <map>
+#include <vector>
+
+/** 
+Tydefs used in this class.
+
+@internalComponent
+@released
+*/
+
+typedef map<string,unsigned int> OptionsMap;
+typedef map<string,unsigned int> SuppressionsMap; 
+typedef vector<const char*> cstrings ;
+
+/** 
+Long options will be intialized into an MAP, this data is used later to
+validate the received command line arguments.
+
+@internalComponent
+@released
+*/
+const string KLongHelpOption("--help");
+const string KLongXmlOption("--xml");
+const string KLongQuietOption("--quiet");
+const string KLongAllOption("--all");
+const string KLongOutputOption("--output");
+const string KLongVerboseOption("--verbose");
+const string KLongSuppressOption("--suppress");
+const string KLongVidValOption("--vidlist");
+const string KLongSidAllOption("--sidall");
+const string KLongE32InputOption("--e32input");
+
+/** 
+Short options will be intialized into an MAP, this data is used later to
+validate the received command line arguments.
+
+@internalComponent
+@released
+*/
+const string KShortHelpOption("-h");
+const string KShortXmlOption("-x");
+const string KShortQuietOption("-q");
+const string KShortAllOption("-a");
+const string KShortOutputOption("-o");
+const string KShortVerboseOption("-v");
+const string KShortSuppressOption("-s");
+const string KShortNoCheck("-n");
+
+/**
+options to enable required Validation
+
+@internalComponent
+@released
+*/
+const string KLongEnableDepCheck("--dep");
+const string KLongEnableSidCheck("--sid");
+const string KLongEnableVidCheck("--vid");
+const string KLongEnableDbgFlagCheck("--dbg");
+const string KLongNoCheck("--nocheck");
+
+/**
+option values to disable specific Validation.
+
+@internalComponent
+@released
+*/
+const string KSuppressDependency("dep");
+const string KSuppressSid("sid");
+const string KSuppressVid("vid");
+
+/**
+To mark whether validaition is enabled or not
+
+@internalComponent
+@released
+*/
+const unsigned int KMarkEnable = 0x80000000;
+
+/**
+VID value size
+
+@internalComponent
+@released
+*/
+const unsigned int KHexEightByte = 8;
+const unsigned int KDecHighValue = 0xFFFFFFFF;
+
+/**
+Applicable values of option suppress or -s, allocate each bit for every Validation.
+
+@internalComponent
+@released
+*/
+typedef enum Suppress
+{
+    EDep = 0x1,
+    ESid = 0x2,
+    EVid = 0x4,
+	EDbg = 0x8,
+    //While including more checks, define the constants here;
+    EAllValidation = EDep | ESid | EVid //Add the new check over here.
+};
+
+/**
+Constants to define number of values.
+
+@internalComponent
+@released
+*/
+typedef enum NumberOfValue
+{
+    ENone = 0x0,
+    ESingle = 0x1,
+    //Include new number of values here 
+    EMultiple = 0x2,
+	EOptional
+};
+
+/** 
+Prefix to the short option
+
+@internalComponent
+@released
+*/
+const char KShortOptionPrefix = '-';
+
+/** 
+XML file extension, if the extension is not provided as part of report name,
+this string is appended.
+
+@internalComponent
+@released
+*/
+const char KXmlExtension[] = ".xml";
+
+/** 
+Default XML report name, used if the output report name is not passed through 
+command line.
+
+@internalComponent
+@released
+*/
+const char GXmlFileName[] = "imgcheckreport.xml";
+
+/** 
+Tool name
+
+@internalComponent
+@released
+*/
+const char KToolName[] = "imgcheck";
+
+/**
+Constants used validate the input Decimal or Hexadecimal values
+
+@internalComponent
+@released
+*/
+const char KHexNumber[] = "0123456789abcdef";
+const char KDecNumber[] = "0123456789"; 
+/** 
+class command line handler
+
+@internalComponent
+@released
+*/
+class CmdLineHandler
+{
+public:
+	CmdLineHandler(void);
+	~CmdLineHandler(void);
+	void Usage(void);
+	void Version(void);
+	const string& PrintUsage(void) const;
+	const string& PrintVersion(void) const;
+	const char* NextImageName(void);
+	unsigned int NoOfImages(void) const;
+	const unsigned int ReportFlag(void) const;
+	const string& XmlReportName(void) const;
+	ReturnType ProcessCommandLine(unsigned int aArgc, char* aArgv[]);
+	void ValidateArguments(void) const;
+	const unsigned int EnabledValidations(void) const;
+	UnIntList& VidValueList(void);
+	const string& Command(void) const;
+	bool DebuggableFlagVal(void);
+	void ValidateImageNameList(void);
+	void ValidateE32NoCheckArguments(void);
+
+private:
+	bool IsOption(const char* aName, int& aLongOptionFlag);
+	bool Validate(const string& aName, bool aOptionValue, unsigned int aNoOfVal);
+	void NormaliseName(void);
+	void ParseOption(char* aFullName, cstrings& aOptionValues, bool& aOptionValue);
+	void HandleImage(const char* aImageName);
+	void StringListToUnIntList(cstrings& aStrList, UnIntList& aUnIntList);
+	bool AlreadyReceived(const char* aName);
+
+private:
+	cstrings iImageNameList;
+	OptionsMap iOptionMap;
+	SuppressionsMap iSuppressVal;
+	UnIntList iVidValList;
+	bool iDebuggableFlagVal;
+	string iInputCommand;
+	string iXmlFileName;
+	bool iNoImage;
+	unsigned int iCommmandFlag;
+	unsigned int iValidations;
+	unsigned int iSuppressions;
+	string iVersion;
+	string iUsage;
+};
+
+#endif //CMDLINEHANDLER_H
--- a/imgtools/imgcheck/inc/cmdlinewriter.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/inc/cmdlinewriter.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,94 +1,88 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Cmdlinewriter class declaration.
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef CMDLINEWRITER_H
-#define CMDLINEWRITER_H
-
-#include "reportwriter.h"
-#include "common.h"
-
-/**
-Constants for Cmd Line report section.
-*/
-const String KCmdHeader(" Executable		Attribute	Value                   Status");
-const String KCmdLineDelimiter("-------------------------------------------------------------------------------");
-const String KCmdHeaderNoStatus(" Executable		Attribute	Value         ");
-const String KCmdLineDelimiterNoStatus("--------------------------------------------------");
-const String KCmdImageName("Image Name: ");
-const String KCmdLine("Command line");
-const int KCmdGenBufferSize=260;
-// width to fill the values displayed as 0x00000056
-const unsigned int KCmdFormatEightWidth = 8;
-// width to print the attribute names
-const unsigned int KCmdFormatTwelveWidth = 12;
-// width to print the executable names and attribute names when executable name is not emitted
-const unsigned int KCmdFormatTwentyTwoWidth = 22;
-//width to print the status after the attribute values are printed for SID and VID
-const unsigned int KCmdFormatThirtyWidth = 30;
-// this check is taken for formatting the values (like SID and VID) other that the dependency names.
-const String KCmdDepName("Dependency");
-const String KCmdDbgName("DBG");
-const String KCmdDbgDisplayName("Debug Flag");
-
-typedef std::stringstream OstrStream;
-
-/** 
-class command line writer
-
-@internalComponent
-@released
-*/
-class CmdLineWriter: public ReportWriter
-{
-public:
-
-	CmdLineWriter(unsigned int aInputOptions);
-	~CmdLineWriter(void);
-	void StartReport(void);
-	void EndReport(void);
-	void StartImage(const String& aImageName);
-	void EndImage(void);
-	void StartExecutable(const unsigned int aSerNo, const String& aExeName);
-	void EndExecutable(void);
-  	
-   	void FormatAndWriteElement(const String& aElement);
-	void WriteExeAttribute(ExeAttribute& aOneSetExeAtt);
-	void WriteDelimiter(void);
-	void WriteNote(void);
-	const String& ReportType(void);
-
-private:
-	
-	// Output streams for cmd line output.
-	OstrStream iFormatMessage;
-	// For Dependencies align.
-	bool iForDepAlign;
-	// For formating purpose.
-	unsigned int iFormatSize;
-	// Buffer pointer for formating purpose.
-	char* iBuffer;
-	//Hold the report type
-	String iRptType;
-	//Contains the input options
-	unsigned int iCmdOptions;
-};
-
-#endif // CMDLINEWRITER_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Cmdlinewriter class declaration.
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef CMDLINEWRITER_H
+#define CMDLINEWRITER_H
+
+#include "reportwriter.h"
+#include "common.h"
+
+/**
+Constants for Cmd Line report section.
+*/
+ 
+const char KCmdLineDelimiter[] = "-------------------------------------------------------------------------------"; 
+const char KCmdLineDelimiterNoStatus[] = "--------------------------------------------------";
+const char KCmdImageName[] = "Image Name: ";
+const char KCmdLine[] = "Command line"; 
+ 
+// width to print the attribute names
+const unsigned int KCmdFormatTwelveWidth = 12; 
+// width to print the executable names and attribute names when executable name is not emitted
+//width to print the status after the attribute values are printed for SID and VID
+const unsigned int KCmdFormatTwentyEightWidth = 28;
+// this check is taken for formatting the values (like SID and VID) other that the dependency names.
+const char KCmdDepName[] = "Dependency";
+const char KCmdDbgName[] = "DBG";
+const char KCmdDbgDisplayName[] = "Debug Flag";
+
+ 
+
+/** 
+class command line writer
+
+@internalComponent
+@released
+*/
+class CmdLineWriter: public ReportWriter
+{
+public:
+
+	CmdLineWriter(unsigned int aInputOptions);
+	~CmdLineWriter(void);
+	void StartReport(void);
+	void EndReport(void);
+	void StartImage(const string& aImageName);
+	void EndImage(void);
+	void StartExecutable(const unsigned int aSerNo, const string& aExeName);
+	void EndExecutable(void);
+  	
+   	void FormatAndWriteElement(const string& aElement);
+	void WriteExeAttribute(ExeAttribute& aOneSetExeAtt);
+	void WriteDelimiter(void);
+	void WriteNote(void);
+	const string& ReportType(void);
+
+private:
+	
+	// Output streams for cmd line output.
+	stringstream iFormatMessage;
+	// For Dependencies align.
+	bool iForDepAlign;
+	// For formating purpose.
+	unsigned int iFormatSize; 
+	//Hold the report type
+	string iRptType;
+	//Contains the input options
+	unsigned int iCmdOptions;
+};
+
+#endif // CMDLINEWRITER_H
--- a/imgtools/imgcheck/inc/common.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/inc/common.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,126 +1,131 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* These declarations are used all over the program.
-* @internalComponent
-* @released
-*
-*/
-
-
-
-#ifndef COMMON_H
-#define COMMON_H
-
-#include "typedefs.h"
-
-/**
-Forward declaration
-
-@internalComponent
-@released
-*/
-class ReportWriter;
-class Checker;
-class ImageReader;
-
-/**
-Typedefs used all over the tool.
-
-@internalComponent
-@released
-*/
-typedef std::multimap<String, ExeNamesVsDepListMap> ImageVsDependencyMap;
-typedef std::list<unsigned int> UnIntList;
-typedef std::vector<ReportWriter*> WriterPtrList;
-typedef std::vector<Checker*> CheckerPtrList;
-typedef std::vector<ImageReader*> ImageReaderPtrList;
-
-/**
-Constants used to mark whether the option received or not.
-
-@internalComponent
-@released
-*/
-const unsigned int KNone = 0x0;
-const unsigned int QuietMode = 0x1;
-const unsigned int KAll = 0x2;
-const unsigned int KXmlReport = 0x4;
-const unsigned int KVerbose = 0x8;
-const unsigned int KSidAll = 0x10;
-const unsigned int KNoCheck = 0x20;
-const unsigned int KE32Input = 0x40;
-//Can set value for new options over here
-
-/**
-Class used to put each attribute of a exetuble into integrated container.
-
-@internalComponent
-@released
-*/
-class ExeAttribute
-{
-public:
-	ExeAttribute(){};
-	~ExeAttribute(){};
-
-	String iAttName;
-	String iAttValue;
-	String iAttStatus;
-};
-
-/**
-Enums used during command line input processing.
-
-@internalComponent
-@released
-*/
-typedef enum ReturnType
-{
-	ESuccess = 0,
-	EQuit,
-	EFail
-};
-
-/**
-Tool's exit status
-
-@internalComponent
-@released
-*/
-#define EXIT_SUCCESS 0
-#define EXIT_FAILURE 1
-
-/**
-Class Common, all general purpose funtions can be included here.
-
-@internalComponent
-@released
-*/
-class Common
-{
-public:
-	static String IntToString(unsigned int aValue);
-	static unsigned int StringToInt(String& aStringVal);
-};
-
-/** 
-Default Log file name, used for logging the progress of application.
-
-@internalComponent
-@released
-*/
-const String gLogFileName ("imgcheck.log");
-
-#endif //COMMON_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* These declarations are used all over the program.
+* @internalComponent
+* @released
+*
+*/
+
+
+
+#ifndef COMMON_H
+#define COMMON_H
+#ifdef WIN32
+#ifdef _STLP_INTERNAL_WINDOWS_H
+#define __INTERLOCKED_DECLARED
+#endif
+#include <windows.h>
+#undef DELETE
+#endif
+#include "typedefs.h"
+
+/**
+Forward declaration
+
+@internalComponent
+@released
+*/
+class ReportWriter;
+class Checker;
+class ImageReader;
+
+/**
+Typedefs used all over the tool.
+
+@internalComponent
+@released
+*/ 
+typedef list<unsigned int> UnIntList;
+typedef vector<ReportWriter*> WriterPtrList;
+typedef vector<Checker*> CheckerPtrList;
+typedef vector<ImageReader*> ImageReaderPtrList;
+
+/**
+Constants used to mark whether the option received or not.
+
+@internalComponent
+@released
+*/
+const unsigned int KNone = 0x0;
+const unsigned int QuietMode = 0x1;
+const unsigned int KAll = 0x2;
+const unsigned int KXmlReport = 0x4;
+const unsigned int KVerbose = 0x8;
+const unsigned int KSidAll = 0x10;
+const unsigned int KNoCheck = 0x20;
+const unsigned int KE32Input = 0x40;
+//Can set value for new options over here
+
+/**
+Class used to put each attribute of a exetuble into integrated container.
+
+@internalComponent
+@released
+*/
+class ExeAttribute
+{
+public:
+	ExeAttribute(){};
+	~ExeAttribute(){};
+
+	string iAttName;
+	string iAttValue;
+	string iAttStatus;
+};
+
+/**
+Enums used during command line input processing.
+
+@internalComponent
+@released
+*/
+typedef enum ReturnType
+{
+	ESuccess = 0,
+	EQuit,
+	EFail
+};
+
+/**
+Tool's exit status
+
+@internalComponent
+@released
+*/
+#define EXIT_SUCCESS 0
+#define EXIT_FAILURE 1
+
+/**
+Class Common, all general purpose funtions can be included here.
+
+@internalComponent
+@released
+*/
+class Common
+{
+public:
+	static string IntToString(unsigned int aValue);
+	static unsigned int StringToInt(string& aStringVal);
+};
+
+/** 
+Default Log file name, used for logging the progress of application.
+
+@internalComponent
+@released
+*/
+const string gLogFileName ("imgcheck.log");
+
+#endif //COMMON_H
--- a/imgtools/imgcheck/inc/dbgflagchecker.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/inc/dbgflagchecker.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,44 +1,44 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* DbgFlagChecker class declaration
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef DBGFLAGCHECKER_H
-#define DBGFLAGCHECKER_H
-
-#include "checker.h"
-
-/**
-class VID Checker for VID validation
-
-@internalComponent
-@released
-*/
-class DbgFlagChecker : public Checker
-{
-protected:
-	bool iUserDefinedDbgFlag;
-
-public:
-	DbgFlagChecker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList);
-	~DbgFlagChecker(void);
-	void Check(ImgVsExeStatus& aImgVsExeStatus);
-	void PrepareAndWriteData(ExeContainer* aExeContainer);
-};
-#endif//DBGFLAGCHECKER_H
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* DbgFlagChecker class declaration
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef DBGFLAGCHECKER_H
+#define DBGFLAGCHECKER_H
+
+#include "checker.h"
+
+/**
+class VID Checker for VID validation
+
+@internalComponent
+@released
+*/
+class DbgFlagChecker : public Checker
+{
+protected:
+	bool iUserDefinedDbgFlag;
+
+public:
+	DbgFlagChecker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList);
+	~DbgFlagChecker(void);
+	void Check(ImgVsExeStatus& aImgVsExeStatus);
+	void PrepareAndWriteData(ExeContainer& aExeContainer);
+};
+#endif//DBGFLAGCHECKER_H
--- a/imgtools/imgcheck/inc/depchecker.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/inc/depchecker.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,80 +1,80 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* DepChecker class declaration
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef DEPCHECKER_H
-#define DEPCHECKER_H
-
-#include "imgcheckmanager.h"
-#include "hash.h"
-
-/** 
-Typedefs locally used
-
-@internalComponent
-@released
-*/
-typedef std::map<unsigned int, String> AddressVsExeName;
-
-/**
-If multiple images are specified as the input, then this value must be 
-high to acheive effective searching
-
-@internalComponent
-@released
-*/
-const int KHashTableSize = 2000; 
-
-/**
-The possibilities for more number of hidden files are less, so this 
-much size of Hash pointer is more than enough
-
-@internalComponent
-@released
-*/
-const int KHiddenExeHashSize = 100; //Hidden 
-/**
-class Dependency Checker
-
-@internalComponent
-@released
-*/
-class DepChecker : public Checker
-{
-public:
-	DepChecker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList, bool aNoRomImage);
-	~DepChecker(void);
-	void Check(ImgVsExeStatus& aImgVsExeStatus);
-	void PrepareAndWriteData(ExeContainer* aExeContainer);
-	
-private:
-	void DeleteHiddenExeFromExecutableList(ImageReader* aImageReader, StringList& aHiddenExeList);
-	void CollectDependencyStatus(String& aString, String& aStatus) const;
-	void PrepareImageExeList(ImageReader* aImageReader);
-	void RomImagePassed(void) const;
-	
-private:
-	AddressVsExeName iAddressVsExeName; //ROM specific
-	HashTable* iHashPtr; //Used to search the dependencies effectively
-	HashTable* iHiddenExeHashPtr;
-	bool iNoRomImage;
-};
-
-#endif //DEPCHECKER_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* DepChecker class declaration
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef DEPCHECKER_H
+#define DEPCHECKER_H
+
+#include "imgcheckmanager.h"
+#include "hash.h"
+
+/** 
+Typedefs locally used
+
+@internalComponent
+@released
+*/
+typedef map<unsigned int, string> AddressVsExeName;
+
+/**
+If multiple images are specified as the input, then this value must be 
+high to acheive effective searching
+
+@internalComponent
+@released
+*/
+const int KHashTableSize = 2000; 
+
+/**
+The possibilities for more number of hidden files are less, so this 
+much size of Hash pointer is more than enough
+
+@internalComponent
+@released
+*/
+const int KHiddenExeHashSize = 100; //Hidden 
+/**
+class Dependency Checker
+
+@internalComponent
+@released
+*/
+class DepChecker : public Checker
+{
+public:
+	DepChecker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList, bool aNoRomImage);
+	~DepChecker(void);
+	void Check(ImgVsExeStatus& aImgVsExeStatus);
+	void PrepareAndWriteData(ExeContainer& aExeContainer);
+	
+private:
+	void DeleteHiddenExeFromExecutableList(ImageReader* aImageReader, const StringList& aHiddenExeList);
+	void CollectDependencyStatus(const char* aString, string& aStatus) const;
+	void PrepareImageExeList(ImageReader* aImageReader);
+	void RomImagePassed(void) const;
+	
+private:
+	AddressVsExeName iAddressVsExeName; //ROM specific
+	HashTable* iHashPtr; //Used to search the dependencies effectively
+	HashTable* iHiddenExeHashPtr;
+	bool iNoRomImage;
+};
+
+#endif //DEPCHECKER_H
--- a/imgtools/imgcheck/inc/exceptionimplementation.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/inc/exceptionimplementation.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,122 +1,122 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef EXCEPTIONIMPLEMENTATION_H
-#define EXCEPTIONIMPLEMENTATION_H
-
-#include "common.h"
-
-typedef std::map<int,String> IndexVsMessageMap;
-const unsigned int KMAXWARNINGSORERROR = 100;
-
-/**
-To include more error or warning messages, Just include the key word here and
-write the key word contents into the Message array at ".cpp" file.
-Then increase the Message array MAX size by number of messages included
-
-@internalComponent
-@released
-*/
-enum
-{
-	UNKNOWNIMAGETYPE = 1,
-	UNKNOWNPREFIX,
-	VALUEEXPECTED,
-	VALUENOTEXPECTED,
-	UNKNOWNOPTION,
-	QUIETMODESELECTED,
-	NOIMAGE,
-	NOROMIMAGE,
-	XMLOPTION,
-	NOMEMORY,
-	FILENAMETOOBIG,
-	XMLNAMENOTVALID,
-	REPORTTYPEINVALID,
-	FILEOPENFAIL,
-	XSLCREATIONFAILED,
-	UNEXPECTEDNUMBEROFVALUE,
-	INVALIDVIDVALUE,
-	UNKNOWNSUPPRESSVAL,
-	ALLCHECKSSUPPRESSED,
-	SUPPRESSCOMBINEDWITHVIDVAL,
-	SIDALLCOMBINEDWITHSID,
-	DATAOVERFLOW,
-	VALIDIMAGE,
-	IMAGENAMEALREADYRECEIVED,
-	UNKNOWNDBGVALUE,
-	ONLYSINGLEDIRECTORYEXPECTED,
-	INVALIDDIRECTORY,
-	INCORRECTVALUES,
-	NOVALIDATIONSENABLED,
-	NOEXEPRESENT,
-	E32INPUTNOTEXIST,
-	VALIDE32INPUT,
-	// Add the New Error and warning messages above this line
-	GATHERINGDEPENDENCIES = 101,
-	WRITINGINTOREPORTER,
-	COLLECTDEPDATA,
-	NOOFEXECUTABLES,
-	NOOFHEXECUTABLES,
-	READINGIMAGE,
-	GATHERINGIDDATA,
-	GENERATINGREPORT,
-	REPORTGENERATION,
-	//Add the new status informations below this line
-	NODISKSPACE
-};
-
-/**
-Structure for Messages.
-
-@internalComponent
-@released
-*/
-struct Messages
-{
-	int iIndex;
-	char* iMessage;
-};
-
-/**
-Class Exception implementation.
-
-@internalComponent
-@released
-*/
-class ExceptionImplementation
-{
-public:
-	static ExceptionImplementation* Instance(unsigned int aCmdFlag);
-	static void DeleteInstance(void);
-	String& Message(int aMsgIndex);
-	void Log(const String aMsg);
-	void Report(const String aMsg);
-	
-private:
-	ofstream iLogStream;
-	IndexVsMessageMap iMessage;
-	unsigned int iMsgIndex;
-	static unsigned int iCmdFlag;
-	static ExceptionImplementation* iInstance;
-	ExceptionImplementation(void);
-	~ExceptionImplementation(void);
-};
-
-#endif //EXCEPTIONIMPLEMENTATION_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef EXCEPTIONIMPLEMENTATION_H
+#define EXCEPTIONIMPLEMENTATION_H
+
+#include "common.h"
+
+typedef map<int,string> IndexVsMessageMap;
+const unsigned int KMAXWARNINGSORERROR = 100;
+
+/**
+To include more error or warning messages, Just include the key word here and
+write the key word contents into the Message array at ".cpp" file.
+Then increase the Message array MAX size by number of messages included
+
+@internalComponent
+@released
+*/
+enum
+{
+	UNKNOWNIMAGETYPE = 1,
+	UNKNOWNPREFIX,
+	VALUEEXPECTED,
+	VALUENOTEXPECTED,
+	UNKNOWNOPTION,
+	QUIETMODESELECTED,
+	NOIMAGE,
+	NOROMIMAGE,
+	XMLOPTION,
+	NOMEMORY,
+	FILENAMETOOBIG,
+	XMLNAMENOTVALID,
+	REPORTTYPEINVALID,
+	FILEOPENFAIL,
+	XSLCREATIONFAILED,
+	UNEXPECTEDNUMBEROFVALUE,
+	INVALIDVIDVALUE,
+	UNKNOWNSUPPRESSVAL,
+	ALLCHECKSSUPPRESSED,
+	SUPPRESSCOMBINEDWITHVIDVAL,
+	SIDALLCOMBINEDWITHSID,
+	DATAOVERFLOW,
+	VALIDIMAGE,
+	IMAGENAMEALREADYRECEIVED,
+	UNKNOWNDBGVALUE,
+	ONLYSINGLEDIRECTORYEXPECTED,
+	INVALIDDIRECTORY,
+	INCORRECTVALUES,
+	NOVALIDATIONSENABLED,
+	NOEXEPRESENT,
+	E32INPUTNOTEXIST,
+	VALIDE32INPUT,
+	// Add the New Error and warning messages above this line
+	GATHERINGDEPENDENCIES = 101,
+	WRITINGINTOREPORTER,
+	COLLECTDEPDATA,
+	NOOFEXECUTABLES,
+	NOOFHEXECUTABLES,
+	READINGIMAGE,
+	GATHERINGIDDATA,
+	GENERATINGREPORT,
+	REPORTGENERATION,
+	//Add the new status informations below this line
+	NODISKSPACE
+};
+
+/**
+Structure for Messages.
+
+@internalComponent
+@released
+*/
+struct Messages
+{
+	int iIndex;
+	char* iMessage;
+};
+
+/**
+Class Exception implementation.
+
+@internalComponent
+@released
+*/
+class ExceptionImplementation
+{
+public:
+	static ExceptionImplementation* Instance(unsigned int aCmdFlag);
+	static void DeleteInstance(void);
+	string& Message(int aMsgIndex);
+	void Log(const string aMsg);
+	void Report(const string aMsg);
+	
+private:
+	ofstream iLogStream;
+	IndexVsMessageMap iMessage;
+	unsigned int iMsgIndex;
+	static unsigned int iCmdFlag;
+	static ExceptionImplementation* iInstance;
+	ExceptionImplementation(void);
+	~ExceptionImplementation(void);
+};
+
+#endif //EXCEPTIONIMPLEMENTATION_H
--- a/imgtools/imgcheck/inc/exceptionreporter.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/inc/exceptionreporter.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,49 +1,49 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Class ExceptionReporter declaration
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef EXCEPTIONREPORTER_H
-#define EXCEPTIONREPORTER_H
-
-#include "exceptionimplementation.h"
-#include <stdarg.h>
-
-/** 
-class exception reporter
-
-@internalComponent
-@released
-*/
-class ExceptionReporter
-{
-public:
-	ExceptionReporter(int aMsgIndex, ...);
-	~ExceptionReporter(void);
-	void Log(void) const;
-	void Report(void) const;
-
-private:
-	String iMessage;
-	ExceptionImplementation* iExcepImplPtr;
-};
-
-#endif //EXCEPTIONREPORTER_H
-
-
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Class ExceptionReporter declaration
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef EXCEPTIONREPORTER_H
+#define EXCEPTIONREPORTER_H
+
+#include "exceptionimplementation.h"
+#include <stdarg.h>
+
+/** 
+class exception reporter
+
+@internalComponent
+@released
+*/
+class ExceptionReporter
+{
+public:
+	ExceptionReporter(int aMsgIndex, ...);
+	~ExceptionReporter(void);
+	void Log(void) const;
+	void Report(void) const;
+
+private:
+	string iMessage;
+	ExceptionImplementation* iExcepImplPtr;
+};
+
+#endif //EXCEPTIONREPORTER_H
+
+
--- a/imgtools/imgcheck/inc/hash.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/inc/hash.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,57 +1,56 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* class Hash Table declaration
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef HASH_H
-#define HASH_H
-
-#pragma warning(disable: 4786) // identifier was truncated to '255' characters in the debug information
-
-#include<iostream>
-#include<list>
-#include<map>
-#include<string>
-
-typedef std::list<std::string> StringList;
-typedef std::map<unsigned int,StringList> Table;
-typedef std::string String;
-
-/** 
-class Hash Table
-
-@internalComponent
-@released
-*/
-class HashTable 
-{
-public:
-	HashTable(int aSize);
-	~HashTable(void);
-	int Hash(String aString);
-	bool IsAvailable(String aString);
-	void Insert(String aString);
-	void InsertStringList(StringList& aList);
-	void Delete(String aString);
-
-private:
-	int iSize;       /* the size of the table */
-	Table iTable;
-};
-#endif //HASH_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* class Hash Table declaration
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef HASH_H
+#define HASH_H
+ 
+
+#include<iostream>
+#include<list>
+#include<map>
+#include<string>
+using namespace std;
+
+
+typedef multimap<unsigned int,string > Table;
+ 
+/** 
+class Hash Table
+
+@internalComponent
+@released
+*/
+class HashTable 
+{
+public:
+	HashTable(int aSize);
+	~HashTable(void);
+	int Hash(const string& aString);
+	bool IsAvailable(const string& aString);
+	void Insert(const string& aString);
+	void InsertStringList(const StringList& aList);
+	void Delete(const string& aString);
+
+private:
+	int iSize;       /* the size of the table */
+	Table iTable;
+};
+#endif //HASH_H
--- a/imgtools/imgcheck/inc/imgcheckmanager.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/inc/imgcheckmanager.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,60 +1,60 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* ImageChecker controller class declaration
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef IMGCHECKMANAGER_H
-#define IMGCHECKMANAGER_H
-
-#include "cmdlinehandler.h"
-#include "imagereader.h"
-#include "checker.h"
-
-/** 
-This class is a controller class for imgcheck tool. Controls the instantiation and 
-operations of ImageReader, Checker, Reporter and ReportWriter.
-
-@internalComponent
-@released
-*/
-class ImgCheckManager
-{
-public:
-	ImgCheckManager(CmdLineHandler* aCmdPtr);
-	~ImgCheckManager(void);
-	void Process(ImageReader* aImgReader);
-	void CreateObjects(void); 
-	void Execute(void);
-	void FillReporterData(void);
-	void GenerateReport(void);
-	void InsertWriter(ReportWriter* aWriter);
-
-private:
-	void HandleImage(const String& aImgName, EImageType aImageType = EUnknownImage);
-    
-protected:
-	CmdLineHandler* iCmdLine;
-	Reporter *iReporter;
-	ImageReaderPtrList iImageReaderList;
-	CheckerPtrList iCheckerList;
-	WriterPtrList iWriterList;
-	bool iNoRomImage;
-};
-
-#endif //IMGCHECKMANAGER_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* ImageChecker controller class declaration
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef IMGCHECKMANAGER_H
+#define IMGCHECKMANAGER_H
+
+#include "cmdlinehandler.h"
+#include "imagereader.h"
+#include "checker.h"
+
+/** 
+This class is a controller class for imgcheck tool. Controls the instantiation and 
+operations of ImageReader, Checker, Reporter and ReportWriter.
+
+@internalComponent
+@released
+*/
+class ImgCheckManager
+{
+public:
+	ImgCheckManager(CmdLineHandler* aCmdPtr);
+	~ImgCheckManager(void);
+	void Process(ImageReader* aImgReader);
+	void CreateObjects(void); 
+	void Execute(void);
+	void FillReporterData(void);
+	void GenerateReport(void);
+	void InsertWriter(ReportWriter* aWriter);
+
+private:
+	void HandleImage(const char* aImgName, EImageType aImageType = EUnknownImage);
+    
+protected:
+	CmdLineHandler* iCmdLine;
+	Reporter *iReporter;
+	ImageReaderPtrList iImageReaderList;
+	CheckerPtrList iCheckerList;
+	WriterPtrList iWriterList;
+	bool iNoRomImage;
+};
+
+#endif //IMGCHECKMANAGER_H
--- a/imgtools/imgcheck/inc/reporter.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/inc/reporter.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,73 +1,73 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Reporter class declaration.
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef REPORTER_H
-#define REPORTER_H
-
-#include "common.h"
-#include "exceptionreporter.h"
-#include "reportwriter.h"
-#include "cmdlinewriter.h"
-#include "xmlwriter.h"
-#include <vector>
-
-typedef std::list<ExeAttribute*> ExeAttList;
-
-struct ExeContainer
-{
-	String iExeName;
-	IdData* iIdData;
-	StringList iDepList;
-	ExeAttList iExeAttList;
-};
-
-typedef std::map<std::string, ExeContainer> ExeVsMetaData;
-typedef std::map<std::string, ExeVsMetaData> ImgVsExeStatus;
-
-/** 
-Base class for all type of report generation.
-
-@internalComponent
-@released
-*/
-class Reporter
-{
-
-public:
-	~Reporter();
-	void CreateReport(const WriterPtrList& aWriterList);
-	static void DeleteInstance(void);
-	ImgVsExeStatus& GetContainerReference(void);
-	static Reporter* Instance(unsigned int aCmdOptions);
-
-protected:
-	// Container required for report object storing.
-	WriterPtrList iReportWriterPtrList;
-	//Integrated container
-	ImgVsExeStatus iImgVsExeStatus;
-private:
-	static Reporter* iInstance;
-	Reporter(unsigned int aCmdOptions);
-	bool IsAttributeAvailable(void);
-	unsigned int iInputOptions;
-};
-
-#endif // REPORTER_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Reporter class declaration.
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef REPORTER_H
+#define REPORTER_H
+
+#include "common.h"
+#include "exceptionreporter.h"
+#include "reportwriter.h"
+#include "cmdlinewriter.h"
+#include "xmlwriter.h"
+#include <vector>
+
+typedef list<ExeAttribute*> ExeAttList;
+
+struct ExeContainer
+{
+	string iExeName;
+	IdData* iIdData;
+	StringList iDepList;
+	ExeAttList iExeAttList;
+};
+
+typedef map<string, ExeContainer> ExeVsMetaData; 
+typedef map<string, ExeVsMetaData* > ImgVsExeStatus;
+
+/** 
+Base class for all type of report generation.
+
+@internalComponent
+@released
+*/
+class Reporter
+{
+
+public:
+	~Reporter();
+	void CreateReport(const WriterPtrList& aWriterList);
+	static void DeleteInstance(void);
+	ImgVsExeStatus& GetContainerReference(void);
+	static Reporter* Instance(unsigned int aCmdOptions);
+
+protected:
+	// Container required for report object storing.
+	WriterPtrList iReportWriterPtrList;
+	//Integrated container
+	ImgVsExeStatus iImgVsExeStatus;
+private:
+	static Reporter* iInstance;
+	Reporter(unsigned int aCmdOptions);
+	bool IsAttributeAvailable(void);
+	unsigned int iInputOptions;
+};
+
+#endif // REPORTER_H
--- a/imgtools/imgcheck/inc/reportwriter.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/inc/reportwriter.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,71 +1,67 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* ReportWriter class declaration.
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef REPORTWRITER_H
-#define REPORTWRITER_H
-
-// for mingw complier.
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-	#include <iomanip>
-#else //!__MSVCDOTNET__
-	#include <iomanip.h>
-#endif
-	#include <fstream>
-	#include <iostream>
-	#include <sstream>
-
-#include "common.h"
-#include "exceptionreporter.h"
-
-/**
-Note message to explain about unknown dependency in ROM image
- 
-@internalComponent
-@released
-*/
-const String KNoteMesg(" - Executable is hidden in ROM image, but all the links to this executable are statically resolved.");
-const String KNote("Note");
-
-/** 
-Report Writer cass (Abstract base class for cmdline and xml derived writer class)
-
-@internalComponent
-@released
-*/
-class ReportWriter
-{
-public:
-
-    ReportWriter(void){};
-    virtual ~ReportWriter(void){};
-
-	virtual void StartReport(void)=0;
-	virtual void EndReport(void)=0;
-	virtual void StartImage(const String& aImageName)=0;
-    virtual void EndImage(void)=0;
-	virtual void WriteExeAttribute(ExeAttribute& aOneSetExeAtt)=0;
-	virtual void StartExecutable(const unsigned int aSerNo, const String& aExeName)=0;
-	virtual void EndExecutable(void)=0;
-	virtual void WriteNote(void)=0;
-	virtual const String& ReportType(void)=0;
-};
-
-#endif // REPORTWRITER_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* ReportWriter class declaration.
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef REPORTWRITER_H
+#define REPORTWRITER_H
+ 
+#include <iomanip> 
+#include <fstream>
+#include <iostream>
+#include <sstream>
+using namespace std;
+
+#include "common.h"
+#include "exceptionreporter.h"
+
+/**
+Note message to explain about unknown dependency in ROM image
+ 
+@internalComponent
+@released
+*/
+const char KNoteMesg[] = " - Executable is hidden in ROM image, but all the links to this executable are statically resolved.";
+const char KNote[] = "Note";
+
+/** 
+Report Writer cass (Abstract base class for cmdline and xml derived writer class)
+
+@internalComponent
+@released
+*/
+class ReportWriter
+{
+public:
+
+    ReportWriter(void){};
+    virtual ~ReportWriter(void){};
+
+	virtual void StartReport(void)=0;
+	virtual void EndReport(void)=0;
+	virtual void StartImage(const string& aImageName)=0;
+    virtual void EndImage(void)=0;
+	virtual void WriteExeAttribute(ExeAttribute& aOneSetExeAtt)=0;
+	virtual void StartExecutable(const unsigned int aSerNo, const string& aExeName)=0;
+	virtual void EndExecutable(void)=0;
+	virtual void WriteNote(void)=0;
+	virtual const string& ReportType(void)=0;
+};
+
+#endif // REPORTWRITER_H
--- a/imgtools/imgcheck/inc/sidchecker.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/inc/sidchecker.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,51 +1,51 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Checker interface class declaration
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef SIDCHECKER_H
-#define SIDCHECKER_H
-
-#include "checker.h"
-
-/**
-class SID checker for SID validation
-
-@internalComponent
-@released
-*/
-class SidChecker : public Checker
-{
-protected:
-	SidVsExeMap iSidVsExeMap;
-	bool iSidAll;
-	bool iE32Mode;
-
-public:
-	SidChecker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList);
-	~SidChecker(void);
-	void Check(ImgVsExeStatus& aImgVsExeStatus);
-	void PrepareAndWriteData(ExeContainer* aExeContainer);
-
-private:
-	void FillExeSidStatus(ExeContainer* aExeContainer);
-	const unsigned int GetExecutableOffset(const String& aExeName);
-	void FillExeAttribute(ExeContainer* aExeContainer);
-};
-#endif//SIDCHECKER_H
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Checker interface class declaration
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef SIDCHECKER_H
+#define SIDCHECKER_H
+
+#include "checker.h"
+
+/**
+class SID checker for SID validation
+
+@internalComponent
+@released
+*/
+class SidChecker : public Checker
+{
+protected:
+	SidVsExeMap iSidVsExeMap;
+	bool iSidAll;
+	bool iE32Mode;
+
+public:
+	SidChecker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList);
+	~SidChecker(void);
+	void Check(ImgVsExeStatus& aImgVsExeStatus);
+	void PrepareAndWriteData(ExeContainer& aExeContainer);
+
+private:
+	void FillExeSidStatus(ExeContainer& aExeContainer);
+	const unsigned int GetExecutableOffset(const char* aExeName);
+	void FillExeAttribute(ExeContainer& aExeContainer);
+};
+#endif//SIDCHECKER_H
--- a/imgtools/imgcheck/inc/version.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/inc/version.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,54 +1,54 @@
-// Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-// All rights reserved.
-// This component and the accompanying materials are made available
-// under the terms of the License "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:
-// @internalComponent
-// @released
-//
-
-#ifndef VERSION_H
-#define VERSION_H
-/** 
-Constant values needs to be updated for every release of imgcheck tool
-
-@internalComponent
-@released
-*/
-/**
-The versions should be in three parts as 
-<major>.<minor>.<maintenance>
-For any architectural change the major version should be incremented
-For any change in the input or output format or enhancements or feature support the minor version should be incremented
-For any patch or maintenance(defect fixes) changes the maintenance version should be incremented.
-The maintenance version should be reset to 0 if the minor version is incremented.
-*/
-const String gMajorVersion("V1");
-const String gMinorVersion(".3");
-const String gMaintenanceVersion(".5 \n");
-
-/** 
-Copyright to be displayed
-
-@internalComponent
-@released
-*/
-const String gCopyright("Copyright (c) 2007-2009 Nokia Corporation.\n");
-
-/** 
-Tool description
-
-@internalComponent
-@released
-*/
-const String gToolDesc("\nIMGCHECK - Tool for ROM/ROFS partition check ");
-
-#endif //VERSION_H
+// Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of the License "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:
+// @internalComponent
+// @released
+//
+
+#ifndef VERSION_H
+#define VERSION_H
+/** 
+Constant values needs to be updated for every release of imgcheck tool
+
+@internalComponent
+@released
+*/
+/**
+The versions should be in three parts as 
+<major>.<minor>.<maintenance>
+For any architectural change the major version should be incremented
+For any change in the input or output format or enhancements or feature support the minor version should be incremented
+For any patch or maintenance(defect fixes) changes the maintenance version should be incremented.
+The maintenance version should be reset to 0 if the minor version is incremented.
+*/
+const string gMajorVersion("V1");
+const string gMinorVersion(".4");
+const string gMaintenanceVersion(".0 \n");
+
+/** 
+Copyright to be displayed
+
+@internalComponent
+@released
+*/
+const string gCopyright("Copyright (c) 2007-2010 Nokia Corporation.\n");
+
+/** 
+Tool description
+
+@internalComponent
+@released
+*/
+const string gToolDesc("\nIMGCHECK - Tool for ROM/ROFS partition check ");
+
+#endif //VERSION_H
--- a/imgtools/imgcheck/inc/vidchecker.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/inc/vidchecker.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,55 +1,55 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Checker interface class declaration
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef VIDCHECKER_H
-#define VIDCHECKER_H
-
-#include "checker.h"
-
-/** 
-Symbian Vendor Id
-
-@internalComponent
-@released
-*/
-const unsigned int KDefaultVid = 0x70000001;
-
-/**
-class VID Checker for VID validation
-
-@internalComponent
-@released
-*/
-class VidChecker : public Checker
-{
-protected:
-	UnIntList iVidValList;
-
-public:
-	VidChecker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList);
-	~VidChecker(void);
-	void Check(ImgVsExeStatus& aImgVsExeStatus);
-	void PrepareAndWriteData(ExeContainer* aExeContainer);
-
-private:
-	void FillExeVidStatus(IdData* aIdData);
-};
-#endif//VIDCHECKER_H
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Checker interface class declaration
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef VIDCHECKER_H
+#define VIDCHECKER_H
+
+#include "checker.h"
+
+/** 
+Symbian Vendor Id
+
+@internalComponent
+@released
+*/
+const unsigned int KDefaultVid = 0x70000001;
+
+/**
+class VID Checker for VID validation
+
+@internalComponent
+@released
+*/
+class VidChecker : public Checker
+{
+protected:
+	UnIntList iVidValList;
+
+public:
+	VidChecker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList);
+	~VidChecker(void);
+	void Check(ImgVsExeStatus& aImgVsExeStatus);
+	void PrepareAndWriteData(ExeContainer& aExeContainer);
+
+private:
+	void FillExeVidStatus(IdData* aIdData);
+};
+#endif//VIDCHECKER_H
--- a/imgtools/imgcheck/inc/xmlwriter.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/inc/xmlwriter.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,123 +1,123 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* XmlWriter class implementation.
-* @internalComponent
-* @released
-*
-*/
-
-
-
-#ifndef XMLWRITER_H
-#define XMLWRITER_H
-
-#include "reportwriter.h"
-#include "libxml/xmlwriter.h"
-#include "common.h"
-
-/**
-Constants for XML report generation.
-xml tags (headers,elements and attribute names).
-*/
-const String KXmlEncoding("ISO-8859-1");
-const String KXslFileName("imgcheck.xsl");
-const String KXmlVersion("1.0");
-const String KDtdXslInfo("<!DOCTYPE imgcheck_report [ \
-							<!ELEMENT comment (imgcheck_report+) > \
-							<!ELEMENT imgcheck_report (Image*)> \
-							<!ELEMENT Image (Exe_Name*)> \
-							<!ELEMENT Executable (Dependency*,SID*,VID*,DBG*)> \
-							<!ELEMENT Dependency ANY> \
-							<!ATTLIST comment comment CDATA #REQUIRED>\
-							<!ATTLIST Image name CDATA #REQUIRED> \
-							<!ATTLIST Executable \
-							SNo CDATA #REQUIRED  \
-							name CDATA #REQUIRED> \
-							<!ATTLIST Dependency \
-							name CDATA #REQUIRED \
-							status (Nill | Hidden | Available | Missing) \"Nill\"> \
-							<!ATTLIST SID \
-							val CDATA #IMPLIED \
-							status CDATA #IMPLIED> \
-							<!ATTLIST VID \
-							val CDATA #IMPLIED \
-							status CDATA #IMPLIED> \
-							<!ATTLIST DBG \
-							val CDATA #IMPLIED \
-							status CDATA #IMPLIED> \
-							]> \
-							<?xml-stylesheet type=\"text/xsl\" href=\"imgcheck.xsl\"?>");
-
-const String KXmlRootElement("imgcheck_report");
-const String KXmlcomment("comment");
-const String KXmlinputcmd("Inputcmd");
-
-const String KXmlImageName("Image");
-const String KXmlImageAtt1("name");
-
-const String KXmlExeName("Executable");
-const String KXmlExeAtt1("SNo");
-const String KXmlExeAtt2("name");
-
-const String KDepName("Dependency");
-const String KDepAtt1("name");
-const String KAtt1("status");
-const String KAtt2("val");
-const String KDepAvaStatus("Available");
-const String KXml("XML");
-const String KXMLDbgFlag("DBG");
-const unsigned int KXmlGenBuffer=1024;
-
-/** 
-Xml writer derived class.
-
-@internalComponent
-@released
-*/
-class XmlWriter: public ReportWriter
-{
-public:
-
-	XmlWriter(const String& aXmlFileName, const String& aInputCommand);
-	~XmlWriter(void);
-
-	int CreateXslFile(void);
-	bool GetXslSourcePath(String& aExePath);
-	void StartReport(void);
-	void EndReport(void);
-	void StartImage(const String& aImageName);
-    void EndImage(void);
-	void WriteExeAttribute(ExeAttribute& aOneSetExeAtt);
-	void StartExecutable(const unsigned int aSerNo, const String& aExeName);
-	void EndExecutable(void);
-	void WriteNote(void);
-	const String& ReportType(void);
-
-private:
-	// File stream for xml output.
-	ofstream iXmlFile;
-	// Xml file name for output.
-	const String iXmlFileName;
-	// Xml Buffer pointer.
-	xmlBufferPtr iXmlBufPtr;
-	// Xml write pointer to buffer.
-	xmlTextWriterPtr iXmlTextWriter;
-	//Hold the input command string
-	String iInputCommnd;
-	//Hold the report type
-	String iRptType;
-};
-
-#endif // XMLWRITER_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* XmlWriter class implementation.
+* @internalComponent
+* @released
+*
+*/
+
+
+
+#ifndef XMLWRITER_H
+#define XMLWRITER_H
+
+#include "reportwriter.h"
+#include "libxml/xmlwriter.h"
+#include "common.h"
+
+/**
+Constants for XML report generation.
+xml tags (headers,elements and attribute names).
+*/
+const char KXmlEncoding[] = "ISO-8859-1";
+const char KXslFileName[] = "imgcheck.xsl";
+const char KXmlVersion[] = "1.0";
+const char KDtdXslInfo[] = "<!DOCTYPE imgcheck_report [ \
+							<!ELEMENT comment (imgcheck_report+) > \
+							<!ELEMENT imgcheck_report (Image*)> \
+							<!ELEMENT Image (Exe_Name*)> \
+							<!ELEMENT Executable (Dependency*,SID*,VID*,DBG*)> \
+							<!ELEMENT Dependency ANY> \
+							<!ATTLIST comment comment CDATA #REQUIRED>\
+							<!ATTLIST Image name CDATA #REQUIRED> \
+							<!ATTLIST Executable \
+							SNo CDATA #REQUIRED  \
+							name CDATA #REQUIRED> \
+							<!ATTLIST Dependency \
+							name CDATA #REQUIRED \
+							status (Nill | Hidden | Available | Missing) \"Nill\"> \
+							<!ATTLIST SID \
+							val CDATA #IMPLIED \
+							status CDATA #IMPLIED> \
+							<!ATTLIST VID \
+							val CDATA #IMPLIED \
+							status CDATA #IMPLIED> \
+							<!ATTLIST DBG \
+							val CDATA #IMPLIED \
+							status CDATA #IMPLIED> \
+							]> \
+							<?xml-stylesheet type=\"text/xsl\" href=\"imgcheck.xsl\"?>";
+
+const char KXmlRootElement[] = "imgcheck_report";
+const char KXmlcomment[] = "comment";
+const char KXmlinputcmd[] = "Inputcmd";
+
+const char KXmlImageName[] = "Image";
+const char KXmlImageAtt1[] = "name";
+
+const char KXmlExeName[] = "Executable";
+const char KXmlExeAtt1[] = "SNo";
+const char KXmlExeAtt2[] = "name";
+
+const char KDepName[] = "Dependency";
+const char KDepAtt1[] = "name";
+const char KAtt1[] = "status";
+const char KAtt2[] = "val";
+const char KDepAvaStatus[] = "Available";
+const char KXml[] = "XML";
+const char KXMLDbgFlag[] = "DBG";
+const unsigned int KXmlGenBuffer=1024;
+
+/** 
+Xml writer derived class.
+
+@internalComponent
+@released
+*/
+class XmlWriter: public ReportWriter
+{
+public:
+
+	XmlWriter(const string& aXmlFileName, const string& aInputCommand);
+	~XmlWriter(void);
+
+	int CreateXslFile(void);
+	bool GetXslSourcePath(string& aExePath);
+	void StartReport(void);
+	void EndReport(void);
+	void StartImage(const string& aImageName);
+    void EndImage(void);
+	void WriteExeAttribute(ExeAttribute& aOneSetExeAtt);
+	void StartExecutable(const unsigned int aSerNo, const string& aExeName);
+	void EndExecutable(void);
+	void WriteNote(void);
+	const string& ReportType(void);
+
+private:
+	// File stream for xml output.
+	ofstream iXmlFile;
+	// Xml file name for output.
+	string iXmlFileName;
+	// Xml Buffer pointer.
+	xmlBufferPtr iXmlBufPtr;
+	// Xml write pointer to buffer.
+	xmlTextWriterPtr iXmlTextWriter;
+	//Hold the input command string
+	string iInputCommnd;
+	//Hold the report type
+	string iRptType;
+};
+
+#endif // XMLWRITER_H
--- a/imgtools/imgcheck/libimgutils/inc/dirreader.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/libimgutils/inc/dirreader.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,57 +1,55 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Class to read the directory
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef DIRREADER_H
-#define DIRREADER_H
-
-#include "imagereader.h"
-
-const String KParentDir("..");
-const String KChildDir(".");
-
-/**
-Class Directory reader
-
-@internalComponent
-@released
-*/
-class DirReader : public ImageReader
-{
-private:
-	ExeVsE32ImageMap iExeVsE32ImageMap;
-
-public:
-	DirReader(char* aDirName);
-	~DirReader(void);
-	void ReadImage(void);
-	void ProcessImage(void);
-	void PrepareExeVsIdMap(void);
-	const ExeVsIdDataMap& GetExeVsIdMap() const;
-	ExeNamesVsDepListMap& GatherDependencies(void);
-	void PrepareExeDependencyList(E32Image* aE32Image, StringList& aExecutableList);
-	static EImageType EntryType(char* aStr);
-
-private:	
-	void ReadDir(String aPath);
-	bool IsExecutable(String aName);
-};
- 
-#endif //DIRREADER_H
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Class to read the directory
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef DIRREADER_H
+#define DIRREADER_H
+
+#include "imagereader.h"
+
+const string KParentDir("..");
+const string KChildDir(".");
+
+/**
+Class Directory reader
+
+@internalComponent
+@released
+*/
+class DirReader : public ImageReader
+{ 
+public:
+	DirReader(const char* aDirName);
+	~DirReader(void);
+	void ReadImage(void);
+	void ProcessImage(void);
+	void PrepareExeVsIdMap(void);
+	const ExeVsIdDataMap& GetExeVsIdMap() const;
+	ExeNamesVsDepListMap& GatherDependencies(void);
+	void PrepareExeDependencyList(E32Image* aE32Image, StringList& aExecutables);
+	static EImageType EntryType(string& aStr);
+
+private:	
+	void ReadDir(const string& aPath);
+	bool IsExecutable(const string& aName); 
+	ExeVsE32ImageMap iExeVsE32ImageMap;
+};
+ 
+#endif //DIRREADER_H
--- a/imgtools/imgcheck/libimgutils/inc/e32reader.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/libimgutils/inc/e32reader.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,62 +1,62 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* E32Reader class
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef E32READER_H
-#define E32READER_H
-
-#include "imagereader.h"
-#include "e32image.h"
-
-class E32Image : public E32ImageFile
-{
-public:
-	E32Image(void);
-	~E32Image(void);
-	char** GetImportExecutableNames(int& count);
-};
-
-/**
-class to read E32 image
-
-@internalComponent
-@released
-*/
-class E32Reader : public ImageReader
-{
-private:
-	StringList iDependencyList;
-	E32Image *iE32Image;
-	String iExeName;
-
-public:
-	void ReadImage(void);
-	void ProcessImage(void);
-	E32Reader(char* aImageName);
-	~E32Reader(void);
-
-	const StringList& GetDependencyList(void);
-	ExeNamesVsDepListMap& GatherDependencies(void);
-	static bool IsE32Image(char* aImageName);
-	void PrepareExeVsIdMap(void);
-	const ExeVsIdDataMap& GetExeVsIdMap() const;
-};
-
-#endif //E32READER_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* E32Reader class
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef E32READER_H
+#define E32READER_H
+
+#include "imagereader.h"
+#include "e32image.h"
+
+class E32Image : public E32ImageFile
+{
+public:
+	E32Image(void);
+	~E32Image(void);
+	char** GetImportExecutableNames(int& count);
+};
+
+/**
+class to read E32 image
+
+@internalComponent
+@released
+*/
+class E32Reader : public ImageReader
+{
+private:
+	StringList iDependencyList;
+	E32Image *iE32Image;
+	string iExeName;
+
+public:
+	void ReadImage(void);
+	void ProcessImage(void);
+	E32Reader(const char* aImageName);
+	~E32Reader(void);
+
+	const StringList& GetDependencyList(void) const ;
+	ExeNamesVsDepListMap& GatherDependencies(void);
+	static bool IsE32Image(const char* aImageName);
+	void PrepareExeVsIdMap(void);
+	const ExeVsIdDataMap& GetExeVsIdMap() const;
+};
+
+#endif //E32READER_H
--- a/imgtools/imgcheck/libimgutils/inc/imagereader.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/libimgutils/inc/imagereader.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,63 +1,63 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef IMAGEREADER_H
-#define IMAGEREADER_H
-
-#include "typedefs.h"
-
-class TRomNode;
-
-/**
-Base class to read and process the image(ROFS/ROM/E32)
-
-@internalComponent
-@released
-*/
-class ImageReader
-{
-protected:
-	String	iImgFileName;
-	Ifstream iInputStream;
-	StringList iExecutableList;
-	StringList iHiddenExeList;
-	unsigned int iImageSize;
-    ExeVsIdDataMap iExeVsIdData;
-	ExeNamesVsDepListMap iImageVsDepList;
-	bool iExeAvailable;
-
-public:
-	ImageReader(const char* aFile);
-	virtual ~ImageReader(void);
-	virtual void ReadImage(void) = 0;
-	virtual void ProcessImage(void) = 0;
-	virtual void PrepareExecutableList(void);
-	virtual ExeNamesVsDepListMap& GatherDependencies(void) = 0;
-    virtual void PrepareExeVsIdMap(void) = 0;
-    virtual const ExeVsIdDataMap& GetExeVsIdMap(void) const = 0;
-    
-	const StringList& GetExecutableList(void) const;
-	const StringList& GetHiddenExeList(void) const;
-	String& ImageName(void);
-	static EImageType ReadImageType(const String aImageName);
-	bool ExecutableAvailable(void);
-};
-
-#endif //IMAGEREADER_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef IMAGEREADER_H
+#define IMAGEREADER_H
+
+#include "typedefs.h"
+
+class TRomNode;
+
+/**
+Base class to read and process the image(ROFS/ROM/E32)
+
+@internalComponent
+@released
+*/
+class ImageReader
+{
+protected:
+	string	iImgFileName;
+	ifstream iInputStream;
+	StringList iExecutableList;
+	StringList iHiddenExeList;
+	unsigned int iImageSize;
+    ExeVsIdDataMap iExeVsIdData;
+	ExeNamesVsDepListMap iImageVsDepList;
+	bool iExeAvailable;
+
+public:
+	ImageReader(const char* aFile);
+	virtual ~ImageReader(void);
+	virtual void ReadImage(void) = 0;
+	virtual void ProcessImage(void) = 0;
+	virtual void PrepareExecutableList(void);
+	virtual ExeNamesVsDepListMap& GatherDependencies(void) = 0;
+    virtual void PrepareExeVsIdMap(void) = 0;
+    virtual const ExeVsIdDataMap& GetExeVsIdMap(void) const = 0;
+    
+	const StringList& GetExecutableList(void) const;
+	const StringList& GetHiddenExeList(void) const;
+	const char* ImageName(void) const ;
+	static EImageType ReadImageType(const string aImageName);
+	bool ExecutableAvailable(void);
+};
+
+#endif //IMAGEREADER_H
--- a/imgtools/imgcheck/libimgutils/inc/rofsreader.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/libimgutils/inc/rofsreader.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,66 +1,66 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef ROFSREADER_H
-#define ROFSREADER_H
-
-#include "imagereader.h"
-#include "e32reader.h"
-#include "typedefs.h"
-#include "rofsimage.h"
-
-const String KRofsImageIdentifier = "ROFS";
-const String KRofsExtImageIdentifier = "ROFx";
-
-/**
-class to read rofs image
-
-@internalComponent
-@released
-*/
-class RofsReader : public ImageReader
-{
-public:
-	RofsReader(char *aFile, EImageType aImgType);
-	~RofsReader(void);
-	static bool IsRofsImage(String& aWord);
-	static bool IsRofsExtImage(String& aWord);
-    bool IsExecutable(String aName);
-	void ReadImage(void);
-	void ProcessImage(void);
-	ExeNamesVsDepListMap& GatherDependencies(void);
-	void PrepareExeDependencyList(E32Image* aE32Image, StringList& aExecutableList);
-	void PrepareExecutableList(void);
-    void PrepareExeVsE32ImageMap(TRomNode* aEntry, CCoreImage *aImage, EImageType aImageType, Ifstream& aInputStream, ExeVsE32ImageMap& aExeVsE32ImageMap, ExeVsOffsetMap& aExeVsOffsetMap, StringList& aHiddenExeList);
-	void DeleteHiddenExecutableVsE32ImageEntry(void);
-    void PrepareExeVsIdMap(void);
-    const ExeVsIdDataMap& GetExeVsIdMap(void) const;
-
-private:
-	CCoreImage *iImage;
-	RCoreImageReader *iImageReader;
-	TRomNode *iRootDirEntry;
-    ExeVsOffsetMap iExeVsOffsetMap;
-
-	EImageType iImageType;
-	ExeVsE32ImageMap iExeVsE32ImageMap;
-};
-
-#endif //ROFSREADER_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef ROFSREADER_H
+#define ROFSREADER_H
+
+#include "imagereader.h"
+#include "e32reader.h"
+#include "typedefs.h"
+#include "rofsimage.h"
+
+const string KRofsImageIdentifier = "ROFS";
+const string KRofsExtImageIdentifier = "ROFx";
+
+/**
+class to read rofs image
+
+@internalComponent
+@released
+*/
+class RofsReader : public ImageReader
+{
+public:
+	RofsReader(const char *aFile, EImageType aImgType);
+	~RofsReader(void);
+	static bool IsRofsImage(const string& aWord);
+	static bool IsRofsExtImage(const string& aWord);
+    bool IsExecutable(const string& aName);
+	void ReadImage(void);
+	void ProcessImage(void);
+	ExeNamesVsDepListMap& GatherDependencies(void);
+	void PrepareExeDependencyList(E32Image* aE32Image, StringList& aExecutables);
+	void PrepareExecutableList(void);
+    void PrepareExeVsE32ImageMap(TRomNode* aEntry, CCoreImage *aImage, EImageType aImageType, ifstream& aInputStream, ExeVsE32ImageMap& aExeVsE32ImageMap, ExeVsOffsetMap& aExeVsOffsetMap, StringList& aHiddenExes);
+	void DeleteHiddenExecutableVsE32ImageEntry(void);
+    void PrepareExeVsIdMap(void);
+    const ExeVsIdDataMap& GetExeVsIdMap(void) const;
+
+private:
+	CCoreImage *iImage;
+	RCoreImageReader *iImageReader;
+	TRomNode *iRootDirEntry;
+    ExeVsOffsetMap iExeVsOffsetMap;
+
+	EImageType iImageType;
+	ExeVsE32ImageMap iExeVsE32ImageMap;
+};
+
+#endif //ROFSREADER_H
--- a/imgtools/imgcheck/libimgutils/inc/romfsentry.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/libimgutils/inc/romfsentry.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,136 +1,123 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef ROMFSENTRY_H
-#define ROMFSENTRY_H
-
-#include "typedefs.h"
-
-/**
-Class RomImageFSEntry, Base class ROM image file and directory entry structure
-
-@internalComponent
-@released
-*/
-class RomImageFSEntry 
-{
-public:
-	RomImageFSEntry (char* aName) 
-	: iName(aName), iSibling(0), iChildren(0)
-	{
-	}
-
-	virtual ~RomImageFSEntry(void)
-	{
-	}
-
-	virtual bool IsDirectory(void) = 0;
-	virtual bool IsExecutable(void) = 0;
-	const char *Name(void) { return iName.data();}
-
-	void Destroy(void)
-	{
-		RomImageFSEntry *current = this; // root has no siblings
-		while (current)
-		{
-			if (current->iChildren)
-				current->iChildren->Destroy();
-			RomImageFSEntry* prev=current;
-			current=current->iSibling;
-			DELETE(prev);
-		}
-	}
-
-	String iName;
-	String iPath;
-	RomImageFSEntry *iSibling;
-	RomImageFSEntry *iChildren;
-};
-
-/**
-Class RomImageFileEntry, ROM image file entry structure
-
-@internalComponent
-@released
-*/
-class RomImageFileEntry : public RomImageFSEntry 
-{
-public:
-	RomImageFileEntry(char* aName) 
-	: RomImageFSEntry(aName),iExecutable(true)
-	{
-	}
-	~RomImageFileEntry(void)
-	{
-	}
-	bool IsDirectory(void)
-	{
-		return false;
-	}
-	union ImagePtr
-	{
-		TRomImageHeader *iRomFileEntry;
-		TLinAddr iDataFileAddr;
-	}ImagePtr;
-	TRomEntry *iTRomEntryPtr;
-	bool iExecutable;
-	/** 
-	Function responsible to return the node is executable or not.
-
-	@internalComponent
-	@released
-
-	@return - returns 'true' if executable or 'false'
-	*/
-	bool IsExecutable(void)
-	{
-		if (iExecutable)
-			return true;
-		else
-			return false;
-	}
-};
-
-/**
-Class RomImageDirEntry, ROM image Directory entry structure
-
-@internalComponent
-@released
-*/
-class RomImageDirEntry : public RomImageFSEntry
-{
-public:
-	RomImageDirEntry(char* aName) : RomImageFSEntry(aName)
-	{
-	}
-	~RomImageDirEntry(void)
-	{
-	}
-	bool IsDirectory(void)
-	{
-		return true;
-	}
-	bool IsExecutable(void)
-	{
-		return false;
-	}
-};
-
-#endif //ROMFSENTRY_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef ROMFSENTRY_H
+#define ROMFSENTRY_H
+
+#include "typedefs.h"
+
+/**
+Class RomImageFSEntry, Base class ROM image file and directory entry structure
+
+@internalComponent
+@released
+*/
+class RomImageFSEntry 
+{
+public:
+	RomImageFSEntry (const char* aName) 
+	: iName(aName), iSibling(0), iChildren(0){
+	}
+
+	virtual ~RomImageFSEntry() {
+	}
+
+	virtual bool IsDirectory() const = 0;
+	virtual bool IsExecutable() const = 0;
+	const char *Name() const { return iName.c_str();}
+
+	void Destroy() {
+		RomImageFSEntry *current = this; // root has no siblings
+		while (current) {
+			if (current->iChildren)
+				current->iChildren->Destroy();
+			RomImageFSEntry* prev=current;
+			current=current->iSibling;
+			delete prev;
+		}
+	}
+
+	string iName;
+	string iPath;
+	RomImageFSEntry *iSibling;
+	RomImageFSEntry *iChildren;
+};
+
+/**
+Class RomImageFileEntry, ROM image file entry structure
+
+@internalComponent
+@released
+*/
+class RomImageFileEntry : public RomImageFSEntry 
+{
+public:
+	RomImageFileEntry(const char* aName) 
+	: RomImageFSEntry(aName),iExecutable(true){
+	}
+	~RomImageFileEntry() {
+	}
+	bool IsDirectory() const {
+		return false;
+	}
+	union ImagePtr {
+		TRomImageHeader *iRomFileEntry;
+		TLinAddr iDataFileAddr;
+	}ImagePtr;
+	TRomEntry *iTRomEntryPtr;
+	bool iExecutable;
+	/** 
+	Function responsible to return the node is executable or not.
+
+	@internalComponent
+	@released
+
+	@return - returns 'true' if executable or 'false'
+	*/
+	bool IsExecutable() const {
+		if (iExecutable)
+			return true;
+		else
+			return false;
+	}
+};
+
+/**
+Class RomImageDirEntry, ROM image Directory entry structure
+
+@internalComponent
+@released
+*/
+class RomImageDirEntry : public RomImageFSEntry
+{
+public:
+	RomImageDirEntry(const char* aName) : RomImageFSEntry(aName){
+	}
+	~RomImageDirEntry() {
+	}
+	bool IsDirectory() const {
+		return true;
+	}
+	bool IsExecutable() const {
+		return false;
+	}
+};
+
+#endif //ROMFSENTRY_H
--- a/imgtools/imgcheck/libimgutils/inc/romreader.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/libimgutils/inc/romreader.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,94 +1,92 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef ROMREADER_H
-#define ROMREADER_H
-
-#include <e32image.h>
-#include "imagereader.h"
-
-class TRomRootDirectoryList;
-class TRomDir;
-class TRomImageHeader;
-class TRomEntry;
-class RomImageFSEntry;
-class RomImageHeader;
-
-const String KEpocIdentifier("EPOC");
-const String KRomImageIdentifier("ROM");
-
-const unsigned int KLdrOpcode = 0xe51ff004;
-const unsigned int KRomBase = 0x80000000;
-const unsigned int KRomBaseMaxLimit = 0x82000000;
-
-/**
-Class for ROM reader
-
-@internalComponent
-@released
-*/
-class RomReader : public ImageReader
-{
-private:
-	RomAddrVsExeName iAddVsExeMap;
-	VectorList	iImageAddress;
-
-public:
-	RomReader(const char* aFile, EImageType aImgType );
-	~RomReader(void);
-
-	static bool IsRomImage(const String& aWord);
-	static bool IsRomExtImage(const String& aWord);
-	void ReadImage(void);
-	void ProcessImage(void);
-	void BuildDir(TRomDir *aDir, RomImageFSEntry* aPaFSEntry);
-	void BuildDir(short int *aOffsetTbl, short int aOffsetTblCount, 
-					TRomDir *aDir, RomImageFSEntry* aPaFSEntry);
-	void GetRomDirTbl(short int** aBase, short int& aCount, TRomDir *aRomDir);
-	void AddChild(RomImageFSEntry *aPa, RomImageFSEntry *aChild, TRomEntry* aRomEntry);
-	void Name(String& aName, const char * aUnicodeName, const int aLen);
-       
-	const unsigned long int ImageCompressionType(void) const;
-	const char* RomHdrPtr(void) const;
-	const unsigned long int RomBase(void) const;
-	const unsigned int HdrSize(void) const;
-	const unsigned long int RootDirList(void) const;
-	const unsigned int ImgSize() const;
-    
-	void PrepareExecutableList(void);
-	ExeNamesVsDepListMap& GatherDependencies(void);
-	void PrepareAddVsExeMap(void);
-	void CollectImportExecutableNames(const RomImageFSEntry* aEntry, StringList& aImportExecutableNameList);
-	unsigned int CodeSectionAddress(unsigned int& aImageAddress);
-    void PrepareExeVsIdMap(void);
-    const ExeVsIdDataMap& GetExeVsIdMap(void) const;
-  
-    void PrepareExeVsRomFsEntryMap(void);
-	RomImageHeader *iImageHeader;
-	TRomRootDirectoryList *iRootDirList;
-	RomImageFSEntry	*iRomImageRootDirEntry;
-	unsigned char *iData;
-    ExeVsRomFsEntryMap iExeVsRomFsEntryMap;
-
-	EImageType iImgType;
-	static bool iNoRomLoaderHeader;
-};
- 
-#endif //ROMREADER_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef ROMREADER_H
+#define ROMREADER_H
+
+#include <e32image.h>
+#include "imagereader.h"
+
+class TRomRootDirectoryList;
+class TRomDir;
+class TRomImageHeader;
+class TRomEntry;
+class RomImageFSEntry;
+class RomImageHeader;
+
+const string KEpocIdentifier("EPOC");
+const string KRomImageIdentifier("ROM");
+
+const unsigned int KLdrOpcode = 0xe51ff004;
+const unsigned int KRomBase = 0x80000000;
+const unsigned int KRomBaseMaxLimit = 0x82000000;
+
+/**
+Class for ROM reader
+
+@internalComponent
+@released
+*/
+class RomReader : public ImageReader
+{ 
+	
+
+public:
+	RomReader(const char* aFile, EImageType aImgType );
+	~RomReader(void);
+
+	static bool IsRomImage(const string& aWord);
+	static bool IsRomExtImage(const string& aWord);
+	void ReadImage(void);
+	void ProcessImage(void);
+	void BuildDir(TRomDir *aDir, RomImageFSEntry* aPaFSEntry);
+	void BuildDir(short int *aOffsetTbl, short int aOffsetTblCount, 
+					TRomDir *aDir, RomImageFSEntry* aPaFSEntry);
+	void GetRomDirTbl(short int** aBase, short int& aCount, TRomDir *aRomDir);
+	void AddChild(RomImageFSEntry *aPa, RomImageFSEntry *aChild, TRomEntry* aRomEntry); 
+       
+	const unsigned long int ImageCompressionType(void) const;
+	const char* RomHdrPtr(void) const;
+	const unsigned long int RomBase(void) const;
+	const unsigned int HdrSize(void) const;
+	const unsigned long int RootDirList(void) const;
+	const unsigned int ImgSize() const;
+    
+	void PrepareExecutableList(void);
+	ExeNamesVsDepListMap& GatherDependencies(void);
+	void PrepareAddVsExeMap(void);
+	void CollectImportExecutableNames(const RomImageFSEntry* aEntry, StringList&  aImportExecutables);
+	unsigned int CodeSectionAddress(unsigned int& aImageAddress);
+    void PrepareExeVsIdMap(void);
+    const ExeVsIdDataMap& GetExeVsIdMap(void) const;
+  
+    void PrepareExeVsRomFsEntryMap(void);
+	RomImageHeader *iImageHeader;
+	TRomRootDirectoryList *iRootDirList;
+	RomImageFSEntry	*iRomImageRootDirEntry;
+	unsigned char *iData;
+    ExeVsRomFsEntryMap iExeVsRomFsEntryMap;
+	EImageType iImgType;
+	RomAddrVsExeName iAddVsExeMap;
+	VectorList	iImageAddress;
+	static bool iNoRomLoaderHeader;
+};
+ 
+#endif //ROMREADER_H
--- a/imgtools/imgcheck/libimgutils/inc/typedefs.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/libimgutils/inc/typedefs.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,117 +1,135 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef TYPEDEFS_H
-#define TYPEDEFS_H
-
-#ifdef _MSC_VER
-	#pragma warning(disable: 4786) // identifier was truncated to '255' characters in the debug information
-	#pragma warning(disable: 4503) // decorated name length exceeded, name was truncated
-#endif
-
-#undef _L
-
-#include <fstream.h>
-#include <iostream.h>
-#include <list>
-#include <vector>
-#include <map>
-#include <string>
-#include <sstream>
-
-#include "utils.h"
-
-/**
-Forward declaration
-
-@internalComponent
-@released
-*/
-class E32Image;
-class RomImageFSEntry;
-
-/**
-Typedefs used all over the tool.
-
-@internalComponent
-@released
-*/
-typedef ios Ios;
-typedef std::string String;
-typedef ofstream Ofstream;
-typedef ifstream Ifstream;
-typedef std::list<String> StringList;
-typedef std::map<unsigned int, String> UintVsString;
-typedef std::map<unsigned int, UintVsString> RomAddrVsExeName;
-typedef std::vector<unsigned int> VectorList;
-typedef std::multimap<String, StringList> ExeNamesVsDepListMap;
-typedef std::multimap<String, E32Image*> ExeVsE32ImageMap;
-typedef std::map<String, unsigned int> ExeVsOffsetMap;
-typedef std::map<String, RomImageFSEntry*> ExeVsRomFsEntryMap;
-typedef std::istringstream IStringStream;
-typedef std::ostringstream OStringStream;
-
-/**
-Class used to preserve each attribute of a E32 exectuble.
-
-@internalComponent
-@released
-*/
-typedef struct IdData
-{
-	unsigned long int iUid;
-	unsigned long int iSid;
-	String iSidStatus;
-	unsigned long int iVid;
-	String iVidStatus;
-	bool iDbgFlag;
-	String iDbgFlagStatus;
-    unsigned long int iFileOffset;
-}IdData;
-
-typedef std::map<String,IdData*> ExeVsIdDataMap;
-typedef std::multimap<unsigned long int, String> SidVsExeMap;
-
-/**
-Enums to represent input image type.
-
-@internalComponent
-@released
-*/
-typedef enum EImageType
-{
-	EUnknownImage,
-	ERomImage,
-	ERomExImage,
-	ERofsImage,
-	ERofsExImage,
-	EE32Directoy,
-	EE32File,
-	EE32InputNotExist
-	//more here...
-};
-
-const String KUnknownDependency("unknown");
-typedef const char* c_str ;
-const c_str KDirSeperaor = "/";
-const char KNull = '\0';
-const long KFileHidden_9_1 = 0x0;
-
-#endif// TYPEDEFS_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef TYPEDEFS_H
+#define TYPEDEFS_H
+
+ 
+#include <iostream>
+#include <fstream>
+#include <list>
+#include <vector>
+#include <map>
+#include <string>
+#include <sstream>
+
+#include "utils.h"
+
+/**
+Forward declaration
+
+@internalComponent
+@released
+*/
+class E32Image;
+class RomImageFSEntry;
+
+/**
+Typedefs used all over the tool.
+
+@internalComponent
+@released
+*/
+
+typedef list<string> StringList; 
+typedef map<unsigned int, string> UintVsString; 
+typedef map<unsigned int, UintVsString*> RomAddrVsExeName;
+typedef vector<unsigned int> VectorList;
+typedef map<string, StringList > ExeNamesVsDepListMap;
+typedef map<string, E32Image*> ExeVsE32ImageMap;
+typedef map<string, unsigned int> ExeVsOffsetMap;
+typedef map<string, RomImageFSEntry*> ExeVsRomFsEntryMap; 
+ 
+
+/**
+Class used to preserve each attribute of a E32 exectuble.
+
+@internalComponent
+@released
+*/
+typedef struct IdData
+{
+	unsigned long int iUid;
+	unsigned long int iSid;
+	string iSidStatus;
+	unsigned long int iVid;
+	string iVidStatus;
+	bool iDbgFlag;
+	string iDbgFlagStatus;
+    unsigned long int iFileOffset;
+}IdData;
+
+typedef map<string,IdData*> ExeVsIdDataMap;
+typedef multimap<unsigned long, string> SidVsExeMap;
+
+/**
+Enums to represent input image type.
+
+@internalComponent
+@released
+*/
+typedef enum EImageType
+{
+	EUnknownImage,
+	ERomImage,
+	ERomExImage,
+	ERofsImage,
+	ERofsExImage,
+	EE32Directoy,
+	EE32File,
+	EE32InputNotExist
+	//more here...
+};
+
+const char KUnknownDependency[] = "unknown"; 
+const char KDirSeperaor = '/';
+const char KNull = '\0';
+const long KFileHidden_9_1 = 0x0;
+
+template<typename m, typename l,typename r>
+static typename m::iterator put_item_to_map(m& o, l a,r& b){	
+	typedef typename m::iterator iterator;
+	pair<iterator, bool> ret = o.insert(pair<l,r>(a,b));
+	if(false == ret.second){
+		ret.first->second = b ;
+	}
+	return ret.first ;
+}
+
+template<typename m, typename l,typename r>
+static typename m::iterator put_item_to_map_2(m& o, l a,r& b){	
+	typedef typename m::iterator iterator;
+	pair<iterator,bool> ret = o.insert(pair<l,r>(a,b));
+	if(false == ret.second){
+		if(ret.first->second)
+			delete ret.first->second;
+		ret.first->second = b ;
+	}
+	return ret.first ;
+}
+#ifdef __LINUX__
+const char SLASH_CHAR1 = '/' ;
+const char SLASH_CHAR2 = '\\' ;
+#else
+const char SLASH_CHAR1 = '\\' ;
+const char SLASH_CHAR2 = '/'  ;
+#endif
+
+#endif// TYPEDEFS_H
--- a/imgtools/imgcheck/libimgutils/inc/utils.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/libimgutils/inc/utils.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,102 +1,101 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef UTILS_H
-#define UTILS_H
-
-/**
-Macro to check and delete the pointer.
-
-@internalComponent
-@released
-*/
-#define DELETE(aPtr) if(aPtr != NULL) delete aPtr; aPtr = 0;
-
-typedef std::string String;
-
-/**
-To support large integer values, 64 bit integers are used.
-"__int64" is for MSVC compiler and "long long int" is for GCC compilers
-
-@internalComponent
-@released
-*/
-
-#ifdef _MSC_VER
-	typedef __int64 Long64;
-#else
-	typedef long long int Long64;
-#endif
-
-/**
-Constants for Ascii values
-
-@internalComponent
-@released
-*/
-const int KUpperCaseAsciiValOfCharA = 65;
-const int KUpperCaseAsciiValOfCharZ = 90;
-const int KUpperAndLowerAsciiDiff = 32;
-const int KAsciiValueOfZero = 48;
-
-/**
-Enum for different base
-
-@internalComponent
-@released
-*/
-enum
-{
-	EBase2 = 2,
-	EBase10 = 10,
-	EBase16 = 16
-};
-
-/**
-Enums for different executable type
-
-@internalComponent
-@released
-*/
-enum
-{
-	EAll = 0,
-	EExe = 1,
-	EDll = 2
-};
-
-/**
-class ReaderUtil
-
-@internalComponent
-@released
-*/
-class ReaderUtil
-{
-public:
-	static bool IsExecutable(unsigned char* aUids1, int aType = EAll);
-	static bool IsExe(unsigned long* Uids1);
-	static bool IsDll(unsigned long* Uids1);
-	static const String& ToLower(String& aString);
-	static const String IntToAscii(const int aValue, const int aBase);
-	static Long64 DecStrToInt(String& aString);
-	static unsigned int HexStrToInt(String& aStringVal);
-};
-#endif //UTILS_H
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef UTILS_H
+#define UTILS_H
+
+/**
+Macro to check and delete the pointer.
+
+@internalComponent
+@released
+*/
+#define DELETE(aPtr) if(aPtr != NULL) delete aPtr; aPtr = 0;
+
+ using namespace std;
+/**
+To support large integer values, 64 bit integers are used.
+"__int64" is for MSVC compiler and "long long int" is for GCC compilers
+
+@internalComponent
+@released
+*/
+
+#ifdef _MSC_VER
+	typedef __int64 Long64;
+#else
+	typedef long long int Long64;
+#endif
+
+/**
+Constants for Ascii values
+
+@internalComponent
+@released
+*/
+const int KUpperCaseAsciiValOfCharA = 65;
+const int KUpperCaseAsciiValOfCharZ = 90;
+const int KUpperAndLowerAsciiDiff = 32;
+const int KAsciiValueOfZero = 48;
+
+/**
+Enum for different base
+
+@internalComponent
+@released
+*/
+enum
+{
+	EBase2 = 2,
+	EBase10 = 10,
+	EBase16 = 16
+};
+
+/**
+Enums for different executable type
+
+@internalComponent
+@released
+*/
+enum
+{
+	EAll = 0,
+	EExe = 1,
+	EDll = 2
+};
+
+/**
+class ReaderUtil
+
+@internalComponent
+@released
+*/
+class ReaderUtil
+{
+public:
+	static bool IsExecutable(unsigned char* aUids1, int aType = EAll);
+	static bool IsExe(unsigned long* Uids1);
+	static bool IsDll(unsigned long* Uids1);
+	static const string& ToLower(string& aString);
+	static const string IntToAscii(const int aValue, const int aBase);
+	static Long64 DecStrToInt(string& aString);
+	static unsigned int HexStrToInt(string& aStringVal);
+};
+#endif //UTILS_H
--- a/imgtools/imgcheck/libimgutils/src/dirreader.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/libimgutils/src/dirreader.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,387 +1,362 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "dirreader.h"
-#include "e32reader.h"
-
-#ifdef __LINUX__
-#include <dirent.h>
-#include <sys/stat.h>
-#else
-#include <io.h>
-#include <direct.h>
-#endif
-
-#define MAXPATHLEN 255
-
-/** 
-Constructor.
-
-@internalComponent
-@released
-*/
-DirReader::DirReader(char* aDirName)
-:ImageReader(aDirName)
-{
-}
-
-/** 
-Destructor.
-
-@internalComponent
-@released
-*/
-DirReader::~DirReader(void)
-{
-	ExeVsE32ImageMap::iterator begin = iExeVsE32ImageMap.begin();
-	ExeVsE32ImageMap::iterator end = iExeVsE32ImageMap.end();
-	while(begin != end)
-	{
-		DELETE(begin->second);
-		++begin;
-	}
-	iExeVsE32ImageMap.clear();
-}
-
-/** 
-Function to check whether the node is an executable or not.
-
-@internalComponent
-@released
-
-@param aName - Executable name
-*/
-bool DirReader::IsExecutable(String aName)
-{
-	unsigned int strPos = aName.find_last_of('.');
-	if(strPos != String::npos)
-	{
-		aName = aName.substr(strPos);
-		if(aName.length() <= 4)
-		{
-			ReaderUtil::ToLower(aName);
-			if (aName.find(".exe") != String::npos || aName.find(".dll") != String::npos ||
-				aName.find(".prt") != String::npos || aName.find(".nif") != String::npos ||
-				aName.find(".pdl") != String::npos || aName.find(".csy") != String::npos || 
-				aName.find(".agt") != String::npos || aName.find(".ani") != String::npos || 
-				aName.find(".loc") != String::npos || aName.find(".drv") != String::npos || 
-				aName.find(".pdd") != String::npos || aName.find(".ldd") != String::npos ||
-				aName.find(".tsy") != String::npos || aName.find(".fsy") != String::npos ||
-				aName.find(".fxt") != String::npos)
-			{
-				return true;
-			}
-		}
-	}
-	return false;
-}
-
-/** 
-Dummy function to be compatible with other Readers.
-
-@internalComponent
-@released
-*/
-void DirReader::ReadImage(void)
-{
-}
-
-/** 
-Function to 
-1. Preserve the present working directory
-2. Invoke the function which reads the directory entires recursively.
-3. Go back to the original directory.
-
-@internalComponent
-@released
-*/
-void DirReader::ProcessImage()
-{
-	char* cwd = new char[MAXPATHLEN];
-	getcwd(cwd,MAXPATHLEN);
-	ReadDir(iImgFileName);
-	chdir(cwd);
-	if(cwd != NULL)
-		delete [] cwd;
-	cwd = 0;
-}
-
-/** 
-Function to 
-1. Read the directory entires recursively.
-2. Prepare the ExeVsE32ImageMap.
-
-@internalComponent
-@released
-
-@param aPath - Directory name.
-*/
-void DirReader::ReadDir(String aPath)
-{
-	int handle;
-	int retVal = 0; 
-	E32Image* e32Image = KNull;
-
-#ifdef __LINUX__
-	DIR* dirEntry = opendir( aPath.c_str());
-	static struct dirent* dirPtr;
-	while ((dirPtr= readdir(dirEntry)) != NULL)
-	{
-		if ((strcmp(dirPtr->d_name, KChildDir.c_str()) == 0) || 
-			(strcmp(dirPtr->d_name, KParentDir.c_str()) == 0)) 
-			continue; // current dir || parent dir
-
-		String fullName( aPath + "/" + dirPtr->d_name );
-		
-		struct stat fileEntrybuf;
-		int retVal = stat((char*)fullName.c_str(), &fileEntrybuf);
-		if(retVal >= 0)
-		{
-			if(S_ISDIR(fileEntrybuf.st_mode)) //Is Directory?
-			{
-				ReadDir(fullName);
-			}
-			else if(S_ISREG(fileEntrybuf.st_mode)) //Is regular file?
-			{
-				if ((fileEntrybuf.st_blksize > 0) && IsExecutable(String(dirPtr->d_name)) && E32Image::IsE32ImageFile((char*)fullName.c_str()))
-				{
-					iExeAvailable = true;
-					e32Image = new E32Image();
-					Ifstream inputStream((char*)fullName.c_str(), Ios::binary | Ios::in);
-					inputStream.seekg(0, Ios::end);
-					TUint32 aSz = inputStream.tellg();
-					inputStream.seekg(0, Ios::beg);
-					e32Image->iFileSize=aSz;
-					e32Image->Adjust(aSz);
-					inputStream >> *e32Image;
-					String exeName(dirPtr->d_name);
-					ReaderUtil::ToLower(exeName);
-					if(iExeVsE32ImageMap.find(exeName) != iExeVsE32ImageMap.end())
-					{
-						cout << "Warning: "<< "Duplicate entry '" << dirPtr->d_name << " '"<< endl;
-						continue;
-					}
-					iExeVsE32ImageMap.insert(std::make_pair(exeName, e32Image));
-					iExecutableList.push_back(exeName);
-				}
-				else
-				{
-					cout << "Warning: "<< dirPtr->d_name << " is not a valid E32 executable" << endl;
-				}
-			}
-		}
-	}
-	closedir(dirEntry);
-
-#else
-	retVal = chdir(aPath.c_str());
-	struct _finddata_t  finder;
-	handle = _findfirst("*.*", &finder);
-	while (retVal == 0)
-	{
-		if ((strcmp(finder.name, KChildDir.c_str()) == 0) || 
-			(strcmp(finder.name, KParentDir.c_str()) == 0) ) // current dir || parent dir  
-		{
-			retVal = _findnext(handle, &finder);
-			continue;
-		}
-
-		if (finder.attrib & _A_SUBDIR)
-		{
-			ReadDir(finder.name);
-			chdir(KParentDir.c_str());
-		}
-		else
-		{
-			if ((finder.size > 0) && IsExecutable(String(finder.name)) && E32Image::IsE32ImageFile(finder.name))
-			{
-				e32Image = new E32Image();
-				Ifstream inputStream(finder.name, Ios::binary | Ios::in);
-				iExeAvailable = true;
-				e32Image->iFileSize=finder.size;
-				e32Image->Adjust(finder.size);
-				inputStream >> *e32Image;
-				String exeName(finder.name);
-				ReaderUtil::ToLower(exeName);
-				if(iExeVsE32ImageMap.find(exeName) != iExeVsE32ImageMap.end())
-				{
-					cout << "Warning: "<< "Duplicate entry '" << finder.name << " '"<< endl;
-					retVal = _findnext(handle, &finder);
-					continue;
-				}
-				iExeVsE32ImageMap.insert(std::make_pair(exeName, e32Image));
-				iExecutableList.push_back(exeName);
-			}
-			else
-			{
-				cout << "Warning: "<< finder.name << " is not a valid E32 executable" << endl;
-			}
-		}
-		retVal = _findnext(handle,&finder);
-	}
-#endif
-}
-
-/** 
-Function to traverse through ExeVsE32ImageMap and prepare ExeVsIdData map.
-
-@internalComponent
-@released
-*/
-void DirReader::PrepareExeVsIdMap(void)
-{
-	ExeVsE32ImageMap::iterator begin = iExeVsE32ImageMap.begin();
-	ExeVsE32ImageMap::iterator end = iExeVsE32ImageMap.end();
-	String exeName;
-	E32Image* e32Image = KNull;
-	IdData* id = KNull;
-	if(iExeVsIdData.size() == 0) //Is not already prepared
-	{
-		while(begin != end)
-		{
-			exeName = begin->first;
-			e32Image = begin->second;
-			id = new IdData;
-			id->iUid = e32Image->iOrigHdr->iUid1;
-			id->iDbgFlag = (e32Image->iOrigHdr->iFlags & KImageDebuggable)? true : false;
-			TUint aHeaderFmt = E32ImageHeader::HdrFmtFromFlags(e32Image->iOrigHdr->iFlags);
-			if (aHeaderFmt >= KImageHdrFmt_V)
-			{
-				E32ImageHeaderV* v = e32Image->iHdr;
-				id->iSid = v->iS.iSecureId;
-				id->iVid = v->iS.iVendorId;
-				id->iFileOffset = 0;//Entry read from directory input, has no offset.
-			}
-			iExeVsIdData[exeName] = id;
-			++begin;
-		}
-	}
-	id = KNull;
-}
-
-/** 
-Function to return ExeVsIdData map.
-
-@internalComponent
-@released
-
-@return returns iExeVsIdData.
-*/
-const ExeVsIdDataMap& DirReader::GetExeVsIdMap() const
-{
-	return iExeVsIdData;
-}
-
-/** 
-Function responsible to gather dependencies for all the executables using the container iExeVsE32ImageMap.
-
-@internalComponent
-@released
-
-@return iImageVsDepList - returns all executable's dependencies
-*/
-ExeNamesVsDepListMap& DirReader::GatherDependencies()
-{
-	ExeVsE32ImageMap::iterator begin = iExeVsE32ImageMap.begin();
-	ExeVsE32ImageMap::iterator end = iExeVsE32ImageMap.end();
-
-	StringList executableList;
-	while(begin != end)
-	{
-		PrepareExeDependencyList((*begin).second, executableList);
-		iImageVsDepList.insert(std::make_pair((*begin).first, executableList));
-		executableList.clear();
-		++begin;
-	}
-	return iImageVsDepList;
-}
-
-/** 
-Function responsible to prepare the dependency list.
-
-@internalComponent
-@released
-
-@param - aE32Image, Using this, can get all the information about the executable
-@param - aExecutableList, Excutables placed into this list
-*/
-void DirReader::PrepareExeDependencyList(E32Image* aE32Image, StringList& aExecutableList)
-{
-	int count = 0;
-	char** nameList = aE32Image->GetImportExecutableNames(count);
-	int i = 0;
-	String dependency;
-	for(; i < count; ++i)
-	{
-		dependency.assign(nameList[i]);
-		aExecutableList.push_back(ReaderUtil::ToLower(dependency));
-	}
-	DELETE(nameList);
-}
-
-/** 
-Function to identify the given path as file or directory
-
-@internalComponent
-@released
-
-@param - aStr, path name
-@return - retuns the either Directory, file or Unknown.
-*/
-EImageType DirReader::EntryType(char* aStr)
-{
-	int strLength = strlen(aStr);
-	if(aStr[strLength - 1] == '\\' || aStr[strLength - 1] == '/')
-	{
-		aStr[strLength - 1] = KNull;
-	}
-	int retVal = 0;
-	#ifdef __LINUX__
-		struct stat fileEntrybuf;
-		retVal = stat(aStr, &fileEntrybuf);
-		if(retVal >= 0)
-		{
-			if(S_ISDIR(fileEntrybuf.st_mode))
-			{
-	#else
-		struct _finddata_t  finder;
-		retVal = _findfirst(aStr, &finder);
-		if(retVal > 0) //No error
-		{
-			if(finder.attrib & _A_SUBDIR)
-			{
-	#endif
-				return EE32Directoy;
-			}
-			else
-			{
-				if(E32Reader::IsE32Image(aStr) == true)
-				{
-					return EE32File;
-				}
-			}
-		}
-
-	return EE32InputNotExist;
-}
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+/**
+@file
+@internalComponent
+@released
+*/
+#include "dirreader.h"
+#include "e32reader.h"
+
+#ifdef WIN32
+#include <io.h>
+#include <direct.h>
+#else//__LINUX__
+#include <dirent.h>
+#include <unistd.h>
+#include <sys/stat.h>
+#define stricmp strcasecmp
+#define strinicmp strncasecmp
+#endif
+
+#define MAXPATHLEN 255
+
+/** 
+Constructor.
+
+@internalComponent
+@released
+*/
+DirReader::DirReader(const char* aDirName)
+:ImageReader(aDirName) {
+}
+
+/** 
+Destructor.
+
+@internalComponent
+@released
+*/
+DirReader::~DirReader(void) {
+	ExeVsE32ImageMap::iterator begin = iExeVsE32ImageMap.begin();
+	ExeVsE32ImageMap::iterator end = iExeVsE32ImageMap.end();
+	while(begin != end) {
+		DELETE(begin->second);
+		++begin;
+	}  
+	iExeVsE32ImageMap.clear();
+}
+
+/** 
+Function to check whether the node is an executable or not.
+
+@internalComponent
+@released
+
+@param aName - Executable name
+*/
+bool DirReader::IsExecutable(const string& aName) {
+	unsigned int strPos = aName.find_last_of('.');
+	if(strPos != string::npos) {
+		string ext = aName.substr(strPos);
+		if(ext.length() <= 4) {
+			ReaderUtil::ToLower(ext);
+			if (ext.find(".exe") != string::npos || ext.find(".dll") != string::npos ||
+				ext.find(".prt") != string::npos || ext.find(".nif") != string::npos ||
+				ext.find(".pdl") != string::npos || ext.find(".csy") != string::npos || 
+				ext.find(".agt") != string::npos || ext.find(".ani") != string::npos || 
+				ext.find(".loc") != string::npos || ext.find(".drv") != string::npos || 
+				ext.find(".pdd") != string::npos || ext.find(".ldd") != string::npos ||
+				ext.find(".tsy") != string::npos || ext.find(".fsy") != string::npos ||
+				ext.find(".fxt") != string::npos) {
+				return true;
+			}
+		}
+	}
+	return false;
+}
+
+/** 
+Dummy function to be compatible with other Readers.
+
+@internalComponent
+@released
+*/
+void DirReader::ReadImage(void) {
+}
+
+/** 
+Function to 
+1. Preserve the present working directory
+2. Invoke the function which reads the directory entires recursively.
+3. Go back to the original directory.
+
+@internalComponent
+@released
+*/
+void DirReader::ProcessImage() {
+	char* cwd = new char[MAXPATHLEN]; 
+	getcwd(cwd,MAXPATHLEN);
+	ReadDir(iImgFileName); 
+	chdir(cwd); 
+	if(cwd != NULL)
+		delete [] cwd;
+	cwd = 0;
+}
+
+/** 
+Function to 
+1. Read the directory entires recursively.
+2. Prepare the ExeVsE32ImageMap.
+
+@internalComponent
+@released
+
+@param aPath - Directory name.
+*/
+void DirReader::ReadDir(const string& aPath) {
+
+
+	E32Image* e32Image = KNull;
+
+#ifdef WIN32
+	int handle ; 
+	int retVal = chdir(aPath.c_str());
+	struct _finddata_t  finder;
+	handle = _findfirst("*.*", &finder);
+	while (retVal == 0) {
+		if ((strcmp(finder.name, KChildDir.c_str()) == 0) || 
+			(strcmp(finder.name, KParentDir.c_str()) == 0) ) {// current dir || parent dir   
+			retVal = _findnext(handle, &finder);
+			continue;
+		}
+
+		if (finder.attrib & _A_SUBDIR) {
+			ReadDir(finder.name);  
+			chdir(KParentDir.c_str()); 
+		}
+		else {
+			if ((finder.size > 0) && IsExecutable(string(finder.name)) && E32Image::IsE32ImageFile(finder.name)) {
+				e32Image = new E32Image();
+				ifstream inputStream(finder.name, ios_base::binary | ios_base::in);
+				iExeAvailable = true;
+				e32Image->iFileSize=finder.size;
+				e32Image->Adjust(finder.size);
+				inputStream >> *e32Image;				
+				ExeVsE32ImageMap::iterator it  ;
+				for(it = iExeVsE32ImageMap.begin() ;it != iExeVsE32ImageMap.end(); it++){
+					if(it->first == finder.name){ 
+						break ;
+					}
+				}				
+				if(it != iExeVsE32ImageMap.end()) {
+					cout << "Warning: "<< "Duplicate entry '" << finder.name << " '"<< endl;					
+					retVal = _findnext(handle, &finder);
+					continue;
+				}
+				size_t len = strlen(finder.name) + 1;
+				e32Image->iFileName = new char[len ];
+				memcpy(e32Image->iFileName,finder.name,len); 
+				put_item_to_map_2(iExeVsE32ImageMap,e32Image->iFileName, e32Image);
+				
+				iExecutableList.push_back(e32Image->iFileName); 
+			}
+			else {
+				cout << "Warning: "<< finder.name << " is not a valid E32 executable" << endl;
+			}
+		}
+		retVal = _findnext(handle,&finder);
+	}
+#else //__LINUX__
+	DIR* dirEntry = opendir( aPath.c_str());
+	static struct dirent* dirPtr;
+	while ((dirPtr= readdir(dirEntry)) != NULL) {
+		if ((strcmp(dirPtr->d_name, KChildDir.c_str()) == 0) || 
+			(strcmp(dirPtr->d_name, KParentDir.c_str()) == 0)) 
+			continue; // current dir || parent dir
+
+		string fullName( aPath + "/" + dirPtr->d_name );
+
+		struct stat fileEntrybuf; 
+		int retVal = stat((char*)fullName.c_str(), &fileEntrybuf); 
+		if(retVal >= 0) {
+			if(S_ISDIR(fileEntrybuf.st_mode)) { //Is Directory?
+				ReadDir(fullName);
+			}
+			else if(S_ISREG(fileEntrybuf.st_mode)){ //Is regular file? 
+				if ((fileEntrybuf.st_blksize > 0) && IsExecutable(string(dirPtr->d_name)) && E32Image::IsE32ImageFile(fullName.c_str())) {
+					iExeAvailable = true;
+					e32Image = new E32Image();
+					ifstream inputStream(fullName.c_str(), ios_base::binary | ios_base::in);
+					inputStream.seekg(0, ios_base::end);
+					TUint32 aSz = inputStream.tellg();
+					inputStream.seekg(0, ios_base::beg);
+					e32Image->iFileSize=aSz;
+					e32Image->Adjust(aSz);
+					inputStream >> *e32Image;
+					//string exeName(dirPtr->d_name);
+					//ReaderUtil::ToLower(exeName);
+					ExeVsE32ImageMap::iterator it  ;
+					for(it = iExeVsE32ImageMap.begin() ;it != iExeVsE32ImageMap.end(); it++){
+						if(!stricmp(dirPtr->d_name,it->first.c_str())){ 
+							break ;
+						}
+					}	
+					if(it != iExeVsE32ImageMap.end()) {
+						cout << "Warning: "<< "Duplicate entry '" << dirPtr->d_name << " '"<< endl;
+						continue;
+					}
+					size_t len = strlen(dirPtr->d_name) + 1;
+					if(e32Image->iFileName) delete []e32Image->iFileName;
+					e32Image->iFileName = new char[len ];
+					memcpy(e32Image->iFileName,dirPtr->d_name,len); 					
+					put_item_to_map_2(iExeVsE32ImageMap,e32Image->iFileName, e32Image);					
+					iExecutableList.push_back(e32Image->iFileName); 
+				}
+				else {
+					cout << "Warning: "<< dirPtr->d_name << " is not a valid E32 executable" << endl;
+				}
+			}
+		}
+	}
+	closedir(dirEntry);
+
+
+
+#endif
+}
+
+/** 
+Function to traverse through ExeVsE32ImageMap and prepare ExeVsIdData map.
+
+@internalComponent
+@released
+*/
+void DirReader::PrepareExeVsIdMap(void) {  
+	if(iExeVsIdData.size() == 0)  {//Is not already prepared
+		for(ExeVsE32ImageMap::iterator it = iExeVsE32ImageMap.begin();
+		it != iExeVsE32ImageMap.end(); it++) { 
+			E32Image* e32Image = it->second;
+			IdData* id = new IdData;
+			id->iUid = e32Image->iOrigHdr->iUid1;
+			id->iDbgFlag = (e32Image->iOrigHdr->iFlags & KImageDebuggable)? true : false;
+			TUint aHeaderFmt = E32ImageHeader::HdrFmtFromFlags(e32Image->iOrigHdr->iFlags);
+			if (aHeaderFmt >= KImageHdrFmt_V) {
+				E32ImageHeaderV* v = e32Image->iHdr;
+				id->iSid = v->iS.iSecureId;
+				id->iVid = v->iS.iVendorId;
+				id->iFileOffset = 0;//Entry read from directory input, has no offset.
+			}
+			put_item_to_map_2(iExeVsIdData,it->first,id); 
+		}
+	} 
+}
+
+/** 
+Function to return ExeVsIdData map.
+
+@internalComponent
+@released
+
+@return returns iExeVsIdData.
+*/
+const ExeVsIdDataMap& DirReader::GetExeVsIdMap() const {
+	return iExeVsIdData;
+}
+
+/** 
+Function responsible to gather dependencies for all the executables using the container iExeVsE32ImageMap.
+
+@internalComponent
+@released
+
+@return iImageVsDepList - returns all executable's dependencies
+*/
+ExeNamesVsDepListMap& DirReader::GatherDependencies() {  
+	StringList executables;
+	for(ExeVsE32ImageMap::iterator it =  iExeVsE32ImageMap.begin();
+	it != iExeVsE32ImageMap.end(); it++) {
+		PrepareExeDependencyList(it->second, executables);
+		put_item_to_map(iImageVsDepList,it->first, executables);
+		executables.clear(); 
+	}
+	return iImageVsDepList;
+}
+
+/** 
+Function responsible to prepare the dependency list.
+
+@internalComponent
+@released
+
+@param - aE32Image, Using this, can get all the information about the executable
+@param - aExecutables, Excutables placed into this list
+*/
+void DirReader::PrepareExeDependencyList(E32Image* aE32Image, StringList& aExecutables) {
+	int count = 0;
+	char** names = aE32Image->GetImportExecutableNames(count); 
+	for(int i = 0; i < count; ++i) { 
+		aExecutables.push_back(names[i]);
+	}
+	if(names){
+		delete [](reinterpret_cast<long*>(names));
+	}
+}
+
+/** 
+Function to identify the given path as file or directory
+
+@internalComponent
+@released
+
+@param - aStr, path name
+@return - retuns the either Directory, file or Unknown.
+*/
+EImageType DirReader::EntryType(string& aStr) {	
+	int pos = aStr.length() - 1;
+	if(pos < 0)
+		return EUnknownImage;
+	char ch = aStr.at(pos);
+	if(ch == SLASH_CHAR1 || ch == SLASH_CHAR2) {
+		aStr.erase(pos,1);
+	} 
+#ifdef WIN32 
+	struct _finddata_t  finder;
+	int retVal = _findfirst(aStr.c_str(), &finder);
+	if(retVal > 0) {//No error 
+		if(finder.attrib & _A_SUBDIR) {
+#else//__LINUX__
+	struct stat fileEntrybuf;
+	int retVal = stat(aStr.c_str(), &fileEntrybuf);
+	if(retVal >= 0) {
+		if(S_ISDIR(fileEntrybuf.st_mode)) {
+
+
+#endif
+			return EE32Directoy;
+		}
+		else {
+			if(E32Reader::IsE32Image(aStr.c_str()) == true) {
+				return EE32File;
+			}
+		}
+	}
+
+	return EE32InputNotExist;
+}
--- a/imgtools/imgcheck/libimgutils/src/e32reader.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/libimgutils/src/e32reader.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,235 +1,220 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "e32reader.h"
-#include <f32image.h>
-
-/** 
-Constructor.
-
-@internalComponent
-@released
-*/
-E32Image::E32Image()
-:E32ImageFile()
-{
-}
-
-/** 
-Destructor.
-
-@internalComponent
-@released
-*/
-E32Image::~E32Image()
-{
-}
-
-/** 
-Function responsible to read the import section of an e32 image and return the dependency names.
-
-@internalComponent
-@released
-
-@param aCount - Number of imports found
-
-@return - returns the two dimensional 
-*/
-char** E32Image::GetImportExecutableNames(int& aCount)
-{
-	const E32ImportSection* isection = (const E32ImportSection*)(iData + iOrigHdr->iImportOffset);
-	const E32ImportBlock* impBlock = (const E32ImportBlock*)(isection + 1);
-
-	char** nameList = (char**)malloc(iOrigHdr->iDllRefTableCount * sizeof(char*));
-
-	aCount = iOrigHdr->iDllRefTableCount;
-
-	for (int d = 0; d < iOrigHdr->iDllRefTableCount; ++d)
-		{
-			char* dllname = iData + iOrigHdr->iImportOffset + impBlock->iOffsetOfDllName;
-			char* curlyStart = strchr(dllname, '{');
-			char* dotStart = strrchr(dllname, '.');
-			
-			dllname[curlyStart - dllname] = '\0';
-			strcat(dllname,dotStart);
-			
-			nameList[d] = dllname;
-			TUint impfmt = iOrigHdr->ImportFormat();
-			impBlock = impBlock->NextBlock(impfmt); //Get next import block
-		}
-	return nameList;	
-}
-
-/** 
-Constructor intializes the class pointer members.
-
-@internalComponent
-@released
-
-@param aImageName - image file name
-*/
-E32Reader::E32Reader(char* aImageName)
-:ImageReader(aImageName)
-{
-	iInputStream.open(iImgFileName.c_str(), Ios::binary | Ios::in);
-	int fwdSlashOff = iImgFileName.find_last_of('/');
-	int bwdSlashOff = iImgFileName.find_last_of('\\');
-	int exeNameOff = (fwdSlashOff > bwdSlashOff) ? fwdSlashOff : bwdSlashOff;
-	iExeName = iImgFileName.substr(exeNameOff + 1);
-}
-
-/** 
-Destructor deletes the class pointer members.
-
-@internalComponent
-@released
-*/
-E32Reader::~E32Reader()
-{
-	iInputStream.close();
-	DELETE(iE32Image);
-}
-
-/** 
-Function responsible to say whether it is an e32 image or not.
-
-@internalComponent
-@released
-
-@param aImage - e32 image
-*/
-bool E32Reader::IsE32Image(char* aFile)
-{
-	if(E32Image::IsE32ImageFile(aFile))
-		return true;
-	return false;
-}
-
-/** 
-Funtion to read the whole e32 image file and write the contents into iData memeber
-
-@internalComponent
-@released
-*/
-void E32Reader::ReadImage()
-{
-	if( !iInputStream.is_open() )
-	{
-		cerr << "Error: " << "Can not open file" << iImgFileName.c_str() << endl;
-		exit(EXIT_FAILURE);
-	}
-	iE32Image = new E32Image();
-	iInputStream.seekg(0, Ios::end);
-	TUint32 aSz = iInputStream.tellg();
-	iInputStream.seekg(0, Ios::beg);
-	iE32Image->Adjust(aSz);
-	iE32Image->iFileSize = aSz;
-}
-
-/** 
-Function responsible to read the E32 image and put the data into E32ImageFile object.
-It is achieved using the operator >> overloaded function.
-
-@internalComponent
-@released
-*/
-void E32Reader::ProcessImage()
-{
-	iInputStream >> *iE32Image;
-	iExeAvailable = true;
-}
-
-/** 
-Function responsible to gather dependencies for one e32 image.
-
-@internalComponent
-@released
-
-@return iExeNamesVsDepListMap - returns all executable's dependencies
-*/
-ExeNamesVsDepListMap& E32Reader::GatherDependencies()
-{
-	int count=0;
-	char** nameList = iE32Image->GetImportExecutableNames(count);
-	int i = 0;
-	for(; i < count; ++i)
-	{
-		iDependencyList.push_back(String(nameList[i]));
-	}
-	iImageVsDepList.insert(std::make_pair(iExeName, iDependencyList));
-	return iImageVsDepList;
-}
-
-/** 
-Function responsible to return the dependency list of an e32 image.
-
-@internalComponent
-@released
-
-@return iDependencyList - returns all executable's dependencies
-*/
-const StringList& E32Reader::GetDependencyList()
-{
-	return iDependencyList;
-}
-
-/** 
-Function responsible prepare the ExeVsId map.
-
-@internalComponent
-@released
-*/
-void E32Reader::PrepareExeVsIdMap()
-{
-	IdData* id;
-	if(iExeVsIdData.size() == 0) //Is not already prepared
-	{
-		id = new IdData;
-		id->iUid = iE32Image->iOrigHdr->iUid1;
-		id->iDbgFlag = (iE32Image->iOrigHdr->iFlags & KImageDebuggable)? true : false;
-		TUint aHeaderFmt = E32ImageHeader::HdrFmtFromFlags(iE32Image->iOrigHdr->iFlags);
-		if (aHeaderFmt >= KImageHdrFmt_V)
-		{
-			E32ImageHeaderV* v = iE32Image->iHdr;
-			id->iSid = v->iS.iSecureId;
-			id->iVid = v->iS.iVendorId;
-		}
-		id->iFileOffset = 0;
-		iExeVsIdData[iExeName] = id;
-	}
-	id = KNull;
-}
-
-/** 
-Function responsible to return the Executable versus IdData container. 
-
-@internalComponent
-@released
-
-@return - returns iExeVsIdData
-*/
-const ExeVsIdDataMap& E32Reader::GetExeVsIdMap() const
-{
-	return iExeVsIdData;
-}
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+/**
+@file
+@internalComponent
+@released
+*/
+
+#include "e32reader.h"
+#include <f32image.h>
+
+/** 
+Constructor.
+
+@internalComponent
+@released
+*/
+E32Image::E32Image()
+:E32ImageFile() {
+}
+
+/** 
+Destructor.
+
+@internalComponent
+@released
+*/
+E32Image::~E32Image() {
+}
+
+/** 
+Function responsible to read the import section of an e32 image and return the dependency names.
+
+@internalComponent
+@released
+
+@param aCount - Number of imports found
+
+@return - returns the two dimensional 
+*/
+char** E32Image::GetImportExecutableNames(int& aCount) {
+	const E32ImportSection* isection = (const E32ImportSection*)(iData + iOrigHdr->iImportOffset);
+	const E32ImportBlock* impBlock = (const E32ImportBlock*)(isection + 1);
+
+	char** nameList = reinterpret_cast<char**>(new long[iOrigHdr->iDllRefTableCount]);
+
+	aCount = iOrigHdr->iDllRefTableCount;
+
+	for (int d = 0; d < iOrigHdr->iDllRefTableCount; ++d) {
+		char* dllname = iData + iOrigHdr->iImportOffset + impBlock->iOffsetOfDllName;
+		char* curlyStart = strchr(dllname, '{');
+		char* dotStart = strrchr(dllname, '.');
+
+		dllname[curlyStart - dllname] = '\0';
+		strcat(dllname,dotStart);
+
+		nameList[d] = dllname;
+		TUint impfmt = iOrigHdr->ImportFormat();
+		impBlock = impBlock->NextBlock(impfmt); //Get next import block
+	}
+	return nameList;	
+}
+
+/** 
+Constructor intializes the class pointer members.
+
+@internalComponent
+@released
+
+@param aImageName - image file name
+*/
+E32Reader::E32Reader(const char* aImageName)
+:ImageReader(aImageName) {
+	iInputStream.open(iImgFileName.c_str(), ios_base::binary | ios_base::in);
+	int fwdSlashOff = iImgFileName.find_last_of('/');
+	int bwdSlashOff = iImgFileName.find_last_of('\\');
+	int exeNameOff = (fwdSlashOff > bwdSlashOff) ? fwdSlashOff : bwdSlashOff;
+	iExeName = iImgFileName.substr(exeNameOff + 1);
+}
+
+/** 
+Destructor deletes the class pointer members.
+
+@internalComponent
+@released
+*/
+E32Reader::~E32Reader() {
+	
+	iInputStream.close();
+	DELETE(iE32Image);
+}
+
+/** 
+Function responsible to say whether it is an e32 image or not.
+
+@internalComponent
+@released
+
+@param aImage - e32 image
+*/
+bool E32Reader::IsE32Image(const char* aFile) {
+	if(E32Image::IsE32ImageFile(aFile))
+		return true;
+	return false;
+}
+
+/** 
+Funtion to read the whole e32 image file and write the contents into iData memeber
+
+@internalComponent
+@released
+*/
+void E32Reader::ReadImage() {
+	if( !iInputStream.is_open() ) {
+		cerr << "Error: " << "Can not open file" << iImgFileName.c_str() << endl;
+		exit(EXIT_FAILURE);
+	}
+	iE32Image = new E32Image();
+	iInputStream.seekg(0, ios_base::end);
+	TUint32 aSz = iInputStream.tellg();
+	iInputStream.seekg(0, ios_base::beg);
+	iE32Image->Adjust(aSz);
+	iE32Image->iFileSize = aSz;
+}
+
+/** 
+Function responsible to read the E32 image and put the data into E32ImageFile object.
+It is achieved using the operator >> overloaded function.
+
+@internalComponent
+@released
+*/
+void E32Reader::ProcessImage() {
+	iInputStream >> *iE32Image;
+	iExeAvailable = true;
+}
+
+/** 
+Function responsible to gather dependencies for one e32 image.
+
+@internalComponent
+@released
+
+@return iExeNamesVsDepListMap - returns all executable's dependencies
+*/
+ExeNamesVsDepListMap& E32Reader::GatherDependencies() {
+	int count=0; 
+	iDependencyList.clear();
+	char** names = iE32Image->GetImportExecutableNames(count); 
+	for(int i = 0 ; i < count; ++i) {
+		iDependencyList.push_back(names[i]);
+	}
+	put_item_to_map(iImageVsDepList,iExeName.c_str(), iDependencyList);
+	if(names){
+		delete [](reinterpret_cast<long*>(names));
+	}
+	return iImageVsDepList;
+}
+
+/** 
+Function responsible to return the dependency list of an e32 image.
+
+@internalComponent
+@released
+
+@return iDependencyList - returns all executable's dependencies
+*/
+const StringList& E32Reader::GetDependencyList() const {
+	return iDependencyList;
+}
+
+/** 
+Function responsible prepare the ExeVsId map.
+
+@internalComponent
+@released
+*/
+void E32Reader::PrepareExeVsIdMap() { 
+	if(iExeVsIdData.size() == 0) { //Is not already prepared 
+		IdData* id = new IdData;
+		id->iUid = iE32Image->iOrigHdr->iUid1;
+		id->iDbgFlag = (iE32Image->iOrigHdr->iFlags & KImageDebuggable)? true : false;
+		TUint aHeaderFmt = E32ImageHeader::HdrFmtFromFlags(iE32Image->iOrigHdr->iFlags);
+		if (aHeaderFmt >= KImageHdrFmt_V) {
+			E32ImageHeaderV* v = iE32Image->iHdr;
+			id->iSid = v->iS.iSecureId;
+			id->iVid = v->iS.iVendorId;
+		}
+		id->iFileOffset = 0;
+		put_item_to_map_2(iExeVsIdData,iExeName.c_str(),id); 
+	} 
+}
+
+/** 
+Function responsible to return the Executable versus IdData container. 
+
+@internalComponent
+@released
+
+@return - returns iExeVsIdData
+*/
+const ExeVsIdDataMap& E32Reader::GetExeVsIdMap() const {
+	return iExeVsIdData;
+}
--- a/imgtools/imgcheck/libimgutils/src/imagereader.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/libimgutils/src/imagereader.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,170 +1,162 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "imagereader.h"
-#include "romreader.h"
-#include "rofsreader.h"
-
-#include <time.h>
-
-/** 
-Constructor intializes the input stream.
-
-@internalComponent
-@released
-
-@param aFile - image file name
-*/
-ImageReader::ImageReader(const char* aFile)
-:iImgFileName(String(aFile)), iImageSize(0), iExeAvailable(false)
-{
-}
-
-/** 
-Destructor closes the input stream
-
-@internalComponent
-@released
-*/
-ImageReader::~ImageReader()
-{
-    ExeVsIdDataMap::iterator exeBegin = iExeVsIdData.begin();
-    ExeVsIdDataMap::iterator exeEnd = iExeVsIdData.end();
-    while(exeBegin != exeEnd)
-    {
-        DELETE(exeBegin->second);
-        ++exeBegin;
-    }
-	iHiddenExeList.clear();
-	iExecutableList.clear();
-	iImageVsDepList.clear();
-}
-
-/** 
-Function responsible to identify the image type
-
-@internalComponent
-@released
-
-@param aImageName - image filename
-*/
-EImageType ImageReader::ReadImageType(const String aImageName)
-{
-	char* imageName = (char*)aImageName.c_str();
-	Ifstream aIfs(imageName, Ios::in | Ios::binary);
-	if(!aIfs)
-	{
-		cout << "Error: " << "Cannot open file: " << imageName << endl;
-		exit(EXIT_FAILURE);
-	}
-	EImageType imgType = EUnknownImage;
-	char* aMagicW = new char[1024];
-	aIfs.read(aMagicW, 1024);
-	aIfs.close();
-	String magicWord(aMagicW, 1024);
-	if(aMagicW != NULL)
-		delete [] aMagicW;
-	aMagicW = 0;
-
-	if(RofsReader::IsRofsImage(magicWord))
-	{
-		imgType = ERofsImage;        
-	}
-	else if(RofsReader::IsRofsExtImage(magicWord))
-	{
-		imgType = ERofsExImage;
-	}
-	else if (RomReader::IsRomImage(magicWord))
-	{
-		imgType = ERomImage;
-	}
-	else if(RomReader::IsRomExtImage(magicWord))
-	{
-		imgType = ERomExImage;
-	}
-	return imgType;
-}
-
-/** 
-Dummy function.
-
-@internalComponent
-@released
-*/
-void ImageReader::PrepareExecutableList()
-{
-}
-
-/** 
-Function responsible to return the executable list
-
-@internalComponent
-@released
-
-@return iExecutableList - returns all executable names present in the image
-*/
-const StringList& ImageReader::GetExecutableList() const
-{
-	return iExecutableList;
-}
-
-/** 
-Function responsible to return the Hidden executables list
-
-@internalComponent
-@released
-
-@return iHiddenExeList - returns all hidden executable names present in the image
-*/
-const StringList& ImageReader::GetHiddenExeList() const
-{
-	return iHiddenExeList;
-}
-
-/** 
-Function responsible to return the image name which is under process
-
-@internalComponent
-@released
-
-@return iImgFileName - the image name which is under process
-*/
-String& ImageReader::ImageName()
-{
-	return iImgFileName;
-}
-
-/** 
-Function responsible to identify the executable presence.
-
-@internalComponent
-@released
-
-@return true - Executable is present
-        false - Executable is not present
-*/
-bool ImageReader::ExecutableAvailable()
-{
-	return iExeAvailable;
-}
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+/**
+@file
+@internalComponent
+@released
+*/
+
+#include "imagereader.h"
+#include "romreader.h"
+#include "rofsreader.h"
+
+#include <time.h>
+#include <boost/filesystem.hpp> 
+using namespace boost::filesystem;
+/** 
+Constructor intializes the input stream.
+
+@internalComponent
+@released
+
+@param aFile - image file name
+*/
+ImageReader::ImageReader(const char* aFile)
+:iImgFileName(aFile), iImageSize(0), iExeAvailable(false) {
+}
+
+/** 
+Destructor closes the input stream
+
+@internalComponent
+@released
+*/
+ImageReader::~ImageReader() {   
+	 for(ExeVsIdDataMap::iterator it = iExeVsIdData.begin();
+		it != iExeVsIdData.end(); it++) { 
+		if(it->second){		 
+			delete it->second ;
+			it->second = 0 ;
+		}
+	}
+	iHiddenExeList.clear();
+	iExecutableList.clear();
+	iImageVsDepList.clear(); 
+}
+
+/** 
+Function responsible to identify the image type
+
+@internalComponent
+@released
+
+@param aImageName - image filename
+*/
+EImageType ImageReader::ReadImageType(const string aImageName) {
+	const char* imageName = aImageName.c_str();
+	if(!exists(imageName)){
+		cout << "Error: ROM\\ROFS image not found."<< endl;
+		exit(EXIT_FAILURE);
+	}
+	ifstream aIfs(imageName, ios_base::in | ios_base::binary);
+	if(!aIfs) {
+		cout << "Error: " << "Cannot open file: " << imageName << endl;
+		exit(EXIT_FAILURE);
+	}
+	EImageType imgType = EUnknownImage;
+	char* aMagicW = new char[1024];
+	aIfs.read(aMagicW, 1024);
+	aIfs.close();
+	string magicWord(aMagicW, 1024);
+	if(aMagicW != NULL)
+		delete [] aMagicW;
+	aMagicW = 0;
+
+	if(RofsReader::IsRofsImage(magicWord)) {
+		imgType = ERofsImage;        
+	}
+	else if(RofsReader::IsRofsExtImage(magicWord)) {
+		imgType = ERofsExImage;
+	}
+	else if (RomReader::IsRomImage(magicWord)) {
+		imgType = ERomImage;
+	}
+	else if(RomReader::IsRomExtImage(magicWord)) {
+		imgType = ERomExImage;
+	}
+	return imgType;
+}
+
+/** 
+Dummy function.
+
+@internalComponent
+@released
+*/
+void ImageReader::PrepareExecutableList() {
+}
+
+/** 
+Function responsible to return the executable list
+
+@internalComponent
+@released
+
+@return iExecutableList - returns all executable names present in the image
+*/
+const StringList& ImageReader::GetExecutableList() const {
+	return iExecutableList;
+}
+
+/** 
+Function responsible to return the Hidden executables list
+
+@internalComponent
+@released
+
+@return iHiddenExeList - returns all hidden executable names present in the image
+*/
+const StringList& ImageReader::GetHiddenExeList() const {
+	return iHiddenExeList;
+}
+
+/** 
+Function responsible to return the image name which is under process
+
+@internalComponent
+@released
+
+@return iImgFileName - the image name which is under process
+*/
+const char* ImageReader::ImageName() const {
+	return iImgFileName.c_str();
+}
+
+/** 
+Function responsible to identify the executable presence.
+
+@internalComponent
+@released
+
+@return true - Executable is present
+false - Executable is not present
+*/
+bool ImageReader::ExecutableAvailable() {
+	return iExeAvailable;
+}
--- a/imgtools/imgcheck/libimgutils/src/rofsimage.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/libimgutils/src/rofsimage.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,108 +1,102 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "typedefs.h"
-#include "rofsimage.h"
-
-/** 
-Constructor.
-
-@internalComponent
-@released
-
-@param aReader - image reader pointer
-*/
-RofsImage::RofsImage(RCoreImageReader *aReader)
-: CCoreImage(aReader) ,
-iRofsHeader(0), iRofsExtnHeader(0),iAdjustment(0), 
-iImageType((RCoreImageReader::TImageType)0)
-{
-}
-
-/** 
-Destructor deletes iRofsHeader and iRofsExtnHeader.
-
-@internalComponent
-@released
-
-@param aReader - image reader pointer
-*/
-RofsImage::~RofsImage()
-{
-	DELETE(iRofsHeader);
-	DELETE(iRofsExtnHeader);
-}
-
-/** 
-Function responsible to read the ROFS image and to construct the tree for the 
-elements available in Directory section.
-
-@internalComponent
-@released
-
-@return - returns the error code
-*/
-TInt RofsImage::ProcessImage()
-{
-	int result = CreateRootDir();
-	if (result == KErrNone)
-	{
-		if (iReader->Open())
-		{
-			iImageType = iReader->ReadImageType();
-			if (iImageType == RCoreImageReader::E_ROFS)
-			{
-				iRofsHeader = new TRofsHeader;
-				result = iReader->ReadCoreHeader(*iRofsHeader);
-				if (result != KErrNone)
-					return result;
-				
-				SaveDirInfo(*iRofsHeader);
-				result = ProcessDirectory(0);
-			}
-			else if (iImageType == RCoreImageReader::E_ROFX)
-			{
-				iRofsExtnHeader = new TExtensionRofsHeader ;
-				result = iReader->ReadExtensionHeader(*iRofsExtnHeader);
-				if(result != KErrNone)
-					return result;
-
-				long filePos = iReader->FilePosition();
-				iAdjustment = iRofsExtnHeader->iDirTreeOffset - filePos;
-
-				SaveDirInfo(*iRofsExtnHeader);
-				result = ProcessDirectory(iAdjustment);
-			}
-			else
-			{
-				result = KErrNotSupported;
-			}
-		}
-		else
-		{
-			result = KErrGeneral;
-		}
-	}
-	return result;
-}
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+/**
+@file
+@internalComponent
+@released
+*/
+
+#include "typedefs.h"
+#include "rofsimage.h"
+
+/** 
+Constructor.
+
+@internalComponent
+@released
+
+@param aReader - image reader pointer
+*/
+RofsImage::RofsImage(RCoreImageReader *aReader)
+: CCoreImage(aReader) ,
+iRofsHeader(0), iRofsExtnHeader(0),iAdjustment(0), 
+iImageType((RCoreImageReader::TImageType)0) {
+}
+
+/** 
+Destructor deletes iRofsHeader and iRofsExtnHeader.
+
+@internalComponent
+@released
+
+@param aReader - image reader pointer
+*/
+RofsImage::~RofsImage() {
+	DELETE(iRofsHeader);
+	DELETE(iRofsExtnHeader);
+}
+
+/** 
+Function responsible to read the ROFS image and to construct the tree for the 
+elements available in Directory section.
+
+@internalComponent
+@released
+
+@return - returns the error code
+*/
+TInt RofsImage::ProcessImage() {
+	int result = CreateRootDir();
+	if (result == KErrNone) {
+		if (iReader->Open()) {
+			iImageType = iReader->ReadImageType();
+			if (iImageType == RCoreImageReader::E_ROFS) {
+				iRofsHeader = new TRofsHeader;
+				result = iReader->ReadCoreHeader(*iRofsHeader);
+				if (result != KErrNone){
+					cerr << "error is :"<< result << endl;
+					return result;
+				}
+
+
+				SaveDirInfo(*iRofsHeader);
+				result = ProcessDirectory(0);
+			}
+			else if (iImageType == RCoreImageReader::E_ROFX) {
+				iRofsExtnHeader = new TExtensionRofsHeader ;
+				result = iReader->ReadExtensionHeader(*iRofsExtnHeader);
+				if(result != KErrNone)
+					return result;
+
+				long filePos = iReader->FilePosition();
+				iAdjustment = iRofsExtnHeader->iDirTreeOffset - filePos;
+
+				SaveDirInfo(*iRofsExtnHeader);
+				result = ProcessDirectory(iAdjustment);
+			}
+			else {
+				result = KErrNotSupported;
+			}
+		}
+		else {
+			result = KErrGeneral;
+		}
+	}
+	return result;
+}
--- a/imgtools/imgcheck/libimgutils/src/rofsreader.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/libimgutils/src/rofsreader.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,384 +1,337 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-#include "rofsreader.h"
-#include "r_romnode.h"
-
-
-/** 
-Constructor intializes the class pointer members.
-
-@internalComponent
-@released
-
-@param aFile - image file name
-@param aImageType - image type
-*/
-RofsReader::RofsReader(char* aFile, EImageType aImageType)
-:ImageReader(aFile), iImageType(aImageType)
-{
-	iImageReader = new RCoreImageReader(aFile);
-	iImage = new RofsImage(iImageReader);
-	iInputStream.open(aFile, Ios::binary | Ios::in);
-}
-
-/** 
-Destructor deletes the class pointer members.
-
-@internalComponent
-@released
-*/
-RofsReader::~RofsReader()
-{
-	ExeVsE32ImageMap::iterator e32ImageBegin = iExeVsE32ImageMap.begin();
-    ExeVsE32ImageMap::iterator e32ImageEnd  = iExeVsE32ImageMap.end();
-	while(e32ImageBegin != e32ImageEnd)
-	{
-		DELETE(e32ImageBegin->second);
-		++e32ImageBegin;
-	}
-	iRootDirEntry->Destroy();
-	iExeVsOffsetMap.clear();
-	DELETE(iImageReader);
-	iInputStream.close();
-	iExeVsE32ImageMap.clear();
-}
-
-/** 
-Dummy function for compatibility
-
-@internalComponent
-@released
-*/
-void RofsReader::ReadImage()
-{
-}
-
-/** 
-Function responsible to 
-1. Invoke E32Imagefile process method which will read the header part and identifies the 
-   compression method.
-2. Prepare executable vs E32Image map, which will be used later to read the E32Image contents.
-
-@internalComponent
-@released
-*/
-void RofsReader::ProcessImage()
-{
-	int retVal = iImage->ProcessImage();
-	if(retVal != KErrNone)
-	{
-		exit(retVal);
-	}
-	iRootDirEntry = iImage->RootDirectory();
-	PrepareExeVsE32ImageMap(iRootDirEntry, iImage, iImageType, iInputStream, iExeVsE32ImageMap, iExeVsOffsetMap, iHiddenExeList);
-}
-
-/** 
-Function to check whether the node is an executable or not.
-
-@internalComponent
-@released
-
-@param aName - Executable name
-*/
-bool RofsReader::IsExecutable(String aName)
-{
-	unsigned int extOffset = aName.find_last_of('.');
-	if(extOffset != String::npos)
-	{
-		aName = aName.substr(extOffset);
-		if(aName.length() <= 4)
-		{
-			ReaderUtil::ToLower(aName);
-			if (aName.find(".exe") != String::npos || aName.find(".dll") != String::npos || 
-				aName.find(".prt") != String::npos || aName.find(".nif") != String::npos || 
-				aName.find(".tsy") != String::npos || aName.find(".pdl") != String::npos || 
-				aName.find(".csy") != String::npos || aName.find(".agt") != String::npos || 
-				aName.find(".ani") != String::npos || aName.find(".loc") != String::npos || 
-				aName.find(".pdd") != String::npos || aName.find(".ldd") != String::npos ||
-				aName.find(".drv") != String::npos) 
-			{
-				return true;
-			}
-		}
-	}
-	return false;
-}
-
-/** 
-Function responsible to prepare iExeVsE32ImageMap by traversing the tree recursively.
-
-@internalComponent
-@released
-
-@param aEntry - Root directory entry
-@param aImage - core image
-@param aImageType - Image type
-@param aInputStream - Input stream to read image file
-@param aExeVsE32ImageMap - Container to be filled
-@param aExeVsOffsetMap - Container to be filled
-@param aHiddenExeList - Hidden executables filled here.
-*/
-void RofsReader::PrepareExeVsE32ImageMap(TRomNode* aEntry, CCoreImage *aImage, EImageType aImageType, Ifstream& aInputStream, ExeVsE32ImageMap& aExeVsE32ImageMap, ExeVsOffsetMap& aExeVsOffsetMap, StringList& aHiddenExeList)
-{
-    String name((char*)aEntry->iName);
-	bool insideRofs = false;
-    E32Image* e32Image;
-    if(IsExecutable(name))
-    {
-		iExeAvailable = true;
-		//V9.1 images has hidden file offset as 0x0
-		//V9.2 to V9.6 has hidden file offset as 0xFFFFFFFFF
-        if(aEntry->iEntry->iFileOffset != KFileHidden && aEntry->iEntry->iFileOffset != KFileHidden_9_1)
-        {
-            long fileOffset = 0;
-            if(aImageType == ERofsExImage)
-            {
-				if(aEntry->iEntry->iFileOffset > (long)((RofsImage*)aImage)->iAdjustment)
-				{
-	            // File exists in Rofs extension 
-		            fileOffset = aEntry->iEntry->iFileOffset - ((RofsImage*)aImage)->iAdjustment;
-				}
-				else
-				{
-					insideRofs = true;
-				}
-            }
-            else
-            {
-	            // For rofs files
-	            fileOffset = aEntry->iEntry->iFileOffset;
-            }
-	            
-            aInputStream.seekg(fileOffset, Ios::beg);
-            /*
-            Due to the complexities involved in sending the physical file size to E32Reader class, 
-            here we avoided using it for gathering dependencies. Hence class E32ImageFile is used
-            directly.
-            */
-            e32Image = new E32Image();
-            e32Image->iFileSize = aEntry->iSize;
-            e32Image->Adjust(aEntry->iSize); //Initialise the data pointer to the file size
-            aInputStream >> *e32Image; //Input the E32 file to E32ImageFile class
-            aExeVsOffsetMap[ReaderUtil::ToLower(name)] = fileOffset;
-			if(!insideRofs)
-			{
-				aExeVsE32ImageMap.insert(std::make_pair(ReaderUtil::ToLower(name), e32Image));
-			}
-        }
-        else
-        {
-            aHiddenExeList.push_back(ReaderUtil::ToLower(name));
-        }
-    }
-
-    if(aEntry->Currentchild())
-    {
-        PrepareExeVsE32ImageMap(aEntry->Currentchild(), aImage, aImageType, aInputStream, aExeVsE32ImageMap, aExeVsOffsetMap, aHiddenExeList);
-    }
-    if(aEntry->Currentsibling())
-    {
-        PrepareExeVsE32ImageMap(aEntry->Currentsibling(), aImage, aImageType, aInputStream, aExeVsE32ImageMap, aExeVsOffsetMap, aHiddenExeList);
-    }
-}
-
-/** 
-Function responsible to the executable lists using the container iExeVsE32ImageMap.
-
-@internalComponent
-@released
-*/
-void RofsReader::PrepareExecutableList()
-{
-    ExeVsE32ImageMap::iterator e32ImageBegin = iExeVsE32ImageMap.begin();
-    ExeVsE32ImageMap::iterator e32ImageEnd  = iExeVsE32ImageMap.end();
-    E32Image* entry;
-    String name;
-    while(e32ImageBegin != e32ImageEnd)
-    {
-        entry = e32ImageBegin->second;
-        name = e32ImageBegin->first;
-        iExecutableList.push_back(name);
-        ++e32ImageBegin;
-    }
-	DeleteHiddenExecutableVsE32ImageEntry();
-}
-
-/** 
-Function responsible to delete the hidden executable nodes, in order to
-avoid the dependency data collection for the same.
-
-@internalComponent
-@released
-*/
-void RofsReader::DeleteHiddenExecutableVsE32ImageEntry()
-{
-	StringList::iterator hExeBegin = iHiddenExeList.begin();
-	StringList::iterator hExeEnd = iHiddenExeList.end();
-	ExeVsE32ImageMap::iterator loc;
-
-	while(hExeBegin != hExeEnd)
-	{
-		//Remove the hidden executable entry from executables vs RomNode Map
-		loc = iExeVsE32ImageMap.find(*hExeBegin);
-		if(loc != iExeVsE32ImageMap.end())
-		{
-			iExeVsE32ImageMap.erase(loc);
-		}
-		++hExeBegin;
-	}
-}
-
-/** 
-Function responsible to gather dependencies for all the executables using the container iExeVsE32ImageMap.
-
-@internalComponent
-@released
-
-@return iImageVsDepList - returns all executable's dependencies
-*/
-ExeNamesVsDepListMap& RofsReader::GatherDependencies()
-{
-	ExeVsE32ImageMap::iterator begin = iExeVsE32ImageMap.begin();
-	ExeVsE32ImageMap::iterator end = iExeVsE32ImageMap.end();
-
-	StringList executableList;
-	while(begin != end)
-	{
-		PrepareExeDependencyList((*begin).second, executableList);
-		iImageVsDepList.insert(std::make_pair((*begin).first, executableList));
-		executableList.clear();
-		++begin;
-	}
-	return iImageVsDepList;
-}
-
-/** 
-Function responsible to prepare the dependency list.
-This function can handle ROFS and ROFS extension images.
-
-@internalComponent
-@released
-
-@param - aE32Image, Using this, can get all the information about the executable
-@param - aExecutableList, Excutables placed into this list
-*/
-void RofsReader::PrepareExeDependencyList(E32Image* aE32Image, StringList& aExecutableList)
-{
-	int count = 0;
-	char** nameList = aE32Image->GetImportExecutableNames(count);
-	int i = 0;
-	String dependency;
-	for(; i < count; ++i)
-	{
-		dependency.assign(nameList[i]);
-		aExecutableList.push_back(ReaderUtil::ToLower(dependency));
-	}
-	DELETE(nameList);
-}
-
-/** 
-Function responsible to say whether it is an ROFS image or not.
-
-@internalComponent
-@released
-
-@param - aWord which has the identifier string
-*/
-bool RofsReader::IsRofsImage(String& aWord)
-{
-	if(aWord.find(KRofsImageIdentifier) == 0) //Identifier should start at the beginning
-	{
-		return true;
-	}
-	return false;
-}
-
-/** 
-Function responsible to say whether it is an ROFS extension image or not.
-
-@internalComponent
-@released
-
-@param - aWord which has the identifier string
-*/
-bool RofsReader::IsRofsExtImage(String& aWord)
-{
-	if(aWord.find(KRofsExtImageIdentifier) == 0) //Identifier should start at the beginning
-	{
-		return true;
-	}
-	return false;
-}
-
-/** 
-Function responsible to traverse through the the map using the container iExeVsE32ImageMap to collect 
-iExeVsIdData.
-
-@internalComponent
-@released
-*/
-void RofsReader::PrepareExeVsIdMap()
-{
-    ExeVsE32ImageMap::iterator begin = iExeVsE32ImageMap.begin();
-    ExeVsE32ImageMap::iterator end = iExeVsE32ImageMap.end();
-    String exeName;
-    E32Image* e32Image;
-    IdData* id;
-    if(iExeVsIdData.size() == 0) //Is not already prepared
-    {
-        while(begin != end)
-        {
-            exeName = begin->first;
-            e32Image = begin->second;
-			id = new IdData;
-			id->iUid = e32Image->iOrigHdr->iUid1;
-			id->iDbgFlag = (e32Image->iOrigHdr->iFlags & KImageDebuggable)? true : false;
-            TUint aHeaderFmt = E32ImageHeader::HdrFmtFromFlags(e32Image->iOrigHdr->iFlags);
-	        if (aHeaderFmt >= KImageHdrFmt_V)
-	        {
-                E32ImageHeaderV* v = e32Image->iHdr;
-                id->iSid = v->iS.iSecureId;
-                id->iVid = v->iS.iVendorId;
-	        }
-			id->iFileOffset = iExeVsOffsetMap[exeName];
-			iExeVsIdData[exeName] = id;
-            ++begin;
-        }
-    }
-	id = KNull;
-}
-
-/** 
-Function responsible to return the Executable versus IdData container. 
-
-@internalComponent
-@released
-
-@return - returns iExeVsIdData
-*/
-const ExeVsIdDataMap& RofsReader::GetExeVsIdMap() const
-{
-    return iExeVsIdData;
-}
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+/**
+ @file
+ @internalComponent
+ @released
+*/
+#include "rofsreader.h"
+#include "r_romnode.h"
+
+
+/** 
+Constructor intializes the class pointer members.
+
+@internalComponent
+@released
+
+@param aFile - image file name
+@param aImageType - image type
+*/
+RofsReader::RofsReader(const char* aFile, EImageType aImageType)
+:ImageReader(aFile), iImageType(aImageType) {
+	iImageReader = new RCoreImageReader(aFile);
+	iImage = new RofsImage(iImageReader);
+	iInputStream.open(aFile, ios_base::binary | ios_base::in);
+}
+
+/** 
+Destructor deletes the class pointer members.
+
+@internalComponent
+@released
+*/
+RofsReader::~RofsReader() {
+	 
+	 for(ExeVsE32ImageMap::iterator it = iExeVsE32ImageMap.begin();
+		it != iExeVsE32ImageMap.end(); it++) {
+		if(it->second){
+			delete it->second ;
+			it->second = 0 ;
+		}
+		
+	} 
+	 
+	iRootDirEntry = 0 ;
+	 
+	iExeVsOffsetMap.clear();
+	if(iImageReader){
+		delete iImageReader;
+		iImageReader = 0 ;
+	}
+	if(iImage){
+		delete iImage;
+		iImage = 0 ;
+	}
+	iInputStream.close();
+	iExeVsE32ImageMap.clear();
+}
+
+/** 
+Dummy function for compatibility
+
+@internalComponent
+@released
+*/
+void RofsReader::ReadImage() {
+}
+
+/** 
+Function responsible to 
+1. Invoke E32Imagefile process method which will read the header part and identifies the 
+   compression method.
+2. Prepare executable vs E32Image map, which will be used later to read the E32Image contents.
+
+@internalComponent
+@released
+*/
+void RofsReader::ProcessImage() {
+	int retVal = iImage->ProcessImage();
+	if(retVal != KErrNone) {
+		exit(retVal);
+	}
+	iRootDirEntry = iImage->RootDirectory();
+	PrepareExeVsE32ImageMap(iRootDirEntry, iImage, iImageType, iInputStream, iExeVsE32ImageMap, iExeVsOffsetMap, iHiddenExeList);
+}
+
+/** 
+Function to check whether the node is an executable or not.
+
+@internalComponent
+@released
+
+@param aName - Executable name
+*/
+bool RofsReader::IsExecutable(const string& aName) {
+	unsigned int extOffset = aName.find_last_of('.');
+	if(extOffset != string::npos) {
+		string ext = aName.substr(extOffset);
+		if(ext.length() <= 4) {
+			ReaderUtil::ToLower(ext);
+			if (ext.find(".exe") != string::npos || ext.find(".dll") != string::npos || 
+				ext.find(".prt") != string::npos || ext.find(".nif") != string::npos || 
+				ext.find(".tsy") != string::npos || ext.find(".pdl") != string::npos || 
+				ext.find(".csy") != string::npos || ext.find(".agt") != string::npos || 
+				ext.find(".ani") != string::npos || ext.find(".loc") != string::npos || 
+				ext.find(".pdd") != string::npos || ext.find(".ldd") != string::npos ||
+				ext.find(".drv") != string::npos)  {
+				return true;
+			}
+		}
+	}
+	return false;
+}
+
+/** 
+Function responsible to prepare iExeVsE32ImageMap by traversing the tree recursively.
+
+@internalComponent
+@released
+
+@param aEntry - Root directory entry
+@param aImage - core image
+@param aImageType - Image type
+@param aInputStream - Input stream to read image file
+@param aExeVsE32ImageMap - Container to be filled
+@param aExeVsOffsetMap - Container to be filled
+@param aHiddenExeList - Hidden executables filled here.
+*/
+void RofsReader::PrepareExeVsE32ImageMap(TRomNode* aEntry, CCoreImage *aImage, EImageType aImageType, ifstream& aInputStream, ExeVsE32ImageMap& aExeVsE32ImageMap, ExeVsOffsetMap& aExeVsOffsetMap, StringList& aHiddenExes) {
+    string name(aEntry->iName);
+	bool insideRofs = false;
+    E32Image* e32Image;
+    if(IsExecutable(name)) {
+		iExeAvailable = true;
+		//V9.1 images has hidden file offset as 0x0
+		//V9.2 to V9.6 has hidden file offset as 0xFFFFFFFFF
+        if(aEntry->iEntry->iFileOffset != KFileHidden && aEntry->iEntry->iFileOffset != KFileHidden_9_1) {
+            long fileOffset = 0;
+            if(aImageType == ERofsExImage) {
+				if(aEntry->iEntry->iFileOffset > (long)((RofsImage*)aImage)->iAdjustment) {
+	            // File exists in Rofs extension 
+		            fileOffset = aEntry->iEntry->iFileOffset - ((RofsImage*)aImage)->iAdjustment;
+				}
+				else {
+					insideRofs = true;
+				}
+            }
+            else {
+	            // For rofs files
+	            fileOffset = aEntry->iEntry->iFileOffset;
+            }
+	            
+            aInputStream.seekg(fileOffset, ios_base::beg);
+            /*
+            Due to the complexities involved in sending the physical file size to E32Reader class, 
+            here we avoided using it for gathering dependencies. Hence class E32ImageFile is used
+            directly.
+            */
+            e32Image = new E32Image();
+            e32Image->iFileSize = aEntry->iSize;
+            e32Image->Adjust(aEntry->iSize); //Initialise the data pointer to the file size
+            aInputStream >> *e32Image; //Input the E32 file to E32ImageFile class
+            put_item_to_map(aExeVsOffsetMap,aEntry->iName,fileOffset);
+			if(!insideRofs) {
+				put_item_to_map_2(aExeVsE32ImageMap,aEntry->iName, e32Image);
+				
+			}
+        }
+        else { 
+            aHiddenExes.push_back(aEntry->iName);
+        }
+    }
+
+    if(aEntry->Currentchild()) {
+        PrepareExeVsE32ImageMap(aEntry->Currentchild(), aImage, aImageType, aInputStream, aExeVsE32ImageMap, aExeVsOffsetMap, aHiddenExes);
+    }
+    if(aEntry->Currentsibling()) {
+        PrepareExeVsE32ImageMap(aEntry->Currentsibling(), aImage, aImageType, aInputStream, aExeVsE32ImageMap, aExeVsOffsetMap, aHiddenExes);
+    }
+}
+
+/** 
+Function responsible to the executable lists using the container iExeVsE32ImageMap.
+
+@internalComponent
+@released
+*/
+void RofsReader::PrepareExecutableList() { 
+	iExecutableList.clear();
+    for(ExeVsE32ImageMap::iterator it = iExeVsE32ImageMap.begin();
+		it != iExeVsE32ImageMap.end() ; it ++) { 
+        iExecutableList.push_back(it->first); 
+    }
+	DeleteHiddenExecutableVsE32ImageEntry();
+}
+
+/** 
+Function responsible to delete the hidden executable nodes, in order to
+avoid the dependency data collection for the same.
+
+@internalComponent
+@released
+*/
+void RofsReader::DeleteHiddenExecutableVsE32ImageEntry() { 
+	for(StringList::iterator it = iHiddenExeList.begin();
+		it != iHiddenExeList.end(); it++){ 
+		//Remove the hidden executable entry from executables vs RomNode Map
+		ExeVsE32ImageMap::iterator pos = iExeVsE32ImageMap.find(*it);
+		if(pos != iExeVsE32ImageMap.end()) { 
+			if(pos->second)
+				delete pos->second ;
+			iExeVsE32ImageMap.erase(pos);
+		} 
+	}
+}
+
+/** 
+Function responsible to gather dependencies for all the executables using the container iExeVsE32ImageMap.
+
+@internalComponent
+@released
+
+@return iImageVsDepList - returns all executable's dependencies
+*/
+ExeNamesVsDepListMap& RofsReader::GatherDependencies() { 
+
+	StringList executables;
+	for(ExeVsE32ImageMap::iterator it = iExeVsE32ImageMap.begin() ; 
+		it != iExeVsE32ImageMap.end() ; it++) {
+		PrepareExeDependencyList(it->second, executables);
+		put_item_to_map(iImageVsDepList,it->first, executables);
+		executables.clear(); 
+	}
+	return iImageVsDepList;
+}
+
+/** 
+Function responsible to prepare the dependency list.
+This function can handle ROFS and ROFS extension images.
+
+@internalComponent
+@released
+
+@param - aE32Image, Using this, can get all the information about the executable
+@param - aExecutables, Excutables placed into this list
+*/
+void RofsReader::PrepareExeDependencyList(E32Image* aE32Image, StringList& aExecutables) {
+	int count = 0;
+	char** names = aE32Image->GetImportExecutableNames(count); 
+	for(int i = 0 ; i < count; ++i) { 
+		aExecutables.push_back(names[i]);
+	}
+	if(names){
+		delete [](reinterpret_cast<long*>(names));
+	}
+}
+
+/** 
+Function responsible to say whether it is an ROFS image or not.
+
+@internalComponent
+@released
+
+@param - aWord which has the identifier string
+*/
+bool RofsReader::IsRofsImage(const string& aWord) {
+	return (aWord.find(KRofsImageIdentifier) == 0);//Identifier should start at the beginning
+ 
+}
+
+/** 
+Function responsible to say whether it is an ROFS extension image or not.
+
+@internalComponent
+@released
+
+@param - aWord which has the identifier string
+*/
+bool RofsReader::IsRofsExtImage(const string& aWord) {
+	return (aWord.find(KRofsExtImageIdentifier) == 0) ;//Identifier should start at the beginning
+}
+
+/** 
+Function responsible to traverse through the the map using the container iExeVsE32ImageMap to collect 
+iExeVsIdData.
+
+@internalComponent
+@released
+*/
+void RofsReader::PrepareExeVsIdMap() { 
+    if(iExeVsIdData.size() == 0) {//Is not already prepared 
+        for(ExeVsE32ImageMap::iterator it = iExeVsE32ImageMap.begin();
+			it != iExeVsE32ImageMap.end() ; it++) {
+            string exeName(it->first);
+            E32Image* e32Image = it->second;
+			IdData* id = new IdData;
+			id->iUid = e32Image->iOrigHdr->iUid1;
+			id->iDbgFlag = (e32Image->iOrigHdr->iFlags & KImageDebuggable)? true : false;
+            TUint aHeaderFmt = E32ImageHeader::HdrFmtFromFlags(e32Image->iOrigHdr->iFlags);
+	        if (aHeaderFmt >= KImageHdrFmt_V) {
+                E32ImageHeaderV* v = e32Image->iHdr;
+                id->iSid = v->iS.iSecureId;
+                id->iVid = v->iS.iVendorId;
+	        }
+			id->iFileOffset = iExeVsOffsetMap[exeName]; 
+			put_item_to_map_2(iExeVsIdData,exeName,id); 
+        }
+    } 
+}
+
+/** 
+Function responsible to return the Executable versus IdData container. 
+
+@internalComponent
+@released
+
+@return - returns iExeVsIdData
+*/
+const ExeVsIdDataMap& RofsReader::GetExeVsIdMap() const {
+    return iExeVsIdData;
+}
--- a/imgtools/imgcheck/libimgutils/src/romimageheader.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/libimgutils/src/romimageheader.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,62 +1,59 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-#include "romimageheader.h"
-/** 
-Constructor intializes the Rom image header.
-
-@internalComponent
-@released
-
-@param aHdr - ROM laoder header
-@param aImgType - Image type
-*/
-RomImageHeader::RomImageHeader(char* aHdr, EImageType aImgType , bool aNoRomLoaderHeader)
-{
-	switch(aImgType)
-	{
-	case ERomImage:
-		if(!aNoRomLoaderHeader)
-		{
-		iLoaderHdr = (TRomLoaderHeader*)aHdr;
-		iRomHdr = (TRomHeader*)(aHdr + sizeof(TRomLoaderHeader));
-		}
-		else
-		{
-			iRomHdr = (TRomHeader*)(aHdr);
-		}
-		iExtRomHdr = 0;
-		break;
-
-	case ERomExImage:
-		iExtRomHdr = (TExtensionRomHeader*)(aHdr);
-		iRomHdr = 0;
-		iLoaderHdr = 0;
-		break;
-	default:
-	 iLoaderHdr = 0 ;
-	 iRomHdr = 0;
-	 iExtRomHdr = 0 ; 
-		break ;
-	}
-}
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+/**
+@file
+@internalComponent
+@released
+*/
+#include "romimageheader.h"
+/** 
+Constructor intializes the Rom image header.
+
+@internalComponent
+@released
+
+@param aHdr - ROM laoder header
+@param aImgType - Image type
+*/
+RomImageHeader::RomImageHeader(char* aHdr, EImageType aImgType , bool aNoRomLoaderHeader) {
+	switch(aImgType)
+	{
+	case ERomImage:
+		if(!aNoRomLoaderHeader) {
+			iLoaderHdr = (TRomLoaderHeader*)aHdr;
+			iRomHdr = (TRomHeader*)(aHdr + sizeof(TRomLoaderHeader));
+		}
+		else {
+			iRomHdr = (TRomHeader*)(aHdr);
+		}
+		iExtRomHdr = 0;
+		break;
+
+	case ERomExImage:
+		iExtRomHdr = (TExtensionRomHeader*)(aHdr);
+		iRomHdr = 0;
+		iLoaderHdr = 0;
+		break;
+	default:
+		iLoaderHdr = 0 ;
+		iRomHdr = 0;
+		iExtRomHdr = 0 ; 
+		break ;
+	}
+}
--- a/imgtools/imgcheck/libimgutils/src/romreader.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/libimgutils/src/romreader.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,804 +1,725 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "romreader.h"
-#include "romfsentry.h"
-#include "romimageheader.h"
-#include  <e32rom.h>
-#include  <e32ldr.h>
-#include  <iostream>
-#include  <algorithm>
-#include  <functional>
-
-void InflateUnCompress(unsigned char* source, int sourcesize, unsigned char* dest, int destsize);
-
-/** 
-Static variable to mark whether TRomLoaderHeader is present in the ROM image or not.
-
-@internalComponent
-@released
-*/
-bool RomReader::iNoRomLoaderHeader = false;
-
-/** 
-Constructor intializes the class pointer members and member variables.
-
-@internalComponent
-@released
-
-@param aFile - image file name
-@param aImageType - image type
-*/
-RomReader::RomReader(const char* aFile, EImageType aImgType) 
-: ImageReader(aFile), iImageHeader(0), iData(0), iImgType(aImgType)
-{
-	iRomImageRootDirEntry = new RomImageDirEntry("");
-}
-
-/** 
-Destructor deletes the class pointer members.
-
-@internalComponent
-@released
-*/
-RomReader::~RomReader()
-{
-	delete [] iData;
-	iRomImageRootDirEntry->Destroy();
-	iRomImageRootDirEntry = 0;
-	DELETE(iImageHeader);
-	iRootDirList = 0;
-	iExeVsRomFsEntryMap.clear();
-}
-
-/** 
-Function responsible to read the whole image and assign it to an member
-
-@internalComponent
-@released
-*/
-void RomReader::ReadImage()
-{
-	iInputStream.open(iImgFileName.c_str(), Ios::binary | Ios::in);
-	if(!iInputStream.is_open())
-	{
-		cout << "Error: " << "Can not open file: " << ImageName().c_str() << endl;
-		exit(EXIT_FAILURE);
-	}
-	iInputStream.seekg(0, Ios::end);
-	iImageSize = iInputStream.tellg();
-	iData = new unsigned char[iImageSize];
-	memset(iData, 0, iImageSize);
-	iInputStream.seekg(0, Ios::beg);
-	iInputStream.read((char*)iData, iImageSize);
-	iInputStream.close();
-}
-
-
-/** 
-Function responsible to return the compression type
-Can handle ROM and Extension ROM images.
-
-@internalComponent
-@released
-
-@return - returns the compression type
-*/
-const unsigned long int RomReader::ImageCompressionType() const
-{
-	if(iImageHeader->iRomHdr)
-		return iImageHeader->iRomHdr->iCompressionType;
-	else
-		return iImageHeader->iExtRomHdr->iCompressionType;
-}
-
-
-/** 
-Function responsible to return the Rom header pointer address
-Can handle ROM and Extension ROM images.
-
-@internalComponent
-@released
-
-@return - returns the Rom header pointer address
-*/
-const char* RomReader::RomHdrPtr() const
-{
-	if(iImageHeader->iRomHdr)
-		return (char*)(iImageHeader->iRomHdr);
-	else
-		return (char*)(iImageHeader->iExtRomHdr);
-}
-
-
-/** 
-Function responsible to return the Rom base address in the image
-Can handle ROM and Extension ROM images.
-
-@internalComponent
-@released
-
-@return - returns the Rom base address
-*/
-const unsigned long int RomReader::RomBase() const
-{
-	if(iImageHeader->iRomHdr)
-		return iImageHeader->iRomHdr->iRomBase ;
-	else
-		return iImageHeader->iExtRomHdr->iRomBase;
-}
-
-
-/** 
-Function responsible to return the Rom root directory list
-Can handle ROM and Extension ROM images.
-
-@internalComponent
-@released
-
-@return - returns the Rom root directory list
-*/
-const unsigned long int RomReader::RootDirList() const
-{
-	if(iImageHeader->iRomHdr)
-		return iImageHeader->iRomHdr->iRomRootDirectoryList;
-	else
-		return iImageHeader->iExtRomHdr->iRomRootDirectoryList;
-}
-
-
-/** 
-Function responsible to return the Rom header size
-Can handle ROM and Extension ROM images.
-
-@internalComponent
-@released
-
-@return - returns the Rom header size
-*/
-const unsigned int RomReader::HdrSize() const
-{
-	if(iImageHeader->iRomHdr) 
-		return (sizeof(TRomLoaderHeader) + sizeof(TRomHeader));
-	else
-		return sizeof(TExtensionRomHeader);
-}
-
-/** 
-Function responsible to return the Rom image size
-Can handle ROM and Extension ROM images.
-
-@internalComponent
-@released
-
-@return - returns the Rom Image size
-*/
-const unsigned int RomReader::ImgSize() const
-{
-	if(ImageCompressionType() == KUidCompressionDeflate) 
-		return iImageHeader->iRomHdr->iUncompressedSize;
-	else
-		return iImageSize;
-}
-
-/** 
-Function responsible to process the ROM image
-1. Read the header.
-2. Identify the compression type.
-3. If the image is compressed then uncompress and update the image content buffer iData.
-4. Build the directory tree by reading all the Rood and subdirectory elements.
-
-@internalComponent
-@released
-*/
-void RomReader::ProcessImage()
-{
-	if(iImageSize > sizeof(TRomLoaderHeader) || iImageSize > sizeof(TExtensionRomHeader))
-	{
-	iImageHeader = new RomImageHeader((char*)iData, iImgType, iNoRomLoaderHeader);
-	
-	if(ImageCompressionType() == KUidCompressionDeflate)
-	{
-		unsigned int aDataStart = HdrSize();
-		unsigned char* aData = new unsigned char[iImageHeader->iRomHdr->iUncompressedSize + aDataStart];
-		InflateUnCompress((iData + aDataStart), iImageHeader->iRomHdr->iCompressedSize, (aData + aDataStart), iImageHeader->iRomHdr->iUncompressedSize);
-		memcpy(aData, iData, aDataStart);
-		delete [] iData;
-
-		iData = aData;
-		//update the header fields...
-		if(iImgType == ERomImage)
-		{
-			iImageHeader->iLoaderHdr = (TRomLoaderHeader*)iData;
-			iImageHeader->iRomHdr = (TRomHeader*)(iData + sizeof(TRomLoaderHeader));
-		}
-	}
-	else if(ImageCompressionType() != 0)
-	{
-		std::cout << "Error: Invalid image: " << ImageName() << std::endl;
-		exit(EXIT_FAILURE);
-	}
-	else if (iImageHeader->iRomHdr && iImageHeader->iRomHdr->iRomPageIndex) // paged ROM
-	{
-		const int KPageSize = 0x1000;
-		TRomHeader *pRomHdr = iImageHeader->iRomHdr;
-		unsigned int headerSize = HdrSize();
-
-        TInt numPages = (pRomHdr->iPageableRomStart + pRomHdr->iPageableRomSize+KPageSize-1)/KPageSize;
-		unsigned char* aData = new unsigned char[pRomHdr->iUncompressedSize + headerSize];
-		unsigned char* dest = aData + sizeof(TRomLoaderHeader) + pRomHdr->iPageableRomStart;
-		SRomPageInfo* pi = (SRomPageInfo*)((unsigned char*)pRomHdr + pRomHdr->iRomPageIndex);
-                CBytePair bpe(EFalse);
-
-		for(int i = 0; i < numPages; i++, pi++)
-			{
-			if (pi->iPagingAttributes != SRomPageInfo::EPageable) // skip uncompressed part at the beginning of ROM image
-				continue;
-			
-			switch(pi->iCompressionType)
-				{
-				case SRomPageInfo::ENoCompression:
-					memcpy(dest, (unsigned char*)pRomHdr + pi->iDataStart, pi->iDataSize);
-					dest += pi->iDataSize;
-					break;
-
-				case SRomPageInfo::EBytePair:
-					{
-					unsigned char* srcNext = 0;
-					int unpacked = bpe.Decompress(dest, KPageSize, (unsigned char*)pRomHdr + pi->iDataStart, pi->iDataSize, srcNext);
-					if (unpacked  <  0)
-						{
-						delete [] aData;
-						std::cout  << "Error:" <<  "Corrupted BytePair compressed ROM image"  <<  std::endl;
-						exit(EXIT_FAILURE);
-						}
-
-					dest += unpacked;
-					break;
-					}
-
-				default:
-					delete [] aData;
-					std::cout  << "Error:" << "Undefined compression type"  <<  std::endl;
-					exit(EXIT_FAILURE);
-				}
-			}
-	
-		memcpy(aData, iData, sizeof(TRomLoaderHeader) + pRomHdr->iPageableRomStart);
-		delete [] iData;
-
-		iData = aData;
-
-		//update the header fields...
-		if(iImgType == ERomImage)
-		{
-			iImageHeader->iLoaderHdr = (TRomLoaderHeader*)iData;
-			iImageHeader->iRomHdr = (TRomHeader*)(iData + sizeof(TRomLoaderHeader));
-		}
-	}
-
-	unsigned long int aOff = RootDirList() - RomBase();
-	iRootDirList = (TRomRootDirectoryList*)(RomHdrPtr() + aOff);
-	int aDirs = 0;
-	TRomDir	*aRomDir;
-	while(aDirs  <  iRootDirList->iNumRootDirs)
-	{
-		aOff = iRootDirList->iRootDir[aDirs].iAddressLin - RomBase();
-		aRomDir = (TRomDir*)(RomHdrPtr() + aOff);
-
-		BuildDir(aRomDir, iRomImageRootDirEntry);
-		aDirs++;
-	}
-	}
-	else
-	{
-		std::cout << "Error: " << "Invalid image: " << iImgFileName.c_str() << std::endl;
-		exit(EXIT_FAILURE);
-	}
-}
-
-
-/** 
-Function responsible to Get Rom directory table
-
-@internalComponent
-@released
-
-@param aBase - base poniter
-@param aCount - No of entries in the table
-@param aRomDir - Current Rom directory.
-*/
-void RomReader::GetRomDirTbl(short int** aBase, short int& aCount, TRomDir *aRomDir)
-{
-	short int *aSubDirCnt = 0;
-	short int *aFileCnt = 0;
-
-	//Sub directories in this directories
-	aSubDirCnt = (short int*)((char*)aRomDir + aRomDir->iSize + sizeof(aRomDir->iSize));
-	//Files within this directory
-	aFileCnt = aSubDirCnt+1;
-	aCount = (*aFileCnt + *aSubDirCnt);
-	*aBase = aFileCnt+1;
-}
-
-
-/** 
-Function responsible to Build directory tree.
-
-@internalComponent
-@released
-
-@param aDir - directory
-@param aPaFSEntry - Parent RomImageFSEntry
-*/
-void RomReader::BuildDir(TRomDir* aDir, RomImageFSEntry* aPaFSEntry)
-{
-
-	short int			*aBase, aCount;
-
-	GetRomDirTbl(&aBase, aCount, aDir);
-	/**Images built using option -no-sorted-romfs are compatible with Symbian OS v6.1.
-	But imgcheck tool supports only Symbian OS v9.1 to Future versions.
-	*/
-	if(aCount <= 0)
-	{
-		cerr << "Error: Invalid Image " << iImgFileName.c_str() << endl;
-		exit(EXIT_FAILURE);
-	}
-	BuildDir(aBase, aCount, aDir, aPaFSEntry);
-}
-
-
-/** 
-Function responsible to add the read directory or file into tree.
-
-@internalComponent
-@released
-
-@param aOffsetTbl - Table offset
-@param aOffsetTblCount - No of entries in the table
-@param aPaRomDir - Parent TRomDir
-@param aPaFSEntry - Parent RomImageFSEntry
-*/
-void RomReader::BuildDir(short int *aOffsetTbl, short int aOffsetTblCount, 
-							   TRomDir *aPaRomDir, RomImageFSEntry* aPaFSEntry)
-{
-	RomImageFSEntry *aNewFSEntry;
-	TRomDir	*aNewDir;
-	TRomEntry *aRomEntry;
-	unsigned long int aOffsetFromBase;
-	unsigned int aOffset;
-	String	aName;
-	char	*aPtr;
-
-	while(aOffsetTblCount--)
-	{
-		aOffsetFromBase = *aOffsetTbl;
-		aOffsetFromBase  <<= 2;
-		aRomEntry = (TRomEntry*)((char*)aPaRomDir + sizeof(int) + aOffsetFromBase);
-		aPtr = (char*)aRomEntry->iName;
-		Name(aName, aPtr, aRomEntry->iNameLength);
-
-		if(aRomEntry->iAtt & 0x10)//KEntryAttDir
-		{
-			aNewFSEntry = new RomImageDirEntry((char*)aName.data());
-			AddChild(aPaFSEntry, aNewFSEntry, KNull);
-
-			aOffset = aRomEntry->iAddressLin - RomBase();
-			aNewDir = (TRomDir*)(RomHdrPtr() + aOffset);
-			BuildDir(aNewDir, aNewFSEntry);
-		}
-		else
-		{
-			aNewFSEntry = new RomImageFileEntry((char*)aName.data());
-			AddChild(aPaFSEntry, aNewFSEntry, aRomEntry);
-		}
-		aOffsetTbl++;
-	}
-}
-
-
-/** 
-Function responsible to add current entry as child to aPa.
-
-@internalComponent
-@released
-
-@param aPa - Parent RomImageFSEntry.
-@param aChild - child RomImageFSEntry.
-@param aRomEntry - Current entry.
-*/
-void RomReader::AddChild(RomImageFSEntry *aPa, RomImageFSEntry *aChild, TRomEntry* aRomEntry)
-{
-	if(!aPa->iChildren)
-	{
-		aPa->iChildren = aChild;
-	}
-	else
-	{
-		RomImageFSEntry *aLast = aPa->iChildren;
-		while(aLast->iSibling)
-			aLast = aLast->iSibling;
-
-		aLast->iSibling = aChild;
-	}
-
-	if(!aChild->IsDirectory())
-	{
-		TRomImageHeader* aImgHdr;
-		unsigned long int aOff;
-		RomImageFileEntry* entry = (RomImageFileEntry*)aChild;
-		entry->iTRomEntryPtr = aRomEntry;
-		if(aRomEntry->iAddressLin > RomBase())
-		{
-			aOff = aRomEntry->iAddressLin - RomBase();
-			aImgHdr = (TRomImageHeader*)(RomHdrPtr() + aOff);
-			entry->ImagePtr.iRomFileEntry = aImgHdr;
-			unsigned char aUid1[4];
-            memcpy(aUid1, &((RomImageFileEntry*)aChild)->ImagePtr.iRomFileEntry->iUid1, 4);
-
-			//Skip the E32 executables included as a DATA files in ROM image.
-			if(ReaderUtil::IsExecutable(aUid1) && aImgHdr->iCodeAddress > RomBase() && 
-			aImgHdr->iCodeAddress < (RomBase() + ImgSize()))
-			{
-				iExeAvailable = true;
-				entry->iExecutable = true;
-                iExeVsRomFsEntryMap.insert(std::make_pair(entry->iName, aChild));
-			}
-			else
-			{
-				entry->iExecutable = false;
-				entry->ImagePtr.iDataFileAddr = aRomEntry->iAddressLin;
-			}
-		}
-		else
-		{
-			entry->ImagePtr.iRomFileEntry = KNull;
-		}
-	}
-	if(aPa != iRomImageRootDirEntry)
-	{
-		aChild->iPath = aPa->iPath;
-		aChild->iPath += KDirSeperaor;
-		aChild->iPath += aPa->iName.data();
-	}
-}
-
-
-/** 
-Function responsible to return the complete name by taking its unicode and length.
-
-@internalComponent
-@released
-
-@param aName - Name to be returned
-@param aUnicodeName - Unicode name
-@param aLen - Length of the name
-*/
-void RomReader::Name(String& aName, const char * aUnicodeName, const int aLen)
-{
-	int aPos = 0;
-	int uncodeLen = aLen  <<  1;
-	aName = ("");
-	while(aPos  <  uncodeLen)
-	{
-		if(aUnicodeName[aPos])
-			aName += aUnicodeName[aPos];
-		aPos++;
-	}
-}
-
-/** 
-Function responsible to prepare Executable List by traversing through iExeVsRomFsEntryMap
-
-@internalComponent
-@released
-*/
-void RomReader::PrepareExecutableList()
-{
-    ExeVsRomFsEntryMap::iterator exeBegin = iExeVsRomFsEntryMap.begin();
-    ExeVsRomFsEntryMap::iterator exeEnd = iExeVsRomFsEntryMap.end();
-    while(exeBegin != exeEnd)
-    {
-        String str = exeBegin->first;
-        iExecutableList.push_back(ReaderUtil::ToLower(str));
-        ++exeBegin;
-    }
-}
-
-/** 
-Function responsible to create address vs executable map.
-Later this address is used as a key to get executable name
-
-@internalComponent
-@released
-*/
-void RomReader::PrepareAddVsExeMap()
-{
-    ExeVsRomFsEntryMap::iterator exeBegin = iExeVsRomFsEntryMap.begin();
-    ExeVsRomFsEntryMap::iterator exeEnd = iExeVsRomFsEntryMap.end();
-    while(exeBegin != exeEnd)
-    {
-   		UintVsString sizeVsExeName;
-		unsigned int address;
-		RomImageFileEntry* fileEntry = (RomImageFileEntry*)exeBegin->second;
-		TRomImageHeader	*aRomImgEntry = fileEntry->ImagePtr.iRomFileEntry;
-		if(aRomImgEntry != KNull)
-		{
-			address = aRomImgEntry->iCodeAddress;
-			sizeVsExeName[aRomImgEntry->iCodeSize] = ReaderUtil::ToLower(exeBegin->second->iName);
-		}
-		else
-		{
-			address = fileEntry->iTRomEntryPtr->iAddressLin;
-			sizeVsExeName[fileEntry->iTRomEntryPtr->iSize] = ReaderUtil::ToLower(exeBegin->second->iName);
-		}
-		iAddVsExeMap.insert(std::make_pair(address, sizeVsExeName));
-		iImageAddress.push_back(address);
-        ++exeBegin;
-    }
-	std::sort(iImageAddress.begin(), iImageAddress.end(), std::greater < unsigned int>());
-}
-
-/** 
-Function responsible to say whether it is an ROM image or not.
-
-@internalComponent
-@released
-
-@param aWord - which has the identifier string
-@return - returns true or false.
-*/
-bool RomReader::IsRomImage(const String& aWord)
-{
-	//Epoc Identifier should start at 0th location, Rom Identifier should start at 8th location
-	if((aWord.find(KEpocIdentifier) == 0) && (aWord.find(KRomImageIdentifier) == 8))
-	{
-		return true;
-	}
-	else
-	{
-		iNoRomLoaderHeader = true;
-		//TRomLoaderHeader is not present
-		TRomHeader *romHdr = (TRomHeader*)aWord.c_str();
-	    /**If the ROM image is built without TRomLoaderHeaderi, ROM specific identifier will not be available
-		hence these two header variables used.*/
-		if((romHdr->iRomBase >= KRomBase) && (romHdr->iRomRootDirectoryList > KRomBase) 
-			&& (romHdr->iRomBase < KRomBaseMaxLimit) && (romHdr->iRomRootDirectoryList < KRomBaseMaxLimit))
-		{
-			return true;
-		}
-	}
-	return false;
-}
-
-/** 
-Function responsible to say whether it is an ROM extension image or not.
-
-@internalComponent
-@released
-
-@param aWord - which has the identifier string
-@return - retruns true or false.
-*/
-bool RomReader::IsRomExtImage(const String& aWord)
-{
-    if(aWord.at(0) == KNull && aWord.at(1) == KNull &&
-	aWord.at(2) == KNull && aWord.at(3) == KNull &&
-    aWord.at(4) == KNull && aWord.at(5) == KNull)
-    {
-	    //Since no specific identifier is present in the ROM Extension image these two header variables used.
-	    TExtensionRomHeader* romHdr = (TExtensionRomHeader*)aWord.c_str();
-	    if((romHdr->iRomBase > KRomBase) && (romHdr->iRomRootDirectoryList > KRomBase)
-			&& (romHdr->iRomBase < KRomBaseMaxLimit) && (romHdr->iRomRootDirectoryList < KRomBaseMaxLimit))
-	    {
-		    return true;
-	    }
-    }
-	return false;
-}
-
-/** 
-Function responsible to gather dependencies for all the executables.
-
-@internalComponent
-@released
-
-@return iImageVsDepList - returns all executable's dependencies
-*/
-ExeNamesVsDepListMap& RomReader::GatherDependencies()
-{
-	PrepareAddVsExeMap();
-	ExeVsRomFsEntryMap::iterator exeBegin = iExeVsRomFsEntryMap.begin();
-    ExeVsRomFsEntryMap::iterator exeEnd = iExeVsRomFsEntryMap.end();
-    while(exeBegin != exeEnd)
-    {
-		if(((RomImageFileEntry*)exeBegin->second)->iTRomEntryPtr->iAddressLin > RomBase())
-		{
-			StringList importExecutableNameList;
-			CollectImportExecutableNames(exeBegin->second, importExecutableNameList);
-			iImageVsDepList.insert(std::make_pair(exeBegin->second->iName, importExecutableNameList));
-		}
-        ++exeBegin;
-	}
-	return iImageVsDepList;
-}
-
-/** 
-Function responsible to read the dependency names.
-
-@internalComponent
-@released
-
-@param aRomReader - ROM reader pointer
-@param aEntry - Current RomImageFSEntry
-@param aImportExecutableNameList - Executable list.(output)
-*/
-void RomReader::CollectImportExecutableNames(const RomImageFSEntry* aEntry, StringList& aImportExecutableNameList)
-{
-	unsigned int sectionOffset = 0;
-	unsigned int codeSize = 0;
-	unsigned int dependencyAddress = 0;
-	unsigned int* codeSection = 0;
-	bool patternFound = false;
-
-	RomImageFileEntry* fileEntry = (RomImageFileEntry*)aEntry;
-	TRomImageHeader	*romImgEntry = fileEntry->ImagePtr.iRomFileEntry;
-	sectionOffset = romImgEntry->iCodeAddress - RomBase();
-	codeSection = (unsigned int*)((char*)RomHdrPtr() + sectionOffset);
-	codeSize = romImgEntry->iCodeSize;
-
-	UintVsString* CodeSizeVsExeNameAddress = 0;
-	RomAddrVsExeName::iterator addVsSizeExeName;
-	UintVsString::iterator CodeSizeVsExeName;
-	// Checking for LDR Instruction in PLT section(Inside Code section)
-	// to get the import address.
-	while(codeSize > 0)
-	{
-		if(*codeSection++ == KLdrOpcode)
-		{
-			patternFound = true;
-			dependencyAddress = *codeSection++;
-			addVsSizeExeName = iAddVsExeMap.find(CodeSectionAddress(dependencyAddress));
-			CodeSizeVsExeNameAddress = &addVsSizeExeName->second;
-			CodeSizeVsExeName = CodeSizeVsExeNameAddress->begin();
-			if(!(dependencyAddress < (addVsSizeExeName->first + CodeSizeVsExeName->first)))
-			{
-				aImportExecutableNameList.push_back(KUnknownDependency);
-			}
-			else
-			{
-				aImportExecutableNameList.push_back(CodeSizeVsExeName->second);
-			}
-		}
-		else
-		{
-			if(patternFound == true)
-			{
-				break;
-			}
-		}
-        --codeSize;
-	} 
-	aImportExecutableNameList.sort();
-	aImportExecutableNameList.unique();
-}
-typedef std::iterator_traits<VectorList::iterator>::difference_type Distance;
-static VectorList::iterator get_lower_bound(VectorList aVec, const unsigned int& aVal){
-	VectorList::iterator first = aVec.begin();
-	VectorList::iterator last = aVec.end();
-	Distance len = std::distance(first, last);
-  Distance half;
-  VectorList::iterator middle;
-
-  while (len > 0) {
-    half = len >> 1;
-    middle = first;
-    std::advance(middle, half);    
-    if (*middle > aVal) {      
-      first = middle;
-      ++first;
-      len = len - half - 1;
-    }
-    else
-     len = half;
-  }
-  return first;
-}
-
- 
-/** 
-Function responsible to read the dependency address from the Exe Map container.
-
-@internalComponent
-@released
-
-@param aImageAddress - Dependency address (function address)
-@returns - e32image start address(code section).
-*/
-unsigned int RomReader::CodeSectionAddress(unsigned int& aImageAddress)
-{
-	/*
-	This invocation leads to a warning, due to the stlport implememtation
-	VectorList::iterator lowerAddress = std::lower_bound(iImageAddress.begin(), 
-										iImageAddress.end(), aImageAddress, std::greater <unsigned int>());
-	*/
-										
-	VectorList::iterator lowerAddress = get_lower_bound(iImageAddress,aImageAddress);
-	return *lowerAddress;
-}
-
-/** 
-Function responsible to fill iExeVsIdData and iSidVsExeName containers.
-
-@internalComponent
-@released
-
-@param iRomImageRootDirEntry - Root directory entry
-@param iExeVsIdData - Container
-@param iSidVsExeName - Container
-*/
-void RomReader::PrepareExeVsIdMap()
-{
-    ExeVsRomFsEntryMap::iterator exeBegin = iExeVsRomFsEntryMap.begin();
-    ExeVsRomFsEntryMap::iterator exeEnd = iExeVsRomFsEntryMap.end();
-    IdData* id = KNull;
-	RomImageFileEntry* entry = KNull;
-	if(iExeVsIdData.size() == 0) //Is not already prepared
-	{
-		while(exeBegin != exeEnd)
-		{
-			id = new IdData;
-			entry = (RomImageFileEntry*)exeBegin->second;
-			id->iUid = entry->ImagePtr.iRomFileEntry->iUid1;
-			id->iDbgFlag = (entry->ImagePtr.iRomFileEntry->iFlags & KImageDebuggable) ? true : false;
-			if(entry->iTRomEntryPtr->iAddressLin > RomBase())
-			{
-				String& exeName = exeBegin->second->iName;
-				//This header contains the SID and VID, so create the instance of IdData.
-				TRomImageHeader	*aRomImgEntry = entry->ImagePtr.iRomFileEntry;
-				
-				id->iSid = aRomImgEntry->iS.iSecureId;
-				id->iVid = aRomImgEntry->iS.iVendorId;
-				id->iFileOffset = aRomImgEntry->iEntryPoint;
-				iExeVsIdData[exeName] = id;
-			}
-			++exeBegin;
-		}
-	}
-	id = KNull;
-}
-
-/** 
-Function responsible to return the Executable versus IdData container. 
-
-@internalComponent
-@released
-
-@return - returns iExeVsIdData
-*/
-const ExeVsIdDataMap& RomReader::GetExeVsIdMap() const
-{
-    return iExeVsIdData;
-}
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+/**
+@file
+@internalComponent
+@released
+*/
+
+#include "romreader.h"
+#include "romfsentry.h"
+#include "romimageheader.h"
+#include "utf16string.h"
+#include  <e32rom.h>
+#include  <e32ldr.h>
+#include  <iostream>
+#include  <algorithm>
+#include  <functional>
+
+void InflateUnCompress(unsigned char* source, int sourcesize, unsigned char* dest, int destsize);
+
+/** 
+Static variable to mark whether TRomLoaderHeader is present in the ROM image or not.
+
+@internalComponent
+@released
+*/
+bool RomReader::iNoRomLoaderHeader = false;
+
+/** 
+Constructor intializes the class pointer members and member variables.
+
+@internalComponent
+@released
+
+@param aFile - image file name
+@param aImageType - image type
+*/
+RomReader::RomReader(const char* aFile, EImageType aImgType) 
+: ImageReader(aFile), iImageHeader(0), iData(0), iImgType(aImgType) {
+	iRomImageRootDirEntry = new RomImageDirEntry("");
+}
+
+/** 
+Destructor deletes the class pointer members.
+
+@internalComponent
+@released
+*/
+RomReader::~RomReader() {
+	if(iData){
+		delete [] iData;
+		iData = 0 ;
+	}
+	iRomImageRootDirEntry->Destroy();
+	iRomImageRootDirEntry = 0;
+	if(iImageHeader){
+		delete iImageHeader;
+		iImageHeader = 0;
+	}
+	iRootDirList = 0;
+	for(RomAddrVsExeName::iterator it = iAddVsExeMap.begin(); it != iAddVsExeMap.end() ; it++){
+		delete (*it).second;
+	}
+	iAddVsExeMap.clear();
+	iExeVsRomFsEntryMap.clear();
+}
+
+/** 
+Function responsible to read the whole image and assign it to an member
+
+@internalComponent
+@released
+*/
+void RomReader::ReadImage() {
+	iInputStream.open(iImgFileName.c_str(), ios_base::binary | ios_base::in);
+	if(!iInputStream.is_open()) {
+		cout << "Error: " << "Can not open file: " << ImageName() << endl;
+		exit(EXIT_FAILURE);
+	}
+	iInputStream.seekg(0, ios_base::end);
+	iImageSize = iInputStream.tellg();
+	iData = new unsigned char[iImageSize];
+	memset(iData, 0, iImageSize);
+	iInputStream.seekg(0, ios_base::beg);
+	iInputStream.read((char*)iData, iImageSize);
+	iInputStream.close();
+}
+
+
+/** 
+Function responsible to return the compression type
+Can handle ROM and Extension ROM images.
+
+@internalComponent
+@released
+
+@return - returns the compression type
+*/
+const unsigned long int RomReader::ImageCompressionType() const {
+	if(iImageHeader->iRomHdr)
+		return iImageHeader->iRomHdr->iCompressionType;
+	else
+		return iImageHeader->iExtRomHdr->iCompressionType;
+}
+
+
+/** 
+Function responsible to return the Rom header pointer address
+Can handle ROM and Extension ROM images.
+
+@internalComponent
+@released
+
+@return - returns the Rom header pointer address
+*/
+const char* RomReader::RomHdrPtr() const {
+	if(iImageHeader->iRomHdr)
+		return (char*)(iImageHeader->iRomHdr);
+	else
+		return (char*)(iImageHeader->iExtRomHdr);
+}
+
+
+/** 
+Function responsible to return the Rom base address in the image
+Can handle ROM and Extension ROM images.
+
+@internalComponent
+@released
+
+@return - returns the Rom base address
+*/
+const unsigned long int RomReader::RomBase() const {
+	if(iImageHeader->iRomHdr)
+		return iImageHeader->iRomHdr->iRomBase ;
+	else
+		return iImageHeader->iExtRomHdr->iRomBase;
+}
+
+
+/** 
+Function responsible to return the Rom root directory list
+Can handle ROM and Extension ROM images.
+
+@internalComponent
+@released
+
+@return - returns the Rom root directory list
+*/
+const unsigned long int RomReader::RootDirList() const {
+	if(iImageHeader->iRomHdr)
+		return iImageHeader->iRomHdr->iRomRootDirectoryList;
+	else
+		return iImageHeader->iExtRomHdr->iRomRootDirectoryList;
+}
+
+
+/** 
+Function responsible to return the Rom header size
+Can handle ROM and Extension ROM images.
+
+@internalComponent
+@released
+
+@return - returns the Rom header size
+*/
+const unsigned int RomReader::HdrSize() const {
+	if(iImageHeader->iRomHdr) 
+		return (sizeof(TRomLoaderHeader) + sizeof(TRomHeader));
+	else
+		return sizeof(TExtensionRomHeader);
+}
+
+/** 
+Function responsible to return the Rom image size
+Can handle ROM and Extension ROM images.
+
+@internalComponent
+@released
+
+@return - returns the Rom Image size
+*/
+const unsigned int RomReader::ImgSize() const {
+	if(ImageCompressionType() == KUidCompressionDeflate) 
+		return iImageHeader->iRomHdr->iUncompressedSize;
+	else
+		return iImageSize;
+}
+
+/** 
+Function responsible to process the ROM image
+1. Read the header.
+2. Identify the compression type.
+3. If the image is compressed then uncompress and update the image content buffer iData.
+4. Build the directory tree by reading all the Rood and subdirectory elements.
+
+@internalComponent
+@released
+*/
+void RomReader::ProcessImage() {
+	if(iImageSize > sizeof(TRomLoaderHeader) || iImageSize > sizeof(TExtensionRomHeader)) {
+		iImageHeader = new RomImageHeader(reinterpret_cast<char*>(iData), iImgType, iNoRomLoaderHeader);
+
+		if(ImageCompressionType() == KUidCompressionDeflate) {
+			unsigned int aDataStart = HdrSize();
+			unsigned char* aData = new unsigned char[iImageHeader->iRomHdr->iUncompressedSize + aDataStart];
+			InflateUnCompress((iData + aDataStart), iImageHeader->iRomHdr->iCompressedSize, (aData + aDataStart), iImageHeader->iRomHdr->iUncompressedSize);
+			memcpy(aData, iData, aDataStart);
+			delete [] iData;
+
+			iData = aData;
+			//update the header fields...
+			if(iImgType == ERomImage) {
+				iImageHeader->iLoaderHdr = (TRomLoaderHeader*)iData;
+				iImageHeader->iRomHdr = (TRomHeader*)(iData + sizeof(TRomLoaderHeader));
+			}
+		}
+		else if(ImageCompressionType() != 0) {
+			cout << "Error: Invalid image: " << ImageName() << endl;
+			exit(EXIT_FAILURE);
+		}
+		else if (iImageHeader->iRomHdr && iImageHeader->iRomHdr->iRomPageIndex)  { // paged ROM
+			const int KPageSize = 0x1000;
+			TRomHeader *pRomHdr = iImageHeader->iRomHdr;
+			unsigned int headerSize = HdrSize();
+
+			TInt numPages = (pRomHdr->iPageableRomStart + pRomHdr->iPageableRomSize+KPageSize-1)/KPageSize;
+			unsigned char* aData = new unsigned char[pRomHdr->iUncompressedSize + headerSize];
+			unsigned char* dest = aData + sizeof(TRomLoaderHeader) + pRomHdr->iPageableRomStart;
+			SRomPageInfo* pi = (SRomPageInfo*)((unsigned char*)pRomHdr + pRomHdr->iRomPageIndex);
+			CBytePair bpe;
+
+			for(int i = 0; i < numPages; i++, pi++) {
+				if (pi->iPagingAttributes != SRomPageInfo::EPageable) // skip uncompressed part at the beginning of ROM image
+					continue;
+
+				switch(pi->iCompressionType) {
+				case SRomPageInfo::ENoCompression:
+					memcpy(dest, (unsigned char*)pRomHdr + pi->iDataStart, pi->iDataSize);
+					dest += pi->iDataSize;
+					break;
+
+				case SRomPageInfo::EBytePair: {
+					unsigned char* srcNext = 0;
+					int unpacked = bpe.Decompress(dest, KPageSize, (unsigned char*)pRomHdr + pi->iDataStart, pi->iDataSize, srcNext);
+					if (unpacked  <  0) {
+						delete [] aData;
+						cout  << "Error:" <<  "Corrupted BytePair compressed ROM image"  <<  endl;
+						exit(EXIT_FAILURE);
+					}
+
+					dest += unpacked;
+					break;
+											  }
+
+				default:
+					delete [] aData;
+					cout  << "Error:" << "Undefined compression type"  <<  endl;
+					exit(EXIT_FAILURE);
+				}
+			}
+
+			memcpy(aData, iData, sizeof(TRomLoaderHeader) + pRomHdr->iPageableRomStart);
+			delete [] iData;
+
+			iData = aData;
+
+			//update the header fields...
+			if(iImgType == ERomImage) {
+				iImageHeader->iLoaderHdr = (TRomLoaderHeader*)iData;
+				iImageHeader->iRomHdr = (TRomHeader*)(iData + sizeof(TRomLoaderHeader));
+			}
+		}
+
+		unsigned long int aOff = RootDirList() - RomBase();
+		iRootDirList = (TRomRootDirectoryList*)(RomHdrPtr() + aOff);
+		int aDirs = 0;
+		TRomDir	*aRomDir;
+		while(aDirs  <  iRootDirList->iNumRootDirs) {
+			aOff = iRootDirList->iRootDir[aDirs].iAddressLin - RomBase();
+			aRomDir = (TRomDir*)(RomHdrPtr() + aOff);
+
+			BuildDir(aRomDir, iRomImageRootDirEntry);
+			aDirs++;
+		}
+	}
+	else {
+		cout << "Error: " << "Invalid image: " << iImgFileName.c_str() << endl;
+		exit(EXIT_FAILURE);
+	}
+}
+
+
+/** 
+Function responsible to Get Rom directory table
+
+@internalComponent
+@released
+
+@param aBase - base poniter
+@param aCount - No of entries in the table
+@param aRomDir - Current Rom directory.
+*/
+void RomReader::GetRomDirTbl(short int** aBase, short int& aCount, TRomDir *aRomDir) {
+	short int *aSubDirCnt = 0;
+	short int *aFileCnt = 0;
+
+	//Sub directories in this directories
+	aSubDirCnt = (short int*)((char*)aRomDir + aRomDir->iSize + sizeof(aRomDir->iSize));
+	//Files within this directory
+	aFileCnt = aSubDirCnt+1;
+	aCount = (*aFileCnt + *aSubDirCnt);
+	*aBase = aFileCnt+1;
+}
+
+
+/** 
+Function responsible to Build directory tree.
+
+@internalComponent
+@released
+
+@param aDir - directory
+@param aPaFSEntry - Parent RomImageFSEntry
+*/
+void RomReader::BuildDir(TRomDir* aDir, RomImageFSEntry* aPaFSEntry) {
+
+	short int			*aBase, aCount;
+
+	GetRomDirTbl(&aBase, aCount, aDir);
+	/**Images built using option -no-sorted-romfs are compatible with Symbian OS v6.1.
+	But imgcheck tool supports only Symbian OS v9.1 to Future versions.
+	*/
+	if(aCount <= 0) {
+		cerr << "Error: Invalid Image " << iImgFileName.c_str() << endl;
+		exit(EXIT_FAILURE);
+	}
+	BuildDir(aBase, aCount, aDir, aPaFSEntry);
+}
+
+
+/** 
+Function responsible to add the read directory or file into tree.
+
+@internalComponent
+@released
+
+@param aOffsetTbl - Table offset
+@param aOffsetTblCount - No of entries in the table
+@param aPaRomDir - Parent TRomDir
+@param aPaFSEntry - Parent RomImageFSEntry
+*/
+void RomReader::BuildDir(short int *aOffsetTbl, short int aOffsetTblCount, 
+						 TRomDir *aPaRomDir, RomImageFSEntry* aPaFSEntry) {
+							 RomImageFSEntry *aNewFSEntry;
+							 TRomDir	*aNewDir;
+							 TRomEntry *aRomEntry;
+							 unsigned long int aOffsetFromBase;
+							 unsigned int aOffset;
+							 string	aName; 
+
+							 while(aOffsetTblCount--) {
+								 aOffsetFromBase = *aOffsetTbl;
+								 aOffsetFromBase  <<= 2;
+								 aRomEntry = (TRomEntry*)((char*)aPaRomDir + sizeof(int) + aOffsetFromBase);
+								 UTF16String unistr(reinterpret_cast<const TUint16*>(aRomEntry->iName),aRomEntry->iNameLength);
+								 if(!unistr.ToUTF8(aName))
+									 aName.assign(reinterpret_cast<const char*>(aRomEntry->iName),aRomEntry->iNameLength);
+
+								 if(aRomEntry->iAtt & 0x10) {//KEntryAttDir
+
+									 aNewFSEntry = new RomImageDirEntry(const_cast<char*>(aName.c_str()));
+									 AddChild(aPaFSEntry, aNewFSEntry, KNull);
+
+									 aOffset = aRomEntry->iAddressLin - RomBase();
+									 aNewDir = (TRomDir*)(RomHdrPtr() + aOffset);
+									 BuildDir(aNewDir, aNewFSEntry);
+								 }
+								 else {
+									 aNewFSEntry = new RomImageFileEntry((char*)aName.data());
+									 AddChild(aPaFSEntry, aNewFSEntry, aRomEntry);
+								 }
+								 aOffsetTbl++;
+							 }
+}
+
+
+/** 
+Function responsible to add current entry as child to aPa.
+
+@internalComponent
+@released
+
+@param aPa - Parent RomImageFSEntry.
+@param aChild - child RomImageFSEntry.
+@param aRomEntry - Current entry.
+*/
+
+void RomReader::AddChild(RomImageFSEntry *aPa, RomImageFSEntry *aChild, TRomEntry* aRomEntry) {
+	if(!aPa->iChildren) {
+		aPa->iChildren = aChild;
+	}
+	else {
+		RomImageFSEntry *aLast = aPa->iChildren;
+		while(aLast->iSibling)
+			aLast = aLast->iSibling;
+
+		aLast->iSibling = aChild;
+	}
+
+	if(!aChild->IsDirectory()) {
+		TRomImageHeader* aImgHdr;
+		unsigned long int aOff;
+		RomImageFileEntry* entry = dynamic_cast<RomImageFileEntry*>(aChild);
+		entry->iTRomEntryPtr = aRomEntry;
+		if(aRomEntry->iAddressLin > RomBase()) {
+			aOff = aRomEntry->iAddressLin - RomBase();
+			aImgHdr = (TRomImageHeader*)(RomHdrPtr() + aOff);
+			entry->ImagePtr.iRomFileEntry = aImgHdr;
+			unsigned char aUid1[4];
+			memcpy(aUid1, &entry->ImagePtr.iRomFileEntry->iUid1, 4);
+
+			//Skip the E32 executables included as a DATA files in ROM image.
+			if(ReaderUtil::IsExecutable(aUid1) && aImgHdr->iCodeAddress > RomBase() && 
+				aImgHdr->iCodeAddress < (RomBase() + ImgSize())) {
+					iExeAvailable = true;
+					entry->iExecutable = true; 
+					pair<ExeVsRomFsEntryMap::iterator,bool> ret =
+						iExeVsRomFsEntryMap.insert(
+							pair<const char*,RomImageFSEntry*>(entry->Name(), aChild));
+					if(ret.second == false)
+						ret.first->second = aChild ;
+						
+			}
+			else {
+				entry->iExecutable = false;
+				entry->ImagePtr.iDataFileAddr = aRomEntry->iAddressLin;
+			}
+		}
+		else {
+			entry->ImagePtr.iRomFileEntry = KNull;
+		}
+	}
+	if(aPa != iRomImageRootDirEntry) {
+		aChild->iPath = aPa->iPath;
+		aChild->iPath += KDirSeperaor;
+		aChild->iPath += aPa->iName.data();
+	}
+
+}
+
+
+/** 
+Function responsible to prepare Executable List by traversing through iExeVsRomFsEntryMap
+
+@internalComponent
+@released
+*/
+void RomReader::PrepareExecutableList() { 
+	for (ExeVsRomFsEntryMap::iterator it = iExeVsRomFsEntryMap.begin() ;
+		it != iExeVsRomFsEntryMap.end(); it++) { 
+		iExecutableList.push_back(it->first); 
+	}
+}
+
+/** 
+Function responsible to create address vs executable map.
+Later this address is used as a key to get executable name
+
+@internalComponent
+@released
+*/
+void RomReader::PrepareAddVsExeMap() {
+	for (ExeVsRomFsEntryMap::iterator it = iExeVsRomFsEntryMap.begin() ;
+		it != iExeVsRomFsEntryMap.end(); it++) { 
+		UintVsString* sizeVsExeName = new UintVsString();
+		unsigned int address;
+		RomImageFileEntry* fileEntry = (RomImageFileEntry*)it->second;
+		TRomImageHeader	*aRomImgEntry = fileEntry->ImagePtr.iRomFileEntry;
+		const char* name = it->second->Name();
+		if(aRomImgEntry != KNull) {
+			address = aRomImgEntry->iCodeAddress;
+			put_item_to_map(*sizeVsExeName,aRomImgEntry->iCodeSize,name);
+		}
+		else {
+			address = fileEntry->iTRomEntryPtr->iAddressLin;
+			put_item_to_map(*sizeVsExeName,fileEntry->iTRomEntryPtr->iSize,name);
+		}
+		put_item_to_map(iAddVsExeMap,address, sizeVsExeName);
+		iImageAddress.push_back(address); 
+	}
+	sort(iImageAddress.begin(), iImageAddress.end(), greater < unsigned int>());
+}
+
+/** 
+Function responsible to say whether it is an ROM image or not.
+
+@internalComponent
+@released
+
+@param aWord - which has the identifier string
+@return - returns true or false.
+*/
+bool RomReader::IsRomImage(const string& aWord) {
+	//Epoc Identifier should start at 0th location, Rom Identifier should start at 8th location
+	if((aWord.find(KEpocIdentifier) == 0) && (aWord.find(KRomImageIdentifier) == 8)) {
+		return true;
+	}
+	else {
+		iNoRomLoaderHeader = true;
+		//TRomLoaderHeader is not present
+		TRomHeader *romHdr = (TRomHeader*)aWord.c_str();
+		/**If the ROM image is built without TRomLoaderHeaderi, ROM specific identifier will not be available
+		hence these two header variables used.*/
+		if((romHdr->iRomBase >= KRomBase) && (romHdr->iRomRootDirectoryList > KRomBase) 
+			&& (romHdr->iRomBase < KRomBaseMaxLimit) && (romHdr->iRomRootDirectoryList < KRomBaseMaxLimit)) {
+				return true;
+		}
+	}
+	return false;
+}
+
+/** 
+Function responsible to say whether it is an ROM extension image or not.
+
+@internalComponent
+@released
+
+@param aWord - which has the identifier string
+@return - retruns true or false.
+*/
+bool RomReader::IsRomExtImage(const string& aWord) {
+	if(aWord.at(0) == KNull && aWord.at(1) == KNull &&
+		aWord.at(2) == KNull && aWord.at(3) == KNull &&
+		aWord.at(4) == KNull && aWord.at(5) == KNull) {
+			//Since no specific identifier is present in the ROM Extension image these two header variables used.
+			TExtensionRomHeader* romHdr = (TExtensionRomHeader*)aWord.c_str();
+			if((romHdr->iRomBase > KRomBase) && (romHdr->iRomRootDirectoryList > KRomBase)
+				&& (romHdr->iRomBase < KRomBaseMaxLimit) && (romHdr->iRomRootDirectoryList < KRomBaseMaxLimit)) {
+					return true;
+			}
+	}
+	return false;
+}
+
+/** 
+Function responsible to gather dependencies for all the executables.
+
+@internalComponent
+@released
+
+@return iImageVsDepList - returns all executable's dependencies
+*/
+ 
+ExeNamesVsDepListMap& RomReader::GatherDependencies() {  
+	PrepareAddVsExeMap();   
+	for(ExeVsRomFsEntryMap::iterator it =  iExeVsRomFsEntryMap.begin();
+		it != iExeVsRomFsEntryMap.end(); it++) {
+		RomImageFileEntry* entry = dynamic_cast<RomImageFileEntry*>(it->second);
+		if(!entry){ 
+			continue ;
+		}
+		if(entry->iTRomEntryPtr->iAddressLin > RomBase()) {
+			StringList executables; 
+			CollectImportExecutableNames(entry, executables); 
+			put_item_to_map(iImageVsDepList,entry->Name(), executables); 
+		} 
+	}
+	return iImageVsDepList;
+}
+
+/** 
+Function responsible to read the dependency names.
+
+@internalComponent
+@released
+
+@param aRomReader - ROM reader pointer
+@param aEntry - Current RomImageFSEntry
+@param aImportExecutableNameList - Executable list.(output)
+*/
+void RomReader::CollectImportExecutableNames(const RomImageFSEntry* aEntry, StringList&  aImportExecutables) { 
+	RomImageFileEntry* fileEntry = (RomImageFileEntry*)aEntry;
+	TRomImageHeader	*romImgEntry = fileEntry->ImagePtr.iRomFileEntry;
+	TUint sectionOffset = romImgEntry->iCodeAddress - RomBase();
+	TUint* codeSection = reinterpret_cast<TUint*>(const_cast<char*>(RomHdrPtr()) + sectionOffset);
+	TUint codeSize = romImgEntry->iCodeSize;
+	// Checking for LDR Instruction in PLT section(Inside Code section)
+	// to get the import address.	
+	bool patternFound = false;	
+	while(codeSize > 0) {
+		if(*codeSection++ == KLdrOpcode) {
+			patternFound = true;
+			TUint dependencyAddress = *codeSection++;
+			
+			unsigned int addr = CodeSectionAddress(dependencyAddress);			 
+			RomAddrVsExeName::iterator it = iAddVsExeMap.find(addr);
+			
+			if(it == iAddVsExeMap.end()) break ; 
+			
+			UintVsString::iterator i = it->second->begin();
+			 
+			if(!(dependencyAddress < (it->first + i->first))) {
+				aImportExecutables.push_back(KUnknownDependency);
+			}
+			else {
+				aImportExecutables.push_back(i->second);
+			}			 
+		}
+		else if(patternFound) {
+			break;
+			
+		}
+		--codeSize;
+	} 
+	aImportExecutables.sort();
+	aImportExecutables.unique();
+}
+typedef iterator_traits<VectorList::iterator>::difference_type Distance;
+static VectorList::iterator get_lower_bound(VectorList aVec, const unsigned int& aVal){
+	VectorList::iterator first = aVec.begin();
+	VectorList::iterator last = aVec.end();
+	Distance len = distance(first, last);
+	Distance half;
+	VectorList::iterator middle;
+
+	while (len > 0) {
+		half = len >> 1;
+		middle = first;
+		advance(middle, half);    
+		if (*middle > aVal) {      
+			first = middle;
+			++first;
+			len = len - half - 1;
+		}
+		else
+			len = half;
+	}
+	return first;
+}
+
+
+/** 
+Function responsible to read the dependency address from the Exe Map container.
+
+@internalComponent
+@released
+
+@param aImageAddress - Dependency address (function address)
+@returns - e32image start address(code section).
+*/
+unsigned int RomReader::CodeSectionAddress(unsigned int& aImageAddress) {
+	/*
+	This invocation leads to a warning, due to the stlport implememtation
+	VectorList::iterator lowerAddress = lower_bound(iImageAddress.begin(), 
+	iImageAddress.end(), aImageAddress, greater <unsigned int>());
+	*/
+
+	VectorList::iterator lowerAddress = get_lower_bound(iImageAddress,aImageAddress);
+	return *lowerAddress;
+}
+
+/** 
+Function responsible to fill iExeVsIdData and iSidVsExeName containers.
+
+@internalComponent
+@released
+
+@param iRomImageRootDirEntry - Root directory entry
+@param iExeVsIdData - Container
+@param iSidVsExeName - Container
+*/
+void RomReader::PrepareExeVsIdMap() {
+	  
+	//IdData* id = KNull;
+	//RomImageFileEntry* entry = KNull;
+	if(iExeVsIdData.size() == 0) { //Is not already prepared 
+		for(ExeVsRomFsEntryMap::iterator it =  iExeVsRomFsEntryMap.begin();
+		it != iExeVsRomFsEntryMap.end() ; it++) {
+			RomImageFileEntry* entry = dynamic_cast<RomImageFileEntry*>(it->second);
+			if(!entry) continue ;			
+			IdData* id = new IdData;
+			id->iUid = entry->ImagePtr.iRomFileEntry->iUid1;
+			id->iDbgFlag = (entry->ImagePtr.iRomFileEntry->iFlags & KImageDebuggable) ? true : false;
+			if(entry->iTRomEntryPtr->iAddressLin > RomBase()) {
+				const char* exeName = it->second->Name();
+				//This header contains the SID and VID, so create the instance of IdData.
+				TRomImageHeader	*aRomImgEntry = entry->ImagePtr.iRomFileEntry;
+
+				id->iSid = aRomImgEntry->iS.iSecureId;
+				id->iVid = aRomImgEntry->iS.iVendorId;
+				id->iFileOffset = aRomImgEntry->iEntryPoint; 
+				put_item_to_map_2(iExeVsIdData,exeName,id);  
+			} 
+		}
+	} 
+}
+
+/** 
+Function responsible to return the Executable versus IdData container. 
+
+@internalComponent
+@released
+
+@return - returns iExeVsIdData
+*/
+const ExeVsIdDataMap& RomReader::GetExeVsIdMap() const {
+	return iExeVsIdData;
+}
--- a/imgtools/imgcheck/libimgutils/src/utils.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/libimgutils/src/utils.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,211 +1,195 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "typedefs.h"
-#include <e32def.h>
-#include "h_utl.h"
-#include "r_obey.h"
-#include "r_romnode.h"
-#include <algorithm>
-
-ECompression gCompress = ECompressionUnknown;
-unsigned int  gCompressionMethod = 0;
-TBool gPagingOverride = 0;
-TInt gCodePagingOverride = -1;
-TInt gDataPagingOverride = -1;
-TInt gLogLevel = 0;
-
-/** 
-Function receives an UID type of an executable and identifies whether it is a
-1. EXE or not,
-2. DLL or not
-3. Executable or not.
-
-@internalComponent
-@released
-
-@param Uids1 - Uid1 of a E32 executable
-@param aType - Type to be compared against aUids1. 
-*/
-bool ReaderUtil::IsExecutable(unsigned char* aUids1, int aType)
-{
-	//In the little-endian world
-	if( aUids1[3] == 0x10 && aUids1[2] == 0x0 && aUids1[1] == 0x0 )
-		{
-			switch(aType)
-			{
-			case EExe:
-				if(aUids1[0] == 0x7a)
-				{
-					return true;
-				}
-				break;
-			case EDll:
-				if(aUids1[0] == 0x79)
-				{
-					return true;
-				}
-				break;
-			case EAll:
-				if((aUids1[0] == 0x79) || (aUids1[0] == 0x7a))
-				{
-					return true;
-				}
-				break;
-			}
-		}
-	return false;
-}
-
-/** 
-Function receives an UID type of an executable and identifies whether it is a EXE or not.
-
-@internalComponent
-@released
-
-@param aType - Type to be compared against aUids1.
-*/
-bool ReaderUtil::IsExe(unsigned long* aUids1)
-{
-	return IsExecutable((unsigned char*)aUids1, EExe);
-}
-
-/** 
-Function receives an UID type of an executable and identifies whether it is a DLL or not,
-
-@internalComponent
-@released
-
-@param aType - Type to be compared against aUids1.
-*/
-bool ReaderUtil::IsDll(unsigned long* aUids1)
-{
-	return IsExecutable((unsigned char*)aUids1, EDll);
-}
-
-/** 
-Function responsible to convert lower case strings to upper case
-
-@internalComponent
-@released
-
-@param aString - String which needs to be inserted
-*/
-const String&  ReaderUtil::ToLower(String& aString)
-{
-	unsigned int stringLength = aString.length();
-	unsigned char stringChar;
-	for(unsigned int stringIndex = 0; stringIndex < stringLength; stringIndex++)
-	{
-		stringChar = aString.at(stringIndex);
-		if( stringChar >= KUpperCaseAsciiValOfCharA && stringChar <= KUpperCaseAsciiValOfCharZ )
-		{
-			stringChar += KUpperAndLowerAsciiDiff; //Upper case alphabets case changed to lower case
-		}
-		aString[stringIndex] = stringChar;
-	}
-	return aString;
-}
-
-/** 
-Function responsible to convert integer to ASCII characters with respect to its base value.
-Function takes the integer value with its base.
-Calculates the first reminder by dividing the value with its base, put this value into result string .
-Do the same until the value becomes zero.
-
-Regular itoa() function from stdlib.h, definition is not available in linux.
-
-@internalComponent
-@released
-
-@param aString - String which needs to be inserted
-*/
-const String ReaderUtil::IntToAscii(const int aValue, const int aBase)
-{
-	String result;
-	// check that the base if valid, the valid range is between 2 and 16
-	if (aBase < EBase2 || aBase > EBase16) 
-	{ 
-		return result; 
-	}
-	int quotient = aValue;
-	do 
-	{
-	#ifdef __TOOLS__
-		result += "0123456789abcdef"[abs(quotient % aBase)];
-	#else
-		result += "0123456789abcdef"[std::abs(quotient % aBase)];
-	#endif
-		quotient /= aBase;
-	} while (quotient);
-	
-	// Only apply negative sign for base 10
-	if (aValue < 0 && aBase == EBase10) 
-	{
-		result += '-';
-	}
-	std::reverse(result.begin(), result.end());
-	return result;
-}
-
-/** 
-Function responsible to convert string to integer.
-Regular atoi() function from stdlib.h, definition is not available in linux.
-
-@internalComponent
-@released
-
-@param aString - String which needs to be converted.
-*/
-Long64 ReaderUtil::DecStrToInt(String& aString)
-{
-	Long64 val = 0;
-	std::string::iterator strBegIter = aString.begin();
-	std::string::iterator strEndIter = aString.end();
-
-	while(strBegIter != strEndIter)
-	{
-		val *= EBase10;
-		val += *strBegIter - KAsciiValueOfZero;
-		++strBegIter;
-	}
-	return val;
-}
-
-/**
-Function to convert String to any numeric type.
-
-@internalComponent
-@released
-
-@param aStringVal - the string which has to be converted.
-@return - returns the coverted value.
-*/
-unsigned int ReaderUtil::HexStrToInt(String& aStringVal)
-{
-	IStringStream inputStrStream(aStringVal);
-	unsigned int intVal = 0;
-	inputStrStream >> std::hex >> intVal;
-	return intVal;
-}
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+/**
+@file
+@internalComponent
+@released
+*/
+
+#include "typedefs.h"
+#include <e32def.h>
+#include "h_utl.h"
+#include "r_obey.h"
+#include "r_romnode.h"
+#include <algorithm>
+
+ECompression gCompress = ECompressionUnknown;
+unsigned int  gCompressionMethod = 0;
+TBool gPagingOverride = 0;
+TInt gCodePagingOverride = -1;
+TInt gDataPagingOverride = -1;
+TInt gLogLevel = 0;
+bool gCache = false;
+
+/** 
+Function receives an UID type of an executable and identifies whether it is a
+1. EXE or not,
+2. DLL or not
+3. Executable or not.
+
+@internalComponent
+@released
+
+@param Uids1 - Uid1 of a E32 executable
+@param aType - Type to be compared against aUids1. 
+*/
+bool ReaderUtil::IsExecutable(unsigned char* aUids1, int aType) {
+	//In the little-endian world
+	if( aUids1[3] == 0x10 && aUids1[2] == 0x0 && aUids1[1] == 0x0 ) {
+		switch(aType) {
+			case EExe:
+				if(aUids1[0] == 0x7a) {
+					return true;
+				}
+				break;
+			case EDll:
+				if(aUids1[0] == 0x79) {
+					return true;
+				}
+				break;
+			case EAll:
+				if((aUids1[0] == 0x79) || (aUids1[0] == 0x7a)) {
+					return true;
+				}
+				break;
+		}
+	}
+	return false;
+}
+
+/** 
+Function receives an UID type of an executable and identifies whether it is a EXE or not.
+
+@internalComponent
+@released
+
+@param aType - Type to be compared against aUids1.
+*/
+bool ReaderUtil::IsExe(unsigned long* aUids1) {
+	return IsExecutable((unsigned char*)aUids1, EExe);
+}
+
+/** 
+Function receives an UID type of an executable and identifies whether it is a DLL or not,
+
+@internalComponent
+@released
+
+@param aType - Type to be compared against aUids1.
+*/
+bool ReaderUtil::IsDll(unsigned long* aUids1) {
+	return IsExecutable((unsigned char*)aUids1, EDll);
+}
+
+/** 
+Function responsible to convert lower case StringList to upper case
+
+@internalComponent
+@released
+
+@param aString - string which needs to be inserted
+*/
+const string&  ReaderUtil::ToLower(string& aString) {
+	unsigned int stringLength = aString.length();
+	unsigned char stringChar;
+	for(unsigned int stringIndex = 0; stringIndex < stringLength; stringIndex++) {
+		stringChar = aString.at(stringIndex);
+		if( stringChar >= KUpperCaseAsciiValOfCharA && stringChar <= KUpperCaseAsciiValOfCharZ ) {
+			stringChar += KUpperAndLowerAsciiDiff; //Upper case alphabets case changed to lower case
+		}
+		aString[stringIndex] = stringChar;
+	}
+	return aString;
+}
+
+/** 
+Function responsible to convert integer to ASCII characters with respect to its base value.
+Function takes the integer value with its base.
+Calculates the first reminder by dividing the value with its base, put this value into result string .
+Do the same until the value becomes zero.
+
+Regular itoa() function from stdlib.h, definition is not available in linux.
+
+@internalComponent
+@released
+
+@param aString - string which needs to be inserted
+*/
+const string ReaderUtil::IntToAscii(const int aValue, const int aBase) {
+	string result;
+	// check that the base if valid, the valid range is between 2 and 16
+	if (aBase < EBase2 || aBase > EBase16) 
+	{ 
+		return result; 
+	}
+	int quotient = aValue;
+	do  {
+#ifdef __TOOLS__
+		result += "0123456789abcdef"[abs(quotient % aBase)];
+#else
+		result += "0123456789abcdef"[abs(quotient % aBase)];
+#endif
+		quotient /= aBase;
+	} while (quotient);
+
+	// Only apply negative sign for base 10
+	if (aValue < 0 && aBase == EBase10)  {
+		result += '-';
+	}
+	reverse(result.begin(), result.end());
+	return result;
+}
+
+/** 
+Function responsible to convert string to integer.
+Regular atoi() function from stdlib.h, definition is not available in linux.
+
+@internalComponent
+@released
+
+@param aString - string which needs to be converted.
+*/
+Long64 ReaderUtil::DecStrToInt(string& aString) {
+	Long64 val = 0;
+	string::iterator strBegIter = aString.begin();
+	string::iterator strEndIter = aString.end();
+
+	while(strBegIter != strEndIter) {
+		val *= EBase10;
+		val += *strBegIter - KAsciiValueOfZero;
+		++strBegIter;
+	}
+	return val;
+}
+
+/**
+Function to convert string to any numeric type.
+
+@internalComponent
+@released
+
+@param aStringVal - the string which has to be converted.
+@return - returns the coverted value.
+*/
+unsigned int ReaderUtil::HexStrToInt(string& aStringVal) {
+	istringstream inputStrStream(aStringVal);
+	unsigned int intVal = 0;
+	inputStrStream >> hex >> intVal;
+	return intVal;
+}
--- a/imgtools/imgcheck/src/checker.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/src/checker.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,65 +1,61 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Checker interface class.
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "checker.h"
-
-/** 
-Constructor intializes iCmdLine and iImageReaderList members.
-
-@internalComponent
-@released
-
-@param aCmdPtr - pointer to a processed CmdLineHandler object
-@param aImageReaderList - List of ImageReader insatance pointers
-*/
-Checker::Checker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList)
-:iCmdLine(aCmdPtr), iImageReaderList(aImageReaderList), iAllExecutables(false), iNoCheck(false)
-{
-    /**
-	The funciton iCmdLine->ReportFlag(), needs to be called for each and 
-	every executable present in the image. To increase the performance it is 
-	better to preserve this value.
-	*/
-	if(iCmdLine->ReportFlag() & KAll)
-	{
-		iAllExecutables = true;
-	}
-
-	if(iCmdLine->ReportFlag() & KNoCheck)
-	{
-		iNoCheck = true;
-	}
-}
-
-/** 
-Destructor
-
-@internalComponent
-@released
-*/
-Checker::~Checker()
-{
-	iCmdLine = 0;
-}
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Checker interface class.
+*
+*/
+
+
+/**
+ @file
+ @internalComponent
+ @released
+*/
+
+#include "checker.h"
+
+/** 
+Constructor intializes iCmdLine and iImageReaderList members.
+
+@internalComponent
+@released
+
+@param aCmdPtr - pointer to a processed CmdLineHandler object
+@param aImageReaderList - List of ImageReader insatance pointers
+*/
+Checker::Checker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList)
+:iCmdLine(aCmdPtr), iImageReaderList(aImageReaderList), iAllExecutables(false), iNoCheck(false) {
+    /**
+	The funciton iCmdLine->ReportFlag(), needs to be called for each and 
+	every executable present in the image. To increase the performance it is 
+	better to preserve this value.
+	*/
+	if(iCmdLine->ReportFlag() & KAll) {
+		iAllExecutables = true;
+	}
+
+	if(iCmdLine->ReportFlag() & KNoCheck) {
+		iNoCheck = true;
+	}
+}
+
+/** 
+Destructor
+
+@internalComponent
+@released
+*/
+Checker::~Checker() {
+	iCmdLine = 0;
+}
--- a/imgtools/imgcheck/src/cmdlinehandler.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/src/cmdlinehandler.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,786 +1,688 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Commandline handler for imgcheck Tool, responsible to parse the
-* commandline options and preserve the data for later use
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "cmdlinehandler.h"
-
-/**
-Constructor initializes the iOptionMap with short and long option names as key and
-the value pair says whether the respective option can have value or not.
-
-@internalComponent
-@released
-*/
-CmdLineHandler::CmdLineHandler()
-:iDebuggableFlagVal(false),iXmlFileName(GXmlFileName), iNoImage(true), iCommmandFlag(0), iValidations(0), iSuppressions(0) 
-{
-	iOptionMap[KLongHelpOption] = ENone;
-	iOptionMap[KLongAllOption] = ENone;
-	iOptionMap[KLongXmlOption] = ENone;
-	iOptionMap[KLongOutputOption] = ESingle; //option can have only 1 value
-	iOptionMap[KLongQuietOption] = ENone;
-	iOptionMap[KLongVerboseOption] = ENone;
-	iOptionMap[KLongSuppressOption]= EMultiple; //This value should be updated, while introducing new validations
-	iOptionMap[KLongVidValOption]= EMultiple;
-	iOptionMap[KShortHelpOption] = ENone;
-	iOptionMap[KShortAllOption] = ENone;
-	iOptionMap[KShortXmlOption] = ENone;
-	iOptionMap[KShortOutputOption] = ESingle; //option can have only 1 value
-	iOptionMap[KShortQuietOption] = ENone;
-	iOptionMap[KShortVerboseOption] = ENone;
-	iOptionMap[KShortSuppressOption] = EMultiple;
-	iOptionMap[KShortNoCheck] = ENone;
-	iOptionMap[KLongSidAllOption] = ENone;
-	iOptionMap[KLongEnableDepCheck] = ENone;
-	iOptionMap[KLongEnableSidCheck] = ENone;
-	iOptionMap[KLongEnableVidCheck] = ENone;
-	iOptionMap[KLongEnableDbgFlagCheck] = EOptional;
-	iOptionMap[KLongE32InputOption] = ENone;
-	iOptionMap[KLongNoCheck] = ENone;
-	iSuppressVal[KSuppressDependency] = EDep;
-	iSuppressVal[KSuppressSid] = ESid;
-	iSuppressVal[KSuppressVid] = EVid;
-
-	Version();
-	Usage();
-}
-
-/**
-Destructor.
-
-@internalComponent
-@released
-*/
-CmdLineHandler::~CmdLineHandler()
-{
-	iOptionMap.clear();
-	iImageNameList.clear();
-	iSuppressVal.clear();
-	iVidValList.clear();
-}
-
-/**
-Function to parse the command line options.
-Responsible to
-1. Parse the input values.
-2. Print the usage note. 
-3. Identify the valdations to be carried out.
-4. Type of report needs to be generated.
-
-@internalComponent
-@released
-
-@param aArgc - argument count
-@param aArgv[] - argument values
-*/
-ReturnType CmdLineHandler::ProcessCommandLine(unsigned int aArgc, char* aArgv[])
-{
-	if(aArgc < 2)
-	{
-		std::cout << PrintVersion().c_str() << std::endl;
-		std::cout << PrintUsage().c_str() << std::endl;
-		return EQuit;
-	}
-	ArgumentList argumentList(&aArgv[0], aArgv + aArgc);
-	int argCount = argumentList.size();
-
-	 iInputCommand = KToolName;
-
-	for( int i = 1; i < argCount; i++ ) //Skip tool name
-	{
-		String name = argumentList.at(i);
-		iInputCommand += " ";
-		iInputCommand += name;
-		int longOptionFlag = 0;
-		if(IsOption(name, longOptionFlag))
-		{
-			String optionName;
-			bool optionValue = false;
-			StringList optionValueList;
-			ParseOption(name, optionName, optionValueList, optionValue);
-			char shortOption = KNull;
-			if(Validate(ReaderUtil::ToLower(optionName), optionValue, optionValueList.size()))
-			{
-				if(longOptionFlag)
-				{
-					shortOption = optionName.at(2);
-				}
-				else
-				{
-					shortOption = optionName.at(1);
-				}
-			}
-
-			switch(shortOption)
-			{
-				case 'q':
-					iCommmandFlag |= QuietMode;
-					break;
-				case 'a':
-					iCommmandFlag |= KAll;
-					break;
-				case 'x':
-					iCommmandFlag |= KXmlReport;
-					break;
-				case 'o':
-					iXmlFileName.assign(optionValueList.front());
-					NormaliseName();
-					break;
-				case 's':
-					if((optionName == KShortSuppressOption) || (optionName == KLongSuppressOption))
-					{
-						String value;
-						while(optionValueList.size() > 0)
-						{
-							value = optionValueList.front();
-							if(iSuppressVal[value])
-							{
-								if(iValidations > 0) //Is any check enabled?
-								{
-									if(iValidations & iSuppressVal[value])
-									{
-										iValidations ^= iSuppressVal[value]; //Consider only 3 LSB's
-									}
-								}
-								else //Is this valid value?
-								{
-									iSuppressions |= iSuppressVal[value];
-								}
-							}
-							else
-							{
-								throw ExceptionReporter(UNKNOWNSUPPRESSVAL,(char*)(optionValueList.front().c_str()));
-							}
-							optionValueList.pop_front();
-						}
-					}
-					else if(optionName == KLongEnableSidCheck)
-					{
-						iValidations |= KMarkEnable;
-						iValidations |= ESid;
-					}
-					else if(optionName == KLongSidAllOption)
-					{
-						iCommmandFlag |= KSidAll;
-					}
-					break;
-				case 'd':
-					if(optionName == KLongEnableDbgFlagCheck)
-					{
-						iValidations |= KMarkEnable;
-						iValidations |= EDbg;
-						if(optionValueList.size() > 0)
-						{
-							if(optionValueList.front() == String("true"))
-							{
-								iDebuggableFlagVal = true;
-							}
-							else if (optionValueList.front() == String("false"))
-							{
-								iDebuggableFlagVal = false; 
-							}
-							else
-							{
-								throw ExceptionReporter(UNKNOWNDBGVALUE);
-							}
-						}
-					}
-					else if (optionName == KLongEnableDepCheck)
-					{
-						iValidations |= KMarkEnable;
-						iValidations |= EDep;
-					}
-					break;
-
-				case 'e':
-					if (optionName == KLongE32InputOption)
-					{
-						iCommmandFlag |= KE32Input;
-					}
-					break;
-
-				case 'v':
-					if(optionName == KLongVidValOption)
-					{
-						StringListToUnIntList(optionValueList, iVidValList);
-					}
-					else if(optionName == KLongEnableVidCheck)
-					{
-						iValidations |= KMarkEnable;
-						iValidations |= EVid;
-					}
-					else
-					{
-						iCommmandFlag |= KVerbose;
-						/**Initialize ExceptionImplementation class with verbose mode flag
-						to print all status information to standard output*/
-						ExceptionImplementation::Instance(iCommmandFlag);
-					}
-					break;
-				case 'n':
-						iCommmandFlag |= KNoCheck;
-					break;
-				case 'h':
-					std::cout << PrintVersion().c_str() << std::endl;
-					std::cout << PrintUsage().c_str() << std::endl;
-					return EQuit; //Don't proceed further
-			}
-		}
-		else
-		{
-			if(!AlreadyReceived(name))
-			{
-				iImageNameList.push_back(name);
-			}
-			else
-			{
-				ExceptionReporter(IMAGENAMEALREADYRECEIVED, (char*)name.c_str()).Report();
-			}
-
-			iNoImage = false;
-		}
-	} //While loop ends here
-	if((iCommmandFlag || iValidations || iSuppressions) && iNoImage)
-	{
-		PrintVersion();
-		PrintUsage();
-	}
-	//Always log the version information into log file
-	ExceptionImplementation::Instance(iCommmandFlag)->Log(iVersion);
-	ValidateArguments();
-	ValidateE32NoCheckArguments();
-	if(iCommmandFlag & KE32Input)
-	{
-		ValidateImageNameList();
-	}
-	return ESuccess;
-}
-
-/**
-Function identify whether the passed string is an option or not.
-
-@internalComponent
-@released
-
-@param aName - a string received as part of command line
-@param aLongOptionFlag - this flag is set if the option is long else
-it is assumed as short option.
-
-@return - returns true or false
-*/
-bool CmdLineHandler::IsOption(const String& aName, int& aLongOptionFlag)
-{
-	unsigned int prefixCount = 0;
-	while(aName.at(prefixCount) == KShortOptionPrefix)
-	{
-		if(aName.length() == ++prefixCount)
-		{
-			throw ExceptionReporter(UNKNOWNOPTION, (char*)aName.c_str());
-		}
-	}
-
-	switch(prefixCount)
-	{
-		case 0: //argument can be an image
-			return false;
-		case 1: // '-'
-			return true;
-		case 2: // '--'
-			aLongOptionFlag = 1;
-			return true;
-		default:
-			throw ExceptionReporter(UNKNOWNPREFIX, (char*)aName.c_str());
-	}
-}
-
-/**
-Function to do syntax validation on the received option.
-1. Identifies whether the received option is valid or not.
-2. Identifies whether the option can have vaue or not.
-3. Throws an error if no value received for an option which should have value.
-4. Throws an error if more number of values received.
-5. Throws an error if an unwanted value received.
-6. Throws an error if the option is not a valid one.
-
-@internalComponent
-@released
-
-@param aOption - a string received as part of command line.
-@param aOptionValue - Whether option value received or not.
-@param aNoOfVal - Number of values received for this option.
-
-@return - returns true if it is a valid option
-*/
-bool CmdLineHandler::Validate(const String& aOption, bool aOptionValue, unsigned int aNoOfVal)
-{
-	if(iOptionMap.find(aOption) != iOptionMap.end())
-	{
-		if(iOptionMap[aOption]) //Option can have value?
-		{
-			if((aNoOfVal == ENone) && (iOptionMap[aOption] != EOptional)) //No values received?
-			{
-				throw ExceptionReporter(VALUEEXPECTED, (char*)aOption.c_str());
-			}
-			
-			if((iOptionMap[aOption] == ESingle) && (ESingle < aNoOfVal)) //Received values are more than expected
-			{
-				throw ExceptionReporter(UNEXPECTEDNUMBEROFVALUE,(char*)aOption.c_str());
-  			}
-		}
-		else
-		{
-			if(aOptionValue) //Is option value received? Any character after the option considered as value.
-			{
-				throw ExceptionReporter(VALUENOTEXPECTED, (char*)aOption.c_str());
-			}
-		}
-		return true;
-	}
-	throw ExceptionReporter(UNKNOWNOPTION, (char*)aOption.c_str());
-}
-
-/**
-Function to split the option name and option values.
-1. Ignore's the '=' symbol which is following the option. But this is an error, if that
-option does not expecting any value.
-2. Parses the value received with options.
-
-@internalComponent
-@released
-
-@param aFullName - Option with its value
-@param aOptionName - Option name put into this parameter
-@param aOptionValues - Option values put into this parameter
-@param aOptionValue - Set this flag if any value received with the option.
-*/
-void CmdLineHandler::ParseOption(const String& aFullName, String& aOptionName, StringList& aOptionValues, bool& aOptionValue)
-{
-	unsigned int optionEndLocation = aFullName.find("=");
-	if(optionEndLocation != String::npos)
-	{
-		aOptionValue = true;
-		aOptionName = aFullName.substr(0, optionEndLocation++);
-		if(aFullName.length() == optionEndLocation)
-		{
-			throw ExceptionReporter(VALUEEXPECTED, (char*)aOptionName.c_str());
-		}
-		String sub = aFullName.substr(optionEndLocation);
-		char* optionValues = (char*)sub.c_str();
-		//Get all the values; use (,) as delimiter
-		char* value = strtok(optionValues,",");
-		while(value != KNull)
-		{
-			String str(value);
-			aOptionValues.push_back(ReaderUtil::ToLower(str));
-			value = strtok(KNull,",");
-		}
-		return;
-	}
-	aOptionName = aFullName;
-}
-
-/**
-Function to initialize the usage.
-
-@internalComponent
-@released
-*/
-void CmdLineHandler::Usage(void)
-{
-    iUsage.assign("imgcheck [options] <img1> [<img2 .. imgN>] \n"
-		"imgcheck --e32input [options] (<file> | <directory>) \n"
-        "\n"
-        "options: \n"
-		"  -a, --all,             Report all executable's status\n"
-	    "  -q, --quiet,           Command line display off\n"
-	    "  -x, --xml,             Generate XML report\n"
-        "  -o=xxx, --output=xxx   Override default XML file name\n"
-		"  -v, --verbose,         Verbose mode output\n"
-		"  -h, --help,            Display this message\n"
-		"  -s=val1[,val2][...], --suppress=val1[,val2][...] \n"
-		"                         Suppress one or more check,\n"
-		"                         Possible values are dep, sid and vid\n"
-        "  --vidlist=val1[,val2][...] \n"
-		"                         One or more VID value(s) \n"
-        "  --dep                  Enable dependency check\n"
-        "  --vid                  Enable VID check\n"
-        "  --sid                  Enable SID check, only EXEs are considered by default\n"
-		"  --sidall               Include DLL also into SID check\n"
-		"  --dbg[=val]            Enable Debug flag check,\n"
-		"                         Optionally over ride the default value 'false'\n"
-		"  --e32input             Switches the tool to filesystem mode\n"
-		"  -n, --nocheck          Don't report any check(s) status\n");
-}
-
-/**
-Function to return the usage.
-
-@internalComponent
-@released
-*/
-const String& CmdLineHandler::PrintUsage(void) const
-{
-	return iUsage;
-}
-
-/**
-Function to prepare the version information.
-
-@internalComponent
-@released
-*/
-void CmdLineHandler::Version(void)
-{
-	iVersion.append(gToolDesc);
-	iVersion.append(gMajorVersion);
-	iVersion.append(gMinorVersion);
-	iVersion.append(gMaintenanceVersion);
-	iVersion.append(gCopyright);
-}
-
-/**
-Function to return the version information.
-
-@internalComponent
-@released
-*/
-const String& CmdLineHandler::PrintVersion(void) const
-{
-	return iVersion;
-}
-
-/**
-Function to return the image name one by one.
-
-@internalComponent
-@released
-
-@return - returns image name
-*/
-String CmdLineHandler::NextImageName(void)
-{
-	String imageName = iImageNameList.front();
-	iImageNameList.pop_front();
-	return imageName;
-}
-
-/**
-Function to return the iCommmandFlag.
-
-@internalComponent
-@released
-
-@return - returns iCommmandFlag value.
-*/
-const unsigned int CmdLineHandler::ReportFlag(void) const
-{
-	return iCommmandFlag;
-}
-
-/**
-Function to return the iXmlFileName.
-
-@internalComponent
-@released
-
-@return - returns iXmlFileName value.
-*/
-const String& CmdLineHandler::XmlReportName(void) const
-{
-	return iXmlFileName;
-}
-
-
-/**
-Function to append the XML extension to the received XML name.
-
-@internalComponent
-@released
-*/
-void CmdLineHandler::NormaliseName(void)
-{
-	if (iXmlFileName.find(KXmlExtension) == String::npos)
-	{
-		iXmlFileName.append(KXmlExtension);
-	}
-}
-
-/**
-Function to validate the arguements to ensure that the tool is invoked with proper
-arguments.
-
-@internalComponent
-@released
-*/
-void CmdLineHandler::ValidateArguments(void) const
-{
-	unsigned int validations = EnabledValidations();
-	validations = (validations & KMarkEnable) ? iValidations ^ KMarkEnable:validations; //disable MSB
-
-	if( iCommmandFlag & QuietMode && !(iCommmandFlag & KXmlReport))
-	{
-		throw ExceptionReporter(QUIETMODESELECTED);
-	}
-
-	if(!(iCommmandFlag & KXmlReport) && (iXmlFileName != GXmlFileName))
-	{
-		ExceptionReporter(XMLOPTION).Report();
-	}
-
-	if((iVidValList.size() > 0) && (validations & EVid) == 0)
-	{
-		ExceptionReporter(SUPPRESSCOMBINEDWITHVIDVAL).Report();
-	}
-
-	if((iCommmandFlag & KSidAll) && ((validations & ESid)==0))
-	{
-		ExceptionReporter(SIDALLCOMBINEDWITHSID).Report();
-	}
-
-	if( validations == ENone)
-	{
-		throw ExceptionReporter(ALLCHECKSSUPPRESSED);
-	}
-	
-	if(iNoImage)
-	{
-		throw ExceptionReporter(NOIMAGE);
-	}
-}
-
-/**
-Function to return number of images received through command line.
-
-@internalComponent
-@released
-*/
-unsigned int CmdLineHandler::NoOfImages(void) const
-{
-	return iImageNameList.size();
-}
-
-/**
-Function to return Validations needs to be performed.
-1. If any validation is enabled, then only enabled validations are carried.
-2. If any validation is suppressed, then all validations are carried execept the suppressed ones.
-
-@internalComponent
-@released
-
-@return - returns the enabled Validations
-*/
-const unsigned int CmdLineHandler::EnabledValidations(void) const
-{
-	if(iValidations > 0)
-	{
-		return iValidations;
-	}
-	return (iSuppressions ^ EAllValidation); //Enable unsuppressed options
-}
-
-/**
-Function to convert strings to integers.
-1. If any validation is enabled, then only enabled validations are carried.
-2. If any validation is suppressed, then all validations are carried execept the suppressed ones.
-3. Throws an error if the value is not a decimal or hexadecimal one.
-
-@internalComponent
-@released
-
-@param aStrList - List VID values received at command line
-@param aUnIntList - Received values are validated and put into this container.
-*/
-void CmdLineHandler::StringListToUnIntList(StringList& aStrList, UnIntList& aUnIntList)
-{
-    String tempString;
-	Long64 intValue = 0;
-    while(aStrList.size() > 0)
-    {
-		tempString = aStrList.front();
-		if(tempString.length() >= 2) //Hex number should start with '0x'
-		{
-			//is this an Hexadecimal number?
-			if((tempString.at(0) == '0') && (tempString.at(1) == 'x'))
-			{
-				tempString = tempString.substr(2);
-				unsigned int location = 0;
-				if(!tempString.empty())
-				{
-					while(location < tempString.length()) //Ignore proceeding zeros.
-					{
-						if(tempString.at(location) == '0')
-						{
-							location++; 
-							continue;
-						}
-						break;
-					}
-				}
-				else
-				{
-					throw ExceptionReporter(INVALIDVIDVALUE,(char*)aStrList.front().c_str());
-				}
-				tempString = tempString.substr(location);
-				if(tempString.empty() && location != 0)
-				{
-					tempString = '0';
-				}
-				unsigned int strLength = tempString.length();
-				if(strLength <= KHexEightByte && strLength > 0)
-				{
-					if(tempString.find_first_not_of(KHexNumber) == String::npos)
-					{
-						aUnIntList.push_back(ReaderUtil::HexStrToInt(tempString));
-						aStrList.pop_front();
-						continue;
-					}
-				}
-				else
-				{
-					throw ExceptionReporter(DATAOVERFLOW,(char*)tempString.c_str());
-				}
-			}
-		}
-		//is this an Decimal number?
-		if(tempString.find_first_not_of(KDecNumber) == String::npos)
-		{
-			intValue = ReaderUtil::DecStrToInt(tempString);
-			if(intValue <= KDecHighValue)
-			{
-				aUnIntList.push_back(intValue);
-			}
-			else
-			{
-				throw ExceptionReporter(DATAOVERFLOW,(char*)tempString.c_str());
-			}
-		}
-		else
-		{
-			throw ExceptionReporter(INVALIDVIDVALUE,(char*)tempString.c_str());
-		}
-		aStrList.pop_front();
-    }
-}
-
-
-
-/**
-Function to return vid value list.
-
-@internalComponent
-@released
-
-@return - returns vid value list.
-*/
-UnIntList& CmdLineHandler::VidValueList()
-{
-	return iVidValList;
-}
-
-/**
-Function to return input command string.
-
-@internalComponent
-@released
-
-@return - returns iInputCommand.
-*/
-const String& CmdLineHandler::Command() const
-{
-	return iInputCommand;
-}
-
-/**
-Function identifies whether the image is already received or not.
-
-@internalComponent
-@released
-
-@return	- returns true if the image is already received.
-		- returns false if the image is not received already.
-*/
-bool CmdLineHandler::AlreadyReceived(String& aName)
-{
-	StringList::iterator nameBegin = iImageNameList.begin();
-	StringList::iterator nameEnd = iImageNameList.end();
-	while(nameBegin != nameEnd)
-	{
-		if(aName == *nameBegin)
-		{
-			return true;
-		}
-		++nameBegin;
-	}
-	return false;
-}
-
-/**
-Function to return debug flag value.
-
-@internalComponent
-@released
-
-@return - returns iDebuggableFlagVal.
-*/
-bool CmdLineHandler::DebuggableFlagVal()
-{
-	return iDebuggableFlagVal;
-}
-
-/**
-Function to validate the e32 input.
-
-@internalComponent
-@released
-
-*/
-void CmdLineHandler::ValidateImageNameList(void) 
-{
-	if(iImageNameList.size() > 1)
-	{
-		throw ExceptionReporter(ONLYSINGLEDIRECTORYEXPECTED);
-	}
-}
-
-
-/**
-Function to validate the e32 and no check option arguments.
-
-@internalComponent
-@released
-
-*/
-void CmdLineHandler::ValidateE32NoCheckArguments(void)
-{
-	if((iCommmandFlag & KE32Input) && !iValidations)
-	{
-		throw ExceptionReporter(NOVALIDATIONSENABLED);
-	}
-
-	if((iCommmandFlag & KE32Input) && (iValidations & (EDep | ESid)))
-	{
-		ExceptionReporter(INCORRECTVALUES).Report();
-	}
-}
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Commandline handler for imgcheck Tool, responsible to parse the
+* commandline options and preserve the data for later use
+*
+*/
+
+
+/**
+@file
+@internalComponent
+@released
+*/
+
+#include "cmdlinehandler.h"
+
+/**
+Constructor initializes the iOptionMap with short and long option names as key and
+the value pair says whether the respective option can have value or not.
+
+@internalComponent
+@released
+*/
+CmdLineHandler::CmdLineHandler()
+:iDebuggableFlagVal(false),iXmlFileName(GXmlFileName), iNoImage(true), iCommmandFlag(0), iValidations(0), iSuppressions(0)  {
+	iOptionMap[KLongHelpOption] = ENone;
+	iOptionMap[KLongAllOption] = ENone;
+	iOptionMap[KLongXmlOption] = ENone;
+	iOptionMap[KLongOutputOption] = ESingle; //option can have only 1 value
+	iOptionMap[KLongQuietOption] = ENone;
+	iOptionMap[KLongVerboseOption] = ENone;
+	iOptionMap[KLongSuppressOption]= EMultiple; //This value should be updated, while introducing new validations
+	iOptionMap[KLongVidValOption]= EMultiple;
+	iOptionMap[KShortHelpOption] = ENone;
+	iOptionMap[KShortAllOption] = ENone;
+	iOptionMap[KShortXmlOption] = ENone;
+	iOptionMap[KShortOutputOption] = ESingle; //option can have only 1 value
+	iOptionMap[KShortQuietOption] = ENone;
+	iOptionMap[KShortVerboseOption] = ENone;
+	iOptionMap[KShortSuppressOption] = EMultiple;
+	iOptionMap[KShortNoCheck] = ENone;
+	iOptionMap[KLongSidAllOption] = ENone;
+	iOptionMap[KLongEnableDepCheck] = ENone;
+	iOptionMap[KLongEnableSidCheck] = ENone;
+	iOptionMap[KLongEnableVidCheck] = ENone;
+	iOptionMap[KLongEnableDbgFlagCheck] = EOptional;
+	iOptionMap[KLongE32InputOption] = ENone;
+	iOptionMap[KLongNoCheck] = ENone;
+	iSuppressVal[KSuppressDependency] = EDep;
+	iSuppressVal[KSuppressSid] = ESid;
+	iSuppressVal[KSuppressVid] = EVid;
+
+	Version();
+	Usage();
+}
+
+/**
+Destructor.
+
+@internalComponent
+@released
+*/
+CmdLineHandler::~CmdLineHandler() {
+	iOptionMap.clear();
+	iImageNameList.clear();
+	iSuppressVal.clear();
+	iVidValList.clear();
+}
+
+/**
+Function to parse the command line options.
+Responsible to
+1. Parse the input values.
+2. Print the usage note. 
+3. Identify the valdations to be carried out.
+4. Type of report needs to be generated.
+
+@internalComponent
+@released
+
+@param aArgc - argument count
+@param aArgv[] - argument values
+*/
+ReturnType CmdLineHandler::ProcessCommandLine(unsigned int aArgc, char* aArgv[]) {
+	if(aArgc < 2) {
+		cout << PrintVersion().c_str() << endl;
+		cout << PrintUsage().c_str() << endl;
+		return EQuit;
+	}
+	//ArgumentList argumentList(&aArgv[0], aArgv + aArgc);
+	//int argCount = argumentList.size();
+
+	iInputCommand = KToolName;
+
+	for(unsigned int i = 1; i < aArgc; i++ )  {//Skip tool name		 
+		iInputCommand.append(1,' ');
+		char* arg = aArgv[i];
+		iInputCommand.append(arg);
+		int longOptionFlag = 0;
+		if(IsOption(arg, longOptionFlag)) { 
+			bool optionValue = false;
+			cstrings optionValueList;
+			ParseOption(arg, optionValueList, optionValue);
+			string optionName(arg) ;
+			ReaderUtil::ToLower(optionName);
+			char shortOption = 0;
+			if(Validate(optionName, optionValue, optionValueList.size())) {
+				if(longOptionFlag) {
+					shortOption = optionName.at(2);
+				}
+				else {
+					shortOption = optionName.at(1);
+				}
+			}
+
+			switch(shortOption) {
+				case 'q':
+					iCommmandFlag |= QuietMode;
+					break;
+				case 'a': 
+					iCommmandFlag |= KAll;
+					break;
+				case 'x':
+					iCommmandFlag |= KXmlReport;
+					break;
+				case 'o':
+					iXmlFileName = string(optionValueList.front()); 
+					NormaliseName();
+					break;
+				case 's':
+					if((optionName == KShortSuppressOption) || (optionName == KLongSuppressOption)) {
+						int size = optionValueList.size();
+						for(int idx = 0 ; idx < size ; idx++) {
+							string value(optionValueList.at(idx));
+							SuppressionsMap::iterator it = iSuppressVal.find(value);
+							if(it != iSuppressVal.end()) {
+								if(iValidations > 0) { //Is any check enabled? 
+									if(iValidations & it->second) {
+										iValidations ^= it->second; //Consider only 3 LSB's
+									}
+								}
+								else {//Is this valid value? 
+									iSuppressions |= it->second;
+								}
+							}
+							else {
+								throw ExceptionReporter(UNKNOWNSUPPRESSVAL,optionValueList.at(idx));
+							} 
+						}
+						optionValueList.clear();
+					}
+					else if(optionName == KLongEnableSidCheck) {
+						iValidations |= KMarkEnable;
+						iValidations |= ESid;
+					}
+					else if(optionName == KLongSidAllOption) {
+						iCommmandFlag |= KSidAll;
+					}
+					break;
+				case 'd':
+					if(optionName == KLongEnableDbgFlagCheck) {
+						iValidations |= KMarkEnable;
+						iValidations |= EDbg;
+						if(optionValueList.size() > 0) {
+							if(strcmp(optionValueList.front(),"true") == 0) {
+								iDebuggableFlagVal = true;
+							}
+							else if (strcmp(optionValueList.front(),"false") == 0) {
+								iDebuggableFlagVal = false; 
+							}
+							else {
+								throw ExceptionReporter(UNKNOWNDBGVALUE);
+							}
+						}
+					}
+					else if (optionName == KLongEnableDepCheck) {
+						iValidations |= KMarkEnable;
+						iValidations |= EDep;
+					}
+					break;
+
+				case 'e':
+					if (optionName == KLongE32InputOption) {
+						iCommmandFlag |= KE32Input;
+					}
+					break;
+
+				case 'v':
+					if(optionName == KLongVidValOption) {
+						StringListToUnIntList(optionValueList, iVidValList);
+					}
+					else if(optionName == KLongEnableVidCheck) {
+						iValidations |= KMarkEnable;
+						iValidations |= EVid;
+					}
+					else {
+						iCommmandFlag |= KVerbose;
+						/**Initialize ExceptionImplementation class with verbose mode flag
+						to print all status information to standard output*/
+						ExceptionImplementation::Instance(iCommmandFlag);
+					}
+					break;
+				case 'n':
+					iCommmandFlag |= KNoCheck;
+					break;
+				case 'h':
+					cout << PrintVersion().c_str() << endl;
+					cout << PrintUsage().c_str() << endl;
+					return EQuit; //Don't proceed further
+			}
+		}
+		else {
+			if(!AlreadyReceived(arg)) {
+				iImageNameList.push_back(arg);
+			}
+			else {
+				ExceptionReporter(IMAGENAMEALREADYRECEIVED, arg).Report();
+			}
+
+			iNoImage = false;
+		}
+	} //While loop ends here
+	if((iCommmandFlag || iValidations || iSuppressions) && iNoImage) {
+		PrintVersion();
+		PrintUsage();
+	}
+	//Always log the version information into log file
+	ExceptionImplementation::Instance(iCommmandFlag)->Log(iVersion);
+	ValidateArguments();
+	ValidateE32NoCheckArguments();
+	if(iCommmandFlag & KE32Input) {
+		ValidateImageNameList();
+	}
+	return ESuccess;
+}
+
+/**
+Function identify whether the passed string is an option or not.
+
+@internalComponent
+@released
+
+@param aName - a string received as part of command line
+@param aLongOptionFlag - this flag is set if the option is long else
+it is assumed as short option.
+
+@return - returns true or false
+*/
+bool CmdLineHandler::IsOption(const char* aName, int& aLongOptionFlag) {
+	int prefixCount = 0;
+	int len = strlen(aName);
+	while(aName[prefixCount] == KShortOptionPrefix) {
+		if(len == ++prefixCount) {
+			throw ExceptionReporter(UNKNOWNOPTION, aName);
+		}
+	}
+
+	switch(prefixCount) {
+		case 0: //argument can be an image
+			return false;
+		case 1: // '-'
+			return true;
+		case 2: // '--'
+			aLongOptionFlag = 1;
+			return true;
+		default:
+			throw ExceptionReporter(UNKNOWNPREFIX, aName);
+	}
+}
+
+/**
+Function to do syntax validation on the received option.
+1. Identifies whether the received option is valid or not.
+2. Identifies whether the option can have vaue or not.
+3. Throws an error if no value received for an option which should have value.
+4. Throws an error if more number of values received.
+5. Throws an error if an unwanted value received.
+6. Throws an error if the option is not a valid one.
+
+@internalComponent
+@released
+
+@param aOption - a string received as part of command line.
+@param aOptionValue - Whether option value received or not.
+@param aNoOfVal - Number of values received for this option.
+
+@return - returns true if it is a valid option
+*/
+bool CmdLineHandler::Validate(const string& aOption, bool aOptionValue, unsigned int aNoOfVal) {
+	if(iOptionMap.find(aOption) != iOptionMap.end()) {
+		if(iOptionMap[aOption]) {//Option can have value? 
+			if((aNoOfVal == ENone) && (iOptionMap[aOption] != EOptional)) {//No values received? 
+				throw ExceptionReporter(VALUEEXPECTED, aOption.c_str());
+			}
+
+			if((iOptionMap[aOption] == ESingle) && (ESingle < aNoOfVal)){ //Received values are more than expected 
+				throw ExceptionReporter(UNEXPECTEDNUMBEROFVALUE,aOption.c_str());
+			}
+		}
+		else {
+			if(aOptionValue) {//Is option value received? Any character after the option considered as value. 
+				throw ExceptionReporter(VALUENOTEXPECTED, aOption.c_str());
+			}
+		}
+		return true;
+	}
+	throw ExceptionReporter(UNKNOWNOPTION, aOption.c_str());
+}
+
+/**
+Function to split the option name and option values.
+1. Ignore's the '=' symbol which is following the option. But this is an error, if that
+option does not expecting any value.
+2. Parses the value received with options.
+
+@internalComponent
+@released
+
+@param aFullName - Option with its value 
+@param aOptionValues - Option values put into this parameter
+@param aOptionValue - Set this flag if any value received with the option.
+*/
+void CmdLineHandler::ParseOption(char* aFullName, cstrings& aOptionValues, bool& aOptionValue) { 
+	//unsigned int optionEndLocation = aFullName.find('='); 
+	char* p = strchr(aFullName,'=');
+	if(NULL != p) {
+		aOptionValue = true;
+		*p = 0 ;
+		p++ ;
+		if(0 == *p) {
+			throw ExceptionReporter(VALUEEXPECTED, aFullName);
+		}		 
+		 
+		//Get all the values; use (,) as delimiter
+		char* start = p , *stop = p ; 
+		bool cont = true ;
+		while(cont){
+			while(*stop != ',' && *stop != 0)
+				stop ++;	
+			cont = (0 != *stop) ;
+			if(stop > start){  
+				*stop = 0 ;
+				aOptionValues.push_back(start); 
+				
+			}			 
+			start = stop + 1;
+			stop = start ;
+		}  
+	} 
+}
+
+/**
+Function to initialize the usage.
+
+@internalComponent
+@released
+*/
+void CmdLineHandler::Usage(void) {
+	iUsage.assign("syntax: imgcheck [options] <img1> [<img2 .. imgN>] \n"
+		"imgcheck --e32input [options] (<file> | <directory>) \n"
+		"\n"
+		"options: \n"
+		"  -a, --all,             Report all executable's status\n"
+		"  -q, --quiet,           Command line display off\n"
+		"  -x, --xml,             Generate XML report\n"
+		"  -o=xxx, --output=xxx   Override default XML file name\n"
+		"  -v, --verbose,         Verbose mode output\n"
+		"  -h, --help,            Display this message\n"
+		"  -s=val1[,val2][...], --suppress=val1[,val2][...] \n"
+		"                         Suppress one or more check,\n"
+		"                         Possible values are dep, sid and vid\n"
+		"  --vidlist=val1[,val2][...] \n"
+		"                         One or more VID value(s) \n"
+		"  --dep                  Enable dependency check\n"
+		"  --vid                  Enable VID check\n"
+		"  --sid                  Enable SID check, only EXEs are considered by default\n"
+		"  --sidall               Include DLL also into SID check\n"
+		"  --dbg[=val]            Enable Debug flag check,\n"
+		"                         Optionally over ride the default value 'false'\n"
+		"  --e32input             Switches the tool to filesystem mode\n"
+		"  -n, --nocheck          Don't report any check(s) status\n");
+}
+
+/**
+Function to return the usage.
+
+@internalComponent
+@released
+*/
+const string& CmdLineHandler::PrintUsage(void) const {
+	return iUsage;
+}
+
+/**
+Function to prepare the version information.
+
+@internalComponent
+@released
+*/
+void CmdLineHandler::Version(void) {
+	iVersion.append(gToolDesc);
+	iVersion.append(gMajorVersion);
+	iVersion.append(gMinorVersion);
+	iVersion.append(gMaintenanceVersion);
+	iVersion.append(gCopyright);
+}
+
+/**
+Function to return the version information.
+
+@internalComponent
+@released
+*/
+const string& CmdLineHandler::PrintVersion(void) const {
+	return iVersion;
+}
+
+/**
+Function to return the image name one by one.
+
+@internalComponent
+@released
+
+@return - returns image name
+*/
+const char* CmdLineHandler::NextImageName(void) {
+	const char* imageName = 0 ;
+	if( iImageNameList.size() > 0 ) {
+		imageName = iImageNameList.at(0);
+		iImageNameList.erase(iImageNameList.begin());
+	}
+	return imageName;
+}
+
+/**
+Function to return the iCommmandFlag.
+
+@internalComponent
+@released
+
+@return - returns iCommmandFlag value.
+*/
+const unsigned int CmdLineHandler::ReportFlag(void) const {
+	return iCommmandFlag;
+}
+
+/**
+Function to return the iXmlFileName.
+
+@internalComponent
+@released
+
+@return - returns iXmlFileName value.
+*/
+const string& CmdLineHandler::XmlReportName(void) const {
+	return iXmlFileName;
+}
+
+
+/**
+Function to append the XML extension to the received XML name.
+
+@internalComponent
+@released
+*/
+void CmdLineHandler::NormaliseName(void) {
+	if (iXmlFileName.find(KXmlExtension) == string::npos) {
+		iXmlFileName.append(KXmlExtension);
+	}
+}
+
+/**
+Function to validate the arguements to ensure that the tool is invoked with proper
+arguments.
+
+@internalComponent
+@released
+*/
+void CmdLineHandler::ValidateArguments(void) const {
+	unsigned int validations = EnabledValidations();
+	validations = (validations & KMarkEnable) ? iValidations ^ KMarkEnable:validations; //disable MSB
+
+	if( iCommmandFlag & QuietMode && !(iCommmandFlag & KXmlReport)) {
+		throw ExceptionReporter(QUIETMODESELECTED);
+	}
+
+	if(!(iCommmandFlag & KXmlReport) && (iXmlFileName != GXmlFileName)) {
+		ExceptionReporter(XMLOPTION).Report();
+	}
+
+	if((iVidValList.size() > 0) && (validations & EVid) == 0) {
+		ExceptionReporter(SUPPRESSCOMBINEDWITHVIDVAL).Report();
+	}
+
+	if((iCommmandFlag & KSidAll) && ((validations & ESid)==0)) {
+		ExceptionReporter(SIDALLCOMBINEDWITHSID).Report();
+	}
+
+	if( validations == ENone) {
+		throw ExceptionReporter(ALLCHECKSSUPPRESSED);
+	}
+
+	if(iNoImage) {
+		throw ExceptionReporter(NOIMAGE);
+	}
+}
+
+/**
+Function to return number of images received through command line.
+
+@internalComponent
+@released
+*/
+unsigned int CmdLineHandler::NoOfImages(void) const {
+	return iImageNameList.size();
+}
+
+/**
+Function to return Validations needs to be performed.
+1. If any validation is enabled, then only enabled validations are carried.
+2. If any validation is suppressed, then all validations are carried execept the suppressed ones.
+
+@internalComponent
+@released
+
+@return - returns the enabled Validations
+*/
+const unsigned int CmdLineHandler::EnabledValidations(void) const {
+	if(iValidations > 0) {
+		return iValidations;
+	}
+	return (iSuppressions ^ EAllValidation); //Enable unsuppressed options
+}
+static int indexOf(const char* str, char ch){ 
+	for(int i = 0 ; str[i] != 0 ; i++){
+		if(str[i] == ch) 
+			return i ;
+	}
+	return -1 ;
+}
+/**
+Function to convert cstrings to integers.
+1. If any validation is enabled, then only enabled validations are carried.
+2. If any validation is suppressed, then all validations are carried execept the suppressed ones.
+3. Throws an error if the value is not a decimal or hexadecimal one.
+
+@internalComponent
+@released
+
+@param aStrList - List VID values received at command line
+@param aUnIntList - Received values are validated and put into this container.
+*/
+void CmdLineHandler::StringListToUnIntList(cstrings& aStrList, UnIntList& aUnIntList) { 
+	int size = aStrList.size();
+	for(int i = 0 ; i < size ; i++ ) {
+		const char* arg = aStrList.at(i); 
+		unsigned int val = 0 ;
+		if('0' == arg[0]  && 'x' == (arg[1] | 0x20)){ // hex
+			arg += 2; 		
+			const char* savedStr = arg ;
+			int index;			
+			while(*arg){ 
+				if(val > 0x0fffffff)
+					throw ExceptionReporter(DATAOVERFLOW,savedStr);
+				index = indexOf(KHexNumber,*arg);
+				if(-1 == index)
+					throw ExceptionReporter(INVALIDVIDVALUE,savedStr);
+				val <<= 4 ;
+				val += index ;
+				arg ++ ;
+			}
+		}else{ // dec
+			const char* savedStr = arg ;
+			int index;
+			while(*arg){ 
+				if(val >= 0x1999999A) // 0xffffffff / 10
+					throw ExceptionReporter(DATAOVERFLOW,savedStr);
+				index = indexOf(KDecNumber,*arg);
+				if(-1 == index)
+					throw ExceptionReporter(INVALIDVIDVALUE,savedStr);
+				val *= 10 ;
+				val += index ;
+				arg ++ ;
+			}
+		}		
+		aUnIntList.push_back(val);	 
+	}
+	aStrList.clear();
+}
+
+
+
+/**
+Function to return vid value list.
+
+@internalComponent
+@released
+
+@return - returns vid value list.
+*/
+UnIntList& CmdLineHandler::VidValueList() {
+	return iVidValList;
+}
+
+/**
+Function to return input command string.
+
+@internalComponent
+@released
+
+@return - returns iInputCommand.
+*/
+const string& CmdLineHandler::Command() const {
+	return iInputCommand;
+}
+
+/**
+Function identifies whether the image is already received or not.
+
+@internalComponent
+@released
+
+@return	- returns true if the image is already received.
+- returns false if the image is not received already.
+*/
+bool CmdLineHandler::AlreadyReceived(const char* aName) {
+	for(cstrings::iterator it = iImageNameList.begin(); it != iImageNameList.end();it++) {
+		if(aName == *it || strcmp(aName,*it) == 0) {
+			return true;
+		} 
+	}
+	return false;
+}
+
+/**
+Function to return debug flag value.
+
+@internalComponent
+@released
+
+@return - returns iDebuggableFlagVal.
+*/
+bool CmdLineHandler::DebuggableFlagVal() {
+	return iDebuggableFlagVal;
+}
+
+/**
+Function to validate the e32 input.
+
+@internalComponent
+@released
+
+*/
+void CmdLineHandler::ValidateImageNameList(void)  {
+	if(iImageNameList.size() > 1) {
+		throw ExceptionReporter(ONLYSINGLEDIRECTORYEXPECTED);
+	}
+}
+
+
+/**
+Function to validate the e32 and no check option arguments.
+
+@internalComponent
+@released
+
+*/
+void CmdLineHandler::ValidateE32NoCheckArguments(void) {
+	if((iCommmandFlag & KE32Input) && !iValidations) {
+		throw ExceptionReporter(NOVALIDATIONSENABLED);
+	}
+
+	if((iCommmandFlag & KE32Input) && (iValidations & (EDep | ESid))) {
+		ExceptionReporter(INCORRECTVALUES).Report();
+	}
+}
--- a/imgtools/imgcheck/src/cmdlinewriter.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/src/cmdlinewriter.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,271 +1,234 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Generates commandline report.
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "cmdlinewriter.h"
-
-/**
-Constructor: CmdLineWriter class
-
-@internalComponent
-@released
-*/
-CmdLineWriter::CmdLineWriter(unsigned int aInputOptions)
-: iForDepAlign(0), iFormatSize(0), iBuffer(0), iRptType(KCmdLine), iCmdOptions(aInputOptions)
-{
-	iFormatMessage.flush();
-}
-
-
-/**
-Destructor:	CmdLineWriter class
-
-Clear the Buffer.
-
-@internalComponent
-@released
-*/
-CmdLineWriter::~CmdLineWriter(void)
-{
-	delete [] iBuffer;
-}
-
-
-/**
-Writes report header to the cmd line..
-Allocates the memory for formatting purpose.
-
-@internalComponent
-@released
-*/
-void CmdLineWriter::StartReport(void)
-{
-	iBuffer = new char[KCmdGenBufferSize];
-	if (iBuffer == KNull)
-	{
-		throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
-	}
-}
-
-
-/**
-Writes the end report info..
-Transfer the stream data to stdout.
-
-@internalComponent
-@released
-*/
-void CmdLineWriter::EndReport(void)
-{
-	String outMsg = iFormatMessage.str();
-	std::cout << outMsg.c_str();
-}
-
-
-/**
-Writes the executable element footer.
-
-@internalComponent
-@released
-*/
-void CmdLineWriter::EndExecutable(void)
-{
-	iFormatMessage << std::endl;
-	iForDepAlign = false;
-
-}
-
-
-/**
-Writes the Delimiter to cmd line.
-
-@internalComponent
-@released
-*/
-void CmdLineWriter::WriteDelimiter(void)
-{
-	if(iCmdOptions & KNoCheck)
-	{
-		iFormatMessage << KCmdLineDelimiterNoStatus.c_str() << std::endl;
-	}
-	else
-	{
-		iFormatMessage << KCmdLineDelimiter.c_str() << std::endl;
-	}
-}
-
-
-/**
-Formats the given element based on set size and places to outstream.
-
-@internalComponent
-@released
-
-@param aElement - Reference element to be formated
-*/
-void CmdLineWriter::FormatAndWriteElement(const String& aElement)
-{
-	if (aElement.size() < iFormatSize)
-	{
-		memset(iBuffer,' ',iFormatSize);
-		iBuffer[iFormatSize] = '\0';
-		memcpy(iBuffer,aElement.c_str(),aElement.size());
-	}
-	else if(aElement.size() >= (unsigned long)KCmdGenBufferSize)
-	{
-		throw ExceptionReporter(FILENAMETOOBIG, __FILE__, __LINE__);
-	}
-	else
-	{
-		strcpy(iBuffer,aElement.c_str());
-	}
-	iFormatMessage << iBuffer << '\t';
-}
-
-/**
-Writes the note about unknown dependency.
-
-@internalComponent
-@released
-*/
-void CmdLineWriter::WriteNote(void)
-{
-	iFormatMessage << KNote.c_str() << ": " << KUnknownDependency << KNoteMesg.c_str() << std::endl;
-}
-
-
-/**
-Writes the image element footer.
-
-@internalComponent
-@released
-*/
-void CmdLineWriter::EndImage(void)
-{
-	WriteDelimiter();	
-}
-
-
-/**
-Writes the executable name element.
-
-@internalComponent
-@released
-
-@param aExeName  - Reference to executable name.
-*/
-void CmdLineWriter::StartExecutable(const unsigned int /* aSerNo */, const String& aExeName)
-{
-	iFormatSize = KCmdFormatTwentyTwoWidth;
-	FormatAndWriteElement(aExeName);
-	iForDepAlign = true;
-}	
-
-
-/**
-Writes the image name element.
-
-@internalComponent
-@released
-
-@param aImageName  - Reference to image name.
-*/
-void CmdLineWriter::StartImage(const String& aImageName)
-{
-	WriteDelimiter();
-	iFormatMessage << KCmdImageName.c_str() << aImageName.c_str() << std::endl;
-	WriteDelimiter();
-	if(iCmdOptions & KNoCheck)
-	{
-		iFormatMessage << KCmdHeaderNoStatus.c_str() << std::endl;
-	}
-	else
-	{
-		iFormatMessage << KCmdHeader.c_str() << std::endl;
-	}
-	WriteDelimiter();
-}
-
-
-/**
-Writes the attribute, their values and the status along with formating the output.
-
-@internalComponent
-@released
-
-@param aOneSetExeAtt - Reference to the attributes, their value and status
-*/	
-void CmdLineWriter::WriteExeAttribute(ExeAttribute& aOneSetExeAtt)
-{
-	if(!iForDepAlign)
-	{
-		iFormatSize = KCmdFormatTwentyTwoWidth;
-		FormatAndWriteElement("");
-	}
-
-	iFormatSize = KCmdFormatTwelveWidth;
-	if(KCmdDbgName != aOneSetExeAtt.iAttName)
-	{
-		FormatAndWriteElement(aOneSetExeAtt.iAttName.c_str());
-	}
-	else
-	{
-		FormatAndWriteElement(KCmdDbgDisplayName.c_str());
-	}
-	
-   	if (KCmdDepName != aOneSetExeAtt.iAttName && KCmdDbgName != aOneSetExeAtt.iAttName)
-	{
-		unsigned int val;
-		val = Common::StringToInt(aOneSetExeAtt.iAttValue);
-		
-		// to display the hex value in the format of 0x00000000 if the value is 0
-		iFormatMessage << "0x";
-		iFormatMessage.width(KCmdFormatEightWidth);
-		iFormatMessage.fill('0');
-		iFormatMessage << std::hex << val << '\t';	
-		iFormatMessage.fill(' ');
-		iFormatMessage.width(KCmdFormatThirtyWidth);
-	}
-	else
-	{
-		iFormatSize = KCmdFormatTwentyTwoWidth;
-		FormatAndWriteElement(aOneSetExeAtt.iAttValue.c_str());
-	}
-	iFormatSize = KCmdFormatTwentyTwoWidth;
-	FormatAndWriteElement(aOneSetExeAtt.iAttStatus.c_str());
-	iFormatMessage << std::endl;
-	iForDepAlign = false;
-}
-
-
-/**
-Returns the report type.
-
-@internalComponent
-@released
-*/
-const String& CmdLineWriter::ReportType(void)
-{
-	return iRptType;
-}
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Generates commandline report.
+*
+*/
+
+
+/**
+@file
+@internalComponent
+@released
+*/
+
+#include "cmdlinewriter.h"
+#include <stdio.h>
+/**
+Constructor: CmdLineWriter class
+
+@internalComponent
+@released
+*/
+CmdLineWriter::CmdLineWriter(unsigned int aInputOptions)
+: iForDepAlign(0), iFormatSize(0),  iRptType(KCmdLine), iCmdOptions(aInputOptions) {
+	//iFormatMessage.flush();
+}
+
+
+/**
+Destructor:	CmdLineWriter class
+
+Clear the Buffer.
+
+@internalComponent
+@released
+*/
+CmdLineWriter::~CmdLineWriter(void) {
+
+}
+
+
+/**
+Writes report header to the cmd line..
+Allocates the memory for formatting purpose.
+
+@internalComponent
+@released
+*/
+void CmdLineWriter::StartReport(void) { 
+}
+
+
+/**
+Writes the end report info..
+Transfer the stream data to stdout.
+
+@internalComponent
+@released
+*/
+void CmdLineWriter::EndReport(void) {
+	iFormatMessage.flush();
+	string str ;
+	while(!iFormatMessage.eof()){
+		getline(iFormatMessage,str);
+		cout << str.c_str()<<endl ;
+	}
+}
+
+
+/**
+Writes the executable element footer.
+
+@internalComponent
+@released
+*/
+void CmdLineWriter::EndExecutable(void) {
+	iFormatMessage << endl;
+	iForDepAlign = false;
+
+}
+
+
+/**
+Writes the Delimiter to cmd line.
+
+@internalComponent
+@released
+*/
+void CmdLineWriter::WriteDelimiter(void) {
+	if(iCmdOptions & KNoCheck) {
+		iFormatMessage << KCmdLineDelimiterNoStatus << endl;
+	}
+	else {
+		iFormatMessage << KCmdLineDelimiter << endl;
+	}
+
+}
+
+
+/**
+Formats the given element based on set size and places to outstream.
+
+@internalComponent
+@released
+
+@param aElement - Reference element to be formated
+*/
+void CmdLineWriter::FormatAndWriteElement(const string& aElement) {
+	if(aElement.length() < iFormatSize)
+		iFormatMessage << setw(iFormatSize) << aElement.c_str(); 
+	else 
+		iFormatMessage << aElement.c_str() << ' '; 
+}
+
+/**
+Writes the note about unknown dependency.
+
+@internalComponent
+@released
+*/
+void CmdLineWriter::WriteNote(void){
+	iFormatMessage << KNote << ": " << KUnknownDependency << KNoteMesg << endl;
+}
+
+
+/**
+Writes the image element footer.
+
+@internalComponent
+@released
+*/
+void CmdLineWriter::EndImage(void){
+	WriteDelimiter();	
+
+}
+
+
+/**
+Writes the executable name element.
+
+@internalComponent
+@released
+
+@param aExeName  - Reference to executable name.
+*/
+void CmdLineWriter::StartExecutable(const unsigned int /* aSerNo */, const string& aExeName) {
+	iFormatSize = KCmdFormatTwentyEightWidth; 
+	FormatAndWriteElement(aExeName);
+	iForDepAlign = true;
+}	
+
+
+/**
+Writes the image name element.
+
+@internalComponent
+@released
+
+@param aImageName  - Reference to image name.
+*/
+void CmdLineWriter::StartImage(const string& aImageName) {
+	WriteDelimiter();
+	iFormatMessage << KCmdImageName << aImageName.c_str() << endl;
+	WriteDelimiter();
+	iFormatMessage << setw(KCmdFormatTwentyEightWidth) << left <<setfill(' ')<< "Executable" ;
+	iFormatMessage << setw(KCmdFormatTwelveWidth)  << "Attribute" ;
+	iFormatMessage << setw(KCmdFormatTwelveWidth) << "Value" ;
+	if(0 == (iCmdOptions & KNoCheck)) {
+		iFormatMessage << setw(KCmdFormatTwelveWidth) << "Status" ;
+	}
+	iFormatMessage<<endl;
+	WriteDelimiter();
+}
+
+
+/**
+Writes the attribute, their values and the status along with formating the output.
+
+@internalComponent
+@released
+
+@param aOneSetExeAtt - Reference to the attributes, their value and status
+*/	
+void CmdLineWriter::WriteExeAttribute(ExeAttribute& aOneSetExeAtt) {
+	if(!iForDepAlign) {		
+		iFormatSize = KCmdFormatTwentyEightWidth;
+		FormatAndWriteElement("");
+	}
+	iFormatSize = KCmdFormatTwelveWidth; 
+	if(KCmdDbgName != aOneSetExeAtt.iAttName) { 
+		FormatAndWriteElement(aOneSetExeAtt.iAttName);
+	}
+	else {
+		FormatAndWriteElement(KCmdDbgDisplayName);
+	}
+
+	if (KCmdDepName != aOneSetExeAtt.iAttName && KCmdDbgName != aOneSetExeAtt.iAttName) {
+		unsigned int val = Common::StringToInt(aOneSetExeAtt.iAttValue);
+		char str[20];
+		sprintf(str,"0x%08X",val);
+		// to display the hex value in the format of 0x00000000 if the value is 0
+		iFormatMessage << setw(KCmdFormatTwelveWidth)  << str ; 
+	}
+	else {
+		iFormatSize = KCmdFormatTwentyEightWidth;
+		FormatAndWriteElement(aOneSetExeAtt.iAttValue);
+	}
+	iFormatSize = KCmdFormatTwelveWidth;
+	FormatAndWriteElement(aOneSetExeAtt.iAttStatus);  
+	iFormatMessage << endl;
+	iForDepAlign = false;
+}
+
+
+/**
+Returns the report type.
+
+@internalComponent
+@released
+*/
+const string& CmdLineWriter::ReportType(void) {
+	return iRptType;
+}
--- a/imgtools/imgcheck/src/common.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/src/common.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,62 +1,60 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Generally used functions written here
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "common.h"
-#include <sstream>
-
-/** 
-Function to convert Integer to string
-
-@internalComponent
-@released
-
-@param aValue - The value needs to be converted
-
-@return - return the converted string
-*/
-String Common::IntToString(unsigned int aValue)
-{
-    OStringStream outStrStream;
-    outStrStream << aValue;
-    return outStrStream.str();
-}
-
-/** 
-Function to convert string to integer
-
-@internalComponent
-@released
-
-@param aValue - The string needs to be converted
-
-@return - return the converted value
-*/
-unsigned int Common::StringToInt(String& aStringVal)
-{
-    std::istringstream iss(aStringVal);
-    unsigned int intVal;
-    iss >> std::dec >> intVal;
-    return intVal;
-}
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Generally used functions written here
+*
+*/
+
+
+/**
+@file
+@internalComponent
+@released
+*/
+
+#include "common.h"
+#include <sstream>
+
+/** 
+Function to convert Integer to string
+
+@internalComponent
+@released
+
+@param aValue - The value needs to be converted
+
+@return - return the converted string
+*/
+string Common::IntToString(unsigned int aValue) {
+	ostringstream outStrStream;
+	outStrStream << aValue;
+	return outStrStream.str();
+}
+
+/** 
+Function to convert string to integer
+
+@internalComponent
+@released
+
+@param aValue - The string needs to be converted
+
+@return - return the converted value
+*/
+unsigned int Common::StringToInt(string& aStringVal) {
+	istringstream iss(aStringVal);
+	unsigned int intVal;
+	iss >> dec >> intVal;
+	return intVal;
+}
--- a/imgtools/imgcheck/src/dbgflagchecker.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/src/dbgflagchecker.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,131 +1,126 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* DbgFlagChecker class is to 
-* 1. extract all Debuggable flag from all executables present in ROM/ROFS sections.
-* 2. Validate them.
-* 3. Put the validated data into Reporter class Instance.
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-#include "dbgflagchecker.h"
-
-/** 
-Constructor intializes the iDbgFlag member.
-
-@internalComponent
-@released
-
-@param aCmdPtr - pointer to an processed CmdLineHandler object
-@param aImageReaderList - List of ImageReader insatance pointers
-*/
-DbgFlagChecker::DbgFlagChecker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList)
-:Checker(aCmdPtr, aImageReaderList)
-{
-	iUserDefinedDbgFlag = iCmdLine->DebuggableFlagVal();
-}
-
-/**
-Destructor
-
-@internalComponent
-@released
-*/
-DbgFlagChecker::~DbgFlagChecker()
-{
-}
-
-/**
-Fucntion responsible to Prepare the E32 executables Debuggable flag data
-
-@internalComponent
-@released
-
-@param ImgVsExeStatus - Global integrated container which contains image, exes and attribute value status.
-*/
-void DbgFlagChecker::Check(ImgVsExeStatus& aImgVsExeStatus)
-{
-	ImageReaderPtrList::iterator begin = iImageReaderList.begin();
-	ImageReaderPtrList::iterator end = iImageReaderList.end();
-	ExeVsIdDataMap exeVsIdDataMap;
-	ExeVsIdDataMap::iterator exeBegin;
-	ExeVsIdDataMap::iterator exeEnd;
-	ExeVsIdDataMap::iterator exeTemp;
-	ImageReader* imageReader = KNull;
-	String imageName;
-	while(begin != end)
-	{
-		imageReader = *begin;
-		imageName = imageReader->ImageName();
-		ExceptionReporter(GATHERINGIDDATA, (char*)KDbgFlag.c_str(),(char*)imageName.c_str()).Log();
-		imageReader->PrepareExeVsIdMap();
-		
-		exeVsIdDataMap = imageReader->GetExeVsIdMap();
-		exeBegin = exeVsIdDataMap.begin();
-		exeEnd = exeVsIdDataMap.end();
-		if((aImgVsExeStatus[imageName].size() == 0) 
-			|| (aImgVsExeStatus[imageName][exeBegin->first].iIdData == KNull))
-		{
-			while(exeBegin != exeEnd)
-			{
-				aImgVsExeStatus[imageName][exeBegin->first].iIdData = exeBegin->second;
-				aImgVsExeStatus[imageName][exeBegin->first].iExeName = exeBegin->first;
-				++exeBegin;
-			}
-		}
-		++begin;
-	}
-}
-
-/**
-Function responsible to Validate and write the debuggable flag data into Reporter.
-
-@internalComponent
-@released
-
-@param aExeContainer - Global integrated container which contains all the attribute, values and the status.
-*/
-void DbgFlagChecker::PrepareAndWriteData(ExeContainer* aExeContainer)
-{
-	ExeAttribute* exeAtt = KNull;
-	IdData* idData = KNull;
-	
-	idData = aExeContainer->iIdData;
-	exeAtt = new ExeAttribute;
-	if(!exeAtt)
-	{
-		throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
-	}
-	exeAtt->iAttName = KDbgFlag;
-	exeAtt->iAttValue = (idData->iDbgFlag)? String("true") : String("false");
-	if(!iNoCheck)
-	{
-		idData->iDbgFlagStatus = (iUserDefinedDbgFlag == idData->iDbgFlag) ? KDbgMatching : KDbgNotMatching;
-		exeAtt->iAttStatus = idData->iDbgFlagStatus;		
-	}
-	else
-	{
-		exeAtt->iAttStatus = KNull;
-	}
-	if(iAllExecutables || (exeAtt->iAttStatus == KDbgNotMatching) || iNoCheck)
-	{
-		aExeContainer->iExeAttList.push_back(exeAtt);
-	}
-}
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* DbgFlagChecker class is to 
+* 1. extract all Debuggable flag from all executables present in ROM/ROFS sections.
+* 2. Validate them.
+* 3. Put the validated data into Reporter class Instance.
+*
+*/
+
+
+/**
+ @file
+ @internalComponent
+ @released
+*/
+#include "dbgflagchecker.h"
+
+/** 
+Constructor intializes the iDbgFlag member.
+
+@internalComponent
+@released
+
+@param aCmdPtr - pointer to an processed CmdLineHandler object
+@param aImageReaderList - List of ImageReader insatance pointers
+*/
+DbgFlagChecker::DbgFlagChecker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList)
+:Checker(aCmdPtr, aImageReaderList) {
+	iUserDefinedDbgFlag = iCmdLine->DebuggableFlagVal();
+}
+
+/**
+Destructor
+
+@internalComponent
+@released
+*/
+DbgFlagChecker::~DbgFlagChecker() {
+}
+
+/**
+Fucntion responsible to Prepare the E32 executables Debuggable flag data
+
+@internalComponent
+@released
+
+@param ImgVsExeStatus - Global integrated container which contains image, exes and attribute value status.
+*/
+void DbgFlagChecker::Check(ImgVsExeStatus& aImgVsExeStatus) { 
+	 
+	int readerCount = iImageReaderList.size();
+	for(int i = 0 ; i < readerCount ; i++) {
+		ImageReader* reader = iImageReaderList.at(i);
+		const char* imageName = reader->ImageName();
+		ExceptionReporter(GATHERINGIDDATA, KDbgFlag,imageName).Log();
+		reader->PrepareExeVsIdMap();
+		
+		ExeVsIdDataMap& exeVsIdDataMap = const_cast<ExeVsIdDataMap&>(reader->GetExeVsIdMap()); 
+		ImgVsExeStatus::iterator pos = aImgVsExeStatus.find(imageName);
+		ExeVsMetaData* p = 0;
+		if(pos == aImgVsExeStatus.end()){
+			p = new ExeVsMetaData();
+			put_item_to_map(aImgVsExeStatus,imageName,p);
+		}
+		else
+			p = pos->second ;
+		for(ExeVsIdDataMap::iterator it = exeVsIdDataMap.begin();
+		it != exeVsIdDataMap.end(); it++ ) {			 
+			ExeVsMetaData::iterator i = p->find(it->first);
+			if(i == p->end()){
+				ExeContainer container;
+				container.iExeName = it->first;
+				container.iIdData = it->second ;
+				put_item_to_map(*p,it->first,container);
+			}
+			else if(i->second.iIdData == KNull){				
+				i->second.iExeName = it->first;
+				i->second.iIdData = it->second ;
+			}  
+			 
+		} 
+	}
+}
+
+/**
+Function responsible to Validate and write the debuggable flag data into Reporter.
+
+@internalComponent
+@released
+
+@param aExeContainer - Global integrated container which contains all the attribute, values and the status.
+*/
+void DbgFlagChecker::PrepareAndWriteData(ExeContainer& aExeContainer) {
+	ExeAttribute* exeAtt = KNull;
+	IdData* idData = KNull;
+	
+	idData = aExeContainer.iIdData;
+	exeAtt = new ExeAttribute;
+	if(!exeAtt) {
+		throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
+	}
+	exeAtt->iAttName = KDbgFlag;
+	exeAtt->iAttValue = (idData->iDbgFlag)? string("true") : string("false");
+	if(!iNoCheck) {
+		idData->iDbgFlagStatus = (iUserDefinedDbgFlag == idData->iDbgFlag) ? KDbgMatching : KDbgNotMatching;
+		exeAtt->iAttStatus = idData->iDbgFlagStatus;		
+	}
+	else {
+		exeAtt->iAttStatus = KNull;
+	}
+	if(iAllExecutables || (exeAtt->iAttStatus == KDbgNotMatching) || iNoCheck) {
+		aExeContainer.iExeAttList.push_back(exeAtt);
+	}
+}
--- a/imgtools/imgcheck/src/depchecker.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/src/depchecker.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,243 +1,227 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* DepChecker class is responsible to Validate the dependencies existence and put the  
-* prepared data into Reporter.
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "depchecker.h"
-
-/** 
-Constructor intializes the iHashPtr and iHiddenExeHashPtr members.
-
-@internalComponent
-@released
-
-@param aCmdInput - pointer to a processed CmdLineHandler object
-@param aImageReaderList - List of ImageReader insatance pointers
-*/
-DepChecker::DepChecker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList, bool aNoRomImage) 
-:Checker(aCmdPtr, aImageReaderList), iNoRomImage(aNoRomImage)
-{
-	iHashPtr = new HashTable(KHashTableSize); 
-	iHiddenExeHashPtr = new HashTable(KHiddenExeHashSize);
-}
-
-/** 
-Destructor deletes the imagereader objects and hash tables.
-
-@internalComponent
-@released
-*/
-DepChecker::~DepChecker()
-{
-	DELETE(iHiddenExeHashPtr);
-	DELETE(iHashPtr);
-	iAddressVsExeName.clear();
-}
-
-/**
-Fucntion responsible to
-1. Prepare the ROM and ROFS image executable List
-2. Gather Dependencies of all executables present in the ROFS image
-3. Prepare the input data for Reporter
-
-@internalComponent
-@released
-
-@param ImgVsExeStatus - Global integrated container which contains image, exes and attribute value status.
-*/
-void DepChecker::Check(ImgVsExeStatus& aImgVsExeStatus)
-{
-	unsigned int imgCnt = 0;
-	RomImagePassed();
-	String imageName;
-	ExeNamesVsDepListMap::iterator exeBegin;
-	ExeNamesVsDepListMap::iterator exeEnd;
-	while(imgCnt < iImageReaderList.size())
-	{
-		imageName = iImageReaderList[imgCnt]->ImageName();
-		PrepareImageExeList(iImageReaderList[imgCnt]);
-		//Gather dependencies of all the images.
-		ExceptionReporter(GATHERINGDEPENDENCIES, (char*)imageName.c_str()).Log();
-		ExeNamesVsDepListMap& depMap = iImageReaderList[imgCnt]->GatherDependencies();
-		exeBegin = depMap.begin();
-		exeEnd = depMap.end();
-		while(exeBegin != exeEnd)
-		{
-			StringList& list = exeBegin->second;
-			aImgVsExeStatus[imageName][exeBegin->first].iIdData = KNull;
-			aImgVsExeStatus[imageName][exeBegin->first].iDepList = list;
-			++exeBegin;
-		}
-		++imgCnt;
-	}
-}
-
-/**
-Function responsible to
-1. Prepare the ExecutableList
-2. Put the received Excutable list into HASH table, this data will be used later 
-   to identify the dependencies existense.
-
-@internalComponent
-@released
-
-@param aImageReader - ImageReader instance pointer.
-*/
-void DepChecker::PrepareImageExeList(ImageReader* aImageReader)
-{
-	aImageReader->PrepareExecutableList();
-	StringList aExeList = aImageReader->GetExecutableList();
-	iHashPtr->InsertStringList(aExeList); //Put executable names into Hash
-	/**
-	In ROM if any file is hidden then its entry is not placed in the directory 
-	section of the image during image building time. But still the entry data is 
-	already resolved and ready for xip. So this entry is marked here as Unknown
-	Dependency and its status is Hidden.
-	*/
-	StringList hiddenExeList = aImageReader->GetHiddenExeList();
-	iHiddenExeHashPtr->Insert(KUnknownDependency); //ROm Specific and only once
-	iHiddenExeHashPtr->InsertStringList(hiddenExeList);
-	DeleteHiddenExeFromExecutableList(aImageReader, hiddenExeList);
-	String imgName = aImageReader->ImageName();
-	ExceptionReporter(NOOFEXECUTABLES, (char*)imgName.c_str(), aExeList.size()).Log();
-	ExceptionReporter(NOOFHEXECUTABLES, (char*)imgName.c_str(), hiddenExeList.size()).Log();
-}
-
-/**
-Function responsible to delete the hidden executables from iExecutableList.
-In ROFS image, if a file is hidden then its duplicate entry is created to say it is
-hidden. But the other entry is already placed in the executable list and it is 
-available in iHashPtr Hash table. So this needs to be deleted form iHashPtr, then only
-it is possible to get the status "Hidden" for such executables.
-
-@internalComponent
-@released
-
-@param aImageReader - ImageReader instance pointer.
-@param aHiddenExeList - List containing the hidden exe's.
-*/
-void DepChecker::DeleteHiddenExeFromExecutableList(ImageReader* /*aImageReader*/, StringList& aHiddenExeList)
-{
-	StringList::iterator begin = aHiddenExeList.begin();
-	StringList::iterator end = aHiddenExeList.end();
-	while(begin != end)
-	{
-		iHashPtr->Delete(*begin);
-		++begin;
-	}
-}
-
-/**
-Function responsible to prepare the data input for Report Generator.
-Traverses through all the images to identify the executables dependency status.
-
-@internalComponent
-@released
-
-@param aExeContainer - Global integrated container which contains all the attribute, values and the status.
-*/
-void DepChecker::PrepareAndWriteData(ExeContainer* aExeContainer)
-{
-	ExeAttribute* exeAtt;
-	StringList& depList = aExeContainer->iDepList;
-	StringList::iterator depBegin = depList.begin();
-	StringList::iterator depEnd = depList.end();
-	while(depBegin != depEnd)
-	{
-		String status;
-		if(!iNoCheck)
-		{
-			CollectDependencyStatus((*depBegin), status);
-		
-			if(status == String(KStatusNo))
-			{
-				if(iHiddenExeHashPtr->IsAvailable(*depBegin))
-				{
-					status.assign(KStatusHidden);
-				}
-			}
-			//Include only missing dependencies by default
-			if(!iAllExecutables && (status != String(KStatusNo)))
-			{
-				++depBegin;
-				continue;
-			}
-		}
-		exeAtt = new ExeAttribute;
-		if(exeAtt == KNull)
-		{
-			throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
-		}
-		exeAtt->iAttName = KDependency;
-		exeAtt->iAttValue = *depBegin;
-		if(!iNoCheck)
-		{
-			exeAtt->iAttStatus = status;
-		}
-		else
-		{
-			exeAtt->iAttStatus = KNull;
-		}
-		aExeContainer->iExeAttList.push_back(exeAtt);
-		++depBegin;
-	}
-}
-
-/**
-Function responsible to Get the dependency status for one executable at instant.
-Check for the existence of executable in the Hash table which is created while
-preparing executable list.
-
-@internalComponent
-@released
-
-@param aString - Individual dependency name. (input)
-@param aStatus - Dependency status.(for output)
-*/
-void DepChecker::CollectDependencyStatus(String& aString, String& aStatus) const
-{
-	if(iHashPtr->IsAvailable(aString))
-	{
-		aStatus.assign(KStatusYes);
-		return;
-	}
-	aStatus.assign(KStatusNo);
-}
-
-/**
-Function responsible to display the no rom image warning.
-While checking for dependency if ROM image is not passed and only ROFS is passed then 
-there is a chance that most of the executables dependencies will not be available.
-Hence this warning is raised.
-
-@internalComponent
-@released
-*/
-void DepChecker::RomImagePassed(void) const
-{
-	if(iNoRomImage)
-	{
-		ExceptionReporter(NOROMIMAGE).Report();
-	}
-}
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* DepChecker class is responsible to Validate the dependencies existence and put the  
+* prepared data into Reporter.
+*
+*/
+
+
+/**
+@file
+@internalComponent
+@released
+*/
+
+#include "depchecker.h"
+
+/** 
+Constructor intializes the iHashPtr and iHiddenExeHashPtr members.
+
+@internalComponent
+@released
+
+@param aCmdInput - pointer to a processed CmdLineHandler object
+@param aImageReaderList - List of ImageReader insatance pointers
+*/
+DepChecker::DepChecker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList, bool aNoRomImage) 
+:Checker(aCmdPtr, aImageReaderList), iNoRomImage(aNoRomImage) {
+	iHashPtr = new HashTable(KHashTableSize); 
+	iHiddenExeHashPtr = new HashTable(KHiddenExeHashSize);
+}
+
+/** 
+Destructor deletes the imagereader objects and hash tables.
+
+@internalComponent
+@released
+*/
+DepChecker::~DepChecker() {
+	if(iHiddenExeHashPtr){
+		delete iHiddenExeHashPtr;
+		iHiddenExeHashPtr = 0 ;
+	}
+	if(iHashPtr){
+		delete iHashPtr ;
+		iHashPtr = 0 ;
+	}
+	iAddressVsExeName.clear();
+}
+
+/**
+Fucntion responsible to
+1. Prepare the ROM and ROFS image executable List
+2. Gather Dependencies of all executables present in the ROFS image
+3. Prepare the input data for Reporter
+
+@internalComponent
+@released
+
+@param ImgVsExeStatus - Global integrated container which contains image, exes and attribute value status.
+*/
+void DepChecker::Check(ImgVsExeStatus& aImgVsExeStatus) { 
+	RomImagePassed();  
+	int readerCount = iImageReaderList.size();  
+	
+	for(int i = 0 ; i < readerCount ; i++){ 
+		ImageReader* reader = iImageReaderList.at(i);
+		const char* name = reader->ImageName();
+		PrepareImageExeList(reader); 
+		//Gather dependencies of all the images.
+		ExceptionReporter(GATHERINGDEPENDENCIES, name).Log();
+		ExeNamesVsDepListMap& depMap = iImageReaderList[i]->GatherDependencies();  
+		for(ExeNamesVsDepListMap::iterator it = depMap.begin() ; 
+				it != depMap.end() ; it++) { 
+			StringList& list = it->second;
+			ImgVsExeStatus::iterator pos = aImgVsExeStatus.find(name);
+			ExeVsMetaData* p = 0;
+			if(pos == aImgVsExeStatus.end()){
+				p = new ExeVsMetaData();
+				put_item_to_map(aImgVsExeStatus,name,p);
+			}
+			else
+				p = pos->second ;
+			ExeContainer container ;
+			container.iExeName = it->first ;
+			container.iIdData = KNull;
+			container.iDepList = list ;
+			put_item_to_map(*p,it->first,container);  
+		} 
+	} 
+}
+
+/**
+Function responsible to
+1. Prepare the ExecutableList
+2. Put the received Excutable list into HASH table, this data will be used later 
+to identify the dependencies existense.
+
+@internalComponent
+@released
+
+@param aImageReader - ImageReader instance pointer.
+*/
+void DepChecker::PrepareImageExeList(ImageReader* aImageReader) {
+	 
+	aImageReader->PrepareExecutableList(); 
+	const StringList& aExeList = aImageReader->GetExecutableList(); 
+	iHashPtr->InsertStringList(aExeList); //Put executable names into Hash 
+	/**
+	In ROM if any file is hidden then its entry is not placed in the directory 
+	section of the image during image building time. But still the entry data is 
+	already resolved and ready for xip. So this entry is marked here as Unknown
+	Dependency and its status is Hidden.
+	*/
+	const StringList& hiddenExeList = aImageReader->GetHiddenExeList(); 	 
+	iHiddenExeHashPtr->Insert(KUnknownDependency); //ROm Specific and only once 
+	iHiddenExeHashPtr->InsertStringList(hiddenExeList); 
+	DeleteHiddenExeFromExecutableList(aImageReader, hiddenExeList); 
+	const char* imgName = aImageReader->ImageName();
+	ExceptionReporter(NOOFEXECUTABLES, imgName, aExeList.size()).Log();
+	ExceptionReporter(NOOFHEXECUTABLES, imgName, hiddenExeList.size()).Log();
+}
+
+/**
+Function responsible to delete the hidden executables from iExecutableList.
+In ROFS image, if a file is hidden then its duplicate entry is created to say it is
+hidden. But the other entry is already placed in the executable list and it is 
+available in iHashPtr Hash table. So this needs to be deleted form iHashPtr, then only
+it is possible to get the status "Hidden" for such executables.
+
+@internalComponent
+@released
+
+@param aImageReader - ImageReader instance pointer.
+@param aHiddenExeList - List containing the hidden exe's.
+*/
+void DepChecker::DeleteHiddenExeFromExecutableList(ImageReader* /*aImageReader*/, const StringList& aHiddenExeList) {
+	for(StringList::const_iterator it = aHiddenExeList.begin(); it != aHiddenExeList.end(); it++){
+		iHashPtr->Delete(*it);  
+	}
+}
+
+/**
+Function responsible to prepare the data input for Report Generator.
+Traverses through all the images to identify the executables dependency status.
+
+@internalComponent
+@released
+
+@param aExeContainer - Global integrated container which contains all the attribute, values and the status.
+*/
+void DepChecker::PrepareAndWriteData(ExeContainer& aExeContainer) { 
+	StringList& depList = aExeContainer.iDepList;  
+	for(StringList::iterator it = depList.begin(); it != depList.end(); it++) {
+		string status;
+		const char* str = it->c_str() ;
+		if(!iNoCheck) {			
+			CollectDependencyStatus(str, status);
+			if(status == KStatusNo) { 
+				if(iHiddenExeHashPtr->IsAvailable(str)) { 
+					status.assign(KStatusHidden);
+				}
+			}			 
+			//Include only missing dependencies by default
+			if(!iAllExecutables && (status != KStatusNo)) {
+				continue;
+			}
+		}
+		ExeAttribute* exeAtt = new ExeAttribute();
+		if(exeAtt == KNull) {
+			throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
+		}
+		exeAtt->iAttName.assign(KDependency);
+		exeAtt->iAttValue.assign(str);
+		if(!iNoCheck) {
+			exeAtt->iAttStatus = status;
+		}
+		else {
+			exeAtt->iAttStatus = KNull;
+		}
+		aExeContainer.iExeAttList.push_back(exeAtt); 
+	}
+}
+
+/**
+Function responsible to Get the dependency status for one executable at instant.
+Check for the existence of executable in the Hash table which is created while
+preparing executable list.
+
+@internalComponent
+@released
+
+@param aString - Individual dependency name. (input)
+@param aStatus - Dependency status.(for output)
+*/
+void DepChecker::CollectDependencyStatus(const char* aString, string& aStatus) const {
+	if(iHashPtr->IsAvailable(aString)) 
+		aStatus.assign(KStatusYes);
+	else
+		aStatus.assign(KStatusNo);
+}
+
+/**
+Function responsible to display the no rom image warning.
+While checking for dependency if ROM image is not passed and only ROFS is passed then 
+there is a chance that most of the executables dependencies will not be available.
+Hence this warning is raised.
+
+@internalComponent
+@released
+*/
+void DepChecker::RomImagePassed(void) const {
+	if(iNoRomImage) {
+		ExceptionReporter(NOROMIMAGE).Report();
+	}
+}
--- a/imgtools/imgcheck/src/exceptionimplementation.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/src/exceptionimplementation.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,216 +1,203 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* This class is used to log and/or display the error, warning and status
-* messages. This is a sigleton class.
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "exceptionimplementation.h"
-
-enum MessageArraySize{MAX=42};
-
-/**
-Message objects are created and these objects holds the error, warning and status
-message required by imgcheck tool.
-
-@internalComponent
-@released
-*/
-struct Messages MessageArray[MAX]=
-{
-	{UNKNOWNIMAGETYPE, "Error: Image Type Unknown: '%s'"},
-	{UNKNOWNPREFIX,"Error: Option has Un-Known Prefix: '%s'"},
-	{VALUEEXPECTED,"Error: Value expected for option: '%s'"},
-	{VALUENOTEXPECTED,"Error: Value not expected for option: '%s'"},
-	{UNKNOWNOPTION,"Error: Unknown option: '%s'"},
-	{QUIETMODESELECTED,"Error: Quiet mode selected while not generating XML report"},
-	{NOIMAGE,"Error: No images specified in the input"},
-	{NOROMIMAGE,"Warning: ROM image not passed"},
-	{XMLOPTION,"Warning: XML file name specified while not generating XML report"},
-	{NOMEMORY,"Error:%s:%d: Insuffient program memory"},
-	{FILENAMETOOBIG,"Error:'%s':%d: Improper File Name Size"},
-	{XMLNAMENOTVALID,"Error: Not a valid Xml File name"},
-	{REPORTTYPEINVALID,"Error: Not a valid report type"},
-	{FILEOPENFAIL,"Error:%s:%d: Cannot Open file: '%s'"},
-	{XSLCREATIONFAILED,"Warning:%s:%d: Unable to Create XSL file: '%s'"},
-	{UNEXPECTEDNUMBEROFVALUE, "Error: Unexpected number of values received for option: '%s'"},
-	{INVALIDVIDVALUE, "Error: Invalid VID value: '%s'"},
-	{UNKNOWNSUPPRESSVAL, "Error: Unknown suppress value: '%s'"},
-	{ALLCHECKSSUPPRESSED, "Error: All Validations suppressed"},
-	{SUPPRESSCOMBINEDWITHVIDVAL, "Warning: VID values received but VID validation suppressed"},
-	{SIDALLCOMBINEDWITHSID, "Warning: --sidall option received but SID validation suppressed"},
-	{DATAOVERFLOW, "Overflow: Input value '%s'"},
-	{VALIDIMAGE, "Success: Image(s) are valid"},
-	{IMAGENAMEALREADYRECEIVED, "Warning: Image '%s' passed in multiple times, first one is considered and rest are ignored."},
-	{UNKNOWNDBGVALUE , "Error: Invalid value is passed to --dbg, expected values are TRUE or FALSE."},
-	{ONLYSINGLEDIRECTORYEXPECTED , "Error: Only single directory should be passed as input when E32Input is enabled."},
-	{INVALIDDIRECTORY , "Error: Invalid directory or E32 file received as E32Input."},
-	{INCORRECTVALUES , "Warning: The status reported for Dependency and SID check may not be correct in E32 input mode."},
-	{NOVALIDATIONSENABLED , "Error: No validations are enabled."},
-	{NOEXEPRESENT, "Error: No valid executables are present"},
-	{E32INPUTNOTEXIST, "Error: Invalid E32 input '%s'"},
-	{VALIDE32INPUT, "Success: E32 executable(s) are validated"},
-	// Add the New Error and warning messages above this line
-	{GATHERINGDEPENDENCIES,"Gathering dependencies for '%s'"},
-	{WRITINGINTOREPORTER,"'%s' Checker writing data into Reporter"},
-	{COLLECTDEPDATA,"Collecting dependency data for '%s'"},
-	{NOOFEXECUTABLES,"No of executables in '%s': %d"},
-	{NOOFHEXECUTABLES,"No of hidden executables in '%s': %d"},
-	{READINGIMAGE,"Reading image: '%s'"},
-	{GATHERINGIDDATA,"Gathering %s data for '%s'"},
-	{GENERATINGREPORT,"Generating '%s' Report"},
-	{REPORTGENERATION,"Report generation %s"},
-	//Add the new status informations below this line
-	{NODISKSPACE,"Error: No enough disk space for %s"}
-};
-
-/**
-Static variables used to construct singleton class are initialized
-
-@internalComponent
-@released
-*/
-unsigned int ExceptionImplementation::iCmdFlag = 0;
-ExceptionImplementation* ExceptionImplementation::iInstance = KNull;
-
-/**
-Static function provides the way to get the instance of ExceptionImplementation
-class. It takes aCmdFlag as argument, this argument contains the specified 
-commandline options and this flag is used to display the status information to 
-standard output upon receiving verbose mode flag.
-
-@internalComponent
-@released
-
-@param aCmdFlag - has all the options received in commandline.
-
-@return - returns the instance
-*/
-ExceptionImplementation* ExceptionImplementation::Instance(unsigned int aCmdFlag)
-{
-	if(iInstance == KNull)
-	{
-		iCmdFlag = aCmdFlag;
-		iInstance = new ExceptionImplementation();
-	}
-	return iInstance;
-}
-
-/**
-Static function to delete the instance.
-
-@internalComponent
-@released
-*/
-void ExceptionImplementation::DeleteInstance()
-{
-	DELETE(iInstance);
-}
-
-/**
-Constructor opens the output stream and traverses through MessageArray objects to 
-initialize iMessage map. This map is used later to log the messages.
-
-@internalComponent
-@released
-*/
-ExceptionImplementation::ExceptionImplementation()
-:iMsgIndex(0)
-{
-	iLogStream.open(gLogFileName.c_str(),Ios::out);
-	int i;
-	for(i = 0; i < MAX; i++)
-	{
-		iMessage.insert(std::make_pair(MessageArray[i].iIndex,MessageArray[i].iMessage));
-	}
-}
-
-/**
-Destructor closes the output stream opened during construction.
-
-@internalComponent
-@released
-*/
-ExceptionImplementation::~ExceptionImplementation()
-{
-	iLogStream.close();
-}
-
-/**
-Function returns the message equivalent to the recived enum value.
-
-@internalComponent
-@released
-
-@param aMsgIndex - enum value
-*/
-String& ExceptionImplementation::Message(const int aMsgIndex)
-{
-	iMsgIndex = aMsgIndex;
-	return iMessage[aMsgIndex];
-}
-
-/**
-Function to log the error, warning and status information.
-Irrespective of the messgae type all the messages are logged into the imgcheck 
-logfile. The warning and error messages are needed to be displayed on the command
-prompt always. But the status information is displayed at standard output only if
-the verbose mode is selected by the user.
-
-@internalComponent
-@released
-
-@param aMsgIndex - enum value
-*/
-void ExceptionImplementation::Log(const String aMsg)
-{
-	iLogStream <<  aMsg.c_str() << "\n";
-    
-	if(iCmdFlag & KVerbose)
-	{
-		cout << aMsg.c_str() << endl;
-	}
-}
-
-/**
-Function to report the error and warning information.
-Irrespective of the messgae type all the messages are logged into the imgcheck 
-logfile. The warning and error messages are needed to be displayed on the command
-prompt always. 
-
-@internalComponent
-@released
-
-@param aMsgIndex - enum value
-*/
-void ExceptionImplementation::Report(const String aMsg)
-{
-	iLogStream <<  aMsg.c_str() << "\n";
-	if(aMsg.find("Success") != String::npos)
-	{
-		cout << aMsg.c_str() << endl;
-	}
-	else
-	{
-		cerr << aMsg.c_str() << endl;
-	}
-}
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* This class is used to log and/or display the error, warning and status
+* messages. This is a sigleton class.
+*
+*/
+
+
+/**
+@file
+@internalComponent
+@released
+*/
+
+#include "exceptionimplementation.h"
+
+enum MessageArraySize{MAX=42};
+
+/**
+Message objects are created and these objects holds the error, warning and status
+message required by imgcheck tool.
+
+@internalComponent
+@released
+*/
+struct Messages MessageArray[MAX]= {
+	{UNKNOWNIMAGETYPE, "Error: Image Type Unknown: '%s'"},
+	{UNKNOWNPREFIX,"Error: Option has Un-Known Prefix: '%s'"},
+	{VALUEEXPECTED,"Error: Value expected for option: '%s'"},
+	{VALUENOTEXPECTED,"Error: Value not expected for option: '%s'"},
+	{UNKNOWNOPTION,"Error: Unknown option: '%s'"},
+	{QUIETMODESELECTED,"Error: Quiet mode selected while not generating XML report"},
+	{NOIMAGE,"Error: No images specified in the input"},
+	{NOROMIMAGE,"Warning: ROM image not passed"},
+	{XMLOPTION,"Warning: XML file name specified while not generating XML report"},
+	{NOMEMORY,"Error:%s:%d: Insuffient program memory"},
+	{FILENAMETOOBIG,"Error:'%s':%d: Improper File Name Size"},
+	{XMLNAMENOTVALID,"Error: Not a valid Xml File name"},
+	{REPORTTYPEINVALID,"Error: Not a valid report type"},
+	{FILEOPENFAIL,"Error:%s:%d: Cannot Open file: '%s'"},
+	{XSLCREATIONFAILED,"Warning:%s:%d: Unable to Create XSL file: '%s'"},
+	{UNEXPECTEDNUMBEROFVALUE, "Error: Unexpected number of values received for option: '%s'"},
+	{INVALIDVIDVALUE, "Error: Invalid VID value: '%s'"},
+	{UNKNOWNSUPPRESSVAL, "Error: Unknown suppress value: '%s'"},
+	{ALLCHECKSSUPPRESSED, "Error: All Validations suppressed"},
+	{SUPPRESSCOMBINEDWITHVIDVAL, "Warning: VID values received but VID validation suppressed"},
+	{SIDALLCOMBINEDWITHSID, "Warning: --sidall option received but SID validation suppressed"},
+	{DATAOVERFLOW, "Overflow: Input value '%s'"},
+	{VALIDIMAGE, "Success: Image(s) are valid"},
+	{IMAGENAMEALREADYRECEIVED, "Warning: Image '%s' passed in multiple times, first one is considered and rest are ignored."},
+	{UNKNOWNDBGVALUE , "Error: Invalid value is passed to --dbg, expected values are TRUE or FALSE."},
+	{ONLYSINGLEDIRECTORYEXPECTED , "Error: Only single directory should be passed as input when E32Input is enabled."},
+	{INVALIDDIRECTORY , "Error: Invalid directory or E32 file received as E32Input."},
+	{INCORRECTVALUES , "Warning: The status reported for Dependency and SID check may not be correct in E32 input mode."},
+	{NOVALIDATIONSENABLED , "Error: No validations are enabled."},
+	{NOEXEPRESENT, "Error: No valid executables are present"},
+	{E32INPUTNOTEXIST, "Error: Invalid E32 input '%s'"},
+	{VALIDE32INPUT, "Success: E32 executable(s) are validated"},
+	// Add the New Error and warning messages above this line
+	{GATHERINGDEPENDENCIES,"Gathering dependencies for '%s'"},
+	{WRITINGINTOREPORTER,"'%s' Checker writing data into Reporter"},
+	{COLLECTDEPDATA,"Collecting dependency data for '%s'"},
+	{NOOFEXECUTABLES,"No of executables in '%s': %d"},
+	{NOOFHEXECUTABLES,"No of hidden executables in '%s': %d"},
+	{READINGIMAGE,"Reading image: '%s'"},
+	{GATHERINGIDDATA,"Gathering %s data for '%s'"},
+	{GENERATINGREPORT,"Generating '%s' Report"},
+	{REPORTGENERATION,"Report generation %s"},
+	//Add the new status informations below this line
+	{NODISKSPACE,"Error: No enough disk space for %s"}
+};
+
+/**
+Static variables used to construct singleton class are initialized
+
+@internalComponent
+@released
+*/
+unsigned int ExceptionImplementation::iCmdFlag = 0;
+ExceptionImplementation* ExceptionImplementation::iInstance = KNull;
+
+/**
+Static function provides the way to get the instance of ExceptionImplementation
+class. It takes aCmdFlag as argument, this argument contains the specified 
+commandline options and this flag is used to display the status information to 
+standard output upon receiving verbose mode flag.
+
+@internalComponent
+@released
+
+@param aCmdFlag - has all the options received in commandline.
+
+@return - returns the instance
+*/
+ExceptionImplementation* ExceptionImplementation::Instance(unsigned int aCmdFlag) {
+	if(iInstance == KNull) {
+		iCmdFlag = aCmdFlag;
+		iInstance = new ExceptionImplementation();
+	}
+	return iInstance;
+}
+
+/**
+Static function to delete the instance.
+
+@internalComponent
+@released
+*/
+void ExceptionImplementation::DeleteInstance() {
+	DELETE(iInstance);
+}
+
+/**
+Constructor opens the output stream and traverses through MessageArray objects to 
+initialize iMessage map. This map is used later to log the messages.
+
+@internalComponent
+@released
+*/
+ExceptionImplementation::ExceptionImplementation()
+:iMsgIndex(0) {
+	iLogStream.open(gLogFileName.c_str(),ios_base::out);
+	int i;
+	for(i = 0; i < MAX; i++) {
+		iMessage.insert(make_pair(MessageArray[i].iIndex,MessageArray[i].iMessage));
+	}
+}
+
+/**
+Destructor closes the output stream opened during construction.
+
+@internalComponent
+@released
+*/
+ExceptionImplementation::~ExceptionImplementation() {
+	iLogStream.close();
+}
+
+/**
+Function returns the message equivalent to the recived enum value.
+
+@internalComponent
+@released
+
+@param aMsgIndex - enum value
+*/
+string& ExceptionImplementation::Message(const int aMsgIndex) {
+	iMsgIndex = aMsgIndex;
+	return iMessage[aMsgIndex];
+}
+
+/**
+Function to log the error, warning and status information.
+Irrespective of the messgae type all the messages are logged into the imgcheck 
+logfile. The warning and error messages are needed to be displayed on the command
+prompt always. But the status information is displayed at standard output only if
+the verbose mode is selected by the user.
+
+@internalComponent
+@released
+
+@param aMsgIndex - enum value
+*/
+void ExceptionImplementation::Log(const string aMsg) {
+	iLogStream <<  aMsg.c_str() << "\n";
+
+	if(iCmdFlag & KVerbose) {
+		cout << aMsg.c_str() << endl;
+	}
+}
+
+/**
+Function to report the error and warning information.
+Irrespective of the messgae type all the messages are logged into the imgcheck 
+logfile. The warning and error messages are needed to be displayed on the command
+prompt always. 
+
+@internalComponent
+@released
+
+@param aMsgIndex - enum value
+*/
+void ExceptionImplementation::Report(const string aMsg) {
+	iLogStream <<  aMsg.c_str() << "\n";
+	if(aMsg.find("Success") != string::npos) {
+		cout << aMsg.c_str() << endl;
+	}
+	else {
+		cerr << aMsg.c_str() << endl;
+	}
+}
--- a/imgtools/imgcheck/src/exceptionreporter.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/src/exceptionreporter.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,122 +1,105 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* This class is used to receive the enum index of the original 
-* message with some more variable arguments. These variable 
-* arguments are split and put into the original message.
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "exceptionreporter.h"
-#include "utils.h"
-
-/** 
-Constructor receives the variable arguements and gets the instance 
-of MessageImplementation class. Invokes GetMessage to get the 
-original message. Find %d and %s inside the original message and
-replace these specifiers with the received variable argument value.
-
-@internalComponent
-@released
-
-@param aMsgIndex - an enum index to get original message from 
-MessageImplementation class
-@param ... - variable arguments.
-*/
-ExceptionReporter::ExceptionReporter(int aMsgIndex, ...)
-{
-	iExcepImplPtr = ExceptionImplementation::Instance(0);
-	iMessage = iExcepImplPtr->Message(aMsgIndex);
-	int fileNameIndex = 0;
-	if(iMessage.length() > 0)
-	{
-		va_list argList;
-		va_start(argList,aMsgIndex);
-		
-		int intVal;
-		String strVal;
-		
-		unsigned int index = iMessage.find("%");
-		String subStr = iMessage.substr(index + 1);//skip '%'
-		while( index != String::npos )
-		{
-			switch(iMessage.at(index + 1)) 
-			{
-				case 'd':
-					intVal = va_arg(argList, int);
-					iMessage.erase(index, 2);//delete two characters "%d"
-					iMessage.insert(index, ReaderUtil::IntToAscii(intVal, EBase10));
-					break;
-				case 's':
-					strVal.assign(va_arg(argList, char*));
-					#ifdef __TOOLS2__
-					fileNameIndex = strVal.find_last_of('\\');
-					++fileNameIndex;
-					#endif 
-					#ifdef __LINUX__
-					fileNameIndex = strVal.find_last_of('/'); //Remove the 
-					++fileNameIndex;
-					#endif
-					strVal = (index != String::npos)? strVal.substr(fileNameIndex) : strVal;
-					iMessage.erase(index, 2); //delete two characters "%s"
-					iMessage.insert(index, strVal);
-					break;
-			}
-			index = iMessage.find("%");
-		}
-	}
-}
-
-
-/** 
-Destructor. 
-
-@internalComponent
-@released
-*/
-ExceptionReporter::~ExceptionReporter()
-{
-}
-
-
-/**
-Invokes the Log function of ExceptionImplementation, which puts the 
-data into logfile directly and takes decision whether to put the same 
-on standard output or not.
-
-@internalComponent
-@released
-*/
-void ExceptionReporter::Log(void) const
-{
-	iExcepImplPtr->Log(iMessage);
-}
-
-/**
-Invokes the Report function of ExceptionImplementation to report error or warning.
-
-@internalComponent
-@released
-*/
-void ExceptionReporter::Report(void) const
-{
-	iExcepImplPtr->Report(iMessage);
-}
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* This class is used to receive the enum index of the original 
+* message with some more variable arguments. These variable 
+* arguments are split and put into the original message.
+*
+*/
+
+
+/**
+ @file
+ @internalComponent
+ @released
+*/
+
+#include "exceptionreporter.h"
+#include "utils.h"
+#include "h_utl.h"
+/** 
+Constructor receives the variable arguements and gets the instance 
+of MessageImplementation class. Invokes GetMessage to get the 
+original message. Find %d and %s inside the original message and
+replace these specifiers with the received variable argument value.
+
+@internalComponent
+@released
+
+@param aMsgIndex - an enum index to get original message from 
+MessageImplementation class
+@param ... - variable arguments.
+*/
+ExceptionReporter::ExceptionReporter(int aMsgIndex, ...) {
+	iExcepImplPtr = ExceptionImplementation::Instance(0);
+	iMessage = iExcepImplPtr->Message(aMsgIndex); 
+	if(iMessage.length() > 0) {
+		va_list argList;
+		va_start(argList,aMsgIndex);
+		
+		int intVal;
+		string strVal;
+		
+		unsigned int index = iMessage.find("%");
+		string subStr = iMessage.substr(index + 1);//skip '%'
+		while( index != string::npos ) {
+			switch(iMessage.at(index + 1))  {
+				case 'd':
+					intVal = va_arg(argList, int);
+					iMessage.erase(index, 2);//delete two characters "%d"
+					iMessage.insert(index, ReaderUtil::IntToAscii(intVal, EBase10));
+					break;
+				case 's':
+					strVal.assign(va_arg(argList, char*));		 
+					iMessage.erase(index, 2); //delete two characters "%s"
+					iMessage.insert(index, strVal);
+					break;
+			}
+			index = iMessage.find("%");
+		}
+	}
+}
+
+
+/** 
+Destructor. 
+
+@internalComponent
+@released
+*/
+ExceptionReporter::~ExceptionReporter() {
+}
+
+
+/**
+Invokes the Log function of ExceptionImplementation, which puts the 
+data into logfile directly and takes decision whether to put the same 
+on standard output or not.
+
+@internalComponent
+@released
+*/
+void ExceptionReporter::Log(void) const {
+	iExcepImplPtr->Log(iMessage);
+}
+
+/**
+Invokes the Report function of ExceptionImplementation to report error or warning.
+
+@internalComponent
+@released
+*/
+void ExceptionReporter::Report(void) const {
+	iExcepImplPtr->Report(iMessage);
+}
--- a/imgtools/imgcheck/src/hash.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/src/hash.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,177 +1,151 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Hash class for imgcheck tool. All the executable names of ROM/ROFS 
-* are stored into this hash table. After gathering the dependencies
-* for those executables, dependencies existence is checked very 
-* efficiently using this table.
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "common.h"
-#include "hash.h"
-
-/** 
-Constructor, intializes the table size
-
-@internalComponent
-@released
-
-@param aSize - Hash table size (Number of dissimilar data can stored)
-*/
-HashTable::HashTable(int aSize)
-:iSize(aSize)
-{
-}
-
-/** 
-Destructor
-
-@internalComponent
-@released
-*/
-HashTable::~HashTable()
-{
-}
-
-/** 
-Function responsible to return the Hash value for the received string.
-
-@internalComponent
-@released
-
-@param aString - String on which Hash value calcualtion to be done
-*/
-int HashTable::Hash(String aString)
-{
-	unsigned int hashVal = 0;
-	int length = aString.length();
-	/* we start our hash out at 0 */
-
-	/* for each character, we multiply the old hash by 31 and add the current
-	 * character.  Remember that shifting a number left is equivalent to 
-	 * multiplying it by 2 raised to the number of places shifted.  So we 
-	 * are in effect multiplying hashval by 32 and then subtracting hashval.  
-	 * Why do we do this?  Because shifting and subtraction are much more 
-	 * efficient operations than multiplication.
-	 */
-	for(int strIter = 0; strIter < length ; strIter++)
-	{
-		hashVal = aString[strIter] + (hashVal << 5) - hashVal;
-	}
-	/* we then return the hash value mod the hashtable size so that it will
-	 * fit into the necessary range
-	 */
-	return hashVal % iSize;
-
-}
-
-/** 
-Function returns ture or false based on the String availability in Hash
-
-@internalComponent
-@released
-
-@param aString - String which needs to be searched
-*/
-bool HashTable::IsAvailable(String aString)
-{
-	unsigned int hashVal = Hash(aString);
-	if (iTable[hashVal].size() > 0)
-	{
-		StringList nameList = iTable[hashVal];
-		StringList::iterator listIter = nameList.begin();
-		while(listIter != nameList.end())
-		{
-			if ((*listIter) == aString)
-			{
-				return true;
-			}
-			++listIter;
-		}
-	}
-	return false;
-}
-
-/** 
-Function responsible to insert a single string into Hash table
-
-@internalComponent
-@released
-
-@param aString - String which needs to be inserted
-*/
-void HashTable::Insert(String aString)
-{
-	unsigned int hashVal = Hash(aString);
-	if(!IsAvailable(aString)) //Is exists
-	{
-		iTable[hashVal].push_back(aString);
-	}
-}
-
-/** 
-Function responsible to insert list of strings into Hash table
-
-@internalComponent
-@released
-
-@param aString - String which needs to be inserted
-*/
-void HashTable::InsertStringList(StringList& aList)
-{
-	StringList::iterator beginIter = aList.begin();
-	StringList::iterator endIter = aList.end();
-	while(beginIter != endIter)
-	{
-		Insert((*beginIter));
-		++beginIter;
-	}
-}
-
-/** 
-Function to delete an entry from Hash
-
-@internalComponent
-@released
-
-@param aString - String which needs to be deleted
-*/
-void HashTable::Delete(String aString)
-{
-	unsigned int hashVal = Hash(aString);
-	if(iTable[hashVal].size() > 0)
-	{
-		StringList list = iTable[hashVal];
-		StringList::iterator beginIter = list.begin();
-		StringList::iterator endIter = list.end();
-		while(beginIter != endIter)
-		{
-			if((*beginIter) == aString)
-			{
-				list.erase(beginIter);
-				iTable[hashVal] = list;
-				return;
-			}
-			++beginIter;
-		}
-	}
-}
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Hash class for imgcheck tool. All the executable names of ROM/ROFS 
+* are stored into this hash table. After gathering the dependencies
+* for those executables, dependencies existence is checked very 
+* efficiently using this table.
+*
+*/
+
+
+/**
+ @file
+ @internalComponent
+ @released
+*/
+
+#include "common.h"
+#include "hash.h"
+/** 
+Constructor, intializes the table size
+
+@internalComponent
+@released
+
+@param aSize - Hash table size (Number of dissimilar data can stored)
+*/
+HashTable::HashTable(int aSize)
+:iSize(aSize) {
+}
+
+/** 
+Destructor
+
+@internalComponent
+@released
+*/
+HashTable::~HashTable() {
+}
+
+/** 
+Function responsible to return the Hash value for the received string.
+
+@internalComponent
+@released
+
+@param aString - const string& on which Hash value calcualtion to be done
+*/
+int HashTable::Hash(const string& aString) {
+	unsigned int hashVal = 0;
+	int length = aString.length() ;
+	/* we start our hash out at 0 */
+
+	/* for each character, we multiply the old hash by 31 and add the current
+	 * character.  Remember that shifting a number left is equivalent to 
+	 * multiplying it by 2 raised to the number of places shifted.  So we 
+	 * are in effect multiplying hashval by 32 and then subtracting hashval.  
+	 * Why do we do this?  Because shifting and subtraction are much more 
+	 * efficient operations than multiplication.
+	 */
+	for(int strIter = 0; strIter < length ; strIter++) {
+		hashVal = aString[strIter] + (hashVal << 5) - hashVal;
+	}
+	/* we then return the hash value mod the hashtable size so that it will
+	 * fit into the necessary range
+	 */
+	return hashVal % iSize;
+
+}
+
+/** 
+Function returns ture or false based on the string availability in Hash
+
+@internalComponent
+@released
+
+@param aString - const char* which needs to be searched
+*/
+bool HashTable::IsAvailable(const string& aString) { 
+	unsigned int hashVal = Hash(aString);
+	if (iTable.count(hashVal) > 0) {
+		pair<Table::iterator,Table::iterator> range = iTable.equal_range(hashVal);
+		for(Table::iterator it = range.first; it != range.second ; it++) {				 
+			if(aString == it->second ) {
+				return true;
+			}			 
+		}
+	}	
+	return false;
+}
+
+/** 
+Function responsible to insert a single string into Hash table
+
+@internalComponent
+@released
+
+@param aString - const char* which needs to be inserted
+*/
+void HashTable::Insert(const string& aString) {
+	unsigned int hashVal = Hash(aString);
+	if(!IsAvailable(aString))  {
+		iTable.insert(pair<unsigned int,string>(hashVal,aString));
+	}
+}
+
+/** 
+Function responsible to insert list of StringList into Hash table
+
+@internalComponent
+@released
+
+@param aString - string which needs to be inserted
+*/
+void HashTable::InsertStringList(const StringList& aList) { 
+	for(StringList::const_iterator it = aList.begin(); it != aList.end(); it++ ) {
+		Insert(*it); 
+	}
+}
+
+/** 
+Function to delete an entry from Hash
+
+@internalComponent
+@released
+
+@param aString - const char* which needs to be deleted
+*/
+void HashTable::Delete(const string& aString) {
+	unsigned int hashVal = Hash(aString);
+	if (iTable.count(hashVal) > 0) {
+		pair<Table::iterator,Table::iterator> range = iTable.equal_range(hashVal);
+		for(Table::iterator it = range.first; it != range.second ; it++) {			 
+			if(aString == it->second ) {
+				iTable.erase(it); 
+				return ;
+			}			 
+		}
+	}
+}
--- a/imgtools/imgcheck/src/imgcheckmanager.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/src/imgcheckmanager.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,305 +1,275 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* ImgCheckManager controller class Controls the instantiation and 
-* operations of ImageReader, Checker, Reporter and ReportWriter.
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "imgcheckmanager.h"
-#include "romreader.h"
-#include "rofsreader.h"
-#include "dirreader.h"
-#include "depchecker.h"
-#include "sidchecker.h"
-#include "vidchecker.h"
-#include "dbgflagchecker.h"
-
-/**
-Constructor initializes command line handler pointer.
-Which can be used by any tool which is derived from this class.
-
-@internalComponent
-@released
-
-@param aCmdPtr - command line handler pointer
-*/
-ImgCheckManager::ImgCheckManager(CmdLineHandler* aCmdPtr)
-:iCmdLine(aCmdPtr)
-{
-	iReporter = Reporter::Instance(iCmdLine->ReportFlag());
-	iNoRomImage = true; 
-}
-
-/**
-Destructor traverses through the imagereader list and delets the same
-
-@internalComponent
-@released
-*/
-ImgCheckManager::~ImgCheckManager()
-{
-	while(iImageReaderList.size() > 0)
-	{
-		DELETE(iImageReaderList.back());
-		iImageReaderList.pop_back();
-	}
-	while(iCheckerList.size() > 0)
-	{
-		DELETE(iCheckerList.back());
-		iCheckerList.pop_back();
-	}
-	while(iWriterList.size() > 0)
-	{
-		DELETE(iWriterList.back())
-		iWriterList.pop_back();
-	}
-	Reporter::DeleteInstance();
-	iCmdLine = 0;
-}
-
-/**
-Function responsible to read the header and directory section.
-
-@internalComponent
-@released
-
-@param aImageName - image name
-@param aImageType - image type
-*/
-void ImgCheckManager::Process(ImageReader* aImageReader)
-{
-	ExceptionReporter(READINGIMAGE,(char*)aImageReader->ImageName().c_str()).Log();
-	aImageReader->ReadImage();
-	aImageReader->ProcessImage();
-	if(!aImageReader->ExecutableAvailable())
-	{
-		throw ExceptionReporter(NOEXEPRESENT);
-	}
-}
-
-/**
-Function responsible to 
-1. get the image names one by one. 
-2. Identify the image type and Create respective Reader objects.
-3. Identify the required validations and create respective Instances.
-4. Identify the required Writers and create respective instances.
-
-@internalComponent
-@released
-*/
-void ImgCheckManager::CreateObjects(void)
-{
-	unsigned int imgCnt = iCmdLine->NoOfImages();
-	String imgName;
-	
-	while(imgCnt > 0)
-	{	
-		imgName = iCmdLine->NextImageName();
-		--imgCnt;
-		HandleImage(imgName);
-	}
-
-	Checker* checkerPtr = KNull;
-	unsigned int checks = iCmdLine->EnabledValidations();
-	unsigned short int bitPos = 1;
-	while(bitPos)
-	{
-		if(bitPos & checks)
-		{
-			switch(bitPos)
-			{
-			case EDep:
-				checkerPtr = new DepChecker(iCmdLine, iImageReaderList,iNoRomImage);
-				break;
-			case ESid:
-				checkerPtr = new SidChecker(iCmdLine, iImageReaderList);
-				break;
-			case EVid:
-				checkerPtr = new VidChecker(iCmdLine, iImageReaderList);
-				break;
-			case EDbg:
-				checkerPtr = new DbgFlagChecker(iCmdLine, iImageReaderList);
-				break;
-			}
-			if(checkerPtr == KNull)
-			{
-				throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
-			}
-			iCheckerList.push_back(checkerPtr);
-		}
-		bitPos <<= 1; //Shift one bit left
-	}
-
-	unsigned int rptFlag = iCmdLine->ReportFlag();
-	ReportWriter* rptWriter = KNull;
-	if(!( rptFlag & QuietMode))
-	{
-		rptWriter = new CmdLineWriter(rptFlag);
-		InsertWriter(rptWriter);
-	}
-	if(iCmdLine->ReportFlag() & KXmlReport)
-	{
-		rptWriter = new XmlWriter(iCmdLine->XmlReportName(), iCmdLine->Command());
-		InsertWriter(rptWriter);
-	}
-}
-
-/**
-Function responsible to insert the ReprtWriter into iWriterList
-
-@internalComponent
-@released
-*/
-void ImgCheckManager::InsertWriter(ReportWriter* aWriter)
-{
-	if(aWriter == KNull)
-	{
-		throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
-	}
-	iWriterList.push_back(aWriter);
-}
-
-/**
-Function responsible to initiate the enabled validations
-
-@internalComponent
-@released
-*/
-void ImgCheckManager::Execute(void)
-{
-	unsigned int cnt = 0;
-	ImgVsExeStatus& imgVsExeStatus = iReporter->GetContainerReference();
-	while(cnt < iCheckerList.size())
-	{
-		iCheckerList[cnt++]->Check(imgVsExeStatus);
-	}
-}
-
-/**
-Function responsible to write the validated data into Reporter.
-
-@internalComponent
-@released
-*/
-void ImgCheckManager::FillReporterData(void)
-{
-	
-	ImgVsExeStatus& imgVsExeStatus = iReporter->GetContainerReference();
-	ImgVsExeStatus::iterator imgBegin = imgVsExeStatus.begin();
-	ImgVsExeStatus::iterator imgEnd = imgVsExeStatus.end();
-	
-	ExeVsMetaData::iterator exeBegin;
-	ExeVsMetaData::iterator exeEnd;
-
-
-	while(imgBegin != imgEnd)
-	{
-		ExeVsMetaData& exeVsMetaData = imgBegin->second;
-		exeBegin = exeVsMetaData.begin();
-		exeEnd = exeVsMetaData.end();
-		while(exeBegin != exeEnd)
-		{
-			ExeContainer& exeContainer = (*exeBegin).second;
-
-			unsigned int cnt = 0;
-			while(cnt < iCheckerList.size())
-			{
-				iCheckerList[cnt++]->PrepareAndWriteData(&exeContainer);
-			}
-			++exeBegin;
-		}
-		++imgBegin;
-	}
-}
-
-/**
-Function responsible to start report generation. This function invokes the Reporter's
-CreateReport function by passing iWriterList as argument.
-
-@internalComponent
-@released
-
-@return - returns the return value of Reporter::CreateReport function.
-*/
-void ImgCheckManager::GenerateReport(void)
-{
-	iReporter->CreateReport(iWriterList);
-}
-
-/** 
-Function to identify the image type and read the header and file and/or directory entries.
-
-@internalComponent
-@released
-
-@param aImageName - image name received as part of command line
-@param EImageType - type of the input image
-*/
-void ImgCheckManager::HandleImage(const String& aImageName, EImageType aImageType)
-{
-	unsigned int rptFlag = iCmdLine->ReportFlag();
-	if(rptFlag & KE32Input)
-	{
-		aImageType = DirReader::EntryType((char*)aImageName.c_str());
-	}
-	else if(aImageType == EUnknownImage)
-	{
-		aImageType = ImageReader::ReadImageType(aImageName);
-	}
-	ImageReader* imgReader = KNull;
-
-	switch(aImageType)
-	{
-	case ERomImage:
-		iNoRomImage = false;
-	case ERomExImage:
-		imgReader = new RomReader((char*)aImageName.c_str(), aImageType);
-		break;
-
-	case ERofsImage:
-	case ERofsExImage:
-		imgReader = new RofsReader((char*)aImageName.c_str(), aImageType);
-		break;
-
-	case EE32Directoy:
-		imgReader = new DirReader((char*)aImageName.c_str());
-		break;
-	
-	case EE32File:
-		imgReader = new E32Reader((char*)aImageName.c_str());
-		break;
-
-	case EUnknownImage:
-		throw ExceptionReporter(UNKNOWNIMAGETYPE, (char*)aImageName.c_str());
-		break;
-
-	case EE32InputNotExist:
-		throw ExceptionReporter(E32INPUTNOTEXIST, (char*)aImageName.c_str());
-		break;
-	}
-	if(imgReader == KNull)
-	{
-		throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
-	}
-	Process(imgReader);
-	iImageReaderList.push_back(imgReader);
-}
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* ImgCheckManager controller class Controls the instantiation and 
+* operations of ImageReader, Checker, Reporter and ReportWriter.
+*
+*/
+
+
+/**
+ @file
+ @internalComponent
+ @released
+*/
+
+#include "imgcheckmanager.h"
+#include "romreader.h"
+#include "rofsreader.h"
+#include "dirreader.h"
+#include "depchecker.h"
+#include "sidchecker.h"
+#include "vidchecker.h"
+#include "dbgflagchecker.h"
+
+/**
+Constructor initializes command line handler pointer.
+Which can be used by any tool which is derived from this class.
+
+@internalComponent
+@released
+
+@param aCmdPtr - command line handler pointer
+*/
+ImgCheckManager::ImgCheckManager(CmdLineHandler* aCmdPtr)
+:iCmdLine(aCmdPtr) {
+	iReporter = Reporter::Instance(iCmdLine->ReportFlag());
+	iNoRomImage = true; 
+}
+
+/**
+Destructor traverses through the imagereader list and delets the same
+
+@internalComponent
+@released
+*/
+ImgCheckManager::~ImgCheckManager() {
+	int i ;	 
+	for(i = iImageReaderList.size() - 1 ; i >= 0 ; i--) {		
+		ImageReader* reader = iImageReaderList.at(i); 
+		if(NULL != reader)
+			delete reader ;
+	}
+	iImageReaderList.clear(); 
+	for(i = iCheckerList.size() - 1 ; i >= 0 ; i--) { 
+		Checker* checker = iCheckerList.at(i); 
+		if(NULL != checker)
+			delete checker ;
+	}
+	iCheckerList.clear(); 
+	for(i = iWriterList.size() - 1 ; i >= 0 ; i--) { 
+		ReportWriter* writer = iWriterList.at(i); 
+		if(NULL != writer)
+			delete writer ;
+	}
+	iWriterList.clear();  
+	Reporter::DeleteInstance();
+	iCmdLine = 0;
+}
+
+/**
+Function responsible to read the header and directory section.
+
+@internalComponent
+@released
+
+@param aImageName - image name
+@param aImageType - image type
+*/
+void ImgCheckManager::Process(ImageReader* aImageReader) {
+	ExceptionReporter(READINGIMAGE,aImageReader->ImageName()).Log();
+	aImageReader->ReadImage();
+	aImageReader->ProcessImage();
+	if(!aImageReader->ExecutableAvailable()) {
+		throw ExceptionReporter(NOEXEPRESENT);
+	}
+}
+
+/**
+Function responsible to 
+1. get the image names one by one. 
+2. Identify the image type and Create respective Reader objects.
+3. Identify the required validations and create respective Instances.
+4. Identify the required Writers and create respective instances.
+
+@internalComponent
+@released
+*/
+void ImgCheckManager::CreateObjects(void) { 
+
+	const char* imgName = iCmdLine->NextImageName();	
+	while(imgName) {		 
+		HandleImage(imgName);
+		imgName = iCmdLine->NextImageName();
+	}
+
+	Checker* checkerPtr = KNull;
+	unsigned int checks = iCmdLine->EnabledValidations();
+	unsigned short int bitPos = 1;
+	while(bitPos) {
+		if(bitPos & checks) {
+			switch(bitPos) {
+			case EDep:
+				checkerPtr = new DepChecker(iCmdLine, iImageReaderList,iNoRomImage);
+				break;
+			case ESid:
+				checkerPtr = new SidChecker(iCmdLine, iImageReaderList);
+				break;
+			case EVid:
+				checkerPtr = new VidChecker(iCmdLine, iImageReaderList);
+				break;
+			case EDbg:
+				checkerPtr = new DbgFlagChecker(iCmdLine, iImageReaderList);
+				break;
+			}
+			if(checkerPtr == KNull) {
+				throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
+			}
+			iCheckerList.push_back(checkerPtr);
+		}
+		bitPos <<= 1; //Shift one bit left
+	}
+
+	unsigned int rptFlag = iCmdLine->ReportFlag();
+	ReportWriter* rptWriter = KNull;
+	if(!( rptFlag & QuietMode)) {
+		rptWriter = new CmdLineWriter(rptFlag);
+		InsertWriter(rptWriter);
+	}
+	
+	if(iCmdLine->ReportFlag() & KXmlReport) { 
+		rptWriter = new XmlWriter(iCmdLine->XmlReportName(), iCmdLine->Command());
+		if(!rptWriter){
+			cerr << "Failed at file :"<< iCmdLine->XmlReportName() <<" With args "<< iCmdLine->Command()<< endl;
+			throw ExceptionReporter(FILEOPENFAIL, __FILE__, __LINE__);
+		}
+		InsertWriter(rptWriter);		
+	}
+}
+
+/**
+Function responsible to insert the ReprtWriter into iWriterList
+
+@internalComponent
+@released
+*/
+void ImgCheckManager::InsertWriter(ReportWriter* aWriter) {
+	if(aWriter == KNull) {
+		throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
+	}
+	iWriterList.push_back(aWriter);
+}
+
+/**
+Function responsible to initiate the enabled validations
+
+@internalComponent
+@released
+*/
+void ImgCheckManager::Execute(void) {	
+	ImgVsExeStatus& imgVsExeStatus = iReporter->GetContainerReference();
+	unsigned int cnt = 0;
+	while(cnt < iCheckerList.size()) {		
+		iCheckerList[cnt++]->Check(imgVsExeStatus);
+	}
+}
+
+/**
+Function responsible to write the validated data into Reporter.
+
+@internalComponent
+@released
+*/
+void ImgCheckManager::FillReporterData(void) {	
+	ImgVsExeStatus& imgVsExeStatus = iReporter->GetContainerReference(); 	
+	for(ImgVsExeStatus::iterator it = imgVsExeStatus.begin();
+		it != imgVsExeStatus.end(); it++) {
+		ExeVsMetaData* exeVsMetaData = it->second;
+		
+		for(ExeVsMetaData::iterator i = exeVsMetaData->begin();
+			i != exeVsMetaData->end() ; i++ ) {  
+			for(unsigned int cnt = 0 ; cnt < iCheckerList.size() ; cnt++) {
+				iCheckerList[cnt]->PrepareAndWriteData(i->second);
+			} 
+		} 
+	}
+}
+
+/**
+Function responsible to start report generation. This function invokes the Reporter's
+CreateReport function by passing iWriterList as argument.
+
+@internalComponent
+@released
+
+@return - returns the return value of Reporter::CreateReport function.
+*/
+void ImgCheckManager::GenerateReport(void) {
+	iReporter->CreateReport(iWriterList); 
+}
+
+/** 
+Function to identify the image type and read the header and file and/or directory entries.
+
+@internalComponent
+@released
+
+@param aImageName - image name received as part of command line
+@param EImageType - type of the input image
+*/
+void ImgCheckManager::HandleImage(const char* aImageName, EImageType aImageType) {
+	unsigned int rptFlag = iCmdLine->ReportFlag();
+	string name(aImageName);
+	if(rptFlag & KE32Input) {
+		aImageType = DirReader::EntryType(name);
+	}
+	else if(aImageType == EUnknownImage) {
+		aImageType = ImageReader::ReadImageType(name);
+	}
+	ImageReader* imgReader = KNull;
+	
+	switch(aImageType) {
+	case ERomImage:
+		iNoRomImage = false;
+	case ERomExImage:
+		imgReader = new RomReader(aImageName, aImageType);
+		break;
+
+	case ERofsImage:
+	case ERofsExImage:
+		imgReader = new RofsReader(aImageName, aImageType);
+		break;
+
+	case EE32Directoy:
+		imgReader = new DirReader(aImageName);
+		break;
+	
+	case EE32File:
+		imgReader = new E32Reader(aImageName);
+		break;
+
+	case EUnknownImage:
+		throw ExceptionReporter(UNKNOWNIMAGETYPE, aImageName);
+		break;
+
+	case EE32InputNotExist:
+		throw ExceptionReporter(E32INPUTNOTEXIST, aImageName);
+		break;
+	}
+	if(imgReader == KNull) {
+		throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
+	}
+	Process(imgReader);
+	iImageReaderList.push_back(imgReader);
+}
--- a/imgtools/imgcheck/src/main.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/src/main.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,108 +1,107 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Begining of imgcheck tool.
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "imgcheckmanager.h"
-#include "exceptionreporter.h"
-
-/**
-Global pointers declaration.
-
-@internalComponent
-@released
-*/
-CmdLineHandler* cmdInput = KNull;
-ImgCheckManager* imgCheckerPtr = KNull;
-
-/**
-Function to delete the created instances
-
-@internalComponent
-@released
-*/
-
-void DeleteInstances()
-{
-	DELETE(imgCheckerPtr);
-	DELETE(cmdInput);
-}
-
-/**
-Main function for imgcheck Tool, invokes ImgCheckManager public functions
-to carry out the validation and to generate report.
-
-@internalComponent
-@released
-
-@param argc - commandline argument count
-@param argv - argument variables
-
-@return - returns Exit status success or failure
-*/
-int main(int argc,char* argv[])
-{
-	try
-	{
-		cmdInput = new CmdLineHandler();
-		if(cmdInput == KNull)
-		{
-			throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
-		}
-		ReturnType val = cmdInput->ProcessCommandLine(argc,argv);
-
-		int ret = 0;
-		switch(val)
-		{
-			case EQuit:
-				ret = EXIT_SUCCESS;
-				break;
-	
-			case ESuccess:
-				imgCheckerPtr = new ImgCheckManager(cmdInput);
-				if(imgCheckerPtr == KNull)
-				{
-					throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
-				}
-				imgCheckerPtr->CreateObjects();
-				imgCheckerPtr->Execute();
-				imgCheckerPtr->FillReporterData();
-				imgCheckerPtr->GenerateReport();
-				break;
-			
-			case EFail:
-				ret = EXIT_FAILURE;
-				break;
-		}
-		DeleteInstances();
-		ExceptionImplementation::DeleteInstance();
-		return ret;
-	}
-    catch(ExceptionReporter& aExceptionReport)
-	{
-		aExceptionReport.Report();
-		ExceptionImplementation::DeleteInstance();
-		DeleteInstances();
-		return EXIT_FAILURE;
-	}
-}
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Begining of imgcheck tool.
+*
+*/
+
+
+/**
+ @file
+ @internalComponent
+ @released
+*/
+
+#include "imgcheckmanager.h"
+#include "exceptionreporter.h"
+
+/**
+Global pointers declaration.
+
+@internalComponent
+@released
+*/
+CmdLineHandler* cmdInput = 0;
+ImgCheckManager* imgCheckerPtr = 0;
+
+/**
+Function to delete the created instances
+
+@internalComponent
+@released
+*/
+
+void DeleteInstances() {
+	if(imgCheckerPtr){
+		delete imgCheckerPtr;
+		imgCheckerPtr = 0 ;
+	}
+	if(cmdInput){
+		delete cmdInput;
+		cmdInput = 0 ;
+	}
+}
+
+/**
+Main function for imgcheck Tool, invokes ImgCheckManager public functions
+to carry out the validation and to generate report.
+
+@internalComponent
+@released
+
+@param argc - commandline argument count
+@param argv - argument variables
+
+@return - returns Exit status success or failure
+*/
+int main(int argc,char* argv[]) {
+	try {
+		cmdInput = new CmdLineHandler(); 
+		if(cmdInput == 0) {
+			throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
+		}
+		ReturnType val = cmdInput->ProcessCommandLine(argc,argv);
+
+		int ret = 0;
+		switch(val) {
+			case EQuit:
+				ret = EXIT_SUCCESS;
+				break;
+	
+			case ESuccess:
+				imgCheckerPtr = new ImgCheckManager(cmdInput);
+				if(imgCheckerPtr == 0) {
+					throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
+				} 
+				imgCheckerPtr->CreateObjects();  
+				imgCheckerPtr->Execute();  
+				imgCheckerPtr->FillReporterData();  
+				imgCheckerPtr->GenerateReport();  
+				break;
+			
+			case EFail:
+				ret = EXIT_FAILURE;
+				break;
+		}
+		DeleteInstances();
+		ExceptionImplementation::DeleteInstance();
+		return ret;
+	}
+    catch(ExceptionReporter& aExceptionReport) {
+		aExceptionReport.Report();
+		ExceptionImplementation::DeleteInstance();
+		DeleteInstances();
+		return EXIT_FAILURE;
+	}
+}
--- a/imgtools/imgcheck/src/reporter.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/src/reporter.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,242 +1,196 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Base for commandline or xml report generation.
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "reporter.h"
-
-/**
-Static variable as instance pointer
-
-@internalComponent
-@released
-*/
-Reporter* Reporter::iInstance = KNull;
-
-/**
-Constructor: Reporter class
-Initilize the parameters to data members.
-
-@internalComponent
-@released
-*/
-Reporter::Reporter(unsigned int aCmdOptions)
-:iInputOptions(aCmdOptions)
-{
-}
-
-
-/**
-Destructor: Reporter class 
-Release the objects. 
-
-@internalComponent
-@released
-*/
-Reporter::~Reporter()
-{
-	iImgVsExeStatus.clear();
-}
-
-/**
-Function responsible to return the reference of iImgVsExeStatus
-
-@internalComponent
-@released
-
-@return - returns the reference of iImgVsExeStatus
-*/
-ImgVsExeStatus& Reporter::GetContainerReference()
-{
-	return iImgVsExeStatus;
-}
-
-
-/**
-Function responsible to create the report instances.
-
-@internalComponent
-@released
-
-@param aReportType - report type either commandline or XML
-@param aXmlFile - if XML then pass the xml filename
-
-@return - return the new report instance created
-*/
-Reporter* Reporter::Instance(unsigned int aCmdOptions)
-{
-	if(iInstance == KNull)
-	{
-		iInstance = new Reporter(aCmdOptions);
-		if(!iInstance)
-		{
-			throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
-		}
-	}
-	return iInstance;
-}
-
-/**
-Function to delete the instance.
-
-@internalComponent
-@released
-*/
-void Reporter::DeleteInstance()
-{
-	DELETE(iInstance);
-}
-
-
-/**
-Function responsible to create the report which is common for both the XML and command line output.
-
-@internalComponent
-@released
-
-@param aWriterList - Container which stores the report objects
-*/
-void Reporter::CreateReport(const WriterPtrList& aWriterList)
-{
-	int wtrPtrLstCnt = aWriterList.size();
-	int attrCnt=0;
-	int serNo = 0;
-	ReportWriter* rptWriter = KNull;
-
-	// fetches the begin and end of the image and the related data from the integrated container
-	ImgVsExeStatus::iterator imgBegin;
-	ImgVsExeStatus::iterator imgEnd;
-
-	ExeVsMetaData::iterator exeBegin;
-	ExeVsMetaData::iterator exeEnd;
-	
-	if(IsAttributeAvailable())
-	{
-		while(wtrPtrLstCnt)
-		{
-			imgBegin = iImgVsExeStatus.begin();
-			imgEnd = iImgVsExeStatus.end();
-
-			rptWriter = aWriterList[wtrPtrLstCnt-1];
-			ExceptionReporter(GENERATINGREPORT, (char*)rptWriter->ReportType().c_str()).Log();
-			// starts the report
-			rptWriter->StartReport();
-			
-			while(imgBegin != imgEnd)
-			{
-				// starts the image
-				rptWriter->StartImage(imgBegin->first);
-
-				// fetches the begin and end of the executable container
-				ExeVsMetaData& exeAttStatus = imgBegin->second;
-				exeBegin = exeAttStatus.begin();
-				exeEnd = exeAttStatus.end();
-				serNo = 1;
-				while(exeBegin != exeEnd)
-				{
-					ExeAttList exeAttList = exeBegin->second.iExeAttList;
-					attrCnt = exeAttList.size();
-					if(attrCnt)
-					{
-						// starts the executable	
-						rptWriter->StartExecutable(serNo, exeBegin->first);
-					
-						while(attrCnt)
-						{
-							// writes the attributes
-							rptWriter->WriteExeAttribute(*exeAttList.front());
-							if(wtrPtrLstCnt == 1)
-							{
-								DELETE(exeAttList.front()); //If no more reports to be generated, delete it
-							}
-							exeAttList.pop_front();
-							--attrCnt;
-						}
-						// ends the executable
-						rptWriter->EndExecutable();	
-						++serNo;
-					}
-					++exeBegin;
-				}
-				++imgBegin;
-				// ends the image
-				rptWriter->EndImage();
-			}
-			rptWriter->WriteNote();
-			// ends the report
-			rptWriter->EndReport();
-			--wtrPtrLstCnt;
-		}
-		ExceptionReporter(REPORTGENERATION,"Success").Log();
-	}
-	else
-	{
-		if(iInputOptions & KE32Input)
-		{
-			ExceptionReporter(VALIDE32INPUT).Report();
-		}
-		else
-		{
-			ExceptionReporter(VALIDIMAGE).Report();
-		}
-	}
-}
-
-/**
-Function checks if the attributes are valid and are not blank.
-
-@internalComponent
-@released
-
-*/
-bool Reporter::IsAttributeAvailable()
-{
-	ImgVsExeStatus::iterator imgBegin = iImgVsExeStatus.begin();
-	ImgVsExeStatus::iterator imgEnd = iImgVsExeStatus.end();
-
-	ExeVsMetaData::iterator exeBegin;
-	ExeVsMetaData::iterator exeEnd;
-
-	while(imgBegin != imgEnd)
-	{
-		ExeVsMetaData& exeVsMetaData = imgBegin->second;
-
-		exeBegin = exeVsMetaData.begin();
-		exeEnd = exeVsMetaData.end();
-		while(exeBegin != exeEnd)
-		{
-			if((exeBegin->second).iExeAttList.size() == 0)
-			{
-				++exeBegin;
-				continue;
-			}
-			else
-			{
-				return true;
-			}
-			++exeBegin;
-		}
-		++imgBegin;
-	}
-	return false;
-}
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Base for commandline or xml report generation.
+*
+*/
+
+
+/**
+ @file
+ @internalComponent
+ @released
+*/
+
+#include "reporter.h"
+
+/**
+Static variable as instance pointer
+
+@internalComponent
+@released
+*/
+Reporter* Reporter::iInstance = KNull;
+
+/**
+Constructor: Reporter class
+Initilize the parameters to data members.
+
+@internalComponent
+@released
+*/
+Reporter::Reporter(unsigned int aCmdOptions)
+:iInputOptions(aCmdOptions) {
+}
+
+
+/**
+Destructor: Reporter class 
+Release the objects. 
+
+@internalComponent
+@released
+*/
+Reporter::~Reporter() {
+	for(ImgVsExeStatus::iterator it = iImgVsExeStatus.begin() ; it != iImgVsExeStatus.end(); it++)
+		delete it->second; 
+	iImgVsExeStatus.clear();
+}
+
+/**
+Function responsible to return the reference of iImgVsExeStatus
+
+@internalComponent
+@released
+
+@return - returns the reference of iImgVsExeStatus
+*/
+ImgVsExeStatus& Reporter::GetContainerReference() {
+	return iImgVsExeStatus;
+}
+
+
+/**
+Function responsible to create the report instances.
+
+@internalComponent
+@released
+
+@param aReportType - report type either commandline or XML
+@param aXmlFile - if XML then pass the xml filename
+
+@return - return the new report instance created
+*/
+Reporter* Reporter::Instance(unsigned int aCmdOptions) {
+	if(iInstance == KNull) {
+		iInstance = new Reporter(aCmdOptions);
+		if(!iInstance) {
+			throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
+		}
+	}
+	return iInstance;
+}
+
+/**
+Function to delete the instance.
+
+@internalComponent
+@released
+*/
+void Reporter::DeleteInstance() {
+	if(NULL != iInstance) {
+	  delete iInstance;
+	  iInstance = 0 ;
+	}
+}
+
+
+/**
+Function responsible to create the report which is common for both the XML and command line output.
+
+@internalComponent
+@released
+
+@param aWriterList - Container which stores the report objects
+*/
+void Reporter::CreateReport(const WriterPtrList& aWriterList) {
+	int maxIndex = aWriterList.size() - 1;  
+	int serNo = 0; 
+	// fetches the begin and end of the image and the related data from the integrated container 
+	if(IsAttributeAvailable()) {
+		for(int i = 0 ; i <= maxIndex ; i++) { 
+			ReportWriter* writer = aWriterList.at(i) ;
+			ExceptionReporter(GENERATINGREPORT, writer->ReportType().c_str()).Log(); 
+			// starts the report			
+			writer->StartReport();			
+			for(ImgVsExeStatus::iterator j = iImgVsExeStatus.begin();
+			j != iImgVsExeStatus.end(); j++) {
+				// starts the image
+				writer->StartImage(j->first);
+
+				// fetches the begin and end of the executable container
+				ExeVsMetaData* exeAttStatus = j->second; 
+				serNo = 1;
+				for(ExeVsMetaData::iterator k = exeAttStatus->begin(); 
+				k != exeAttStatus->end(); k++ ) {
+					ExeAttList exeAttList = k->second.iExeAttList;
+					int attrCnt = exeAttList.size();
+					for(int ii = 0 ; ii < attrCnt ; ii++) {
+						// starts the executable	
+						if(ii == 0)
+							writer->StartExecutable(serNo, k->first);					
+						 
+						// writes the attributes
+						ExeAttribute* attr = exeAttList.front();											
+						if(attr) { 
+							writer->WriteExeAttribute(*attr);
+							//If no more reports to be generated, delete it
+							if(maxIndex == i ) delete attr; 
+							
+						}
+						exeAttList.pop_front(); 
+						if(ii == attrCnt - 1){
+						// ends the executable
+							writer->EndExecutable();	
+							++serNo;
+						}
+					} 
+				} 
+				// ends the image
+				writer->EndImage();
+			}
+			writer->WriteNote();
+			// ends the report
+			writer->EndReport();  
+		}
+		ExceptionReporter(REPORTGENERATION,"Success").Log();
+	}
+	else {
+		if(iInputOptions & KE32Input) {
+			ExceptionReporter(VALIDE32INPUT).Report();
+		}
+		else {
+			ExceptionReporter(VALIDIMAGE).Report();
+		}
+	}
+}
+
+/**
+Function checks if the attributes are valid and are not blank.
+
+@internalComponent
+@released
+
+*/
+bool Reporter::IsAttributeAvailable() { 
+	for(ImgVsExeStatus::iterator i = iImgVsExeStatus.begin(); 
+		i != iImgVsExeStatus.end(); i++) {
+		ExeVsMetaData* d = i->second; 
+		for(ExeVsMetaData::iterator j = d->begin() ; j != d->end() ; j++) {
+			if(j->second.iExeAttList.size() > 0)
+				return true ;
+		}
+	}
+	return false;
+}
--- a/imgtools/imgcheck/src/sidchecker.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/src/sidchecker.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,258 +1,230 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* SidChecker class is to 
-* 1. extract all SID's from all executables present in ROM/ROFS sections.
-* 2. Validate them.
-* 3. Put the validated data into Reporter class Instance.
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-#include "sidchecker.h"
-
-/** 
-Constructor.
-
-@internalComponent
-@released
-
-@param aCmdPtr - pointer to an processed CmdLineHandler object
-@param aImageReaderList - List of ImageReader insatance pointers
-*/
-SidChecker::SidChecker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList)
-:Checker(aCmdPtr, aImageReaderList)
-{
-	iSidAll = (iCmdLine->ReportFlag() & KSidAll) ? true : false;
-	iE32Mode = (iCmdLine->ReportFlag() & KE32Input) ? true : false;
-}
-
-/**
-Destructor
-
-@internalComponent
-@released
-*/
-SidChecker::~SidChecker()
-{
-	iSidVsExeMap.clear();
-}
-
-/**
-Function responsible to Prepare the ROM and ROFS image SID data
-
-@internalComponent
-@released
-
-@param ImgVsExeStatus - Global integrated container which contains image, exes and attribute value status.
-*/
-void SidChecker::Check(ImgVsExeStatus& aImgVsExeStatus)
-{
-	ImageReaderPtrList::iterator begin = iImageReaderList.begin();
-	ImageReaderPtrList::iterator end = iImageReaderList.end();
-
-	ExeVsIdDataMap::iterator exeBegin;
-	ExeVsIdDataMap::iterator exeEnd;
-	ExeVsIdDataMap exeVsIdDataMap;
-	ImageReader* imageReader = KNull;
-	String imageName;
-	while(begin != end)
-	{
-		imageReader = *begin;
-		imageName = imageReader->ImageName();
-		ExceptionReporter(GATHERINGIDDATA, (char*)KSid.c_str(),(char*)imageName.c_str()).Log();
-		imageReader->PrepareExeVsIdMap();
-		
-		exeVsIdDataMap = imageReader->GetExeVsIdMap();
-		exeBegin = exeVsIdDataMap.begin();
-		exeEnd = exeVsIdDataMap.end();
-		if((aImgVsExeStatus[imageName].size() == 0) 
-			|| (aImgVsExeStatus[imageName][exeBegin->first].iIdData == KNull))
-		{
-			while(exeBegin != exeEnd)
-			{
-				if(!iSidAll)
-				{
-					if(ReaderUtil::IsExe(&exeBegin->second->iUid))
-					{
-						iSidVsExeMap.insert(std::make_pair(exeBegin->second->iSid, exeBegin->first));
-					}
-				}
-				else
-				{
-					iSidVsExeMap.insert(std::make_pair(exeBegin->second->iSid, exeBegin->first));
-				}
- 				aImgVsExeStatus[imageName][exeBegin->first].iIdData = exeBegin->second;
-				aImgVsExeStatus[imageName][exeBegin->first].iExeName = exeBegin->first;
-				++exeBegin;
-			}
-		}
-		++begin;
-	}
-}
-
-/**
-Function responsible to Validate and write the SID data into reporter.
-
-@internalComponent
-@released
-
-@param aExeContainer - Global integrated container which contains all the attribute, values and the status.
-*/
-void SidChecker::PrepareAndWriteData(ExeContainer* aExeContainer)
-{
-	if(!iSidAll)
-	{
-		/**This map is used to find the uniqueness of the SID, instead of traversing through 
-		the iImgVsExeStatus again and again to get all Executables SID*/
-		if(ReaderUtil::IsExe(&aExeContainer->iIdData->iUid))
-		{
-			FillExeAttribute(aExeContainer);
-		}
-	}
-	else
-	{
-		FillExeAttribute(aExeContainer);
-	}
-}
-
-/**
-Function responsible to Validate the executble SID.
-1. If the SID occurence across all the ROM/ROFS sections is one then the status is Unique.
-2. If more than one entry found and those executables Offset in ROM/ROFS section are same 
-then its status is Unique(Alias).
-3. If those Offsets are differnt, then the status is Duplicate.
-
-@internalComponent
-@released
-
-@param aExeContainer - Global integrated container which contains all the attribute, values and the status.
-*/
-void SidChecker::FillExeSidStatus(ExeContainer* aExeContainer)
-{
-	SidVsExeMap::iterator sidIter;
-	unsigned int cnt = iSidVsExeMap.count(aExeContainer->iIdData->iSid);
-	if(cnt > 1) //Is More than one SID exists?
-	{
-		sidIter = iSidVsExeMap.find(aExeContainer->iIdData->iSid);
-		while(cnt > 0)
-		{
-			if( aExeContainer->iExeName != sidIter->second)
-			{
-				aExeContainer->iIdData->iSidStatus = KDuplicate;
-				
-				if(!iE32Mode)
-				{
-					unsigned int offset = GetExecutableOffset(sidIter->second);
-					if(aExeContainer->iIdData->iFileOffset == offset)
-					{
-						aExeContainer->iIdData->iSidStatus = KUniqueAlias;	
-						break;
-					}
-				}
-			}
-			--cnt;
-			++sidIter;
-		}
-	}
-	else
-	{
-		aExeContainer->iIdData->iSidStatus = KUnique;
-	}
-}
-
-/**
-Function to get an executable's Offset location.
-1. Traverse through all the image entries available in the iImgVsExeStatus container.
-2. Get the executable Offset.
-
-@internalComponent
-@released
-
-@param aExeName - Executable's name.
-
-@return - returns 0 upon failure to find the Executable.
-        - otherwise returns the Offset.
-*/
-const unsigned int SidChecker::GetExecutableOffset(const String& aExeName)
-{
-	Reporter* reporter = Reporter::Instance(iCmdLine->ReportFlag());
-	ImgVsExeStatus& aImgVsExeStatus = reporter->GetContainerReference();
-
-	ImgVsExeStatus::iterator imgBegin = aImgVsExeStatus.begin();
-	ImgVsExeStatus::iterator imgEnd = aImgVsExeStatus.end();
-
-	ExeVsMetaData::iterator exeBegin;
-	ExeVsMetaData::iterator exeEnd;
-	
-	while(imgBegin != imgEnd)
-	{
-		ExeVsMetaData& exeVsMetaData = imgBegin->second;
-		exeBegin = exeVsMetaData.begin();
-		exeEnd = exeVsMetaData.end();
-		
-		while(exeBegin != exeEnd)
-		{
-			if(aExeName == (exeBegin->second).iExeName)
-			{
-				return (exeBegin->second).iIdData->iFileOffset;
-			}
-			++exeBegin;
-		}
-		++imgBegin;
-	}
-	return 0;
-}
-
-/**
-Function responsible fill up the exe attribute list
-
-@internalComponent
-@released
-
-@param aExeContainer - Global integrated container which contains all the attribute, values and the status.
-*/
-void SidChecker::FillExeAttribute(ExeContainer* aExeContainer)
-{
-	ExeAttribute* exeAtt = KNull;
-
-	exeAtt = new ExeAttribute;
-	if(!exeAtt)
-	{
-		throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
-	}
-
-	exeAtt->iAttName = KSid;
-	exeAtt->iAttValue = Common::IntToString(aExeContainer->iIdData->iSid);
-	if(!iNoCheck)
-	{
-		FillExeSidStatus(aExeContainer);
-		exeAtt->iAttStatus = aExeContainer->iIdData->iSidStatus;
-	}
-	else
-	{
-		exeAtt->iAttStatus = KNull;
-	}
-	if((iAllExecutables 
-		|| (exeAtt->iAttStatus == KDuplicate)) && !exeAtt->iAttStatus.empty() 
-		|| iNoCheck)
-	{
-		aExeContainer->iExeAttList.push_back(exeAtt);
-	}
-}
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* SidChecker class is to 
+* 1. extract all SID's from all executables present in ROM/ROFS sections.
+* 2. Validate them.
+* 3. Put the validated data into Reporter class Instance.
+*
+*/
+
+
+/**
+@file
+@internalComponent
+@released
+*/
+#include "sidchecker.h"
+
+/** 
+Constructor.
+
+@internalComponent
+@released
+
+@param aCmdPtr - pointer to an processed CmdLineHandler object
+@param aImageReaderList - List of ImageReader insatance pointers
+*/
+SidChecker::SidChecker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList)
+:Checker(aCmdPtr, aImageReaderList) {
+	iSidAll = (iCmdLine->ReportFlag() & KSidAll) ? true : false;
+	iE32Mode = (iCmdLine->ReportFlag() & KE32Input) ? true : false;
+}
+
+/**
+Destructor
+
+@internalComponent
+@released
+*/
+SidChecker::~SidChecker() {
+	iSidVsExeMap.clear();
+}
+
+/**
+Function responsible to Prepare the ROM and ROFS image SID data
+
+@internalComponent
+@released
+
+@param ImgVsExeStatus - Global integrated container which contains image, exes and attribute value status.
+*/
+void SidChecker::Check(ImgVsExeStatus& aImgVsExeStatus) {  
+ 
+	int readerCount = iImageReaderList.size();
+	for(int i = 0 ; i < readerCount ; i++) {
+		ImageReader* imageReader = iImageReaderList.at(i);
+		const char* imageName = imageReader->ImageName();
+		ExceptionReporter(GATHERINGIDDATA, KSid,imageName).Log();
+		imageReader->PrepareExeVsIdMap();
+
+		ExeVsIdDataMap& exeVsIdDataMap = const_cast<ExeVsIdDataMap&>(imageReader->GetExeVsIdMap());
+		ImgVsExeStatus::iterator pos = aImgVsExeStatus.find(imageName);
+		ExeVsMetaData* p = 0;
+		if(pos == aImgVsExeStatus.end()){
+			p = new ExeVsMetaData();
+			put_item_to_map(aImgVsExeStatus,imageName,p);
+		}
+		else
+			p = pos->second ; 
+		 
+		for(ExeVsIdDataMap::iterator it = exeVsIdDataMap.begin()
+			;it != exeVsIdDataMap.end(); it++) {
+			ExeVsMetaData::iterator i = p->find(it->first);
+			if(i == p->end()){
+				ExeContainer container;
+				container.iExeName = it->first;
+				container.iIdData = KNull ;
+				i = put_item_to_map(*p,it->first,container);
+			}
+			if(i->second.iIdData == KNull){
+				if(!iSidAll) {
+					if(ReaderUtil::IsExe(&it->second->iUid)) {
+						iSidVsExeMap.insert(
+							pair<unsigned long, string>(it->second->iSid, it->first)
+							); 
+					}
+				}
+				else {
+					iSidVsExeMap.insert(
+							pair<unsigned long, string>(it->second->iSid, it->first)
+							); 
+				}
+				i->second.iIdData = it->second;
+				i->second.iExeName = it->first; 
+			}
+		}		 
+	}
+}
+
+/**
+Function responsible to Validate and write the SID data into reporter.
+
+@internalComponent
+@released
+
+@param aExeContainer - Global integrated container which contains all the attribute, values and the status.
+*/
+void SidChecker::PrepareAndWriteData(ExeContainer& aExeContainer) {
+	if(!iSidAll) {
+		/**This map is used to find the uniqueness of the SID, instead of traversing through 
+		the iImgVsExeStatus again and again to get all Executables SID*/
+		if(ReaderUtil::IsExe(&aExeContainer.iIdData->iUid)) {
+			FillExeAttribute(aExeContainer);
+		}
+	}
+	else {
+		FillExeAttribute(aExeContainer);
+	}
+}
+
+/**
+Function responsible to Validate the executble SID.
+1. If the SID occurence across all the ROM/ROFS sections is one then the status is Unique.
+2. If more than one entry found and those executables Offset in ROM/ROFS section are same 
+then its status is Unique(Alias).
+3. If those Offsets are differnt, then the status is Duplicate.
+
+@internalComponent
+@released
+
+@param aExeContainer - Global integrated container which contains all the attribute, values and the status.
+*/
+void SidChecker::FillExeSidStatus(ExeContainer& aExeContainer) {
+	SidVsExeMap::iterator sidIter;
+	unsigned int cnt = iSidVsExeMap.count(aExeContainer.iIdData->iSid);
+	if(cnt > 1) {//Is More than one SID exists? 
+		sidIter = iSidVsExeMap.find(aExeContainer.iIdData->iSid);
+		while(cnt > 0) {
+			if( aExeContainer.iExeName != sidIter->second) {
+				aExeContainer.iIdData->iSidStatus = KDuplicate;
+
+				if(!iE32Mode) {
+					unsigned int offset = GetExecutableOffset(sidIter->second.c_str());
+					if(aExeContainer.iIdData->iFileOffset == offset) {
+						aExeContainer.iIdData->iSidStatus = KUniqueAlias;	
+						break;
+					}
+				}
+			}
+			--cnt;
+			++sidIter;
+		}
+	}
+	else {
+		aExeContainer.iIdData->iSidStatus = KUnique;
+	}
+}
+
+/**
+Function to get an executable's Offset location.
+1. Traverse through all the image entries available in the iImgVsExeStatus container.
+2. Get the executable Offset.
+
+@internalComponent
+@released
+
+@param aExeName - Executable's name.
+
+@return - returns 0 upon failure to find the Executable.
+- otherwise returns the Offset.
+*/
+const unsigned int SidChecker::GetExecutableOffset(const char* aExeName) {
+	Reporter* reporter = Reporter::Instance(iCmdLine->ReportFlag());
+	ImgVsExeStatus& aImgVsExeStatus = reporter->GetContainerReference();	 
+
+	for(ImgVsExeStatus::iterator it = aImgVsExeStatus.begin();
+		it != aImgVsExeStatus.end() ; it++) {
+		ExeVsMetaData* exeVsMetaData = it->second; 
+		for(ExeVsMetaData::iterator i = exeVsMetaData->begin();
+			i != exeVsMetaData->end() ; i++) {
+			if(i->second.iExeName == aExeName  ) {
+				return (i->second).iIdData->iFileOffset;
+			} 
+		} 
+	}
+	return 0;
+}
+
+/**
+Function responsible fill up the exe attribute list
+
+@internalComponent
+@released
+
+@param aExeContainer - Global integrated container which contains all the attribute, values and the status.
+*/
+void SidChecker::FillExeAttribute(ExeContainer& aExeContainer) {
+	ExeAttribute* exeAtt = KNull;
+
+	exeAtt = new ExeAttribute;
+	if(!exeAtt) {
+		throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
+	}
+
+	exeAtt->iAttName = KSid;
+	exeAtt->iAttValue = Common::IntToString(aExeContainer.iIdData->iSid);
+	if(!iNoCheck) {
+		FillExeSidStatus(aExeContainer);
+		exeAtt->iAttStatus = aExeContainer.iIdData->iSidStatus;
+	}
+	else {
+		exeAtt->iAttStatus = KNull;
+	}
+	if((iAllExecutables 
+		|| (exeAtt->iAttStatus == KDuplicate)) && !exeAtt->iAttStatus.empty() 
+		|| iNoCheck) {
+			aExeContainer.iExeAttList.push_back(exeAtt);
+	}
+}
--- a/imgtools/imgcheck/src/vidchecker.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/src/vidchecker.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,161 +1,149 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* VidChecker class is to 
-* 1. extract all VIDs from all executables present in ROM/ROFS sections.
-* 2. Validate them.
-* 3. Put the validated data into Reporter class Instance.
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-#include "vidchecker.h"
-
-/** 
-Constructor intializes the iVidValList member.
-
-@internalComponent
-@released
-
-@param aCmdPtr - pointer to an processed CmdLineHandler object
-@param aImageReaderList - List of ImageReader insatance pointers
-*/
-VidChecker::VidChecker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList)
-:Checker(aCmdPtr, aImageReaderList)
-{
-	iVidValList = iCmdLine->VidValueList();
-	iVidValList.push_back(KDefaultVid);
-}
-
-/**
-Destructor
-
-@internalComponent
-@released
-*/
-VidChecker::~VidChecker()
-{
-	iVidValList.clear();
-}
-
-/**
-Fucntion responsible to Prepare the ROM and ROFS image VID data
-
-@internalComponent
-@released
-
-@param ImgVsExeStatus - Global integrated container which contains image, exes and attribute value status.
-*/
-void VidChecker::Check(ImgVsExeStatus& aImgVsExeStatus)
-{
-	ImageReaderPtrList::iterator begin = iImageReaderList.begin();
-	ImageReaderPtrList::iterator end = iImageReaderList.end();
-
-	ExeVsIdDataMap::iterator exeBegin;
-	ExeVsIdDataMap::iterator exeEnd;
-
-	String imageName;
-
-	while(begin != end)
-	{
-		ImageReader* imageReader = *begin;
-		imageName = imageReader->ImageName();
-		ExceptionReporter(GATHERINGIDDATA, (char*)KVid.c_str(),(char*)imageName.c_str()).Log();
-		imageReader->PrepareExeVsIdMap();
-		ExeVsIdDataMap& exeVsIdDataMa = (ExeVsIdDataMap&)imageReader->GetExeVsIdMap();
-		exeBegin = exeVsIdDataMa.begin();
-		exeEnd = exeVsIdDataMa.end();
-		if((aImgVsExeStatus[imageName].size() == 0) 
-			|| (aImgVsExeStatus[imageName][exeBegin->first].iIdData == KNull))
-		{
-			while(exeBegin != exeEnd)
-			{
-				aImgVsExeStatus[imageName][exeBegin->first].iIdData = exeBegin->second;
-				aImgVsExeStatus[imageName][exeBegin->first].iExeName = exeBegin->first;
-				++exeBegin;
-			}
-		}
-		++begin;
-	}
-}
-
-/**
-Function responsible to Validate and write the VID data into Reporter.
-
-@internalComponent
-@released
-
-@param aExeContainer - Global integrated container which contains all the attribute, values and the status.
-*/
-void VidChecker::PrepareAndWriteData(ExeContainer* aExeContainer)
-{
-	ExeAttribute* exeAtt = KNull;
-	
-	IdData* idData = KNull;
-
-	idData = aExeContainer->iIdData;
-	exeAtt = new ExeAttribute;
-	if(!exeAtt)
-	{
-		throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
-	}
-	exeAtt->iAttName = KVid;
-	exeAtt->iAttValue = Common::IntToString(idData->iVid);
-	if(!iNoCheck)
-	{
-		FillExeVidStatus(idData);
-		exeAtt->iAttStatus = idData->iVidStatus;
-	}
-	else
-	{
-		exeAtt->iAttStatus = KNull;
-	}
-	if(iAllExecutables || (exeAtt->iAttStatus == KInValid) || iNoCheck)
-	{
-		aExeContainer->iExeAttList.push_back(exeAtt);
-	}
-}
-
-/**
-Function responsible to Validate the executble VID.
-1. Compare the executable VID with all the iVidValList entries, if any one of the
-comparison is success then the VID status is Valid.
-2. Otherwise Invalid.
-
-@internalComponent
-@released
-
-@param aIdData - Executable's IdData data instance.
-*/
-void VidChecker::FillExeVidStatus(IdData* aIdData)
-{
-	aIdData->iVidStatus.assign(KInValid);
-	UnIntList::iterator vidValBegin = iVidValList.begin();
-	UnIntList::iterator vidValEnd = iVidValList.end();
-
-	while(vidValBegin != vidValEnd)
-	{
-		if((*vidValBegin) == aIdData->iVid)
-		{
-			aIdData->iVidStatus = KValid;
-			break;
-		}
-		++vidValBegin;
-	}
-}
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* VidChecker class is to 
+* 1. extract all VIDs from all executables present in ROM/ROFS sections.
+* 2. Validate them.
+* 3. Put the validated data into Reporter class Instance.
+*
+*/
+
+
+/**
+ @file
+ @internalComponent
+ @released
+*/
+#include "vidchecker.h"
+
+/** 
+Constructor intializes the iVidValList member.
+
+@internalComponent
+@released
+
+@param aCmdPtr - pointer to an processed CmdLineHandler object
+@param aImageReaderList - List of ImageReader insatance pointers
+*/
+VidChecker::VidChecker(CmdLineHandler* aCmdPtr, ImageReaderPtrList& aImageReaderList)
+:Checker(aCmdPtr, aImageReaderList) {
+	iVidValList = iCmdLine->VidValueList();
+	iVidValList.push_back(KDefaultVid);
+}
+
+/**
+Destructor
+
+@internalComponent
+@released
+*/
+VidChecker::~VidChecker() {
+	iVidValList.clear();
+}
+
+/**
+Fucntion responsible to Prepare the ROM and ROFS image VID data
+
+@internalComponent
+@released
+
+@param ImgVsExeStatus - Global integrated container which contains image, exes and attribute value status.
+*/
+void VidChecker::Check(ImgVsExeStatus& aImgVsExeStatus) {  	
+	int readerCount = iImageReaderList.size();
+	for(int i = 0 ; i < readerCount ; i++ ) {
+		ImageReader* imageReader = iImageReaderList.at(i);
+		const char* imageName = imageReader->ImageName();
+		ExceptionReporter(GATHERINGIDDATA, KVid ,imageName).Log();
+		imageReader->PrepareExeVsIdMap();
+		ExeVsIdDataMap& exeVsIdDataMap = const_cast<ExeVsIdDataMap&>(imageReader->GetExeVsIdMap());
+		ImgVsExeStatus::iterator pos = aImgVsExeStatus.find(imageName);
+		ExeVsMetaData* p = 0;
+		if(pos == aImgVsExeStatus.end()){
+			p = new ExeVsMetaData();
+			put_item_to_map(aImgVsExeStatus,imageName,p);
+		}
+		else
+			p = pos->second ;
+		for(ExeVsIdDataMap::iterator it = exeVsIdDataMap.begin(); 
+		it != exeVsIdDataMap.end(); it++) {
+			ExeVsMetaData::iterator i = p->find(it->first);
+			if(i == p->end()){
+				ExeContainer container;
+				container.iExeName = it->first;
+				container.iIdData = it->second ;
+				put_item_to_map(*p,it->first,container);
+			}
+			else if(i->second.iIdData == KNull){				
+				i->second.iExeName = it->first;
+				i->second.iIdData = it->second ;
+			}  
+		}
+		 
+	}
+}
+
+/**
+Function responsible to Validate and write the VID data into Reporter.
+
+@internalComponent
+@released
+
+@param aExeContainer - Global integrated container which contains all the attribute, values and the status.
+*/
+void VidChecker::PrepareAndWriteData(ExeContainer& aExeContainer) {
+	ExeAttribute* exeAtt = KNull;
+	
+	IdData* idData = KNull;
+
+	idData = aExeContainer.iIdData;
+	exeAtt = new ExeAttribute;
+	if(!exeAtt) {
+		throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
+	}
+	exeAtt->iAttName = KVid;
+	exeAtt->iAttValue = Common::IntToString(idData->iVid);
+	if(!iNoCheck) {
+		FillExeVidStatus(idData);
+		exeAtt->iAttStatus = idData->iVidStatus;
+	}
+	else {
+		exeAtt->iAttStatus = KNull;
+	}
+	if(iAllExecutables || (exeAtt->iAttStatus == KInValid) || iNoCheck) {
+		aExeContainer.iExeAttList.push_back(exeAtt);
+	}
+}
+
+/**
+Function responsible to Validate the executble VID.
+1. Compare the executable VID with all the iVidValList entries, if any one of the
+comparison is success then the VID status is Valid.
+2. Otherwise Invalid.
+
+@internalComponent
+@released
+
+@param aIdData - Executable's IdData data instance.
+*/
+void VidChecker::FillExeVidStatus(IdData* aIdData) {
+	aIdData->iVidStatus.assign(KInValid); 
+	for(UnIntList::iterator it = iVidValList.begin(); 
+		it != iVidValList.end(); it++) {
+		if(*it == aIdData->iVid) {
+			aIdData->iVidStatus.assign(KValid);
+			break;
+		} 
+	}
+}
--- a/imgtools/imgcheck/src/xmlwriter.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imgcheck/src/xmlwriter.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,353 +1,321 @@
-/*
-* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Writes XML elements into output stream to generate a XML file
-*
-*/
-
-
-/**
- @file
- @internalComponent
- @released
-*/
-
-#include "xmlwriter.h"
-
-#ifndef __LINUX__		
-	#include "/epoc32/gcc_mingw/include/windows.h"	
-#endif //__LINUX__
-
-/**
-Constructor: XmlWriter class
-
-@internalComponent
-@released
-
-@param aXmlfileName - Reference to xml filename.
-@param iInputCommnd - Reference to the input options
-*/
-XmlWriter::XmlWriter(const String& aXmlFileName, const String& aInputCommand)
-: iXmlFileName(aXmlFileName), iXmlBufPtr(0) , iXmlTextWriter(0) , iInputCommnd(aInputCommand), iRptType(KXml)
-{
-}
-
-
-/**
-Destructor : XmlWriter class
-Closes the Xml output file.
-
-@internalComponent
-@released
-*/
-XmlWriter::~XmlWriter(void)
-{
-	if(iXmlFile.is_open())
-	{
-		iXmlFile.close();
-	}
-}
-
-
-/**
-Create the XSL file, OverWrites if exist.
-Get the Xsl Source Path.
-
-@internalComponent
-@released
-
-@returns : 'True' for Success or 'False'.
-*/		   
-int XmlWriter::CreateXslFile(void)
-{
-	// Validate the user entered xml path.
-	char* xslFileName = (char*)iXmlFileName.c_str();
-	String xslSourcePath;
-
-	while(*xslFileName)
-	{
-		if(*xslFileName++ == '\\')
-			*(--xslFileName) = '/';
-	}
-	String xslDestPath(iXmlFileName);
-	unsigned int position = xslDestPath.rfind('/');
-	if(position != String::npos)
-	{
-		xslDestPath.erase(position+1);
-		xslDestPath.append(KXslFileName);
-	}
-	else
-	{
-		xslDestPath.erase();
-		xslDestPath.assign(KXslFileName);
-	}
-
-	if(!(GetXslSourcePath(xslSourcePath)))
-	{
-		return false;
-	}
-	xslSourcePath.append(KXslFileName.c_str());
-
-	ifstream xslSourceHandle;
-	xslSourceHandle.open(xslSourcePath.c_str(), Ios::binary);
-	if(!xslSourceHandle)
-	{
-		return false;
-	}
-	xslSourceHandle.seekg(0, Ios::end);		
-	int fileSize = xslSourceHandle.tellg();
-	xslSourceHandle.seekg(0, Ios::beg);
-	char* filetocopy = new char[fileSize];
-	if (!filetocopy)
-	{
-		throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
-	}
-	xslSourceHandle.read(filetocopy,fileSize);
-	xslSourceHandle.close();
-
-	ofstream xslDestHandle(xslDestPath.c_str(), Ios::binary | Ios::out);
-	if(!xslDestHandle)
-	{
-		delete [] filetocopy;
-		return false;
-	}
-	xslDestHandle.write(filetocopy,fileSize);			
-	xslDestHandle.close();
-	delete [] filetocopy;
-	return true;
-}
-	
-
-/**
-Get Xsl file path (imagecheck.xsl).
-
-@internalComponent
-@released
-
-@param aExePath - Reference to Xsl file Path.
-@return - 'true' for success.
-*/
-bool XmlWriter::GetXslSourcePath(String& aExePath)
-{
-#ifdef __LINUX__
-	aExePath.assign("/");
-	return true;
-#else
-
-	char* size = new char[KXmlGenBuffer];
-	if (!size)
-	{
-		throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
-	}
-	if(!(GetModuleFileName(NULL, size, KXmlGenBuffer)))
-	{
-		delete [] size;
-		return false;
-	}
-	String path(size);
-	delete [] size;
-	size_t last = path.rfind('\\');
-	if(last != String::npos)
-	{
-		aExePath = path.substr(0, last+1);
-		return true;
-	}
-#endif
-	return true ; // to avoid warning
-}
-
-
-/**
-Writes report header to xml file..
-
-Opens the xml file for output.
-Allocate the memory for xml report.
-Write the Dtd/Xslt info.
-Write the root element.
-
-@internalComponent
-@released
-*/
-void XmlWriter::StartReport(void)
-{
-	iXmlFile.open(iXmlFileName.c_str());
-
-	if(!(iXmlFile.is_open()))
-	{
-		throw ExceptionReporter(FILEOPENFAIL, __FILE__, __LINE__, (char*)iXmlFileName.c_str());
-	}
-
-	if(!(CreateXslFile()))
-	{
-		ExceptionReporter(XSLCREATIONFAILED, __FILE__, __LINE__, (char*)KXslFileName.c_str()).Report();
-	}
-
-	iXmlBufPtr = xmlBufferCreate();
-	// xml writer pointer to buffer ( with no compression )
-	iXmlTextWriter = xmlNewTextWriterMemory(iXmlBufPtr,0);
-
-	if (!iXmlBufPtr || !iXmlTextWriter)
-	{
-		throw ExceptionReporter(NOMEMORY,__FILE__,__LINE__);
-	}
-
-	xmlTextWriterStartDocument(iXmlTextWriter, KXmlVersion.c_str(), KXmlEncoding.c_str(), KNull);
-	xmlTextWriterWriteRaw(iXmlTextWriter,(unsigned char*)KDtdXslInfo.c_str());
-	xmlTextWriterStartElement(iXmlTextWriter, BAD_CAST KXmlRootElement.c_str());
-	xmlTextWriterStartElement(iXmlTextWriter,BAD_CAST KXmlcomment.c_str());
-	xmlTextWriterWriteAttribute(iXmlTextWriter, BAD_CAST KXmlcomment.c_str(), BAD_CAST iInputCommnd.c_str());
-}
-
-
-/**
-Writes the report footer to Xml file..
-
-Write the xml end doc info..
-Release the writer pointer from the buffer.
-Writes the buffer content to xml file.
-Frees the xml buffer.
-
-@internalComponent
-@released
-*/
-void XmlWriter::EndReport(void)
-{
-	xmlTextWriterEndElement(iXmlTextWriter);
-	xmlTextWriterEndElement(iXmlTextWriter);
-	xmlTextWriterEndDocument(iXmlTextWriter);
-	xmlFreeTextWriter(iXmlTextWriter);
-	
-	iXmlFile.clear(); 
-	iXmlFile.write((const char *)iXmlBufPtr->content,iXmlBufPtr->use);
-	 
-	if(iXmlFile.fail()){
-		xmlBufferFree(iXmlBufPtr);
-		throw ExceptionReporter(NODISKSPACE, (char*)iXmlFileName.c_str()); 
-	}
-	xmlBufferFree(iXmlBufPtr);
-}
-
-
-/**
-Writes the executable name element.
-
-@internalComponent
-@released
-
-@param aSerNo	  - Serial numebr of the executable specific to the image.
-@param aExeName	  - Reference to executable name.
-*/
-void XmlWriter::StartExecutable(const unsigned int aSerNo, const String& aExeName)
-{
-	xmlTextWriterStartElement(iXmlTextWriter, BAD_CAST KXmlExeName.c_str());
-	xmlTextWriterWriteFormatAttribute(iXmlTextWriter, BAD_CAST KXmlExeAtt1.c_str(),
-									"%d",aSerNo);
-	xmlTextWriterWriteAttribute(iXmlTextWriter, BAD_CAST KXmlExeAtt2.c_str(),
-									BAD_CAST aExeName.c_str());
-}
-
-
-/**
-Writes the executable end element
-
-@internalComponent
-@released
-*/
-void XmlWriter::EndExecutable(void)
-{
-	xmlTextWriterEndElement(iXmlTextWriter);
-}
-
-
-/**
-Writes the note about unknown dependency.
-
-@internalComponent
-@released
-*/
-void XmlWriter::WriteNote(void)
-{
-	xmlTextWriterStartElement(iXmlTextWriter, BAD_CAST KNote.c_str());
-	xmlTextWriterWriteAttribute(iXmlTextWriter, BAD_CAST KXmlExeAtt2.c_str(), BAD_CAST KUnknownDependency.c_str());
-	xmlTextWriterWriteAttribute(iXmlTextWriter, BAD_CAST KNote.c_str(), BAD_CAST KNoteMesg.c_str());
-	xmlTextWriterEndElement(iXmlTextWriter);
-}
-
-
-/**
-Writes the attribute, their values and the status.
-
-@internalComponent
-@released
-
-@param aOneSetExeAtt - Reference to the attributes, their value and status
-*/
-void XmlWriter::WriteExeAttribute(ExeAttribute& aOneSetExeAtt)
-{
-	xmlTextWriterStartElement(iXmlTextWriter, BAD_CAST aOneSetExeAtt.iAttName.c_str());
- 	if (!(strcmp(KDepName.c_str(),aOneSetExeAtt.iAttName.c_str())) 
-		|| !(strcmp(KXMLDbgFlag.c_str(),aOneSetExeAtt.iAttName.c_str())))
-	{
-		xmlTextWriterWriteAttribute(iXmlTextWriter, BAD_CAST KDepAtt1.c_str(),
-								BAD_CAST aOneSetExeAtt.iAttValue.c_str());
-	}
-	else
-	{
-		xmlTextWriterWriteFormatAttribute(iXmlTextWriter, BAD_CAST KAtt2.c_str(),
-			"0x%X",(Common::StringToInt(aOneSetExeAtt.iAttValue)));
-	}
-	
-	xmlTextWriterWriteAttribute(iXmlTextWriter, BAD_CAST KAtt1.c_str(),
-								BAD_CAST aOneSetExeAtt.iAttStatus.c_str());
-	xmlTextWriterEndElement(iXmlTextWriter);
-}
-
-
-/**
-Writes the image name element.
-
-@internalComponent
-@released
-
-@param aImageName - Reference to the image name
-*/
-void XmlWriter::StartImage(const String& aImageName)
-{
-	xmlTextWriterStartElement(iXmlTextWriter, BAD_CAST KXmlImageName.c_str());
-	xmlTextWriterWriteAttribute(iXmlTextWriter, BAD_CAST KXmlImageAtt1.c_str() ,
-								BAD_CAST aImageName.c_str());
-}
-
-/**
-Writes the image end element
-
-@internalComponent
-@released
-*/
-void XmlWriter::EndImage(void)
-{
-	xmlTextWriterEndElement(iXmlTextWriter);
-}
-
-
-/**
-Returns the report type.
-
-@internalComponent
-@released
-*/
-const String& XmlWriter::ReportType(void)
-{
-	return iRptType;
-}
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Writes XML elements into output stream to generate a XML file
+*
+*/
+
+
+/**
+@file
+@internalComponent
+@released
+*/
+
+#include "xmlwriter.h"
+
+#ifndef __LINUX__		
+#include <windows.h>	
+#endif //__LINUX__
+
+/**
+Constructor: XmlWriter class
+
+@internalComponent
+@released
+
+@param aXmlfileName - Reference to xml filename.
+@param iInputCommnd - Reference to the input options
+*/
+XmlWriter::XmlWriter(const string& aXmlFileName, const string& aInputCommand)
+: iXmlFileName(aXmlFileName), iXmlBufPtr(0) , iXmlTextWriter(0) , iInputCommnd(aInputCommand), iRptType(KXml) {
+}
+
+
+/**
+Destructor : XmlWriter class
+Closes the Xml output file.
+
+@internalComponent
+@released
+*/
+XmlWriter::~XmlWriter(void) {
+	if(iXmlFile.is_open()) {
+		iXmlFile.close();
+	}
+}
+
+
+/**
+Create the XSL file, OverWrites if exist.
+Get the Xsl Source Path.
+
+@internalComponent
+@released
+
+@returns : 'True' for Success or 'False'.
+*/		   
+int XmlWriter::CreateXslFile(void) {
+	// Validate the user entered xml path.
+	char* xslFileName = (char*)iXmlFileName.c_str(); 
+	string xslSourcePath("");
+
+	while(*xslFileName) {
+		if(*xslFileName == '\\') {
+			*xslFileName = '/';
+		}
+		xslFileName++ ;
+	}
+	string xslDestPath(iXmlFileName);
+	unsigned int position = xslDestPath.rfind('/');
+	if(position != string::npos) {
+		xslDestPath.erase(position+1);
+		xslDestPath.append(KXslFileName);
+	}
+	else { 
+		xslDestPath.assign(KXslFileName);
+	}
+
+	if(!(GetXslSourcePath(xslSourcePath))) { 
+		return false;
+	}
+	xslSourcePath.append(KXslFileName);
+
+	ifstream xslSourceHandle;
+	xslSourceHandle.open(xslSourcePath.c_str(), ios_base::binary | ios_base::in);
+	if(!xslSourceHandle) { 
+		return false;
+	}
+	xslSourceHandle.seekg(0, ios_base::end);		
+	int fileSize = xslSourceHandle.tellg();
+	xslSourceHandle.seekg(0, ios_base::beg);
+	char* buffer = new char[fileSize];
+	if (!buffer) {
+		throw ExceptionReporter(NOMEMORY, __FILE__, __LINE__);
+	}
+	xslSourceHandle.read(buffer,fileSize);
+	xslSourceHandle.close();
+
+	ofstream xslDestHandle(xslDestPath.c_str(), ios_base::binary | ios_base::out);
+	if(!xslDestHandle) {
+		delete [] buffer; 
+		return false;
+	}
+	xslDestHandle.write(buffer,fileSize);			
+	xslDestHandle.close();
+	delete [] buffer;
+	return true;
+}
+
+
+/**
+Get Xsl file path (imagecheck.xsl).
+
+@internalComponent
+@released
+
+@param aExePath - Reference to Xsl file Path.
+@return - 'true' for success.
+*/
+bool XmlWriter::GetXslSourcePath(string& aExePath) { 
+
+#ifdef __LINUX__
+	char* temp = getenv("_");
+	if(NULL == temp) return false ;		
+	string path(temp);
+#else
+	char buffer[MAX_PATH];
+	if(!(GetModuleFileName(NULL, buffer, MAX_PATH))) return false; 
+	string path(buffer);
+#endif  
+	size_t last = path.rfind(SLASH_CHAR1);
+	if(last != string::npos) {
+		aExePath = path.substr(0, last+1);
+		return true;
+	} 
+	
+	return false ;  
+}
+
+
+/**
+Writes report header to xml file..
+
+Opens the xml file for output.
+Allocate the memory for xml report.
+Write the Dtd/Xslt info.
+Write the root element.
+
+@internalComponent
+@released
+*/
+void XmlWriter::StartReport(void) {
+	iXmlFile.open(iXmlFileName.c_str(),ios_base::out | ios_base::binary | ios_base::trunc);
+
+	if(!(iXmlFile.is_open())) { 
+		throw ExceptionReporter(FILEOPENFAIL, __FILE__, __LINE__,iXmlFileName.c_str());
+	}
+
+
+	if(!(CreateXslFile())) {
+		ExceptionReporter(XSLCREATIONFAILED, __FILE__, __LINE__, KXslFileName).Report();
+	}
+
+	iXmlBufPtr = xmlBufferCreate();
+	// xml writer pointer to buffer ( with no compression )
+	iXmlTextWriter = xmlNewTextWriterMemory(iXmlBufPtr,0);
+
+	if (!iXmlBufPtr || !iXmlTextWriter) {
+		throw ExceptionReporter(NOMEMORY,__FILE__,__LINE__);
+	}
+
+	xmlTextWriterStartDocument(iXmlTextWriter, KXmlVersion, KXmlEncoding, KNull);
+	xmlTextWriterWriteRaw(iXmlTextWriter,(unsigned char*)KDtdXslInfo);
+	xmlTextWriterStartElement(iXmlTextWriter, BAD_CAST KXmlRootElement);
+	xmlTextWriterStartElement(iXmlTextWriter,BAD_CAST KXmlcomment);
+	xmlTextWriterWriteAttribute(iXmlTextWriter, BAD_CAST KXmlcomment, BAD_CAST iInputCommnd.c_str()); 
+}
+
+
+/**
+Writes the report footer to Xml file..
+
+Write the xml end doc info..
+Release the writer pointer from the buffer.
+Writes the buffer content to xml file.
+Frees the xml buffer.
+
+@internalComponent
+@released
+*/
+void XmlWriter::EndReport(void) {
+	xmlTextWriterEndElement(iXmlTextWriter);
+	xmlTextWriterEndElement(iXmlTextWriter);
+	xmlTextWriterEndDocument(iXmlTextWriter);
+	xmlFreeTextWriter(iXmlTextWriter);
+
+	iXmlFile.clear(); 
+	iXmlFile.write((const char *)iXmlBufPtr->content,iXmlBufPtr->use);
+
+	if(iXmlFile.fail()){
+		xmlBufferFree(iXmlBufPtr);
+		throw ExceptionReporter(NODISKSPACE, iXmlFileName.c_str()); 
+	}
+	xmlBufferFree(iXmlBufPtr);
+}
+
+
+/**
+Writes the executable name element.
+
+@internalComponent
+@released
+
+@param aSerNo	  - Serial numebr of the executable specific to the image.
+@param aExeName	  - Reference to executable name.
+*/
+void XmlWriter::StartExecutable(const unsigned int aSerNo, const string& aExeName) {
+	xmlTextWriterStartElement(iXmlTextWriter, BAD_CAST KXmlExeName);
+	xmlTextWriterWriteFormatAttribute(iXmlTextWriter, BAD_CAST KXmlExeAtt1,
+		"%d",aSerNo);
+	xmlTextWriterWriteAttribute(iXmlTextWriter, BAD_CAST KXmlExeAtt2,
+		BAD_CAST aExeName.c_str());
+}
+
+
+/**
+Writes the executable end element
+
+@internalComponent
+@released
+*/
+void XmlWriter::EndExecutable(void) {
+	xmlTextWriterEndElement(iXmlTextWriter);
+}
+
+
+/**
+Writes the note about unknown dependency.
+
+@internalComponent
+@released
+*/
+void XmlWriter::WriteNote(void) {
+	xmlTextWriterStartElement(iXmlTextWriter, BAD_CAST KNote);
+	xmlTextWriterWriteAttribute(iXmlTextWriter, BAD_CAST KXmlExeAtt2, BAD_CAST KUnknownDependency);
+	xmlTextWriterWriteAttribute(iXmlTextWriter, BAD_CAST KNote, BAD_CAST KNoteMesg);
+	xmlTextWriterEndElement(iXmlTextWriter);
+}
+
+
+/**
+Writes the attribute, their values and the status.
+
+@internalComponent
+@released
+
+@param aOneSetExeAtt - Reference to the attributes, their value and status
+*/
+void XmlWriter::WriteExeAttribute(ExeAttribute& aOneSetExeAtt) {
+	xmlTextWriterStartElement(iXmlTextWriter, BAD_CAST aOneSetExeAtt.iAttName.c_str());
+	if (!(strcmp(KDepName,aOneSetExeAtt.iAttName.c_str())) 
+		|| !(strcmp(KXMLDbgFlag,aOneSetExeAtt.iAttName.c_str()))) {
+			xmlTextWriterWriteAttribute(iXmlTextWriter, BAD_CAST KDepAtt1,
+				BAD_CAST aOneSetExeAtt.iAttValue.c_str());
+	}
+	else {
+		xmlTextWriterWriteFormatAttribute(iXmlTextWriter, BAD_CAST KAtt2,
+			"0x%X",(Common::StringToInt(aOneSetExeAtt.iAttValue)));
+	}
+
+	xmlTextWriterWriteAttribute(iXmlTextWriter, BAD_CAST KAtt1,
+		BAD_CAST aOneSetExeAtt.iAttStatus.c_str());
+	xmlTextWriterEndElement(iXmlTextWriter);
+}
+
+
+/**
+Writes the image name element.
+
+@internalComponent
+@released
+
+@param aImageName - Reference to the image name
+*/
+void XmlWriter::StartImage(const string& aImageName) {
+	xmlTextWriterStartElement(iXmlTextWriter, BAD_CAST KXmlImageName);
+	xmlTextWriterWriteAttribute(iXmlTextWriter, BAD_CAST KXmlImageAtt1 ,
+		BAD_CAST aImageName.c_str());
+}
+
+/**
+Writes the image end element
+
+@internalComponent
+@released
+*/
+void XmlWriter::EndImage(void) {
+	xmlTextWriterEndElement(iXmlTextWriter);
+}
+
+
+/**
+Returns the report type.
+
+@internalComponent
+@released
+*/
+const string& XmlWriter::ReportType(void) {
+	return iRptType;
+}
--- a/imgtools/imglib/compress/byte_pair.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/compress/byte_pair.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,571 +1,638 @@
-/*
-* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include "byte_pair.h"
-#define __BREAKPOINT()
-
-#undef ASSERT
-#define ASSERT(c)	if(!(c))	\
-{		\
-    __BREAKPOINT()	\
-}
-
-#include <ctime>
-clock_t ClockCompress = 0;
-
-//#define DEBUG_ASSERT
-#ifdef DEBUG_ASSERT
-void myassert(int c) {
-    if (!(c)) {
-        cout <<"myassertion failed" << endl;
-    }
-}
-#endif
-
-void CBytePair::Initialize(TUint8* data, TInt size)
-{
-    TUint32 *p;
-    p = (TUint32*)PairCount;
-    while(p < (TUint32*)PairCount+0x10000) {
-        *p = 0xffff0000;
-        p ++;
-    }
-    p = (TUint32*)PairBuffer;
-    while (p < (TUint32*)PairBuffer + sizeof(PairBuffer) / 4) {
-        *p = 0xffffffff;
-        p++;
-    }
-    PairBufferNext = 0;
-    p = (TUint32*)PairPos;
-    while (p < (TUint32*)PairPos + sizeof(PairPos) /4 ) {
-        *p = 0xffffffff;
-        p ++;
-    }
-    PairPosNext = 0;
-    p = (TUint32*)PairLists;
-    while (p < (TUint32*)PairLists + sizeof(PairLists) / 4) {
-        *p = 0xffffffff;
-        p ++;
-    }
-    PairListHigh = 0;
-    
-    CountBytes(data,size);
-    marker = -1;
-    LeastCommonByte(marker);
-    ByteUsed(marker);
-
-    TUint8 *pData, *pMask;
-    TUint16 pair;
-    pData=data, pMask=Mask; 
-    if (*pData == marker)
-        *pMask = ByteMarked;
-    else if (*(pData+1) == marker)
-        *pMask = ByteTail;
-    else { 
-        *pMask = ByteHead;
-        pair = (TUint16)(*pData | *(pData+1) << 8);
-        InsertPair(pair, 0);
-    }
-    
-    for (pData++, pMask++; pData < data+size-1; pData++, pMask++) {
-        if (*pData == marker){
-            *pMask = ByteMarked;
-            continue;
-        }
-        if (*(pData+1) == marker){
-            *pMask = ByteTail;
-            continue;
-        }
-        if ((*pData == *(pData+1)) && (*pData == *(pData-1))&& (*(pMask-1) == ByteHead)){
-            *pMask = ByteTail;
-            continue;
-        }
-        *pMask = ByteHead;
-        pair = (TUint16)(*pData | *(pData+1) << 8);
-        InsertPair(pair,(TUint16)(pData-data));
-    }
-    if (*pData == marker)
-        *pMask = ByteMarked;
-    else 
-        *pMask = ByteTail;
-}
-
-TInt CBytePair::MostCommonPair(TInt& pair)
-{
-    TUint16 index = PairLists[PairListHigh];
-    TUint16 tmpindex = index; 
-    TUint16 p = PairBuffer[index].Pair;
-    TInt tieBreak, bestTieBreak;
-    bestTieBreak = -ByteCount[p&0xff] - ByteCount[p>>8];
-    while(PairBuffer[tmpindex].Next != PosEnd) {
-            tmpindex = PairBuffer[tmpindex].Next;
-            p = PairBuffer[tmpindex].Pair;
-            tieBreak = -ByteCount[p&0xff]-ByteCount[p>>8];
-            if(tieBreak>bestTieBreak)
-            {
-                index = tmpindex;
-                bestTieBreak = tieBreak;
-            }
-    }
-    pair = PairBuffer[index].Pair;
-    return PairListHigh;
-}
-
-TInt CBytePair::LeastCommonByte(TInt& byte)
-{
-    TInt bestCount = 0xffff;
-    TInt bestByte = -1;
-    TInt b;
-    for(b=0; b<0x100; b++)
-    {
-        TInt f = ByteCount[b];
-        if(f<bestCount)
-        {
-            bestCount = f;
-            bestByte = b;
-        }
-    }
-    byte = bestByte;
-    return bestCount;
-}
-
-
-TInt CBytePair::Compress(TUint8* dst, TUint8* src, TInt size)
-{
-    clock_t ClockStart = clock();
-    TUint8 tokens[0x100*3];
-    TInt tokenCount = 0;
-    TInt overhead;
-
-    TUint8 * dst2 = dst + size*2;
-    memcpy (dst2, src, size);
-    Initialize (dst2, size);
-    //DumpList(dst2, size);
-    for(TInt r=256; r>0; --r)
-    {   
-        TInt byte;
-        TInt byteCount = LeastCommonByte(byte);
-        if (iFastCompress && byteCount) break;
-        //if(byteCount) break;
-        TInt pair;
-        TInt pairCount = MostCommonPair(pair);
-        TInt saving = pairCount-byteCount;
-
-        //cout << "byte: <" << hex << setw(2) << setfill('0') <<  byte << ">"  << byteCount << endl;
-        //cout << "pair: <" << hex << setw(4) << setfill('0') <<  pair << ">" << pairCount << endl;
-        overhead = 3;
-        if(tokenCount>=32)
-            overhead = 2;
-        if(saving<=overhead)
-            break;
-
-        TUint8* d=tokens+3*tokenCount;
-        ++tokenCount;
-        *d++ = (TUint8)byte;
-        ByteUsed(byte);
-        *d++ = (TUint8)pair;
-        ByteUsed(pair&0xff);
-        *d++ = (TUint8)(pair>>8);
-        ByteUsed(pair>>8);
-        //++GlobalPairs[pair];
-
-            //clock_t ClockReplace1 ,ClockReplace2;
-            TUint16 index = PairCount[pair].Index;
-            TUint16 count = PairCount[pair].Count;
-            TUint16 posindex = PairBuffer[index].Pos;
-            TUint16 headpos, tailpos, tmppos, bytepos;
-            TUint16 tmppair;
-            // Remove pairs
-            while (posindex != PosEnd) {
-                headpos = PairPos[posindex].Pos;
-                tailpos = (TUint16)(headpos + 1);
-                while (Mask[tailpos] == ByteRemoved){
-                    tailpos ++;
-                    myassert(tailpos < MaxBlockSize);
-                }
-                GetPairBackward(dst2, headpos, tmppos, tmppair);
-                if ((tmppos != PosEnd) && (Mask[tmppos] == ByteHead)) {
-                    RemovePair(tmppair, tmppos);
-                    Mask[tmppos] = ByteTail;
-                }
-                if (Mask[tailpos] == ByteHead) {
-                    GetPairForward(dst2, tailpos, size, tmppos, tmppair);
-                    myassert(tmppos!=PosEnd);
-                    RemovePair(tmppair, tmppos);
-                    Mask[tmppos] = ByteTail;
-                }
-                posindex = PairPos[posindex].Next;
-            }
-            if (byteCount) {
-                bytepos = ByteIndex[byte];
-                while(bytepos != PosEnd){
-                    if (Mask[bytepos] == ByteRemoved) {
-                        bytepos = BytePos[bytepos];
-                        continue;
-                    }
-                    GetPairBackward(dst2, bytepos, tmppos, tmppair);
-                    if ((tmppos != PosEnd) && (Mask[tmppos] == ByteHead)) {
-                        RemovePair(tmppair, tmppos);
-                        Mask[tmppos] = ByteTail;
-                    }
-                    if (Mask[bytepos] == ByteHead) {
-                        GetPairForward(dst2, bytepos, size, tmppos, tmppair);
-                        myassert(tmppos!=PosEnd);
-                        RemovePair(tmppair, tmppos);
-                        Mask[tmppos] = ByteTail;
-                    }
-                    bytepos = BytePos[bytepos];
-                }
-            }
-            
-            // Update buffer
-            posindex = PairBuffer[index].Pos;
-            while (posindex != PosEnd){
-                headpos = PairPos[posindex].Pos;
-                tailpos = (TUint16)(headpos + 1);
-                while (Mask[tailpos] == ByteRemoved){
-                    tailpos ++;
-                    myassert(tailpos < MaxBlockSize);
-                }
-                dst2[headpos] = (TUint8)byte;
-                dst2[tailpos] = 0xff;
-                Mask[headpos] = ByteNew;
-                Mask[tailpos] = ByteRemoved;
-                posindex = PairPos[posindex].Next;
-            }
-            if (byteCount) {
-                bytepos = ByteIndex[byte];
-                while(bytepos != PosEnd) {
-                    Mask[bytepos] = ByteMarked;
-                    bytepos = BytePos[bytepos];
-                }
-            }
-            
-            // Insert new pairs
-            posindex = PairBuffer[index].Pos;
-            TUint16 firstpos, lastpos;
-            while (posindex != PosEnd){
-                firstpos = PairPos[posindex].Pos;
-                lastpos = firstpos;
-                if (Mask[firstpos] == ByteNew) {
-                    while ((firstpos > 0) && ((Mask[firstpos] == ByteNew) || (Mask[firstpos] == ByteRemoved)))
-                        firstpos --;
-                    while (Mask[firstpos] != ByteNew)
-                        firstpos ++;
-                    while ((lastpos < MaxBlockSize-1) && ((Mask[lastpos] == ByteNew)||(Mask[lastpos] == ByteRemoved)))
-                        lastpos ++;
-                    while (Mask[lastpos] != ByteNew)
-                        lastpos --;
-
-                    GetPairForward(dst2, lastpos, size, tmppos, tmppair);
-                    if (tmppos != PosEnd) {
-                        Mask[lastpos] = ByteHead;
-                        InsertPair(tmppair, tmppos);
-                    }else {
-                        Mask[lastpos] = ByteTail;
-                    }
-                    GetPairBackward(dst2, firstpos, tmppos, tmppair);
-                    if (tmppos != PosEnd) {
-                        Mask[tmppos] = ByteHead;
-                        InsertPair(tmppair, tmppos);
-                    }
-                    
-                    while (firstpos < lastpos) {
-                        tmppair = (TUint16)(dst2[firstpos] | dst2[firstpos]<<8);
-                        InsertPair(tmppair, firstpos);
-                        Mask[firstpos] = ByteHead;
-                        tmppos = (TUint16)(firstpos + 1);
-                        while (Mask[tmppos] == ByteRemoved)
-                            tmppos ++;
-                        myassert(tmppos <= lastpos);
-                        if (tmppos == lastpos)
-                            break;
-                        Mask[tmppos] = ByteTail;
-                        firstpos = (TUint16)(tmppos + 1);
-                        while ((firstpos < lastpos) && (Mask[firstpos] == ByteRemoved))
-                            firstpos ++;
-                    }
-                }
-                posindex = PairPos[posindex].Next;
-            }
-
-            // Remove the pair from PairLists
-            if (PairBuffer[index].Prev == PosHead){
-                if (PairBuffer[index].Next == PosEnd) {
-                    PairLists[count] = PosEnd;
-                } else {
-                    PairLists[count] = PairBuffer[index].Next;
-                    PairBuffer[PairBuffer[index].Next].Prev = PosHead;
-                }
-            } else {
-                if (PairBuffer[index].Next == PosEnd){
-                    PairBuffer[PairBuffer[index].Prev].Next = PosEnd;
-                } else {
-                    PairBuffer[PairBuffer[index].Prev].Next = PairBuffer[index].Next;
-                    PairBuffer[PairBuffer[index].Next].Prev = PairBuffer[index].Prev;
-                }
-            }
-            while (PairLists[PairListHigh] == PosEnd)
-                PairListHigh --;
-            myassert(PairListHigh >= 1);
-            PairBuffer[index].Next = PosEnd;
-            PairBuffer[index].Prev = PosEnd;
-            PairCount[pair].Count = 0;
-            PairCount[pair].Index = PosEnd;
-
-        //cout << "Pair: <" << pair << "> completed" << endl;
-        //DumpList(dst2,size);
-        //for (int i=0;i<100;i++)
-          //  cout << " ";
-        //cout << endl;
-    }
-
-    // sort tokens with a bubble sort...
-    for(TInt x=0; x<tokenCount-1; x++)
-        for(TInt y=x+1; y<tokenCount; y++)
-            if(tokens[x*3]>tokens[y*3])
-            {
-                TInt z = tokens[x*3];
-                tokens[x*3] = tokens[y*3];
-                tokens[y*3] = (TUint8)z;
-                z = tokens[x*3+1];
-                tokens[x*3+1] = tokens[y*3+1];
-                tokens[y*3+1] = (TUint8)z;
-                z = tokens[x*3+2];
-                tokens[x*3+2] = tokens[y*3+2];
-                tokens[y*3+2] = (TUint8)z;
-            }
-        
-    
-    TUint8* originalDst = dst;
-    
-    *dst++ = (TUint8)tokenCount;
-    TInt tmpTokenCount = tokenCount;
-    if(tokenCount)
-    {
-        *dst++ = (TUint8)marker;
-        if(tokenCount<32)
-        {
-            memcpy(dst,tokens,tokenCount*3);
-            dst += tokenCount*3;
-        }
-        else
-        {
-            TUint8* bitMask = dst;
-            memset(bitMask,0,32);
-            dst += 32;
-            TUint8* d=tokens;
-            do
-            {
-                TInt t=*d++;
-                bitMask[t>>3] |= (1<<(t&7));
-                *dst++ = *d++;
-                *dst++ = *d++;
-            }
-            while(--tokenCount);
-        }
-    }
- 
-    if (tmpTokenCount == 0) {
-        memcpy(dst,dst2,size);
-        dst += size;
-    } else {
-        TUint16 pos = 0;
-        for (TUint8 *p=dst2; p < dst2+size; p++, pos++) {
-            if (Mask[pos] == ByteRemoved)
-                continue;
-            if (Mask[pos]== ByteMarked){
-                *dst++ = (TUint8)marker;
-            }
-            *dst++ = *p;
-        }
-    }
-    
-    ClockCompress += clock() - ClockStart;
-    return (dst-originalDst);
-}
-
-
-TInt CBytePair::Decompress(TUint8* dst, TInt dstSize, TUint8* src, TInt srcSize, TUint8*& srcNext)
-{
-
-    TUint8* dstStart = dst;
-    TUint8* dstEnd = dst+dstSize;
-    TUint8* srcEnd = src+srcSize;
-
-    TUint32 LUT[0x100/2];
-    TUint8* LUT0 = (TUint8*)LUT;
-    TUint8* LUT1 = LUT0+0x100;
-
-    TUint8 stack[0x100];
-    TUint8* stackStart = stack+sizeof(stack);
-    TUint8* sp = stackStart;
-
-    TUint32 marker = ~0u;
-    TInt numTokens;
-    TUint32 p1;
-    TUint32 p2;
-
-    TUint32* l = (TUint32*)LUT;
-    TUint32 b = 0x03020100;
-    TUint32 step = 0x04040404;
-    do
-    {
-        *l++ = b;
-        b += step;
-    }
-    while(b>step);
-
-    if(src>=srcEnd)
-        goto error;
-    numTokens = *src++;
-    if(numTokens)
-    {
-        if(src>=srcEnd)
-            goto error;
-        marker = *src++;
-        LUT0[marker] = (TUint8)~marker;
-
-        if(numTokens<32)
-        {
-            TUint8* tokenEnd = src+3*numTokens;
-            if(tokenEnd>srcEnd)
-                goto error;
-            do
-            {
-                TInt b = *src++;
-                TInt p1 = *src++;
-                TInt p2 = *src++;
-                LUT0[b] = (TUint8)p1;
-                LUT1[b] = (TUint8)p2;
-            }
-            while(src<tokenEnd);
-        }
-        else
-        {
-            TUint8* bitMask = src;
-            src += 32;
-            if(src>srcEnd)
-                goto error;
-            TInt b=0;
-            do
-            {
-                TUint8 mask = bitMask[b>>3];
-                if(mask&(1<<(b&7)))
-                {
-                    if(src>srcEnd)
-                        goto error;
-                    TInt p1 = *src++;
-                    if(src>srcEnd)
-                        goto error;
-                    TInt p2 = *src++;
-                    LUT0[b] = (TUint8)p1;
-                    LUT1[b] = (TUint8)p2;		
-                    --numTokens;
-                }
-                ++b;
-            }
-            while(b<0x100);
-            if(numTokens)
-                goto error;
-        }
-    }
-
-    if(src>=srcEnd)
-        goto error;
-    b = *src++;
-    if(dst>=dstEnd)
-        goto error;
-    p1 = LUT0[b];
-    if(p1!=b)
-        goto not_single;
-next:
-    if(src>=srcEnd)
-        goto done_s;
-    b = *src++;
-    *dst++ = (TUint8)p1;
-    if(dst>=dstEnd)
-        goto done_d;
-    p1 = LUT0[b];
-    if(p1==b)
-        goto next;
-
-not_single:
-    if(b==marker)
-        goto do_marker;
-
-do_pair:
-    p2 = LUT1[b];
-    b = p1;
-    p1 = LUT0[b];
-    if(sp<=stack)
-        goto error;
-    *--sp = (TUint8)p2;
-
-recurse:
-    if(b!=p1)
-        goto do_pair;
-
-    if(sp==stackStart)
-        goto next;
-    b = *sp++;
-    if(dst>=dstEnd)
-        goto error;
-    *dst++ = (TUint8)p1;
-    p1 = LUT0[b];
-    goto recurse;
-
-do_marker:
-    if(src>=srcEnd)
-        goto error;
-    p1 = *src++;
-    goto next;
-
-error:
-    srcNext = 0;
-    return KErrCorrupt;
-
-done_s:
-    *dst++ = (TUint8)p1;
-    srcNext = src;
-    return dst-dstStart;
-
-done_d:
-    if(dst>=dstEnd)
-        --src;
-    srcNext = src;
-    return dst-dstStart;
-}
-
-
-TInt BytePairCompress(TUint8* dst, TUint8* src, TInt size, CBytePair *aBPE)
-{
-    TUint8 PakBuffer[MaxBlockSize*4];
-    TUint8 UnpakBuffer[MaxBlockSize];
-    ASSERT(size<=MaxBlockSize);
-    TInt compressedSize = aBPE->Compress(PakBuffer,src,size);
-    TUint8* pakEnd;
-    TInt us = aBPE->Decompress(UnpakBuffer,MaxBlockSize,PakBuffer,compressedSize,pakEnd);
-    ASSERT(us==size)
-    ASSERT(pakEnd==PakBuffer+compressedSize)
-    ASSERT(!memcmp(src,UnpakBuffer,size))
-    if(compressedSize>=size)
-        return KErrTooBig;
-    memcpy(dst,PakBuffer,compressedSize);
-    return compressedSize;
-}
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#include "byte_pair.h"
+#define __BREAKPOINT()
+
+#undef ASSERT
+#define ASSERT(c)	if(!(c))	\
+{		\
+    __BREAKPOINT()	\
+}
+
+#include <ctime>
+clock_t ClockCompress = 0;
+
+//#define DEBUG_ASSERT
+#ifdef DEBUG_ASSERT
+void myassert(int c) {
+    if (!(c)) {
+        cout <<"myassertion failed" << endl;
+    }
+}
+#endif
+
+void CBytePair::SortN(TUint16 *a, TInt n)
+{
+    //bubble sort
+    TInt i,j;
+    TUint16 tmp;
+    for (i=0;i<n-1;i++){
+        for (j=i+1;j<=n-1;j++){
+            if (a[j]<a[i]) {
+                tmp = a[j];
+                a[j]=a[i];
+                a[i]=tmp;
+            }
+        }
+    }
+}
+void CBytePair::InsertN(TUint16 *a, TInt n, TUint16 v)
+{
+    TInt i;
+    for (i=n-1;i>=0;i--){
+        if (a[i] > v)
+            a[i+1]=a[i];
+        else{
+            break;
+        }
+    }
+    a[i+1] = v;
+}
+
+
+TInt CBytePair::PosN(TUint16 index, TInt n){
+    myassert(n<=PairCount[PairBuffer[index].Pair].Count);
+    TUint16 FirstN[1+3+0x1000/256+1];
+    TInt i = 0;
+    TUint16 posindex;
+    posindex = PairBuffer[index].Pos;
+
+    while (i<n) {
+        FirstN[i] = PairPos[posindex].Pos;
+        posindex = PairPos[posindex].Next;
+        i++;
+    }
+    SortN(FirstN, n);
+    while (posindex!=PosEnd){
+        InsertN(FirstN, n, PairPos[posindex].Pos);
+        posindex=PairPos[posindex].Next;
+    }
+    return FirstN[n-1];
+}
+
+void CBytePair::Initialize(TUint8* data, TInt size)
+{
+#if defined(WIN32)
+    TUint32 *p = reinterpret_cast<TUint32*>(PairCount);
+    TUint32 *end = p + 0x10000;
+    while(p < end) {
+        *p++ = 0xffff0000;
+    }
+#else
+    for(int i = 0 ; i < 0x10000 ; i ++){
+	PairCount[i].Count = 0 ;
+	PairCount[i].Index = 0xffff;
+    }	
+#endif
+    memset(reinterpret_cast<char*>(PairBuffer),0xff, sizeof(PairBuffer)); 
+    PairBufferNext = 0;
+    memset(reinterpret_cast<char*>(PairPos),0xff, sizeof(PairPos)); 
+    PairPosNext = 0;
+    memset(reinterpret_cast<char*>(PairLists),0xff, sizeof(PairLists)); 
+    PairListHigh = 0;
+    
+    CountBytes(data,size);
+    marker = -1;
+    markerCount = LeastCommonByte(marker);
+    ByteUsed(marker);
+
+    TUint8 *pData, *pMask;
+    TUint16 pair;
+    pData=data, pMask=Mask; 
+    if (*pData == marker)
+        *pMask = ByteMarked;
+    else if (*(pData+1) == marker)
+        *pMask = ByteTail;
+    else { 
+        *pMask = ByteHead;
+        pair = (TUint16)(*pData | *(pData+1) << 8);
+        InsertPair(pair, 0);
+    }
+    
+    for (pData++, pMask++; pData < data+size-1; pData++, pMask++) {
+        if (*pData == marker){
+            *pMask = ByteMarked;
+            continue;
+        }
+        if (*(pData+1) == marker){
+            *pMask = ByteTail;
+            continue;
+        }
+        if ((*pData == *(pData+1)) && (*pData == *(pData-1))&& (*(pMask-1) == ByteHead)){
+            *pMask = ByteTail;
+            continue;
+        }
+        *pMask = ByteHead;
+        pair = (TUint16)(*pData | *(pData+1) << 8);
+        InsertPair(pair,(TUint16)(pData-data));
+    }
+    if (*pData == marker)
+        *pMask = ByteMarked;
+    else 
+        *pMask = ByteTail;
+}
+
+TInt CBytePair::MostCommonPair(TInt& pair, TInt minFrequency)
+{
+    TUint16 index = PairLists[PairListHigh];
+    TUint16 tmpindex = index; 
+    TUint16 p = PairBuffer[index].Pair;
+    TInt tieBreak, bestTieBreak;
+    bestTieBreak = -ByteCount[p&0xff] - ByteCount[p>>8];
+    while(PairBuffer[tmpindex].Next != PosEnd) {
+            tmpindex = PairBuffer[tmpindex].Next;
+            p = PairBuffer[tmpindex].Pair;
+            tieBreak = -ByteCount[p&0xff]-ByteCount[p>>8];
+            if(tieBreak>bestTieBreak)
+            {
+                index = tmpindex;
+                bestTieBreak = tieBreak;
+            }
+            else if(tieBreak==bestTieBreak){
+                if (minFrequency > PairListHigh)
+                    break;
+                if (PosN(tmpindex, minFrequency) > PosN(index,minFrequency)){
+                    index = tmpindex;
+                }
+            }
+    }
+    pair = PairBuffer[index].Pair;
+    return PairListHigh;
+}
+
+TInt CBytePair::LeastCommonByte(TInt& byte)
+{
+    TInt bestCount = 0xffff;
+    TInt bestByte = -1;
+    TInt b;
+    for(b=0; b<0x100; b++)
+    {
+        TInt f = ByteCount[b];
+        if(f<bestCount)
+        {
+            bestCount = f;
+            bestByte = b;
+        }
+    }
+    byte = bestByte;
+    return bestCount;
+}
+
+
+TInt CBytePair::Compress(TUint8* dst, TUint8* src, TInt size)
+{
+    clock_t ClockStart = clock();
+    TUint8 tokens[0x100*3];
+    TInt tokenCount = 0;
+
+    TUint8 * dst2 = dst + size*2;
+    memcpy (dst2, src, size);
+    Initialize (dst2, size);
+    TInt overhead = 1+3+markerCount;
+    for(TInt r=256; r>0; --r)
+    {   
+        TInt byte;
+        TInt byteCount = LeastCommonByte(byte);
+        TInt pair;
+        TInt pairCount = MostCommonPair(pair, overhead+1);
+        TInt saving = pairCount-byteCount;
+        if(saving<=overhead)
+            break;
+
+        overhead = 3;
+        if(tokenCount>=32)
+            overhead = 2;
+
+        TUint8* d=tokens+3*tokenCount;
+        ++tokenCount;
+        *d++ = (TUint8)byte;
+        ByteUsed(byte);
+        *d++ = (TUint8)pair;
+        ByteUsed(pair&0xff);
+        *d++ = (TUint8)(pair>>8);
+        ByteUsed(pair>>8);
+
+            TUint16 index = PairCount[pair].Index;
+            TUint16 count = PairCount[pair].Count;
+            TUint16 posindex = PairBuffer[index].Pos;
+            TUint16 headpos, tailpos, tmppos, tmpposprev, bytepos;
+            TUint16 tmppair;
+            // Remove pairs
+            while (posindex != PosEnd) {
+                headpos = PairPos[posindex].Pos;
+                tailpos = (TUint16)(headpos + 1);
+                while (Mask[tailpos] == ByteRemoved){
+                    tailpos ++;
+                    myassert(tailpos < MaxBlockSize);
+                }
+                GetPairBackward(dst2, headpos, tmppos, tmppair);
+                if ((tmppos != PosEnd) && (Mask[tmppos] == ByteHead)) {
+                    RemovePair(tmppair, tmppos);
+                    Mask[tmppos] = ByteTail;
+                }
+                if (Mask[tailpos] == ByteHead) {
+                    GetPairForward(dst2, tailpos, size, tmppos, tmppair);
+                    myassert(tmppos!=PosEnd);
+                    RemovePair(tmppair, tmppos);
+                    Mask[tmppos] = ByteTail;
+                }
+                posindex = PairPos[posindex].Next;
+            }
+            if (byteCount) {
+                bytepos = ByteIndex[byte];
+                while(bytepos != PosEnd){
+                    if (Mask[bytepos] == ByteRemoved) {
+                        bytepos = BytePos[bytepos];
+                        continue;
+                    }
+                    GetPairBackward(dst2, bytepos, tmppos, tmppair);
+                    if ((tmppos != PosEnd) && (Mask[tmppos] == ByteHead)) {
+                        RemovePair(tmppair, tmppos);
+                        Mask[tmppos] = ByteTail;
+                    }
+                    if (Mask[bytepos] == ByteHead) {
+                        GetPairForward(dst2, bytepos, size, tmppos, tmppair);
+                        myassert(tmppos!=PosEnd);
+                        RemovePair(tmppair, tmppos);
+                        Mask[tmppos] = ByteTail;
+                    }
+                    bytepos = BytePos[bytepos];
+                }
+            }
+            
+            // Update buffer
+            posindex = PairBuffer[index].Pos;
+            while (posindex != PosEnd){
+                headpos = PairPos[posindex].Pos;
+                tailpos = (TUint16)(headpos + 1);
+                while (Mask[tailpos] == ByteRemoved){
+                    tailpos ++;
+                    myassert(tailpos < MaxBlockSize);
+                }
+                dst2[headpos] = (TUint8)byte;
+                dst2[tailpos] = 0xff;
+                Mask[headpos] = ByteNew;
+                Mask[tailpos] = ByteRemoved;
+                posindex = PairPos[posindex].Next;
+            }
+            if (byteCount) {
+                bytepos = ByteIndex[byte];
+                while(bytepos != PosEnd) {
+                    Mask[bytepos] = ByteMarked;
+                    bytepos = BytePos[bytepos];
+                }
+            }
+            
+            // Insert new pairs
+            posindex = PairBuffer[index].Pos;
+            TUint16 firstpos, lastpos;
+            while (posindex != PosEnd){
+                firstpos = PairPos[posindex].Pos;
+                lastpos = firstpos;
+                if (Mask[firstpos] == ByteNew) {
+                    while ((firstpos > 0) && ((Mask[firstpos] == ByteNew) || (Mask[firstpos] == ByteRemoved)))
+                        firstpos --;
+                    while (Mask[firstpos] != ByteNew)
+                        firstpos ++;
+                    while ((lastpos < MaxBlockSize-1) && ((Mask[lastpos] == ByteNew)||(Mask[lastpos] == ByteRemoved)))
+                        lastpos ++;
+                    while (Mask[lastpos] != ByteNew)
+                        lastpos --;
+
+                    GetPairForward(dst2, lastpos, size, tmppos, tmppair);
+                    if (tmppos != PosEnd) {
+                        Mask[lastpos] = ByteHead;
+                        InsertPair(tmppair, tmppos);
+                        // Potential new pair after the new one
+                        tmppos = (TUint16)(lastpos+1);
+                        while(Mask[tmppos]==ByteRemoved) 
+                            tmppos ++;
+                        if (Mask[tmppos]==ByteTail){
+                            tmpposprev = tmppos;
+                            tmppos ++;
+                            while (tmppos<size){
+                                if (Mask[tmppos]==ByteRemoved){
+                                    tmppos++;
+                                    continue;
+                                }
+                                if (Mask[tmppos]==ByteMarked)
+                                    break;
+                                if (dst2[tmppos]!=dst2[tmpposprev])
+                                    break;
+                                if (Mask[tmpposprev]==ByteTail){
+                                    //myassert(Mask[tmppos]==ByteHead);
+                                    InsertPair((TUint16)(dst2[tmppos]|dst2[tmppos]<<8), tmpposprev);
+                                    Mask[tmpposprev]=ByteHead;
+                                }else{
+                                    myassert(Mask[tmpposprev]==ByteHead);
+                                    RemovePair((TUint16)(dst2[tmppos]|dst2[tmppos]<<8), tmpposprev);
+                                    Mask[tmpposprev]=ByteTail;
+                                }
+                                tmpposprev = tmppos;
+                                tmppos ++;
+                            }
+                        }
+                    }else {
+                        Mask[lastpos] = ByteTail;
+                    }
+                    GetPairBackward(dst2, firstpos, tmppos, tmppair);
+                    if (tmppos != PosEnd) {
+                        Mask[tmppos] = ByteHead;
+                        InsertPair(tmppair, tmppos);
+                    }
+                    
+                    while (firstpos < lastpos) {
+                        tmppair = (TUint16)(dst2[firstpos] | dst2[firstpos]<<8);
+                        InsertPair(tmppair, firstpos);
+                        Mask[firstpos] = ByteHead;
+                        tmppos = (TUint16)(firstpos + 1);
+                        while (Mask[tmppos] == ByteRemoved)
+                            tmppos ++;
+                        myassert(tmppos <= lastpos);
+                        if (tmppos == lastpos)
+                            break;
+                        Mask[tmppos] = ByteTail;
+                        firstpos = (TUint16)(tmppos + 1);
+                        while ((firstpos < lastpos) && (Mask[firstpos] == ByteRemoved))
+                            firstpos ++;
+                    }
+                }
+                posindex = PairPos[posindex].Next;
+            }
+
+            // Remove the pair from PairLists
+            if (PairBuffer[index].Prev == PosHead){
+                if (PairBuffer[index].Next == PosEnd) {
+                    PairLists[count] = PosEnd;
+                } else {
+                    PairLists[count] = PairBuffer[index].Next;
+                    PairBuffer[PairBuffer[index].Next].Prev = PosHead;
+                }
+            } else {
+                if (PairBuffer[index].Next == PosEnd){
+                    PairBuffer[PairBuffer[index].Prev].Next = PosEnd;
+                } else {
+                    PairBuffer[PairBuffer[index].Prev].Next = PairBuffer[index].Next;
+                    PairBuffer[PairBuffer[index].Next].Prev = PairBuffer[index].Prev;
+                }
+            }
+            while (PairLists[PairListHigh] == PosEnd)
+                PairListHigh --;
+            myassert(PairListHigh >= 1);
+            PairBuffer[index].Next = PosEnd;
+            PairBuffer[index].Prev = PosEnd;
+            PairCount[pair].Count = 0;
+            PairCount[pair].Index = PosEnd;
+
+    }
+
+    // sort tokens with a bubble sort...
+    for(TInt x=0; x<tokenCount-1; x++)
+        for(TInt y=x+1; y<tokenCount; y++)
+            if(tokens[x*3]>tokens[y*3])
+            {
+                TInt z = tokens[x*3];
+                tokens[x*3] = tokens[y*3];
+                tokens[y*3] = (TUint8)z;
+                z = tokens[x*3+1];
+                tokens[x*3+1] = tokens[y*3+1];
+                tokens[y*3+1] = (TUint8)z;
+                z = tokens[x*3+2];
+                tokens[x*3+2] = tokens[y*3+2];
+                tokens[y*3+2] = (TUint8)z;
+            }
+        
+    
+    TUint8* originalDst = dst;
+    
+    *dst++ = (TUint8)tokenCount;
+    TInt tmpTokenCount = tokenCount;
+    if(tokenCount)
+    {
+        *dst++ = (TUint8)marker;
+        if(tokenCount<32)
+        {
+            memcpy(dst,tokens,tokenCount*3);
+            dst += tokenCount*3;
+        }
+        else
+        {
+            TUint8* bitMask = dst;
+            memset(bitMask,0,32);
+            dst += 32;
+            TUint8* d=tokens;
+            do
+            {
+                TInt t=*d++;
+                bitMask[t>>3] |= (1<<(t&7));
+                *dst++ = *d++;
+                *dst++ = *d++;
+            }
+            while(--tokenCount);
+        }
+    }
+ 
+    if (tmpTokenCount == 0) {
+        memcpy(dst,dst2,size);
+        dst += size;
+    } else {
+        TUint16 pos = 0;
+        for (TUint8 *p=dst2; p < dst2+size; p++, pos++) {
+            if (Mask[pos] == ByteRemoved)
+                continue;
+            if (Mask[pos]== ByteMarked){
+                *dst++ = (TUint8)marker;
+            }
+            *dst++ = *p;
+        }
+    }
+    
+    ClockCompress += clock() - ClockStart;
+    return (dst-originalDst);
+}
+
+
+TInt CBytePair::Decompress(TUint8* dst, TInt dstSize, TUint8* src, TInt srcSize, TUint8*& srcNext)
+{
+
+    TUint8* dstStart = dst;
+    TUint8* dstEnd = dst+dstSize;
+    TUint8* srcEnd = src+srcSize;
+
+    TUint32 LUT[0x100/2];
+    TUint8* LUT0 = (TUint8*)LUT;
+    TUint8* LUT1 = LUT0+0x100;
+
+    TUint8 stack[0x100];
+    TUint8* stackStart = stack+sizeof(stack);
+    TUint8* sp = stackStart;
+
+    TUint32 marker = ~0u;
+    TInt numTokens;
+    TUint32 p1;
+    TUint32 p2;
+
+    TUint32* l = (TUint32*)LUT;
+    TUint32 b = 0x03020100;
+    TUint32 step = 0x04040404;
+    do
+    {
+        *l++ = b;
+        b += step;
+    }
+    while(b>step);
+
+    if(src>=srcEnd)
+        goto error;
+    numTokens = *src++;
+    if(numTokens)
+    {
+        if(src>=srcEnd)
+            goto error;
+        marker = *src++;
+        LUT0[marker] = (TUint8)~marker;
+
+        if(numTokens<32)
+        {
+            TUint8* tokenEnd = src+3*numTokens;
+            if(tokenEnd>srcEnd)
+                goto error;
+            do
+            {
+                TInt b = *src++;
+                TInt p1 = *src++;
+                TInt p2 = *src++;
+                LUT0[b] = (TUint8)p1;
+                LUT1[b] = (TUint8)p2;
+            }
+            while(src<tokenEnd);
+        }
+        else
+        {
+            TUint8* bitMask = src;
+            src += 32;
+            if(src>srcEnd)
+                goto error;
+            TInt b=0;
+            do
+            {
+                TUint8 mask = bitMask[b>>3];
+                if(mask&(1<<(b&7)))
+                {
+                    if(src>srcEnd)
+                        goto error;
+                    TInt p1 = *src++;
+                    if(src>srcEnd)
+                        goto error;
+                    TInt p2 = *src++;
+                    LUT0[b] = (TUint8)p1;
+                    LUT1[b] = (TUint8)p2;
+                    --numTokens;
+                }
+                ++b;
+            }
+            while(b<0x100);
+            if(numTokens)
+                goto error;
+        }
+    }
+
+    if(src>=srcEnd)
+        goto error;
+    b = *src++;
+    if(dst>=dstEnd)
+        goto error;
+    p1 = LUT0[b];
+    if(p1!=b)
+        goto not_single;
+next:
+    if(src>=srcEnd)
+        goto done_s;
+    b = *src++;
+    *dst++ = (TUint8)p1;
+    if(dst>=dstEnd)
+        goto done_d;
+    p1 = LUT0[b];
+    if(p1==b)
+        goto next;
+
+not_single:
+    if(b==marker)
+        goto do_marker;
+
+do_pair:
+    p2 = LUT1[b];
+    b = p1;
+    p1 = LUT0[b];
+    if(sp<=stack)
+        goto error;
+    *--sp = (TUint8)p2;
+
+recurse:
+    if(b!=p1)
+        goto do_pair;
+
+    if(sp==stackStart)
+        goto next;
+    b = *sp++;
+    if(dst>=dstEnd)
+        goto error;
+    *dst++ = (TUint8)p1;
+    p1 = LUT0[b];
+    goto recurse;
+
+do_marker:
+    if(src>=srcEnd)
+        goto error;
+    p1 = *src++;
+    goto next;
+
+error:
+    srcNext = 0;
+    return KErrCorrupt;
+
+done_s:
+    *dst++ = (TUint8)p1;
+    srcNext = src;
+    return dst-dstStart;
+
+done_d:
+    if(dst>=dstEnd)
+        --src;
+    srcNext = src;
+    return dst-dstStart;
+}
+
+
+TInt BytePairCompress(TUint8* dst, TUint8* src, TInt size, CBytePair *aBPE)
+{
+    TUint8 PakBuffer[MaxBlockSize*4];
+    TUint8 UnpakBuffer[MaxBlockSize];
+    ASSERT(size<=MaxBlockSize);
+    TInt compressedSize = aBPE->Compress(PakBuffer,src,size);
+    TUint8* pakEnd;
+    TInt us = aBPE->Decompress(UnpakBuffer,MaxBlockSize,PakBuffer,compressedSize,pakEnd);
+    ASSERT(us==size)
+    ASSERT(pakEnd==PakBuffer+compressedSize)
+    ASSERT(!memcmp(src,UnpakBuffer,size))
+    if(compressedSize>=size)
+        return KErrTooBig;
+    memcpy(dst,PakBuffer,compressedSize);
+    return compressedSize;
+}
--- a/imgtools/imglib/compress/byte_pair.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/compress/byte_pair.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,356 +1,347 @@
-/*
-* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-#ifndef BYTE_PAIR_H
-#define BYTE_PAIR_H
-
-#ifdef __VC32__
- #ifdef __MSVCDOTNET__
-  #include <strstream>
-  #include <iomanip>
- #else //!__MSVCDOTNET__
-  #include <strstrea.h>
-  #include <iomanip.h>
- #endif //__MSVCDOTNET__
-#else // !__VC32__
-#ifdef __TOOLS2__ 
-#include <sstream>
-#include <iomanip>
-#include <iostream>
-using namespace std;
-#else
- #include <strstream.h>
- #include <iomanip.h>
- #endif
-#endif // __VC32__
-
-//#include <myassert.h>
-//#define DEBUG_ASSERT
-#ifdef DEBUG_ASSERT
-void myassert(int c);
-#else
-#define myassert(c) 
-#endif
-
-#include <e32cmn.h> 
-typedef struct {
-    TUint16 Count;
-    TUint16 Index; 
-} TPairCountIndex;
-
-typedef struct {
-    TUint16 Pair;
-    TUint16 Next;
-    TUint16 Prev;
-    TUint16 Pos;
-} TPair;
-typedef struct {
-    TUint16 Pos;
-    TUint16 Next;
-} TPos;
-
-const TInt MaxBlockSize = 0x1000;
-
-const TUint16 PosEnd = 0xffff;
-const TUint16 PosHead = 0xfffe;
-const TUint8 ByteRemoved = 'R';
-const TUint8 ByteMarked = 'M';
-const TUint8 ByteHead = 'H';
-const TUint8 ByteTail = 'T';
-const TUint8 ByteNew = 'N';
-class CBytePair {
-    private:
-        TBool   iFastCompress;
-        TInt    marker;
-        TUint8  Mask[MaxBlockSize];
-        TUint16 ByteCount[0x100];
-        TUint16 ByteIndex[0x100];
-        TUint16 BytePos[MaxBlockSize];
-        TPairCountIndex PairCount[0x10000];
-        TPair   PairBuffer[MaxBlockSize*2];
-        TInt    PairBufferNext;
-        TPos    PairPos[MaxBlockSize*3];
-        TUint16 PairPosNext;
-        TUint16 PairLists[MaxBlockSize/2+2];
-        TInt    PairListHigh;
-
-        void CountBytes(TUint8* data, TInt size) {
-            TUint32 *p;
-            p = (TUint32*)ByteCount;
-            while (p < (TUint32*)ByteCount + sizeof(ByteCount)/4) {
-                *p++ = 0;
-            }
-            p = (TUint32*)ByteIndex;
-            while (p < (TUint32*)ByteIndex + sizeof(ByteIndex)/4) {
-                *p++ = 0xffffffff;
-            }
-            p = (TUint32*)BytePos;
-            while (p< (TUint32*)BytePos + sizeof(BytePos)/4) {
-                *p++ = 0xffffffff;
-            }
-            TUint8* dataEnd = data+size;
-            int pos = 0;
-            while(data<dataEnd) {
-                BytePos[pos] = ByteIndex[*data];
-                ByteIndex[*data] = (TUint16)pos;
-                pos ++;
-                ++ByteCount[*data++];
-            }
-        }
-        inline void ByteUsed(TInt b) {
-            ByteCount[b] = 0xffff;
-        }
-        int TieBreak(int b1,int b2) {
-            return -ByteCount[b1]-ByteCount[b2];
-        }
-
-        void Initialize(TUint8* data, TInt size);
-        TInt MostCommonPair(TInt& pair);
-        TInt LeastCommonByte(TInt& byte);
-        inline void InsertPair(const TUint16 pair, const TUint16 pos) {
-            //ClockInsert1 = clock();
-            //cout << "Pair:" << hex << setw(4) << setfill ('0') << pair << endl;
-            TUint16 count = PairCount[pair].Count;
-            if (0==count) {
-                PairCount[pair].Index = (TUint16)PairBufferNext;
-                if (PairLists[1] != PosEnd) {
-                    PairBuffer[PairLists[1]].Prev = (TUint16)PairBufferNext;
-                }
-                PairBuffer[PairBufferNext].Next = PairLists[1];
-                PairBuffer[PairBufferNext].Prev = PosHead;
-                PairLists[1] = (TUint16)PairBufferNext;
-                PairBuffer[PairBufferNext].Pair = pair;
-                PairBuffer[PairBufferNext].Pos = PairPosNext;
-                PairBufferNext ++;
-                myassert(PairBufferNext < MaxBlockSize*2);
-                PairPos[PairPosNext].Pos = pos; 
-                PairPos[PairPosNext].Next = PosEnd;
-            } else {
-                TUint16 index = PairCount[pair].Index;
-               
-                if (PairBuffer[index].Next == PosEnd){
-                    if (PairBuffer[index].Prev == PosHead){
-                        PairLists[count] = PosEnd;
-                    } else {
-                        PairBuffer[PairBuffer[index].Prev].Next = PosEnd;
-                    }
-                } else {
-                    if (PairBuffer[index].Prev == PosHead){
-                        PairLists[count] = PairBuffer[index].Next;
-                        PairBuffer[PairBuffer[index].Next].Prev = PosHead;
-                    } else {
-                        PairBuffer[PairBuffer[index].Prev].Next = PairBuffer[index].Next;
-                        PairBuffer[PairBuffer[index].Next].Prev = PairBuffer[index].Prev;
-                    }
-                }
-                
-                if (PairLists[count+1] != PosEnd){
-                    PairBuffer[PairLists[count+1]].Prev = index;
-                    PairBuffer[index].Next = PairLists[count+1];
-                    PairBuffer[index].Prev = PosHead;
-                    PairLists[count+1] = index;
-                }else{
-                    PairLists[count+1] = index;
-                    PairBuffer[index].Next = PosEnd;
-                    PairBuffer[index].Prev = PosHead;
-                }
-
-                PairPos[PairPosNext].Pos = pos;
-                PairPos[PairPosNext].Next = PairBuffer[index].Pos;
-                PairBuffer[index].Pos = PairPosNext;
-            }
-            PairPosNext ++;
-            
-            myassert(PairPosNext < MaxBlockSize*3);
-            PairCount[pair].Count ++;
-            if (PairCount[pair].Count > PairListHigh) 
-                PairListHigh = PairCount[pair].Count; 
-        }
-        inline void RemovePair(const TUint16 pair, const TUint16 pos){
-            //ClockRemove1 = clock();
-            TUint16 count = PairCount[pair].Count;
-            TUint16 index = PairCount[pair].Index;
-            if (count == 1 ) {
-                PairCount[pair].Count = 0;
-                PairCount[pair].Index = PosEnd;
-                return;
-            }
-            
-            myassert(index != PosEnd);
-            TUint16 *posnextp = &PairBuffer[index].Pos;
-            while (*posnextp != PosEnd){
-                if (PairPos[*posnextp].Pos == pos)
-                    break;
-                posnextp = &PairPos[*posnextp].Next;
-            }
-            myassert(*posnextp != PosEnd);
-            *posnextp = PairPos[*posnextp].Next;
-            
-            if (PairBuffer[index].Next == PosEnd){
-                if (PairBuffer[index].Prev == PosHead){
-                    PairLists[count] = PosEnd;
-                } else {
-                    PairBuffer[PairBuffer[index].Prev].Next = PosEnd;
-                }
-            } else {
-                if (PairBuffer[index].Prev == PosHead){
-                    PairLists[count] = PairBuffer[index].Next;
-                    PairBuffer[PairBuffer[index].Next].Prev = PosHead;
-                } else {
-                    PairBuffer[PairBuffer[index].Prev].Next = PairBuffer[index].Next;
-                    PairBuffer[PairBuffer[index].Next].Prev = PairBuffer[index].Prev;
-                }
-            }
-            myassert(PairCount[pair].Count > 0);
-            PairCount[pair].Count --;
-            if (PairCount[pair].Count == 0)
-                PairCount[pair].Index = PosEnd;
-            
-            count = PairCount[pair].Count;
-            if (count > 0) {
-                if (PairLists[count] != PosEnd){
-                    PairBuffer[PairLists[count]].Prev = index;
-                    PairBuffer[index].Next = PairLists[count];
-                    PairBuffer[index].Prev = PosHead;
-                    PairLists[count] = index;
-                }else{
-                    PairLists[count] = index;
-                    PairBuffer[index].Next = PosEnd;
-                    PairBuffer[index].Prev = PosHead;
-                }
-            }            
-            while (PairLists[PairListHigh] == PosEnd) {
-                PairListHigh --;
-            }             
-        }
-        inline void GetPairBackward (TUint8 *data, TUint16 pos, TUint16 &pairpos, TUint16 &pair) {
-            myassert(pos <MaxBlockSize);
-            myassert(Mask[pos] != ByteMarked);
-            myassert(Mask[pos] != ByteRemoved);
-            TUint8 b = data[pos];
-            if (pos == 0) {
-                pair = 0;
-                pairpos = PosEnd;
-                return;
-            }
-            pos --;
-            while ((pos>0) && (Mask[pos] == ByteRemoved)){
-                pos --;
-            }
-            if ((Mask[pos] == ByteRemoved) || (Mask[pos] == ByteMarked)) {
-                pair = 0;
-                pairpos = PosEnd;
-            } else {
-                pair = (TUint16)((b << 8) | data[pos]);
-                pairpos = pos;
-            }
-        }
-        
-        inline void GetPairForward (TUint8 *data, TUint16 pos, TInt size, TUint16 &pairpos, TUint16 &pair) {
-            myassert(Mask[pos] != ByteMarked);
-            myassert(Mask[pos] != ByteRemoved);
-            myassert(pos < size);
-            TUint8 b = data[pos];
-            pairpos = pos;
-            pos ++;
-            while ((pos < size) && (Mask[pos] == ByteRemoved))
-                pos++;
-            if ((pos == size) || (Mask[pos] == ByteMarked)) {
-                pair = 0;
-                pairpos = PosEnd;
-            } else {
-                pair = (TUint16)(b | (data[pos] << 8));
-            }
-        }
-#ifdef  __TOOLS2__        
-        void DumpList(TUint8 *data, TInt size) {
-            int i, j;
-            cout << "src: " << dec << size << " bytes"<< endl;
-            for (i=0;i<size;i+=16){
-                cout << endl;
-                cout << hex;
-                cout << setfill('0') << setw(4) << right << i << " ";
-                for (j=0;j<16;j++) {
-                    cout << setfill ('0') << setw(2) << right << (unsigned int)data[i+j] << " ";
-                }
-                cout << "    ";
-                for (j=0;j<16;j++) {
-                    char c = isgraph(data[i+j]) ? data[i+j]:'.';
-                    cout << c;
-                }
-            }
-            cout << endl;
-            
-            for (i=0;i<256;i+=16){
-                cout << endl << hex << setfill('0') << setw(2) <<right <<i << " ";
-                for (j=0;j<16;j++) {
-                    cout << setfill ('0') << setw(4) << right << (unsigned int)ByteIndex[i+j] << " ";
-                }
-            }
-            cout << endl;
-            for (i=0;i<256;i++){
-                cout << "Byte: <" << i << "> Count: " << ByteCount[i];
-                TUint16 pos = ByteIndex[i];
-                int j = 0;
-                while (pos != PosEnd){
-                    if (j++ % 16 == 0)
-                        cout << endl << "    ";
-                    cout << hex << setw(4) << setfill('0') << pos << " ";
-                    pos = BytePos[pos];
-                }
-                cout << endl;
-            }
-            cout << "buffer lists" << endl;
-            for (i=PairListHigh; i>=0; i--){
-                TUint16 index = PairLists[i];
-                if (index == PosEnd)
-                    continue;
-                cout << dec;
-                cout << "List " << i << endl;
-                while (index != PosEnd){ 
-                    char b0 = (char)PairBuffer[index].Pair;
-                    char b1 = (char)(PairBuffer[index].Pair >> 8);
-                    cout << "    " << setw(4) << setfill('0') << hex << PairBuffer[index].Pair << " " << "<" << (isgraph(b1)? b1:'.') << (isgraph(b0) ? b0 : '.') << ">";  
-                    TUint16 pos;
-                    pos = PairBuffer[index].Pos;
-                    int k = 0;
-                    while (pos != PosEnd){
-                        if (k%16 ==0) {
-                            cout << endl << "        ";
-                        };
-                        cout << setw(4) << setfill('0') << PairPos[pos].Pos << " ";
-                        k ++;
-                        pos = PairPos[pos].Next;
-                    }
-                    cout << endl;
-                    index = PairBuffer[index].Next;
-                }
-                
-            }
-        }
-#endif
-	public:
-        CBytePair(TBool fastCompress) {
-            iFastCompress = fastCompress; 
-        }
-        TInt Compress(TUint8* dst, TUint8* src, TInt size);
-        TInt Decompress(TUint8* dst, TInt dstSize, TUint8* src, TInt srcSize, TUint8*& srcNext);
-};
-TInt BytePairCompress(TUint8* dst, TUint8* src, TInt size, CBytePair *aBPE);
-
-#endif
-
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+#ifndef BYTE_PAIR_H
+#define BYTE_PAIR_H
+
+ 
+#ifdef __VC32__
+ #ifdef __MSVCDOTNET__
+  #include <strstream>
+  #include <iomanip>
+ #else //!__MSVCDOTNET__
+  #include <strstrea.h>
+  #include <iomanip.h>
+ #endif //__MSVCDOTNET__
+#else // !__VC32__
+#ifdef __TOOLS2__ 
+#include <sstream>
+#include <iomanip>
+#include <iostream>
+using namespace std;
+#else
+ #include <strstream.h>
+ #include <iomanip.h>
+ #endif
+#endif // __VC32__
+
+//#include <myassert.h>
+//#define DEBUG_ASSERT
+#ifdef DEBUG_ASSERT
+void myassert(int c);
+#else
+#define myassert(c) 
+#endif
+
+#include <e32cmn.h> 
+typedef struct {
+    TUint16 Count;
+    TUint16 Index; 
+} TPairCountIndex;
+
+typedef struct {
+    TUint16 Pair;
+    TUint16 Next;
+    TUint16 Prev;
+    TUint16 Pos;
+} TPair;
+typedef struct {
+    TUint16 Pos;
+    TUint16 Next;
+} TPos;
+
+const TInt MaxBlockSize = 0x1000;
+
+const TUint16 PosEnd = 0xffff;
+const TUint16 PosHead = 0xfffe;
+const TUint8 ByteRemoved = 'R';
+const TUint8 ByteMarked = 'M';
+const TUint8 ByteHead = 'H';
+const TUint8 ByteTail = 'T';
+const TUint8 ByteNew = 'N';
+class CBytePair {
+    private:
+        TInt    marker;
+        TInt    markerCount;
+        TUint8  Mask[MaxBlockSize];
+        TUint16 ByteCount[0x100];
+        TUint16 ByteIndex[0x100];
+        TUint16 BytePos[MaxBlockSize];
+        TPairCountIndex PairCount[0x10000];
+        TPair   PairBuffer[MaxBlockSize*2];
+        TInt    PairBufferNext;
+        TPos    PairPos[MaxBlockSize*3];
+        TUint16 PairPosNext;
+        TUint16 PairLists[MaxBlockSize/2+2];
+        TInt    PairListHigh;
+
+        void CountBytes(TUint8* data, TInt size) {
+	    memset(reinterpret_cast<char*>(ByteCount),0,sizeof(ByteCount));
+            memset(reinterpret_cast<char*>(ByteIndex),0xff,sizeof(ByteIndex));
+            memset(reinterpret_cast<char*>(BytePos),0xff, sizeof(BytePos));
+            TUint8* dataEnd = data + size;
+            int pos = 0;
+            while(data < dataEnd) {
+                BytePos[pos] = ByteIndex[*data];
+                ByteIndex[*data] = (TUint16)pos;
+                pos ++;
+                ++ByteCount[*data++];
+            }
+        }
+        inline void ByteUsed(TInt b) {
+            ByteCount[b] = 0xffff;
+        }
+        int TieBreak(int b1,int b2) {
+            return -ByteCount[b1]-ByteCount[b2];
+        }
+        void SortN(TUint16 *a, TInt n);
+        void InsertN(TUint16 *a, TInt n, TUint16 v);
+        TInt PosN(TUint16 index, TInt minFrequency);
+
+        void Initialize(TUint8* data, TInt size);
+        TInt MostCommonPair(TInt& pair, TInt minFrequency);
+        TInt LeastCommonByte(TInt& byte);
+        inline void InsertPair(const TUint16 pair, const TUint16 pos) {
+            //ClockInsert1 = clock();
+            //cout << "Pair:" << hex << setw(4) << setfill ('0') << pair << endl;
+            TUint16 count = PairCount[pair].Count;
+            if (0==count) {
+                PairCount[pair].Index = (TUint16)PairBufferNext;
+                if (PairLists[1] != PosEnd) {
+                    PairBuffer[PairLists[1]].Prev = (TUint16)PairBufferNext;
+                }
+                PairBuffer[PairBufferNext].Next = PairLists[1];
+                PairBuffer[PairBufferNext].Prev = PosHead;
+                PairLists[1] = (TUint16)PairBufferNext;
+                PairBuffer[PairBufferNext].Pair = pair;
+                PairBuffer[PairBufferNext].Pos = PairPosNext;
+                PairBufferNext ++;
+                myassert(PairBufferNext < MaxBlockSize*2);
+                PairPos[PairPosNext].Pos = pos; 
+                PairPos[PairPosNext].Next = PosEnd;
+            } else {
+                TUint16 index = PairCount[pair].Index;
+               
+                if (PairBuffer[index].Next == PosEnd){
+                    if (PairBuffer[index].Prev == PosHead){
+                        PairLists[count] = PosEnd;
+                    } else {
+                        PairBuffer[PairBuffer[index].Prev].Next = PosEnd;
+                    }
+                } else {
+                    if (PairBuffer[index].Prev == PosHead){
+                        PairLists[count] = PairBuffer[index].Next;
+                        PairBuffer[PairBuffer[index].Next].Prev = PosHead;
+                    } else {
+                        PairBuffer[PairBuffer[index].Prev].Next = PairBuffer[index].Next;
+                        PairBuffer[PairBuffer[index].Next].Prev = PairBuffer[index].Prev;
+                    }
+                }
+                
+                if (PairLists[count+1] != PosEnd){
+                    PairBuffer[PairLists[count+1]].Prev = index;
+                    PairBuffer[index].Next = PairLists[count+1];
+                    PairBuffer[index].Prev = PosHead;
+                    PairLists[count+1] = index;
+                }else{
+                    PairLists[count+1] = index;
+                    PairBuffer[index].Next = PosEnd;
+                    PairBuffer[index].Prev = PosHead;
+                }
+
+                PairPos[PairPosNext].Pos = pos;
+                PairPos[PairPosNext].Next = PairBuffer[index].Pos;
+                PairBuffer[index].Pos = PairPosNext;
+            }
+            PairPosNext ++;
+            
+            myassert(PairPosNext < MaxBlockSize*3);
+            PairCount[pair].Count ++;
+            if (PairCount[pair].Count > PairListHigh) 
+                PairListHigh = PairCount[pair].Count; 
+        }
+        inline void RemovePair(const TUint16 pair, const TUint16 pos){
+            //ClockRemove1 = clock();
+            TUint16 count = PairCount[pair].Count;
+            TUint16 index = PairCount[pair].Index;
+            if (count == 1 ) {
+                PairCount[pair].Count = 0;
+                PairCount[pair].Index = PosEnd;
+                return;
+            }
+            
+            myassert(index != PosEnd);
+            TUint16 *posnextp = &PairBuffer[index].Pos;
+            while (*posnextp != PosEnd){
+                if (PairPos[*posnextp].Pos == pos)
+                    break;
+                posnextp = &PairPos[*posnextp].Next;
+            }
+            myassert(*posnextp != PosEnd);
+            *posnextp = PairPos[*posnextp].Next;
+            
+            if (PairBuffer[index].Next == PosEnd){
+                if (PairBuffer[index].Prev == PosHead){
+                    PairLists[count] = PosEnd;
+                } else {
+                    PairBuffer[PairBuffer[index].Prev].Next = PosEnd;
+                }
+            } else {
+                if (PairBuffer[index].Prev == PosHead){
+                    PairLists[count] = PairBuffer[index].Next;
+                    PairBuffer[PairBuffer[index].Next].Prev = PosHead;
+                } else {
+                    PairBuffer[PairBuffer[index].Prev].Next = PairBuffer[index].Next;
+                    PairBuffer[PairBuffer[index].Next].Prev = PairBuffer[index].Prev;
+                }
+            }
+            myassert(PairCount[pair].Count > 0);
+            PairCount[pair].Count --;
+            if (PairCount[pair].Count == 0)
+                PairCount[pair].Index = PosEnd;
+            
+            count = PairCount[pair].Count;
+            if (count > 0) {
+                if (PairLists[count] != PosEnd){
+                    PairBuffer[PairLists[count]].Prev = index;
+                    PairBuffer[index].Next = PairLists[count];
+                    PairBuffer[index].Prev = PosHead;
+                    PairLists[count] = index;
+                }else{
+                    PairLists[count] = index;
+                    PairBuffer[index].Next = PosEnd;
+                    PairBuffer[index].Prev = PosHead;
+                }
+            }            
+            while (PairLists[PairListHigh] == PosEnd) {
+                PairListHigh --;
+            }             
+        }
+        inline void GetPairBackward (TUint8 *data, TUint16 pos, TUint16 &pairpos, TUint16 &pair) {
+            myassert(pos <MaxBlockSize);
+            myassert(Mask[pos] != ByteMarked);
+            myassert(Mask[pos] != ByteRemoved);
+            TUint8 b = data[pos];
+            if (pos == 0) {
+                pair = 0;
+                pairpos = PosEnd;
+                return;
+            }
+            pos --;
+            while ((pos>0) && (Mask[pos] == ByteRemoved)){
+                pos --;
+            }
+            if ((Mask[pos] == ByteRemoved) || (Mask[pos] == ByteMarked)) {
+                pair = 0;
+                pairpos = PosEnd;
+            } else {
+                pair = (TUint16)((b << 8) | data[pos]);
+                pairpos = pos;
+            }
+        }
+        
+        inline void GetPairForward (TUint8 *data, TUint16 pos, TInt size, TUint16 &pairpos, TUint16 &pair) {
+            myassert(Mask[pos] != ByteMarked);
+            myassert(Mask[pos] != ByteRemoved);
+            myassert(pos < size);
+            TUint8 b = data[pos];
+            pairpos = pos;
+            pos ++;
+            while ((pos < size) && (Mask[pos] == ByteRemoved))
+                pos++;
+            if ((pos == size) || (Mask[pos] == ByteMarked)) {
+                pair = 0;
+                pairpos = PosEnd;
+            } else {
+                pair = (TUint16)(b | (data[pos] << 8));
+            }
+        }
+#ifdef  __TOOLS2__        
+        void DumpList(TUint8 *data, TInt size) {
+            int i, j;
+            cout << "src: " << dec << size << " bytes"<< endl;
+            for (i=0;i<size;i+=16){
+                cout << endl;
+                cout << hex;
+                cout << setfill('0') << setw(4) << right << i << " ";
+                for (j=0;j<16;j++) {
+                    cout << setfill ('0') << setw(2) << right << (unsigned int)data[i+j] << " ";
+                }
+                cout << "    ";
+                for (j=0;j<16;j++) {
+                    char c = isgraph(data[i+j]) ? data[i+j]:'.';
+                    cout << c;
+                }
+            }
+            cout << endl;
+            
+            for (i=0;i<256;i+=16){
+                cout << endl << hex << setfill('0') << setw(2) <<right <<i << " ";
+                for (j=0;j<16;j++) {
+                    cout << setfill ('0') << setw(4) << right << (unsigned int)ByteIndex[i+j] << " ";
+                }
+            }
+            cout << endl;
+            for (i=0;i<256;i++){
+                cout << "Byte: <" << i << "> Count: " << ByteCount[i];
+                TUint16 pos = ByteIndex[i];
+                int j = 0;
+                while (pos != PosEnd){
+                    if (j++ % 16 == 0)
+                        cout << endl << "    ";
+                    cout << hex << setw(4) << setfill('0') << pos << " ";
+                    pos = BytePos[pos];
+                }
+                cout << endl;
+            }
+            cout << "buffer lists" << endl;
+            for (i=PairListHigh; i>=0; i--){
+                TUint16 index = PairLists[i];
+                if (index == PosEnd)
+                    continue;
+                cout << dec;
+                cout << "List " << i << endl;
+                while (index != PosEnd){ 
+                    char b0 = (char)PairBuffer[index].Pair;
+                    char b1 = (char)(PairBuffer[index].Pair >> 8);
+                    cout << "    " << setw(4) << setfill('0') << hex << PairBuffer[index].Pair << " " << "<" << (isgraph(b1)? b1:'.') << (isgraph(b0) ? b0 : '.') << ">";  
+                    TUint16 pos;
+                    pos = PairBuffer[index].Pos;
+                    int k = 0;
+                    while (pos != PosEnd){
+                        if (k%16 ==0) {
+                            cout << endl << "        ";
+                        };
+                        cout << setw(4) << setfill('0') << PairPos[pos].Pos << " ";
+                        k ++;
+                        pos = PairPos[pos].Next;
+                    }
+                    cout << endl;
+                    index = PairBuffer[index].Next;
+                }
+                
+            }
+        }
+#endif
+	public:
+        TInt Compress(TUint8* dst, TUint8* src, TInt size);
+        TInt Decompress(TUint8* dst, TInt dstSize, TUint8* src, TInt srcSize, TUint8*& srcNext);
+};
+TInt BytePairCompress(TUint8* dst, TUint8* src, TInt size, CBytePair *aBPE);
+
+#endif
+
--- a/imgtools/imglib/compress/pagedcompress.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/compress/pagedcompress.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,353 +1,353 @@
-/*
-* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* byte_pair.cpp
-*
-*/
-
-
-#include <malloc.h>
-#include <string.h>
-#include <stdlib.h>
-#include "h_utl.h"
-#include "h_ver.h"
-#include <stdio.h>
-
-#include "byte_pair.h"
-
-#define PAGE_SIZE 4096
-
-typedef struct IndexTableItemTag
-{
-	TUint16 iSizeOfCompressedPageData;	// pointer to an array TUint16[NumberOfPages]
-	TUint8 *iCompressedPageData;		// pointer to an array TUint8*. Each elemet of 
-										// this array point a compressed Page data	
-}IndexTableItem;
-
-
-typedef struct IndexTableHeaderTag
-{
-	TInt	iSizeOfData;					// Includes the index and compressed pages
-	TInt	iDecompressedSize;
-	TUint16	iNumberOfPages;
-} IndexTableHeader;
-
-
-class CBytePairCompressedImage
-{
-	public:
-		static CBytePairCompressedImage* NewLC(TUint16 aNumberOfPages, TInt aSize);
-		
-		~CBytePairCompressedImage();
-		
-		void AddPage(TUint16 aPageNum, TUint8 * aPageData, TUint16 aPageSize, CBytePair *aBPE);
-		int  GetPage(TUint16 aPageNum, TUint8 * aPageData, CBytePair *aBPE);
-		void WriteOutTable(ostream &os);
-		int  ReadInTable(istream &is, TUint & aNumberOfPages);
-	
-	private:
-		TInt ConstructL( TUint16 aNumberOfPages, TInt aSize);
-		CBytePairCompressedImage();
-		
-	private:
-		IndexTableHeader 	iHeader;
-		IndexTableItem*		iPages;
-		TUint8* 			iOutBuffer; 
-		
-};
-
-
-CBytePairCompressedImage::CBytePairCompressedImage()
-{
-	
-}
-
-
-CBytePairCompressedImage* CBytePairCompressedImage::NewLC(TUint16 aNumberOfPages, TInt aSize)
-{
-	CBytePairCompressedImage* self = new CBytePairCompressedImage;
-	if( NULL == self)
-	{
-		return self;
-	}
-	
-	if( KErrNone == self->ConstructL(aNumberOfPages, aSize))
-	{
-		return self;
-	}
-
-	if(self != NULL)
-		delete self;
-
-	return NULL;
-}
-
-
-TInt CBytePairCompressedImage::ConstructL(TUint16 aNumberOfPages, TInt aSize)
-{
-#ifdef __DEBUG_MSG__
-	Print(EWarning,"Start ofCBytePairCompressedImage::ConstructL(%d, %d)\n", aNumberOfPages, aSize );
-#endif
-
-	iHeader.iNumberOfPages = aNumberOfPages;
-	iHeader.iDecompressedSize = aSize;
-	
-	if( 0 != aNumberOfPages)
-	{
-		iPages = (IndexTableItem *) calloc(aNumberOfPages, sizeof(IndexTableItem));
-		
-		if( NULL == iPages )
-		{
-			return KErrNoMemory;
-		}
-	}
-		
-	iHeader.iSizeOfData = 	sizeof(iHeader.iSizeOfData) + 
-							sizeof(iHeader.iDecompressedSize) + 
-							sizeof(iHeader.iNumberOfPages) + 
-							aNumberOfPages * sizeof(TUint16);
-	
-	iOutBuffer = (TUint8 *) calloc(4 * PAGE_SIZE, sizeof(TUint8) ); 
-	
-	if ( NULL == iOutBuffer)
-	{
-		return KErrNoMemory;
-	}
-	return KErrNone;
-} // End of ConstructL()
-
-CBytePairCompressedImage::~CBytePairCompressedImage()
-{
-#ifdef __DEBUG_MSG__
-	Print(EWarning,"Destructor calling.");
-#endif
-
-	for( int i = 0; i < iHeader.iNumberOfPages; i++)
-	{
-		free(iPages[i].iCompressedPageData);
-		iPages[i].iCompressedPageData = NULL;
-	}
-	
-	free( iPages );
-	iPages = NULL;
-	
-	free( iOutBuffer );
-	iOutBuffer = NULL;
-}
-
-
-void CBytePairCompressedImage::AddPage(TUint16 aPageNum, TUint8 * aPageData, TUint16 aPageSize, CBytePair *aBPE)
-{
-#ifdef __DEBUG_MSG__
-	Print(EWarning,"Start of AddPage(aPageNum:%d, ,aPageSize:%d)\n",aPageNum, aPageSize );
-#endif
-
-#ifdef __TEST_ONLY__
-
-	iPages[aPageNum].iSizeOfCompressedPageData = 2;
-
-	iPages[aPageNum].iCompressedPageData = (TUint8 *) calloc(iPages[aPageNum].iSizeOfCompressedPageData, sizeof(TUint8) );	
-	
-	memcpy(iPages[aPageNum].iCompressedPageData, (TUint8 *) &aPageNum, iPages[aPageNum].iSizeOfCompressedPageData);
-	
-	
-#else
-
-        TUint16 compressedSize;
-        if(aBPE != NULL)
-            compressedSize = (TUint16) aBPE->Compress(iOutBuffer,aPageData,aPageSize);
-        else {
-            CBytePair bpe(EFalse);
-            compressedSize = (TUint16) bpe.Compress(iOutBuffer,aPageData,aPageSize);
-        }
-	iPages[aPageNum].iSizeOfCompressedPageData = compressedSize;
-
-#ifdef __DEBUG_MSG__
-	Print(EWarning,"Compressed page size:%d\n", iPages[aPageNum].iSizeOfCompressedPageData );
-#endif
-	
-	iPages[aPageNum].iCompressedPageData = (TUint8 *) calloc(iPages[aPageNum].iSizeOfCompressedPageData, sizeof(TUint8) );
-	
-	if( NULL == iPages[aPageNum].iCompressedPageData )
-	{
-		return;
-	}
-	
-	memcpy(iPages[aPageNum].iCompressedPageData, iOutBuffer, iPages[aPageNum].iSizeOfCompressedPageData );
-	
-#endif
-
-	iHeader.iSizeOfData += iPages[aPageNum].iSizeOfCompressedPageData;
-}
-
-void CBytePairCompressedImage::WriteOutTable(ostream &os)
-{
-	// Write out IndexTableHeader
-	os.write((const char *) &iHeader.iSizeOfData, sizeof(iHeader.iSizeOfData));
-	os.write((const char *) &iHeader.iDecompressedSize, sizeof(iHeader.iDecompressedSize));
-	os.write((const char *) &iHeader.iNumberOfPages, sizeof(iHeader.iNumberOfPages));
-	
-	TInt i;
-	// Write out IndexTableItems (size of each compressed page)
-	for(i = 0; i < iHeader.iNumberOfPages; i++)
-	{
-		os.write((const char *) &(iPages[i].iSizeOfCompressedPageData), sizeof(TUint16));
-	}
-	
-	// Write out compressed pages
-	for(i = 0; i < iHeader.iNumberOfPages; i++)
-	{
-		os.write((const char*)iPages[i].iCompressedPageData, iPages[i].iSizeOfCompressedPageData); 
-	}
-	
-}
-
-
-int CBytePairCompressedImage::ReadInTable(istream &is, TUint & aNumberOfPages)
-{
-	// Read page index table header 
-	is.read((char *)&iHeader, (sizeof(iHeader.iSizeOfData)+sizeof(iHeader.iDecompressedSize)+sizeof(iHeader.iNumberOfPages)));
-
-	// Allocatin place to Page index table entries
-	iPages = (IndexTableItem *) calloc(iHeader.iNumberOfPages, sizeof(IndexTableItem));
-		
-	if( NULL == iPages )
-	{
-		return KErrNoMemory;
-	}
-	TInt i;
-	// Read whole Page index table 
-
-	for(i = 0; i < iHeader.iNumberOfPages; i++)
-	{
-		is.read((char *) &(iPages[i].iSizeOfCompressedPageData), sizeof(TUint16));
-	}
-
-	// Read compressed data pages page by page, decompress and store them
-	for(i = 0; i < iHeader.iNumberOfPages; i++)
-	{
-
-		iPages[i].iCompressedPageData = (TUint8 *) calloc(iPages[i].iSizeOfCompressedPageData, sizeof(TUint8) );
-	
-		if( NULL == iPages[i].iCompressedPageData )
-		{
-			return KErrNoMemory;
-		}
-
-		is.read((char*)iPages[i].iCompressedPageData, iPages[i].iSizeOfCompressedPageData);
-	}
-
-	aNumberOfPages = iHeader.iNumberOfPages;
-
-	return KErrNone;
-}
-
-int  CBytePairCompressedImage::GetPage(TUint16 aPageNum, TUint8 * aPageData, CBytePair *aBPE)
-{
-	TUint8* pakEnd;
-        
-        const TInt MaxBlockSize = 0x1000;
-
-        TUint16 uncompressedSize;
-        if(aBPE != NULL)
-            uncompressedSize = (TUint16) aBPE->Decompress( aPageData, 
-                MaxBlockSize, 
-                iPages[aPageNum].iCompressedPageData, 
-                iPages[aPageNum].iSizeOfCompressedPageData, 
-                pakEnd );
-        else {
-            CBytePair bpe(EFalse);
-            uncompressedSize = (TUint16) bpe.Decompress( aPageData, 
-                MaxBlockSize, 
-                iPages[aPageNum].iCompressedPageData, 
-                iPages[aPageNum].iSizeOfCompressedPageData, 
-                pakEnd );
-        }
-
-	return uncompressedSize;
-}
-
-
-void CompressPages(TUint8 * bytes, TInt size, ostream& os, CBytePair *aBPE)
-{
-	// Build a list of compressed pages
-	TUint16 numOfPages = (TUint16) (size / PAGE_SIZE);
-
-#ifdef __DEBUG_MSG__
-	Print(EWarning,"numOfPages:%d, (size %% PAGE_SIZE:%d)\n", numOfPages, size % PAGE_SIZE);
-#endif
-
-	if ( size % PAGE_SIZE > 0)
-		++numOfPages;
-	
-	CBytePairCompressedImage *comprImage = CBytePairCompressedImage::NewLC(numOfPages, size);
-	if( NULL == comprImage)
-	{
-		Print(EError," NULL == comprImage\n");
-		return;
-	}
-	
-	TUint8* iPageStart;
-	TUint16 iPageLen;
-	TUint16 iPage = 0;
-	
-	while(iPage * PAGE_SIZE < size )
-	{
-		iPageStart = &bytes[iPage * PAGE_SIZE];
-		iPageLen = (TUint16)( (iPage + 1) * PAGE_SIZE < size ? PAGE_SIZE : size - iPage * PAGE_SIZE);
-		
-		comprImage->AddPage(iPage, iPageStart, iPageLen, aBPE);
-
-		++iPage;
-	}
-	
-	// Write out index table and compressed pages
-	comprImage->WriteOutTable(os);
-	
-	
-	delete comprImage;
-	comprImage = NULL;
-	
-}
-
-int DecompressPages(TUint8 * bytes, istream& is, CBytePair *aBPE)
-{
-	TUint decompressedSize = 0;
-	CBytePairCompressedImage *comprImage = CBytePairCompressedImage::NewLC(0, 0);
-	if( NULL == comprImage)
-	{
-		Print(EError," NULL == comprImage\n");
-		return KErrNoMemory;
-	}
-
-	TUint numberOfPages = 0;
-	comprImage->ReadInTable(is, numberOfPages);
-
-
-	TUint8* iPageStart;
-	TUint16 iPage = 0;
-	
-	while(iPage < numberOfPages )
-	{
-		iPageStart = &bytes[iPage * PAGE_SIZE];
-		
-		decompressedSize += comprImage->GetPage(iPage, iPageStart, aBPE);
-
-		++iPage;
-	}
-	
-	delete comprImage;
-	return decompressedSize;
-
-}
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* byte_pair.cpp
+*
+*/
+
+
+#include <malloc.h>
+#include <string.h>
+#include <stdlib.h>
+#include "h_utl.h"
+#include "h_ver.h"
+#include <stdio.h>
+
+#include "byte_pair.h"
+
+#define PAGE_SIZE 4096
+
+typedef struct IndexTableItemTag
+{
+	TUint16 iSizeOfCompressedPageData;	// pointer to an array TUint16[NumberOfPages]
+	TUint8 *iCompressedPageData;		// pointer to an array TUint8*. Each elemet of 
+										// this array point a compressed Page data	
+}IndexTableItem;
+
+
+typedef struct IndexTableHeaderTag
+{
+	TInt	iSizeOfData;					// Includes the index and compressed pages
+	TInt	iDecompressedSize;
+	TUint16	iNumberOfPages;
+} IndexTableHeader;
+
+
+class CBytePairCompressedImage
+{
+	public:
+		static CBytePairCompressedImage* NewLC(TUint16 aNumberOfPages, TInt aSize);
+		
+		~CBytePairCompressedImage();
+		
+		void AddPage(TUint16 aPageNum, TUint8 * aPageData, TUint16 aPageSize, CBytePair *aBPE);
+		int  GetPage(TUint16 aPageNum, TUint8 * aPageData, CBytePair *aBPE);
+		void WriteOutTable(ostream &os);
+		int  ReadInTable(istream &is, TUint & aNumberOfPages);
+	
+	private:
+		TInt ConstructL( TUint16 aNumberOfPages, TInt aSize);
+		CBytePairCompressedImage();
+		
+	private:
+		IndexTableHeader 	iHeader;
+		IndexTableItem*		iPages;
+		TUint8* 			iOutBuffer; 
+		
+};
+
+
+CBytePairCompressedImage::CBytePairCompressedImage()
+{
+	
+}
+
+
+CBytePairCompressedImage* CBytePairCompressedImage::NewLC(TUint16 aNumberOfPages, TInt aSize)
+{
+	CBytePairCompressedImage* self = new CBytePairCompressedImage;
+	if( NULL == self)
+	{
+		return self;
+	}
+	
+	if( KErrNone == self->ConstructL(aNumberOfPages, aSize))
+	{
+		return self;
+	}
+
+	if(self != NULL)
+		delete self;
+
+	return NULL;
+}
+
+
+TInt CBytePairCompressedImage::ConstructL(TUint16 aNumberOfPages, TInt aSize)
+{
+#ifdef __DEBUG_MSG__
+	Print(EWarning,"Start ofCBytePairCompressedImage::ConstructL(%d, %d)\n", aNumberOfPages, aSize );
+#endif
+
+	iHeader.iNumberOfPages = aNumberOfPages;
+	iHeader.iDecompressedSize = aSize;
+	
+	if( 0 != aNumberOfPages)
+	{
+		iPages = (IndexTableItem *) calloc(aNumberOfPages, sizeof(IndexTableItem));
+		
+		if( NULL == iPages )
+		{
+			return KErrNoMemory;
+		}
+	}
+		
+	iHeader.iSizeOfData = 	sizeof(iHeader.iSizeOfData) + 
+							sizeof(iHeader.iDecompressedSize) + 
+							sizeof(iHeader.iNumberOfPages) + 
+							aNumberOfPages * sizeof(TUint16);
+	
+	iOutBuffer = (TUint8 *) calloc(4 * PAGE_SIZE, sizeof(TUint8) ); 
+	
+	if ( NULL == iOutBuffer)
+	{
+		return KErrNoMemory;
+	}
+	return KErrNone;
+} // End of ConstructL()
+
+CBytePairCompressedImage::~CBytePairCompressedImage()
+{
+#ifdef __DEBUG_MSG__
+	Print(EWarning,"Destructor calling.");
+#endif
+
+	for( int i = 0; i < iHeader.iNumberOfPages; i++)
+	{
+		free(iPages[i].iCompressedPageData);
+		iPages[i].iCompressedPageData = NULL;
+	}
+	
+	free( iPages );
+	iPages = NULL;
+	
+	free( iOutBuffer );
+	iOutBuffer = NULL;
+}
+
+
+void CBytePairCompressedImage::AddPage(TUint16 aPageNum, TUint8 * aPageData, TUint16 aPageSize, CBytePair *aBPE)
+{
+#ifdef __DEBUG_MSG__
+	Print(EWarning,"Start of AddPage(aPageNum:%d, ,aPageSize:%d)\n",aPageNum, aPageSize );
+#endif
+
+#ifdef __TEST_ONLY__
+
+	iPages[aPageNum].iSizeOfCompressedPageData = 2;
+
+	iPages[aPageNum].iCompressedPageData = (TUint8 *) calloc(iPages[aPageNum].iSizeOfCompressedPageData, sizeof(TUint8) );	
+	
+	memcpy(iPages[aPageNum].iCompressedPageData, (TUint8 *) &aPageNum, iPages[aPageNum].iSizeOfCompressedPageData);
+	
+	
+#else
+
+        TUint16 compressedSize;
+        if(aBPE != NULL)
+            compressedSize = (TUint16) aBPE->Compress(iOutBuffer,aPageData,aPageSize);
+        else {
+            CBytePair bpe;
+            compressedSize = (TUint16) bpe.Compress(iOutBuffer,aPageData,aPageSize);
+        }
+	iPages[aPageNum].iSizeOfCompressedPageData = compressedSize;
+
+#ifdef __DEBUG_MSG__
+	Print(EWarning,"Compressed page size:%d\n", iPages[aPageNum].iSizeOfCompressedPageData );
+#endif
+	
+	iPages[aPageNum].iCompressedPageData = (TUint8 *) calloc(iPages[aPageNum].iSizeOfCompressedPageData, sizeof(TUint8) );
+	
+	if( NULL == iPages[aPageNum].iCompressedPageData )
+	{
+		return;
+	}
+	
+	memcpy(iPages[aPageNum].iCompressedPageData, iOutBuffer, iPages[aPageNum].iSizeOfCompressedPageData );
+	
+#endif
+
+	iHeader.iSizeOfData += iPages[aPageNum].iSizeOfCompressedPageData;
+}
+
+void CBytePairCompressedImage::WriteOutTable(ostream &os)
+{
+	// Write out IndexTableHeader
+	os.write((const char *) &iHeader.iSizeOfData, sizeof(iHeader.iSizeOfData));
+	os.write((const char *) &iHeader.iDecompressedSize, sizeof(iHeader.iDecompressedSize));
+	os.write((const char *) &iHeader.iNumberOfPages, sizeof(iHeader.iNumberOfPages));
+	
+	TInt i;
+	// Write out IndexTableItems (size of each compressed page)
+	for(i = 0; i < iHeader.iNumberOfPages; i++)
+	{
+		os.write((const char *) &(iPages[i].iSizeOfCompressedPageData), sizeof(TUint16));
+	}
+	
+	// Write out compressed pages
+	for(i = 0; i < iHeader.iNumberOfPages; i++)
+	{
+		os.write((const char*)iPages[i].iCompressedPageData, iPages[i].iSizeOfCompressedPageData); 
+	}
+	
+}
+
+
+int CBytePairCompressedImage::ReadInTable(istream &is, TUint & aNumberOfPages)
+{
+	// Read page index table header 
+	is.read((char *)&iHeader, (sizeof(iHeader.iSizeOfData)+sizeof(iHeader.iDecompressedSize)+sizeof(iHeader.iNumberOfPages)));
+
+	// Allocatin place to Page index table entries
+	iPages = (IndexTableItem *) calloc(iHeader.iNumberOfPages, sizeof(IndexTableItem));
+		
+	if( NULL == iPages )
+	{
+		return KErrNoMemory;
+	}
+	TInt i;
+	// Read whole Page index table 
+
+	for(i = 0; i < iHeader.iNumberOfPages; i++)
+	{
+		is.read((char *) &(iPages[i].iSizeOfCompressedPageData), sizeof(TUint16));
+	}
+
+	// Read compressed data pages page by page, decompress and store them
+	for(i = 0; i < iHeader.iNumberOfPages; i++)
+	{
+
+		iPages[i].iCompressedPageData = (TUint8 *) calloc(iPages[i].iSizeOfCompressedPageData, sizeof(TUint8) );
+	
+		if( NULL == iPages[i].iCompressedPageData )
+		{
+			return KErrNoMemory;
+		}
+
+		is.read((char*)iPages[i].iCompressedPageData, iPages[i].iSizeOfCompressedPageData);
+	}
+
+	aNumberOfPages = iHeader.iNumberOfPages;
+
+	return KErrNone;
+}
+
+int  CBytePairCompressedImage::GetPage(TUint16 aPageNum, TUint8 * aPageData, CBytePair *aBPE)
+{
+	TUint8* pakEnd;
+        
+        const TInt MaxBlockSize = 0x1000;
+
+        TUint16 uncompressedSize;
+        if(aBPE != NULL)
+            uncompressedSize = (TUint16) aBPE->Decompress( aPageData, 
+                MaxBlockSize, 
+                iPages[aPageNum].iCompressedPageData, 
+                iPages[aPageNum].iSizeOfCompressedPageData, 
+                pakEnd );
+        else {
+            CBytePair bpe;
+            uncompressedSize = (TUint16) bpe.Decompress( aPageData, 
+                MaxBlockSize, 
+                iPages[aPageNum].iCompressedPageData, 
+                iPages[aPageNum].iSizeOfCompressedPageData, 
+                pakEnd );
+        }
+
+	return uncompressedSize;
+}
+
+
+void CompressPages(TUint8 * bytes, TInt size, ostream& os, CBytePair *aBPE)
+{
+	// Build a list of compressed pages
+	TUint16 numOfPages = (TUint16) (size / PAGE_SIZE);
+
+#ifdef __DEBUG_MSG__
+	Print(EWarning,"numOfPages:%d, (size %% PAGE_SIZE:%d)\n", numOfPages, size % PAGE_SIZE);
+#endif
+
+	if ( size % PAGE_SIZE > 0)
+		++numOfPages;
+	
+	CBytePairCompressedImage *comprImage = CBytePairCompressedImage::NewLC(numOfPages, size);
+	if( NULL == comprImage)
+	{
+		Print(EError," NULL == comprImage\n");
+		return;
+	}
+	
+	TUint8* iPageStart;
+	TUint16 iPageLen;
+	TUint16 iPage = 0;
+	
+	while(iPage * PAGE_SIZE < size )
+	{
+		iPageStart = &bytes[iPage * PAGE_SIZE];
+		iPageLen = (TUint16)( (iPage + 1) * PAGE_SIZE < size ? PAGE_SIZE : size - iPage * PAGE_SIZE);
+		
+		comprImage->AddPage(iPage, iPageStart, iPageLen, aBPE);
+
+		++iPage;
+	}
+	
+	// Write out index table and compressed pages
+	comprImage->WriteOutTable(os);
+	
+	
+	delete comprImage;
+	comprImage = NULL;
+	
+}
+
+int DecompressPages(TUint8 * bytes, istream& is, CBytePair *aBPE)
+{
+	TUint decompressedSize = 0;
+	CBytePairCompressedImage *comprImage = CBytePairCompressedImage::NewLC(0, 0);
+	if( NULL == comprImage)
+	{
+		Print(EError," NULL == comprImage\n");
+		return KErrNoMemory;
+	}
+
+	TUint numberOfPages = 0;
+	comprImage->ReadInTable(is, numberOfPages);
+
+
+	TUint8* iPageStart;
+	TUint16 iPage = 0;
+	
+	while(iPage < numberOfPages )
+	{
+		iPageStart = &bytes[iPage * PAGE_SIZE];
+		
+		decompressedSize += comprImage->GetPage(iPage, iPageStart, aBPE);
+
+		++iPage;
+	}
+	
+	delete comprImage;
+	return decompressedSize;
+
+}
--- a/imgtools/imglib/e32image/deflate/deflate.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/e32image/deflate/deflate.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,327 +1,342 @@
-/*
-* Copyright (c) 1998-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* e32tools\petran\Szip\deflate.cpp
-*
-*/
-
-
-#include "deflate.h"
-#include "h_utl.h"
-#include "panic.h"
-
-class HDeflateHash
-	{
-public:
-	inline static HDeflateHash* NewLC(TInt aLinks);
-//
-	inline TInt First(const TUint8* aPtr,TInt aPos);
-	inline TInt Next(TInt aPos,TInt aOffset) const;
-private:
-	inline HDeflateHash();
-	inline static TInt Hash(const TUint8* aPtr);
-private:
-	typedef TUint16 TOffset;
-private:
-	TInt iHash[256];
-	TOffset iOffset[1];	// or more
-	};
-
-class MDeflater
-	{
-public:
-	void DeflateL(const TUint8* aBase,TInt aLength);
-	inline virtual ~MDeflater() { }; 
-private:
-	const TUint8* DoDeflateL(const TUint8* aBase,const TUint8* aEnd,HDeflateHash& aHash);
-	static TInt Match(const TUint8* aPtr,const TUint8* aEnd,TInt aPos,HDeflateHash& aHas);
-	void SegmentL(TInt aLength,TInt aDistance);
-	virtual void LitLenL(TInt aCode) =0;
-	virtual void OffsetL(TInt aCode) =0;
-	virtual void ExtraL(TInt aLen,TUint aBits) =0;
-	};
-
-class TDeflateStats : public MDeflater
-	{
-public:
-	inline TDeflateStats(TEncoding& aEncoding);
-	inline virtual ~TDeflateStats() { } 
-private:
-// from MDeflater
-	void LitLenL(TInt aCode);
-	void OffsetL(TInt aCode);
-	void ExtraL(TInt aLen,TUint aBits);
-private:
-	TEncoding& iEncoding;
-	};
-
-class TDeflater : public MDeflater
-	{
-public:
-	inline TDeflater(TBitOutput& aOutput,const TEncoding& aEncoding);
-	inline virtual ~TDeflater() { }; 
-private:
-// from MDeflater
-	void LitLenL(TInt aCode);
-	void OffsetL(TInt aCode);
-	void ExtraL(TInt aLen,TUint aBits);
-private:
-	TBitOutput& iOutput;
-	const TEncoding& iEncoding;
-	};
-
-
-// Class HDeflateHash
-
-inline HDeflateHash::HDeflateHash()
-	{TInt* p=iHash+256;do *--p=-KDeflateMaxDistance-1; while (p>iHash);}
-
-inline HDeflateHash* HDeflateHash::NewLC(TInt aLinks)
-	{
-	return new(HMem::Alloc(0,_FOFF(HDeflateHash,iOffset[Min(aLinks,KDeflateMaxDistance)]))) HDeflateHash;
-	}
-
-inline TInt HDeflateHash::Hash(const TUint8* aPtr)
-	{
-	TUint x=aPtr[0]|(aPtr[1]<<8)|(aPtr[2]<<16);
-	return (x*KDeflateHashMultiplier)>>KDeflateHashShift;
-	}
-
-inline TInt HDeflateHash::First(const TUint8* aPtr,TInt aPos)
-	{
-	TInt h=Hash(aPtr);
-	TInt offset=Min(aPos-iHash[h],KDeflateMaxDistance<<1);
-	iHash[h]=aPos;
-	iOffset[aPos&(KDeflateMaxDistance-1)]=TOffset(offset);
-	return offset;
-	}
-
-inline TInt HDeflateHash::Next(TInt aPos,TInt aOffset) const
-	{return aOffset+iOffset[(aPos-aOffset)&(KDeflateMaxDistance-1)];}
-
-
-// Class TDeflater
-//
-// generic deflation algorithm, can do either statistics and the encoder
-
-TInt MDeflater::Match(const TUint8* aPtr,const TUint8* aEnd,TInt aPos,HDeflateHash& aHash)
-	{
-	TInt offset=aHash.First(aPtr,aPos);
-	if (offset>KDeflateMaxDistance)
-		return 0;
-	TInt match=0;
-	aEnd=Min(aEnd,aPtr+KDeflateMaxLength);
-	TUint8 c=*aPtr;
-	do
-		{
-		const TUint8* p=aPtr-offset;
-		if (p[match>>16]==c)
-			{	// might be a better match
-			const TUint8* m=aPtr;
-			for (;;)
-				{
-				if (*p++!=*m++)
-					break;
-				if (m<aEnd)
-					continue;
-				return ((m-aPtr)<<16)|offset;
-				}
-			TInt l=m-aPtr-1;
-			if (l>match>>16)
-				{
-				match=(l<<16)|offset;
-				c=m[-1];
-				}
-			}
-		offset=aHash.Next(aPos,offset);
-		} while (offset<=KDeflateMaxDistance);
-	return match;
-	}
-
-const TUint8* MDeflater::DoDeflateL(const TUint8* aBase,const TUint8* aEnd,HDeflateHash& aHash)
-//
-// Apply the deflation algorithm to the data [aBase,aEnd)
-// Return a pointer after the last byte that was deflated (which may not be aEnd)
-//
-	{
-	const TUint8* ptr=aBase;
-	TInt prev=0;		// the previous deflation match
-	do
-		{
-		TInt match=Match(ptr,aEnd,ptr-aBase,aHash);
-// Extra deflation applies two optimisations which double the time taken
-// 1. If we have a match at p, then test for a better match at p+1 before using it
-// 2. When we have a match, add the hash links for all the data which will be skipped 
-		if (match>>16 < prev>>16)
-			{	// use the previous match--it was better
-			TInt len=prev>>16;
-			SegmentL(len,prev-(len<<16));
-			// fill in missing hash entries for better compression
-			const TUint8* e=ptr+len-2;
-			do 
-				{
-				++ptr;
-				if (ptr + 2 < aEnd)
-					aHash.First(ptr,ptr-aBase);
-				} while (ptr<e);
-			prev=0;
-			}
-		else if (match<=(KDeflateMinLength<<16))
-			LitLenL(*ptr);			// no deflation match here
-		else
-			{	// save this match and test the next position
-			if (prev)	// we had a match at ptr-1, but this is better
-				LitLenL(ptr[-1]);
-			prev=match;
-			}
-		++ptr;
-		} while (ptr+KDeflateMinLength-1<aEnd);
-	if (prev)
-		{		// emit the stored match
-		TInt len=prev>>16;
-		SegmentL(len,prev-(len<<16));
-		ptr+=len-1;
-		}
-	return ptr;
-	}
-
-void MDeflater::DeflateL(const TUint8* aBase,TInt aLength)
-//
-// The generic deflation algorithm
-//
-	{
-	const TUint8* end=aBase+aLength;
-	if (aLength>KDeflateMinLength)
-		{	// deflation kicks in if there is enough data
-		HDeflateHash* hash=HDeflateHash::NewLC(aLength);
-		if(hash==NULL)
-			Panic(EHuffmanOutOfMemory);
-
-		aBase=DoDeflateL(aBase,end,*hash);
-		delete hash;
-		}
-	while (aBase<end)					// emit remaining bytes
-		LitLenL(*aBase++);
-	LitLenL(TEncoding::EEos);	// eos marker
-	}
-
-void MDeflater::SegmentL(TInt aLength,TInt aDistance)
-//
-// Turn a (length,offset) pair into the deflation codes+extra bits before calling
-// the specific LitLen(), Offset() and Extra() functions.
-//
-	{
-	aLength-=KDeflateMinLength;
-	TInt extralen=0;
-	TUint len=aLength;
-	while (len>=8)
-		{
-		++extralen;
-		len>>=1;
-		}
-	LitLenL((extralen<<2)+len+TEncoding::ELiterals);
-	if (extralen)
-		ExtraL(extralen,aLength);
-//
-	aDistance--;
-	extralen=0;
-	TUint dist=aDistance;
-	while (dist>=8)
-		{
-		++extralen;
-		dist>>=1;
-		}
-	OffsetL((extralen<<2)+dist);
-	if (extralen)
-		ExtraL(extralen,aDistance);
-	}
-
-// Class TDeflateStats
-//
-// This class analyses the data stream to generate the frequency tables 
-// for the deflation algorithm
-
-inline TDeflateStats::TDeflateStats(TEncoding& aEncoding)
-	:iEncoding(aEncoding)
-	{}
-
-void TDeflateStats::LitLenL(TInt aCode)
-	{
-	++iEncoding.iLitLen[aCode];
-	}
-
-void TDeflateStats::OffsetL(TInt aCode)
-	{
-	++iEncoding.iDistance[aCode];
-	}
-
-void TDeflateStats::ExtraL(TInt,TUint)
-	{}
-
-// Class TDeflater
-//
-// Extends MDeflater to provide huffman encoding of the output
-
-inline TDeflater::TDeflater(TBitOutput& aOutput,const TEncoding& aEncoding)
-//
-// construct for encoding
-//
-	:iOutput(aOutput),iEncoding(aEncoding)
-	{}
-
-void TDeflater::LitLenL(TInt aCode)
-	{
-	iOutput.HuffmanL(iEncoding.iLitLen[aCode]);
-	}
-
-void TDeflater::OffsetL(TInt aCode)
-	{
-	iOutput.HuffmanL(iEncoding.iDistance[aCode]);
-	}
-
-void TDeflater::ExtraL(TInt aLen,TUint aBits)
-	{
-	iOutput.WriteL(aBits,aLen);
-	}
-
-void DoDeflateL(const TUint8* aBuf,TInt aLength,TBitOutput& aOutput,TEncoding& aEncoding)
-	{
-// analyse the data for symbol frequency 
-	TDeflateStats analyser(aEncoding);
-	analyser.DeflateL(aBuf,aLength);
-	
-// generate the required huffman encodings
-	Huffman::HuffmanL(aEncoding.iLitLen,TEncoding::ELitLens,aEncoding.iLitLen);
-	Huffman::HuffmanL(aEncoding.iDistance,TEncoding::EDistances,aEncoding.iDistance);
-
-// Store the encoding table
-	Huffman::ExternalizeL(aOutput,aEncoding.iLitLen,KDeflationCodes);
-
-// generate the tables
-	Huffman::Encoding(aEncoding.iLitLen,TEncoding::ELitLens,aEncoding.iLitLen);
-	Huffman::Encoding(aEncoding.iDistance,TEncoding::EDistances,aEncoding.iDistance);
-
-// now finally deflate the data with the generated encoding
-	TDeflater deflater(aOutput,aEncoding);
-	deflater.DeflateL(aBuf,aLength);
-	aOutput.PadL(1);
-	}
-
-void DeflateL(const TUint8* aBuf, TInt aLength, TBitOutput& aOutput)
-	{
-	TEncoding* encoding=new TEncoding;
-	HMem::FillZ(encoding,sizeof(TEncoding));
-	DoDeflateL(aBuf,aLength,aOutput,*encoding);
-	}
-
+/*
+* Copyright (c) 1998-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* e32tools\petran\Szip\deflate.cpp
+*
+*/
+
+
+#include "deflate.h"
+#include "h_utl.h"
+#include "panic.h"
+
+class HDeflateHash
+	{
+public:
+	inline static HDeflateHash* NewLC(TInt aLinks);
+//
+	inline TInt First(const TUint8* aPtr,TInt aPos);
+	inline TInt Next(TInt aPos,TInt aOffset) const;
+private:
+	inline HDeflateHash();
+	inline static TInt Hash(const TUint8* aPtr);
+private:
+	typedef TUint16 TOffset;
+private:
+	TInt iHash[256];
+	TOffset iOffset[1];	// or more
+	};
+
+class MDeflater
+	{
+public:
+	void DeflateL(const TUint8* aBase,TInt aLength);
+	inline virtual ~MDeflater() { }; 
+private:
+	const TUint8* DoDeflateL(const TUint8* aBase,const TUint8* aEnd,HDeflateHash& aHash);
+	static TInt Match(const TUint8* aPtr,const TUint8* aEnd,TInt aPos,HDeflateHash& aHas);
+	void SegmentL(TInt aLength,TInt aDistance);
+	virtual void LitLenL(TInt aCode) =0;
+	virtual void OffsetL(TInt aCode) =0;
+	virtual void ExtraL(TInt aLen,TUint aBits) =0;
+	};
+
+class TDeflateStats : public MDeflater
+	{
+public:
+	inline TDeflateStats(TEncoding& aEncoding);
+	inline virtual ~TDeflateStats() { } 
+private:
+// from MDeflater
+	void LitLenL(TInt aCode);
+	void OffsetL(TInt aCode);
+	void ExtraL(TInt aLen,TUint aBits);
+private:
+	TEncoding& iEncoding;
+	};
+
+class TDeflater : public MDeflater
+	{
+public:
+	inline TDeflater(TBitOutput& aOutput,const TEncoding& aEncoding);
+	inline virtual ~TDeflater() { }; 
+private:
+// from MDeflater
+	void LitLenL(TInt aCode);
+	void OffsetL(TInt aCode);
+	void ExtraL(TInt aLen,TUint aBits);
+private:
+	TBitOutput& iOutput;
+	const TEncoding& iEncoding;
+	};
+
+
+// Class HDeflateHash
+
+inline HDeflateHash::HDeflateHash()
+	{TInt* p=iHash+256;do *--p=-KDeflateMaxDistance-1; while (p>iHash);}
+    
+inline HDeflateHash* HDeflateHash::NewLC(TInt aLinks)
+	{
+#if __GNUC__ >= 4
+ 	unsigned n = sizeof(TInt) * 256 + sizeof(TOffset) * Min(aLinks, KDeflateMaxDistance);
+ 
+ 	while (n & 0x1f)
+ 	{
+ 		n++;	
+ 	}
+ 
+ 	void* p = ::operator new(n);
+ 
+ 	return new(p) HDeflateHash;
+#else
+   	HDeflateHash *dummy = reinterpret_cast<HDeflateHash *>(0) ;
+	TUint offset = reinterpret_cast<TUint>(&(dummy->iOffset[Min(KDeflateMaxDistance , aLinks)])) ;
+	return new (HMem::Alloc(0,offset)) HDeflateHash;
+#endif
+}
+
+inline TInt HDeflateHash::Hash(const TUint8* aPtr)
+	{
+	TUint x=aPtr[0]|(aPtr[1]<<8)|(aPtr[2]<<16);
+	return (x*KDeflateHashMultiplier)>>KDeflateHashShift;
+	}
+
+inline TInt HDeflateHash::First(const TUint8* aPtr,TInt aPos)
+	{
+	TInt h=Hash(aPtr);
+	TInt offset=Min(aPos-iHash[h],KDeflateMaxDistance<<1);
+	iHash[h]=aPos;
+	iOffset[aPos&(KDeflateMaxDistance-1)]=TOffset(offset);
+	return offset;
+	}
+
+inline TInt HDeflateHash::Next(TInt aPos,TInt aOffset) const
+	{return aOffset+iOffset[(aPos-aOffset)&(KDeflateMaxDistance-1)];}
+
+
+// Class TDeflater
+//
+// generic deflation algorithm, can do either statistics and the encoder
+
+TInt MDeflater::Match(const TUint8* aPtr,const TUint8* aEnd,TInt aPos,HDeflateHash& aHash)
+	{
+	TInt offset=aHash.First(aPtr,aPos);
+	if (offset>KDeflateMaxDistance)
+		return 0;
+	TInt match=0;
+	aEnd=Min(aEnd,aPtr+KDeflateMaxLength);
+	TUint8 c=*aPtr;
+	do
+		{
+		const TUint8* p=aPtr-offset;
+		if (p[match>>16]==c)
+			{	// might be a better match
+			const TUint8* m=aPtr;
+			for (;;)
+				{
+				if (*p++!=*m++)
+					break;
+				if (m<aEnd)
+					continue;
+				return ((m-aPtr)<<16)|offset;
+				}
+			TInt l=m-aPtr-1;
+			if (l>match>>16)
+				{
+				match=(l<<16)|offset;
+				c=m[-1];
+				}
+			}
+		offset=aHash.Next(aPos,offset);
+		} while (offset<=KDeflateMaxDistance);
+	return match;
+	}
+
+const TUint8* MDeflater::DoDeflateL(const TUint8* aBase,const TUint8* aEnd,HDeflateHash& aHash)
+//
+// Apply the deflation algorithm to the data [aBase,aEnd)
+// Return a pointer after the last byte that was deflated (which may not be aEnd)
+//
+	{
+	const TUint8* ptr=aBase;
+	TInt prev=0;		// the previous deflation match
+	do
+		{
+		TInt match=Match(ptr,aEnd,ptr-aBase,aHash);
+// Extra deflation applies two optimisations which double the time taken
+// 1. If we have a match at p, then test for a better match at p+1 before using it
+// 2. When we have a match, add the hash links for all the data which will be skipped 
+		if (match>>16 < prev>>16)
+			{	// use the previous match--it was better
+			TInt len=prev>>16;
+			SegmentL(len,prev-(len<<16));
+			// fill in missing hash entries for better compression
+			const TUint8* e=ptr+len-2;
+			do 
+				{
+				++ptr;
+				if (ptr + 2 < aEnd)
+					aHash.First(ptr,ptr-aBase);
+				} while (ptr<e);
+			prev=0;
+			}
+		else if (match<=(KDeflateMinLength<<16))
+			LitLenL(*ptr);			// no deflation match here
+		else
+			{	// save this match and test the next position
+			if (prev)	// we had a match at ptr-1, but this is better
+				LitLenL(ptr[-1]);
+			prev=match;
+			}
+		++ptr;
+		} while (ptr+KDeflateMinLength-1<aEnd);
+	if (prev)
+		{		// emit the stored match
+		TInt len=prev>>16;
+		SegmentL(len,prev-(len<<16));
+		ptr+=len-1;
+		}
+	return ptr;
+	}
+
+void MDeflater::DeflateL(const TUint8* aBase,TInt aLength)
+//
+// The generic deflation algorithm
+//
+	{
+	const TUint8* end=aBase+aLength;
+	if (aLength>KDeflateMinLength)
+		{	// deflation kicks in if there is enough data
+		HDeflateHash* hash=HDeflateHash::NewLC(aLength);
+		if(hash==NULL)
+			Panic(EHuffmanOutOfMemory);
+
+		aBase=DoDeflateL(aBase,end,*hash);
+		delete hash;
+		}
+	while (aBase<end)					// emit remaining bytes
+		LitLenL(*aBase++);
+	LitLenL(TEncoding::EEos);	// eos marker
+	}
+
+void MDeflater::SegmentL(TInt aLength,TInt aDistance)
+//
+// Turn a (length,offset) pair into the deflation codes+extra bits before calling
+// the specific LitLen(), Offset() and Extra() functions.
+//
+	{
+	aLength-=KDeflateMinLength;
+	TInt extralen=0;
+	TUint len=aLength;
+	while (len>=8)
+		{
+		++extralen;
+		len>>=1;
+		}
+	LitLenL((extralen<<2)+len+TEncoding::ELiterals);
+	if (extralen)
+		ExtraL(extralen,aLength);
+//
+	aDistance--;
+	extralen=0;
+	TUint dist=aDistance;
+	while (dist>=8)
+		{
+		++extralen;
+		dist>>=1;
+		}
+	OffsetL((extralen<<2)+dist);
+	if (extralen)
+		ExtraL(extralen,aDistance);
+	}
+
+// Class TDeflateStats
+//
+// This class analyses the data stream to generate the frequency tables 
+// for the deflation algorithm
+
+inline TDeflateStats::TDeflateStats(TEncoding& aEncoding)
+	:iEncoding(aEncoding)
+	{}
+
+void TDeflateStats::LitLenL(TInt aCode)
+	{
+	++iEncoding.iLitLen[aCode];
+	}
+
+void TDeflateStats::OffsetL(TInt aCode)
+	{
+	++iEncoding.iDistance[aCode];
+	}
+
+void TDeflateStats::ExtraL(TInt,TUint)
+	{}
+
+// Class TDeflater
+//
+// Extends MDeflater to provide huffman encoding of the output
+
+inline TDeflater::TDeflater(TBitOutput& aOutput,const TEncoding& aEncoding)
+//
+// construct for encoding
+//
+	:iOutput(aOutput),iEncoding(aEncoding)
+	{}
+
+void TDeflater::LitLenL(TInt aCode)
+	{
+	iOutput.HuffmanL(iEncoding.iLitLen[aCode]);
+	}
+
+void TDeflater::OffsetL(TInt aCode)
+	{
+	iOutput.HuffmanL(iEncoding.iDistance[aCode]);
+	}
+
+void TDeflater::ExtraL(TInt aLen,TUint aBits)
+	{
+	iOutput.WriteL(aBits,aLen);
+	}
+
+void DoDeflateL(const TUint8* aBuf,TInt aLength,TBitOutput& aOutput,TEncoding& aEncoding)
+	{
+// analyse the data for symbol frequency 
+	TDeflateStats analyser(aEncoding);
+	analyser.DeflateL(aBuf,aLength);
+	
+// generate the required huffman encodings
+	Huffman::HuffmanL(aEncoding.iLitLen,TEncoding::ELitLens,aEncoding.iLitLen);
+	Huffman::HuffmanL(aEncoding.iDistance,TEncoding::EDistances,aEncoding.iDistance);
+
+// Store the encoding table
+	Huffman::ExternalizeL(aOutput,aEncoding.iLitLen,KDeflationCodes);
+
+// generate the tables
+	Huffman::Encoding(aEncoding.iLitLen,TEncoding::ELitLens,aEncoding.iLitLen);
+	Huffman::Encoding(aEncoding.iDistance,TEncoding::EDistances,aEncoding.iDistance);
+
+// now finally deflate the data with the generated encoding
+	TDeflater deflater(aOutput,aEncoding);
+	deflater.DeflateL(aBuf,aLength);
+	aOutput.PadL(1);
+	}
+
+void DeflateL(const TUint8* aBuf, TInt aLength, TBitOutput& aOutput)
+	{
+	TEncoding* encoding=new TEncoding;
+	HMem::FillZ(encoding,sizeof(TEncoding));
+	DoDeflateL(aBuf,aLength,aOutput,*encoding);
+	}
+
--- a/imgtools/imglib/e32image/e32image.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/e32image/e32image.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,861 +1,842 @@
-/*
-* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* e32tools/e32image/e32image.cpp
-* Basic operations on E32Image files which are used by ROMBUILD.
-* These are independent of the original file format from which the
-* E32Image file was derived.
-*
-*/
-
-
-#include <time.h>
-#include <malloc.h>
-#include <string.h>
-#include <stdlib.h>
-#include "h_utl.h"
-
-
-#if defined (__MSVCDOTNET__) || defined(__TOOLS2__)
-#include <fstream>
-#else //!__MSVCDOTNET__
-#include <fstream.h>
-#endif //__MSVCDOTNET__
-
-#include <assert.h>
-#ifndef __LINUX__
-  #include <io.h>
-#endif
-#include "h_ver.h"
-
-// get E32ImageHeader class...
-#define INCLUDE_E32IMAGEHEADER_IMPLEMENTATION
-#define RETURN_FAILURE(_r) return (fprintf(stderr, "line %d\n", __LINE__),_r)
-//#define E32IMAGEHEADER_TRACE(_t) printf _t
-#include "e32image.h"
-
-void DeflateCompress(char* bytes, TInt size, ostream& os);
-void InflateUnCompress(unsigned char* source, int sourcesize, unsigned char* dest, int destsize);
-void CompressPages(TUint8 * bytes, TInt size, ostream &os, CBytePair *aBPE);
-int  DecompressPages(TUint8 * bytes, istream& is, CBytePair *aBPE);
-
-// needed by E32ImageHeaderV::ValidateHeader...
-void Mem::Crc32(TUint32& aCrc, const TAny* aPtr, TInt aLength)
-	{
-	HMem::Crc32(aCrc, aPtr, aLength);
-	}
-
-//
-// E32 Image files
-//
-E32ImageFile::E32ImageFile(CBytePair *aBPE)
-	: iData(NULL), iSize(0), iOrigHdr(NULL), iHdr(NULL), iFileName(NULL)
-#ifndef __LINUX__
-	  , iWideFileName(NULL)
-#endif
-, iError(0), iSource(EE32Image), iOrigHdrOffsetAdj(0), iExportBitMap(0), iBPE(aBPE)
-	{
-        }
-
-E32ImageFile::~E32ImageFile()
-	{
-	free(iData);
-	delete [] iFileName;
-#ifndef __LINUX__
-	delete [] iWideFileName;
-#endif
-	if (iHdr && iHdr != iOrigHdr)
-		delete iHdr;
-	free(iExportBitMap);
-	}
-
-// dummy implementation
-TBool E32ImageFile::Translate(const char*, TUint, TBool, TBool)
-	{
-	return EFalse;
-	}
-
-Int64 timeToInt64(TInt aTime)
-	{
-	aTime-=(30*365*24*60*60+7*24*60*60);	// seconds since midnight Jan 1st, 2000
-	Int64 daysTo2000AD=730497;
-	Int64 t=daysTo2000AD*24*3600+aTime;	// seconds since 0000
-	t=t+3600;								// BST (?)
-	return t*1000000;						// milliseconds
-	}
-
-class TE32ImageUids : public TCheckedUid
-	{
-public:
-	TE32ImageUids(TUint32 aUid1, TUint32 aUid2, TUint32 aUid3) : TCheckedUid(TUidType(TUid::Uid(aUid1), TUid::Uid(aUid2), TUid::Uid(aUid3))) {}
-	TUint Check() { return TCheckedUid::Check(); }
-	};
-
-void E32ImageFile::SetDefaultHeader()
-	{
-	iHdr = (E32ImageHeaderV*)iOrigHdr;
-	iHdr->iUid1 = 0;
-	iHdr->iUid2 = 0;
-	iHdr->iUid3 = 0;
-	iHdr->iHeaderCrc = 0;
-	iHdr->iSignature = 0x434f5045u;
-	iHdr->iModuleVersion = 0x00010000u;
-	iHdr->iCompressionType = 0;
-	iHdr->iToolsVersion = TVersion(MajorVersion, MinorVersion, Build);
-	Int64 time1(timeToInt64(time(0))); 
-	iHdr->iTimeLo=(TUint32)time1;
-	iHdr->iTimeHi=(TUint32)(time1>>32);
-	iHdr->iFlags = KImageHdrFmt_V;
-	iHdr->iCodeSize = 0;
-	iHdr->iDataSize = 0;
-	iHdr->iHeapSizeMin = 0;
-	iHdr->iHeapSizeMax = 0;
-	iHdr->iStackSize = 0;
-	iHdr->iBssSize = 0;
-	iHdr->iEntryPoint = 0;
-	iHdr->iCodeBase = 0;
-	iHdr->iDataBase = 0;
-	iHdr->iDllRefTableCount = 0;
-	iHdr->iExportDirOffset = 0;
-	iHdr->iExportDirCount = 0;
-	iHdr->iTextSize = 0;
-	iHdr->iCodeOffset = 0;
-	iHdr->iDataOffset = 0;
-	iHdr->iImportOffset = 0;
-	iHdr->iCodeRelocOffset = 0;
-	iHdr->iDataRelocOffset = 0;
-	iHdr->iProcessPriority = (TUint16)EPriorityForeground;
-	iHdr->iUncompressedSize = 0;
-	iHdr->iS.iSecureId = 0;
-	iHdr->iS.iVendorId = 0;
-	iHdr->iExceptionDescriptor = 0;
-	iHdr->iSpare2 = 0;
-
-	iHdr->iExportDescSize = 0;
-	iHdr->iExportDescType = KImageHdr_ExpD_NoHoles;
-	iHdr->iExportDesc[0] = 0;
-	}
-
-void E32ImageFile::SetCallEntryPoints(TInt aBool)
-	{
-
-	if (aBool)
-		iHdr->iFlags&=~KImageNoCallEntryPoint;
-	else
-		iHdr->iFlags|=KImageNoCallEntryPoint;
-	}
-
-void E32ImageFile::SetFixedAddress(TInt aBool)
-	{
-
-	if (aBool)
-		iHdr->iFlags|=KImageFixedAddressExe;
-	else
-		iHdr->iFlags&=~KImageFixedAddressExe;
-	}
-
-void E32ImageFile::SetPriority(TProcessPriority aPri)
-	{
-
-	iHdr->iProcessPriority = (TUint16)aPri;
-	}
-
-void E32ImageFile::SetCapability(SCapabilitySet& aCapabilities)
-	{
-	iHdr->iS.iCaps = aCapabilities;
-	}
-
-void E32ImageFile::SetFPU(unsigned int aFPU)
-	{
-	iHdr->iFlags &=~ KImageHWFloatMask;
-
-	if (aFPU == 1)
-		iHdr->iFlags |= KImageHWFloat_VFPv2;
-	}
-
-void E32ImageFile::Adjust(TInt aSize, TBool aAllowShrink)
-//
-// Adjust the size of allocated data and fix the member data
-//
-	{
-
-	TInt asize = ALIGN4(aSize);
-	if (asize == iSize)
-		return;
-	if (iSize == 0)
-		{
-		iSize = asize;
-		iData = (char*)malloc(iSize);
-		memset(iData, 0, iSize);
-		}
-	else if (aAllowShrink || asize > iSize)
-		{
-		TInt oldsize = iSize;
-		iSize = asize;
-		iData = (char*)realloc(iData, iSize);
-		if (iSize > oldsize)
-			memset(iData+oldsize, 0, iSize-oldsize);
-		}
-	if (!iData)
-		iSize = 0;
-	if (iHdr && iHdr == iOrigHdr)
-		iHdr = (E32ImageHeaderV*)iData;
-	iOrigHdr = (E32ImageHeader*)iData;
-	}
-
-TInt E32ImageFile::ReadHeader(ifstream& is)
-	{
-	Adjust(sizeof(E32ImageHeader), EFalse);
-	is.read(iData, sizeof(E32ImageHeader));
-	TInt hdrsz = iOrigHdr->TotalSize();
-	if (hdrsz > 0x10000 || hdrsz <= 0)
-		return KErrCorrupt;	// sanity check
-	if (hdrsz > (TInt)sizeof(E32ImageHeader))
-		{
-		Adjust(hdrsz, EFalse);
-		is.read(iData+sizeof(E32ImageHeader), hdrsz-sizeof(E32ImageHeader));
-		}
-	TUint32 uncompressedSize;
-	TInt r = iOrigHdr->ValidateHeader(iFileSize,uncompressedSize);
-	if (r != KErrNone)
-		{
-		fprintf(stderr, "Integrity check failed %d\n", r);
-		return r;
-		}
-	iHdr = (E32ImageHeaderV*)iOrigHdr;
-	return KErrNone;
-	}
-
-void E32ImageFile::SetStackSize(TInt aSize)
-	{
-	iHdr->iStackSize=aSize;
-	}
-
-void E32ImageFile::SetHeapSizeMin(TInt aSize)
-	{
-	iHdr->iHeapSizeMin=aSize;
-	}
-
-void E32ImageFile::SetHeapSizeMax(TInt aSize)
-	{
-	iHdr->iHeapSizeMax=aSize;
-	}
-
-TUint E32ImageFile::TextOffset()
-//
-// Return the offset of the text section
-//
-	{
-	return 0;
-	}
-
-TUint E32ImageFile::DataOffset()
-//
-// return the offset of the initialised data
-//
-	{
-	return iHdr->iCodeSize;
-	}
-
-TUint E32ImageFile::BssOffset()
-//
-// return the offset from the start of code where the bss is linked
-//
-	{
-	return DataOffset()+iHdr->iDataSize;
-	}
-
-
-TInt E32ImageFile::IsDll()
-//
-//
-//
-	{
-	return iHdr->iFlags&KImageDll;
-	}
-
-
-void E32ImageFile::RelocateSection(char* aPtr, char* aRelocs, TUint aCodeDelta, TUint aDataDelta, char* aImagePtr, TLinAddr** aIATRefs, TBool keepIAT)
-//
-// Relocates the section data at aPtr
-//	
-	{
-
-	TUint codeStart=iHdr->iCodeBase;
-	TUint codeFinish=codeStart+iHdr->iCodeSize;
-	TUint iatStart = aIATRefs ? codeStart+iHdr->iTextSize : 0;
-	TUint iatFinish = aIATRefs ? iatStart+NumberOfImports()*sizeof(TUint) : 0;
-	char* relocs=aRelocs;
-	TUint page=0;
-	TInt size=0;
-	TInt i=((E32RelocSection *)relocs)->iNumberOfRelocs;
-	relocs+=sizeof(E32RelocSection);
-	while (i>0)
-		{
-		if (size>0)
-			{
-			TUint offset=*(TUint16 *)relocs;
-			relocs+=2;
-			if (offset!=0)
-				{ // its a reloc
-				TUint va=page+(offset&0x0fff);
-				TUint relocType=offset&0xf000;
-				TUint *dataptr=(TUint *)(aPtr+va);
-				assert((char *)dataptr < aRelocs);
-				TUint data=*dataptr;
-				if (relocType == KTextRelocType) 
-					*dataptr=data+aCodeDelta; // points to text/rdata section
-				else if (relocType == KDataRelocType)
-					*dataptr=data+aDataDelta;
-				else 
-					{
-					if (relocType != KInferredRelocType)
-						Print(EError,"Unrecognized relocation type %x\n",relocType);
-
-					if (data>=iatStart && data<iatFinish)
-						{
-
-						TUint iatNum = (data-iatStart)/sizeof(TLinAddr);
-
-						// If "keepIAT" is used then the importing instruction must import through the IAT entry,
-						// but otherwise we change the IAT entry to point to the bit of code doing the importing
-						// and do the real fix-up later on in TRomBuilderEntry::FixupImports.
-						// NB: We always want to do this for X86 or data exports dont work.
-						if (keepIAT || (iHdr->iCpuIdentifier & 0x1000) /*denotes X86*/) 
-							*dataptr=data+aCodeDelta; 
-						else 
-							{
-							if ((TUint)aIATRefs[iatNum]>65535)
-								Print(EWarning, "Multiple relocations for IAT entry %d (0x%x, 0x%x)\n",
-										iatNum, aIATRefs[iatNum], dataptr);
-							else
-								aIATRefs[iatNum] = (TLinAddr*)(aImagePtr+va);	// ROM image address of importing pointer					
-							}
-						}
-					else if (data>=codeStart && data<codeFinish)
-						*dataptr=data+aCodeDelta; // points to text/rdata section
-					else
-						*dataptr=data+aDataDelta; // points to data section
-					}
-				--i;
-				}
-			size-=2;
-			}
-		else
-			{ // next page of relocs
-			page=*(TUint *)relocs;
-			relocs+=4;
-			size=*(TUint *)relocs;
-			relocs+=4;
-			size-=8;
-			}
-		}
-	}
-
-void E32ImageFile::SetUids(TUid aUid1, TUid aUid2, TUid aUid3)
-	{
-	iHdr->iUid1=aUid1.iUid;
-	iHdr->iUid2=aUid2.iUid;
-	iHdr->iUid3=aUid3.iUid;
-	}
-
-void E32ImageFile::SetSecureId(TUint32 aId)
-	{
-	((E32ImageHeaderV*)iHdr)->iS.iSecureId = aId;
-	}
-
-void E32ImageFile::SetVendorId(TUint32 aId)
-	{
-	((E32ImageHeaderV*)iHdr)->iS.iVendorId = aId;
-	}
-
-void E32ImageFile::UpdateHeaderCrc()
-	{
-	TE32ImageUids u(iHdr->iUid1, iHdr->iUid2, iHdr->iUid3);
-	iHdr->iUidChecksum = u.Check();
-	TInt hdrsz = iHdr->TotalSize();
-	TInt orighdrsz = iOrigHdr->TotalSize();
-	iHdr->iUncompressedSize = iSize - orighdrsz;
-	iHdr->iHeaderCrc = KImageCrcInitialiser;
-	TUint32 crc = 0;
-	HMem::Crc32(crc, iHdr, hdrsz);
-	iHdr->iHeaderCrc = crc;
-	}
-
-TInt E32ImageFile::NumberOfImports()
-//
-// Return the number of imports made by this image
-//
-	{
-
-	if (iHdr->iDllRefTableCount==0 || iHdr->iImportOffset==0)
-		return 0;
-
-	TUint impfmt = iHdr->ImportFormat();
-	const E32ImportSection* isection = (const E32ImportSection*)(iData + iOrigHdr->iImportOffset);
-	TInt d;
-	TInt nImports = 0;
-	const E32ImportBlock* b = (const E32ImportBlock*)(isection+1);
-	for (d=0; d<iHdr->iDllRefTableCount; d++)
-		{
-		nImports += b->iNumberOfImports;
-		b = b->NextBlock(impfmt);
-		}
-
-	if (impfmt==KImageImpFmt_PE || impfmt==KImageImpFmt_PE2)
-		{
-		TUint *imports=(TUint *)(iData + iOrigHdr->iCodeOffset + iHdr->iTextSize);
-		TInt i=0;
-		while (*imports++)
-			i++;
-		assert(i==nImports);
-		}
-	
-	return nImports;
-	}
-
-// Work out which exports are missing from the export directory
-void E32ImageFile::CreateExportBitMap()
-	{
-	TInt nexp = iOrigHdr->iExportDirCount;
-	TInt memsz = (nexp + 7) >> 3;
-	iExportBitMap = (TUint8*)malloc(memsz);
-	memset(iExportBitMap, 0xff, memsz);
-	TUint* exports = (TUint*)(iData + iOrigHdr->iExportDirOffset);
-	TUint absoluteEntryPoint = iOrigHdr->iEntryPoint + iOrigHdr->iCodeBase;
-	TUint impfmt = iOrigHdr->ImportFormat();
-	TUint hdrfmt = iOrigHdr->HeaderFormat();
-	TUint absentVal = (impfmt == KImageImpFmt_ELF) ? absoluteEntryPoint : iOrigHdr->iEntryPoint;
-	TInt i;
-	iMissingExports = 0;
-	for (i=0; i<nexp; ++i)
-		{
-		if (exports[i] == absentVal)
-			{
-			iExportBitMap[i>>3] &= ~(1u << (i & 7));
-			++iMissingExports;
-			}
-		}
-	if (hdrfmt < KImageHdrFmt_V && iMissingExports)
-		{
-		fprintf(stderr, "Bad exports\n");
-		exit(999);
-		}
-	}
-
-// Append an export description to the E32ImageHeader if necessary
-void E32ImageFile::AddExportDescription()
-	{
-	if (iMissingExports == 0)
-		return;	// nothing to do
-	TInt nexp = iOrigHdr->iExportDirCount;
-	TInt memsz = (nexp + 7) >> 3;	// size of complete bitmap
-	TInt mbs = (memsz + 7) >> 3;	// size of meta-bitmap
-	TInt nbytes = 0;
-	TInt i;
-	for (i=0; i<memsz; ++i)
-		if (iExportBitMap[i] != 0xff)
-			++nbytes;				// number of groups of 8
-	TUint8 edt = KImageHdr_ExpD_FullBitmap;
-	TInt extra_space = memsz - 1;
-	if (mbs + nbytes < memsz)
-		{
-		edt = KImageHdr_ExpD_SparseBitmap8;
-		extra_space = mbs + nbytes - 1;
-		}
-	extra_space = (extra_space + sizeof(TUint) - 1) &~ (sizeof(TUint) - 1);
-	TInt hdrsz = sizeof(E32ImageHeaderV) + extra_space;
-	iHdr = (E32ImageHeaderV*)malloc(hdrsz);
-	memcpy(iHdr, iOrigHdr, sizeof(E32ImageHeaderV));
-	iHdr->iExportDescType = edt;
-	if (edt == KImageHdr_ExpD_FullBitmap)
-		{
-		iHdr->iExportDescSize = (TUint16)memsz;
-		memcpy(iHdr->iExportDesc, iExportBitMap, memsz);
-		}
-	else
-		{
-		iHdr->iExportDescSize = (TUint16)(mbs + nbytes);
-		memset(iHdr->iExportDesc, 0, extra_space + 1);
-		TUint8* mptr = iHdr->iExportDesc;
-		TUint8* gptr = mptr + mbs;
-		for (i=0; i<memsz; ++i)
-			{
-			if (iExportBitMap[i] != 0xff)
-				{
-				mptr[i>>3] |= (1u << (i&7));
-				*gptr++ = iExportBitMap[i];
-				}
-			}
-		}
-	iHdr->iCodeOffset += extra_space;
-	if (iHdr->iDataOffset)
-		iHdr->iDataOffset += extra_space;
-	if (iHdr->iCodeRelocOffset)
-		iHdr->iCodeRelocOffset += extra_space;
-	if (iHdr->iDataRelocOffset)
-		iHdr->iDataRelocOffset += extra_space;
-	if (iHdr->iImportOffset)
-		iHdr->iImportOffset += extra_space;
-	if (iHdr->iExportDirOffset)
-		iHdr->iExportDirOffset += extra_space;
-	}
-
-// Check the export description is consistent with the export directory
-TInt E32ImageFile::CheckExportDescription()
-	{
-	TUint hdrfmt = iOrigHdr->HeaderFormat();
-	if (hdrfmt < KImageHdrFmt_V && iMissingExports)
-		return KErrCorrupt;
-	if (iHdr->iExportDescType == KImageHdr_ExpD_NoHoles)
-		{
-		return iMissingExports ? KErrCorrupt : KErrNone;
-		}
-	TInt nexp = iOrigHdr->iExportDirCount;
-	TInt memsz = (nexp + 7) >> 3;	// size of complete bitmap
-	TInt mbs = (memsz + 7) >> 3;	// size of meta-bitmap
-	TInt eds = iHdr->iExportDescSize;
-	if (iHdr->iExportDescType == KImageHdr_ExpD_FullBitmap)
-		{
-		if (eds != memsz)
-			return KErrCorrupt;
-		if (memcmp(iHdr->iExportDesc, iExportBitMap, eds) == 0)
-			return KErrNone;
-		return KErrCorrupt;
-		}
-	if (iHdr->iExportDescType != KImageHdr_ExpD_SparseBitmap8)
-		return KErrNotSupported;
-	TInt nbytes = 0;
-	TInt i;
-	for (i=0; i<memsz; ++i)
-		if (iExportBitMap[i] != 0xff)
-			++nbytes;				// number of groups of 8
-	TInt exp_extra = mbs + nbytes;
-	if (eds != exp_extra)
-		return KErrCorrupt;
-	const TUint8* mptr = iHdr->iExportDesc;
-	const TUint8* gptr = mptr + mbs;
-	for (i=0; i<memsz; ++i)
-		{
-		TUint mbit = mptr[i>>3] & (1u << (i&7));
-		if (iExportBitMap[i] != 0xff)
-			{
-			if (!mbit || *gptr++ != iExportBitMap[i])
-				return KErrCorrupt;
-			}
-		else if (mbit)
-			return KErrCorrupt;
-		}
-	return KErrNone;
-	}
-
-
-TInt E32ImageFile::Validate()
-	{
-	TInt orighdrsz = iOrigHdr->TotalSize();
-	TInt r = iHdr->ValidateWholeImage(iData+orighdrsz,iSize-orighdrsz);
-	if(r!=KErrNone)
-		return r;
-	return r;
-	}
-
-
-ostream& operator<<(ostream& os, const E32ImageFile& aImage)
-//
-// Output an E32ImageFile
-//
-	{
-	E32ImageHeaderV* h = aImage.iHdr;
-	TUint hdrfmt = h->HeaderFormat();
-	if (hdrfmt != KImageHdrFmt_V)
-		return os;	// don't generate old binary formats
-	TInt hdrsz = h->TotalSize();
-	TInt orighdrsz = aImage.iOrigHdr->TotalSize();
-
-	os.write((const char*)aImage.iHdr, hdrsz);
-
-	TUint compression = h->CompressionType();
-	if (compression == KUidCompressionDeflate)
-		{
-		int srcsize = aImage.iSize - orighdrsz;
-		DeflateCompress(aImage.iData + orighdrsz, srcsize, os);
-		}
-	else if (compression == KUidCompressionBytePair)
-		{
-		// Compress and write out code part
-		int srcStart = orighdrsz;
-		CompressPages( (TUint8*)aImage.iData + srcStart, aImage.iOrigHdr->iCodeSize, os, aImage.iBPE);
-		
-		
-		// Compress and write out data part
-		srcStart += aImage.iOrigHdr->iCodeSize;
-		int srcLen = aImage.iSize - srcStart;
-
-		CompressPages((TUint8*)aImage.iData + srcStart, srcLen, os, aImage.iBPE);		
-
-		}
-	else if (compression == KFormatNotCompressed)
-		{
-		int srcsize = aImage.iSize - orighdrsz;
-		os.write(aImage.iData + orighdrsz, srcsize); // image not to be compressed
-		}
-	return os;
-	}
-
-ifstream& operator>>(ifstream& is, E32ImageFile& aImage)
-//
-// Input an E32ImageFile
-//
-	{
-	aImage.iError = aImage.ReadHeader(is);
-	if (aImage.iError != KErrNone)
-		return is;
-	E32ImageHeader* oh = aImage.iOrigHdr;
-	TInt orighdrsz = oh->TotalSize();
-	int remainder = aImage.iSize - orighdrsz;
-	TUint compression = oh->CompressionType();
-	if (compression == 0)
-		{
-		is.read(aImage.iData + orighdrsz, remainder);
-		}
-	else if (compression == KUidCompressionDeflate)
-		{ //Uncompress
-		aImage.iError = KErrNoMemory;
-		unsigned int uncompsize = ((E32ImageHeaderComp*)aImage.iOrigHdr)->iUncompressedSize;
-		aImage.Adjust(uncompsize + orighdrsz);
-		if (aImage.iData==NULL)
-			return is;
-		oh = aImage.iOrigHdr;
-		unsigned char* compressedData = new unsigned char[remainder];
-		if (compressedData==NULL)
-			return is;
-		is.read(reinterpret_cast<char *>(compressedData), remainder);
-		unsigned int destsize = uncompsize;
-		InflateUnCompress( compressedData, remainder, (unsigned char*)(aImage.iData + orighdrsz), destsize);
-		if (destsize != uncompsize)
-			Print(EWarning, "Inconsistent sizes discovered during uncompression.\n");
-		delete [] compressedData;
-		if ((TUint)orighdrsz > oh->iCodeOffset)
-			{
-			// need to adjust code offsets in original
-			aImage.iOrigHdrOffsetAdj = (TUint)orighdrsz - oh->iCodeOffset;
-			aImage.OffsetAdjust(oh->iCodeOffset);
-			aImage.OffsetAdjust(oh->iDataOffset);
-			aImage.OffsetAdjust(oh->iCodeRelocOffset);
-			aImage.OffsetAdjust(oh->iDataRelocOffset);
-			aImage.OffsetAdjust(oh->iImportOffset);
-			aImage.OffsetAdjust(oh->iExportDirOffset);
-			}
-		aImage.iError = KErrNone;
-		}
-	else if(compression == KUidCompressionBytePair)
-	{ // Uncompress
-		aImage.iError = KErrNoMemory;
-		unsigned int uncompsize = ((E32ImageHeaderComp*)aImage.iOrigHdr)->iUncompressedSize;
-		aImage.Adjust(uncompsize + orighdrsz);
-		if (aImage.iData==NULL)
-			return is;
-		oh = aImage.iOrigHdr;
-
-		// Read and decompress code part of the image
-
-		unsigned int uncompressedCodeSize = DecompressPages((TUint8 *) (aImage.iData + orighdrsz), is, aImage.iBPE);
-
-		
-		// Read and decompress data part of the image
-
-		unsigned int uncompressedDataSize = DecompressPages((TUint8 *) (aImage.iData + orighdrsz + uncompressedCodeSize), is, aImage.iBPE);
-
-		if (uncompressedCodeSize + uncompressedDataSize != uncompsize)
-			Print(EWarning, "Inconsistent sizes discovered during uncompression.\n");
-
-		if ((TUint)orighdrsz > oh->iCodeOffset)
-			{
-			// need to adjust code offsets in original
-			aImage.iOrigHdrOffsetAdj = (TUint)orighdrsz - oh->iCodeOffset;
-			aImage.OffsetAdjust(oh->iCodeOffset);
-			aImage.OffsetAdjust(oh->iDataOffset);
-			aImage.OffsetAdjust(oh->iCodeRelocOffset);
-			aImage.OffsetAdjust(oh->iDataRelocOffset);
-			aImage.OffsetAdjust(oh->iImportOffset);
-			aImage.OffsetAdjust(oh->iExportDirOffset);
-			}
-		aImage.iError = KErrNone;
-	}
-	aImage.CreateExportBitMap();
-	return is;
-	}
-
-TInt E32ImageFile::IsE32ImageFile(char *aFileName)
-	{
-
-#ifdef __LINUX__
-	E32ImageFile f;
-	struct stat buf;
-	if (stat(aFileName, &buf) < 0) 
-		{
-		return FALSE;
-		}
-	f.iFileSize = buf.st_size;
-#else
-	_finddata_t fileinfo;
-	int ret=_findfirst((char *)aFileName,&fileinfo);
-	if (ret==-1) 
-		return FALSE;
-	E32ImageFile f;
-	f.iFileSize = fileinfo.size;
-#endif
-	ifstream ifile(aFileName, ios::in | ios::binary);
-	if(!ifile.is_open())
-		return FALSE;
-	TInt r = f.ReadHeader(ifile);
-	ifile.close();
-	return (r == KErrNone);
-	}
-
-TInt E32ImageFile::IsValid()
-	{
-	return (iError == KErrNone);
-	}
-
-TInt E32ImageFile::Open(const char* aFileName)
-//
-// Open an E32 Image file
-//
-	{
-#ifdef __LINUX__
-	struct stat buf;
-	if (stat(aFileName, &buf) < 0) 
-		{
-		Print(EError,"Cannot open %s for input.\n",aFileName);
-		return 1;
-		}
-	iFileSize = buf.st_size;
-#else
-	_finddata_t fileinfo;
-	int ret=_findfirst((char *)aFileName,&fileinfo);
-	if (ret==-1) 
-		{
-		Print(EError,"Cannot open %s for input.\n",aFileName);
-		return 1;
-		}
-	iFileSize = fileinfo.size;
-#endif
-	Adjust(iFileSize);
-	ifstream ifile((char *)aFileName, ios::in | ios::binary);
-	if(!ifile.is_open())
-		{
-		Print(EError,"Cannot open %s for input.\n",aFileName);
-		return 1;
-		}
-	ifile >> *this;
-	ifile.close();
-	if (iError != KErrNone)
-		return iError;
-	iFileName=strdup((char *)aFileName);
-	if (iFileName==NULL)
-		return KErrNoMemory;
-	return KErrNone;
-	}
-
-#ifndef __LINUX__
-TInt E32ImageFile::Open(const wchar_t* aFileName)
-//
-// Open an E32 Image file
-//
-	{
-	_wfinddata_t fileinfo;
-	int ret=_wfindfirst(aFileName,&fileinfo);
-	if (ret==-1) 
-		{
-		Print(EError,"Cannot open %ls for input.\n",aFileName);
-		return 1;
-		}
-	iFileSize = fileinfo.size;
-	Adjust(iFileSize);
-
-	FILE* file = _wfopen(aFileName, L"rb");
-
-	if(!file)
-		{
-		Print(EError,"Cannot open %ls for input.\n",aFileName);
-		return 1;
-		}
-	
-	#if defined(__TOOLS2__) || defined(__MSVCDOTNET__)
-	char tmp[100];  				// Convert wide character name to char *, then open a file.
-	wcstombs(tmp,aFileName,100);
-	ifstream ifile(tmp, ios::in | ios::binary);
-	#else
-	ifstream ifile(fileno(file));
-	#endif
-	
-	if(!ifile.is_open())
-		{
-		Print(EError,"Cannot open %ls for input,\n",aFileName);
-		return 1;
-		}
-		
-	ifile >> *this;
-	ifile.close();
-	fclose(file);
-	if (iError != KErrNone)
-		return iError;
-	iWideFileName=wcsdup(aFileName);
-	if (iWideFileName==NULL)
-		return KErrNoMemory;
-	return KErrNone;
-	}
-#endif
-
-TUint E32ImageFile::VaOfOrdinal(TUint aOrdinal)
-// return the offset of the exported symbol
-	{
-	TUint* exportdir = (TUint*)(iData + iOrigHdr->iExportDirOffset);
-	return exportdir[aOrdinal-KOrdinalBase];
-	}
-
-// Determine the type of entry point in this module and set the flags
-// in the E32Image header accordingly.
-TInt E32ImageFile::DetermineEntryPointType()
-	{
-	TUint cpu = iHdr->CpuIdentifier();
-	if (cpu != ECpuArmV4 && cpu != ECpuArmV5)
-		return KErrNone;	// if not ARM, leave EPT as 0
-	TUint epOffset = iHdr->iEntryPoint;
-	if (epOffset & 3)
-		return KErrNone;	// if entry point not 4 byte aligned, must be old style
-	TUint fileOffset = epOffset + iHdr->iCodeOffset;
-	if (fileOffset+4 > (TUint)iSize)
-		return KErrCorrupt;	// entry point is past the end of the file??
-	TInt ept = 0;			// old style if first instruction not recognised
-	unsigned char* p = (unsigned char*)iData + fileOffset + 4;
-	TUint32 x = *--p;
-	x<<=8;
-	x|=*--p;
-	x<<=8;
-	x|=*--p;
-	x<<=8;
-	x|=*--p;
-	if ((x & 0xffffff00) == 0xe31f0000)
-		{
-		// starts with tst pc, #n - new entry point
-		ept = (x & 0xff) + 1;
-		}
-	if (ept>7)
-		return KErrNotSupported;
-	iHdr->iFlags |= (ept<<KImageEptShift);
-	return KErrNone;
-	}
-
+/*
+* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* e32tools/e32image/e32image.cpp
+* Basic operations on E32Image files which are used by ROMBUILD.
+* These are independent of the original file format from which the
+* E32Image file was derived.
+*
+*/
+
+#include "h_utl.h"
+#include <time.h>
+#include <malloc.h>
+#include <string.h>
+#include <stdlib.h>
+
+
+
+
+#if defined(__TOOLS2__) || defined(__MSVCDOTNET__) 
+#define IOS_BASE ios_base
+#include <fstream>
+#else
+#define IOS_BASE ios
+#include <fstream.h>
+#endif 
+#include <assert.h>
+#ifndef __LINUX__
+  #include <io.h>
+#endif
+#include "h_ver.h"
+
+// get E32ImageHeader class...
+#define INCLUDE_E32IMAGEHEADER_IMPLEMENTATION
+#define RETURN_FAILURE(_r) return (fprintf(stderr, "line %d\n", __LINE__),_r)
+//#define E32IMAGEHEADER_TRACE(_t) printf _t
+#include "e32image.h"
+
+void DeflateCompress(char* bytes, TInt size, ostream& os);
+void InflateUnCompress(unsigned char* source, int sourcesize, unsigned char* dest, int destsize);
+void CompressPages(TUint8 * bytes, TInt size, ostream &os, CBytePair *aBPE);
+int  DecompressPages(TUint8 * bytes, istream& is, CBytePair *aBPE);
+
+// needed by E32ImageHeaderV::ValidateHeader...
+void Mem::Crc32(TUint32& aCrc, const TAny* aPtr, TInt aLength)
+	{
+	HMem::Crc32(aCrc, aPtr, aLength);
+	}
+
+//
+// E32 Image files
+//
+E32ImageFile::E32ImageFile(CBytePair *aBPE)
+	: iData(NULL), iSize(0), iOrigHdr(NULL), iHdr(NULL), iFileName(NULL)
+#ifndef __LINUX__
+	  , iWideFileName(NULL)
+#endif
+, iError(0), iSource(EE32Image), iOrigHdrOffsetAdj(0), iExportBitMap(0), iBPE(aBPE)
+	{
+}
+
+E32ImageFile::~E32ImageFile(){
+	if(iData){
+		free(iData);
+		iData = 0 ;
+	}
+	if (iHdr && iHdr != iOrigHdr){
+		delete iHdr;
+		iHdr = 0 ;
+	}
+	if(iExportBitMap){
+		delete []iExportBitMap;
+		iExportBitMap = 0 ;
+	}
+	if(iFileName){
+		delete []iFileName ;
+		iFileName = 0;
+	}
+#ifndef __LINUX__
+    if(iWideFileName){
+		delete []iWideFileName ;
+		iWideFileName = 0;
+	}
+#endif
+}
+
+// dummy implementation
+TBool E32ImageFile::Translate(const char*, TUint, TBool, TBool)
+	{
+	return EFalse;
+	}
+
+Int64 timeToInt64(TInt aTime)
+	{
+	aTime-=(30*365*24*60*60+7*24*60*60);	// seconds since midnight Jan 1st, 2000
+	Int64 daysTo2000AD=730497;
+	Int64 t=daysTo2000AD*24*3600+aTime;	// seconds since 0000
+	t=t+3600;								// BST (?)
+	return t*1000000;						// milliseconds
+	}
+
+class TE32ImageUids : public TCheckedUid
+	{
+public:
+	TE32ImageUids(TUint32 aUid1, TUint32 aUid2, TUint32 aUid3) : TCheckedUid(TUidType(TUid::Uid(aUid1), TUid::Uid(aUid2), TUid::Uid(aUid3))) {}
+	TUint Check() { return TCheckedUid::Check(); }
+	};
+
+void E32ImageFile::SetDefaultHeader()
+	{
+	iHdr = (E32ImageHeaderV*)iOrigHdr;
+	iHdr->iUid1 = 0;
+	iHdr->iUid2 = 0;
+	iHdr->iUid3 = 0;
+	iHdr->iHeaderCrc = 0;
+	iHdr->iSignature = 0x434f5045u;
+	iHdr->iModuleVersion = 0x00010000u;
+	iHdr->iCompressionType = 0;
+	iHdr->iToolsVersion = TVersion(MajorVersion, MinorVersion, Build);
+	Int64 time1(timeToInt64(time(0))); 
+	iHdr->iTimeLo=(TUint32)time1;
+	iHdr->iTimeHi=(TUint32)(time1>>32);
+	iHdr->iFlags = KImageHdrFmt_V;
+	iHdr->iCodeSize = 0;
+	iHdr->iDataSize = 0;
+	iHdr->iHeapSizeMin = 0;
+	iHdr->iHeapSizeMax = 0;
+	iHdr->iStackSize = 0;
+	iHdr->iBssSize = 0;
+	iHdr->iEntryPoint = 0;
+	iHdr->iCodeBase = 0;
+	iHdr->iDataBase = 0;
+	iHdr->iDllRefTableCount = 0;
+	iHdr->iExportDirOffset = 0;
+	iHdr->iExportDirCount = 0;
+	iHdr->iTextSize = 0;
+	iHdr->iCodeOffset = 0;
+	iHdr->iDataOffset = 0;
+	iHdr->iImportOffset = 0;
+	iHdr->iCodeRelocOffset = 0;
+	iHdr->iDataRelocOffset = 0;
+	iHdr->iProcessPriority = (TUint16)EPriorityForeground;
+	iHdr->iUncompressedSize = 0;
+	iHdr->iS.iSecureId = 0;
+	iHdr->iS.iVendorId = 0;
+	iHdr->iExceptionDescriptor = 0;
+	iHdr->iSpare2 = 0;
+
+	iHdr->iExportDescSize = 0;
+	iHdr->iExportDescType = KImageHdr_ExpD_NoHoles;
+	iHdr->iExportDesc[0] = 0;
+	}
+
+void E32ImageFile::SetCallEntryPoints(TInt aBool)
+	{
+
+	if (aBool)
+		iHdr->iFlags&=~KImageNoCallEntryPoint;
+	else
+		iHdr->iFlags|=KImageNoCallEntryPoint;
+	}
+
+void E32ImageFile::SetFixedAddress(TInt aBool)
+	{
+
+	if (aBool)
+		iHdr->iFlags|=KImageFixedAddressExe;
+	else
+		iHdr->iFlags&=~KImageFixedAddressExe;
+	}
+
+void E32ImageFile::SetPriority(TProcessPriority aPri)
+	{
+
+	iHdr->iProcessPriority = (TUint16)aPri;
+	}
+
+void E32ImageFile::SetCapability(SCapabilitySet& aCapabilities)
+	{
+	iHdr->iS.iCaps = aCapabilities;
+	}
+
+void E32ImageFile::SetFPU(unsigned int aFPU)
+	{
+	iHdr->iFlags &=~ KImageHWFloatMask;
+
+	if (aFPU == 1)
+		iHdr->iFlags |= KImageHWFloat_VFPv2;
+	}
+
+void E32ImageFile::Adjust(TInt aSize, TBool aAllowShrink)
+//
+// Adjust the size of allocated data and fix the member data
+//
+	{
+
+	TInt asize = ALIGN4(aSize);
+	if (asize == iSize)
+		return;
+	if (iSize == 0)
+		{
+		iSize = asize;
+		iData = (char*)malloc(iSize);
+		memset(iData, 0, iSize);
+		}
+	else if (aAllowShrink || asize > iSize)
+		{
+		TInt oldsize = iSize;
+		iSize = asize;
+		iData = (char*)realloc(iData, iSize);
+		if (iSize > oldsize)
+			memset(iData+oldsize, 0, iSize-oldsize);
+		}
+	if (!iData)
+		iSize = 0;
+	if (iHdr && iHdr == iOrigHdr)
+		iHdr = (E32ImageHeaderV*)iData;
+	iOrigHdr = (E32ImageHeader*)iData;
+	}
+
+TInt E32ImageFile::ReadHeader(ifstream& is)
+	{
+	Adjust(sizeof(E32ImageHeader), EFalse);
+	is.read(iData, sizeof(E32ImageHeader));
+	TInt hdrsz = iOrigHdr->TotalSize();
+	if (hdrsz > 0x10000 || hdrsz <= 0)
+		return KErrCorrupt;	// sanity check
+	if (hdrsz > (TInt)sizeof(E32ImageHeader))
+		{
+		Adjust(hdrsz, EFalse);
+		is.read(iData+sizeof(E32ImageHeader), hdrsz-sizeof(E32ImageHeader));
+		}
+	TUint32 uncompressedSize;
+	TInt r = iOrigHdr->ValidateHeader(iFileSize,uncompressedSize);
+	if (r != KErrNone)
+		{
+		fprintf(stderr, "Integrity check failed %d\n", r);
+		return r;
+		}
+	iHdr = (E32ImageHeaderV*)iOrigHdr;
+	return KErrNone;
+	}
+
+void E32ImageFile::SetStackSize(TInt aSize)
+	{
+	iHdr->iStackSize=aSize;
+	}
+
+void E32ImageFile::SetHeapSizeMin(TInt aSize)
+	{
+	iHdr->iHeapSizeMin=aSize;
+	}
+
+void E32ImageFile::SetHeapSizeMax(TInt aSize)
+	{
+	iHdr->iHeapSizeMax=aSize;
+	}
+
+TUint E32ImageFile::TextOffset()
+//
+// Return the offset of the text section
+//
+	{
+	return 0;
+	}
+
+TUint E32ImageFile::DataOffset()
+//
+// return the offset of the initialised data
+//
+	{
+	return iHdr->iCodeSize;
+	}
+
+TUint E32ImageFile::BssOffset()
+//
+// return the offset from the start of code where the bss is linked
+//
+	{
+	return DataOffset()+iHdr->iDataSize;
+	}
+
+
+TInt E32ImageFile::IsDll()
+//
+//
+//
+	{
+	return iHdr->iFlags&KImageDll;
+	}
+
+
+void E32ImageFile::RelocateSection(char* aPtr, char* aRelocs, TUint aCodeDelta, TUint aDataDelta, char* aImagePtr, TLinAddr** aIATRefs, TBool keepIAT)
+//
+// Relocates the section data at aPtr
+//	
+	{
+
+	TUint codeStart=iHdr->iCodeBase;
+	TUint codeFinish=codeStart+iHdr->iCodeSize;
+	TUint iatStart = aIATRefs ? codeStart+iHdr->iTextSize : 0;
+	TUint iatFinish = aIATRefs ? iatStart+NumberOfImports()*sizeof(TUint) : 0;
+	char* relocs=aRelocs;
+	TUint page=0;
+	TInt size=0;
+	TInt i=((E32RelocSection *)relocs)->iNumberOfRelocs;
+	relocs+=sizeof(E32RelocSection);
+	while (i>0)
+		{
+		if (size>0)
+			{
+			TUint offset=*(TUint16 *)relocs;
+			relocs+=2;
+			if (offset!=0)
+				{ // its a reloc
+				TUint va=page+(offset&0x0fff);
+				TUint relocType=offset&0xf000;
+				TUint *dataptr=(TUint *)(aPtr+va);
+				assert((char *)dataptr < aRelocs);
+				TUint data=*dataptr;
+				if (relocType == KTextRelocType) 
+					*dataptr=data+aCodeDelta; // points to text/rdata section
+				else if (relocType == KDataRelocType)
+					*dataptr=data+aDataDelta;
+				else 
+					{
+					if (relocType != KInferredRelocType)
+						Print(EError,"Unrecognized relocation type %x\n",relocType);
+
+					if (data>=iatStart && data<iatFinish)
+						{
+
+						TUint iatNum = (data-iatStart)/sizeof(TLinAddr);
+
+						// If "keepIAT" is used then the importing instruction must import through the IAT entry,
+						// but otherwise we change the IAT entry to point to the bit of code doing the importing
+						// and do the real fix-up later on in TRomBuilderEntry::FixupImports.
+						// NB: We always want to do this for X86 or data exports dont work.
+						if (keepIAT || (iHdr->iCpuIdentifier & 0x1000) /*denotes X86*/) 
+							*dataptr=data+aCodeDelta; 
+						else 
+							{
+							if ((TUint)aIATRefs[iatNum]>65535)
+								Print(EWarning, "Multiple relocations for IAT entry %d (0x%x, 0x%x)\n",
+										iatNum, aIATRefs[iatNum], dataptr);
+							else
+								aIATRefs[iatNum] = (TLinAddr*)(aImagePtr+va);	// ROM image address of importing pointer					
+							}
+						}
+					else if (data>=codeStart && data<codeFinish)
+						*dataptr=data+aCodeDelta; // points to text/rdata section
+					else
+						*dataptr=data+aDataDelta; // points to data section
+					}
+				--i;
+				}
+			size-=2;
+			}
+		else
+			{ // next page of relocs
+			page=*(TUint *)relocs;
+			relocs+=4;
+			size=*(TUint *)relocs;
+			relocs+=4;
+			size-=8;
+			}
+		}
+	}
+
+void E32ImageFile::SetUids(TUid aUid1, TUid aUid2, TUid aUid3)
+	{
+	iHdr->iUid1=aUid1.iUid;
+	iHdr->iUid2=aUid2.iUid;
+	iHdr->iUid3=aUid3.iUid;
+	}
+
+void E32ImageFile::SetSecureId(TUint32 aId)
+	{
+	((E32ImageHeaderV*)iHdr)->iS.iSecureId = aId;
+	}
+
+void E32ImageFile::SetVendorId(TUint32 aId)
+	{
+	((E32ImageHeaderV*)iHdr)->iS.iVendorId = aId;
+	}
+
+void E32ImageFile::UpdateHeaderCrc()
+	{
+	TE32ImageUids u(iHdr->iUid1, iHdr->iUid2, iHdr->iUid3);
+	iHdr->iUidChecksum = u.Check();
+	TInt hdrsz = iHdr->TotalSize();
+	TInt orighdrsz = iOrigHdr->TotalSize();
+	iHdr->iUncompressedSize = iSize - orighdrsz;
+	iHdr->iHeaderCrc = KImageCrcInitialiser;
+	TUint32 crc = 0;
+	HMem::Crc32(crc, iHdr, hdrsz);
+	iHdr->iHeaderCrc = crc;
+	}
+
+TInt E32ImageFile::NumberOfImports()
+//
+// Return the number of imports made by this image
+//
+	{
+
+	if (iHdr->iDllRefTableCount==0 || iHdr->iImportOffset==0)
+		return 0;
+
+	TUint impfmt = iHdr->ImportFormat();
+	const E32ImportSection* isection = (const E32ImportSection*)(iData + iOrigHdr->iImportOffset);
+	TInt d;
+	TInt nImports = 0;
+	const E32ImportBlock* b = (const E32ImportBlock*)(isection+1);
+	for (d=0; d<iHdr->iDllRefTableCount; d++)
+		{
+		nImports += b->iNumberOfImports;
+		b = b->NextBlock(impfmt);
+		}
+
+	if (impfmt==KImageImpFmt_PE || impfmt==KImageImpFmt_PE2)
+		{
+		TUint *imports=(TUint *)(iData + iOrigHdr->iCodeOffset + iHdr->iTextSize);
+		TInt i=0;
+		while (*imports++)
+			i++;
+		assert(i==nImports);
+		}
+	
+	return nImports;
+	}
+
+// Work out which exports are missing from the export directory
+void E32ImageFile::CreateExportBitMap()
+	{
+	TInt nexp = iOrigHdr->iExportDirCount;
+	TInt memsz = (nexp + 7) >> 3;
+	iExportBitMap = new TUint8[memsz];
+	memset(iExportBitMap, 0xff, memsz);
+	TUint* exports = (TUint*)(iData + iOrigHdr->iExportDirOffset);
+	TUint absoluteEntryPoint = iOrigHdr->iEntryPoint + iOrigHdr->iCodeBase;
+	TUint impfmt = iOrigHdr->ImportFormat();
+	TUint hdrfmt = iOrigHdr->HeaderFormat();
+	TUint absentVal = (impfmt == KImageImpFmt_ELF) ? absoluteEntryPoint : iOrigHdr->iEntryPoint;
+	TInt i;
+	iMissingExports = 0;
+	for (i=0; i<nexp; ++i)
+		{
+		if (exports[i] == absentVal)
+			{
+			iExportBitMap[i>>3] &= ~(1u << (i & 7));
+			++iMissingExports;
+			}
+		}
+	if (hdrfmt < KImageHdrFmt_V && iMissingExports)
+		{
+		fprintf(stderr, "Bad exports\n");
+		exit(999);
+		}
+	}
+
+// Append an export description to the E32ImageHeader if necessary
+void E32ImageFile::AddExportDescription()
+	{
+	if (iMissingExports == 0)
+		return;	// nothing to do
+	TInt nexp = iOrigHdr->iExportDirCount;
+	TInt memsz = (nexp + 7) >> 3;	// size of complete bitmap
+	TInt mbs = (memsz + 7) >> 3;	// size of meta-bitmap
+	TInt nbytes = 0;
+	TInt i;
+	for (i=0; i<memsz; ++i)
+		if (iExportBitMap[i] != 0xff)
+			++nbytes;				// number of groups of 8
+	TUint8 edt = KImageHdr_ExpD_FullBitmap;
+	TInt extra_space = memsz - 1;
+	if (mbs + nbytes < memsz)
+		{
+		edt = KImageHdr_ExpD_SparseBitmap8;
+		extra_space = mbs + nbytes - 1;
+		}
+	extra_space = (extra_space + sizeof(TUint) - 1) &~ (sizeof(TUint) - 1);
+	TInt hdrsz = sizeof(E32ImageHeaderV) + extra_space;
+	iHdr = (E32ImageHeaderV*)malloc(hdrsz);
+	memcpy(iHdr, iOrigHdr, sizeof(E32ImageHeaderV));
+	iHdr->iExportDescType = edt;
+	if (edt == KImageHdr_ExpD_FullBitmap)
+		{
+		iHdr->iExportDescSize = (TUint16)memsz;
+		memcpy(iHdr->iExportDesc, iExportBitMap, memsz);
+		}
+	else
+		{
+		iHdr->iExportDescSize = (TUint16)(mbs + nbytes);
+		memset(iHdr->iExportDesc, 0, extra_space + 1);
+		TUint8* mptr = iHdr->iExportDesc;
+		TUint8* gptr = mptr + mbs;
+		for (i=0; i<memsz; ++i)
+			{
+			if (iExportBitMap[i] != 0xff)
+				{
+				mptr[i>>3] |= (1u << (i&7));
+				*gptr++ = iExportBitMap[i];
+				}
+			}
+		}
+	iHdr->iCodeOffset += extra_space;
+	if (iHdr->iDataOffset)
+		iHdr->iDataOffset += extra_space;
+	if (iHdr->iCodeRelocOffset)
+		iHdr->iCodeRelocOffset += extra_space;
+	if (iHdr->iDataRelocOffset)
+		iHdr->iDataRelocOffset += extra_space;
+	if (iHdr->iImportOffset)
+		iHdr->iImportOffset += extra_space;
+	if (iHdr->iExportDirOffset)
+		iHdr->iExportDirOffset += extra_space;
+	}
+
+// Check the export description is consistent with the export directory
+TInt E32ImageFile::CheckExportDescription()
+	{
+	TUint hdrfmt = iOrigHdr->HeaderFormat();
+	if (hdrfmt < KImageHdrFmt_V && iMissingExports)
+		return KErrCorrupt;
+	if (iHdr->iExportDescType == KImageHdr_ExpD_NoHoles)
+		{
+		return iMissingExports ? KErrCorrupt : KErrNone;
+		}
+	TInt nexp = iOrigHdr->iExportDirCount;
+	TInt memsz = (nexp + 7) >> 3;	// size of complete bitmap
+	TInt mbs = (memsz + 7) >> 3;	// size of meta-bitmap
+	TInt eds = iHdr->iExportDescSize;
+	if (iHdr->iExportDescType == KImageHdr_ExpD_FullBitmap)
+		{
+		if (eds != memsz)
+			return KErrCorrupt;
+		if (memcmp(iHdr->iExportDesc, iExportBitMap, eds) == 0)
+			return KErrNone;
+		return KErrCorrupt;
+		}
+	if (iHdr->iExportDescType != KImageHdr_ExpD_SparseBitmap8)
+		return KErrNotSupported;
+	TInt nbytes = 0;
+	TInt i;
+	for (i=0; i<memsz; ++i)
+		if (iExportBitMap[i] != 0xff)
+			++nbytes;				// number of groups of 8
+	TInt exp_extra = mbs + nbytes;
+	if (eds != exp_extra)
+		return KErrCorrupt;
+	const TUint8* mptr = iHdr->iExportDesc;
+	const TUint8* gptr = mptr + mbs;
+	for (i=0; i<memsz; ++i)
+		{
+		TUint mbit = mptr[i>>3] & (1u << (i&7));
+		if (iExportBitMap[i] != 0xff)
+			{
+			if (!mbit || *gptr++ != iExportBitMap[i])
+				return KErrCorrupt;
+			}
+		else if (mbit)
+			return KErrCorrupt;
+		}
+	return KErrNone;
+	}
+
+
+TInt E32ImageFile::Validate()
+	{
+	TInt orighdrsz = iOrigHdr->TotalSize();
+	TInt r = iHdr->ValidateWholeImage(iData+orighdrsz,iSize-orighdrsz);
+	if(r!=KErrNone)
+		return r;
+	return r;
+	}
+
+
+ostream& operator<<(ostream& os, const E32ImageFile& aImage)
+//
+// Output an E32ImageFile
+//
+	{
+	E32ImageHeaderV* h = aImage.iHdr;
+	TUint hdrfmt = h->HeaderFormat();
+	if (hdrfmt != KImageHdrFmt_V)
+		return os;	// don't generate old binary formats
+	TInt hdrsz = h->TotalSize();
+	TInt orighdrsz = aImage.iOrigHdr->TotalSize();
+
+	os.write((const char*)aImage.iHdr, hdrsz);
+
+	TUint compression = h->CompressionType();
+	if (compression == KUidCompressionDeflate)
+		{
+		int srcsize = aImage.iSize - orighdrsz;
+		DeflateCompress(aImage.iData + orighdrsz, srcsize, os);
+		}
+	else if (compression == KUidCompressionBytePair)
+		{
+		// Compress and write out code part
+		int srcStart = orighdrsz;
+		CompressPages( (TUint8*)aImage.iData + srcStart, aImage.iOrigHdr->iCodeSize, os, aImage.iBPE);
+		
+		
+		// Compress and write out data part
+		srcStart += aImage.iOrigHdr->iCodeSize;
+		int srcLen = aImage.iSize - srcStart;
+
+		CompressPages((TUint8*)aImage.iData + srcStart, srcLen, os, aImage.iBPE);		
+
+		}
+	else if (compression == KFormatNotCompressed)
+		{
+		int srcsize = aImage.iSize - orighdrsz;
+		os.write(aImage.iData + orighdrsz, srcsize); // image not to be compressed
+		}
+	return os;
+	}
+
+ifstream& operator>>(ifstream& is, E32ImageFile& aImage)
+//
+// Input an E32ImageFile
+//
+	{
+	aImage.iError = aImage.ReadHeader(is);
+	if (aImage.iError != KErrNone)
+		return is;
+	E32ImageHeader* oh = aImage.iOrigHdr;
+	TInt orighdrsz = oh->TotalSize();
+	int remainder = aImage.iSize - orighdrsz;
+	TUint compression = oh->CompressionType();
+	if (compression == 0)
+		{
+		is.read(aImage.iData + orighdrsz, remainder);
+		}
+	else if (compression == KUidCompressionDeflate)
+		{ //Uncompress
+		aImage.iError = KErrNoMemory;
+		unsigned int uncompsize = ((E32ImageHeaderComp*)aImage.iOrigHdr)->iUncompressedSize;
+		aImage.Adjust(uncompsize + orighdrsz);
+		if (aImage.iData==NULL)
+			return is;
+		oh = aImage.iOrigHdr;
+		unsigned char* compressedData = new unsigned char[remainder];
+		if (compressedData==NULL)
+			return is;
+		is.read(reinterpret_cast<char *>(compressedData), remainder);
+		unsigned int destsize = uncompsize;
+		InflateUnCompress( compressedData, remainder, (unsigned char*)(aImage.iData + orighdrsz), destsize);
+		if (destsize != uncompsize)
+			Print(EWarning, "Inconsistent sizes discovered during uncompression.\n");
+		delete [] compressedData;
+		if ((TUint)orighdrsz > oh->iCodeOffset)
+			{
+			// need to adjust code offsets in original
+			aImage.iOrigHdrOffsetAdj = (TUint)orighdrsz - oh->iCodeOffset;
+			aImage.OffsetAdjust(oh->iCodeOffset);
+			aImage.OffsetAdjust(oh->iDataOffset);
+			aImage.OffsetAdjust(oh->iCodeRelocOffset);
+			aImage.OffsetAdjust(oh->iDataRelocOffset);
+			aImage.OffsetAdjust(oh->iImportOffset);
+			aImage.OffsetAdjust(oh->iExportDirOffset);
+			}
+		aImage.iError = KErrNone;
+		}
+	else if(compression == KUidCompressionBytePair)
+	{ // Uncompress
+		aImage.iError = KErrNoMemory;
+		unsigned int uncompsize = ((E32ImageHeaderComp*)aImage.iOrigHdr)->iUncompressedSize;
+		aImage.Adjust(uncompsize + orighdrsz);
+		if (aImage.iData==NULL)
+			return is;
+		oh = aImage.iOrigHdr;
+
+		// Read and decompress code part of the image
+
+		unsigned int uncompressedCodeSize = DecompressPages((TUint8 *) (aImage.iData + orighdrsz), is, aImage.iBPE);
+
+		
+		// Read and decompress data part of the image
+
+		unsigned int uncompressedDataSize = DecompressPages((TUint8 *) (aImage.iData + orighdrsz + uncompressedCodeSize), is, aImage.iBPE);
+
+		if (uncompressedCodeSize + uncompressedDataSize != uncompsize)
+			Print(EWarning, "Inconsistent sizes discovered during uncompression.\n");
+
+		if ((TUint)orighdrsz > oh->iCodeOffset)
+			{
+			// need to adjust code offsets in original
+			aImage.iOrigHdrOffsetAdj = (TUint)orighdrsz - oh->iCodeOffset;
+			aImage.OffsetAdjust(oh->iCodeOffset);
+			aImage.OffsetAdjust(oh->iDataOffset);
+			aImage.OffsetAdjust(oh->iCodeRelocOffset);
+			aImage.OffsetAdjust(oh->iDataRelocOffset);
+			aImage.OffsetAdjust(oh->iImportOffset);
+			aImage.OffsetAdjust(oh->iExportDirOffset);
+			}
+		aImage.iError = KErrNone;
+	}
+	aImage.CreateExportBitMap();
+	return is;
+	}
+
+TInt E32ImageFile::IsE32ImageFile(const char *aFileName) {
+ 
+	ifstream ifile(aFileName, IOS_BASE::in | IOS_BASE::binary);
+	if(!ifile.is_open())
+		return FALSE;
+	E32ImageFile f;
+	ifile.seekg(0,IOS_BASE::end);
+	f.iFileSize = ifile.tellg();
+	ifile.seekg(0,IOS_BASE::beg);
+	TInt r = f.ReadHeader(ifile);
+	ifile.close();
+	return (r == KErrNone);
+}
+
+ 
+//
+// Open an E32 Image file
+//
+TInt E32ImageFile::Open(const char* aFileName) {	
+	ifstream ifile(aFileName, IOS_BASE::in | IOS_BASE::binary);
+	if(!ifile.is_open()) {
+		Print(EError,"Cannot open %s for input.\n",aFileName);
+		return 1;
+		}
+	ifile.seekg(0,IOS_BASE::end);
+	iFileSize = ifile.tellg();
+	ifile.seekg(0,IOS_BASE::beg);
+	Adjust(iFileSize);
+	ifile >> *this;
+	ifile.close();
+	if (iError != KErrNone)
+		return iError;
+	size_t len = strlen(aFileName) + 1;
+	iFileName =  new char[len] ;
+	memcpy(iFileName ,aFileName,len);
+	return KErrNone;
+} 
+
+#ifndef __LINUX__
+TInt E32ImageFile::Open(const wchar_t* aFileName)
+//
+// Open an E32 Image file
+//
+	{
+	_wfinddata_t fileinfo;
+	int ret=_wfindfirst((wchar_t*)aFileName,&fileinfo);
+	if (ret==-1) 
+		{
+		Print(EError,"Cannot open %ls for input.\n",aFileName);
+		return 1;
+		}
+	iFileSize = fileinfo.size;
+	Adjust(iFileSize);
+
+	FILE* file = _wfopen(aFileName, L"rb");
+
+	if(!file)
+		{
+		Print(EError,"Cannot open %ls for input.\n",aFileName);
+		return 1;
+		}
+	
+	#if defined(__TOOLS2__) || defined(__MSVCDOTNET__)
+	char tmp[100];  				// Convert wide character name to char *, then open a file.
+	wcstombs(tmp,aFileName,100);
+	ifstream ifile(tmp, ios::in | ios::binary);
+	#else
+	ifstream ifile(fileno(file));
+	#endif
+	
+	if(!ifile.is_open())
+		{
+		Print(EError,"Cannot open %ls for input,\n",aFileName);
+		return 1;
+		}
+		
+	ifile >> *this;
+	ifile.close();
+	fclose(file);
+	if (iError != KErrNone)
+		return iError;
+	iWideFileName=wcsdup(aFileName);
+	if (iWideFileName==NULL)
+		return KErrNoMemory;
+	return KErrNone;
+	}
+#endif
+
+TUint E32ImageFile::VaOfOrdinal(TUint aOrdinal){
+// return the offset of the exported symbol
+	
+	TUint* exportdir = (TUint*)(iData + iOrigHdr->iExportDirOffset);
+	return exportdir[aOrdinal-KOrdinalBase];
+}
+
+// Determine the type of entry point in this module and set the flags
+// in the E32Image header accordingly.
+TInt E32ImageFile::DetermineEntryPointType()
+	{
+	TUint cpu = iHdr->CpuIdentifier();
+	if (cpu != ECpuArmV4 && cpu != ECpuArmV5)
+		return KErrNone;	// if not ARM, leave EPT as 0
+	TUint epOffset = iHdr->iEntryPoint;
+	if (epOffset & 3)
+		return KErrNone;	// if entry point not 4 byte aligned, must be old style
+	TUint fileOffset = epOffset + iHdr->iCodeOffset;
+	if (fileOffset+4 > (TUint)iSize)
+		return KErrCorrupt;	// entry point is past the end of the file??
+	TInt ept = 0;			// old style if first instruction not recognised
+	unsigned char* p = (unsigned char*)iData + fileOffset + 4;
+	TUint32 x = *--p;
+	x<<=8;
+	x|=*--p;
+	x<<=8;
+	x|=*--p;
+	x<<=8;
+	x|=*--p;
+	if ((x & 0xffffff00) == 0xe31f0000)
+		{
+		// starts with tst pc, #n - new entry point
+		ept = (x & 0xff) + 1;
+		}
+	if (ept>7)
+		return KErrNotSupported;
+	iHdr->iFlags |= (ept<<KImageEptShift);
+	return KErrNone;
+	}
+
--- a/imgtools/imglib/e32image/imgdump.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/e32image/imgdump.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,514 +1,514 @@
-/*
-* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* e32tools/e32image/imgdump.cpp
-*
-*/
-
-
-#define __REFERENCE_CAPABILITY_NAMES__
-
-#include <e32image.h>
-#include <h_utl.h>
-#include <string.h>
-
-void PriorityToStr(TProcessPriority aPri, char *aStr)
-	{
-
-	if (aPri==EPrioritySupervisor)
-		strcpy(aStr,"Supervisor");
-
-	else if (aPri>EPriorityRealTimeServer)
-		sprintf(aStr, "RealTime+%d", aPri-EPriorityRealTimeServer);
-	else if (aPri==EPriorityRealTimeServer)
-		strcpy(aStr,"RealTime");
-
-	else if (aPri>EPriorityFileServer)
-		sprintf(aStr, "FileServer+%d", aPri-EPriorityFileServer);
-	else if (aPri==EPriorityFileServer)
-		strcpy(aStr,"FileServer");
-
-	else if (aPri>EPriorityWindowServer)
-		sprintf(aStr, "WindowServer+%d", aPri-EPriorityWindowServer);
-	else if (aPri==EPriorityWindowServer)
-		strcpy(aStr,"WindowServer");
-
-	else if (aPri>EPriorityHigh)
-		sprintf(aStr, "High+%d", aPri-EPriorityHigh);
-	else if (aPri==EPriorityHigh)
-		strcpy(aStr,"High");
-
-	else if (aPri>EPriorityForeground)
-		sprintf(aStr, "Foreground+%d", aPri-EPriorityForeground);
-	else if (aPri==EPriorityForeground)
-		strcpy(aStr,"Foreground");
-
-	else if (aPri>EPriorityBackground)
-		sprintf(aStr, "Background+%d", aPri-EPriorityBackground);
-	else if (aPri==EPriorityBackground)
-		strcpy(aStr,"Background");
-
-	else if (aPri>EPriorityLow)
-		sprintf(aStr, "Low+%d", aPri-EPriorityLow);
-	else if (aPri==EPriorityLow)
-		strcpy(aStr,"Low");
-
-	else
-		sprintf(aStr, "Illegal (%d)", aPri);
-	}
-
-void nl()
-	{
-	Print(EAlways, "\n");
-	}
-
-void E32ImageFile::Dump(TText *aFileName,TInt aDumpFlags)
-	{
-	if (IsValid())
-		{
-		Print(EAlways, "E32ImageFile '%s'\n", aFileName);
-		DumpHeader(aDumpFlags);
-		DumpData(aDumpFlags);
-		}
-	else
-		Print(EAlways, "This is not an E32 image file (error %d).\n", iError);
-	}
-
-void E32ImageFile::DumpHeader(TInt aDumpFlags)
-	{
-	TUint flags = iOrigHdr->iFlags;
-	TUint abi = E32ImageHeader::ABIFromFlags(flags);
-	TUint hdrfmt = E32ImageHeader::HdrFmtFromFlags(flags);
-	TUint impfmt = E32ImageHeader::ImpFmtFromFlags(flags);
-	TUint ept = E32ImageHeader::EptFromFlags(flags);
-	TBool isARM = EFalse;
-
-	if(aDumpFlags&EDumpHeader)
-		{
-		Print(EAlways, "V%d.%02d(%03d)", iOrigHdr->iToolsVersion.iMajor,iOrigHdr->iToolsVersion.iMinor,iOrigHdr->iToolsVersion.iBuild);
-		Print(EAlways, "\tTime Stamp: %08x,%08x\n", iOrigHdr->iTimeHi, iOrigHdr->iTimeLo);
-		char sig[5];
-		memcpy(sig, (const char*)&iOrigHdr->iSignature, 4);
-		sig[4]=0;
-		Print(EAlways, sig);
-		if (iOrigHdr->iFlags&KImageDll)
-			Print(EAlways, " Dll for ");
-		else
-			Print(EAlways, " Exe for ");
-		switch (iOrigHdr->CpuIdentifier())
-			{
-		case ECpuX86:
-			Print(EAlways, "X86 CPU\n");
-			break;
-		case ECpuArmV4:
-			isARM = ETrue;
-			Print(EAlways, "ARMV4 CPU\n");
-			break;
-		case ECpuArmV5:
-			isARM = ETrue;
-			Print(EAlways, "ARMV5 CPU\n");
-			break;
-		case ECpuMCore:
-			Print(EAlways, "M*Core CPU\n");
-			break;
-		case ECpuUnknown:
-			Print(EAlways, "Unknown CPU\n");
-			break;
-		default:
-			Print(EAlways, "something or other\n");
-			break;
-			}
-		
-		Print(EAlways, "Flags:\t%08x\n", flags);
-	
-		if (!(flags & KImageDll))
-			{
-			char str[80];
-			PriorityToStr(iOrigHdr->ProcessPriority(), str);
-			Print(EAlways, "Priority %s\n", str);
-			if (flags & KImageFixedAddressExe)
-				Print(EAlways, "Fixed process\n");
-			}
-		if (flags & KImageNoCallEntryPoint)
-			Print(EAlways, "Entry points are not called\n");
-		Print(EAlways, "Image header is format %d\n", hdrfmt>>24);
-		TUint compression = iOrigHdr->CompressionType();
-		switch (compression)
-			{
-			case KFormatNotCompressed:
-				Print(EAlways, "Image is not compressed\n");
-				break;
-			case KUidCompressionDeflate:
-				Print(EAlways, "Image is compressed using the DEFLATE algorithm\n");
-				break;
-			case KUidCompressionBytePair:
-				Print(EAlways, "Image is compressed using the BYTEPAIR algorithm\n");
-				break;
-			default:
-				Print(EAlways, "Image compression type UNKNOWN (%08x)\n", compression);
-			}
-		if (compression)
-			{
-			Print(EAlways, "Uncompressed size %08x\n", iOrigHdr->UncompressedFileSize());
-			}
-		
-		TUint FPU = flags & KImageHWFloatMask;
-
-		if (FPU == KImageHWFloat_None)
-			Print(EAlways, "Image FPU support : Soft VFP\n");
-		else if (FPU == KImageHWFloat_VFPv2) 
-			Print(EAlways, "Image FPU support : VFPv2\n");
-		else
-			Print(EAlways, "Image FPU support : Unknown\n");
-
-		if (flags & KImageCodeUnpaged)
-			{
-			Print(EAlways, "Code Paging : Unpaged\n");
-			}
-		else if (flags & KImageCodePaged)
-			{
-			Print(EAlways, "Code Paging : Paged\n");
-			}
-		else
-			{
-			Print(EAlways, "Code Paging : Default\n");
-			}
-
-		if (flags & KImageDataUnpaged)
-			{
-			Print(EAlways, "Data Paging : Unpaged\n");
-			}
-		else if (flags & KImageDataPaged)
-			{
-			Print(EAlways, "Data Paging : Paged\n");
-			}
-		else
-			{
-			Print(EAlways, "Data Paging : Default\n");
-			}
-
-		if(flags & KImageDebuggable)
-			{
- 			Print(EAlways, "Debuggable : True\n");
- 			}
- 		else
- 			{
- 			Print(EAlways, "Debuggable : False\n");
- 			}
-
-		if(flags & KImageSMPSafe)
-			{
- 			Print(EAlways, "SMP Safe : True\n");
- 			}
- 		else
- 			{
- 			Print(EAlways, "SMP Safe : False\n");
- 			}
-		}
-
-	if (hdrfmt >= KImageHdrFmt_V && (aDumpFlags&(EDumpHeader|EDumpSecurityInfo)))
-		{
-		//
-		// Important. Don't change output format of following security info
-		// because this is relied on by used by "Symbian Signed".
-		//
-		E32ImageHeaderV* v = iHdr;
-		Print(EAlways, "Secure ID: %08x\n", v->iS.iSecureId);
-		Print(EAlways, "Vendor ID: %08x\n", v->iS.iVendorId);
-		Print(EAlways, "Capabilities: %08x %08x\n", v->iS.iCaps[1], v->iS.iCaps[0]);
-		if(aDumpFlags&EDumpSecurityInfo)
-			{
-			TInt i;
-			for(i=0; i<ECapability_Limit; i++)
-				if(v->iS.iCaps[i>>5]&(1<<(i&31)))
-					Print(EAlways, "              %s\n", CapabilityNames[i]);
-			Print(EAlways, "\n");
-			}
-		}
-
-	if(aDumpFlags&EDumpHeader)
-		{
-		if (hdrfmt >= KImageHdrFmt_V)
-			{
-			E32ImageHeaderV* v = iHdr;
-			TUint32 xd = v->iExceptionDescriptor;
-			if ((xd & 1) && (xd != 0xffffffffu))
-				{
-				xd &= ~1;
-				Print(EAlways, "Exception Descriptor Offset:  %08x\n", v->iExceptionDescriptor);
-				TExceptionDescriptor * aED = (TExceptionDescriptor * )(iData + v->iCodeOffset + xd);
-				Print(EAlways, "Exception Index Table Base: %08x\n", aED->iExIdxBase);
-				Print(EAlways, "Exception Index Table Limit: %08x\n", aED->iExIdxLimit);
-				Print(EAlways, "RO Segment Base: %08x\n", aED->iROSegmentBase);
-				Print(EAlways, "RO Segment Limit: %08x\n", aED->iROSegmentLimit);
-				}
-			else
-				Print(EAlways, "No Exception Descriptor\n");
-
-			Print(EAlways, "Export Description: Size=%03x, Type=%02x\n", v->iExportDescSize, v->iExportDescType);
-			if (v->iExportDescType != KImageHdr_ExpD_NoHoles)
-				{
-				TInt nb = v->iExportDescSize;
-				TInt i;
-				TInt j = 0;
-				for (i=0; i<nb; ++i)
-					{
-					if (++j == 8)
-						{
-						j = 0;
-						Print(EAlways,"\n");
-						}
-					Print(EAlways," %02x", v->iExportDesc[i]);
-					}
-				Print(EAlways,"\n");
-				}
-			TInt r = CheckExportDescription();
-			if (r == KErrNone)
-				Print(EAlways,"Export description consistent\n");
-			else if (r == KErrNotSupported)
-				Print(EAlways,"Export description type not recognised\n");
-			else
-				Print(EAlways,"!! Export description inconsistent !!\n");
-			}
-
-		TUint32 mv = iOrigHdr->ModuleVersion();
-		Print(EAlways, "Module Version: %d.%d\n", mv>>16, mv&0xffff);
-		if (impfmt == KImageImpFmt_PE)
-			{
-			Print(EAlways, "Imports are PE-style\n");
-			}
-		else if (impfmt == KImageImpFmt_ELF)
-			{
-			Print(EAlways, "Imports are ELF-style\n");
-			}
-		else if (impfmt == KImageImpFmt_PE2)
-			{
-			Print(EAlways, "Imports are PE-style without redundant ordinal lists\n");
-			}
-		if (isARM)
-			{
-			if (abi == KImageABI_GCC98r2)
-				{
-				Print(EAlways, "GCC98r2 ABI\n");
-				}
-			else if (abi == KImageABI_EABI)
-				{
-				Print(EAlways, "ARM EABI\n");
-				}
-			if (ept == KImageEpt_Eka1)
-				{
-				Print(EAlways, "Built against EKA1\n");
-				}
-			else if (ept == KImageEpt_Eka2)
-				{
-				Print(EAlways, "Built against EKA2\n");
-				}
-			}
-
-		Print(EAlways, "Uids:\t\t%08x %08x %08x (%08x)\n", iOrigHdr->iUid1, iOrigHdr->iUid2, iOrigHdr->iUid3, iOrigHdr->iUidChecksum);
-		if (hdrfmt >= KImageHdrFmt_V)
-			Print(EAlways, "Header CRC:\t%08x\n", iHdr->iHeaderCrc);
-		Print(EAlways, "File Size:\t%08x\n", iSize);
-		Print(EAlways, "Code Size:\t%08x\n", iOrigHdr->iCodeSize);
-		Print(EAlways, "Data Size:\t%08x\n", iOrigHdr->iDataSize);
-		Print(EAlways, "Compression:\t%08x\n", iOrigHdr->iCompressionType);
-		Print(EAlways, "Min Heap Size:\t%08x\n", iOrigHdr->iHeapSizeMin);
-		Print(EAlways, "Max Heap Size:\t%08x\n", iOrigHdr->iHeapSizeMax);
-		Print(EAlways, "Stack Size:\t%08x\n", iOrigHdr->iStackSize);
-		Print(EAlways, "Code link addr:\t%08x\n", iOrigHdr->iCodeBase);
-		Print(EAlways, "Data link addr:\t%08x\n", iOrigHdr->iDataBase);
-		Print(EAlways, "Code reloc offset:\t%08x\n", OrigCodeRelocOffset());
-		Print(EAlways, "Data reloc offset:\t%08x\n", OrigDataRelocOffset());
-		Print(EAlways, "Dll ref table count: %d\n", iOrigHdr->iDllRefTableCount);
-
-		if (iOrigHdr->iCodeSize || iOrigHdr->iDataSize || iOrigHdr->iBssSize || iOrigHdr->iImportOffset)
-			Print(EAlways, "        Offset  Size  Relocs #Relocs\n");
-
-		Print(EAlways, "Code    %06x %06x", OrigCodeOffset(), iOrigHdr->iCodeSize);
-		if (iOrigHdr->iCodeRelocOffset)
-			{
-			E32RelocSection *r=(E32RelocSection *)(iData + iOrigHdr->iCodeRelocOffset);
-			Print(EAlways, " %06x %06x", OrigCodeRelocOffset(), r->iNumberOfRelocs);
-			}
-		else
-			Print(EAlways, "              ");
-		Print(EAlways, "        +%06x (entry pnt)", iOrigHdr->iEntryPoint);
-		nl();
-
-		Print(EAlways, "Data    %06x %06x", OrigDataOffset(), iOrigHdr->iDataSize);
-		if (iOrigHdr->iDataRelocOffset)
-			{
-			E32RelocSection *r=(E32RelocSection *)(iData + iOrigHdr->iDataRelocOffset);
-			Print(EAlways, " %06x %06x", OrigDataRelocOffset(), r->iNumberOfRelocs);
-			}
-		nl();
-
-		Print(EAlways, "Bss            %06x\n", iOrigHdr->iBssSize);
-
-		if (iOrigHdr->iExportDirOffset)
-			Print(EAlways, "Export  %06x %06x                      (%d entries)\n", OrigExportDirOffset(), iOrigHdr->iExportDirCount*4, iOrigHdr->iExportDirCount);
-		if (iOrigHdr->iImportOffset)
-			Print(EAlways, "Import  %06x\n", OrigImportOffset());
-		}
-	}
-
-void dump(TUint *aData, TInt aLength)
-	{
-	TUint *p=aData;
-	TInt i=0;
-	char line[256];
-	char *cp=(char*)aData;
-	TInt j=0;
-	memset(line,' ',sizeof(line));
-	while (i<aLength)
-		{
-		TInt ccount=0;
-		char* linep=&line[8*9+2];
-		Print(EAlways, "%06x:", i);
-		while (i<aLength && ccount<8)
-			{
-			Print(EAlways," %08x", *p++);
-			i+=4;
-			ccount++;
-			for (j=0; j<4; j++)
-				{
-				char c=*cp++;
-				if (c<32 || c>127)
-					{
-					c = '.';
-					}
-				*linep++ = c;
-				}
-			}
-		*linep='\0';
-		Print(EAlways, "%s", line+(ccount*9));
-		nl();
-		}
-	}
-
-void dumprelocs(char *aRelocs)
-	{
-
-	TInt num=((E32RelocSection *)aRelocs)->iNumberOfRelocs;
-	Print(EAlways, "%d relocs\n", num);
-	aRelocs+=sizeof(E32RelocSection);
-	TInt printed=0;
-	while (num>0)
-		{
-		TInt page=*(TUint *)aRelocs;
-		TInt size=*(TUint *)(aRelocs+4);
-		TInt pagesize=size;
-		size-=8;
-		TUint16 *p=(TUint16 *)(aRelocs+8);
-		while (size>0)
-			{
-			TUint a=*p++;
-			TUint relocType = a >> 12;
-			if (relocType==3 || relocType==1)
-				{
-				Print(EAlways, "%08x(%1x) ", page+(a&0x0fff), relocType);
-				printed++;
-				if (printed>3)
-					{
-					nl();
-					printed=0;
-					}
-				}
-			size-=2;
-			num--;
-			}
-		aRelocs+=pagesize;
-		}
-	nl();
-	}
-
-
-void E32ImageFile::DumpData(TInt aDumpFlags)
-	{
-	if(aDumpFlags&EDumpCode)
-		{
-		Print(EAlways, "\nCode (text size=%08x)\n", iOrigHdr->iTextSize);
-		dump((TUint *)(iData + iOrigHdr->iCodeOffset), iOrigHdr->iCodeSize);
-		if (iOrigHdr->iCodeRelocOffset)
-			dumprelocs(iData + iOrigHdr->iCodeRelocOffset);
-		}
-
-	if((aDumpFlags&EDumpData) && iOrigHdr->iDataOffset)
-		{
-		Print(EAlways, "\nData\n");
-		dump((TUint *)(iData + iOrigHdr->iDataOffset), iOrigHdr->iDataSize);
-		if (iOrigHdr->iDataRelocOffset)
-			dumprelocs(iData + iOrigHdr->iDataRelocOffset);
-		}
-
-	if(aDumpFlags&EDumpExports)
-		{
-		Print(EAlways, "\nNumber of exports = %d\n", iOrigHdr->iExportDirCount);
-		TInt i;
-		TUint* exports = (TUint*)(iData + iOrigHdr->iExportDirOffset);
-		TUint absoluteEntryPoint = iOrigHdr->iEntryPoint + iOrigHdr->iCodeBase;
-		TUint impfmt = iOrigHdr->ImportFormat();
-		TUint absentVal = (impfmt == KImageImpFmt_ELF) ? absoluteEntryPoint : iOrigHdr->iEntryPoint;
-		for (i=0; i<iOrigHdr->iExportDirCount; ++i)
-			{
-			TUint exp = exports[i];
-			if (exp == absentVal)
-				Print(EAlways, "\tOrdinal %5d:\tABSENT\n", i+1);
-			else
-				Print(EAlways, "\tOrdinal %5d:\t%08x\n", i+1, exp);
-			}
-		}
-
-	//
-	// Important. Don't change output format of following inport info
-	// because this is relied on by tools used by "Symbian Signed".
-	//
-	if((aDumpFlags&EDumpImports) && iOrigHdr->iImportOffset)
-		{
-		const E32ImportSection* isection = (const E32ImportSection*)(iData + iOrigHdr->iImportOffset);
-		TUint* iat = (TUint*)((TUint8*)iData + iOrigHdr->iCodeOffset + iOrigHdr->iTextSize);
-		Print(EAlways, "\nIdata\tSize=%08x\n", isection->iSize);
-		Print(EAlways, "Offset of import address table (relative to code section): %08x\n", iOrigHdr->iTextSize);
-		TInt d;
-		const E32ImportBlock* b = (const E32ImportBlock*)(isection + 1);
-		for (d=0; d<iOrigHdr->iDllRefTableCount; d++)
-			{
-			char* dllname = iData + iOrigHdr->iImportOffset + b->iOffsetOfDllName;
-			TInt n = b->iNumberOfImports;
-			Print(EAlways, "%d imports from %s\n", b->iNumberOfImports, dllname);
-			const TUint* p = b->Imports();
-			TUint impfmt = iOrigHdr->ImportFormat();
-			if (impfmt == KImageImpFmt_ELF)
-				{
-				while (n--)
-					{
-					TUint impd_offset = *p++;
-					TUint impd = *(TUint*)(iData + iOrigHdr->iCodeOffset + impd_offset);
-					TUint ordinal = impd & 0xffff;
-					TUint offset = impd >> 16;
-					if (offset)
-						Print(EAlways, "%10d offset by %d\n", ordinal, offset);
-					else
-						Print(EAlways, "%10d\n", ordinal);
-					}
-				}
-			else
-				{
-				while (n--)
-					Print(EAlways, "\t%d\n", *iat++);
-				}
-			b = b->NextBlock(impfmt);
-			}
-		}
-	}
+/*
+* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* e32tools/e32image/imgdump.cpp
+*
+*/
+
+
+#define __REFERENCE_CAPABILITY_NAMES__
+
+#include "e32image.h"
+#include "h_utl.h"
+#include <string.h>
+#include <e32def_private.h>
+void PriorityToStr(TProcessPriority aPri, char *aStr)
+	{
+
+	if (aPri==EPrioritySupervisor)
+		strcpy(aStr,"Supervisor");
+
+	else if (aPri>EPriorityRealTimeServer)
+		sprintf(aStr, "RealTime+%d", aPri-EPriorityRealTimeServer);
+	else if (aPri==EPriorityRealTimeServer)
+		strcpy(aStr,"RealTime");
+
+	else if (aPri>EPriorityFileServer)
+		sprintf(aStr, "FileServer+%d", aPri-EPriorityFileServer);
+	else if (aPri==EPriorityFileServer)
+		strcpy(aStr,"FileServer");
+
+	else if (aPri>EPriorityWindowServer)
+		sprintf(aStr, "WindowServer+%d", aPri-EPriorityWindowServer);
+	else if (aPri==EPriorityWindowServer)
+		strcpy(aStr,"WindowServer");
+
+	else if (aPri>EPriorityHigh)
+		sprintf(aStr, "High+%d", aPri-EPriorityHigh);
+	else if (aPri==EPriorityHigh)
+		strcpy(aStr,"High");
+
+	else if (aPri>EPriorityForeground)
+		sprintf(aStr, "Foreground+%d", aPri-EPriorityForeground);
+	else if (aPri==EPriorityForeground)
+		strcpy(aStr,"Foreground");
+
+	else if (aPri>EPriorityBackground)
+		sprintf(aStr, "Background+%d", aPri-EPriorityBackground);
+	else if (aPri==EPriorityBackground)
+		strcpy(aStr,"Background");
+
+	else if (aPri>EPriorityLow)
+		sprintf(aStr, "Low+%d", aPri-EPriorityLow);
+	else if (aPri==EPriorityLow)
+		strcpy(aStr,"Low");
+
+	else
+		sprintf(aStr, "Illegal (%d)", aPri);
+	}
+
+void nl()
+	{
+	Print(EAlways, "\n");
+	}
+
+void E32ImageFile::Dump(const char* aFileName,TInt aDumpFlags)
+	{
+	if (IsValid())
+		{
+		Print(EAlways, "E32ImageFile '%s'\n", aFileName);
+		DumpHeader(aDumpFlags);
+		DumpData(aDumpFlags);
+		}
+	else
+		Print(EAlways, "This is not an E32 image file (error %d).\n", iError);
+}
+
+void E32ImageFile::DumpHeader(TInt aDumpFlags)
+	{
+	TUint flags = iOrigHdr->iFlags;
+	TUint abi = E32ImageHeader::ABIFromFlags(flags);
+	TUint hdrfmt = E32ImageHeader::HdrFmtFromFlags(flags);
+	TUint impfmt = E32ImageHeader::ImpFmtFromFlags(flags);
+	TUint ept = E32ImageHeader::EptFromFlags(flags);
+	TBool isARM = EFalse;
+
+	if(aDumpFlags&EDumpHeader)
+		{
+		Print(EAlways, "V%d.%02d(%03d)", iOrigHdr->iToolsVersion.iMajor,iOrigHdr->iToolsVersion.iMinor,iOrigHdr->iToolsVersion.iBuild);
+		Print(EAlways, "\tTime Stamp: %08x,%08x\n", iOrigHdr->iTimeHi, iOrigHdr->iTimeLo);
+		char sig[5];
+		memcpy(sig, (const char*)&iOrigHdr->iSignature, 4);
+		sig[4]=0;
+		Print(EAlways, sig);
+		if (iOrigHdr->iFlags&KImageDll)
+			Print(EAlways, " Dll for ");
+		else
+			Print(EAlways, " Exe for ");
+		switch (iOrigHdr->CpuIdentifier())
+			{
+		case ECpuX86:
+			Print(EAlways, "X86 CPU\n");
+			break;
+		case ECpuArmV4:
+			isARM = ETrue;
+			Print(EAlways, "ARMV4 CPU\n");
+			break;
+		case ECpuArmV5:
+			isARM = ETrue;
+			Print(EAlways, "ARMV5 CPU\n");
+			break;
+		case ECpuMCore:
+			Print(EAlways, "M*Core CPU\n");
+			break;
+		case ECpuUnknown:
+			Print(EAlways, "Unknown CPU\n");
+			break;
+		default:
+			Print(EAlways, "something or other\n");
+			break;
+			}
+		
+		Print(EAlways, "Flags:\t%08x\n", flags);
+	
+		if (!(flags & KImageDll))
+			{
+			char str[80];
+			PriorityToStr(iOrigHdr->ProcessPriority(), str);
+			Print(EAlways, "Priority %s\n", str);
+			if (flags & KImageFixedAddressExe)
+				Print(EAlways, "Fixed process\n");
+			}
+		if (flags & KImageNoCallEntryPoint)
+			Print(EAlways, "Entry points are not called\n");
+		Print(EAlways, "Image header is format %d\n", hdrfmt>>24);
+		TUint compression = iOrigHdr->CompressionType();
+		switch (compression)
+			{
+			case KFormatNotCompressed:
+				Print(EAlways, "Image is not compressed\n");
+				break;
+			case KUidCompressionDeflate:
+				Print(EAlways, "Image is compressed using the DEFLATE algorithm\n");
+				break;
+			case KUidCompressionBytePair:
+				Print(EAlways, "Image is compressed using the BYTEPAIR algorithm\n");
+				break;
+			default:
+				Print(EAlways, "Image compression type UNKNOWN (%08x)\n", compression);
+			}
+		if (compression)
+			{
+			Print(EAlways, "Uncompressed size %08x\n", iOrigHdr->UncompressedFileSize());
+			}
+		
+		TUint FPU = flags & KImageHWFloatMask;
+
+		if (FPU == KImageHWFloat_None)
+			Print(EAlways, "Image FPU support : Soft VFP\n");
+		else if (FPU == KImageHWFloat_VFPv2) 
+			Print(EAlways, "Image FPU support : VFPv2\n");
+		else
+			Print(EAlways, "Image FPU support : Unknown\n");
+
+		if (flags & KImageCodeUnpaged)
+			{
+			Print(EAlways, "Code Paging : Unpaged\n");
+			}
+		else if (flags & KImageCodePaged)
+			{
+			Print(EAlways, "Code Paging : Paged\n");
+			}
+		else
+			{
+			Print(EAlways, "Code Paging : Default\n");
+			}
+
+		if (flags & KImageDataUnpaged)
+			{
+			Print(EAlways, "Data Paging : Unpaged\n");
+			}
+		else if (flags & KImageDataPaged)
+			{
+			Print(EAlways, "Data Paging : Paged\n");
+			}
+		else
+			{
+			Print(EAlways, "Data Paging : Default\n");
+			}
+
+		if(flags & KImageDebuggable)
+			{
+ 			Print(EAlways, "Debuggable : True\n");
+ 			}
+ 		else
+ 			{
+ 			Print(EAlways, "Debuggable : False\n");
+ 			}
+
+		if(flags & KImageSMPSafe)
+			{
+ 			Print(EAlways, "SMP Safe : True\n");
+ 			}
+ 		else
+ 			{
+ 			Print(EAlways, "SMP Safe : False\n");
+ 			}
+		}
+
+	if (hdrfmt >= KImageHdrFmt_V && (aDumpFlags&(EDumpHeader|EDumpSecurityInfo)))
+		{
+		//
+		// Important. Don't change output format of following security info
+		// because this is relied on by used by "Symbian Signed".
+		//
+		E32ImageHeaderV* v = iHdr;
+		Print(EAlways, "Secure ID: %08x\n", v->iS.iSecureId);
+		Print(EAlways, "Vendor ID: %08x\n", v->iS.iVendorId);
+		Print(EAlways, "Capabilities: %08x %08x\n", v->iS.iCaps[1], v->iS.iCaps[0]);
+		if(aDumpFlags&EDumpSecurityInfo)
+			{
+			TInt i;
+			for(i=0; i<ECapability_Limit; i++)
+				if(v->iS.iCaps[i>>5]&(1<<(i&31)))
+					Print(EAlways, "              %s\n", CapabilityNames[i]);
+			Print(EAlways, "\n");
+			}
+		}
+
+	if(aDumpFlags&EDumpHeader)
+		{
+		if (hdrfmt >= KImageHdrFmt_V)
+			{
+			E32ImageHeaderV* v = iHdr;
+			TUint32 xd = v->iExceptionDescriptor;
+			if ((xd & 1) && (xd != 0xffffffffu))
+				{
+				xd &= ~1;
+				Print(EAlways, "Exception Descriptor Offset:  %08x\n", v->iExceptionDescriptor);
+				TExceptionDescriptor * aED = (TExceptionDescriptor * )(iData + v->iCodeOffset + xd);
+				Print(EAlways, "Exception Index Table Base: %08x\n", aED->iExIdxBase);
+				Print(EAlways, "Exception Index Table Limit: %08x\n", aED->iExIdxLimit);
+				Print(EAlways, "RO Segment Base: %08x\n", aED->iROSegmentBase);
+				Print(EAlways, "RO Segment Limit: %08x\n", aED->iROSegmentLimit);
+				}
+			else
+				Print(EAlways, "No Exception Descriptor\n");
+
+			Print(EAlways, "Export Description: Size=%03x, Type=%02x\n", v->iExportDescSize, v->iExportDescType);
+			if (v->iExportDescType != KImageHdr_ExpD_NoHoles)
+				{
+				TInt nb = v->iExportDescSize;
+				TInt i;
+				TInt j = 0;
+				for (i=0; i<nb; ++i)
+					{
+					if (++j == 8)
+						{
+						j = 0;
+						Print(EAlways,"\n");
+						}
+					Print(EAlways," %02x", v->iExportDesc[i]);
+					}
+				Print(EAlways,"\n");
+				}
+			TInt r = CheckExportDescription();
+			if (r == KErrNone)
+				Print(EAlways,"Export description consistent\n");
+			else if (r == KErrNotSupported)
+				Print(EAlways,"Export description type not recognised\n");
+			else
+				Print(EAlways,"!! Export description inconsistent !!\n");
+			}
+
+		TUint32 mv = iOrigHdr->ModuleVersion();
+		Print(EAlways, "Module Version: %d.%d\n", mv>>16, mv&0xffff);
+		if (impfmt == KImageImpFmt_PE)
+			{
+			Print(EAlways, "Imports are PE-style\n");
+			}
+		else if (impfmt == KImageImpFmt_ELF)
+			{
+			Print(EAlways, "Imports are ELF-style\n");
+			}
+		else if (impfmt == KImageImpFmt_PE2)
+			{
+			Print(EAlways, "Imports are PE-style without redundant ordinal lists\n");
+			}
+		if (isARM)
+			{
+			if (abi == KImageABI_GCC98r2)
+				{
+				Print(EAlways, "GCC98r2 ABI\n");
+				}
+			else if (abi == KImageABI_EABI)
+				{
+				Print(EAlways, "ARM EABI\n");
+				}
+			if (ept == KImageEpt_Eka1)
+				{
+				Print(EAlways, "Built against EKA1\n");
+				}
+			else if (ept == KImageEpt_Eka2)
+				{
+				Print(EAlways, "Built against EKA2\n");
+				}
+			}
+
+		Print(EAlways, "Uids:\t\t%08x %08x %08x (%08x)\n", iOrigHdr->iUid1, iOrigHdr->iUid2, iOrigHdr->iUid3, iOrigHdr->iUidChecksum);
+		if (hdrfmt >= KImageHdrFmt_V)
+			Print(EAlways, "Header CRC:\t%08x\n", iHdr->iHeaderCrc);
+		Print(EAlways, "File Size:\t%08x\n", iSize);
+		Print(EAlways, "Code Size:\t%08x\n", iOrigHdr->iCodeSize);
+		Print(EAlways, "Data Size:\t%08x\n", iOrigHdr->iDataSize);
+		Print(EAlways, "Compression:\t%08x\n", iOrigHdr->iCompressionType);
+		Print(EAlways, "Min Heap Size:\t%08x\n", iOrigHdr->iHeapSizeMin);
+		Print(EAlways, "Max Heap Size:\t%08x\n", iOrigHdr->iHeapSizeMax);
+		Print(EAlways, "Stack Size:\t%08x\n", iOrigHdr->iStackSize);
+		Print(EAlways, "Code link addr:\t%08x\n", iOrigHdr->iCodeBase);
+		Print(EAlways, "Data link addr:\t%08x\n", iOrigHdr->iDataBase);
+		Print(EAlways, "Code reloc offset:\t%08x\n", OrigCodeRelocOffset());
+		Print(EAlways, "Data reloc offset:\t%08x\n", OrigDataRelocOffset());
+		Print(EAlways, "Dll ref table count: %d\n", iOrigHdr->iDllRefTableCount);
+
+		if (iOrigHdr->iCodeSize || iOrigHdr->iDataSize || iOrigHdr->iBssSize || iOrigHdr->iImportOffset)
+			Print(EAlways, "        Offset  Size  Relocs #Relocs\n");
+
+		Print(EAlways, "Code    %06x %06x", OrigCodeOffset(), iOrigHdr->iCodeSize);
+		if (iOrigHdr->iCodeRelocOffset)
+			{
+			E32RelocSection *r=(E32RelocSection *)(iData + iOrigHdr->iCodeRelocOffset);
+			Print(EAlways, " %06x %06x", OrigCodeRelocOffset(), r->iNumberOfRelocs);
+			}
+		else
+			Print(EAlways, "              ");
+		Print(EAlways, "        +%06x (entry pnt)", iOrigHdr->iEntryPoint);
+		nl();
+
+		Print(EAlways, "Data    %06x %06x", OrigDataOffset(), iOrigHdr->iDataSize);
+		if (iOrigHdr->iDataRelocOffset)
+			{
+			E32RelocSection *r=(E32RelocSection *)(iData + iOrigHdr->iDataRelocOffset);
+			Print(EAlways, " %06x %06x", OrigDataRelocOffset(), r->iNumberOfRelocs);
+			}
+		nl();
+
+		Print(EAlways, "Bss            %06x\n", iOrigHdr->iBssSize);
+
+		if (iOrigHdr->iExportDirOffset)
+			Print(EAlways, "Export  %06x %06x                      (%d entries)\n", OrigExportDirOffset(), iOrigHdr->iExportDirCount*4, iOrigHdr->iExportDirCount);
+		if (iOrigHdr->iImportOffset)
+			Print(EAlways, "Import  %06x\n", OrigImportOffset());
+		}
+	}
+
+void dump(TUint *aData, TInt aLength)
+	{
+	TUint *p=aData;
+	TInt i=0;
+	char line[256];
+	char *cp=(char*)aData;
+	TInt j=0;
+	memset(line,' ',sizeof(line));
+	while (i<aLength)
+		{
+		TInt ccount=0;
+		char* linep=&line[8*9+2];
+		Print(EAlways, "%06x:", i);
+		while (i<aLength && ccount<8)
+			{
+			Print(EAlways," %08x", *p++);
+			i+=4;
+			ccount++;
+			for (j=0; j<4; j++)
+				{
+				unsigned char c=*cp++;
+				if (c<32 || c>127)
+					{
+					c = '.';
+					}
+				*linep++ = c;
+				}
+			}
+		*linep='\0';
+		Print(EAlways, "%s", line+(ccount*9));
+		nl();
+		}
+	}
+
+void dumprelocs(char *aRelocs)
+	{
+
+	TInt num=((E32RelocSection *)aRelocs)->iNumberOfRelocs;
+	Print(EAlways, "%d relocs\n", num);
+	aRelocs+=sizeof(E32RelocSection);
+	TInt printed=0;
+	while (num>0)
+		{
+		TInt page=*(TUint *)aRelocs;
+		TInt size=*(TUint *)(aRelocs+4);
+		TInt pagesize=size;
+		size-=8;
+		TUint16 *p=(TUint16 *)(aRelocs+8);
+		while (size>0)
+			{
+			TUint a=*p++;
+			TUint relocType = a >> 12;
+			if (relocType==3 || relocType==1)
+				{
+				Print(EAlways, "%08x(%1x) ", page+(a&0x0fff), relocType);
+				printed++;
+				if (printed>3)
+					{
+					nl();
+					printed=0;
+					}
+				}
+			size-=2;
+			num--;
+			}
+		aRelocs+=pagesize;
+		}
+	nl();
+	}
+
+
+void E32ImageFile::DumpData(TInt aDumpFlags)
+	{
+	if(aDumpFlags&EDumpCode)
+		{
+		Print(EAlways, "\nCode (text size=%08x)\n", iOrigHdr->iTextSize);
+		dump((TUint *)(iData + iOrigHdr->iCodeOffset), iOrigHdr->iCodeSize);
+		if (iOrigHdr->iCodeRelocOffset)
+			dumprelocs(iData + iOrigHdr->iCodeRelocOffset);
+		}
+
+	if((aDumpFlags&EDumpData) && iOrigHdr->iDataOffset)
+		{
+		Print(EAlways, "\nData\n");
+		dump((TUint *)(iData + iOrigHdr->iDataOffset), iOrigHdr->iDataSize);
+		if (iOrigHdr->iDataRelocOffset)
+			dumprelocs(iData + iOrigHdr->iDataRelocOffset);
+		}
+
+	if(aDumpFlags&EDumpExports)
+		{
+		Print(EAlways, "\nNumber of exports = %d\n", iOrigHdr->iExportDirCount);
+		TInt i;
+		TUint* exports = (TUint*)(iData + iOrigHdr->iExportDirOffset);
+		TUint absoluteEntryPoint = iOrigHdr->iEntryPoint + iOrigHdr->iCodeBase;
+		TUint impfmt = iOrigHdr->ImportFormat();
+		TUint absentVal = (impfmt == KImageImpFmt_ELF) ? absoluteEntryPoint : iOrigHdr->iEntryPoint;
+		for (i=0; i<iOrigHdr->iExportDirCount; ++i)
+			{
+			TUint exp = exports[i];
+			if (exp == absentVal)
+				Print(EAlways, "\tOrdinal %5d:\tABSENT\n", i+1);
+			else
+				Print(EAlways, "\tOrdinal %5d:\t%08x\n", i+1, exp);
+			}
+		}
+
+	//
+	// Important. Don't change output format of following inport info
+	// because this is relied on by tools used by "Symbian Signed".
+	//
+	if((aDumpFlags&EDumpImports) && iOrigHdr->iImportOffset)
+		{
+		const E32ImportSection* isection = (const E32ImportSection*)(iData + iOrigHdr->iImportOffset);
+		TUint* iat = (TUint*)((TUint8*)iData + iOrigHdr->iCodeOffset + iOrigHdr->iTextSize);
+		Print(EAlways, "\nIdata\tSize=%08x\n", isection->iSize);
+		Print(EAlways, "Offset of import address table (relative to code section): %08x\n", iOrigHdr->iTextSize);
+		TInt d;
+		const E32ImportBlock* b = (const E32ImportBlock*)(isection + 1);
+		for (d=0; d<iOrigHdr->iDllRefTableCount; d++)
+			{
+			char* dllname = iData + iOrigHdr->iImportOffset + b->iOffsetOfDllName;
+			TInt n = b->iNumberOfImports;
+			Print(EAlways, "%d imports from %s\n", b->iNumberOfImports, dllname);
+			const TUint* p = b->Imports();
+			TUint impfmt = iOrigHdr->ImportFormat();
+			if (impfmt == KImageImpFmt_ELF)
+				{
+				while (n--)
+					{
+					TUint impd_offset = *p++;
+					TUint impd = *(TUint*)(iData + iOrigHdr->iCodeOffset + impd_offset);
+					TUint ordinal = impd & 0xffff;
+					TUint offset = impd >> 16;
+					if (offset)
+						Print(EAlways, "%10d offset by %d\n", ordinal, offset);
+					else
+						Print(EAlways, "%10d\n", ordinal);
+					}
+				}
+			else
+				{
+				while (n--)
+					Print(EAlways, "\t%d\n", *iat++);
+				}
+			b = b->NextBlock(impfmt);
+			}
+		}
+	}
--- a/imgtools/imglib/e32image/tr_main.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/e32image/tr_main.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,997 +1,981 @@
-/*
-* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* e32tools/e32image/tr_main.cpp
-* Translate X->E32Image top level
-*
-*/
-
-
-#ifndef __LINUX__
-  #include <io.h>
-#endif
-#include <string.h>
-
-#ifdef __VC32__
- #ifdef __MSVCDOTNET__
-  #include <strstream>
-  #include <iomanip>
- #else //!__MSVCDOTNET__
-  #include <strstrea.h>
-  #include <iomanip.h>
- #endif //__MSVCDOTNET__
-#else // !__VC32__*/
-#ifdef __TOOLS2__
-  #include <sstream>
-  #include <iomanip>
-  #else
- #include <strstream.h>
- #include <iomanip.h>
-#endif // __VC32__
-#endif
-
-#include <e32std.h>
-#include <e32std_private.h>
-
-#ifdef __SUPPORT_PE_FILES__
-#include "pe_file.h"
-#endif
-#ifdef __SUPPORT_ELF_FILES__
-#include "elftran.h"
-#endif
-
-#include <h_utl.h>
-#include <h_ver.h>
-#include <stdio.h>
-
-extern int gAlignConstSection;
-extern TUint gConstSectionAddressMask;
-
-int gVerbose=0;
-char *gFile1=NULL;
-char *gFile2=NULL;
-unsigned int gStack=0;
-unsigned int gHeapMin=0;
-unsigned int gHeapMax=0;
-TUid gUid1=KNullUid;
-TUid gUid2=KNullUid;
-TUid gUid3=KNullUid;
-unsigned int gSecureId=0;
-unsigned int gVendorId=0;
-unsigned int gVersionWord=0x00010000u;
-int gCallEntryPoints=TRUE;
-int gFixedAddress=FALSE;
-int gPriority=EPriorityForeground;
-SCapabilitySet gCapability={0};
-int gAllowDllData=FALSE;
-// fix warning for Linux warning: 0 instead of NULL
-TUint gDataBase=0;
-int gCompress=TRUE;
-unsigned int gFPU=0;
-
-int gCodePaged=FALSE;
-int gCodeUnpaged=FALSE;
-int gCodeDefaultPaged=FALSE;
-
-int gDataPaged=FALSE;
-int gDataUnpaged=FALSE;
-int gDataDefaultPaged=FALSE;
-
-int gDebuggable=FALSE;
-int gSmpSafe=FALSE;
-
-int gSetStack=FALSE;
-int gSetHeap=FALSE;
-int gSetUid1=FALSE;
-int gSetUid2=FALSE;
-int gSetUid3=FALSE;
-int gSetCallEntryPoints=FALSE;
-int gSetFixedAddress=FALSE;
-int gSetPriority=FALSE;
-int gSetCapability=FALSE;
-int gSetCompress=FALSE;
-int gSetVersion=FALSE;
-int gSetSecureId=FALSE;
-int gSetVendorId=FALSE;
-int gSetFPU=FALSE;
-
-int gSetCodePaged=FALSE;
-int gSetDataPaged=FALSE;
-
-int gSetSymLkup=FALSE;
-int gSetDebuggable=FALSE;
-int gSetSmpSafe=FALSE;
-
-enum CompressionMethods
-{
-	ENoCompression = 0,
-	EDeflate = 1,
-	EBytePair = 2,
-};
-
-int gCompressionMethod = EDeflate;
-int gSuppressComprMethod = FALSE;
-
-#ifdef __SUPPORT_PE_FILES__
-char* gX86imp=NULL;
-int gX86num_imp_dlls=0;
-int gX86imp_size=0;
-int gX86num_imports=0;
-#endif
-
-TBool gLittleEndian=ETrue;
-
-class E32ImageFileRef
-	{
-public:
-	E32ImageFileRef() {iPtr = E32ImageFile::New();}
-	~E32ImageFileRef() {delete iPtr;}
-	class E32ImageFile& Ref() {return *iPtr;}
-private:
-	E32ImageFileRef(const E32ImageFileRef&);
-	E32ImageFileRef& operator=(const E32ImageFileRef&);
-private:
-	E32ImageFile* iPtr;
-	};
-
-int setPagedFlags(E32ImageFile& f)
-	{
-	unsigned check1 = gCodePaged + gCodeUnpaged + gCodeDefaultPaged;
-	unsigned check2 = gDataPaged + gDataUnpaged + gDataDefaultPaged;
-
-	if (check1 > 1 || check2 > 1)
-		{
-		Print(EError, "Conflicting paging options.\n");
-		return KErrArgument;
-		}
-
-	if (gCodePaged)
-		{
-		f.iHdr->iFlags |= KImageCodePaged;
-		f.iHdr->iFlags &= ~KImageCodeUnpaged;
-		}
-	else if (gCodeUnpaged)
-		{
-		f.iHdr->iFlags |= KImageCodeUnpaged;
-		f.iHdr->iFlags &= ~KImageCodePaged;
-		}
-	else if (gCodeDefaultPaged)
-		{
-		f.iHdr->iFlags &= ~KImageCodePaged;
-		f.iHdr->iFlags &= ~KImageCodeUnpaged;
-		}
-
-	if (gDataPaged)
-		{
-		f.iHdr->iFlags |=  KImageDataPaged;
-		f.iHdr->iFlags &= ~KImageDataUnpaged;
-		}
-	else if (gDataUnpaged)
-		{
-		f.iHdr->iFlags |=  KImageDataUnpaged;
-		f.iHdr->iFlags &= ~KImageDataPaged;
-		}
-	else if (gDataDefaultPaged)
-		{
-		f.iHdr->iFlags &= ~KImageDataPaged;
-		f.iHdr->iFlags &= ~KImageDataUnpaged;
-		}
-
-	return KErrNone;
-	}
-
-void setDebuggableFlags(E32ImageFile& f)
-	{
-	if (gDebuggable)
-		{
-		f.iHdr->iFlags |= KImageDebuggable;
-		}
-	else
-		{
-		f.iHdr->iFlags &= ~KImageDebuggable;
-		}
-	}
-
-void setSmpSafeFlags(E32ImageFile& f)
-	{
-	if (gSmpSafe)
-		{
-		f.iHdr->iFlags |= KImageSMPSafe;
-		}
-	else
-		{
-		f.iHdr->iFlags &= ~KImageSMPSafe;
-		}
-	}
-
-int dotran(const char* ifilename, const char* ofilename)
-	{
-	E32ImageFileRef fRef;
-	E32ImageFile& f = fRef.Ref();
-	int r=f.Translate(ifilename, gDataBase, gAllowDllData, gSetSymLkup);
-	if (r!=KErrNone)
-		return r;
-	if (gSetStack)
-		f.SetStackSize(gStack);
-	if (gSetHeap)
-		{
-		f.SetHeapSizeMin(gHeapMin);
-		f.SetHeapSizeMax(gHeapMax);
-		}
-	if (!gSetUid1)
-		gUid1=TUid::Uid(f.iHdr->iUid1);
-	if (!gSetUid2)
-		gUid2=TUid::Uid(f.iHdr->iUid2);
-	if (!gSetUid3)
-		gUid3=TUid::Uid(f.iHdr->iUid3);
-	if (!gSetSecureId)
-		gSecureId = f.iHdr->iUid3;
-	if (!gSetVendorId)
-		gVendorId = 0;
-	f.SetUids(gUid1, gUid2, gUid3);
-	f.SetSecureId(gSecureId);
-	f.SetVendorId(gVendorId);
-	if (gSetCallEntryPoints)
-		f.SetCallEntryPoints(gCallEntryPoints);
-	if (gSetCapability)
-		f.SetCapability(gCapability);
-	if (gSetPriority)
-		{
-		if (f.iHdr->iFlags&KImageDll)
-			Print(EWarning,"Cannot set priority of a DLL.\n");
-		else
-			f.SetPriority((TProcessPriority)gPriority);
-		}
-	if (gSetFixedAddress)
-		{
-		if (f.iHdr->iFlags&KImageDll)
-			Print(EWarning,"Cannot set fixed address for DLL.\n");
-		else
-			f.SetFixedAddress(gFixedAddress);
-		}
-	if (gSetVersion)
-		f.iHdr->iModuleVersion = gVersionWord;
-
-	if(gCompress)
-	{
-		switch(gCompressionMethod)
-		{
-			case ENoCompression:
-				f.iHdr->iCompressionType = KFormatNotCompressed;
-				break;
-				
-			case EDeflate:
-				f.iHdr->iCompressionType = KUidCompressionDeflate;
-			
-				break;
-			
-			case EBytePair:
-				f.iHdr->iCompressionType = KUidCompressionBytePair;
-			
-				break;
-			
-			default:
-				Print(EError, "Unknown compression method:%d", gCompressionMethod);
-				return 1;
-			
-		} // End of switch()
-		
-	}
-	else
-	{
-		f.iHdr->iCompressionType = KFormatNotCompressed;		
-	}
-		
-
-	if (gSetFPU)
-		f.SetFPU(gFPU);
-
-	r = setPagedFlags(f);
-	if (r != KErrNone)
-	{
-		return r;
-	}
-
-	setDebuggableFlags(f);
-
-	setSmpSafeFlags(f);
-
-	f.CreateExportBitMap();
-	f.AddExportDescription();
-	f.UpdateHeaderCrc();
-	r = f.Validate();
-	if (r!=KErrNone)
-		return r;
-
-	ofstream ofile(ofilename, ios::binary);
-	if (!ofile)
-		{
-		Print(EError,"Cannot open %s for output.\n",ofilename);
-		return 1;
-		}
-	ofile << f;
-	ofile.close();
-	if (gVerbose)
-		f.Dump((TText*)ofilename,gVerbose);
-	return KErrNone;
-	}
-
-
-int dodump(const char* ifilename)
-	{
-	E32ImageFile f;
-	TInt r = f.Open(ifilename);
-	if (r>0)
-		return 1;
-	else if (r==KErrCorrupt || r==KErrNotSupported)
-		{
-		Print(EError,"%s is not a valid E32Image file.\n",ifilename);
-		return 1;
-		}
-	else if (r!=0)
-		{
-		Print(EError,"Error %d reading %s.\n",r,ifilename);
-		return 1;
-		}
-	f.Dump((TText*)ifilename, gVerbose ? gVerbose : E32ImageFile::EDumpDefaults);
-	return KErrNone;
-	}
-
-int doalter(const char* ifilename)
-	{
-	E32ImageFile f;
-	TInt r = f.Open(ifilename);
-	if (r>0)
-		return 1;
-	else if (r==KErrCorrupt || r==KErrNotSupported)
-		{
-		Print(EError,"%s is not a valid E32Image file.\n",ifilename);
-		return 1;
-		}
-	else if (r!=0)
-		{
-		Print(EError,"Error %d reading %s.\n",r,ifilename);
-		return 1;
-		}
-
-	TUint hdrfmt = f.iHdr->HeaderFormat();
-	if (hdrfmt != KImageHdrFmt_V)
-		{
-		Print(EError,"Can't modify old format binaries\n");
-		return 1;
-		}
-
-	if (gDataBase)
-		{
-		Print(EWarning, "Ignoring -datalinkaddress Switch");
-		}
-	if (gSetStack)
-		f.SetStackSize(gStack);
-	if (gSetHeap)
-		{
-		f.SetHeapSizeMin(gHeapMin);
-		f.SetHeapSizeMax(gHeapMax);
-		}
-	if (!gSetUid1)
-		gUid1=TUid::Uid(f.iHdr->iUid1);
-	if (!gSetUid2)
-		gUid2=TUid::Uid(f.iHdr->iUid2);
-	if (!gSetUid3)
-		gUid3=TUid::Uid(f.iHdr->iUid3);
-	f.SetUids(gUid1, gUid2, gUid3);
-	if (gSetSecureId)
-		f.SetSecureId(gSecureId);
-	if (gSetVendorId)
-		f.SetVendorId(gVendorId);
-	if (gSetCallEntryPoints)
-		f.SetCallEntryPoints(gCallEntryPoints);
-	if (gSetCapability)
-		f.SetCapability(gCapability);
-	if (gSetPriority)
-		{
-		if (f.iHdr->iFlags&KImageDll)
-			Print(EWarning,"Cannot set priority of a DLL.\n");
-		else
-			f.SetPriority((TProcessPriority)gPriority);
-		}
-	if (gSetFixedAddress)
-		{
-		if (f.iHdr->iFlags&KImageDll)
-			Print(EWarning,"Cannot set fixed address for DLL.\n");
-		else
-			f.SetFixedAddress(gFixedAddress);
-		}
-	if (gSetVersion)
-		f.iHdr->iModuleVersion = gVersionWord;
-
-	if(gCompress)
-	{
-		switch(gCompressionMethod)
-		{
-			case ENoCompression:
-				f.iHdr->iCompressionType = KFormatNotCompressed;
-				break;
-				
-			case EDeflate:
-				f.iHdr->iCompressionType = KUidCompressionDeflate;
-			
-				break;
-			
-			case EBytePair:
-				f.iHdr->iCompressionType = KUidCompressionBytePair;
-			
-				break;
-			
-			default:
-				Print(EError, "Unknown compression method:%d", gCompressionMethod);
-				return 1;
-			
-		} // End of switch()
-	}
-	else
-		f.iHdr->iCompressionType = KFormatNotCompressed;
-
-	if (gSetFPU)
-		f.SetFPU(gFPU);
-
-	r = setPagedFlags(f);
-	if (r != KErrNone)
-	{
-		return r;
-	}
-	
-	setDebuggableFlags(f);
-
-	setSmpSafeFlags(f);
-
-	f.UpdateHeaderCrc();
-	r = f.Validate();
-	if (r!=KErrNone)
-		return r;
-
-	ofstream ofile(ifilename, ios::binary);
-	if (!ofile)
-		{
-		Print(EError,"Cannot open %s for output.\n",ifilename);
-		return 1;
-		}
-	ofile << f;
-	ofile.close();
-	if (gVerbose)
-		f.Dump((TText *)ifilename,gVerbose);
-	return KErrNone;
-	}
-
-int helpme(char *aStr)
-	{
-	Print(EAlways,"Syntax: %s [options] inputfile outputfile\n",aStr);
-	Print(EAlways,"        %s [options] e32imagefile\n",aStr);
-	Print(EAlways,"option: [-v] [[-no]call[entrypoint]] [-priority <priority>]\n");
-	Print(EAlways,"        [-stack <size>] [-heap <min> <max>] [-uid<n> <uid>]\n");
-	Print(EAlways,"        [-allowdlldata] [-datalinkaddress <base>] [-fixed] [-moving]\n");
-	Print(EAlways,"        [-align-const-section] [-const-section-address-mask <mask>]\n");
-	Print(EAlways,"        [-[no]compress] [-compressionmethod none|deflate|bytepair]\n");
-	Print(EAlways,"        [-capability \"<list>\"] [-version M.m] [-vid <id>]\n");
-	Print(EAlways,"        [-fpu <softvfp|vfpv2>]\n");
-	Print(EAlways,"        [-codepaging <paged|unpaged|default>]\n");
-	Print(EAlways,"        [-datapaging <paged|unpaged|default>]\n");
-	Print(EAlways,"        [-debuggable]\n");
-	Print(EAlways,"        [-smpsafe]\n");
-	Print(EAlways,"        [-sym_name_lkup]\n");
-	Print(EAlways,"        [-dump [h][s][c][d][e][i]]\n");
-	Print(EAlways,"flags for dump: h Header\n");
-	Print(EAlways,"                s Security info\n");
-	Print(EAlways,"                c Code section\n");
-	Print(EAlways,"                d Data section\n");
-	Print(EAlways,"                e Export info\n");
-	Print(EAlways,"                i Import table\n");
-	return KErrArgument;
-	}
-
-int isNumber(char *aStr)
-	{
-	return (aStr[0]>='0') && (aStr[0]<='9');
-	}
-
-int getUIntArg(unsigned int &aVal, int argc, char *argv[], int i)
-	{
-	if (i>=argc)
-		return KErrArgument;
-	if (!isNumber(argv[i]))
-		return KErrArgument;
-#ifdef __LINUX__
-	int n;
-	sscanf(argv[i], "%i", &n);
-	aVal = n;
-#else
-#ifdef __TOOLS2__
-istringstream s(argv[i]/*, strlen(argv[i])*/);
-#else
-istrstream s(argv[i], strlen(argv[i]));
-#endif
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-	s >> setbase(0);
-#endif //__MSVCDOTNET__
-
-	s >> aVal;
-#endif // __LINUX__
-	return KErrNone;
-	}
-
-int getCapabilitiesArg(SCapabilitySet& aVal, int argc, char *argv[], int i)
-	{
-	memset(&aVal,0,sizeof(aVal));
-	if (i>=argc)
-		return KErrArgument;
-	if (isNumber(argv[i]))
-		return getUIntArg(*(TUint*)&aVal[0], argc, argv, i);
-	return ParseCapabilitiesArg(aVal,argv[i]);
-	}
-
-int getPriorityArg(int &aVal, int argc, char *argv[], int i)
-	{
-
-	if (i>=argc)
-		return KErrArgument;
-	if (isNumber(argv[i]))
-		{
-#ifdef __LINUX__
-		int n;
-		sscanf(argv[i], "%i", &n);
-		aVal = n;
-#else
-#ifdef __TOOLS2__
-istringstream s(argv[i]);
-#else
-istrstream s(argv[i], strlen(argv[i]));
-#endif
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-		s >> setbase(0);
-#endif //__MSVCDOTNET__
-
-		s>>aVal;
-#endif // __LINUX__
-		}
-	else
-		{
-		if (stricmp(argv[i], "low")==0)
-			aVal=EPriorityLow;
-		else if (strnicmp(argv[i], "background",4)==0)
-			aVal=EPriorityBackground;
-		else if (strnicmp(argv[i], "foreground",4)==0)
-			aVal=EPriorityForeground;
-		else if (stricmp(argv[i], "high")==0)
-			aVal=EPriorityHigh;
-		else if (strnicmp(argv[i], "windowserver",3)==0)
-			aVal=EPriorityWindowServer;
-		else if (strnicmp(argv[i], "fileserver",4)==0)
-			aVal=EPriorityFileServer;
-		else if (strnicmp(argv[i], "realtime",4)==0)
-			aVal=EPriorityRealTimeServer;
-		else if (strnicmp(argv[i], "supervisor",3)==0)
-			aVal=EPrioritySupervisor;
-		else
-			{
-			Print(EError, "Unrecognised priority\n");
-			return KErrArgument;
-			}
-		}
-	if (aVal<EPriorityLow || aVal>EPrioritySupervisor)
-		{
-		Print(EError, "Priority out of range\n");
-		return KErrArgument;
-		}
-	return KErrNone;
-	}
-
-int getVersionArg(unsigned int& aVal, const char* aArg)
-	{
-	const char* s = aArg;
-	unsigned int major = 0;
-	unsigned int minor = 0;
-	for (; major<=6553 && *s>='0' && *s<='9'; ++s)
-		major = major*10 + (*s - '0');
-	if (*s == '.')
-		{
-		for (++s; minor<=6553 && *s>='0' && *s<='9'; ++s)
-			minor = minor*10 + (*s - '0');
-		if (*s==0 && major<32768 && minor<32768)
-			{
-			aVal = (major << 16) | minor;
-			return KErrNone;
-			}
-		}
-	Print(EError, "Bad argument to -version\n");
-	return KErrArgument;
-	}
-
-int getFPUArg(unsigned int &aVal, int argc, char *argv[], int i)
-	{
-	if (i>=argc)
-		return KErrArgument;
-	else if (strnicmp(argv[i], "softvfp", 7)==0)
-		aVal = 0;
-	else if (strnicmp(argv[i], "vfpv2", 5)==0)
-		aVal = 1;
-	else
-		{
-		Print(EError, "Bad argument to -fpu\n");
-		return KErrArgument;
-		}
-
-	return KErrNone;
-	}
-
-int getCompressionMethod(int &aVal, int argc, char *argv[], int i)
-{
-	if( i >= argc || argv[i] == NULL)
-	{
-		Print(EError, "Missing argument to -compressionmethod\n");
-		return KErrArgument;
-	}
-	else if (strnicmp(argv[i], "none", 2) == 0)
-	{
-		aVal = ENoCompression;
-	}
-	else if (strnicmp(argv[i], "deflate", 7) == 0)
-	{
-		aVal = EDeflate;
-	}
-	else if (strnicmp(argv[i], "bytepair", 8) == 0)
-	{
-		aVal = EBytePair;
-	}
-	else
-	{
-		Print(EError, "Bad argument '%s' to -compressionmethod\n", argv[i]);
-		return KErrArgument;
-	}
-
-	return KErrNone;
-	
-}
-
-
-int processCL(int argc, char *argv[])
-	{
-
-	int r=KErrNone;
-	int i=1;
-	while (i<argc)
-		{
-		if (stricmp("-v", argv[i])==0)
-			gVerbose |= E32ImageFile::EDumpDefaults;
-		else if (stricmp("-dump", argv[i])==0)
-			{
-			i++;
-			if (i>=argc)
-				return KErrArgument;
-			char* s=argv[i];
-			while(char c = *(s++))
-				{
-				if(c<'a')
-					c += 'a'-'A';
-				switch(c)
-					{
-				case 'h': gVerbose |= E32ImageFile::EDumpHeader; break;
-				case 's': gVerbose |= E32ImageFile::EDumpSecurityInfo; break;
-				case 'c': gVerbose |= E32ImageFile::EDumpCode; break;
-				case 'd': gVerbose |= E32ImageFile::EDumpData; break;
-				case 'e': gVerbose |= E32ImageFile::EDumpExports; break;
-				case 'i': gVerbose |= E32ImageFile::EDumpImports; break;
-				default: return KErrArgument;
-					}
-				}
-			}
-		else if (stricmp("-stack", argv[i])==0)
-			{
-			i++;
-			gSetStack=TRUE;
-			r=getUIntArg(gStack, argc, argv, i);
-			}
-		else if (stricmp("-uid1", argv[i])==0)
-			{
-			i++;
-			gSetUid1=TRUE;
-			unsigned int id;
-			r=getUIntArg(id, argc, argv, i);
-			gUid1=TUid::Uid(id);
-			}
-		else if (stricmp("-uid2", argv[i])==0)
-			{
-			i++;
-			gSetUid2=TRUE;
-			unsigned int id;
-			r=getUIntArg(id, argc, argv, i);
-			gUid2=TUid::Uid(id);
-			}
-		else if (stricmp("-uid3", argv[i])==0)
-			{
-			i++;
-			gSetUid3=TRUE;
-			unsigned int id;
-			r=getUIntArg(id, argc, argv, i);
-			gUid3=TUid::Uid(id);
-			}
-		else if (stricmp("-version", argv[i])==0)
-			{
-			i++;
-			r=getVersionArg(gVersionWord, argv[i]);
-			gSetVersion=TRUE;
-			}
-		else if (stricmp("-sid", argv[i])==0)
-			{
-			i++;
-			r=getUIntArg(gSecureId, argc, argv, i);
-			gSetSecureId=TRUE;
-			}
-		else if (stricmp("-vid", argv[i])==0)
-			{
-			i++;
-			r=getUIntArg(gVendorId, argc, argv, i);
-			gSetVendorId=TRUE;
-			}
-		else if (strnicmp("-nocall", argv[i], 7)==0)
-			{
-			gSetCallEntryPoints=TRUE;
-			gCallEntryPoints=FALSE;
-			}
-		else if (strnicmp("-call", argv[i], 5)==0)
-			{
-			gSetCallEntryPoints=TRUE;
-			gCallEntryPoints=TRUE;
-			}
-		else if (strnicmp("-fixed", argv[i], 3)==0)
-			{
-			gSetFixedAddress=TRUE;
-			gFixedAddress=TRUE;
-			}
-		else if (strnicmp("-moving", argv[i], 3)==0)
-			{
-			gSetFixedAddress=TRUE;
-			gFixedAddress=FALSE;
-			}
-		else if (strnicmp("-priority", argv[i], 4)==0)
-			{
-			i++;
-			gSetPriority=TRUE;
-			r=getPriorityArg(gPriority,argc,argv,i);
-			}
-		else if (strnicmp("-capability", argv[i], 10)==0)
-			{
-			i++;
-			gSetCapability=TRUE;
-			r=getCapabilitiesArg(gCapability, argc, argv, i);
-			}
-		else if (strnicmp("-heap", argv[i], 4)==0)
-			{
-			i++;
-			gSetHeap=TRUE;
-			r=getUIntArg(gHeapMin, argc, argv, i);
-			if (r==KErrNone)
-				r=getUIntArg(gHeapMax, argc, argv, ++i);
-			}
-		else if (strnicmp("-allow", argv[i], 6)==0) // Note, toolchain passes 'allow' for 'allowdlldata'
-			{
-			gAllowDllData=TRUE;
-			}
-		else if( strnicmp("-compressionmethod", argv[i], 18) == 0)
-		{
-			if(!gSuppressComprMethod)
-			{
-				gCompress = TRUE;
-				gSetCompress = TRUE;
-				r = getCompressionMethod(gCompressionMethod, argc, argv, ++i);  
-			}
-			else
-			{
-				++i; // Skip the compression method because compessionmethod suppressed.
-			}
-		}
-		else if (strnicmp("-compress", argv[i], 9)==0)
-			{
-			gCompress=TRUE;
-			gSetCompress=TRUE;
-			gSuppressComprMethod=FALSE;
-			}
-		else if (strnicmp("-nocompress", argv[i], 11)==0)
-			{
-			gCompress=FALSE;
-			gSetCompress=TRUE;
-			gSuppressComprMethod = TRUE;
-			gCompressionMethod = ENoCompression;
-			}
-		else if (strnicmp("-datalinkaddress", argv[i], 16)==0)
-			{
-			i++;
-			r=getUIntArg(gDataBase, argc, argv, i);
-			}
-		else if (strnicmp("-align-const-section", argv[i], 20)==0)
-			{
-			gAlignConstSection=TRUE;
-			}
-		else if (strnicmp("-const-section-address-mask", argv[i], 27)==0)
-			{
-			i++;
-			r=getUIntArg(gConstSectionAddressMask, argc, argv, i);
-			}
-		else if (strnicmp("-fpu", argv[i], 4)==0)
-			{
-			i++;
-			r=getFPUArg(gFPU, argc, argv, i);
-			gSetFPU=TRUE;
-			}
-		else if (strnicmp("-paged", argv[i], 6) == 0)
-			{
-			gCodePaged=TRUE;
-			gSetCodePaged=TRUE;
-			}
-		else if (strnicmp("-unpaged", argv[i], 8) == 0)
-			{
-			gCodeUnpaged=TRUE;
-			gSetCodePaged=TRUE;
-			}
-		else if (strnicmp("-defaultpaged", argv[i], 13) == 0)
-			{
-			gCodeDefaultPaged=TRUE;
-			gSetCodePaged=TRUE;
-			}
-		else if (strnicmp("-codepaging", argv[i], 11)==0)
-			{
-			i++;
-
-			if (i>=argc)
-				{
-				r = KErrArgument;
-				}
-			else if ( strnicmp(argv[i], "paged", 5) == 0 )
-				{
-				gCodePaged=TRUE;
-				}
-			else if ( strnicmp(argv[i], "unpaged", 7) == 0 )
-				{
-				gCodeUnpaged=TRUE;
-				}
-			else if ( strnicmp(argv[i], "default", 7) == 0 )
-				{
-				gCodeDefaultPaged=TRUE;
-				}
-			else
-				{
-				Print(EError, "Bad argument to -codepaging\n");
-				r = KErrArgument;
-				}
-
-			gSetCodePaged=TRUE;
-			}
-		else if (strnicmp("-datapaging", argv[i], 11)==0)
-			{
-			i++;
-
-			if (i>=argc)
-				{
-				r = KErrArgument;
-				}
-			else if ( strnicmp(argv[i], "paged", 5) == 0 )
-				{
-				gDataPaged=TRUE;
-				}
-			else if ( strnicmp(argv[i], "unpaged", 7) == 0 )
-				{
-				gDataUnpaged=TRUE;
-				}
-			else if ( strnicmp(argv[i], "default", 7) == 0 )
-				{
-				gDataDefaultPaged=TRUE;
-				}
-			else
-				{
-				Print(EError, "Bad argument to -datapaging\n");
-				r = KErrArgument;
-				}
-
-			gSetDataPaged=TRUE;
-			}
-		else if (strnicmp("-sym_name_lkup", argv[i], 14) == 0)
-			{
-			gSetSymLkup=TRUE;
-			}
-		else if (strnicmp("-debuggable", argv[i], 11) == 0)
-			{
-			gDebuggable=TRUE;
-			gSetDebuggable=TRUE;
-			}
-		else if (strnicmp("-smpsafe", argv[i], 8) == 0)
-			{
-			gSmpSafe=TRUE;
-			gSetSmpSafe=TRUE;
-			}
-#ifdef __SUPPORT_PE_FILES__
-		else if (strnicmp("-x86imp=", argv[i], 8)==0)
-			{
-			const char* x86impfile=argv[i]+8;
-			FILE* f=fopen(x86impfile,"rb");
-			if (!f)
-				r=KErrArgument;
-			else
-				{
-				fseek(f,0,SEEK_END);
-				long size=ftell(f);
-				fseek(f,0,SEEK_SET);
-				if (size>4)
-					{
-					gX86imp=new char[size];
-					fread(gX86imp,1,size,f);
-					}
-				fclose(f);
-				r=KErrNone;
-				if (gX86imp)
-					{
-					gX86imp_size=ALIGN4(size);
-					int i;
-					int* p=(int*)gX86imp;
-					gX86num_imp_dlls=*p++;
-					for (i=0; i<gX86num_imp_dlls; ++i)
-						{
-						++p;
-						int n=*p++;
-						gX86num_imports+=n;
-						p+=n;
-						}
-					}
-				}
-			}
-#endif
-		else if (gFile1==NULL)
-			{
-			gFile1 = NormaliseFileName(argv[i]);
-			}
-		else if (gFile2==NULL)
-			{
-			gFile2 = NormaliseFileName(argv[i]);
-			}
-		else
-			r=KErrArgument;
-		if (r!=KErrNone)
-			return r;
-		i++;
-		}
-	return KErrNone;
-	}
-
-int main(int argc, char *argv[])
-	{
-#ifdef __SUPPORT_PE_FILES__
-	Print(EAlways,"\nPETRAN - PE file preprocessor");
-#endif
-#ifdef __SUPPORT_ELF_FILES__
-	Print(EAlways,"\nELFTRAN - ELF file preprocessor");
-#endif
-  	Print(EAlways," V%02d.%02d (Build %03d)\n",MajorVersion,MinorVersion,Build);
-	int r=processCL(argc, argv);
-	if (r!=KErrNone)
-		return helpme(argv[0]);
-	if (gFile2)
-		return dotran(gFile1, gFile2);
-	if ((gSetStack || gSetUid1 || gSetUid2 || gSetUid3 || gSetCallEntryPoints || gSetPriority
-		|| gSetCapability || gSetCompress || gSetHeap || gSetVersion || gSetSecureId
-		|| gSetVendorId || gSetFixedAddress || gSetFPU || gSetCodePaged || gSetDataPaged || gSetDebuggable || gSetSmpSafe) && gFile1)
-		return doalter(gFile1);
-	if (gFile1)
-		return dodump(gFile1);
-	helpme(argv[0]);
-	return KErrArgument;
-	}
+/*
+* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* e32tools/e32image/tr_main.cpp
+* Translate X->E32Image top level
+*
+*/
+
+
+#ifndef __LINUX__
+  #include <io.h>
+#endif
+#include <string.h>
+
+#ifdef __VC32__
+ #ifdef __MSVCDOTNET__
+  #include <strstream>
+  #include <iomanip>
+ #else //!__MSVCDOTNET__
+  #include <strstrea.h>
+  #include <iomanip.h>
+ #endif //__MSVCDOTNET__
+#else // !__VC32__*/
+#ifdef __TOOLS2__
+  #include <sstream>
+  #include <iomanip>
+  #else
+ #include <strstream.h>
+ #include <iomanip.h>
+#endif // __VC32__
+#endif
+
+#include <e32std.h>
+#include <e32std_private.h>
+
+#ifdef __SUPPORT_PE_FILES__
+#include "pe_file.h"
+#endif
+#ifdef __SUPPORT_ELF_FILES__
+#include "elftran.h"
+#endif
+
+#include "h_utl.h"
+#include "h_ver.h"
+#include <stdio.h>
+
+extern int gAlignConstSection;
+extern TUint gConstSectionAddressMask;
+
+int gVerbose=0;
+char *gFile1=NULL;
+char *gFile2=NULL;
+unsigned int gStack=0;
+unsigned int gHeapMin=0;
+unsigned int gHeapMax=0;
+TUid gUid1=KNullUid;
+TUid gUid2=KNullUid;
+TUid gUid3=KNullUid;
+unsigned int gSecureId=0;
+unsigned int gVendorId=0;
+unsigned int gVersionWord=0x00010000u;
+int gCallEntryPoints=TRUE;
+int gFixedAddress=FALSE;
+int gPriority=EPriorityForeground;
+SCapabilitySet gCapability={{0}};
+int gAllowDllData=FALSE;
+// fix warning for Linux warning: 0 instead of NULL
+TUint gDataBase=0;
+int gCompress=TRUE;
+unsigned int gFPU=0;
+
+int gCodePaged=FALSE;
+int gCodeUnpaged=FALSE;
+int gCodeDefaultPaged=FALSE;
+
+int gDataPaged=FALSE;
+int gDataUnpaged=FALSE;
+int gDataDefaultPaged=FALSE;
+
+int gDebuggable=FALSE;
+int gSmpSafe=FALSE;
+
+int gSetStack=FALSE;
+int gSetHeap=FALSE;
+int gSetUid1=FALSE;
+int gSetUid2=FALSE;
+int gSetUid3=FALSE;
+int gSetCallEntryPoints=FALSE;
+int gSetFixedAddress=FALSE;
+int gSetPriority=FALSE;
+int gSetCapability=FALSE;
+int gSetCompress=FALSE;
+int gSetVersion=FALSE;
+int gSetSecureId=FALSE;
+int gSetVendorId=FALSE;
+int gSetFPU=FALSE;
+
+int gSetCodePaged=FALSE;
+int gSetDataPaged=FALSE;
+
+int gSetSymLkup=FALSE;
+int gSetDebuggable=FALSE;
+int gSetSmpSafe=FALSE;
+
+enum CompressionMethods
+{
+	ENoCompression = 0,
+	EDeflate = 1,
+	EBytePair = 2,
+};
+
+int gCompressionMethod = EDeflate;
+int gSuppressComprMethod = FALSE;
+
+#ifdef __SUPPORT_PE_FILES__
+char* gX86imp=NULL;
+int gX86num_imp_dlls=0;
+int gX86imp_size=0;
+int gX86num_imports=0;
+#endif
+
+TBool gLittleEndian=ETrue;
+
+class E32ImageFileRef
+	{
+public:
+	E32ImageFileRef() {iPtr = E32ImageFile::New();}
+	~E32ImageFileRef() {delete iPtr;}
+	class E32ImageFile& Ref() {return *iPtr;}
+private:
+	E32ImageFileRef(const E32ImageFileRef&);
+	E32ImageFileRef& operator=(const E32ImageFileRef&);
+private:
+	E32ImageFile* iPtr;
+	};
+
+int setPagedFlags(E32ImageFile& f)
+	{
+	unsigned check1 = gCodePaged + gCodeUnpaged + gCodeDefaultPaged;
+	unsigned check2 = gDataPaged + gDataUnpaged + gDataDefaultPaged;
+
+	if (check1 > 1 || check2 > 1)
+		{
+		Print(EError, "Conflicting paging options.\n");
+		return KErrArgument;
+		}
+
+	if (gCodePaged)
+		{
+		f.iHdr->iFlags |= KImageCodePaged;
+		f.iHdr->iFlags &= ~KImageCodeUnpaged;
+		}
+	else if (gCodeUnpaged)
+		{
+		f.iHdr->iFlags |= KImageCodeUnpaged;
+		f.iHdr->iFlags &= ~KImageCodePaged;
+		}
+	else if (gCodeDefaultPaged)
+		{
+		f.iHdr->iFlags &= ~KImageCodePaged;
+		f.iHdr->iFlags &= ~KImageCodeUnpaged;
+		}
+
+	if (gDataPaged)
+		{
+		f.iHdr->iFlags |=  KImageDataPaged;
+		f.iHdr->iFlags &= ~KImageDataUnpaged;
+		}
+	else if (gDataUnpaged)
+		{
+		f.iHdr->iFlags |=  KImageDataUnpaged;
+		f.iHdr->iFlags &= ~KImageDataPaged;
+		}
+	else if (gDataDefaultPaged)
+		{
+		f.iHdr->iFlags &= ~KImageDataPaged;
+		f.iHdr->iFlags &= ~KImageDataUnpaged;
+		}
+
+	return KErrNone;
+	}
+
+void setDebuggableFlags(E32ImageFile& f)
+	{
+	if (gDebuggable)
+		{
+		f.iHdr->iFlags |= KImageDebuggable;
+		}
+	else
+		{
+		f.iHdr->iFlags &= ~KImageDebuggable;
+		}
+	}
+
+void setSmpSafeFlags(E32ImageFile& f)
+	{
+	if (gSmpSafe)
+		{
+		f.iHdr->iFlags |= KImageSMPSafe;
+		}
+	else
+		{
+		f.iHdr->iFlags &= ~KImageSMPSafe;
+		}
+	}
+
+int dotran(const char* ifilename, const char* ofilename)
+	{
+	E32ImageFileRef fRef;
+	E32ImageFile& f = fRef.Ref();
+	int r=f.Translate(ifilename, gDataBase, gAllowDllData, gSetSymLkup);
+	if (r!=KErrNone)
+		return r;
+	if (gSetStack)
+		f.SetStackSize(gStack);
+	if (gSetHeap)
+		{
+		f.SetHeapSizeMin(gHeapMin);
+		f.SetHeapSizeMax(gHeapMax);
+		}
+	if (!gSetUid1)
+		gUid1=TUid::Uid(f.iHdr->iUid1);
+	if (!gSetUid2)
+		gUid2=TUid::Uid(f.iHdr->iUid2);
+	if (!gSetUid3)
+		gUid3=TUid::Uid(f.iHdr->iUid3);
+	if (!gSetSecureId)
+		gSecureId = f.iHdr->iUid3;
+	if (!gSetVendorId)
+		gVendorId = 0;
+	f.SetUids(gUid1, gUid2, gUid3);
+	f.SetSecureId(gSecureId);
+	f.SetVendorId(gVendorId);
+	if (gSetCallEntryPoints)
+		f.SetCallEntryPoints(gCallEntryPoints);
+	if (gSetCapability)
+		f.SetCapability(gCapability);
+	if (gSetPriority)
+		{
+		if (f.iHdr->iFlags&KImageDll)
+			Print(EWarning,"Cannot set priority of a DLL.\n");
+		else
+			f.SetPriority((TProcessPriority)gPriority);
+		}
+	if (gSetFixedAddress)
+		{
+		if (f.iHdr->iFlags&KImageDll)
+			Print(EWarning,"Cannot set fixed address for DLL.\n");
+		else
+			f.SetFixedAddress(gFixedAddress);
+		}
+	if (gSetVersion)
+		f.iHdr->iModuleVersion = gVersionWord;
+
+	if(gCompress)
+	{
+		switch(gCompressionMethod)
+		{
+			case ENoCompression:
+				f.iHdr->iCompressionType = KFormatNotCompressed;
+				break;
+				
+			case EDeflate:
+				f.iHdr->iCompressionType = KUidCompressionDeflate;
+			
+				break;
+			
+			case EBytePair:
+				f.iHdr->iCompressionType = KUidCompressionBytePair;
+			
+				break;
+			
+			default:
+				Print(EError, "Unknown compression method:%d", gCompressionMethod);
+				return 1;
+			
+		} // End of switch()
+		
+	}
+	else
+	{
+		f.iHdr->iCompressionType = KFormatNotCompressed;		
+	}
+		
+
+	if (gSetFPU)
+		f.SetFPU(gFPU);
+
+	r = setPagedFlags(f);
+	if (r != KErrNone)
+	{
+		return r;
+	}
+
+	setDebuggableFlags(f);
+
+	setSmpSafeFlags(f);
+
+	f.CreateExportBitMap();
+	f.AddExportDescription();
+	f.UpdateHeaderCrc();
+	r = f.Validate();
+	if (r!=KErrNone)
+		return r;
+
+	ofstream ofile(ofilename, ios::binary);
+	if (!ofile)
+		{
+		Print(EError,"Cannot open %s for output.\n",ofilename);
+		return 1;
+		}
+	ofile << f;
+	ofile.close();
+	if (gVerbose)
+		f.Dump(ofilename,gVerbose);
+	return KErrNone;
+	}
+
+
+int dodump(const char* ifilename)
+	{
+	E32ImageFile f;
+	TInt r = f.Open(ifilename);
+	if (r>0)
+		return 1;
+	else if (r==KErrCorrupt || r==KErrNotSupported)
+		{
+		Print(EError,"%s is not a valid E32Image file.\n",ifilename);
+		return 1;
+		}
+	else if (r!=0)
+		{
+		Print(EError,"Error %d reading %s.\n",r,ifilename);
+		return 1;
+		}
+	f.Dump(ifilename, gVerbose ? gVerbose : E32ImageFile::EDumpDefaults);
+	return KErrNone;
+	}
+
+int doalter(const char* ifilename)
+	{
+	E32ImageFile f;
+	TInt r = f.Open(ifilename);
+	if (r>0)
+		return 1;
+	else if (r==KErrCorrupt || r==KErrNotSupported)
+		{
+		Print(EError,"%s is not a valid E32Image file.\n",ifilename);
+		return 1;
+		}
+	else if (r!=0)
+		{
+		Print(EError,"Error %d reading %s.\n",r,ifilename);
+		return 1;
+		}
+
+	TUint hdrfmt = f.iHdr->HeaderFormat();
+	if (hdrfmt != KImageHdrFmt_V)
+		{
+		Print(EError,"Can't modify old format binaries\n");
+		return 1;
+		}
+
+	if (gDataBase)
+		{
+		Print(EWarning, "Ignoring -datalinkaddress Switch");
+		}
+	if (gSetStack)
+		f.SetStackSize(gStack);
+	if (gSetHeap)
+		{
+		f.SetHeapSizeMin(gHeapMin);
+		f.SetHeapSizeMax(gHeapMax);
+		}
+	if (!gSetUid1)
+		gUid1=TUid::Uid(f.iHdr->iUid1);
+	if (!gSetUid2)
+		gUid2=TUid::Uid(f.iHdr->iUid2);
+	if (!gSetUid3)
+		gUid3=TUid::Uid(f.iHdr->iUid3);
+	f.SetUids(gUid1, gUid2, gUid3);
+	if (gSetSecureId)
+		f.SetSecureId(gSecureId);
+	if (gSetVendorId)
+		f.SetVendorId(gVendorId);
+	if (gSetCallEntryPoints)
+		f.SetCallEntryPoints(gCallEntryPoints);
+	if (gSetCapability)
+		f.SetCapability(gCapability);
+	if (gSetPriority)
+		{
+		if (f.iHdr->iFlags&KImageDll)
+			Print(EWarning,"Cannot set priority of a DLL.\n");
+		else
+			f.SetPriority((TProcessPriority)gPriority);
+		}
+	if (gSetFixedAddress)
+		{
+		if (f.iHdr->iFlags&KImageDll)
+			Print(EWarning,"Cannot set fixed address for DLL.\n");
+		else
+			f.SetFixedAddress(gFixedAddress);
+		}
+	if (gSetVersion)
+		f.iHdr->iModuleVersion = gVersionWord;
+
+	if(gCompress)
+	{
+		switch(gCompressionMethod)
+		{
+			case ENoCompression:
+				f.iHdr->iCompressionType = KFormatNotCompressed;
+				break;
+				
+			case EDeflate:
+				f.iHdr->iCompressionType = KUidCompressionDeflate;
+			
+				break;
+			
+			case EBytePair:
+				f.iHdr->iCompressionType = KUidCompressionBytePair;
+			
+				break;
+			
+			default:
+				Print(EError, "Unknown compression method:%d", gCompressionMethod);
+				return 1;
+			
+		} // End of switch()
+	}
+	else
+		f.iHdr->iCompressionType = KFormatNotCompressed;
+
+	if (gSetFPU)
+		f.SetFPU(gFPU);
+
+	r = setPagedFlags(f);
+	if (r != KErrNone)
+	{
+		return r;
+	}
+	
+	setDebuggableFlags(f);
+
+	setSmpSafeFlags(f);
+
+	f.UpdateHeaderCrc();
+	r = f.Validate();
+	if (r!=KErrNone)
+		return r;
+
+	ofstream ofile(ifilename, ios::binary);
+	if (!ofile)
+		{
+		Print(EError,"Cannot open %s for output.\n",ifilename);
+		return 1;
+		}
+	ofile << f;
+	ofile.close();
+	if (gVerbose)
+		f.Dump(ifilename,gVerbose);
+	return KErrNone;
+	}
+
+int helpme(char *aStr)
+	{
+	Print(EAlways,"Syntax: %s [options] inputfile outputfile\n",aStr);
+	Print(EAlways,"        %s [options] e32imagefile\n",aStr);
+	Print(EAlways,"option: [-v] [[-no]call[entrypoint]] [-priority <priority>]\n");
+	Print(EAlways,"        [-stack <size>] [-heap <min> <max>] [-uid<n> <uid>]\n");
+	Print(EAlways,"        [-allowdlldata] [-datalinkaddress <base>] [-fixed] [-moving]\n");
+	Print(EAlways,"        [-align-const-section] [-const-section-address-mask <mask>]\n");
+	Print(EAlways,"        [-[no]compress] [-compressionmethod none|deflate|bytepair]\n");
+	Print(EAlways,"        [-capability \"<list>\"] [-version M.m] [-vid <id>]\n");
+	Print(EAlways,"        [-fpu <softvfp|vfpv2>]\n");
+	Print(EAlways,"        [-codepaging <paged|unpaged|default>]\n");
+	Print(EAlways,"        [-datapaging <paged|unpaged|default>]\n");
+	Print(EAlways,"        [-debuggable]\n");
+	Print(EAlways,"        [-smpsafe]\n");
+	Print(EAlways,"        [-sym_name_lkup]\n");
+	Print(EAlways,"        [-dump [h][s][c][d][e][i]]\n");
+	Print(EAlways,"flags for dump: h Header\n");
+	Print(EAlways,"                s Security info\n");
+	Print(EAlways,"                c Code section\n");
+	Print(EAlways,"                d Data section\n");
+	Print(EAlways,"                e Export info\n");
+	Print(EAlways,"                i Import table\n");
+	return KErrArgument;
+	}
+
+int isNumber(char *aStr)
+	{
+	return (aStr[0]>='0') && (aStr[0]<='9');
+	}
+
+int getUIntArg(unsigned int &aVal, int argc, char *argv[], int i)
+	{
+	if (i>=argc)
+		return KErrArgument;
+	if (!isNumber(argv[i]))
+		return KErrArgument;
+ 
+	return Val(aVal,argv[i]); 
+	}
+
+int getCapabilitiesArg(SCapabilitySet& aVal, int argc, char *argv[], int i)
+	{
+	memset(&aVal,0,sizeof(aVal));
+	if (i>=argc)
+		return KErrArgument;
+	if (isNumber(argv[i]))
+		return getUIntArg(*(TUint*)&aVal[0], argc, argv, i);
+	return ParseCapabilitiesArg(aVal,argv[i]);
+	}
+
+int getPriorityArg(int &aVal, int argc, char *argv[], int i)
+	{
+
+	if (i>=argc)
+		return KErrArgument;
+	if (isNumber(argv[i]))
+		{
+#ifdef __LINUX__
+		int n;
+		sscanf(argv[i], "%i", &n);
+		aVal = n;
+#else
+#ifdef __TOOLS2__
+istringstream s(argv[i]);
+#else
+istrstream s(argv[i], strlen(argv[i]));
+#endif
+
+#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
+		s >> setbase(0);
+#endif //__MSVCDOTNET__
+
+		s>>aVal;
+#endif // __LINUX__
+		}
+	else
+		{
+		if (stricmp(argv[i], "low")==0)
+			aVal=EPriorityLow;
+		else if (strnicmp(argv[i], "background",4)==0)
+			aVal=EPriorityBackground;
+		else if (strnicmp(argv[i], "foreground",4)==0)
+			aVal=EPriorityForeground;
+		else if (stricmp(argv[i], "high")==0)
+			aVal=EPriorityHigh;
+		else if (strnicmp(argv[i], "windowserver",3)==0)
+			aVal=EPriorityWindowServer;
+		else if (strnicmp(argv[i], "fileserver",4)==0)
+			aVal=EPriorityFileServer;
+		else if (strnicmp(argv[i], "realtime",4)==0)
+			aVal=EPriorityRealTimeServer;
+		else if (strnicmp(argv[i], "supervisor",3)==0)
+			aVal=EPrioritySupervisor;
+		else
+			{
+			Print(EError, "Unrecognised priority\n");
+			return KErrArgument;
+			}
+		}
+	if (aVal<EPriorityLow || aVal>EPrioritySupervisor)
+		{
+		Print(EError, "Priority out of range\n");
+		return KErrArgument;
+		}
+	return KErrNone;
+	}
+
+int getVersionArg(unsigned int& aVal, const char* aArg)
+	{
+	const char* s = aArg;
+	unsigned int major = 0;
+	unsigned int minor = 0;
+	for (; major<=6553 && *s>='0' && *s<='9'; ++s)
+		major = major*10 + (*s - '0');
+	if (*s == '.')
+		{
+		for (++s; minor<=6553 && *s>='0' && *s<='9'; ++s)
+			minor = minor*10 + (*s - '0');
+		if (*s==0 && major<32768 && minor<32768)
+			{
+			aVal = (major << 16) | minor;
+			return KErrNone;
+			}
+		}
+	Print(EError, "Bad argument to -version\n");
+	return KErrArgument;
+	}
+
+int getFPUArg(unsigned int &aVal, int argc, char *argv[], int i)
+	{
+	if (i>=argc)
+		return KErrArgument;
+	else if (strnicmp(argv[i], "softvfp", 7)==0)
+		aVal = 0;
+	else if (strnicmp(argv[i], "vfpv2", 5)==0)
+		aVal = 1;
+	else
+		{
+		Print(EError, "Bad argument to -fpu\n");
+		return KErrArgument;
+		}
+
+	return KErrNone;
+	}
+
+int getCompressionMethod(int &aVal, int argc, char *argv[], int i)
+{
+	if( i >= argc || argv[i] == NULL)
+	{
+		Print(EError, "Missing argument to -compressionmethod\n");
+		return KErrArgument;
+	}
+	else if (strnicmp(argv[i], "none", 2) == 0)
+	{
+		aVal = ENoCompression;
+	}
+	else if (strnicmp(argv[i], "deflate", 7) == 0)
+	{
+		aVal = EDeflate;
+	}
+	else if (strnicmp(argv[i], "bytepair", 8) == 0)
+	{
+		aVal = EBytePair;
+	}
+	else
+	{
+		Print(EError, "Bad argument '%s' to -compressionmethod\n", argv[i]);
+		return KErrArgument;
+	}
+
+	return KErrNone;
+	
+}
+
+
+int processCL(int argc, char *argv[])
+	{
+
+	int r=KErrNone;
+	int i=1;
+	while (i<argc)
+		{
+		if (stricmp("-v", argv[i])==0)
+			gVerbose |= E32ImageFile::EDumpDefaults;
+		else if (stricmp("-dump", argv[i])==0)
+			{
+			i++;
+			if (i>=argc)
+				return KErrArgument;
+			char* s=argv[i];
+			while(char c = *(s++))
+				{
+				if(c<'a')
+					c += 'a'-'A';
+				switch(c)
+					{
+				case 'h': gVerbose |= E32ImageFile::EDumpHeader; break;
+				case 's': gVerbose |= E32ImageFile::EDumpSecurityInfo; break;
+				case 'c': gVerbose |= E32ImageFile::EDumpCode; break;
+				case 'd': gVerbose |= E32ImageFile::EDumpData; break;
+				case 'e': gVerbose |= E32ImageFile::EDumpExports; break;
+				case 'i': gVerbose |= E32ImageFile::EDumpImports; break;
+				default: return KErrArgument;
+					}
+				}
+			}
+		else if (stricmp("-stack", argv[i])==0)
+			{
+			i++;
+			gSetStack=TRUE;
+			r=getUIntArg(gStack, argc, argv, i);
+			}
+		else if (stricmp("-uid1", argv[i])==0)
+			{
+			i++;
+			gSetUid1=TRUE;
+			unsigned int id;
+			r=getUIntArg(id, argc, argv, i);
+			gUid1=TUid::Uid(id);
+			}
+		else if (stricmp("-uid2", argv[i])==0)
+			{
+			i++;
+			gSetUid2=TRUE;
+			unsigned int id;
+			r=getUIntArg(id, argc, argv, i);
+			gUid2=TUid::Uid(id);
+			}
+		else if (stricmp("-uid3", argv[i])==0)
+			{
+			i++;
+			gSetUid3=TRUE;
+			unsigned int id;
+			r=getUIntArg(id, argc, argv, i);
+			gUid3=TUid::Uid(id);
+			}
+		else if (stricmp("-version", argv[i])==0)
+			{
+			i++;
+			r=getVersionArg(gVersionWord, argv[i]);
+			gSetVersion=TRUE;
+			}
+		else if (stricmp("-sid", argv[i])==0)
+			{
+			i++;
+			r=getUIntArg(gSecureId, argc, argv, i);
+			gSetSecureId=TRUE;
+			}
+		else if (stricmp("-vid", argv[i])==0)
+			{
+			i++;
+			r=getUIntArg(gVendorId, argc, argv, i);
+			gSetVendorId=TRUE;
+			}
+		else if (strnicmp("-nocall", argv[i], 7)==0)
+			{
+			gSetCallEntryPoints=TRUE;
+			gCallEntryPoints=FALSE;
+			}
+		else if (strnicmp("-call", argv[i], 5)==0)
+			{
+			gSetCallEntryPoints=TRUE;
+			gCallEntryPoints=TRUE;
+			}
+		else if (strnicmp("-fixed", argv[i], 3)==0)
+			{
+			gSetFixedAddress=TRUE;
+			gFixedAddress=TRUE;
+			}
+		else if (strnicmp("-moving", argv[i], 3)==0)
+			{
+			gSetFixedAddress=TRUE;
+			gFixedAddress=FALSE;
+			}
+		else if (strnicmp("-priority", argv[i], 4)==0)
+			{
+			i++;
+			gSetPriority=TRUE;
+			r=getPriorityArg(gPriority,argc,argv,i);
+			}
+		else if (strnicmp("-capability", argv[i], 10)==0)
+			{
+			i++;
+			gSetCapability=TRUE;
+			r=getCapabilitiesArg(gCapability, argc, argv, i);
+			}
+		else if (strnicmp("-heap", argv[i], 4)==0)
+			{
+			i++;
+			gSetHeap=TRUE;
+			r=getUIntArg(gHeapMin, argc, argv, i);
+			if (r==KErrNone)
+				r=getUIntArg(gHeapMax, argc, argv, ++i);
+			}
+		else if (strnicmp("-allow", argv[i], 6)==0) // Note, toolchain passes 'allow' for 'allowdlldata'
+			{
+			gAllowDllData=TRUE;
+			}
+		else if( strnicmp("-compressionmethod", argv[i], 18) == 0)
+		{
+			if(!gSuppressComprMethod)
+			{
+				gCompress = TRUE;
+				gSetCompress = TRUE;
+				r = getCompressionMethod(gCompressionMethod, argc, argv, ++i);  
+			}
+			else
+			{
+				++i; // Skip the compression method because compessionmethod suppressed.
+			}
+		}
+		else if (strnicmp("-compress", argv[i], 9)==0)
+			{
+			gCompress=TRUE;
+			gSetCompress=TRUE;
+			gSuppressComprMethod=FALSE;
+			}
+		else if (strnicmp("-nocompress", argv[i], 11)==0)
+			{
+			gCompress=FALSE;
+			gSetCompress=TRUE;
+			gSuppressComprMethod = TRUE;
+			gCompressionMethod = ENoCompression;
+			}
+		else if (strnicmp("-datalinkaddress", argv[i], 16)==0)
+			{
+			i++;
+			r=getUIntArg(gDataBase, argc, argv, i);
+			}
+		else if (strnicmp("-align-const-section", argv[i], 20)==0)
+			{
+			gAlignConstSection=TRUE;
+			}
+		else if (strnicmp("-const-section-address-mask", argv[i], 27)==0)
+			{
+			i++;
+			r=getUIntArg(gConstSectionAddressMask, argc, argv, i);
+			}
+		else if (strnicmp("-fpu", argv[i], 4)==0)
+			{
+			i++;
+			r=getFPUArg(gFPU, argc, argv, i);
+			gSetFPU=TRUE;
+			}
+		else if (strnicmp("-paged", argv[i], 6) == 0)
+			{
+			gCodePaged=TRUE;
+			gSetCodePaged=TRUE;
+			}
+		else if (strnicmp("-unpaged", argv[i], 8) == 0)
+			{
+			gCodeUnpaged=TRUE;
+			gSetCodePaged=TRUE;
+			}
+		else if (strnicmp("-defaultpaged", argv[i], 13) == 0)
+			{
+			gCodeDefaultPaged=TRUE;
+			gSetCodePaged=TRUE;
+			}
+		else if (strnicmp("-codepaging", argv[i], 11)==0)
+			{
+			i++;
+
+			if (i>=argc)
+				{
+				r = KErrArgument;
+				}
+			else if ( strnicmp(argv[i], "paged", 5) == 0 )
+				{
+				gCodePaged=TRUE;
+				}
+			else if ( strnicmp(argv[i], "unpaged", 7) == 0 )
+				{
+				gCodeUnpaged=TRUE;
+				}
+			else if ( strnicmp(argv[i], "default", 7) == 0 )
+				{
+				gCodeDefaultPaged=TRUE;
+				}
+			else
+				{
+				Print(EError, "Bad argument to -codepaging\n");
+				r = KErrArgument;
+				}
+
+			gSetCodePaged=TRUE;
+			}
+		else if (strnicmp("-datapaging", argv[i], 11)==0)
+			{
+			i++;
+
+			if (i>=argc)
+				{
+				r = KErrArgument;
+				}
+			else if ( strnicmp(argv[i], "paged", 5) == 0 )
+				{
+				gDataPaged=TRUE;
+				}
+			else if ( strnicmp(argv[i], "unpaged", 7) == 0 )
+				{
+				gDataUnpaged=TRUE;
+				}
+			else if ( strnicmp(argv[i], "default", 7) == 0 )
+				{
+				gDataDefaultPaged=TRUE;
+				}
+			else
+				{
+				Print(EError, "Bad argument to -datapaging\n");
+				r = KErrArgument;
+				}
+
+			gSetDataPaged=TRUE;
+			}
+		else if (strnicmp("-sym_name_lkup", argv[i], 14) == 0)
+			{
+			gSetSymLkup=TRUE;
+			}
+		else if (strnicmp("-debuggable", argv[i], 11) == 0)
+			{
+			gDebuggable=TRUE;
+			gSetDebuggable=TRUE;
+			}
+		else if (strnicmp("-smpsafe", argv[i], 8) == 0)
+			{
+			gSmpSafe=TRUE;
+			gSetSmpSafe=TRUE;
+			}
+#ifdef __SUPPORT_PE_FILES__
+		else if (strnicmp("-x86imp=", argv[i], 8)==0)
+			{
+			const char* x86impfile=argv[i]+8;
+			FILE* f=fopen(x86impfile,"rb");
+			if (!f)
+				r=KErrArgument;
+			else
+				{
+				fseek(f,0,SEEK_END);
+				long size=ftell(f);
+				fseek(f,0,SEEK_SET);
+				if (size>4)
+					{
+					gX86imp=new char[size];
+					fread(gX86imp,1,size,f);
+					}
+				fclose(f);
+				r=KErrNone;
+				if (gX86imp)
+					{
+					gX86imp_size=ALIGN4(size);
+					int i;
+					int* p=(int*)gX86imp;
+					gX86num_imp_dlls=*p++;
+					for (i=0; i<gX86num_imp_dlls; ++i)
+						{
+						++p;
+						int n=*p++;
+						gX86num_imports+=n;
+						p+=n;
+						}
+					}
+				}
+			}
+#endif
+		else if (gFile1==NULL)
+			{
+			gFile1 = NormaliseFileName(argv[i]);
+			}
+		else if (gFile2==NULL)
+			{
+			gFile2 = NormaliseFileName(argv[i]);
+			}
+		else
+			r=KErrArgument;
+		if (r!=KErrNone)
+			return r;
+		i++;
+		}
+	return KErrNone;
+	}
+
+int main(int argc, char *argv[])
+	{
+#ifdef __SUPPORT_PE_FILES__
+	Print(EAlways,"\nPETRAN - PE file preprocessor");
+#endif
+#ifdef __SUPPORT_ELF_FILES__
+	Print(EAlways,"\nELFTRAN - ELF file preprocessor");
+#endif
+  	Print(EAlways," V%02d.%02d (Build %03d)\n",MajorVersion,MinorVersion,Build);
+	int r=processCL(argc, argv);
+	if (r!=KErrNone)
+		return helpme(argv[0]);
+	if (gFile2)
+		return dotran(gFile1, gFile2);
+	if ((gSetStack || gSetUid1 || gSetUid2 || gSetUid3 || gSetCallEntryPoints || gSetPriority
+		|| gSetCapability || gSetCompress || gSetHeap || gSetVersion || gSetSecureId
+		|| gSetVendorId || gSetFixedAddress || gSetFPU || gSetCodePaged || gSetDataPaged || gSetDebuggable || gSetSmpSafe) && gFile1)
+		return doalter(gFile1);
+	if (gFile1)
+		return dodump(gFile1);
+	helpme(argv[0]);
+	return KErrArgument;
+	}
--- a/imgtools/imglib/e32uid/e32uid.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/e32uid/e32uid.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,251 +1,253 @@
-/*
-* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-	#include <iostream>
-	using namespace std;
-#endif
-typedef unsigned char  BYTE;	// TUint8
-typedef unsigned short WORD;	// TUint16
-typedef unsigned int   UINT;	// TUint
-
-#include <string.h>
-#include <e32std.h>
-#include <e32std_private.h>
-#include "e32uid.h"
-
-const UINT crcTab[256] =
-    {
-	0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,0x8108,0x9129,0xa14a,
-	0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,
-	0x72f7,0x62d6,0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,0x2462,
-	0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,0xa56a,0xb54b,0x8528,0x9509,
-	0xe5ee,0xf5cf,0xc5ac,0xd58d,0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,
-	0x46b4,0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,0x48c4,0x58e5,
-	0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,
-	0x9969,0xa90a,0xb92b,0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,
-	0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,0x6ca6,0x7c87,0x4ce4,
-	0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,
-	0x8d68,0x9d49,0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,0xff9f,
-	0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,0x9188,0x81a9,0xb1ca,0xa1eb,
-	0xd10c,0xc12d,0xf14e,0xe16f,0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,
-	0x6067,0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,0x02b1,0x1290,
-	0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,
-	0xe54f,0xd52c,0xc50d,0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
-	0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,0x26d3,0x36f2,0x0691,
-	0x16b0,0x6657,0x7676,0x4615,0x5634,0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,
-	0xb98a,0xa9ab,0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,0xcb7d,
-	0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,0x4a75,0x5a54,0x6a37,0x7a16,
-	0x0af1,0x1ad0,0x2ab3,0x3a92,0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,
-	0x8dc9,0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,0xef1f,0xff3e,
-	0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,
-	0x3eb2,0x0ed1,0x1ef0
-    };
-
-void Crc(WORD& aCrc,const void* aPtr,int aLength)
-//
-// Perform a CCITT CRC checksum.
-//
-	{
-
-	const BYTE* pB=(const BYTE*)aPtr;
-	const BYTE* pE=pB+aLength;
-	UINT crc=aCrc;
-    while (pB<pE)
-		crc=(crc<<8)^crcTab[((crc>>8)^*pB++)&0xff];
-	aCrc=(WORD)crc;
-	}
-
-UINT checkSum(const void* aPtr)
-//
-// Checksum every other byte
-//
-	{
-
-	const BYTE* pB=(const BYTE*)aPtr;
-	const BYTE* pE=pB+(KMaxCheckedUid*sizeof(TUid));
-	BYTE buf[(KMaxCheckedUid*sizeof(TUid))>>1];
-	BYTE* pT=(&buf[0]);
-	while (pB<pE)
-		{
-		*pT++=(*pB);
-		pB+=2;
-		}
-	WORD crc=0;
-	Crc(crc,&buf[0],(KMaxCheckedUid*sizeof(TUid))>>1);
-	return(crc);
-	}
-	
-int TUid::operator==(const TUid& aUid) const
-//
-// Compare UID's for equality
-//
-	{
-
-	return(iUid==aUid.iUid);
-	}
-
-int TUid::operator!=(const TUid& aUid) const
-//
-// Compare UID's for equality
-//
-	{
-
-	return(iUid!=aUid.iUid);
-	}
-
-TUidType::TUidType()
-//
-// Constructor
-//
-    {
-
-	memset(this,0,sizeof(TUidType));
-    }
-
-TUidType::TUidType(TUid aUid1)
-//
-// Constructor
-//
-    {
-
-
-	memset(this,0,sizeof(TUidType));
-    iUid[0]=aUid1;
-    }
-
-TUidType::TUidType(TUid aUid1,TUid aUid2)
-//
-// Constructor
-//
-    {
-
-    iUid[0]=aUid1;
-    iUid[1]=aUid2;
-    iUid[2]=KNullUid;
-    }
-
-TUidType::TUidType(TUid aUid1,TUid aUid2,TUid aUid3)
-//
-// Constructor
-//
-    {
-
-
-    iUid[0]=aUid1;
-    iUid[1]=aUid2;
-    iUid[2]=aUid3;
-    }
-
-int TUidType::operator==(const TUidType& aUidType) const
-//
-// TRUE if equal.
-//
-    {
-
-    return(iUid[0]==aUidType.iUid[0] &&
-           iUid[1]==aUidType.iUid[1] &&
-           iUid[2]==aUidType.iUid[2]);
-    }
-
-int TUidType::operator!=(const TUidType& aUidType) const
-//
-// TRUE if not equal.
-//
-    {
-
-
-    return(!(*this==aUidType));
-    }
-
-const TUid& TUidType::operator[](int anIndex) const
-//
-// Array operator.
-//
-    {
-
-	return(iUid[anIndex]);
-    }
-
-TUid TUidType::MostDerived() const
-//
-// Return the most derived type
-//
-    {
-
-    if (iUid[2]!=KNullUid)
-        return(iUid[2]);
-    if (iUid[1]!=KNullUid)
-        return(iUid[1]);
-    return(iUid[0]);
-    }
-
-int TUidType::IsPresent(TUid aUid) const
-//
-// TRUE if aUid is present as any type.
-//
-    {
-
-	return(iUid[0]==aUid || iUid[1]==aUid || iUid[2]==aUid);
-    }
-
-int TUidType::IsValid() const
-//
-// TRUE if one of the type is not NULL.
-//
-    {
-
-    return(MostDerived()!=KNullUid);
-    }
-
-TCheckedUid::TCheckedUid()
-//
-// Constructor
-//
-	{
-
-	memset(this,0,sizeof(TCheckedUid));
-	}
-
-TCheckedUid::TCheckedUid(const TUidType& aUidType)
-//
-// Constructor
-//
-	{
-
-    Set(aUidType);
-    }
-
-void TCheckedUid::Set(const TUidType& aUidType)
-//
-// Set from a aUidType
-//
-	{
-
-    iType=aUidType;
-    iCheck=Check();
-    }
-
-UINT TCheckedUid::Check() const
-//
-// Return the checksum of the UIDs
-//
-	{
-
-	return((checkSum(((BYTE*)this)+1)<<16)|checkSum((BYTE*)this));
-	}
-
+/*
+* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
+	#include <iostream>
+	using namespace std;
+#endif
+
+typedef unsigned char  BYTE;	// TUint8
+typedef unsigned short WORD;	// TUint16
+typedef unsigned int   UINT;	// TUint
+
+#include <string.h>
+#include <e32std.h>
+#include <e32std_private.h>
+#include "e32uid.h"
+
+const UINT crcTab[256] =
+    {
+	0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,0x8108,0x9129,0xa14a,
+	0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,
+	0x72f7,0x62d6,0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,0x2462,
+	0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,0xa56a,0xb54b,0x8528,0x9509,
+	0xe5ee,0xf5cf,0xc5ac,0xd58d,0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,
+	0x46b4,0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,0x48c4,0x58e5,
+	0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,
+	0x9969,0xa90a,0xb92b,0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,
+	0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,0x6ca6,0x7c87,0x4ce4,
+	0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,
+	0x8d68,0x9d49,0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,0xff9f,
+	0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,0x9188,0x81a9,0xb1ca,0xa1eb,
+	0xd10c,0xc12d,0xf14e,0xe16f,0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,
+	0x6067,0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,0x02b1,0x1290,
+	0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,
+	0xe54f,0xd52c,0xc50d,0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
+	0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,0x26d3,0x36f2,0x0691,
+	0x16b0,0x6657,0x7676,0x4615,0x5634,0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,
+	0xb98a,0xa9ab,0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,0xcb7d,
+	0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,0x4a75,0x5a54,0x6a37,0x7a16,
+	0x0af1,0x1ad0,0x2ab3,0x3a92,0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,
+	0x8dc9,0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,0xef1f,0xff3e,
+	0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,
+	0x3eb2,0x0ed1,0x1ef0
+    };
+
+void Crc(WORD& aCrc,const void* aPtr,int aLength)
+//
+// Perform a CCITT CRC checksum.
+//
+	{
+
+	const BYTE* pB=(const BYTE*)aPtr;
+	const BYTE* pE=pB+aLength;
+	UINT crc=aCrc;
+    while (pB<pE)
+		crc=(crc<<8)^crcTab[((crc>>8)^*pB++)&0xff];
+	aCrc=(WORD)crc;
+	}
+
+UINT checkSum(const void* aPtr)
+//
+// Checksum every other byte
+//
+	{
+
+	const BYTE* pB=(const BYTE*)aPtr;
+	const BYTE* pE=pB+(KMaxCheckedUid*sizeof(TUid));
+	BYTE buf[(KMaxCheckedUid*sizeof(TUid))>>1];
+	BYTE* pT=(&buf[0]);
+	while (pB<pE)
+		{
+		*pT++=(*pB);
+		pB+=2;
+		}
+	WORD crc=0;
+	Crc(crc,&buf[0],(KMaxCheckedUid*sizeof(TUid))>>1);
+	return(crc);
+	}
+	
+int TUid::operator==(const TUid& aUid) const
+//
+// Compare UID's for equality
+//
+	{
+
+	return(iUid==aUid.iUid);
+	}
+
+int TUid::operator!=(const TUid& aUid) const
+//
+// Compare UID's for equality
+//
+	{
+
+	return(iUid!=aUid.iUid);
+	}
+
+TUidType::TUidType()
+//
+// Constructor
+//
+    {
+
+	memset(this,0,sizeof(TUidType));
+    }
+
+TUidType::TUidType(TUid aUid1)
+//
+// Constructor
+//
+    {
+
+
+	memset(this,0,sizeof(TUidType));
+    iUid[0]=aUid1;
+    }
+
+TUidType::TUidType(TUid aUid1,TUid aUid2)
+//
+// Constructor
+//
+    {
+
+    iUid[0]=aUid1;
+    iUid[1]=aUid2;
+    iUid[2]=KNullUid;
+    }
+
+TUidType::TUidType(TUid aUid1,TUid aUid2,TUid aUid3)
+//
+// Constructor
+//
+    {
+
+
+    iUid[0]=aUid1;
+    iUid[1]=aUid2;
+    iUid[2]=aUid3;
+    }
+
+int TUidType::operator==(const TUidType& aUidType) const
+//
+// TRUE if equal.
+//
+    {
+
+    return(iUid[0]==aUidType.iUid[0] &&
+           iUid[1]==aUidType.iUid[1] &&
+           iUid[2]==aUidType.iUid[2]);
+    }
+
+int TUidType::operator!=(const TUidType& aUidType) const
+//
+// TRUE if not equal.
+//
+    {
+
+
+    return(!(*this==aUidType));
+    }
+
+const TUid& TUidType::operator[](int anIndex) const
+//
+// Array operator.
+//
+    {
+
+	return(iUid[anIndex]);
+    }
+
+TUid TUidType::MostDerived() const
+//
+// Return the most derived type
+//
+    {
+
+    if (iUid[2]!=KNullUid)
+        return(iUid[2]);
+    if (iUid[1]!=KNullUid)
+        return(iUid[1]);
+    return(iUid[0]);
+    }
+
+int TUidType::IsPresent(TUid aUid) const
+//
+// TRUE if aUid is present as any type.
+//
+    {
+
+	return(iUid[0]==aUid || iUid[1]==aUid || iUid[2]==aUid);
+    }
+
+int TUidType::IsValid() const
+//
+// TRUE if one of the type is not NULL.
+//
+    {
+
+    return(MostDerived()!=KNullUid);
+    }
+
+TCheckedUid::TCheckedUid()
+//
+// Constructor
+//
+	{
+
+	memset(this,0,sizeof(TCheckedUid));
+	}
+
+TCheckedUid::TCheckedUid(const TUidType& aUidType)
+//
+// Constructor
+//
+	{
+
+    Set(aUidType);
+    }
+
+void TCheckedUid::Set(const TUidType& aUidType)
+//
+// Set from a aUidType
+//
+	{
+
+    iType=aUidType;
+    iCheck=Check();
+    }
+
+UINT TCheckedUid::Check() const
+//
+// Return the checksum of the UIDs
+//
+	{
+
+	return((checkSum(((BYTE*)this)+1)<<16)|checkSum((BYTE*)this));
+	}
+
--- a/imgtools/imglib/e32uid/uidcrc.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/e32uid/uidcrc.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,94 +1,91 @@
-/*
-* Copyright (c) 1999-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-	#include <iostream>
-	using namespace std;
-#endif
- 
-#include <stdio.h>
-#include <stdlib.h>
-#include <e32std.h>
-#include <e32std_private.h>
-#include <e32uid.h>
-
-// Get round the privateness of the checksum etc.
-// See also PE_TRAN.CPP TE32ImageUids
-
-class TCheckedUidX : public TCheckedUid
-	{
-public:
-	inline TCheckedUidX(TUint uids[3])
-		: TCheckedUid(TUidType(TUid::Uid(uids[1]),TUid::Uid(uids[2]),TUid::Uid(uids[3]))) 
-		{}
-	inline TUint CRC() 
-		{ return Check(); }
-	};
-
-int usage()
-	{
-	fprintf(stderr, "uidcrc <uid1> <uid2> <uid3> [ <outputfile> ]\n");
-	return -1;
-	}
-
-int main(int argc, char* argv[])
-	{
-	if (argc<4 || argc>5)
-		return usage();
-
-	TUint uids[5];
-	int i=0;
-
-	for (i=1; i<4; i++)
-		{
-		char* endptr = "failed";
-		uids[i] = strtoul(argv[i],&endptr,0);
-		if (*endptr!='\0')
-			{
-			fprintf(stderr, "invalid uid%d >%s<\n",i,argv[i]);
-			return -1;
-			}
-		}
-
-	TCheckedUidX checked(uids);
-	uids[4] = checked.CRC();
-
-	if (argc==5)
-		{
-		FILE* fp=fopen(argv[4], "wb");
-		if (fp==0)
-			{
-			fprintf(stderr, "cannot open %s for writing\n", argv[4]);
-			return -1;
-			}
-		for (i=1; i<5; i++)
-			{
-			TUint word=uids[i];
-			unsigned char bytes[4];
-			bytes[0] = (unsigned char)( word     &0xFF);
-			bytes[1] = (unsigned char)((word>> 8)&0xFF);
-			bytes[2] = (unsigned char)((word>>16)&0xFF);
-			bytes[3] = (unsigned char)((word>>24)&0xFF);
-			fwrite(bytes, 4, 1, fp);
-			}
-		fclose(fp);
-		return 0;
-		}
-
-	printf("0x%08x 0x%08x 0x%08x 0x%08x\n", uids[1], uids[2], uids[3], uids[4]);
-	return 0;
-	}
+/*
+* Copyright (c) 1999-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+#include <iostream>
+using namespace std;
+ 
+#include <stdio.h>
+#include <stdlib.h>
+#include <e32std.h>
+#include <e32std_private.h>
+#include <e32uid.h>
+
+// Get round the privateness of the checksum etc.
+// See also PE_TRAN.CPP TE32ImageUids
+
+class TCheckedUidX : public TCheckedUid
+	{
+public:
+	inline TCheckedUidX(TUint uids[3])
+		: TCheckedUid(TUidType(TUid::Uid(uids[1]),TUid::Uid(uids[2]),TUid::Uid(uids[3]))) 
+		{}
+	inline TUint CRC() 
+		{ return Check(); }
+	};
+
+int usage()
+	{
+	fprintf(stderr, "uidcrc <uid1> <uid2> <uid3> [ <outputfile> ]\n");
+	return -1;
+	}
+
+int main(int argc, char* argv[])
+	{
+	if (argc<4 || argc>5)
+		return usage();
+
+	TUint uids[5];
+	int i=0;
+
+	for (i=1; i<4; i++)
+		{
+		char* endptr = "failed";
+		uids[i] = strtoul(argv[i],&endptr,0);
+		if (*endptr!='\0')
+			{
+			fprintf(stderr, "invalid uid%d >%s<\n",i,argv[i]);
+			return -1;
+			}
+		}
+
+	TCheckedUidX checked(uids);
+	uids[4] = checked.CRC();
+
+	if (argc==5)
+		{
+		FILE* fp=fopen(argv[4], "wb");
+		if (fp==0)
+			{
+			fprintf(stderr, "cannot open %s for writing\n", argv[4]);
+			return -1;
+			}
+		for (i=1; i<5; i++)
+			{
+			TUint word=uids[i];
+			unsigned char bytes[4];
+			bytes[0] = (unsigned char)( word     &0xFF);
+			bytes[1] = (unsigned char)((word>> 8)&0xFF);
+			bytes[2] = (unsigned char)((word>>16)&0xFF);
+			bytes[3] = (unsigned char)((word>>24)&0xFF);
+			fwrite(bytes, 4, 1, fp);
+			}
+		fclose(fp);
+		return 0;
+		}
+
+	printf("0x%08x 0x%08x 0x%08x 0x%08x\n", uids[1], uids[2], uids[3], uids[4]);
+	return 0;
+	}
--- a/imgtools/imglib/group/bld.inf	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/group/bld.inf	Tue Jun 29 14:52:54 2010 +0800
@@ -1,40 +1,67 @@
-/*
-* Copyright (c) 1999-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Base tools (e.g. petran)
-*
-*/
-
-
-/**
- @file
-*/
-
-PRJ_PLATFORMS
-TOOLS2
-
-PRJ_EXPORTS
-../boostlibrary/binary/linux/libboost_thread-mgw34-mt-1_39.a	/epoc32/release/tools2/rel/libboost_thread-mgw34-mt-1_39_linux.a
-../boostlibrary/binary/linux/libboost_thread-mgw34-mt-1_39.a	/epoc32/release/tools2/deb/libboost_thread-mgw34-mt-1_39_linux.a
-../boostlibrary/binary/windows/libboost_thread-mgw34-mt-1_39.a	/epoc32/release/tools2/rel/libboost_thread-mgw34-mt-1_39_win32.a
-../boostlibrary/binary/windows/libboost_thread-mgw34-mt-1_39.a	/epoc32/release/tools2/deb/libboost_thread-mgw34-mt-1_39_win32.a
-../boostlibrary/binary/windows/mingwm10.dll	/epoc32/tools/mingwm10.dll
-
-
-PRJ_MMPFILES
-patchdataprocessor
-parameterfileprocessor
-memmap
-filesystem
-uidcrc
+/*
+* Copyright (c) 1999-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Base tools (e.g. petran)
+*
+*/
+
+
+/**
+ @file
+*/
+
+PRJ_PLATFORMS
+TOOLS2
+
+PRJ_EXPORTS
+#ifdef TOOLS2_LINUX
+../boostlibrary/binary/linux/libboost_filesystem-1.39.a /epoc32/release/tools2/linux-i386-libc2_5/rel/libboost_filesystem-1.39.a
+../boostlibrary/binary/linux/libboost_thread-1.39.a /epoc32/release/tools2/linux-i386-libc2_5/rel/libboost_thread-1.39.a
+../boostlibrary/binary/linux/libboost_regex-1.39.a /epoc32/release/tools2/linux-i386-libc2_5/rel/libboost_regex-1.39.a
+../boostlibrary/binary/linux/libboost_system-1.39.a /epoc32/release/tools2/linux-i386-libc2_5/rel/libboost_system-1.39.a
+
+../boostlibrary/binary/linux/libboost_filesystem-1.39.a /epoc32/release/tools2/linux-i386-libc2_5/deb/libboost_filesystem-1.39.a
+../boostlibrary/binary/linux/libboost_thread-1.39.a /epoc32/release/tools2/linux-i386-libc2_5/deb/libboost_thread-1.39.a
+../boostlibrary/binary/linux/libboost_regex-1.39.a /epoc32/release/tools2/linux-i386-libc2_5/deb/libboost_regex-1.39.a
+../boostlibrary/binary/linux/libboost_system-1.39.a /epoc32/release/tools2/linux-i386-libc2_5/deb/libboost_system-1.39.a
+
+../boostlibrary/binary/linux/libboost_filesystem-1.39.a /epoc32/release/tools2/linux-x86_64-libc2_5/rel/libboost_filesystem-1.39.a
+../boostlibrary/binary/linux/libboost_thread-1.39.a /epoc32/release/tools2/linux-x86_64-libc2_5/rel/libboost_thread-1.39.a
+../boostlibrary/binary/linux/libboost_regex-1.39.a /epoc32/release/tools2/linux-x86_64-libc2_5/rel/libboost_regex-1.39.a
+../boostlibrary/binary/linux/libboost_system-1.39.a /epoc32/release/tools2/linux-x86_64-libc2_5/rel/libboost_system-1.39.a
+
+../boostlibrary/binary/linux/libboost_filesystem-1.39.a /epoc32/release/tools2/linux-x86_64-libc2_5/deb/libboost_filesystem-1.39.a
+../boostlibrary/binary/linux/libboost_thread-1.39.a /epoc32/release/tools2/linux-x86_64-libc2_5/deb/libboost_thread-1.39.a
+../boostlibrary/binary/linux/libboost_regex-1.39.a /epoc32/release/tools2/linux-x86_64-libc2_5/deb/libboost_regex-1.39.a
+../boostlibrary/binary/linux/libboost_system-1.39.a /epoc32/release/tools2/linux-x86_64-libc2_5/deb/libboost_system-1.39.a
+
+#else
+../boostlibrary/binary/windows/libboost_thread-1.39.a	/epoc32/release/tools2/rel/libboost_thread-1.39.a
+../boostlibrary/binary/windows/libboost_regex-1.39.a	/epoc32/release/tools2/rel/libboost_regex-1.39.a
+../boostlibrary/binary/windows/libboost_filesystem-1.39.a /epoc32/release/tools2/rel/libboost_filesystem-1.39.a 
+../boostlibrary/binary/windows/libboost_system-1.39.a /epoc32/release/tools2/rel/libboost_system-1.39.a 
+
+../boostlibrary/binary/windows/libboost_thread-1.39.a	/epoc32/release/tools2/deb/libboost_thread-1.39.a
+../boostlibrary/binary/windows/libboost_regex-1.39.a	/epoc32/release/tools2/deb/libboost_regex-1.39.a
+../boostlibrary/binary/windows/libboost_filesystem-1.39.a /epoc32/release/tools2/deb/libboost_filesystem-1.39.a 
+../boostlibrary/binary/windows/libboost_system-1.39.a /epoc32/release/tools2/deb/libboost_system-1.39.a 
+
+../boostlibrary/binary/windows/mingwm10.dll	/epoc32/tools/mingwm10.dll
+#endif
+
+PRJ_MMPFILES
+patchdataprocessor
+parameterfileprocessor
+memmap
+uidcrc
--- a/imgtools/imglib/group/imglib.mrp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/group/imglib.mrp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,8 +1,8 @@
 component	dev_build_imgtools_imglib
 
-source		\src\tools\dev\build\imgtools\imglib
-binary		\src\tools\dev\build\imgtools\imglib\group all
-exports		\src\tools\dev\build\imgtools\imglib\group
+source		\src\tools\build\imgtools\imglib
+binary		\src\tools\build\imgtools\imglib\group all
+exports		\src\tools\build\imgtools\imglib\group
 
 binary	\epoc32\release\tools2\rel\uidcrc.exe
 
--- a/imgtools/imglib/host/h_file.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/host/h_file.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,150 +1,150 @@
-/*
-* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifdef __LINUX__
-#include <unistd.h>
-#else	// Windows specific
-#include <io.h>
-#endif
-#include <fcntl.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <errno.h>
-
-#include "h_utl.h"
-
-TInt HFile::Open(const TText * const aFileName, TInt32 * const aFileHandle)
-	{
-#ifdef __LINUX__
-	TInt32 hFile = open((const char *)aFileName, O_RDONLY );
-#else
-	TInt32 hFile = _open((const char *)aFileName, _O_RDONLY | _O_BINARY);
-#endif
-
-	if (hFile == -1)
-		{
-		switch (errno)
-			{
-		case EACCES:
-			Print(EError,"Can't open file %s - access violation.\n",aFileName);
-			break;
-		case EEXIST:
-			Print(EAlways,"Tried to create existing file %s\n",aFileName);
-			break;
-		case EINVAL:
-			Print(EError,"Can't open file %s - invalid open flags.\n",aFileName);
-			break;
-		case EMFILE:
-			Print(EError,"Can't open file %s - too many open files.\n",aFileName);
-			break;
-		case ENOENT:
-			Print(EError,"Can't open file %s - file or path not found.\n",aFileName);
-			break;
-		default:
-			Print(EError,"Can't open file %s, error %d (decimal).\n",aFileName,errno);
-			break;
-			}
-		return errno;
-		}
- 	*aFileHandle = hFile;
-	return 0;
-	}	
-
-/******************************************************************************/
-TBool HFile::Read(const TInt32 aFileHandle, TAny * const aBuffer, const TUint32 aCount)
-	{
-	TInt32 bytesRead =  _read(aFileHandle, aBuffer, aCount);
-	if (bytesRead != (TInt32)aCount)
-		return EFalse;
-	else
-		return ETrue;
-	}  
-
-/******************************************************************************/
-TBool HFile::Seek(const TInt32 aFileHandle, const TUint32 aOffset)
-	{
-	TInt32 newPos = _lseek(aFileHandle, aOffset, SEEK_SET);
-	if (newPos == -1)
-		return(EFalse);
-	else
-		return ETrue;
-	}
-
-/******************************************************************************/
-TUint32 HFile::GetPos(const TInt32 aFileHandle)
-	{
-	TUint32 pos = _lseek(aFileHandle, 0, SEEK_CUR);
-	return pos;
-	}
-
-/******************************************************************************/
-TUint32 HFile::GetLength(TText *aName)
-	{
-	TInt32 handle;
-	if (HFile::Open(aName, &handle)==0)
-		{
-		TUint32 size = _filelength(handle);
-		HFile::Close(handle);
-		return size;
-		}
-	else
-		return 0;
-	}
-
-/******************************************************************************/
-TUint32 HFile::GetLength(const TInt32 aFileHandle)
-	{
-
-	TUint32 size = _filelength(aFileHandle);
-	return size;
-	}
-
-
-/******************************************************************************/
-void HFile::Close(const TInt32 aFileHandle)
-	{
-	_close(aFileHandle);
-	}
-
-
-/******************************************************************************/
-TUint32 HFile::Read(TText *aName, TAny *someMem)
- 	{
-	TInt32 handle;
-	if (HFile::Open(aName, &handle)==0)
-		{
-		TUint32 size = HFile::GetLength(handle);
-		if (HFile::Read(handle, someMem, size))
-			{
-			HFile::Close(handle);
-			return size;
-			}
-		else 
-			{
-			HFile::Close(handle);
-			return 0;
-			}
-		}
-	else
-		return 0;
-	}
-
-
-/******************************************************************************/
+/*
+* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifdef __LINUX__
+#include <unistd.h>
+#else	// Windows specific
+#include <io.h>
+#endif
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+
+#include "h_utl.h"
+
+TInt HFile::Open(const char* aFileName, TInt32 * const aFileHandle)
+	{
+#ifdef __LINUX__
+	TInt32 hFile = open(aFileName, O_RDONLY );
+#else
+	TInt32 hFile = _open(aFileName, _O_RDONLY | _O_BINARY);
+#endif
+
+	if (hFile == -1)
+		{
+		switch (errno)
+			{
+		case EACCES:
+			Print(EError,"Can't open file %s - access violation.\n",aFileName);
+			break;
+		case EEXIST:
+			Print(EAlways,"Tried to create existing file %s\n",aFileName);
+			break;
+		case EINVAL:
+			Print(EError,"Can't open file %s - invalid open flags.\n",aFileName);
+			break;
+		case EMFILE:
+			Print(EError,"Can't open file %s - too many open files.\n",aFileName);
+			break;
+		case ENOENT:
+			Print(EError,"Can't open file %s - file or path not found.\n",aFileName);
+			break;
+		default:
+			Print(EError,"Can't open file %s, error %d (decimal).\n",aFileName,errno);
+			break;
+			}
+		return errno;
+		}
+ 	*aFileHandle = hFile;
+	return 0;
+	}	
+
+/******************************************************************************/
+TBool HFile::Read(const TInt32 aFileHandle, TAny * const aBuffer, const TUint32 aCount)
+	{
+	TInt32 bytesRead =  _read(aFileHandle, aBuffer, aCount);
+	if (bytesRead != (TInt32)aCount)
+		return EFalse;
+	else
+		return ETrue;
+	}  
+
+/******************************************************************************/
+TBool HFile::Seek(const TInt32 aFileHandle, const TUint32 aOffset)
+	{
+	TInt32 newPos = _lseek(aFileHandle, aOffset, SEEK_SET);
+	if (newPos == -1)
+		return(EFalse);
+	else
+		return ETrue;
+	}
+
+/******************************************************************************/
+TUint32 HFile::GetPos(const TInt32 aFileHandle)
+	{
+	TUint32 pos = _lseek(aFileHandle, 0, SEEK_CUR);
+	return pos;
+	}
+
+/******************************************************************************/
+TUint32 HFile::GetLength(const char* aName)
+	{
+	TInt32 handle;
+	if (HFile::Open(aName, &handle)==0)
+		{
+		TUint32 size = _filelength(handle);
+		HFile::Close(handle);
+		return size;
+		}
+	else
+		return 0;
+	}
+
+/******************************************************************************/
+TUint32 HFile::GetLength(const TInt32 aFileHandle)
+	{
+
+	TUint32 size = _filelength(aFileHandle);
+	return size;
+	}
+
+
+/******************************************************************************/
+void HFile::Close(const TInt32 aFileHandle)
+	{
+	_close(aFileHandle);
+	}
+
+
+/******************************************************************************/
+TUint32 HFile::Read(const char* aName, TAny *someMem)
+ 	{
+	TInt32 handle;
+	if (HFile::Open(aName, &handle)==0)
+		{
+		TUint32 size = HFile::GetLength(handle);
+		if (HFile::Read(handle, someMem, size))
+			{
+			HFile::Close(handle);
+			return size;
+			}
+		else 
+			{
+			HFile::Close(handle);
+			return 0;
+			}
+		}
+	else
+		return 0;
+	}
+
+
+/******************************************************************************/
--- a/imgtools/imglib/host/h_utl.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/host/h_utl.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,684 +1,714 @@
-/*
-* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-
-#define __INCLUDE_CAPABILITY_NAMES__
-
-#if defined(_MSVCDOTNET__) || defined(__TOOLS2__)
-#include <string>
-#else //!__MSVCDOTNET__
-#include <string.h>
-#endif //__MSVCDOTNET__
-
-#include <stdarg.h>
-#include <stdlib.h>
-
-#include <e32std.h>
-#include <e32std_private.h>
-
-#include "h_utl.h"
-
-#ifdef __LINUX__
- 
- // Convert the supplied string to uppercase, in-place 
- char* strupr(char *a)
-    {
-     char *ret = a;
- 
-    while (*a)
-        {
-        *a = toupper(*a);
-        a++;
-         }
- 
-     return ret;
-     }
- 
- off_t filelength(int filedes)
-     {
-     struct stat buf;
-     if(!fstat(filedes, &buf))
-         {
-        return buf.st_size;
-         }
-    perror("fstat failed");
-   return 0;
-    }
- 
-#endif
-
-TBool PVerbose=ETrue;
-
-HPrint H;
-
-HPrint::~HPrint()
-	{
-	iLogFile.close();
-	}
-
-void HPrint::SetLogFile(TText *aFileName)
-	{
-	iLogFile.open((const char *)aFileName);
-	}
-
-
-/**
-Closing the logfile.(since 'n' number of drive images can be created)
-
-@internalComponent
-@released
-
-*/
-void HPrint::CloseLogFile()
-	{
-	if(iLogFile.is_open())
-		iLogFile.close();
-	}
-
-TInt HPrint::PrintString(TPrintType aType,const char *aFmt,...)
-//
-// Print text, noting where to send it.
-//
-	{
-
-	TInt r=KErrNone;
-	va_list list;
-	va_start(list,aFmt);
-	_vsnprintf((char *)iText,KMaxStringLength,aFmt,list);
-	va_end(list);
-	switch (aType)
-		{
-	case EAlways:
-		cout << iText;
-		iLogFile << iText;
-		break;
-	case EScreen:
-		cout << iText;
-		break;
-	case ELog:
-		if (iVerbose)
-			cout << iText;
-		iLogFile << iText;
-		break;
-	case EWarning:
-		cerr << "WARNING: " << iText;
-		iLogFile << "WARNING: "<<iText;
-		break;
-	case EError:
-		cerr << "ERROR: " << iText;
-		iLogFile << "ERROR: " << iText;
-		r=KErrGeneral;
-		break;
-	case EPeError:
-		if (PVerbose)
-			{
-			cerr << "ERROR: " << iText;
-			iLogFile << "ERROR: " << iText;
-			}
-		r=KErrGeneral;
-		break;
-	case ESevereError:
-		cerr << "ERROR: " << iText;
-		iLogFile << "ERROR: " << iText;
-		r=KErrGeneral;
-		break;
-	case EDiagnostic:
-		cerr << "DIAGNOSTIC MESSAGE: " << iText;
-		iLogFile << "DIAGNOSTIC MESSAGE: "<<iText;
-		break;
-	default:
-		cerr << "ERROR: Invalid print type" << endl;
-		r=KErrGeneral;
-		}
-	cout.flush();
-	iLogFile.flush();
-	return r;
-    }
-
-TVersion::TVersion()
-	{}
-TVersion::TVersion(TInt aMajor, TInt aMinor, TInt aBuild)
-	: iMajor((TInt8)aMajor), iMinor((TInt8)aMinor), iBuild((TInt16)aBuild)
-	{}
-#ifdef __TOOLS2__
-istringstream &operator>>(istringstream &is, TVersion &aVersion)
-#else
-istrstream &operator>>(istrstream &is, TVersion &aVersion)
-#endif
-//
-// Input a TVersion with syntax: major[.minor][(build)]
-//	
-	{
-#ifdef __TOOLS2__
-string tmp = is.str();
-const char *str=tmp.c_str();
-#else
-#ifdef __LINUX__
-    char *str = is.rdbuf()->str();
-#else
-    char *str=is.str();
-#endif
-#endif
-
-
-	TInt build=0;
-	memset(&aVersion, sizeof(TVersion), 0);	
-	TInt i;
-	TInt len=strlen(str);
-	for (i=0; i<len; i++)
-		if (str[i]=='(')
-			break;
-	if (i<len)
-		build=atoi(str+i+1);
-	aVersion.iMajor = (TInt8)Min(KMaxTInt8, atoi(str));
-	int majorV = atoi(str);
-	// iMajor is defined as TInt8 so it should not be bigger than 127
-	if (majorV > 127)
-		{ 
-		cout << "\n Warning: major version must be in range 0 - 127 \n";
-		}
-	char* pMinor = strchr(str, '.');
-	if (pMinor)
-		{
-		pMinor++; 
-		aVersion.iMinor = (TInt8)Min(KMaxTInt8, atoi(pMinor));
-		int minorV = atoi(pMinor);
-		// iMinor is defined as TInt8 so it should not be bigger than 127
-		if (minorV > 127)
-			{ 
-			cout << "\n Warning: minor version must be in range 0 - 127 \n";
-			}
-		}	
-	aVersion.iBuild=(TInt16)build;
-	return is;
-	}
-
-TInt Locate(const char *aString, char aChar)
-//
-// Locate aChar in aString
-//
-	{
-
-	if (aString==NULL)
-		return KErrNotFound;
-	TInt i=0;
-	while (*aString!=0)
-		{
-		if (*aString==aChar)
-			return i;
-		aString++;
-		i++;
-		}
-	return KErrNotFound;
-	}
-
-
-#define KHoursToMicroSeconds	Int64(3600000000UL) 
-#define KDaysToMicroSeconds		(Int64(24)*KHoursToMicroSeconds)
-const TInt KMinutesToMicroSeconds = 60000000;
-const TInt KSecondsToMicroSeconds =  1000000;
-
-const TInt8 mTab[2][12]=
-    {
-    {31,28,31,30,31,30,31,31,30,31,30,31}, // 28 days in Feb
-    {31,29,31,30,31,30,31,31,30,31,30,31}  // 29 days in Feb
-    };
-
-TInt Time::LeapYearsUpTo(TInt aYear)
-//
-// from 0AD to present year according to the rule above
-//
-	{
-
-	if (aYear<=0)
-		return(aYear/4);
-	if (aYear<=1600)
-		return(1+((aYear-1)/4));
-	TInt num=401; // 1600/4+1
-	aYear-=1601;
-	num+=(aYear/4-aYear/100+aYear/400);
-	return(num);
-	}
-
-TBool Time::IsLeapYear(TInt aYear)
-//
-// up to and including 1600 leap years were every 4 years,since then leap years are every 4 years unless
-// the year falls on a century which is not divisible by 4 (ie 1900 wasnt,2000 will be)
-// for simplicity define year 0 as a leap year
-//
-	{
-
-	if (aYear>1600)
-    	return(!(aYear%4) && (aYear%100 || !(aYear%400)));
-	return(!(aYear%4));
-	}
-
-
-Int64 ConvertTime(TInt aDay, TInt aMonth, TInt aYear, TInt aHour, TInt aMinute, TInt aSecond, TInt aMilliSeconds)
-//
-// converts TDateTime into a TTime, doesnt check for overflows
-//
-	{
-	
-	TInt days=365*aYear+Time::LeapYearsUpTo(aYear);
-	TBool isleap=Time::IsLeapYear(aYear);
-	for (TInt ii=0; ii<aMonth; ii++)
-	    days+=(mTab[isleap][ii]);	
-	days+=aDay;
-	TInt sum=aMilliSeconds+aSecond*KSecondsToMicroSeconds;
-	return((Int64(days)*KDaysToMicroSeconds+Int64(aHour)*KHoursToMicroSeconds) 
-			+(Int64(KMinutesToMicroSeconds)*Int64(aMinute)+Int64(sum))); 
-	}
-	
-TInt StringToTime(Int64 &aTime, char *aString)
-//
-// Convert string to time. String is in the format:
-//
-// dd/mm/yyyy hh:mm:ss.mmmmmmm
-//
-	{
-	TInt day=1;
-	TInt month=1;
-	TInt year=1997;
-	TInt hour=10;
-	TInt minute=10;
-	TInt sec=0;
-	TInt mill=0;
-	char ch;
-	#ifdef __TOOLS2__
-	istringstream val(aString);
-	#else
-	istrstream val(aString,strlen(aString));
-	#endif
-	val >> dec >> day; // locks istrstream in decimal mode for further extractions
-	val >> ch;
-	if (ch!='/')
-		return KErrGeneral;
-	val >> month;
-	val >> ch;
-	if (ch!='/')
-		return KErrGeneral;
-	val >> year;
-	val >> ch;
-
-	if (ch=='_')
-		{
-		// time too.
-		val >> hour;
-		val >> ch;
-		if (ch!=':')
-			return KErrGeneral;
-		val >> minute;
-		val >> ch;
-		if (ch!=':')
-			return KErrGeneral;
-		val >> sec;
-		val >> ch;
-		if (ch=='.')
-			{
-			val >> mill;
-			}
-		}
-
-	if (day<1 || day>31)
-		return KErrArgument;
-	if (month<1 || month>12)
-		return KErrArgument;
-	if (year<1970 || year>2060)
-		return KErrArgument;
-	if (hour<0 || hour>23)
-		return KErrArgument;
-	if (minute<0 || minute>59)
-		return KErrArgument;
-	if (sec<0 || sec>59)
-		return KErrArgument;
-	if (mill<0 || mill>999999)
-		return KErrArgument;
-
-	aTime=ConvertTime(day-1, month-1, year, hour, minute, sec, mill);
-	return KErrNone;
-	}
-
-void ByteSwap(TUint &aVal)
-	{
-	TUint t0=aVal & 0xff;
-	TUint t1=(aVal>>8)  & 0xff;
-	TUint t2=(aVal>>16) & 0xff;
-	TUint t3=aVal>>24;
-	aVal=(t0 << 24) | (t1 << 16) | (t2 << 8) | (t3);
-	}
-
-void ByteSwap(TUint16 &aVal)
-	{
-	TUint16 t0=(TUint16)((aVal >> 8) & 0xff);
-	TUint16 t1=(TUint16)(aVal & 0xff);
-	aVal=(TUint16)((t1 << 8) | t0);
-	}
-
-void ByteSwap(TUint *aPtr, TInt aSize)
-	{
-
-	while ((aSize-=4)>=0)
-		ByteSwap(*aPtr++);
-	}
-
-TBool IsBracketedHex(const char* s, const char* brackets, TInt digits, TUint32& aValue)
-	{
-	if (s[0]!=brackets[0] || s[1+digits]!=brackets[1])
-		return EFalse;
-	TInt i;
-	TUint32 x = 0;
-	for (i=1; i<=digits; ++i)
-		{
-		TInt c = s[i];
-		if (c>='a' && c<='z') c-=32;
-		if (c<'0' || (c>'9' && c<'A') || c>'F')
-			return EFalse;
-		c-='0';
-		if (c>9) c-=7;
-		x = (x<<4) | (TUint32)c;
-		}
-	aValue = x;
-	return ETrue;
-	}
-
-TInt CheckForDecimalVersion(const char* begin, const char* s, TUint32& aValue)
-	{
-	aValue = 0;
-	if (s <= begin || *s != '}')
-		return 0;
-	TUint32 v[2] = {0,0};
-	TUint32 m = 1;
-	TInt pos = 0;
-	const char* s0 = s + 1;
-	for (--s; s >= begin; --s)
-		{
-		int c = *s;
-		if (c >= '0' && c <= '9')
-			{
-			v[pos] += m * (c - '0');
-			if (v[pos] >= 65536u)
-				return 0;
-			m *= 10;
-			}
-		else if (c == '.')
-			{
-			m = 1;
-			if (++pos >= 2)
-				return 0;
-			}
-		else if (c == '{')
-			break;
-		else
-			return 0;
-		}
-	if (s < begin)
-		return 0;
-	aValue = (v[1] << 16) | v[0];
-	return s0 - s;
-	}
-
-// Decompose a name of the form NAME{MMMMmmmm}[UUUUUUUU].EXT where the bracketed
-// sections and extension are both optional.
-// Return a newly malloc-ed string containing NAME.EXT
-// Set aUid = 0xUUUUUUUU if present, 0 if not
-// Set aModuleVersion = 0xMMMMmmmm if present, 0 if not
-// Set aFlags according to which of these are present
-char* SplitFileName(const char* aName, TUint32& aUid, TUint32& aModuleVersion, TUint32& aFlags)
-	{
-	TFileNameInfo f(aName, ETrue);
-	aUid = f.iUid3;
-	aModuleVersion = f.iModuleVersion;
-	aFlags = f.iFlags;
-	TInt nl = f.iBaseLength;
-	TInt el = f.iTotalLength - f.iExtPos;
-	TInt tl = nl + el;
-	char* t = (char*)malloc(tl + 1);
-	if (t)
-		{
-		memcpy(t, aName, nl);
-		if (el)
-			memcpy(t + nl, aName + f.iExtPos, el);
-		t[tl] = 0;
-		}
-	return t;
-	}
-
-
-// Decompose a name of the form NAME{MMMMmmmm}.EXT where the bracketed
-// sections and extension are both optional.
-// Return a newly malloc-ed string containing NAME.EXT
-// Set aModuleVersion = 0xMMMMmmmm if present, 0 if not
-// Set aFlags according to whether version present
-char* SplitFileName(const char* aName, TUint32& aModuleVersion, TUint32& aFlags)
-	{
-	TFileNameInfo f(aName, EFalse);
-	aModuleVersion = f.iModuleVersion;
-	aFlags = f.iFlags;
-	TInt nl = f.iBaseLength;
-	TInt el = f.iTotalLength - f.iExtPos;
-	TInt tl = nl + el;
-	char* t = (char*)malloc(tl + 1);
-	if (t)
-		{
-		memcpy(t, aName, nl);
-		if (el)
-			memcpy(t + nl, aName + f.iExtPos, el);
-		t[tl] = 0;
-		}
-	return t;
-	}
-
-
-// Parse a filename and convert decimal version number to hex
-char* NormaliseFileName(const char* aName)
-{
-	//convert forward slashes into back slashes.
-	char* filename = strdup(aName);  //prevent violated access from stack.
-	char* fwdslashfinder = filename;
-	fwdslashfinder=strstr(fwdslashfinder, "/");
-	while(fwdslashfinder)
-	  {
-		*fwdslashfinder++ = '\\';
-		fwdslashfinder=strstr(fwdslashfinder, "/");
-	  }
-
-	//normalize filename.
-	TFileNameInfo f(filename, EFalse);
-	TInt nl = f.iBaseLength;
-	TInt el = f.iTotalLength - f.iExtPos;
-	TInt tl = nl + el;
-	if (f.iFlags & EVerPresent)
-		tl += 10;
-	char* t = (char*)malloc(tl + 1);
-	if (t)
-		{
-		memcpy(t, filename, nl);
-		if (f.iFlags & EVerPresent)
-			sprintf(t + nl, "{%08lx}%s", f.iModuleVersion, filename + f.iExtPos);
-		else if (el)
-			memcpy(t + nl, filename + f.iExtPos, el);
-		t[tl] = 0;
-		}
-	free(filename);
-
-	return t;
-}
-
-TFileNameInfo::TFileNameInfo(const char* aFileName, TBool aLookForUid)
-	{
-	iFileName = aFileName;
-	TInt l = strlen(aFileName);
-	iTotalLength = l;
-	TInt remain = l;
-	iFlags = 0;
-	iUid3 = 0;
-	iModuleVersion = 0;
-	iBaseLength = l;
-	iExtPos = l;
-	const char* s = iFileName + l;
-	for (; s>=iFileName && *s!='.' && *s!='}' && (!aLookForUid || *s!=']'); --s) {}
-	if (s<iFileName)
-		return;
-	if (*s == '.')
-		{
-		iExtPos = s - iFileName;
-		if (iExtPos == 0)
-			{
-			iBaseLength = 0;
-			return;
-			}
-		remain = iExtPos;
-		--s;
-		}
-	else if (s != iFileName + l)
-		return;
-	if (aLookForUid && remain>=10 && IsBracketedHex(s-9, "[]", 8, iUid3))
-		{
-		iFlags |= EUidPresent;
-		remain -= 10;
-		s -= 10;
-		}
-	if (remain>=10 && IsBracketedHex(s-9, "{}", 8, iModuleVersion))
-		{
-		iFlags |= EVerPresent;
-		remain -= 10;
-		s -= 10;
-		}
-	else
-		{
-		TInt n = CheckForDecimalVersion(iFileName, s, iModuleVersion);
-		if (n>0)
-			{
-			iFlags |= EVerPresent;
-			remain -= n;
-			s -= n;
-			}
-		}
-	iBaseLength = remain;
-	}
-
-
-#define PARSE_CAPABILITIES_ERROR(aMessage) Print(EError, "%s\n",aMessage)
-#define PARSE_CAPABILITIES_ERROR2(aMessage1,aMessage2) Print(EError, "%s%s\n",aMessage1,aMessage2)
-
-TInt ParseCapabilitiesArg(SCapabilitySet& aCapabilities, const char *aText)
-//
-// This is a cun'n'paste copy of the function in BASE\WINS\SPECIFIC\PROPERTY.CPP
-// Keep both of these versions up to date with each other
-//
-	{
-	memset(&aCapabilities,0,sizeof(aCapabilities));
-	char c;
-	while((c=*aText)!=0)
-		{
-		if(c<=' ')
-			{
-			++aText;
-			continue;
-			}
-		int invert=0;
-		if(c=='+')
-			{
-			++aText;
-			c=*aText;
-			}
-		if(c=='-')
-			{
-			invert=1;
-			++aText;
-			}
-		const char* name = aText;
-		while((c=*aText)>' ')
-			{
-			if(c=='-' || c=='+')
-				break;
-			++aText;
-			}
-		TUint n = aText-name; 
-		TInt i; 
-
-		if(n==3 && strnicmp("all",name,n)==0)
-			{
-			if(invert)
-				{
-				PARSE_CAPABILITIES_ERROR("Capability '-ALL' not allowed");
-				return KErrArgument;
-				}
-			for(i=0; i<ECapability_Limit; i++)
-				{
-				if(CapabilityNames[i])
-					aCapabilities[i>>5] |= (1<<(i&31));
-				}
-			continue;
-			}
-
-		if(n==4 && strnicmp("none",name,n)==0)
-			{
-			if(invert)
-				{
-				PARSE_CAPABILITIES_ERROR("Capability '-NONE' not allowed");
-				return KErrArgument;
-				}
-			memset(&aCapabilities,0,sizeof(aCapabilities));
-			continue;
-			}
-
-		for(i=0; i<ECapability_Limit; i++)
-			{
-			const char* cap = CapabilityNames[i];
-			if(!cap)
-				continue;
-			if((TUint)strlen(cap)!=n) 
-				continue;
-			if(strnicmp(cap,name,n)!=0)
-				continue;
-			break;
-			}
-		if(i>=ECapability_Limit)
-			{
-			char badName[32];
-			if(n>=sizeof(badName)) n=sizeof(badName)-1;
-			memcpy(badName,name,n);
-			badName[n]=0;
-			PARSE_CAPABILITIES_ERROR2("Unrecognised capability name: ",badName);
-			return KErrArgument;
-			}
-		if(invert)
-			aCapabilities[i>>5] &= ~(1<<(i&31));
-		else
-			aCapabilities[i>>5] |= (1<<(i&31));
-		}
-	return KErrNone;
-	}
-
-TInt ParseBoolArg(TBool& aValue, const char *aText)
-	{
-	if (_stricmp(aText, "on")==0 || _stricmp(aText, "yes")==0 || _stricmp(aText, "1")==0 || strlen(aText)==0)
-		{
-		aValue = ETrue;
-		return KErrNone;
-		}
-	if (_stricmp(aText, "off")==0 || _stricmp(aText, "no")==0 || _stricmp(aText, "0")==0 )
-		{
-		aValue = EFalse;
-		return KErrNone;
-		}
-	Print(EError, "Expected a boolean on/off value but found %s\n",aText);
-	return KErrArgument;
-	}
+/*
+* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+
+#define __INCLUDE_CAPABILITY_NAMES__
+
+#if defined(_MSVCDOTNET__) || defined(__TOOLS2__)
+
+#else //!__MSVCDOTNET__
+#include <string.h>
+#endif //__MSVCDOTNET__
+
+#include <stdarg.h>
+#include <stdlib.h>
+
+#include <e32std.h>
+#include <e32std_private.h>
+
+#include "h_utl.h"
+
+#ifdef __LINUX__
+ 
+ // Convert the supplied string to uppercase, in-place 
+ char* strupr(char *a)
+    {
+     char *ret = a;
+ 
+    while (*a)
+        {
+        *a = toupper(*a);
+        a++;
+         }
+ 
+     return ret;
+     }
+ 
+ off_t filelength(int filedes)
+     {
+     struct stat buf;
+     if(!fstat(filedes, &buf))
+         {
+        return buf.st_size;
+         }
+    perror("fstat failed");
+   return 0;
+    }
+ 
+#endif
+
+TBool PVerbose=ETrue;
+
+HPrint H;
+
+HPrint::~HPrint()
+	{
+	iLogFile.close();
+	}
+
+void HPrint::SetLogFile(const char* aFileName)
+	{
+	iLogFile.open(aFileName);
+	}
+
+
+/**
+Closing the logfile.(since 'n' number of drive images can be created)
+
+@internalComponent
+@released
+
+*/
+void HPrint::CloseLogFile()
+	{
+	if(iLogFile.is_open())
+		iLogFile.close();
+	}
+
+TInt HPrint::PrintString(TPrintType aType,const char *aFmt,...)
+//
+// Print text, noting where to send it.
+//
+	{
+
+	TInt r=KErrNone;
+	va_list list;
+	va_start(list,aFmt);
+	_vsnprintf((char *)iText,KMaxStringLength,aFmt,list);
+	va_end(list);
+	switch (aType)
+		{
+	case EAlways:
+		cout << iText;
+		iLogFile << iText;
+		break;
+	case EScreen:
+		cout << iText;
+		break;
+	case ELog:
+		if (iVerbose)
+			cout << iText;
+		iLogFile << iText;
+		break;
+	case EWarning:
+		cerr << "WARNING: " << iText;
+		iLogFile << "WARNING: "<<iText;
+		break;
+	case EError:
+		cerr << "ERROR: " << iText;
+		iLogFile << "ERROR: " << iText;
+		r=KErrGeneral;
+		break;
+	case EPeError:
+		if (PVerbose)
+			{
+			cerr << "ERROR: " << iText;
+			iLogFile << "ERROR: " << iText;
+			}
+		r=KErrGeneral;
+		break;
+	case ESevereError:
+		cerr << "ERROR: " << iText;
+		iLogFile << "ERROR: " << iText;
+		r=KErrGeneral;
+		break;
+	case EDiagnostic:
+		cerr << "DIAGNOSTIC MESSAGE: " << iText;
+		iLogFile << "DIAGNOSTIC MESSAGE: "<<iText;
+		break;
+	default:
+		cerr << "ERROR: Invalid print type" << endl;
+		r=KErrGeneral;
+		}
+	cout.flush();
+	iLogFile.flush();
+	return r;
+    }
+
+TVersion::TVersion()
+	{}
+TVersion::TVersion(TInt aMajor, TInt aMinor, TInt aBuild)
+	: iMajor((TInt8)aMajor), iMinor((TInt8)aMinor), iBuild((TInt16)aBuild)
+	{}
+#ifdef __TOOLS2__
+istringstream &operator>>(istringstream &is, TVersion &aVersion)
+#else
+istrstream &operator>>(istrstream &is, TVersion &aVersion)
+#endif
+//
+// Input a TVersion with syntax: major[.minor][(build)]
+//	
+	{
+#ifdef __TOOLS2__
+string tmp = is.str();
+const char *str=tmp.c_str();
+#else
+#ifdef __LINUX__
+    char *str = is.rdbuf()->str();
+#else
+    char *str=is.str();
+#endif
+#endif
+
+
+	TInt build=0;
+	memset(&aVersion, sizeof(TVersion), 0);	
+	TInt i;
+	TInt len=strlen(str);
+	for (i=0; i<len; i++)
+		if (str[i]=='(')
+			break;
+	if (i<len)
+		build=atoi(str+i+1);
+	aVersion.iMajor = (TInt8)Min(KMaxTInt8, atoi(str));
+	int majorV = atoi(str);
+	// iMajor is defined as TInt8 so it should not be bigger than 127
+	if (majorV > 127)
+		{ 
+		cout << "\n Warning: major version must be in range 0 - 127 \n";
+		}
+	char* pMinor = strchr(str, '.');
+	if (pMinor)
+		{
+		pMinor++; 
+		aVersion.iMinor = (TInt8)Min(KMaxTInt8, atoi(pMinor));
+		int minorV = atoi(pMinor);
+		// iMinor is defined as TInt8 so it should not be bigger than 127
+		if (minorV > 127)
+			{ 
+			cout << "\n Warning: minor version must be in range 0 - 127 \n";
+			}
+		}	
+	aVersion.iBuild=(TInt16)build;
+	return is;
+	}
+
+TInt Locate(const char *aString, char aChar)
+//
+// Locate aChar in aString
+//
+	{
+
+	if (aString==NULL)
+		return KErrNotFound;
+	TInt i=0;
+	while (*aString!=0)
+		{
+		if (*aString==aChar)
+			return i;
+		aString++;
+		i++;
+		}
+	return KErrNotFound;
+	}
+
+
+#define KHoursToMicroSeconds	Int64(3600000000UL) 
+#define KDaysToMicroSeconds		(Int64(24)*KHoursToMicroSeconds)
+const TInt KMinutesToMicroSeconds = 60000000;
+const TInt KSecondsToMicroSeconds =  1000000;
+
+const TInt8 mTab[2][12]=
+    {
+    {31,28,31,30,31,30,31,31,30,31,30,31}, // 28 days in Feb
+    {31,29,31,30,31,30,31,31,30,31,30,31}  // 29 days in Feb
+    };
+
+TInt Time::LeapYearsUpTo(TInt aYear)
+//
+// from 0AD to present year according to the rule above
+//
+	{
+
+	if (aYear<=0)
+		return(aYear/4);
+	if (aYear<=1600)
+		return(1+((aYear-1)/4));
+	TInt num=401; // 1600/4+1
+	aYear-=1601;
+	num+=(aYear/4-aYear/100+aYear/400);
+	return(num);
+	}
+
+TBool Time::IsLeapYear(TInt aYear)
+//
+// up to and including 1600 leap years were every 4 years,since then leap years are every 4 years unless
+// the year falls on a century which is not divisible by 4 (ie 1900 wasnt,2000 will be)
+// for simplicity define year 0 as a leap year
+//
+	{
+
+	if (aYear>1600)
+    	return(!(aYear%4) && (aYear%100 || !(aYear%400)));
+	return(!(aYear%4));
+	}
+
+
+Int64 ConvertTime(TInt aDay, TInt aMonth, TInt aYear, TInt aHour, TInt aMinute, TInt aSecond, TInt aMilliSeconds)
+//
+// converts TDateTime into a TTime, doesnt check for overflows
+//
+	{
+	
+	TInt days=365*aYear+Time::LeapYearsUpTo(aYear);
+	TBool isleap=Time::IsLeapYear(aYear);
+	for (TInt ii=0; ii<aMonth; ii++)
+	    days+=(mTab[isleap][ii]);	
+	days+=aDay;
+	TInt sum=aMilliSeconds+aSecond*KSecondsToMicroSeconds;
+	return((Int64(days)*KDaysToMicroSeconds+Int64(aHour)*KHoursToMicroSeconds) 
+			+(Int64(KMinutesToMicroSeconds)*Int64(aMinute)+Int64(sum))); 
+	}
+	
+TInt StringToTime(Int64 &aTime, char *aString)
+//
+// Convert string to time. String is in the format:
+//
+// dd/mm/yyyy hh:mm:ss.mmmmmmm
+//
+	{
+	TInt day=1;
+	TInt month=1;
+	TInt year=1997;
+	TInt hour=10;
+	TInt minute=10;
+	TInt sec=0;
+	TInt mill=0;
+	char ch;
+	#ifdef __TOOLS2__
+	istringstream val(aString);
+	#else
+	istrstream val(aString,strlen(aString));
+	#endif
+	val >> dec >> day; // locks istrstream in decimal mode for further extractions
+	val >> ch;
+	if (ch!='/')
+		return KErrGeneral;
+	val >> month;
+	val >> ch;
+	if (ch!='/')
+		return KErrGeneral;
+	val >> year;
+	val >> ch;
+
+	if (ch=='_')
+		{
+		// time too.
+		val >> hour;
+		val >> ch;
+		if (ch!=':')
+			return KErrGeneral;
+		val >> minute;
+		val >> ch;
+		if (ch!=':')
+			return KErrGeneral;
+		val >> sec;
+		val >> ch;
+		if (ch=='.')
+			{
+			val >> mill;
+			}
+		}
+
+	if (day<1 || day>31)
+		return KErrArgument;
+	if (month<1 || month>12)
+		return KErrArgument;
+	if (year<1970 || year>2060)
+		return KErrArgument;
+	if (hour<0 || hour>23)
+		return KErrArgument;
+	if (minute<0 || minute>59)
+		return KErrArgument;
+	if (sec<0 || sec>59)
+		return KErrArgument;
+	if (mill<0 || mill>999999)
+		return KErrArgument;
+
+	aTime=ConvertTime(day-1, month-1, year, hour, minute, sec, mill);
+	return KErrNone;
+	}
+
+void ByteSwap(TUint &aVal)
+	{
+	TUint t0=aVal & 0xff;
+	TUint t1=(aVal>>8)  & 0xff;
+	TUint t2=(aVal>>16) & 0xff;
+	TUint t3=aVal>>24;
+	aVal=(t0 << 24) | (t1 << 16) | (t2 << 8) | (t3);
+	}
+
+void ByteSwap(TUint16 &aVal)
+	{
+	TUint16 t0=(TUint16)((aVal >> 8) & 0xff);
+	TUint16 t1=(TUint16)(aVal & 0xff);
+	aVal=(TUint16)((t1 << 8) | t0);
+	}
+
+void ByteSwap(TUint *aPtr, TInt aSize)
+	{
+
+	while ((aSize-=4)>=0)
+		ByteSwap(*aPtr++);
+	}
+
+TBool IsBracketedHex(const char* s, const char* brackets, TInt digits, TUint32& aValue)
+	{
+	if (s[0]!=brackets[0] || s[1+digits]!=brackets[1])
+		return EFalse;
+	TInt i;
+	TUint32 x = 0;
+	for (i=1; i<=digits; ++i)
+		{
+		TInt c = s[i];
+		if (c>='a' && c<='z') c-=32;
+		if (c<'0' || (c>'9' && c<'A') || c>'F')
+			return EFalse;
+		c-='0';
+		if (c>9) c-=7;
+		x = (x<<4) | (TUint32)c;
+		}
+	aValue = x;
+	return ETrue;
+	}
+
+TInt CheckForDecimalVersion(const char* begin, const char* s, TUint32& aValue)
+	{
+	aValue = 0;
+	if (s <= begin || *s != '}')
+		return 0;
+	TUint32 v[2] = {0,0};
+	TUint32 m = 1;
+	TInt pos = 0;
+	const char* s0 = s + 1;
+	for (--s; s >= begin; --s)
+		{
+		int c = *s;
+		if (c >= '0' && c <= '9')
+			{
+			v[pos] += m * (c - '0');
+			if (v[pos] >= 65536u)
+				return 0;
+			m *= 10;
+			}
+		else if (c == '.')
+			{
+			m = 1;
+			if (++pos >= 2)
+				return 0;
+			}
+		else if (c == '{')
+			break;
+		else
+			return 0;
+		}
+	if (s < begin)
+		return 0;
+	aValue = (v[1] << 16) | v[0];
+	return s0 - s;
+	}
+
+// Decompose a name of the form NAME{MMMMmmmm}[UUUUUUUU].EXT where the bracketed
+// sections and extension are both optional.
+// Return a newly malloc-ed string containing NAME.EXT
+// Set aUid = 0xUUUUUUUU if present, 0 if not
+// Set aModuleVersion = 0xMMMMmmmm if present, 0 if not
+// Set aFlags according to which of these are present
+char* SplitFileName(const char* aName, TUint32& aUid, TUint32& aModuleVersion, TUint32& aFlags)
+	{
+	TFileNameInfo f(aName, ETrue);
+	aUid = f.iUid3;
+	aModuleVersion = f.iModuleVersion;
+	aFlags = f.iFlags;
+	TInt nl = f.iBaseLength;
+	TInt el = f.iTotalLength - f.iExtPos;
+	TInt tl = nl + el;
+	char* t = (char*)malloc(tl + 1);
+	if (t)
+		{
+		memcpy(t, aName, nl);
+		if (el)
+			memcpy(t + nl, aName + f.iExtPos, el);
+		t[tl] = 0;
+		}
+	return t;
+	}
+
+
+// Decompose a name of the form NAME{MMMMmmmm}.EXT where the bracketed
+// sections and extension are both optional.
+// Return a newly malloc-ed string containing NAME.EXT
+// Set aModuleVersion = 0xMMMMmmmm if present, 0 if not
+// Set aFlags according to whether version present
+char* SplitFileName(const char* aName, TUint32& aModuleVersion, TUint32& aFlags)
+	{
+	TFileNameInfo f(aName, EFalse);
+	aModuleVersion = f.iModuleVersion;
+	aFlags = f.iFlags;
+	TInt nl = f.iBaseLength;
+	TInt el = f.iTotalLength - f.iExtPos;
+	TInt tl = nl + el;
+	char* t = (char*)malloc(tl + 1);
+	if (t)
+		{
+		memcpy(t, aName, nl);
+		if (el)
+			memcpy(t + nl, aName + f.iExtPos, el);
+		t[tl] = 0;
+		}
+	return t;
+	}
+
+
+// Parse a filename and convert decimal version number to hex
+char* NormaliseFileName(const char* aName) {
+	//convert forward slashes into back slashes.
+	char* filename = strdup(aName);  //prevent violated access from stack.	
+#ifdef WIN32
+#define SPLIT_CHAR1	'/'
+#define SPLIT_CHAR2	'\\'
+#else
+#define SPLIT_CHAR1	'\\'
+#define SPLIT_CHAR2	'/'
+#endif
+	char* fwdslashfinder = filename;
+	fwdslashfinder=strchr(fwdslashfinder, SPLIT_CHAR1);
+	while(fwdslashfinder){
+		*fwdslashfinder++ = SPLIT_CHAR2;
+		fwdslashfinder=strchr(fwdslashfinder, SPLIT_CHAR1);
+	}
+
+	//normalize filename.
+	TFileNameInfo f(filename, EFalse);
+	TInt nl = f.iBaseLength;
+	TInt el = f.iTotalLength - f.iExtPos;
+	TInt tl = nl + el;
+	if (f.iFlags & EVerPresent)
+		tl += 10;
+	char* t = new char[tl + 1];
+	if (t) {
+		memcpy(t, filename, nl);
+		if (f.iFlags & EVerPresent)
+			sprintf(t + nl, "{%08lx}%s", f.iModuleVersion, filename + f.iExtPos);
+		else if (el)
+			memcpy(t + nl,  filename + f.iExtPos, el);
+		t[tl] = 0;
+	} 
+	free(filename);
+	return t;
+}
+
+TFileNameInfo::TFileNameInfo(const char* aFileName, TBool aLookForUid)
+	{
+	iFileName = aFileName;
+	TInt l = strlen(aFileName);
+	iTotalLength = l;
+	TInt remain = l;
+	iFlags = 0;
+	iUid3 = 0;
+	iModuleVersion = 0;
+	iBaseLength = l;
+	iExtPos = l;
+	const char* s = iFileName + l;
+	for (; s>=iFileName && *s!='.' && *s!='}' && (!aLookForUid || *s!=']'); --s) {}
+	if (s<iFileName)
+		return;
+	if (*s == '.')
+		{
+		iExtPos = s - iFileName;
+		if (iExtPos == 0)
+			{
+			iBaseLength = 0;
+			return;
+			}
+		remain = iExtPos;
+		--s;
+		}
+	else if (s != iFileName + l)
+		return;
+	if (aLookForUid && remain>=10 && IsBracketedHex(s-9, "[]", 8, iUid3))
+		{
+		iFlags |= EUidPresent;
+		remain -= 10;
+		s -= 10;
+		}
+	if (remain>=10 && IsBracketedHex(s-9, "{}", 8, iModuleVersion))
+		{
+		iFlags |= EVerPresent;
+		remain -= 10;
+		s -= 10;
+		}
+	else
+		{
+		TInt n = CheckForDecimalVersion(iFileName, s, iModuleVersion);
+		if (n>0)
+			{
+			iFlags |= EVerPresent;
+			remain -= n;
+			s -= n;
+			}
+		}
+	iBaseLength = remain;
+	}
+
+
+#define PARSE_CAPABILITIES_ERROR(aMessage) Print(EError, "%s\n",aMessage)
+#define PARSE_CAPABILITIES_ERROR2(aMessage1,aMessage2) Print(EError, "%s%s\n",aMessage1,aMessage2)
+
+TInt ParseCapabilitiesArg(SCapabilitySet& aCapabilities, const char *aText)
+//
+// This is a cun'n'paste copy of the function in BASE\WINS\SPECIFIC\PROPERTY.CPP
+// Keep both of these versions up to date with each other
+//
+	{
+	memset(&aCapabilities,0,sizeof(aCapabilities));
+	char c;
+	while((c=*aText)!=0)
+		{
+		if(c<=' ')
+			{
+			++aText;
+			continue;
+			}
+		int invert=0;
+		if(c=='+')
+			{
+			++aText;
+			c=*aText;
+			}
+		if(c=='-')
+			{
+			invert=1;
+			++aText;
+			}
+		const char* name = aText;
+		while((c=*aText)>' ')
+			{
+			if(c=='-' || c=='+')
+				break;
+			++aText;
+			}
+		TUint n = aText-name; 
+		TInt i; 
+
+		if(n==3 && strnicmp("all",name,n)==0)
+			{
+			if(invert)
+				{
+				PARSE_CAPABILITIES_ERROR("Capability '-ALL' not allowed");
+				return KErrArgument;
+				}
+			for(i=0; i<ECapability_Limit; i++)
+				{
+				if(CapabilityNames[i])
+					aCapabilities[i>>5] |= (1<<(i&31));
+				}
+			continue;
+			}
+
+		if(n==4 && strnicmp("none",name,n)==0)
+			{
+			if(invert)
+				{
+				PARSE_CAPABILITIES_ERROR("Capability '-NONE' not allowed");
+				return KErrArgument;
+				}
+			memset(&aCapabilities,0,sizeof(aCapabilities));
+			continue;
+			}
+
+		for(i=0; i<ECapability_Limit; i++)
+			{
+			const char* cap = CapabilityNames[i];
+			if(!cap)
+				continue;
+			if((TUint)strlen(cap)!=n) 
+				continue;
+			if(strnicmp(cap,name,n)!=0)
+				continue;
+			break;
+			}
+		if(i>=ECapability_Limit)
+			{
+			char badName[32];
+			if(n>=sizeof(badName)) n=sizeof(badName)-1;
+			memcpy(badName,name,n);
+			badName[n]=0;
+			PARSE_CAPABILITIES_ERROR2("Unrecognised capability name: ",badName);
+			return KErrArgument;
+			}
+		if(invert)
+			aCapabilities[i>>5] &= ~(1<<(i&31));
+		else
+			aCapabilities[i>>5] |= (1<<(i&31));
+		}
+	return KErrNone;
+	}
+
+TInt ParseBoolArg(TBool& aValue, const char *aText)
+	{
+	if (_stricmp(aText, "on")==0 || _stricmp(aText, "yes")==0 || _stricmp(aText, "1")==0 || strlen(aText)==0)
+		{
+		aValue = ETrue;
+		return KErrNone;
+		}
+	if (_stricmp(aText, "off")==0 || _stricmp(aText, "no")==0 || _stricmp(aText, "0")==0 )
+		{
+		aValue = EFalse;
+		return KErrNone;
+		}
+	Print(EError, "Expected a boolean on/off value but found %s\n",aText);
+	return KErrArgument;
+}
+ 
+TBool IsValidNumber(const char* aStr){
+	if(0 == aStr || 0 == *aStr) 
+		return EFalse ;
+	if(*aStr == '+' || *aStr == '-') 
+			aStr ++ ; 
+	if(aStr[0] == '0' && (aStr[1] | 0x20) == 'x'){
+		aStr += 2 ;
+		while(*aStr){
+			if((*aStr >= '0' && *aStr <= '9') ||
+				(*aStr >= 'a' && *aStr <= 'f') ||
+				(*aStr >= 'A' && *aStr <= 'F'))
+				aStr++ ;
+			else
+				return EFalse ;
+		}
+	}
+	else {		
+		while(*aStr){
+			if(*aStr >= '0' && *aStr <= '9')
+				aStr++ ;
+			else
+				return EFalse ;
+		}
+	}
+	return ETrue ;
+}
--- a/imgtools/imglib/host/utf16string.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/host/utf16string.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -41,6 +41,7 @@
 UTF16String::UTF16String(const TUint16* aUtf16Str,TInt aLength /* = -1*/){
 	
 	if(aLength < 0){
+		aLength = 0 ;
 		const TUint16* p = aUtf16Str ;
 		while(*p){
 			p++ ;
--- a/imgtools/imglib/inc/e32image.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/inc/e32image.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,132 +1,129 @@
-/*
-* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifndef __E32IMAGE_H__
-#define __E32IMAGE_H__
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-#include <fstream>
-using namespace std;
-#else //!__MSVCDOTNET__
-#include <fstream.h>
-#endif //__MSVCDOTNET__
-
-#include <e32std.h>
-#include <e32ldr.h>
-#include <f32image.h>
-#include "byte_pair.h"
-
-enum TFileSource
-	{
-	EE32Image=0,
-	EPeFile=1,
-	EElfFile=2,
-	};
-
-class E32ImageFile
-	{
-public:
-	static E32ImageFile* New();
-	E32ImageFile(CBytePair *aBPE = NULL);
-	virtual ~E32ImageFile();
-	virtual TBool Translate(const char* aFileName, TUint aDataBase, TBool aAllowDllData, TBool aSymLkupEnabled = FALSE);
-	TInt ReadHeader(ifstream& is);
-	TInt Open(const char* aFileName);
-#ifndef __LINUX__
-	TInt Open(const wchar_t* aFileName);
-#endif
-	void Adjust(TInt aSize, TBool aAllowShrink=ETrue);
-	TUint VaOfOrdinal(TUint aOrdinal);
-	void RelocateSection(char* aPtr, char *aRelocs, TUint aCodeDelta, TUint aDataDelta, char* aImagePtr, TLinAddr** aIATRefs, TBool keepIAT=EFalse);
-	//
-	TUint TextOffset();
-	TUint DataOffset();
-	TUint BssOffset();
-	TUint32 Capability();
-	TUint32 Format();
-	TInt NumberOfImports();
-
-	TInt IsValid();
-	TInt IsDll();
-	enum TDumpFlags
-		{
-		EDumpHeader = 1<<0,
-		EDumpSecurityInfo = 1<<1,
-		EDumpCode = 1<<2,
-		EDumpData = 1<<3,
-		EDumpExports = 1<<4,
-		EDumpImports = 1<<5,
-		EDumpDefaults = EDumpHeader|EDumpCode|EDumpData|EDumpExports|EDumpImports
-		};
-	void Dump(TText *aFileName,TInt aDumpFlags);
-	void DumpHeader(TInt aDumpFlags);
-	void DumpData(TInt aDumpFlags);
-	void SetStackSize(TInt aSize);
-	void SetHeapSizeMin(TInt aSize);
-	void SetHeapSizeMax(TInt aSize);
-	void SetUids(TUid aUid1, TUid aUid2, TUid aUid3);
-	void SetSecureId(TUint32 aId);
-	void SetVendorId(TUint32 aId);
-	void SetCallEntryPoints(TInt aBool);
-	void SetFixedAddress(TInt aBool);
-	void SetPriority(TProcessPriority aPri);
-	void SetCapability(SCapabilitySet& aCapabilities);
-	void SetFPU(unsigned int aFPU);
-	static TInt IsE32ImageFile(char *aFileName);
-	TInt DetermineEntryPointType();
-	void UpdateHeaderCrc();
-	void SetDefaultHeader();
-	void CreateExportBitMap();
-	void AddExportDescription();
-	TInt CheckExportDescription();
-	TInt Validate();
-public:
-	inline TUint OrigCodeOffset() const {return OffsetUnadjust(iOrigHdr->iCodeOffset);}
-	inline TUint OrigDataOffset() const {return OffsetUnadjust(iOrigHdr->iDataOffset);}
-	inline TUint OrigCodeRelocOffset() const {return OffsetUnadjust(iOrigHdr->iCodeRelocOffset);}
-	inline TUint OrigDataRelocOffset() const {return OffsetUnadjust(iOrigHdr->iDataRelocOffset);}
-	inline TUint OrigImportOffset() const {return OffsetUnadjust(iOrigHdr->iImportOffset);}
-	inline TUint OrigExportDirOffset() const {return OffsetUnadjust(iOrigHdr->iExportDirOffset);}
-	inline TUint OffsetUnadjust(TUint a) const {return a ? a-iOrigHdrOffsetAdj : 0;}
-	inline void OffsetAdjust(TUint& a) { if (a) a+=iOrigHdrOffsetAdj; }
-public:
-	char* iData;
-	TInt iSize;
-	E32ImageHeader* iOrigHdr;
-	E32ImageHeaderV* iHdr;
-	char* iFileName;
-#ifndef __LINUX__
-	wchar_t* iWideFileName;
-#endif
-	TInt iError;
-	TFileSource iSource;
-	TUint iOrigHdrOffsetAdj;
-	TInt iFileSize;
-	TUint8* iExportBitMap;
-	TInt iMissingExports;
-	CBytePair *iBPE;
-	};
-
-#ifdef __VC32__
-ostream &operator<<(ostream &os, const E32ImageFile &aImage);
-#else
-ostream &operator<<(ostream &os, const E32ImageFile &aImage);
-#endif
-ifstream &operator>>(ifstream &is, E32ImageFile &aImage);
-
-#endif
+/*
+* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifndef __E32IMAGE_H__
+#define __E32IMAGE_H__
+
+ 
+#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
+#include <fstream>
+using namespace std;
+#else //!__MSVCDOTNET__
+#include <fstream.h>
+#endif //__MSVCDOTNET__
+
+#include <e32std.h>
+#include <e32ldr.h>
+#include <f32image.h>
+#include "byte_pair.h"
+
+enum TFileSource
+	{
+	EE32Image=0,
+	EPeFile=1,
+	EElfFile=2,
+	};
+
+class E32ImageFile
+	{
+public:
+	static E32ImageFile* New();
+	E32ImageFile(CBytePair *aBPE = NULL);
+	virtual ~E32ImageFile();
+	virtual TBool Translate(const char* aFileName, TUint aDataBase, TBool aAllowDllData, TBool aSymLkupEnabled = FALSE);
+	TInt ReadHeader(ifstream& is);
+	TInt Open(const char* aFileName);
+#ifndef __LINUX__
+	TInt Open(const wchar_t* aFileName);
+#endif
+	void Adjust(TInt aSize, TBool aAllowShrink=ETrue);
+	TUint VaOfOrdinal(TUint aOrdinal);
+	void RelocateSection(char* aPtr, char *aRelocs, TUint aCodeDelta, TUint aDataDelta, char* aImagePtr, TLinAddr** aIATRefs, TBool keepIAT=EFalse);
+	//
+	TUint TextOffset();
+	TUint DataOffset();
+	TUint BssOffset();
+	TUint32 Capability();
+	TUint32 Format();
+	TInt NumberOfImports();
+
+	TInt IsValid() const {return (iError == KErrNone);}
+	TInt IsDll();
+	enum TDumpFlags
+		{
+		EDumpHeader = 1<<0,
+		EDumpSecurityInfo = 1<<1,
+		EDumpCode = 1<<2,
+		EDumpData = 1<<3,
+		EDumpExports = 1<<4,
+		EDumpImports = 1<<5,
+		EDumpDefaults = EDumpHeader|EDumpCode|EDumpData|EDumpExports|EDumpImports
+		};
+	void Dump(const char* aFileName,TInt aDumpFlags);
+	void DumpHeader(TInt aDumpFlags);
+	void DumpData(TInt aDumpFlags);
+	void SetStackSize(TInt aSize);
+	void SetHeapSizeMin(TInt aSize);
+	void SetHeapSizeMax(TInt aSize);
+	void SetUids(TUid aUid1, TUid aUid2, TUid aUid3);
+	void SetSecureId(TUint32 aId);
+	void SetVendorId(TUint32 aId);
+	void SetCallEntryPoints(TInt aBool);
+	void SetFixedAddress(TInt aBool);
+	void SetPriority(TProcessPriority aPri);
+	void SetCapability(SCapabilitySet& aCapabilities);
+	void SetFPU(unsigned int aFPU);
+	static TInt IsE32ImageFile(const char *aFileName);
+	TInt DetermineEntryPointType();
+	void UpdateHeaderCrc();
+	void SetDefaultHeader();
+	void CreateExportBitMap();
+	void AddExportDescription();
+	TInt CheckExportDescription();
+	TInt Validate();
+public:
+	inline TUint OrigCodeOffset() const {return OffsetUnadjust(iOrigHdr->iCodeOffset);}
+	inline TUint OrigDataOffset() const {return OffsetUnadjust(iOrigHdr->iDataOffset);}
+	inline TUint OrigCodeRelocOffset() const {return OffsetUnadjust(iOrigHdr->iCodeRelocOffset);}
+	inline TUint OrigDataRelocOffset() const {return OffsetUnadjust(iOrigHdr->iDataRelocOffset);}
+	inline TUint OrigImportOffset() const {return OffsetUnadjust(iOrigHdr->iImportOffset);}
+	inline TUint OrigExportDirOffset() const {return OffsetUnadjust(iOrigHdr->iExportDirOffset);}
+	inline TUint OffsetUnadjust(TUint a) const {return a ? a-iOrigHdrOffsetAdj : 0;}
+	inline void OffsetAdjust(TUint& a) { if (a) a+=iOrigHdrOffsetAdj; }
+public:
+	char* iData;
+	TInt iSize;
+	E32ImageHeader* iOrigHdr;
+	E32ImageHeaderV* iHdr;
+	char* iFileName;
+#ifndef __LINUX__
+	wchar_t* iWideFileName;
+#endif
+	TInt iError;
+	TFileSource iSource;
+	TUint iOrigHdrOffsetAdj;
+	TInt iFileSize;
+	TUint8* iExportBitMap;
+	TInt iMissingExports;
+	CBytePair *iBPE;
+	};
+
+ostream& operator<<(ostream &os, const E32ImageFile &aImage); 
+ifstream& operator>>(ifstream &is, E32ImageFile &aImage);
+
+#endif
--- a/imgtools/imglib/inc/h_utl.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/inc/h_utl.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,218 +1,219 @@
-/*
-* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#if !defined(__H_UTL_H__)
-#define __H_UTL_H__
-//
-#include <stdio.h>
-
-#ifdef __VC32__
- #ifdef __MSVCDOTNET__
-  #include <iostream>
-  #include <strstream>
-  #include <fstream>
-  using namespace std;
- #else //!__MSVCDOTNET__
-  #include <iostream.h>
-  #include <strstrea.h>
-  #include <fstream.h>
- #endif //__MSVCDOTNET__
-#else //!__VC32__
-#ifdef __TOOLS2__ 
-#include <fstream>
-#include <iostream>
-#include <sstream>
-#include <iomanip>
-using namespace std;
-#else // !__TOOLS2__ OR __VC32__ OR __MSVCDOTNET__
-  #include <iostream.h>
-  #include <strstream.h>
-  #include <fstream.h>
-#endif
-#endif 
-
-#ifdef __LINUX__
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#include <ctype.h>
-
-
-#define _close close
-#define _filelength filelength
-#define _lseek lseek
-#define _read read
-#define _snprintf snprintf
-#define _vsnprintf vsnprintf
-
-// linux case insensitive stromg comparisons have different names
-#define stricmp  strcasecmp		
-#define _stricmp strcasecmp		
-#define strnicmp strncasecmp	
-
-// to fix the linux problem: memcpy does not work with overlapped areas.
-#define memcpy memmove
-
-// hand-rolled strupr function for converting a string to all uppercase
-char* strupr(char *a);
-
-// return the length of a file
-off_t filelength (int filedes);
-#endif
-
-
-#include <e32cmn.h>
-#include <e32def.h>
-
-#define ALIGN4K(a) ((a+0xfff)&0xfffff000)
-#define ALIGN4(a) ((a+0x3)&0xfffffffc)
-
-
-#ifdef HEAPCHK
-#define NOIMAGE
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-void HeapCheck();
-#endif
-#define Print H.PrintString
-//
-const TInt KMaxStringLength=0x400;
-//
-class HFile
-	{
-public:
-	static TBool Open(const TText * const aFileName, TInt32 * const aFileHandle);
-	static TBool Read(const TInt32 aFileHandle, TAny * const aBuffer, const TUint32 aCount);
-	static TBool Seek(const TInt32 aFileHandle, const TUint32 aOffset);
-	static TUint32 GetPos(const TInt32 aFileHandle);
-	static TAny Close(const TInt32 aFileHandle);
-	static TUint32 GetLength(const TInt32 aFileHandle);
-	static TUint32 GetLength(TText *aName);
-	static TUint32 Read(TText *aName, TAny *someMem);
-	};
-//
-//inline TAny* operator new(TUint /*aSize*/, TAny* aBase)
-//	{return aBase;}
-
-class HMem
-	{
-public:
-	static TAny *Alloc(TAny * const aBaseAddress,const TUint32 aImageSize);
-	static void Free(TAny * const aMem);
-	static void Copy(TAny * const aDestAddr,const TAny * const aSourceAddr,const TUint32 aLength);
-	static void Move(TAny * const aDestAddr,const TAny * const aSourceAddr,const TUint32 aLength);
-	static void Set(TAny * const aDestAddr, const TUint8 aFillChar, const TUint32 aLength);
-	static void FillZ(TAny * const aDestAddr, const TUint32 aLength);
-
-	static TUint CheckSum(TUint *aPtr, TInt aSize);
-	static TUint CheckSum8(TUint8 *aPtr, TInt aSize);
-	static TUint CheckSumOdd8(TUint8 *aPtr, TInt aSize);
-	static TUint CheckSumEven8(TUint8 *aPtr, TInt aSize);
-
-	static void Crc32(TUint32& aCrc, const TAny* aPtr, TInt aLength);
-	};
-//
-enum TPrintType {EAlways, EScreen, ELog, EWarning, EError, EPeError, ESevereError, EDiagnostic};
-//
-class HPrint
-	{
-public:
-	~HPrint();
-	void SetLogFile(TText *aFileName);
-	void CloseLogFile();						//	Added to close intermediate log files.
-	TInt PrintString(TPrintType aType,const char *aFmt,...);
-public:
-	TText iText[KMaxStringLength];
-	TBool iVerbose;
-private:
-	ofstream iLogFile;
-	};
-//
-extern HPrint H;
-extern TBool PVerbose;
-//
-TAny *operator new(TUint aSize);
-void operator delete(TAny *aPtr);
-//
-#ifdef __TOOLS2__
-istringstream &operator>>(istringstream &is, TVersion &aVersion);
-#else
-istrstream &operator>>(istrstream &is, TVersion &aVersion);
-#endif
-//
-TInt StringToTime(TInt64 &aTime, char *aString);
-
-void ByteSwap(TUint &aVal);
-void ByteSwap(TUint16 &aVal);
-void ByteSwap(TUint *aPtr, TInt aSize);
-
-extern TBool gLittleEndian;
-
-
-/**
- Convert string to number.
-*/
-template <class T>
-TInt Val(T& aVal, char* aStr)
-	{
-
-	T x;
-	#ifdef __TOOLS2__
-	istringstream val(aStr);
-	#else
-	istrstream val(aStr,strlen(aStr));
-	#endif
-	#if defined(__MSVCDOTNET__) || defined (__TOOLS2__) 
-		val >> setbase(0);
-	#endif //__MSVCDOTNET__                             
-	val >> x;
-	if (!val.eof() || val.fail())
-		return KErrGeneral;
-	aVal=x;
-	return KErrNone;
-	}
-
-// Filename decompose routines
-enum TDecomposeFlag
-	{
-	EUidPresent=1,
-	EVerPresent=2
-	};
-
-class TFileNameInfo
-	{
-public:
-	TFileNameInfo(const char* aFileName, TBool aLookForUid);
-public:
-	const char* iFileName;
-	TInt iTotalLength;
-	TInt iBaseLength;
-	TInt iExtPos;
-	TUint32 iUid3;
-	TUint32 iModuleVersion;
-	TUint32 iFlags;
-	};
-
-extern char* NormaliseFileName(const char* aName);
-extern char* SplitFileName(const char* aName, TUint32& aUid, TUint32& aModuleVersion, TUint32& aFlags);
-extern char* SplitFileName(const char* aName, TUint32& aModuleVersion, TUint32& aFlags);
-extern TInt ParseCapabilitiesArg(SCapabilitySet& aCapabilities, const char *aText);
-extern TInt ParseBoolArg(TBool& aValue, const char *aText);
-
-#endif
-
+/*
+* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#if !defined(__H_UTL_H__)
+#define __H_UTL_H__
+//
+#include <stdio.h>
+
+#ifdef __VC32__
+ #ifdef __MSVCDOTNET__
+  #include <iostream>
+  #include <strstream>
+  #include <fstream>
+  using namespace std;
+ #else //!__MSVCDOTNET__
+  #include <iostream.h>
+  #include <strstrea.h>
+  #include <fstream.h>
+ #endif //__MSVCDOTNET__
+#else //!__VC32__
+#ifdef __TOOLS2__ 
+#include <fstream>
+#include <iostream>
+#include <sstream>
+#include <iomanip>
+using namespace std;
+#else // !__TOOLS2__ OR __VC32__ OR __MSVCDOTNET__
+  #include <iostream.h>
+  #include <strstream.h>
+  #include <fstream.h>
+#endif
+#endif 
+
+#ifdef __LINUX__
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <ctype.h>
+
+
+#define _close close
+#define _filelength filelength
+#define _lseek lseek
+#define _read read
+#define _snprintf snprintf
+#define _vsnprintf vsnprintf
+
+// linux case insensitive stromg comparisons have different names
+#define stricmp  strcasecmp		
+#define _stricmp strcasecmp		
+#define strnicmp strncasecmp	
+
+// to fix the linux problem: memcpy does not work with overlapped areas.
+#define memcpy memmove
+#define SLASH_CHAR	'/'
+// hand-rolled strupr function for converting a string to all uppercase
+char* strupr(char *a);
+
+// return the length of a file
+off_t filelength (int filedes);
+#else
+#define SLASH_CHAR	'\\'
+#endif
+
+
+#include <e32cmn.h>
+#include <e32def.h>
+
+#define ALIGN4K(a) ((a+0xfff)&0xfffff000)
+#define ALIGN4(a) ((a+0x3)&0xfffffffc)
+
+
+#ifdef HEAPCHK
+#define NOIMAGE
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+void HeapCheck();
+#endif
+#define Print H.PrintString
+//
+const TInt KMaxStringLength=0x400;
+//
+class HFile
+	{
+public:
+	static TBool Open(const char* aFileName, TInt32 * const aFileHandle);
+	static TBool Read(const TInt32 aFileHandle, TAny * const aBuffer, const TUint32 aCount);
+	static TBool Seek(const TInt32 aFileHandle, const TUint32 aOffset);
+	static TUint32 GetPos(const TInt32 aFileHandle);
+	static TAny Close(const TInt32 aFileHandle);
+	static TUint32 GetLength(const TInt32 aFileHandle);
+	static TUint32 GetLength(const char* aName);
+	static TUint32 Read(const char* aName, TAny *someMem);
+	};
+//
+//inline TAny* operator new(TUint /*aSize*/, TAny* aBase)
+//	{return aBase;}
+
+class HMem
+	{
+public:
+	static TAny *Alloc(TAny * const aBaseAddress,const TUint32 aImageSize);
+	static void Free(TAny * const aMem);
+	static void Copy(TAny * const aDestAddr,const TAny * const aSourceAddr,const TUint32 aLength);
+	static void Move(TAny * const aDestAddr,const TAny * const aSourceAddr,const TUint32 aLength);
+	static void Set(TAny * const aDestAddr, const TUint8 aFillChar, const TUint32 aLength);
+	static void FillZ(TAny * const aDestAddr, const TUint32 aLength);
+
+	static TUint CheckSum(TUint *aPtr, TInt aSize);
+	static TUint CheckSum8(TUint8 *aPtr, TInt aSize);
+	static TUint CheckSumOdd8(TUint8 *aPtr, TInt aSize);
+	static TUint CheckSumEven8(TUint8 *aPtr, TInt aSize);
+
+	static void Crc32(TUint32& aCrc, const TAny* aPtr, TInt aLength);
+	};
+//
+enum TPrintType {EAlways, EScreen, ELog, EWarning, EError, EPeError, ESevereError, EDiagnostic};
+//
+class HPrint
+	{
+public:
+	~HPrint();
+	void SetLogFile(const char* aFileName);
+	void CloseLogFile();						//	Added to close intermediate log files.
+	TInt PrintString(TPrintType aType,const char *aFmt,...);
+public:
+	char iText[KMaxStringLength];
+	TBool iVerbose;
+private:
+	ofstream iLogFile;
+	};
+//
+extern HPrint H;
+extern TBool PVerbose;
+//
+TAny *operator new(TUint aSize);
+void operator delete(TAny *aPtr);
+//
+#ifdef __TOOLS2__
+istringstream &operator>>(istringstream &is, TVersion &aVersion);
+#else
+istrstream &operator>>(istrstream &is, TVersion &aVersion);
+#endif
+//
+TInt StringToTime(TInt64 &aTime, char *aString);
+
+void ByteSwap(TUint &aVal);
+void ByteSwap(TUint16 &aVal);
+void ByteSwap(TUint *aPtr, TInt aSize);
+
+extern TBool gLittleEndian;
+
+/**
+ Convert string to number.
+*/
+template <class T>
+TInt Val(T& aVal, const char* aStr)
+	{
+
+	T x;
+	#ifdef __TOOLS2__
+	istringstream val(aStr);
+	#else
+	istrstream val((char*)aStr,strlen(aStr));
+	#endif
+	#if defined(__MSVCDOTNET__) || defined (__TOOLS2__) 
+		val >> setbase(0);
+	#endif //__MSVCDOTNET__                             
+	val >> x;
+	if (!val.eof() || val.fail())
+		return KErrGeneral;
+	aVal=x;
+	return KErrNone;
+	}
+ 
+// Filename decompose routines
+enum TDecomposeFlag
+	{
+	EUidPresent=1,
+	EVerPresent=2
+	};
+
+class TFileNameInfo
+	{
+public:
+	TFileNameInfo(const char* aFileName, TBool aLookForUid);
+	const char* iFileName;
+	TInt iTotalLength;
+	TInt iBaseLength;
+	TInt iExtPos;
+	TUint32 iUid3;
+	TUint32 iModuleVersion;
+	TUint32 iFlags;
+	};
+
+extern char* NormaliseFileName(const char* aName);
+extern char* SplitFileName(const char* aName, TUint32& aUid, TUint32& aModuleVersion, TUint32& aFlags);
+extern char* SplitFileName(const char* aName, TUint32& aModuleVersion, TUint32& aFlags);
+extern TInt ParseCapabilitiesArg(SCapabilitySet& aCapabilities, const char *aText);
+extern TInt ParseBoolArg(TBool& aValue, const char *aText); 
+extern TBool IsValidNumber(const char* aStr);
+
+#endif
+
--- a/imgtools/imglib/inc/h_ver.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/inc/h_ver.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,26 +1,26 @@
-/*
-* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifndef __H_VER_H__
-#define __H_VER_H__
-const TInt MajorVersion=2;
-const TInt MinorVersion=1;
-const TInt Build=603;
-const char Copyright[]="Copyright (c) 1996-2009 Nokia Corporation.\n\n";
-#endif
-
+/*
+* Copyright (c) 1996-2010 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifndef __H_VER_H__
+#define __H_VER_H__
+const TInt MajorVersion=2;
+const TInt MinorVersion=2;
+const TInt Build=2;
+const char Copyright[]="Copyright (c) 1996-2010 Nokia Corporation.\n\n";
+#endif
+
--- a/imgtools/imglib/inc/pe_file.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/inc/pe_file.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,184 +1,178 @@
-/*
-* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#if !defined(__PE_FILE_H__)
-#define __PE_FILE_H__
-#include <e32rom.h>
-#include <e32image.h>
-#include "pe_defs.h"
-//
-const TInt KTextSection=0;
-const TInt KConstSection=1;
-const TInt KExportSection=2;
-const TInt KDataSection=3;
-const TInt KBssSection=4;
-const TInt KImportSection=5;
-const TInt KCrtSection=6;
-const TInt KRelocSection=7;
-const TInt KNumberOfSections=8;
-//
-enum TImportStat {EImpError, EImpSuccess, EImpDone};
-//
-class PEFile
-	{
-public:
-	PEFile();
-	~PEFile();
-	TBool Init(const TText * const aFileName);
-	void Close();
-	//
-	TImportStat GetNextImport(TText * &aDllName, TUint16 &aOrdinal, TUint32 * &aThunkPtr);
-	TUint32 GetFixUp(const TUint16 aOrdinal);
-// 	TText *GetImageName();
-//	TUint8 *GetExportName(const TUint16 aOrdinal);
-//	TUint32 WriteDllRefTable(PEFile aPeArray[], TUint aMaxFiles);
-	void RelocateExportTable();
-	TUint GetNumberOfExportedFunctions();
-	TUint GetOrdinalBase();
-	TBool ExportSectionExists();
-	TBool ImportSectionExists();
-	TUint RoundToSectionSize(TUint aSize);
-	void DumpPeHeaders();
-	//
-	TInt Normalise();
-	void GetRelocs(TUint *aReloc, TUint *aRelocSection, TInt aNumberOfRelocs);
-	TInt ReadSectionHeaders();
-	TInt ReadData();
-	TInt ReadExportDirectory();
-	char *ReadSectionData(PIMAGE_SECTION_HEADER aHeader);
-	TInt NumberOfImports() const;
-	TInt NumberOfImportDlls() const;
-	TInt NumberOfExports() const;
-	TInt NumberOfRelocs();
-public:
-	static TInt CmpSectionName(PIMAGE_SECTION_HEADER apSectionHeader, char *aName);
-	TInt VirtualAddressInSection(TUint aVA, PIMAGE_SECTION_HEADER aHeader);
-	TUint DistanceFromSection(TUint aVA, PIMAGE_SECTION_HEADER aHeader);
-	TInt FindSectionByVa(TUint aVa, TUint aTryToBeClever=0);
-	static TInt HasInitialisedData(PIMAGE_SECTION_HEADER aHeader);
-	
-//	static TBool DoFixUps(PEFile aPeArray[], TUint aMaxFiles);
-//	static TBool FindByName(PEFile aPeArray[], TUint aMaxFiles,const TText * const aDllName, PEFile * &aExportPEFile);
-//	static void WriteDllRefTables(PEFile aPeArray[], TUint aMaxFiles);
-//	static void RelocateExportTables(PEFile aPeArray[], TUint aMaxFiles);
-private:
-	TBool IsInCode(TUint32 anAddr);
-	TBool IsInData(TUint32 anAddr);
-	TBool IsInDataReloc(TUint32 anAddr);
-	TBool IsInExport(TUint32 anAddr);
-	TBool IsInImport(TUint32 anAddr);
-	TBool IsValidDOSHeader(PIMAGE_DOS_HEADER pDOSHeader);
-	TBool IsValidNTHeader(PIMAGE_NT_HEADERS pNTHeader);
-	TBool IsValidFileHeader(PIMAGE_FILE_HEADER pFileHeader);
-	void DumpNextSectionInFile(PIMAGE_SECTION_HEADER pSectionHeader);
-	void CopySectionData(TAny *source, TAny *dest, TUint32 fileLength, TUint32 memLength);
-	TBool ProcessRelocData(TAny *relocData,TInt dataSize);
-	PEFile(const PEFile&);
-	const PEFile & operator = (const PEFile&);
-public:
-	static TUint32 iRomMemBase; // where the ROM is being loaded to
-	static TUint32 iRomLinearBase; // where the ROM will run
-	TUint32 iMemBase; // where this file is being loaded to
-	TUint32 iEntryPoint;
-	TUint32 iImageSize;
-	TUint32 iCodeSize;
-	TUint32 iDataSize;
-	TUint32 iHeapReservedSize;
-	TUint32 iHeapCommittedSize;
-	TUint32 iStackReservedSize;
-	TUint32 iStackCommittedSize;
-	TUint32 iBssSize;
-	TUint32 iBssOffset;
-	TUint32 iSectionAlign;
-	TUint32 iExpDirectoryOffset;
-	TUint32 iDataOffset;
-	TBool	iImageIsDll;
-private:
-	IMAGE_NT_HEADERS *iHeader;
- 	PIMAGE_EXPORT_DIRECTORY	iExpDirectory;
-	PIMAGE_IMPORT_DESCRIPTOR iImpDescriptor; 
-	TText *iFileName;
-	TInt32 iFileHandle;
-	TUint32 iLinkedBase;
-	TUint32 iStartOfHeaders; // whether DOS header or not
-	TUint32 iSizeOfHeaders; // Up to and including section headers
-	TUint32 iNumSections;
-	TUint32 iRomRunAddr; // where the code will run & rdata be accessed
-	TUint32 iRamRunAddr; // and where the data & bss will be when it does
-	TUint32 iRomDelta;
-	TUint32 iRamDelta;
-	TBool iHadDataSection;
-
-// stuff for relocating image successfully in 2 parts
-	TUint32 iBssSectionLinkedAddr;
-	TUint32 iBssSectionAddr;
-	TUint32 iBssSectionSize;
-	TUint32 iDataSectionLinkedAddr;
-	TUint32 iDataSectionAddr;
-	TUint32 iDataSectionSize;
-	TUint32 iCodeSectionAddr;
-	TUint32 iCodeSectionSize;
-	TUint32 iRDataSectionAddr;
-	TUint32 iRDataSectionSize;
-	TUint32 iCRTSectionAddr;
-	TUint32 iCRTSectionSize;
-	TUint32 iExportDataDir;
-
-// stuff for the pe->e32image translator
-	PIMAGE_SECTION_HEADER iSectionHeader[KNumberOfSections];
-	char *iSectionData[KNumberOfSections];
-	TInt iExportDirSize;
-	TInt iCpu;
-	friend class E32ImageFile;
-	friend class E32ImageFile_PE;
-	};
-
-class E32ImageFile_PE : public E32ImageFile
-	{
-public:
-	E32ImageFile_PE();
-	virtual ~E32ImageFile_PE();
-	virtual TBool Translate(const char* aFileName, TUint aDataBase, TBool aAllowDllData, TBool /*aSymLkupEnabled*/);
-	TBool Translate(PEFile &aPEFile);
-	TUint ImportAddressTableOffset();
-	TUint ConstOffset();
-private:
-	TInt DoCodeHeader(PEFile &aPeFile);
-	TInt DoDataHeader(PEFile &aPeFile, TUint aDataBase);
-	TInt CopyCode(char *aPtr, PEFile &aPeFile);
-	TInt CopyData(char *aPtr, PEFile &aPeFile);
-	TInt CopyImportAddrTable(char *aPtr, PEFile &aPeFile);
-	char *CreateImportSection(const PEFile &aPeFile, TInt &aSize);
-	void CreateExportSection(char *aPtr, PEFile &aPeFile);
-
-	void CreateExportDirectory(char *aPtr, PEFile &aPeFile);
-	void FixExportDirectory(TUint *aExportDir, PEFile &aPeFile);
-	void FixRelocs(PEFile &aPeFile, TUint *relocation, TUint *relocsection, TInt aNumberOfRelocs);
-	char *CreateCodeRelocs(TUint *reloc, TUint *relocsection, TInt nrelocs, TInt &aSize);
-	char *CreateDataRelocs(TUint *reloc, TUint *relocsection, TInt nrelocs, TInt &aSize);
-
-	TUint FixAddress(PEFile &aPeFile, TUint va);
-	TUint FixImportThunk(PEFile &aPeFile, TUint va);
-private:
-	PIMAGE_SECTION_HEADER iPeHeader[KNumberOfSections];
-	char *iPeData[KNumberOfSections];
-	TUint iConstOffset;
-	TUint iCrtOffset;
-	};
-
-#endif
+/*
+* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#if !defined(__PE_FILE_H__)
+#define __PE_FILE_H__
+#include <e32rom.h>
+#include <e32image.h>
+#include "pe_defs.h"
+//
+const TInt KTextSection=0;
+const TInt KConstSection=1;
+const TInt KExportSection=2;
+const TInt KDataSection=3;
+const TInt KBssSection=4;
+const TInt KImportSection=5;
+const TInt KCrtSection=6;
+const TInt KRelocSection=7;
+const TInt KNumberOfSections=8;
+//
+enum TImportStat {EImpError, EImpSuccess, EImpDone};
+//
+class PEFile
+	{
+public:
+	PEFile();
+	~PEFile();
+	TBool Init(const char* aFileName);
+	void Close();
+	//
+	TImportStat GetNextImport(char * &aDllName, TUint16 &aOrdinal, TUint32 * &aThunkPtr);
+	TUint32 GetFixUp(const TUint16 aOrdinal);
+
+	void RelocateExportTable();
+	TUint GetNumberOfExportedFunctions();
+	TUint GetOrdinalBase();
+	TBool ExportSectionExists();
+	TBool ImportSectionExists();
+	TUint RoundToSectionSize(TUint aSize);
+	void DumpPeHeaders();
+	//
+	TInt Normalise();
+	void GetRelocs(TUint *aReloc, TUint *aRelocSection, TInt aNumberOfRelocs);
+	TInt ReadSectionHeaders();
+	TInt ReadData();
+	TInt ReadExportDirectory();
+	char *ReadSectionData(PIMAGE_SECTION_HEADER aHeader);
+	TInt NumberOfImports() const;
+	TInt NumberOfImportDlls() const;
+	TInt NumberOfExports() const;
+	TInt NumberOfRelocs();
+public:
+	static TInt CmpSectionName(PIMAGE_SECTION_HEADER apSectionHeader, char *aName);
+	TInt VirtualAddressInSection(TUint aVA, PIMAGE_SECTION_HEADER aHeader);
+	TUint DistanceFromSection(TUint aVA, PIMAGE_SECTION_HEADER aHeader);
+	TInt FindSectionByVa(TUint aVa, TUint aTryToBeClever=0);
+	static TInt HasInitialisedData(PIMAGE_SECTION_HEADER aHeader);
+ 
+private:
+	TBool IsInCode(TUint32 anAddr);
+	TBool IsInData(TUint32 anAddr);
+	TBool IsInDataReloc(TUint32 anAddr);
+	TBool IsInExport(TUint32 anAddr);
+	TBool IsInImport(TUint32 anAddr);
+	TBool IsValidDOSHeader(PIMAGE_DOS_HEADER pDOSHeader);
+	TBool IsValidNTHeader(PIMAGE_NT_HEADERS pNTHeader);
+	TBool IsValidFileHeader(PIMAGE_FILE_HEADER pFileHeader);
+	void DumpNextSectionInFile(PIMAGE_SECTION_HEADER pSectionHeader);
+	void CopySectionData(TAny *source, TAny *dest, TUint32 fileLength, TUint32 memLength);
+	TBool ProcessRelocData(TAny *relocData,TInt dataSize);
+	PEFile(const PEFile&);
+	const PEFile & operator = (const PEFile&);
+public:
+	static TUint32 iRomMemBase; // where the ROM is being loaded to
+	static TUint32 iRomLinearBase; // where the ROM will run
+	TUint32 iMemBase; // where this file is being loaded to
+	TUint32 iEntryPoint;
+	TUint32 iImageSize;
+	TUint32 iCodeSize;
+	TUint32 iDataSize;
+	TUint32 iHeapReservedSize;
+	TUint32 iHeapCommittedSize;
+	TUint32 iStackReservedSize;
+	TUint32 iStackCommittedSize;
+	TUint32 iBssSize;
+	TUint32 iBssOffset;
+	TUint32 iSectionAlign;
+	TUint32 iExpDirectoryOffset;
+	TUint32 iDataOffset;
+	TBool	iImageIsDll;
+private:
+	IMAGE_NT_HEADERS *iHeader;
+ 	PIMAGE_EXPORT_DIRECTORY	iExpDirectory;
+	PIMAGE_IMPORT_DESCRIPTOR iImpDescriptor; 
+	char *iFileName;
+	TInt32 iFileHandle;
+	TUint32 iLinkedBase;
+	TUint32 iStartOfHeaders; // whether DOS header or not
+	TUint32 iSizeOfHeaders; // Up to and including section headers
+	TUint32 iNumSections;
+	TUint32 iRomRunAddr; // where the code will run & rdata be accessed
+	TUint32 iRamRunAddr; // and where the data & bss will be when it does
+	TUint32 iRomDelta;
+	TUint32 iRamDelta;
+	TBool iHadDataSection;
+
+// stuff for relocating image successfully in 2 parts
+	TUint32 iBssSectionLinkedAddr;
+	TUint32 iBssSectionAddr;
+	TUint32 iBssSectionSize;
+	TUint32 iDataSectionLinkedAddr;
+	TUint32 iDataSectionAddr;
+	TUint32 iDataSectionSize;
+	TUint32 iCodeSectionAddr;
+	TUint32 iCodeSectionSize;
+	TUint32 iRDataSectionAddr;
+	TUint32 iRDataSectionSize;
+	TUint32 iCRTSectionAddr;
+	TUint32 iCRTSectionSize;
+	TUint32 iExportDataDir;
+
+// stuff for the pe->e32image translator
+	PIMAGE_SECTION_HEADER iSectionHeader[KNumberOfSections];
+	char *iSectionData[KNumberOfSections];
+	TInt iExportDirSize;
+	TInt iCpu;
+	friend class E32ImageFile;
+	friend class E32ImageFile_PE;
+	};
+
+class E32ImageFile_PE : public E32ImageFile
+	{
+public:
+	E32ImageFile_PE();
+	virtual ~E32ImageFile_PE();
+	virtual TBool Translate(const char* aFileName, TUint aDataBase, TBool aAllowDllData, TBool /*aSymLkupEnabled*/);
+	TBool Translate(PEFile &aPEFile);
+	TUint ImportAddressTableOffset();
+	TUint ConstOffset();
+private:
+	TInt DoCodeHeader(PEFile &aPeFile);
+	TInt DoDataHeader(PEFile &aPeFile, TUint aDataBase);
+	TInt CopyCode(char *aPtr, PEFile &aPeFile);
+	TInt CopyData(char *aPtr, PEFile &aPeFile);
+	TInt CopyImportAddrTable(char *aPtr, PEFile &aPeFile);
+	char *CreateImportSection(const PEFile &aPeFile, TInt &aSize);
+	void CreateExportSection(char *aPtr, PEFile &aPeFile);
+
+	void CreateExportDirectory(char *aPtr, PEFile &aPeFile);
+	void FixExportDirectory(TUint *aExportDir, PEFile &aPeFile);
+	void FixRelocs(PEFile &aPeFile, TUint *relocation, TUint *relocsection, TInt aNumberOfRelocs);
+	char *CreateCodeRelocs(TUint *reloc, TUint *relocsection, TInt nrelocs, TInt &aSize);
+	char *CreateDataRelocs(TUint *reloc, TUint *relocsection, TInt nrelocs, TInt &aSize);
+
+	TUint FixAddress(PEFile &aPeFile, TUint va);
+	TUint FixImportThunk(PEFile &aPeFile, TUint va);
+private:
+	PIMAGE_SECTION_HEADER iPeHeader[KNumberOfSections];
+	char *iPeData[KNumberOfSections];
+	TUint iConstOffset;
+	TUint iCrtOffset;
+	};
+
+#endif
--- a/imgtools/imglib/memmap/include/memmap.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/memmap/include/memmap.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,76 +1,76 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#if !defined(__MEMMAP_H__)
-#define __MEMMAP_H__
-
-#include "memmaputils.h"
-
-/** 
-class Memmap
-
-@internalComponent
-@released
-*/
-class Memmap
-{
-private:
-	// Output image file name
-	String iOutFileName;
-	// Map pointer
-	char *iData;
-	// Maximum size of the memory map
-	unsigned long iMaxMapSize;
-	// Start offset of the memory map
-	unsigned long iStartOffset;
-
-	// Flag to fill the map after creating
-	int iFillFlg;
-
-	// Interface to platform utility functions
-	MemmapUtils *iUtils;
-
-	// Fill the memory map
-	int FillMemMap( unsigned char fillVal = 0 );
-public:
-
-	Memmap( int aFillFlg, String aOutputFile );
-	Memmap( int aFillFlg = 1);
-	~Memmap( );
-
-	// Create memory map
-	int CreateMemoryMap( unsigned long aStartOffset = 0, unsigned char aFillVal = 0 );
-	// Close the memory map
-	void CloseMemoryMap( int aCloseFile = 1 );
-	// Dump the memory map into a file
-	void WriteToOutputFile( );
-
-	// Set the output image file name
-	void SetOutputFile( String aOutputFile );
-	// Set the maximum memory map size
-	void SetMaxMapSize( unsigned long aMaxSize );
-	// Get the memory map pointer
-	char* GetMemoryMapPointer( );
-	// Get the map size
-	unsigned long GetMapSize( );
-
-	// Operator [] for accessing memory map
-	char& operator[]( unsigned long aIndex );
-};
-
-#endif //__MEMMAP_H__
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#if !defined(__MEMMAP_H__)
+#define __MEMMAP_H__
+
+#include "memmaputils.h"
+
+/** 
+class Memmap
+
+@internalComponent
+@released
+*/
+class Memmap
+{
+private:
+	// Output image file name
+	string iOutFileName;
+	// Map pointer
+	char *iData;
+	// Maximum size of the memory map
+	unsigned long iMaxMapSize;
+	// Start offset of the memory map
+	unsigned long iStartOffset;
+
+	// Flag to fill the map after creating
+	int iFillFlg;
+
+	// Interface to platform utility functions
+	MemmapUtils *iUtils;
+
+	// Fill the memory map
+	int FillMemMap( unsigned char fillVal = 0 );
+public:
+
+	Memmap( int aFillFlg, const string& aOutputFile );
+	Memmap( int aFillFlg = 1);
+	~Memmap( );
+
+	// Create memory map
+	int CreateMemoryMap( unsigned long aStartOffset = 0, unsigned char aFillVal = 0 );
+	// Close the memory map
+	void CloseMemoryMap( int aCloseFile = 1 );
+	// Dump the memory map into a file
+	void WriteToOutputFile( );
+
+	// Set the output image file name
+	void SetOutputFile(const string& aOutputFile );
+	// Set the maximum memory map size
+	void SetMaxMapSize( unsigned long aMaxSize );
+	// Get the memory map pointer
+	char* GetMemoryMapPointer( );
+	// Get the map size
+	unsigned long GetMapSize( );
+
+	// Operator [] for accessing memory map
+	char& operator[]( unsigned long aIndex );
+};
+
+#endif //__MEMMAP_H__
--- a/imgtools/imglib/memmap/include/memmaputils.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/memmap/include/memmaputils.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,86 +1,83 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#if !defined(__MEMMAPUTILS_H__)
-#define __MEMMAPUTILS_H__
-
-#ifdef WIN32
-#include <windows.h>
-#include <io.h>
-#endif
-
-#include <fcntl.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <stdio.h>
-#include <string>
-#include <fstream>
-
-#include "h_utl.h"
-
-typedef std::string String;
-typedef std::ofstream Ofstream;
-
-const int KStatTrue = 1;
-const int KStatFalse = 0;
-
-/** 
-class MemmapUtils
-
-@internalComponent
-@released
-*/
-class MemmapUtils
-{
-private:
-	// Memory map file descriptor
-	int iHFile;
-
-#ifdef WIN32
-	// Windows specific Memory map object handle
-	HANDLE iHMMFile;
-#endif
-	// Map file name
-	String iMapFileName;
-
-public:
-	MemmapUtils();
-	~MemmapUtils();
-
-	// Generate temporary file name
-	void GetMapFileName(String& aFile);
-
-	// Create the memory map
-	void* OpenMemMapPointer(unsigned long aOffset, unsigned long aSize);
-	// Close the memory map
-	int CloseMemMapPointer(void* aData, unsigned long aSize);
-	// Open the file for memory mapping
-	int OpenMapFile();
-	// Close the memory mapped file
-	void CloseMapFile();
-	// Delete the memory mapped file
-	void DeleteMapFile();
-
-	int IsMapFileOpen();
-
-	// Windows specific file mapping object
-	int CreateFileMapObject(unsigned long aSize);
-	void CloseFileMapObject();
-};
-
-#endif //__MEMMAPUTILS_H__
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#if !defined(__MEMMAPUTILS_H__)
+#define __MEMMAPUTILS_H__
+#include "h_utl.h"
+#ifdef WIN32
+#ifdef _STLP_INTERNAL_WINDOWS_H
+#define __INTERLOCKED_DECLARED
+#endif
+#include <windows.h>
+#include <io.h>
+#endif
+
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stdio.h>
+ 
+
+const int KStatTrue = 1;
+const int KStatFalse = 0;
+
+/** 
+class MemmapUtils
+
+@internalComponent
+@released
+*/
+class MemmapUtils
+{
+private:
+	// Memory map file descriptor
+	int iHFile;
+
+#ifdef WIN32
+	// Windows specific Memory map object handle
+	HANDLE iHMMFile;
+#endif
+	// Map file name
+	string iMapFileName;
+
+public:
+	MemmapUtils();
+	~MemmapUtils();
+
+	// Generate temporary file name
+	void GetMapFileName(string& aFile);
+
+	// Create the memory map
+	void* OpenMemMapPointer(unsigned long aOffset, unsigned long aSize);
+	// Close the memory map
+	int CloseMemMapPointer(void* aData, unsigned long aSize);
+	// Open the file for memory mapping
+	int OpenMapFile();
+	// Close the memory mapped file
+	void CloseMapFile();
+	// Delete the memory mapped file
+	void DeleteMapFile();
+
+	int IsMapFileOpen();
+
+	// Windows specific file mapping object
+	int CreateFileMapObject(unsigned long aSize);
+	void CloseFileMapObject();
+};
+
+#endif //__MEMMAPUTILS_H__
--- a/imgtools/imglib/memmap/source/memmap.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/memmap/source/memmap.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,283 +1,257 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include "memmap.h"
-
-/**
-Constructor: Memmap class
-Initilize the parameters to data members.
-
-@internalComponent
-@released
-
-@param aFillFlg	- Flag to enable the initialisation of memory map
-@param aOutputFile - Name of the output file
-*/
-Memmap::Memmap( int aFillFlg, String aOutputFile )
-: iOutFileName(aOutputFile), iData(0), iMaxMapSize(0), iStartOffset(0), iFillFlg(aFillFlg)
-{
-	iUtils = new MemmapUtils();
-}
-
-/**
-Constructor: Memmap class
-Initilize the parameters to data members.
-
-@internalComponent
-@released
-
-@param aFillFlg	- Flag to enable the initialisation of memory map
-*/
-Memmap::Memmap( int aFillFlg )
-: iData(0), iMaxMapSize(0), iStartOffset(0), iFillFlg(aFillFlg)
-{
-	iUtils = new MemmapUtils();
-}
-
-
-/**
-Destructor: Memmap class
-Deallocates the memory for data members
-
-@internalComponent
-@released
-*/
-Memmap::~Memmap( )
-{
-	if(iData)
-	{
-		CloseMemoryMap();
-	}
-
-	if(iUtils)
-	{
-		delete iUtils;
-	}
-}
-
-/**
-SetOutputFile: To set the output image file
-
-@internalComponent
-@released
-
-@param aOutputFile  - Name of the output image file
-*/
-void Memmap::SetOutputFile( String aOutputFile )
-{
-	iOutFileName = aOutputFile;
-}
-
-/**
-SetMaxMapSize: To set the maximum size of the memory map
-
-@internalComponent
-@released
-
-@param aMaxSize  - Size of the memory map
-*/
-void Memmap::SetMaxMapSize( unsigned long aMaxSize )
-{ 
-	iMaxMapSize = aMaxSize; 
-};
-
-/**
-GetMapSize: To get the size of the memory map
-
-@internalComponent
-@released
-*/
-unsigned long Memmap::GetMapSize( )
-{ 
-	return iMaxMapSize; 
-}
-
-/**
-operator[]: To access the memory map contents
-
-@internalComponent
-@released
-
-@param aIndex - Offset of the memory map location
-*/
-char& Memmap::operator[]( unsigned long aIndex )
-{ 
-	return iData[aIndex]; 
-}
-
-/**
-CreateMemoryMap: 
- Opens the memory map file
- Initialises the map size member
- Create the memory map pointer
- Fill the memory map with the specified value
-
-@internalComponent
-@released
-
-@param aStartOffset - Start offset of the memory map location
-@param aFillVal - Value to be filled in the memory map
-*/
-int Memmap::CreateMemoryMap( unsigned long aStartOffset, unsigned char aFillVal )
-{
-	if((!iMaxMapSize) || (aStartOffset > iMaxMapSize))
-	{
-		return KStatFalse;
-	}
-	else if(iUtils->IsMapFileOpen() && iData)
-	{
-		iStartOffset = aStartOffset;
-		return KStatTrue;
-	}
-
-	if(iUtils->IsMapFileOpen() == KStatFalse)
-	{
-		if(iUtils->OpenMapFile() == KStatFalse)
-		{
-			return KStatFalse;
-		}
-	}
-
-	if(iUtils->CreateFileMapObject(iMaxMapSize) == KStatFalse)
-	{
-		return KStatFalse;
-	}
-
-	iData = (char*)(iUtils->OpenMemMapPointer(0,iMaxMapSize));
-	if( !iData )
-	{
-		return KStatFalse;
-	}
-
-	iStartOffset = aStartOffset;
-	
-	if(iFillFlg)
-	{
-		return FillMemMap( aFillVal );
-	}
-
-	return KStatTrue;
-}
-
-/**
-CloseMemoryMap: Close the memory map and the associated objects
-
-@internalComponent
-@released
-
-@param aCloseFile - Flag to close the memory map file
-*/
-void Memmap::CloseMemoryMap( int aCloseFile )
-{
-	// Close map view pointer
-	if(!iUtils->CloseMemMapPointer((void*)iData, iMaxMapSize))
-	{
-		Print(ELog, "Failed to unmap the memory map object");
-	}
-	iData = 0;
-
-	iUtils->CloseFileMapObject();
-
-	// Close map file
-	if(aCloseFile)
-	{
-		iUtils->CloseMapFile();
-	}
-}
-
-/**
-GetMemoryMapPointer: Get the stating address of the memory map
-
-@internalComponent
-@released
-*/
-char *Memmap::GetMemoryMapPointer( )
-{
-	if(iData)
-		return (iData + iStartOffset);
-
-	return KStatFalse;
-}
-
-/**
-WriteToOutputFile: Writes the memory map contents to the output file
-
-@internalComponent
-@released
-*/
-void Memmap::WriteToOutputFile( )
-{
-	Ofstream ofs;
-
-	if(!iData)
-	{
-		Print(EAlways, "Memory map has not been created");
-	}
-
-	if(iOutFileName.empty())
-	{
-		Print(EAlways, "Output file has not been set");
-		return;
-	}
-
-	ofs.open(((const char*)iOutFileName.data()), std::ios::binary);
-	if(!ofs.is_open())
-	{
-		Print(EAlways, "Cannot open output file %s", (char*)iOutFileName.data());
-		return;
-	}
-
-	ofs.write((const char*)(iData + iStartOffset), (iMaxMapSize - iStartOffset));
-
-	ofs.close();
-
-	return;
-}
-
-/**
-FillMemMap: Fills the memory map with the specified value
-
-@internalComponent
-@released
-
-@param aFillVal - Value to be filled
-*/
-int Memmap::FillMemMap( unsigned char aFillVal )
-{
-	if(iData)
-	{
-		// Fill the value
-		memset(iData, aFillVal, iMaxMapSize);
-
-		// Unmap the file
-		if(iUtils->CloseMemMapPointer((void*)iData, iMaxMapSize) == KStatFalse)
-		{
-			return KStatFalse;
-		}
-
-		// Map it again
-		iData = (char*)(iUtils->OpenMemMapPointer(0,iMaxMapSize));
-		if(!iData)
-		{
-			return KStatFalse;
-		}
-	}
-
-	return KStatTrue;
-}
-
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#include "memmap.h"
+
+/**
+Constructor: Memmap class
+Initilize the parameters to data members.
+
+@internalComponent
+@released
+
+@param aFillFlg	- Flag to enable the initialisation of memory map
+@param aOutputFile - Name of the output file
+*/
+Memmap::Memmap( int aFillFlg, const string& aOutputFile )
+: iOutFileName(aOutputFile), iData(0), iMaxMapSize(0), iStartOffset(0), iFillFlg(aFillFlg) {
+	iUtils = new MemmapUtils();
+}
+
+/**
+Constructor: Memmap class
+Initilize the parameters to data members.
+
+@internalComponent
+@released
+
+@param aFillFlg	- Flag to enable the initialisation of memory map
+*/
+Memmap::Memmap( int aFillFlg )
+: iData(0), iMaxMapSize(0), iStartOffset(0), iFillFlg(aFillFlg) {
+	iUtils = new MemmapUtils();
+}
+
+
+/**
+Destructor: Memmap class
+Deallocates the memory for data members
+
+@internalComponent
+@released
+*/
+Memmap::~Memmap( ) {
+	if(iData) {
+		CloseMemoryMap();
+	}
+
+	if(iUtils) {
+		delete iUtils;
+	}
+}
+
+/**
+SetOutputFile: To set the output image file
+
+@internalComponent
+@released
+
+@param aOutputFile  - Name of the output image file
+*/
+void Memmap::SetOutputFile(const string& aOutputFile ) {
+	iOutFileName = aOutputFile;
+}
+
+/**
+SetMaxMapSize: To set the maximum size of the memory map
+
+@internalComponent
+@released
+
+@param aMaxSize  - Size of the memory map
+*/
+void Memmap::SetMaxMapSize( unsigned long aMaxSize )
+{ 
+	iMaxMapSize = aMaxSize; 
+};
+
+/**
+GetMapSize: To get the size of the memory map
+
+@internalComponent
+@released
+*/
+unsigned long Memmap::GetMapSize( )
+{ 
+	return iMaxMapSize; 
+}
+
+/**
+operator[]: To access the memory map contents
+
+@internalComponent
+@released
+
+@param aIndex - Offset of the memory map location
+*/
+char& Memmap::operator[]( unsigned long aIndex )
+{ 
+	return iData[aIndex]; 
+}
+
+/**
+CreateMemoryMap: 
+Opens the memory map file
+Initialises the map size member
+Create the memory map pointer
+Fill the memory map with the specified value
+
+@internalComponent
+@released
+
+@param aStartOffset - Start offset of the memory map location
+@param aFillVal - Value to be filled in the memory map
+*/
+int Memmap::CreateMemoryMap( unsigned long aStartOffset, unsigned char aFillVal ) {
+	if((!iMaxMapSize) || (aStartOffset > iMaxMapSize)) {
+		return KStatFalse;
+	}
+	else if(iUtils->IsMapFileOpen() && iData) {
+		iStartOffset = aStartOffset;
+		return KStatTrue;
+	}
+
+	if(iUtils->IsMapFileOpen() == KStatFalse) {
+		if(iUtils->OpenMapFile() == KStatFalse) {
+			return KStatFalse;
+		}
+	}
+
+	if(iUtils->CreateFileMapObject(iMaxMapSize) == KStatFalse) {
+		return KStatFalse;
+	}
+
+	iData = (char*)(iUtils->OpenMemMapPointer(0,iMaxMapSize));
+	if( !iData ) {
+		return KStatFalse;
+	}
+
+	iStartOffset = aStartOffset;
+
+	if(iFillFlg) {
+		return FillMemMap( aFillVal );
+	}
+
+	return KStatTrue;
+}
+
+/**
+CloseMemoryMap: Close the memory map and the associated objects
+
+@internalComponent
+@released
+
+@param aCloseFile - Flag to close the memory map file
+*/
+void Memmap::CloseMemoryMap( int aCloseFile ) {
+	// Close map view pointer
+	if(!iUtils->CloseMemMapPointer((void*)iData, iMaxMapSize)) {
+		Print(ELog, "Failed to unmap the memory map object");
+	}
+	iData = 0;
+
+	iUtils->CloseFileMapObject();
+
+	// Close map file
+	if(aCloseFile) {
+		iUtils->CloseMapFile();
+	}
+}
+
+/**
+GetMemoryMapPointer: Get the stating address of the memory map
+
+@internalComponent
+@released
+*/
+char *Memmap::GetMemoryMapPointer( ) {
+	if(iData)
+		return (iData + iStartOffset);
+
+	return KStatFalse;
+}
+
+/**
+WriteToOutputFile: Writes the memory map contents to the output file
+
+@internalComponent
+@released
+*/
+void Memmap::WriteToOutputFile( ) {
+ 
+
+	if(!iData) {
+		Print(EAlways, "Memory map has not been created");
+	}
+
+	if(iOutFileName.empty()) {
+		Print(EAlways, "Output file has not been set");
+		return;
+	}
+
+	ofstream ofs(iOutFileName.c_str(), ios_base::out + ios_base::binary );
+	if(!ofs.is_open()) {
+		Print(EAlways, "Cannot open output file %s", (char*)iOutFileName.data());
+		return;
+	}
+
+	ofs.write((const char*)(iData + iStartOffset), (iMaxMapSize - iStartOffset));
+
+	ofs.close();
+
+	return;
+}
+
+/**
+FillMemMap: Fills the memory map with the specified value
+
+@internalComponent
+@released
+
+@param aFillVal - Value to be filled
+*/
+int Memmap::FillMemMap( unsigned char aFillVal ) {
+	if(iData) {
+		// Fill the value
+		memset(iData, aFillVal, iMaxMapSize);
+
+		// Unmap the file
+		if(iUtils->CloseMemMapPointer((void*)iData, iMaxMapSize) == KStatFalse) {
+			return KStatFalse;
+		}
+
+		// Map it again
+		iData = (char*)(iUtils->OpenMemMapPointer(0,iMaxMapSize));
+		if(!iData) {
+			return KStatFalse;
+		}
+	}
+
+	return KStatTrue;
+}
+
--- a/imgtools/imglib/memmap/source/memmaputils.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/memmap/source/memmaputils.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,237 +1,237 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include "memmaputils.h"
-
-/**
-Constructor: MemmapUtils class
-Initilize the parameters to data members.
-
-@internalComponent
-@released
-*/
-MemmapUtils::MemmapUtils( )
-: iHFile(0)
-{
-#ifdef WIN32
-	iHMMFile = 0;
-#endif
-}
-
-
-/**
-Destructor: MemmapUtils class
-Deallocates the memory for data members
-
-@internalComponent
-@released
-*/
-MemmapUtils::~MemmapUtils( )
-{
-	CloseMapFile();
-
-	DeleteMapFile();
-}
-
-/**
-OpenMemMapPointer: Opens the memory map pointer
-
-@internalComponent
-@released
-
-@param aOffset - Starting offset of the memory map
-@param aSize - Size of the memory map
-*/
-void* MemmapUtils::OpenMemMapPointer(unsigned long aOffset, unsigned long aSize)
-{
-#ifdef WIN32
-	// Create map view pointer
-	return (void*)MapViewOfFile(iHMMFile, FILE_MAP_ALL_ACCESS, 0, aOffset, aSize);
-#else
-	return KStatFalse;
-#endif
-}
-
-/**
-CloseMemMapPointer: Closes the memory map pointer
-
-@internalComponent
-@released
-
-@param aData - Memory map pointer
-@param aSize - Size of the memory map
-*/
-int MemmapUtils::CloseMemMapPointer(void* aData, unsigned long aSize)
-{
-	unsigned long statusFlg = KStatFalse;
-
-	if(aData && iHFile)
-	{
-#ifdef WIN32
-		statusFlg = FlushViewOfFile(aData, aSize);
-		statusFlg &= FlushFileBuffers((HANDLE)_get_osfhandle(iHFile));
-		statusFlg &= UnmapViewOfFile(aData);
-#endif
-	}
-
-	if(statusFlg == (unsigned long)KStatFalse)
-	{
-		return KStatFalse;
-	}
-
-	return KStatTrue;
-}
-
-/**
-OpenMapFile: Opens the file for memory mapping
-
-@internalComponent
-@released
-*/
-int MemmapUtils::OpenMapFile()
-{
-	GetMapFileName(iMapFileName);
-
-	if(iMapFileName.empty())
-	{
-		return KStatFalse;
-	}
-
-#ifdef WIN32
-	iHFile = open((const char*)iMapFileName.data(), (_O_CREAT | _O_BINARY | _O_RDWR));
-#endif
-
-	if((iHFile == (-1)) || (!iHFile))
-	{
-		Print(EAlways, "Cannot open the memory map file %s", (char*)iMapFileName.data());
-		iHFile = 0;
-
-		return KStatFalse;
-	}
-
-	return KStatTrue;
-}
-
-/**
-IsMapFileOpen: Returns the open status of the memory map file
-
-@internalComponent
-@released
-*/
-int MemmapUtils::IsMapFileOpen()
-{
-	return (iHFile) ? KStatTrue : KStatFalse;
-}
-
-/**
-CloseMapFile: Closes the file for memory mapping
-
-@internalComponent
-@released
-*/
-void MemmapUtils::CloseMapFile()
-{
-	if(iHFile)
-	{
-#ifdef WIN32
-		close(iHFile);
-#endif
-		iHFile = 0;
-	}
-}
-
-/**
-DeleteMapFile: Deletes the file for memory mapping
-
-@internalComponent
-@released
-*/
-void MemmapUtils::DeleteMapFile()
-{
-#ifdef WIN32
-	unlink((char*)iMapFileName.data());
-#endif
-}
-
-/**
-CreateFileMapObject: Creates the map file object
-
-@internalComponent
-@released
-
-@param aSize - Size of the memory map
-*/
-int MemmapUtils::CreateFileMapObject(unsigned long aSize)
-{
-#ifdef WIN32
-	// Create memory map object for the given size of the file
-	iHMMFile = CreateFileMapping((HANDLE)_get_osfhandle(iHFile), NULL, 
-				PAGE_READWRITE, 0, aSize, NULL);
-
-	if(!iHMMFile || (iHMMFile == INVALID_HANDLE_VALUE))
-	{
-		return KStatFalse;
-	}
-#endif
-
-	return KStatTrue;
-}
-
-/**
-CloseFileMapObject: Closes the map file object
-
-@internalComponent
-@released
-*/
-void MemmapUtils::CloseFileMapObject()
-{
-#ifdef WIN32
-	if(iHMMFile)
-	{
-		CloseHandle(iHMMFile);
-		iHMMFile = 0;
-	}
-#endif
-}
-
-/**
-GetMapFileName: Generates a temporary file name
-
-@internalComponent
-@released
-
-@param aFile - Returns the name of the temporary file
-*/
-void MemmapUtils::GetMapFileName(String& aFile)
-{
-	char *fileName = 0;
-
-#ifdef WIN32
-	fileName = new char[MAX_PATH];
-
-	if(fileName)
-		GetTempFileName(".", "MMAP", 0, fileName);
-
-	aFile.assign(fileName);
-#endif
-
-	if(fileName)
-		delete[] fileName;
-
-}
-
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#include "memmaputils.h"
+
+/**
+Constructor: MemmapUtils class
+Initilize the parameters to data members.
+
+@internalComponent
+@released
+*/
+MemmapUtils::MemmapUtils( )
+: iHFile(0)
+{
+#ifdef WIN32
+	iHMMFile = 0;
+#endif
+}
+
+
+/**
+Destructor: MemmapUtils class
+Deallocates the memory for data members
+
+@internalComponent
+@released
+*/
+MemmapUtils::~MemmapUtils( )
+{
+	CloseMapFile();
+
+	DeleteMapFile();
+}
+
+/**
+OpenMemMapPointer: Opens the memory map pointer
+
+@internalComponent
+@released
+
+@param aOffset - Starting offset of the memory map
+@param aSize - Size of the memory map
+*/
+void* MemmapUtils::OpenMemMapPointer(unsigned long aOffset, unsigned long aSize)
+{
+#ifdef WIN32
+	// Create map view pointer
+	return (void*)MapViewOfFile(iHMMFile, FILE_MAP_ALL_ACCESS, 0, aOffset, aSize);
+#else
+	return KStatFalse;
+#endif
+}
+
+/**
+CloseMemMapPointer: Closes the memory map pointer
+
+@internalComponent
+@released
+
+@param aData - Memory map pointer
+@param aSize - Size of the memory map
+*/
+int MemmapUtils::CloseMemMapPointer(void* aData, unsigned long aSize)
+{
+	unsigned long statusFlg = KStatFalse;
+
+	if(aData && iHFile)
+	{
+#ifdef WIN32
+		statusFlg = FlushViewOfFile(aData, aSize);
+		statusFlg &= FlushFileBuffers((HANDLE)_get_osfhandle(iHFile));
+		statusFlg &= UnmapViewOfFile(aData);
+#endif
+	}
+
+	if(statusFlg == (unsigned long)KStatFalse)
+	{
+		return KStatFalse;
+	}
+
+	return KStatTrue;
+}
+
+/**
+OpenMapFile: Opens the file for memory mapping
+
+@internalComponent
+@released
+*/
+int MemmapUtils::OpenMapFile()
+{
+	GetMapFileName(iMapFileName);
+
+	if(iMapFileName.empty())
+	{
+		return KStatFalse;
+	}
+
+#ifdef WIN32
+	iHFile = open((const char*)iMapFileName.data(), (_O_CREAT | _O_BINARY | _O_RDWR));
+#endif
+
+	if((iHFile == (-1)) || (!iHFile))
+	{
+		Print(EAlways, "Cannot open the memory map file %s", (char*)iMapFileName.data());
+		iHFile = 0;
+
+		return KStatFalse;
+	}
+
+	return KStatTrue;
+}
+
+/**
+IsMapFileOpen: Returns the open status of the memory map file
+
+@internalComponent
+@released
+*/
+int MemmapUtils::IsMapFileOpen()
+{
+	return (iHFile) ? KStatTrue : KStatFalse;
+}
+
+/**
+CloseMapFile: Closes the file for memory mapping
+
+@internalComponent
+@released
+*/
+void MemmapUtils::CloseMapFile()
+{
+	if(iHFile)
+	{
+#ifdef WIN32
+		close(iHFile);
+#endif
+		iHFile = 0;
+	}
+}
+
+/**
+DeleteMapFile: Deletes the file for memory mapping
+
+@internalComponent
+@released
+*/
+void MemmapUtils::DeleteMapFile()
+{
+#ifdef WIN32
+	unlink((char*)iMapFileName.data());
+#endif
+}
+
+/**
+CreateFileMapObject: Creates the map file object
+
+@internalComponent
+@released
+
+@param aSize - Size of the memory map
+*/
+int MemmapUtils::CreateFileMapObject(unsigned long aSize)
+{
+#ifdef WIN32
+	// Create memory map object for the given size of the file
+	iHMMFile = CreateFileMapping((HANDLE)_get_osfhandle(iHFile), NULL, 
+				PAGE_READWRITE, 0, aSize, NULL);
+
+	if(!iHMMFile || (iHMMFile == INVALID_HANDLE_VALUE))
+	{
+		return KStatFalse;
+	}
+#endif
+
+	return KStatTrue;
+}
+
+/**
+CloseFileMapObject: Closes the map file object
+
+@internalComponent
+@released
+*/
+void MemmapUtils::CloseFileMapObject()
+{
+#ifdef WIN32
+	if(iHMMFile)
+	{
+		CloseHandle(iHMMFile);
+		iHMMFile = 0;
+	}
+#endif
+}
+
+/**
+GetMapFileName: Generates a temporary file name
+
+@internalComponent
+@released
+
+@param aFile - Returns the name of the temporary file
+*/
+void MemmapUtils::GetMapFileName(string& aFile)
+{
+	char *fileName = 0;
+
+#ifdef WIN32
+	fileName = new char[MAX_PATH];
+
+	if(fileName)
+		GetTempFileName(".", "MMAP", 0, fileName);
+
+	aFile.assign(fileName);
+#endif
+
+	if(fileName)
+		delete[] fileName;
+
+}
+
--- a/imgtools/imglib/parameterfileprocessor/include/parameterfileprocessor.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/parameterfileprocessor/include/parameterfileprocessor.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,65 +1,64 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Class for processing parameter-file.
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef PARAMETERFILEPROCESSOR_H
-#define PARAMETERFILEPROCESSOR_H
-
-#include<iostream>
-#include<string>
-#include<vector>
-#include<fstream>
-
-typedef std::string String;
-typedef std::vector<String> VectorOfStrings;
-typedef std::ifstream FileInputStream;
-
-/**
-Class CParameterFileProcessor for processing parameter-file
-
-@internalComponent
-@released
-*/
-
-class CParameterFileProcessor
-{
-	FileInputStream iParamFile;	 	
-	String iParamFileName;		 // Parameter-file name
-	VectorOfStrings iParameters; // Parameters read from parameter-file
-	unsigned int iNoOfArguments; // Number of parameters present in the parameter-file.
-	char **iParamFileArgs; // Pointer to 2D character array containing the parameters 
-						   // read from parameter-file.	 
-							   
-public:			
-	CParameterFileProcessor(String aParamFileName);	
-	bool ParameterFileProcessor();	
-	unsigned int GetNoOfArguments() const;
-	char** GetParameters() const;
-	~CParameterFileProcessor();
-
-private:
-	bool OpenFile();
-	bool SplitLine(String& aLine);
-	bool SetNoOfArguments();
-	void SetParameters();
-	void CloseFile();
-};	
-
-#endif //PARAMETERFILEPROCESSOR_H
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Class for processing parameter-file.
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef PARAMETERFILEPROCESSOR_H
+#define PARAMETERFILEPROCESSOR_H
+
+#include<iostream>
+#include<string>
+#include<vector>
+#include<fstream>
+
+using namespace std ;
+typedef vector<string> VectorOfStrings; 
+
+/**
+Class CParameterFileProcessor for processing parameter-file
+
+@internalComponent
+@released
+*/
+
+class CParameterFileProcessor
+{
+	ifstream iParamFile;	 	
+	string iParamFileName;		 // Parameter-file name
+	VectorOfStrings iParameters; // Parameters read from parameter-file
+	unsigned int iNoOfArguments; // Number of parameters present in the parameter-file.
+	char **iParamFileArgs; // Pointer to 2D character array containing the parameters 
+						   // read from parameter-file.	 
+							   
+public:			
+	CParameterFileProcessor(const string& aParamFileName);	
+	bool ParameterFileProcessor();	
+	unsigned int GetNoOfArguments() const;
+	char** GetParameters() const;
+	~CParameterFileProcessor();
+
+private:
+	bool OpenFile();
+	bool SplitLine(string& aLine);
+	bool SetNoOfArguments();
+	void SetParameters();
+	void CloseFile();
+};	
+
+#endif //PARAMETERFILEPROCESSOR_H
--- a/imgtools/imglib/parameterfileprocessor/source/parameterfileprocessor.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/parameterfileprocessor/source/parameterfileprocessor.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,262 +1,262 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Class for processing parameter-file.
-* @internalComponent
-* @released
-*
-*/
-
-
-
-#include "parameterfileprocessor.h"
-
-
-/**
-Constructor of CParameterFileProcessor class
-
-@param aParamFileName parameter-file name
-
-@internalComponent
-@released
-*/
-CParameterFileProcessor::CParameterFileProcessor(String aParamFileName):
-												 iParamFileName(aParamFileName),iNoOfArguments(0),
-												 iParamFileArgs(NULL)
-{
-}	
-
-
-/**
-Function to open parameter-file
-
-@internalComponent
-@released
-
-@return True/False depending on the status of parameter-file open statement.
-*/
-bool CParameterFileProcessor::OpenFile()
-{
-	
-	iParamFile.open(iParamFileName.data(),std::ios::binary);
-	if (iParamFile.is_open())
-		return true;
-	else
-	{		
-		std::cout<<"Error: Couldn't open parameter-file for reading:"<<iParamFileName.c_str()<<"\n";
-		return false;
-	}
-}
-
-
-/**
-Function to parse the parameter-file
-
-@internalComponent
-@released
-
-@return True/False depending on the status of parameter-file parsing.
-*/
-bool CParameterFileProcessor::ParameterFileProcessor()
-{
-	if(OpenFile())
-	{
-		while(!iParamFile.eof())
-		{
-			// Read the parameter-file line by line.
-			String line;
-			std::getline(iParamFile,line);
-
-			// Read the line till the occurence of character ';' or EOL.
-			unsigned int pos = line.find_first_of(";\r\n");
-			if (pos != std::string::npos)
-				line = line.substr(0,pos);
-			
-			// Split the line if multiple parameters are provided
-			// in a single line.
-			if(!SplitLine(line))
-				return false;
-		}		
-		
-		if (SetNoOfArguments() == false)
-		{
-			return false;
-		}
-		
-		SetParameters();
-		
-		// Close parameter-file 
-		CloseFile();
-
-		return true;		
-	}
-	else
-		return false;				
-}
-
-
-/**
-Function to split line of paramfile-file 
-
-@param aLine parameter-file line
-
-@internalComponent
-@released
-
-@return True/False depending on the status of spliting.
-*/
-bool CParameterFileProcessor::SplitLine(String& aLine)
-{
-	unsigned int startPos=0;
-	unsigned int endPos=0; 	
-
-	// Segregate parameters based on white-space or tabs.
-	startPos= aLine.find_first_not_of(" \t",endPos);
-	while(startPos != std::string::npos)
-	{		
-		endPos= aLine.find_first_of(" \t",startPos);
-		String paramStr= aLine.substr(startPos,endPos-startPos);
-
-		unsigned int position= aLine.find_first_of("\"",startPos);
-
-		// If the parameter contains double quotes('"') then also include the spaces(if provided)
-		// within the quotes.		
-		if((position!=std::string::npos) && position<=endPos)
-		{
-			endPos= aLine.find_first_of("\"",position+1);
-			if(endPos!= std::string::npos)
-			{				
-				endPos= aLine.find_first_of(" \t",endPos+1);
-				if(endPos != std::string::npos)
-				{
-					paramStr= aLine.substr(startPos,endPos-startPos);
-				}
-				
-				// Remove '"' from parameter
-				for(unsigned int count =0;count<paramStr.size();count++)
-				{
-					if (paramStr.at(count) == '"')
-					{
-						paramStr.erase(count,count+1);
-					}
-				}
-			}
-			// Generate error message if enclosing quotes are not found.
-			else
-			{
-				std::cout<<"Error while parsing parameter-file"<<iParamFileName.c_str()<<". Closing \"\"\" not found\n";
-				return false;				
-			}
-		}
-
-		iParameters.push_back(paramStr);
-		startPos= aLine.find_first_not_of(" \t",endPos);
-	}	
-	return true;
-}
-
-
-/**
-Function to set number of parameters read.
-
-@return false if no parameters are specified in parameter-file, else true
-@internalComponent
-@released
-*/
-bool CParameterFileProcessor::SetNoOfArguments()
-{
-	unsigned int noOfArguements = iParameters.size();	
-	if (!noOfArguements)
-	{
-		std::cout<<"Warning: No parameters specified in paramer-file:"<<iParamFileName.data()<<"\n";
-		return false;
-	}
-	iNoOfArguments = noOfArguements+1;
-	return true;
-}
-
-
-/**
-Function to set the value of parameters read in the 
-form of 2D char array.
-
-@internalComponent
-@released
-*/
-void CParameterFileProcessor::SetParameters()
-{
-	// Store the parameters read in a 2D array of characters
-	unsigned int paramSize = iParameters.size();
-	iParamFileArgs=new char*[paramSize+1];			  
-	
-	for (unsigned int count=1; count<=paramSize; count++)
-	{
-		String param = iParameters.at(count-1);
-		*(iParamFileArgs+count) = new char[param.size()+1];
-		strcpy(*(iParamFileArgs+count),param.c_str());
-	}
-}
-
-
-/**
-Function to close parameter-file
-
-@internalComponent
-@released
-*/
-void CParameterFileProcessor::CloseFile()
-{
-	iParamFile.close();	
-}
-
-
-/**
-Function to return number of parameters read from parameter-file
-
-@internalComponent
-@released
-
-@return iNoOfArguments - Number of parameters read from parameter-file
-*/
-unsigned int CParameterFileProcessor::GetNoOfArguments() const
-{
-	return iNoOfArguments;
-}
-
-
-/**
-Function to return parameters read from parameter-file
-
-@internalComponent
-@released
-
-@return iParamFileArgs - Parameters read from parameter-file
-*/
-char** CParameterFileProcessor::GetParameters() const
-{
-	return iParamFileArgs;
-}
-
-
-/**
-Destructor of CParameterFileProcessor class
-
-@internalComponent
-@released
-*/
-CParameterFileProcessor::~CParameterFileProcessor()
-{
-	for (unsigned int count=1;count<iNoOfArguments;count++)
-		delete[] *(iParamFileArgs+count);	
-}
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Class for processing parameter-file.
+* @internalComponent
+* @released
+*
+*/
+
+
+
+#include "parameterfileprocessor.h"
+
+
+/**
+Constructor of CParameterFileProcessor class
+
+@param aParamFileName parameter-file name
+
+@internalComponent
+@released
+*/
+CParameterFileProcessor::CParameterFileProcessor(const string& aParamFileName):
+												 iParamFileName(aParamFileName),iNoOfArguments(0),
+												 iParamFileArgs(NULL)
+{
+}	
+
+
+/**
+Function to open parameter-file
+
+@internalComponent
+@released
+
+@return True/False depending on the status of parameter-file open statement.
+*/
+bool CParameterFileProcessor::OpenFile()
+{
+	
+	iParamFile.open(iParamFileName.data(),ios_base::binary);
+	if (iParamFile.is_open())
+		return true;
+	else
+	{		
+		cout<<"Error: Couldn't open parameter-file for reading:"<<iParamFileName.c_str()<<"\n";
+		return false;
+	}
+}
+
+
+/**
+Function to parse the parameter-file
+
+@internalComponent
+@released
+
+@return True/False depending on the status of parameter-file parsing.
+*/
+bool CParameterFileProcessor::ParameterFileProcessor()
+{
+	if(OpenFile())
+	{
+		while(!iParamFile.eof())
+		{
+			// Read the parameter-file line by line.
+			string line;
+			getline(iParamFile,line);
+
+			// Read the line till the occurence of character ';' or EOL.
+			unsigned int pos = line.find_first_of(";\r\n");
+			if (pos != string::npos)
+				line = line.substr(0,pos);
+			
+			// Split the line if multiple parameters are provided
+			// in a single line.
+			if(!SplitLine(line))
+				return false;
+		}		
+		
+		if (SetNoOfArguments() == false)
+		{
+			return false;
+		}
+		
+		SetParameters();
+		
+		// Close parameter-file 
+		CloseFile();
+
+		return true;		
+	}
+	else
+		return false;				
+}
+
+
+/**
+Function to split line of paramfile-file 
+
+@param aLine parameter-file line
+
+@internalComponent
+@released
+
+@return True/False depending on the status of spliting.
+*/
+bool CParameterFileProcessor::SplitLine(string& aLine)
+{
+	unsigned int startPos=0;
+	unsigned int endPos=0; 	
+
+	// Segregate parameters based on white-space or tabs.
+	startPos= aLine.find_first_not_of(" \t",endPos);
+	while(startPos != string::npos)
+	{		
+		endPos= aLine.find_first_of(" \t",startPos);
+		string paramStr= aLine.substr(startPos,endPos-startPos);
+
+		unsigned int position= aLine.find_first_of("\"",startPos);
+
+		// If the parameter contains double quotes('"') then also include the spaces(if provided)
+		// within the quotes.		
+		if((position!=string::npos) && position<=endPos)
+		{
+			endPos= aLine.find_first_of("\"",position+1);
+			if(endPos!= string::npos)
+			{				
+				endPos= aLine.find_first_of(" \t",endPos+1);
+				if(endPos != string::npos)
+				{
+					paramStr= aLine.substr(startPos,endPos-startPos);
+				}
+				
+				// Remove '"' from parameter
+				for(unsigned int count =0;count<paramStr.size();count++)
+				{
+					if (paramStr.at(count) == '"')
+					{
+						paramStr.erase(count,count+1);
+					}
+				}
+			}
+			// Generate error message if enclosing quotes are not found.
+			else
+			{
+				cout<<"Error while parsing parameter-file"<<iParamFileName.c_str()<<". Closing \"\"\" not found\n";
+				return false;				
+			}
+		}
+
+		iParameters.push_back(paramStr);
+		startPos= aLine.find_first_not_of(" \t",endPos);
+	}	
+	return true;
+}
+
+
+/**
+Function to set number of parameters read.
+
+@return false if no parameters are specified in parameter-file, else true
+@internalComponent
+@released
+*/
+bool CParameterFileProcessor::SetNoOfArguments()
+{
+	unsigned int noOfArguements = iParameters.size();	
+	if (!noOfArguements)
+	{
+		cout<<"Warning: No parameters specified in paramer-file:"<<iParamFileName.data()<<"\n";
+		return false;
+	}
+	iNoOfArguments = noOfArguements+1;
+	return true;
+}
+
+
+/**
+Function to set the value of parameters read in the 
+form of 2D char array.
+
+@internalComponent
+@released
+*/
+void CParameterFileProcessor::SetParameters()
+{
+	// Store the parameters read in a 2D array of characters
+	unsigned int paramSize = iParameters.size();
+	iParamFileArgs=new char*[paramSize+1];			  
+	
+	for (unsigned int count=1; count<=paramSize; count++)
+	{
+		string param = iParameters.at(count-1);
+		*(iParamFileArgs+count) = new char[param.size()+1];
+		strcpy(*(iParamFileArgs+count),param.c_str());
+	}
+}
+
+
+/**
+Function to close parameter-file
+
+@internalComponent
+@released
+*/
+void CParameterFileProcessor::CloseFile()
+{
+	iParamFile.close();	
+}
+
+
+/**
+Function to return number of parameters read from parameter-file
+
+@internalComponent
+@released
+
+@return iNoOfArguments - Number of parameters read from parameter-file
+*/
+unsigned int CParameterFileProcessor::GetNoOfArguments() const
+{
+	return iNoOfArguments;
+}
+
+
+/**
+Function to return parameters read from parameter-file
+
+@internalComponent
+@released
+
+@return iParamFileArgs - Parameters read from parameter-file
+*/
+char** CParameterFileProcessor::GetParameters() const
+{
+	return iParamFileArgs;
+}
+
+
+/**
+Destructor of CParameterFileProcessor class
+
+@internalComponent
+@released
+*/
+CParameterFileProcessor::~CParameterFileProcessor()
+{
+	for (unsigned int count=1;count<iNoOfArguments;count++)
+		delete[] *(iParamFileArgs+count);	
+}
--- a/imgtools/imglib/patchdataprocessor/include/patchdataprocessor.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/patchdataprocessor/include/patchdataprocessor.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,98 +1,90 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Class for Patching Exported Data 
-* @internalComponents
-* @released
-*
-*/
-
-
-#ifndef PATCHDATAPROCESSOR_H
-#define PATCHDATAPROCESSOR_H
-
-#ifdef _MSC_VER
-	#pragma warning(disable: 4786) // identifier was truncated to '255' characters in the debug information
-#endif
-
-#include <e32def.h>
-
-#ifdef _L
-#undef _L
-#endif
-
-#include <iostream>
-#include <vector>
-#include <map>
-#include <sstream>
-
-typedef std::string String;
-typedef std::vector<String> StringVector;
-typedef std::vector<StringVector> VectorOfStringVector;
-typedef std::map<String,String> MapOfString;
-typedef std::map<String,String>::iterator MapOfStringIterator;
-typedef std::ostringstream OutputStringStream; 
-
-/**
-Class for patching exported data.
-
-@internalComponent
-@released
-*/
-class CPatchDataProcessor
-{
-	VectorOfStringVector iPatchDataStatements; // Vector of string containing patchdata statements.
-	MapOfString iRenamedFileMap; // Map containing information of renamed files. 
-
-public:	
-	void AddPatchDataStatement(StringVector aPatchDataStatement);
-	void AddToRenamedFileMap(String aCurrentName, String aNewName);
-	VectorOfStringVector GetPatchDataStatements() const;
-	MapOfString GetRenamedFileMap() const;		
-};
-
-
-class TRomNode;
-
-/**
-Class to form a patchdata linked-list contatining symbol size, address/ordinal 
-new value to be patched.
-
-@internalComponent
-@released
-*/
-class DllDataEntry
-{
-	
-public:
-	DllDataEntry(TUint32 aSize, TUint32 aNewValue) :
-				 iSize(aSize), iDataAddress((TUint32)-1), iOrdinal((TUint32)-1), iOffset(0),
-				 iNewValue(aNewValue), iRomNode(NULL), iNextDllEntry(NULL)
-	{
-	}
-
-
-	TUint32			iSize;
-	TLinAddr		iDataAddress;
-	TUint32			iOrdinal;
-	TUint32			iOffset;
-	TUint32			iNewValue;
-	TRomNode*		iRomNode;
-	DllDataEntry*	iNextDllEntry;
- 
- 	void			AddDllDataEntry(DllDataEntry*);
-	DllDataEntry*	NextDllDataEntry() const;
-};
-
-#endif //PATCHDATAPROCESSOR_H
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Class for Patching Exported Data 
+* @internalComponents
+* @released
+*
+*/
+
+
+#ifndef PATCHDATAPROCESSOR_H
+#define PATCHDATAPROCESSOR_H
+
+#include <e32def.h>
+#include <string> 
+#include <iostream>
+#include <vector>
+#include <map>
+#include <sstream>
+
+
+using namespace std;
+typedef vector<string> StringVector;
+typedef vector<StringVector> VectorOfStringVector;
+typedef map<string,string> MapOfString;
+typedef map<string,string>::iterator MapOfStringIterator; 
+
+/**
+Class for patching exported data.
+
+@internalComponent
+@released
+*/
+class CPatchDataProcessor
+{
+	VectorOfStringVector iPatchDataStatements; // Vector of string containing patchdata statements.
+	MapOfString iRenamedFileMap; // Map containing information of renamed files. 
+
+public:	
+	void AddPatchDataStatement(StringVector aPatchDataStatement);
+	void AddToRenamedFileMap(string aCurrentName, string aNewName);
+	VectorOfStringVector GetPatchDataStatements() const;
+	MapOfString GetRenamedFileMap() const;		
+};
+
+
+class TRomNode;
+
+/**
+Class to form a patchdata linked-list contatining symbol size, address/ordinal 
+new value to be patched.
+
+@internalComponent
+@released
+*/
+class DllDataEntry
+{
+	
+public:
+	DllDataEntry(TUint32 aSize, TUint32 aNewValue) :
+				 iSize(aSize), iDataAddress((TUint32)-1), iOrdinal((TUint32)-1), iOffset(0),
+				 iNewValue(aNewValue), iRomNode(NULL), iNextDllEntry(NULL)
+	{
+	}
+
+
+	TUint32			iSize;
+	TLinAddr		iDataAddress;
+	TUint32			iOrdinal;
+	TUint32			iOffset;
+	TUint32			iNewValue;
+	TRomNode*		iRomNode;
+	DllDataEntry*	iNextDllEntry;
+ 
+ 	void			AddDllDataEntry(DllDataEntry*);
+	DllDataEntry*	NextDllDataEntry() const;
+};
+
+#endif //PATCHDATAPROCESSOR_H
--- a/imgtools/imglib/patchdataprocessor/source/patchdataprocessor.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/imglib/patchdataprocessor/source/patchdataprocessor.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,107 +1,107 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Class for Patching Exported Data 
-* @internalComponent
-* @released
-*
-*/
-
-#include "patchdataprocessor.h"
-
-/**
-Add patchdata statement to the vector containing all patchdata statements
-
-@param aPatchDataStatement new patchdata statement.
-
-@internalComponent
-@released
-*/
-void CPatchDataProcessor::AddPatchDataStatement(StringVector aPatchDataStatement)
-{
-	iPatchDataStatements.push_back(aPatchDataStatement);
-}
-
-/**
-Get the vector containing patchdata statements 
-
-@return iPatchDataStatements list of patchdata statements.
-
-@internalComponent
-@released
-*/
-VectorOfStringVector CPatchDataProcessor::GetPatchDataStatements(void) const
-{
-	return iPatchDataStatements;
-}
-
-/**
-Add a new entry to renamed file map.
-
-@param aCurrentName current name of the file.
-@param aNewName new name of the file.
-
-@internalComponent
-@released
-*/
-void CPatchDataProcessor::AddToRenamedFileMap(String aCurrentName, String aNewName)
-{
-	iRenamedFileMap[aCurrentName]=aNewName;
-}
-
-/**
-Get renamed file map.
-
-@return iRenamedFileMap renamed file map
-
-@internalComponent
-@released
-*/
-MapOfString CPatchDataProcessor::GetRenamedFileMap() const
-{
-	return iRenamedFileMap;
-}
-
-/**
-Add link to the patchdata linked list
-
-@param aDllData pointer to a patchdata link.
-
-@internalComponent
-@released
-*/
-void DllDataEntry::AddDllDataEntry(DllDataEntry *aDllData)
-{
-	iNextDllEntry=aDllData;	
-}
-
-/**
-Get the next node in the patchdata linked list
-
-@return  pointer to the next node.
-
-@internalComponent
-@released
-*/
-DllDataEntry*	DllDataEntry::NextDllDataEntry() const
-{
-	if (iNextDllEntry)
-	{
-		return iNextDllEntry;
-	}
-	else
-	{
-		return NULL;
-	}
-}
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Class for Patching Exported Data 
+* @internalComponent
+* @released
+*
+*/
+
+#include "patchdataprocessor.h"
+
+/**
+Add patchdata statement to the vector containing all patchdata statements
+
+@param aPatchDataStatement new patchdata statement.
+
+@internalComponent
+@released
+*/
+void CPatchDataProcessor::AddPatchDataStatement(StringVector aPatchDataStatement)
+{
+	iPatchDataStatements.push_back(aPatchDataStatement);
+}
+
+/**
+Get the vector containing patchdata statements 
+
+@return iPatchDataStatements list of patchdata statements.
+
+@internalComponent
+@released
+*/
+VectorOfStringVector CPatchDataProcessor::GetPatchDataStatements(void) const
+{
+	return iPatchDataStatements;
+}
+
+/**
+Add a new entry to renamed file map.
+
+@param aCurrentName current name of the file.
+@param aNewName new name of the file.
+
+@internalComponent
+@released
+*/
+void CPatchDataProcessor::AddToRenamedFileMap(string aCurrentName, string aNewName)
+{
+	iRenamedFileMap[aCurrentName]=aNewName;
+}
+
+/**
+Get renamed file map.
+
+@return iRenamedFileMap renamed file map
+
+@internalComponent
+@released
+*/
+MapOfString CPatchDataProcessor::GetRenamedFileMap() const
+{
+	return iRenamedFileMap;
+}
+
+/**
+Add link to the patchdata linked list
+
+@param aDllData pointer to a patchdata link.
+
+@internalComponent
+@released
+*/
+void DllDataEntry::AddDllDataEntry(DllDataEntry *aDllData)
+{
+	iNextDllEntry=aDllData;	
+}
+
+/**
+Get the next node in the patchdata linked list
+
+@return  pointer to the next node.
+
+@internalComponent
+@released
+*/
+DllDataEntry*	DllDataEntry::NextDllDataEntry() const
+{
+	if (iNextDllEntry)
+	{
+		return iNextDllEntry;
+	}
+	else
+	{
+		return NULL;
+	}
+}
--- a/imgtools/romtools/group/BLD.INF	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/group/BLD.INF	Tue Jun 29 14:52:54 2010 +0800
@@ -1,42 +1,51 @@
-/*
-* Copyright (c) 1999-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-PRJ_PLATFORMS
-TOOLS2
-
-PRJ_EXPORTS
-
-../maksym/fixupsym.bat              /epoc32/tools/fixupsym.bat
-../maksym/hpsym.bat                 /epoc32/tools/hpsym.bat
-../maksym/maksym.bat                /epoc32/tools/maksym.bat
-../maksym/maksymrofs.bat            /epoc32/tools/maksymrofs.bat
-../maksym/fixupsym.pl               /epoc32/tools/fixupsym.pl
-../maksym/hpsym.pl                  /epoc32/tools/hpsym.pl
-../maksym/maksym.pl                 /epoc32/tools/maksym.pl
-../maksym/maksymrofs.pl             /epoc32/tools/maksymrofs.pl
-
-../rombuild/checkstubs.pl		/epoc32/rom/tools/checkstubs.pl
-../rombuild/addextension.pl		/epoc32/rom/tools/addextension.pl
-
-PRJ_MMPFILES 
-readimage 
-../rofsbuild/rofsbuild.mmp
-../rombuild/rombuild.mmp 
-
-PRJ_TESTMMPFILES
-../rombuild/r_t_areaset
+/*
+* Copyright (c) 1999-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+PRJ_PLATFORMS
+TOOLS2
+
+PRJ_EXPORTS
+
+#ifdef TOOLS2_LINUX
+../maksym/fixupsym              /epoc32/tools/fixupsym
+../maksym/hpsym                 /epoc32/tools/hpsym
+../maksym/maksym                /epoc32/tools/maksym
+../maksym/maksymrofs            /epoc32/tools/maksymrofs
+#else
+../maksym/fixupsym.bat              /epoc32/tools/fixupsym.bat
+../maksym/hpsym.bat                 /epoc32/tools/hpsym.bat
+../maksym/maksym.bat                /epoc32/tools/maksym.bat
+../maksym/maksymrofs.bat            /epoc32/tools/maksymrofs.bat
+#endif
+
+../maksym/fixupsym.pl               /epoc32/tools/fixupsym.pl
+../maksym/hpsym.pl                  /epoc32/tools/hpsym.pl
+../maksym/maksym.pl                 /epoc32/tools/maksym.pl
+../maksym/maksymrofs.pl             /epoc32/tools/maksymrofs.pl
+
+../rombuild/checkstubs.pl		/epoc32/rom/tools/checkstubs.pl
+../rombuild/addextension.pl		/epoc32/rom/tools/addextension.pl
+
+PRJ_MMPFILES 
+readimage 
+../rofsbuild/rofsbuild.mmp
+../rombuild/rombuild.mmp 
+
+PRJ_TESTMMPFILES
+../rombuild/r_t_areaset
+ 
--- a/imgtools/romtools/group/readimage.mmp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/group/readimage.mmp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,61 +1,64 @@
-/*
-* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-macro		__SUPPORT_ELF_FILES__
-
-target			readimage.exe
-targettype		exe
-sourcepath	..\readimage\src
-source			common.cpp e32_image_reader.cpp image_handler.cpp image_reader.cpp rofs_image_reader.cpp rom_image_reader.cpp
-sourcepath	..\..\imglib\e32uid
-source			e32uid.cpp
-sourcepath	..\..\imglib\host
-source			h_file.cpp h_mem.cpp h_utl.cpp
-userinclude	..\readimage\inc ..\rofsbuild ..\rombuild
-sourcepath	..\rofsbuild
-source			r_build.cpp r_coreimage.cpp 
-sourcepath	..\rombuild
-source			r_global.cpp
-sourcepath	..\..\imglib\e32image
-source			e32image.cpp
-sourcepath	..\..\imglib\e32image\deflate
-source			decode.cpp encode.cpp deflate.cpp inflate.cpp panic.cpp compress.cpp
-
-sourcepath	..\..\imglib\compress
-source			pagedcompress.cpp byte_pair.cpp
-
-sourcepath	..\..\imglib\patchdataprocessor\source
-source			patchdataprocessor.cpp
-
-userinclude     ..\..\imglib\compress 
-userinclude		..\..\imglib\patchdataprocessor\include
-userinclude		..\..\sisutils\inc
-userinclude   ..\..\imglib\boostlibrary
-
-USERINCLUDE ..\..\imglib\inc
-OS_LAYER_SYSTEMINCLUDE_SYMBIAN
-
-staticlibrary 	sisutils
-#ifdef TOOLS2_LINUX
-STATICLIBRARY   boost_thread-mgw34-mt-1_39_linux
-OPTION    GCC -pthread -O2 -Wno-uninitialized
-#else
-STATICLIBRARY   boost_thread-mgw34-mt-1_39_win32
-OPTION    GCC -mthreads -O2 -Wno-uninitialized
-#endif
-VENDORID 0x70000001
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+macro		__SUPPORT_ELF_FILES__
+macro		_STLP_USE_STATIC_LIB
+target			readimage.exe
+targettype		exe
+sourcepath	..\readimage\src
+source			common.cpp e32_image_reader.cpp image_handler.cpp image_reader.cpp rofs_image_reader.cpp rom_image_reader.cpp
+sourcepath	..\..\imglib\e32uid
+source			e32uid.cpp
+sourcepath	..\..\imglib\host
+source			h_file.cpp h_mem.cpp h_utl.cpp
+userinclude	..\readimage\inc ..\rofsbuild ..\rombuild
+sourcepath	..\rofsbuild
+source			r_build.cpp r_coreimage.cpp 
+SOURCEPATH ../rofsbuild/src/cache
+SOURCE cachemanager.cpp cacheexception.cpp cache.cpp cacheablelist.cpp cachevalidator.cpp cachegenerator.cpp cacheentry.cpp
+sourcepath	..\rombuild
+source			r_global.cpp
+sourcepath	..\..\imglib\e32image
+source			e32image.cpp
+sourcepath	..\..\imglib\e32image\deflate
+source			decode.cpp encode.cpp deflate.cpp inflate.cpp panic.cpp compress.cpp
+
+sourcepath	..\..\imglib\compress
+source			pagedcompress.cpp byte_pair.cpp
+
+sourcepath	..\..\imglib\patchdataprocessor\source
+source			patchdataprocessor.cpp
+
+userinclude     ..\..\imglib\compress 
+userinclude		..\..\imglib\patchdataprocessor\include
+userinclude		..\..\sisutils\inc
+USERINCLUDE   ../rofsbuild/inc
+userinclude   ..\..\imglib\boostlibrary
+USERINCLUDE   ../../imglib/boostlibrary/boost
+
+USERINCLUDE ..\..\imglib\inc
+OS_LAYER_SYSTEMINCLUDE_SYMBIAN
+STATICLIBRARY   boost_thread-1.39 boost_filesystem-1.39 sisutils
+
+#ifdef TOOLS2_LINUX
+STATICLIBRARY	boost_system-1.39
+OPTION    GCC -pthread -O2 -Wno-uninitialized -fno-strict-aliasing
+#else
+OPTION    GCC -mthreads -O2 -Wno-uninitialized
+#endif
+
+VENDORID 0x70000001
--- a/imgtools/romtools/group/release.txt	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/group/release.txt	Tue Jun 29 14:52:54 2010 +0800
@@ -1,3680 +1,3841 @@
-Version 2.14.0 (rombuild)
-===============
-Made by Zhi Dou 26/10/2009
-
-1. RM-RIM406-1263: BU: Visual ROM Layout
-
-Version 2.13.4 (rombuild)
-===============
-Made by Zhi Dou 19/10/2009
-
-1. Minor change for copyright from SPL to EPL.
-
-Version 2.6.5 (rofsbuild)
-===============
-Made by Zhi Dou 19/10/2009
-
-1. Minor change for copyright from SPL to EPL.
-
-Version 2.6.4 (rofsbuild)
-===============
-Made by Zhi Dou 14/10/2009
-
-1. DPDEF142516 rofsbuild somtimes crash when building rofs image for tube with many times.
-
-Version 2.13.3 (rombuild)
-===============
-Made by Ross Qin 14/09/2009
-
-1. DPDEF141843 Coverity defects about Resource Leak and Delete Array. 
-
-Version 2.6.3 (rofsbuild)
-===============
-Made by Ross Qin 14/09/2009
-
-1. DPDEF141843 Coverity defects about Resource Leak and Delete Array. 
-
-Version 2.6.2 (rofsbuild)
-===============
-Made by Ross Qin 10/09/2009
-
-1.DPDEF141840 ROFSBUILD is not processing "-s<log|screen|both>" and "-loglevel<012>" correctly  
-
-Version 2.6.1 (rofsbuild)
-===============
-Made by Ross Qin 07/09/2009
-
-1.DPDEF141838 rofsbuild behaves differently from rombuild when invalid numbers given 
-
-Version 2.13.2 (rombuild)
-===============
-Made by Ross Qin 07/09/2009
-
-1.DPDEF141838 rofsbuild behaves differently from rombuild when invalid numbers given 
-2.DPDEF141291 Update unpaged memory overflow error message of rombuild.exe
-
-Version 2.13.1 (rombuild)
-===============
-Made by Ross Qin 03/09/2009
-
-1.DPDEF141685 Low error privilege for Kernel/variant/extension links to non-extension
-
-Version 2.6.0 (rofsbuild)
-===============
-Made by Ross Qin 26/08/2009
-
-1. REQ11940 Parallel processing - ROFSBUILD
-
-Version 2.13.0 (rombuild)
-===============
-Made by Ross Qin 26/08/2009
-
-1. REQ12560 Parallelise Content Preparation - ROMBUILD
-2. REQ13102 Parallelise Image Generation - ROMBUILD
-
-Version 2.1.603 (readimage)
-===============
-Made by Ross Qin 24/08/2009
-
-1. DPDEF141624 Coverity reports delete array in C++ without [] and deadcode.
-
-Version 2.12.2 (rombuild)
-===============
-Made by Ross Qin 24/08/2009
-
-1. DPDEF141624 Coverity reports delete array in C++ without [] and deadcode.
-
-Version 2.5.3 (rofsbuild)
-===============
-Made by Ross Qin 24/08/2009
-
- 1. DPDEF141076 Memory leak in rofsbuild
- 2. DPDEF141624 Coverity reports delete array in C++ without [] and deadcode.
-
-Version 2.1.602 (readimage)
-===============
-Made by Zhi Dou 19/08/2009
-
-  1. DPDEF141566 Textshell ROM fails to build due to 'cannot open obey file' 
-  
-Version 2.12.1 (rombuild)
-===============
-Made by Zhi Dou 19/08/2009
-
-  1. DPDEF141566 Textshell ROM fails to build due to 'cannot open obey file' 
-
-Version 2.5.1 (rofsbuild)
-===============
-Made by Zhi Dou 19/08/2009
-
-  1. DPDEF141566 Textshell ROM fails to build due to 'cannot open obey file' 
-  
-Version 2.5.0 (rofsbuild)
-===============
-Made by Zhi Dou 31/07/2009
-
-  1. PREQ2465's REQ12562 Byte-pair compression update
-  
-Version 2.12.0 (rombuild)
-===============
-Made by Zhi Dou 31/07/2009
-
-  1. PREQ2465's REQ12562 Byte-pair compression update
-
-Version 2.4.1 (rofsbuild)
-===============
-Made by Zhi Dou 29/07/2009
-
-  1. DPDEF141175 - Removal of the "-w" option in imgtools .mmp files results in a lot of warnings 
-  
-Version 2.11.2 (rombuild)
-===============
-Made by Zhi Dou 29/07/2009
-
-  1. DPDEF141175 - Removal of the "-w" option in imgtools .mmp files results in a lot of warnings 
-
-Version 2.11.1 (rombuild)
-===============
-Made by Zhi Dou 27/07/2009
-
-  1. DPDEF141013 ROMBUILD should prevent kernel extensions linking to user side 
-  
-Version 2.11.0 (rombuild)
-===============
-Made by Zhi Dou 21/07/2009
-
-  1. PREQ2465's REQ11939 Warnings for unpaged memory size overflows
-
-Version 2.10.0 (rombuild)
-===============
-Made by Zhi Dou 20/07/2009
-
-  1. REQ13110 HCR file in ROM (ROMBUILD)
-
-Version 2.4.0 (rofsbuild)
-===============
-Made by Zhi Dou 20/07/2009
-
-  1. REQ13111 HCR file in a separate NAND partition (ROFSBUILD)
-  
-Version 2.1.602
-===============
-Made by Vino Jose 10/07/2009
-
-1.	ChrisN
-	1.	MILESTONE: SymTB9.2, GT0419, MS3.36, DS.1815 PREQ2621 System Architecture Relocating header files - K&HS support
-
-Version 2.1.601
-===============
-Made by DeleOgunjumelo 15/01/2009
-
-1.	JonCo
-	1.	MILESTONE: Diran, GT0421, MS3.20, DS1210, REQ11822: WDP support for SBSv1
-	2.	MILESTONE: Diran, GT0421, MS3.20, DS1210, REQ11823: WDP support for romtools
-		PREQ1954 Writeable data paging: prototype release 
-
-Version 2.1.600
-===============
-Released by Kun Xu, 20/06/2008
-	1. DEF122540: Slight issue with readimage and sis files that specify a drive letter.
-
-Version 2.1.599
-===============
-Released by Kun Xu, 17/06/2008
-	1. DEF122721 READIMAGE:Files are extracted in 'reftsp.ini' directory for an ROFS image.
-
-Version 2.1.598
-===============
-Released by Kun Xu, 02/06/2008
-	1. DEF122243: ROMBuild deal with file contain line more than 255 characters incorrectly 
-
-Version 2.1.597
-===============
-Released by Kun Xu, 02/06/2008
-	1. DEF122827: Rom build failure with _ONENAND switch
-	2. DEF119470: ROFSBUILD hangs when an empty OBY file is passed as input
-	3. DEF122024: Many warnings when compiling readimage tool with MSVC++ 6.0
-	4. DEF122533: ROFSBUILD loglevel2 generates logs which don't work for interpretsis
-	
-Version 2.1.596
-===============
-Released by ReubenH, 12/05/2008
-	1. DEF115401: Incomplete validation of data in loader 
-
-Version 2.1.595
-===============
-Released by Mool Chand Tyagi, 13/12/2007
-	1. PDEF115166 	Symbian rombuild.exe work incorrectly when compression is used
-
-Version 2.1.594
-===============
-Released by Tamilarasu Byran, 04/12/2007
-	1. PDEF114692: elf2e32 - failed to report relocation data.
-
-Version 2.1.593
-===============
-Released by Tamilarasu Byran, 07/11/2007
-	1. DEF113140: Buildrom fails with error "Use the keyword 'romsize' " for extension ROFS image.
-
-Version 2.1.592
-===============
-Released by Madhu, 31/10/2007
-	1. PDEF107501: readimage is not able to display output of the patched dll.
-
-Version 2.1.591
-===============
-Released by Tamilarasu Byran, 26/10/2007
-	1. INC112577: Readimage tool crashes when run on S60 3.2 rom image.
-
-Version 2.1.590
-===============
-Released by Tamilarasu Byran, 25/10/2007
-	1. DEF107096: Postlinker ignores references to imports from the data segment.
-	2. DEF112586: Buildrom fails while building extension rofs image.
-
-Version 2.1.589
-===============
-Released by Saurabh, 11/10/2007
-	1.	INC112241: Operator precedence bug in Rombuild  
-
-Version 2.1.588
-===============
-Released by Moolchand, 10/10/2007
-	1.	PDEF109724: Rombuild/Rofsbuild should warn if dll or exe is located outside standard paths 
-
-Version 2.1.587
-===============
-Released by Saurabh, 03/10/2007
-	1.	DEF111903: Elf2e32 GT warning base e32  
-
-Version 2.1.586
-===============
-Released by Madhu, 28/09/2007
-	1.	PDEF102323: rofsbuild crashes without generating appropriate error message 
-
-Version 2.1.585
-===============
-Released by Tamilarasu Byran, 25/09/2007
-	1.	DEF111695: Data drive image generation failed
-	2.	DEF104630: elf2e32 crashes
-
-Version 2.1.584
-===============
-Released by AndrewSmi, 09/08/2007
-1.	AndrewSmi
-	1.	DEF110094: Run mode debug: debuggable keyword not supported for armv5_abiv1 in MCL
-
-Version 2.1.583
-===============
-Released by Tamilarasu Byran, 08/08/2007
-	1.	DEF106861: Specifying a compression method in buildrom doesn't work
-
-Version 2.1.582
-===============
-Released by MiguelB, 06/06/2007
-
-1.	Andrew Haigh
-	1.	PREQ1426: Added Debuggable bitfield to E32 header and associated changes
-
-
-Version 2.1.581
-===============
-Released by ???, dd/mm/yyyy
-1.  SivashankarN
-	1.	EC114: Core OS: Enhance File Server to solve 1085/1086 interoperability issue. 
-			Enhanced rofsbuild tools to handle the special attributes to create the rofs image
-
-Version 2.1.580
-===============
-Released by JonC, 03/04/2007
-
-	1) DEF104558 ELF2E32 should build dynamically for TOOLS2 rather than statically for TOOLS
-
-Version 2.1.579
-===============
-Released by KunalM, 27/03/2007
-
-	1) Seclib built as part of the system build
-
-Version 2.1.578
-===============
-Released by KunalM, 20/03/2007
-
-	1) ROM building tools (ROMBUILD,ROFSBUILD) ported to the TOOLS2 platform, under PREQ1182, MS3.1
-
-Version 2.00.577
-==========================
-(Made by SushmitaR, 19/03/2007)
-
-1) OlegI
-	DEFECT FIX: PDEF102522: DP: unhandled exception readimage.exe when using a XIP ROM paged core image 
-
-Version 2.1.576
-===============
-Released by KunalM, 06/03/2007
-
-	1) Build tools (elfdump,uidcrc) ported to the TOOLS2 platform, under PREQ1182, MS3.6.2
-	2) Seclib and Zlib added as pre-built libraries in the MCL for TOOLS2
-
-
-Version 2.00.575
-==========================
-(Made by JonathanM, 07/02/2007)
-
-1) JonathanM
-	DEFECT FIX: DEF101095: DP: Rofsbuild doesn't support paged, unpaged and pagingoverride keywords
-
-Version 2.00.574
-==========================
-(Made by Dusko, 12/12/2006)
-
-1) Dusko
-	DEF097419: DemandPaging:Keywords paged/unpaged are case sensitive
-
-Version 2.00.573
-==========================
-(Made by Dusko, 11/10/2006)
-
-1) Dusko
-	DEF095506: Change in behaviour for 0 length files (rofsbuild)
-
-Version 2.00.572
-==========================
-(Made by Dusko, 27/09/2006)
-
-1.	Dusko
-	DEF093537: Re-Introducing warnings when creating demand paged ROMs
-
-2.	RajeswariR
-	DEF087061 : PR0104 test failures - Incorrect function call, incorrect msg checking
-	DEF088937: Incorrect usage of $ChopSrcPath in cl_bpabi.pm.
-	DEF091008: ignorenoncallablefunction not supported in ABIV2 mode toolchain.
-	DEF093342: Symbol name for absent exports present in the DSO file.
-	DEF093344: ABIV2 fixup should not happen for export table relocation entries in postlinker.
-	DEF093345: Support for no exception compiler option in the ABIV2 mode toolchain.
-	DEF094731: Workaround to handle ARM linker veneer problem.	
-
-Version 2.00.571
-==========================
-(Made by RichardC, 13/09/2006)
-
-1.	RichardCo
-	1.	DEF093954: GetSecurityInfo does not support opening unicode filenames
-	2.	DEF092758: E32ImageFile::Open does not support opening unicode filenames
-
-Version 2.00.570
-==========================
-(Made by Dusko, 05/09/2006)
-
-1.	Dusko
-	INC088317 Elftran crashes during compilation of ARMV5 dll 
-
-Version 2.00.569
-==========================
-(Made by JonathanM, 01/09/2006)
-
-1.	DanH
-	1.	DEF091669: Several rombuild problems in demand paged roms.
-		Fixed various rombuild problems with different demand paging configurations, including
-		unhandled exceptions with certain edge cases and missing support for the 'alwayspage'
-		value for the pagingoverride keyword.
-
-Version 2.00.568
-==========================
-(Made by Dusko, 23/08/2006)
-
-1.	Dusko
-	DEF092459: Warnings when creating demand paged ROMs
-
-Version 2.00.567
-==========================
-(Made by ????, ??/??/2006)
-
-1.	AttilaV
-	1.	DEF090973: elf2e32 can't dump header of a byte pair compressed binary
-		Added missing image header wirting code fragment into e32imagefile.cpp 
-		E32ImageFile::WriteImage()method Bytepair compressed image generation branch.
-		Added new case: branch for display bytepair compression method in t the imgdump.cpp 
-		E32ImageFile::DumpHeader method. 
-
-	2.	DEF091564: Spurious warnings when using BytePair compression.
-		In \e32tools\e32image\e32image.cpp there are spuriou 'warning' messages whenever 
-		BytePair compression is used in "ostream& operator<<". These should be deleted. 
-
-Version 2.00.566
-==========================
-(Made by RobertJ, 20/07/2006)
-
-1.	DanH
-	1. 	DEF090813: Rofsbuild has warnings when creating demand paged ROMs
-		Added support for paged/unpaged attributes in rofsbuild. No action is taken with these 
-		attributes yet (not needed until "Code Paging" support is added) but the warnings have
-		been removed when DP ROMs are created.
-
-Version 2.00.565
-===========================
-(Made by DmitryL, 28/06/2006)
-
-1.	AttilaV
-	1.	DEF088473: ELF2E32 tool terminates if --compressionmethod bytepair CLI parameter presents
-		Fixed an uninitialised pointer use at create byte pair compressed executable image.
-
-
-Version 2.00.564
-===========================
-(Made by Dusko, 19/06/2006)
-
-1.	JohanG
-	DEF088447 Change in the rom log file format breaks CW debugging ...
-
-
-Version 2.00.563
-===========================
-(Made by Dusko, 19/06/2006)
-
-1.	JohanG
-	1.	DEF079348: ROMBUILD doesn't always fail cleanly on OOM
-	2.	DEF083206: elftran only dumps inferred relocations, not code or data
-
-
-Version 2.00.562
-===========================
-(Made by DjordjeK, 06/06/2006)
-
-1.	AttilaV
-	1.	DEF081770: The Loader should verify compression type.
-
-
-Version 2.00.561
-===========================
-(Made by DavidM, 26/05/2006)
-
-1.	AttilaV
-	Milestone: Argus,GT0286,MS3.2
-	Extended PETRAN, ELFTRAN, ELF2E32, ROMBUILD, ROFSBUILD to handle new compression method Byte Pair 
-	and new executable image compressed by the new compression
-
-
-Version 2.00.560
-===========================
-(Made by DuskoJ, 30/05/2006)
-1) SatyakamM
-	DEF083920: Rofsbuild crashes on using patchdata for ABIV2 DLL (ABIV1 works fine)
-
-Version 2.00.559
-===========================
-(Made by DuskoJ, 13/04/2006)
-1) Dusko
-	DEF083116 Validaterel always fails 
-
-Version 2.00.558
-===========================
-(Made by DuskoJ, 16/03/2006)
-1) JonC
-	DEF082002 - EVALID can't deal with case differences in ARMV5 DLL
-
-Version 2.00.557
-===========================
-(Made by JonathanM, 06/03/2006)
-
-1)	JonathanM
-	MILESTONE: Argus GT0286, MS3.1 PREQ209 Demand Paging Prototype.
-	First delivery of demand paging prototype. Delivery step DS204.
-
-Version 2.00.556
-===========================
-(Made by KuldipN, 08/02/2006)
-1) KuldipN
-	DEF078510 buildrom does not validate new XML files 
-	DEF077827 buildrom feature management - should disallow default ranges with extra flags 
-
-Version 2.00.555
-===========================
-(Made by DuskoJ, 24/01/2006)
-1) DuskoJ
-	DEF075849 Feature registry API returning error when featreg.cfg file is greater than 64KB
-	DEF077941 VA_* macros cannot be used with GCCE 
-
-Version 2.00.554
-===========================
-(Made by JonathanM, 04/01/2006)
-
-1) JonathanM
-	PREQ1030 - Kernel support for device driver test suites - Generic Logging Engine.
-	This adds support for the following keywords into ROMBUILD:
-		btrace, btracemode and btracebuffer
-	See base/documentation/Base_How_To_BTrace.doc
-
-Version 2.00.553
-===========================
-(Made by KuldipN, 21/10/2005)
-1) KuldipN
-	PREQ1086 - Device Feature Management (DS 069)
-Version 2.00.552
-===========================
-(Made by KuldipN, 12/10/2005)
-1) KuldipN
-	PREQ1028 - Plug-in compiler integration (DS 063)
-Version 2.00.551
-===========================
-(Made by KuldipN, 06/10/2005)
-1) KuldipN
-	PREQ1085 Flexible device ROM configuration
-Version 2.00.550
-===========================
-(Made by KuldipN, 14/09/2005)
-1) KuldipN
-	REQ5412: Enhance ROM tools compression options  (part of PREQ1192)
-
-Version 2.00.549
-===========================
-(Made by DuskoJ, 12/07/2005)
-1) RajeswariR
-	DEF065105 Using GCC-E should not require modification of existing bld.inf files
-	DEF063447 Postlinker crashes with unsupported outfile
-
-Version 2.00.548
-================
-(Made by JonC, 21/07/2005)
-1) JonC
-      PREQ1032 Hardware-dependent support for "VFP" floating point acceleration and accelerated maths functions
-
-Version 2.00.547
-===========================
-(Made by DuskoJ, 13/07/2005)
-1) Dusko
-	DEF063791 ROFSBUILD resets main ROFS file attributes when processing a ROFS extension
-
-Version 2.00.546
-===========================
-(Made by DuskoJ, 01/07/2005)
-
-1) Dusko
-	DEF062362 PE_DUMP does not report all significant content in NSIS files 
-	DEF064173 secdump.exe blows up when you try and use it 
-
-Version 2.00.545
-===========================
-(Made by KuldipN, 22/06/2005)
-
-1) KuldipN
-		DEF060825  PR0104: Addition of GCCE support to CodeWarrior 
-
-Version 2.00.544
-===========================
-(Made by KuldipN, 10/06/2005)
-
-1) KuldipN
-		DEF062125  PR104: Custom DLL generation is failing 
-
-Version 2.00.543
-===========================
-(Made by DuskoJ, 10/06/2005)
-
-1) Dusko
-		DEF061701 Petran.exe can crash on certain non E32 files
-
-Version 2.00.542
-===========================
-(Made by KuldipN, 27/05/2005)
-
-1) KuldipN
-	PREQ413   Changes to support the GCCE toolchain.
-      	PREQ414   Enable Commercial Compatible Compilers
-      	DEF061420 Elf2e32 Problems
-
-Version 2.00.541
-===========================
-(Made by DuskoJ, 27/05/2005)
-
-1) BalaT
-	DEF060837 RVCT2.2 emits unresolved symbols which ELFTRAN does not notice.
-
-
-Version 2.00.540
-===========================
-(Made by KuldipN, 11/05/2005)
-
-1) KuldipN
-	DEF060826 - PR0104 - PostLinker Memory Leaks
-
-Version 2.00.539
-===========================
-(Made by KuldipN, 3/05/2005)
-
-1) KuldipN
-	PREQ413 - Changes to support the GCCE toolchain.
-
-Version 2.00.538
-===========================
-(Made by BalaT, 1/04/2005)
-
-1) BalaT
-	DEF058002 - [System Build] Failed to build EIKCORE.DLL using RVCT2.2 
-
-Version 2.00.537
-===========================
-(Made by MiguelB, 1/03/2005)
-
-1) MiguelB
-	DEF055301 - ROFSBUILD, COREIMAGE keyword: problem with single-char files/directories 
-
-Version 2.00.536
-===========================
-(Made by Bala, 22/02/2005)
-1) Bala
-	PREQ1027 Submission of RVCT 2.2 Run-Time ABI Compliance to MCL
-
-Version 2.00.535
-===========================
-(Made by Dusko, 21/02/2005)
-
-1)	BalaT
-	DEF051265 Problems debugging .cia files in ARMV5 builds.
-
-Version 2.00.534
-===========================
-(Made by Dusko, 19/01/2005)
-
-1)	Dusko
-	DEF052809 - GENSTUB ERROR: can't open output file....
-
-Version 2.00.533
-===========================
-(Made by Dusko, 23/11/2004)
-
-1)	BalaT
-	1) DEF051128 - armv5 library build in parallel cause conflicts
-
-Version 2.00.532
-===========================
-(Made by KamranN, 11/11/2004)
-
-1)	KamranN
-	1)	Fix for defect DEF051421  Problems with binary search in ROFS  
-
-Version 2.00.531
-===========================
-(Made by Dusko, 08/10/2004)
-
-1)	BalaT
-	1) DEF047934 - ROMBUILD:EXE corrupts ROM directory of an extension ROM 
-
-Version 2.00.530
-===========================
-(Made by Dusko, 04/10/2004)
-
-1)	BalaT
-    1.	Fix for DEF046271 - EVALID cannot cope with differing temp paths present in some ARMV5 .lib files.
-
-Patch to Version 2.00.529
-===========================
-(Made by ???, ??/??/2004)
-
-1.	JonathanM
-	1.	Fix for -dump option in PETRAN.
-
-Patch to Version 2.00.529
-===========================
-(Made by MichaelP, 27/08/2004)
-
-1.	JonathanM
-	1.	Defect Fix: DEF048051 - ROMBUILD can when PlatSecEnforceSysBin is ON
-
-
-Version 2.00.529
-===========================
-(Made by KuldipN, 25/08/2004)
-
-1.	NaheedA
-	1.  DEF047579 - petran fails to report a corrupted input file.
-	2.  DEF046271 - EVALID cannot cope with differing temp paths present in some ARMV5 .lib files
-
-Patch to Version 2.00.528
-===========================
-(Made by JonathanM, 19/08/2004)
-
-1.	JonathanM
-	1.	Defect Fix: DEF048015 - [System Build] ROMs failed to build for MCL 03344 8.1b/9.0
-
-Version 2.00.528
-===========================
-(Made by DjordjeK, 18/08/2004)
-
-1.	JonathanM
-	1.	Added -dump option to PETRAN and ELFTRAN to select what information should
-		be displayed about an image file. This takes a string argument consisting
-		of letters to select the information to be dumped:
-			h	All header info
-			s	Platform Security info
-			c	Code section
-			d	Data section
-			e	Exports
-			i	Imports
-		These letters can be used in any combinations, e.g. "PETRAN -dump ie foo.exe"
-		will show all Imports and Exports of FOO.EXE
-
-Version 2.00.527
-===========================
-(Made by JonathanM, 26/07/2004)
-
-1.	JonathanM
-	1.	Added PlatSecEnforceSysBin setting to ROMBUILD which forces all binary files to
-		be placed under the \sys\bin\ directory.
-		Part of Yankee,GT0217,MS3.1.4 PS6.3.2 Ignore path information for binary files
-		within ROM build and loader.
-		
-Version 2.00.526
-===========================
-(Made by JonathanM, 26/05/2004)
-
-1.	DennisM
-	1.	Fixed defect DEF041434 EKA2 ROMBUILD can't build extension ROMs
-	2.	ROMBUILD now checks that kernel side code doesn't link to user side
-		code, and vice-versa.
-
-Version 2.00.525
-================
-Made by Dusko, 18/05/2004
-
-1) Dusko
-	1) Fix for DEF045146  EVALID does not correctly handle ARMV5 lib files or RVCT .MAP files.
-
-Version 2.00.524
-================
-Made by JonC, 29/04/2004
-
-1) Jon
-	Fixes for:
-	1) DEF044567 gendirective obtains ELF section header data incorrectly
-	2) DEF044048 RVCT version of DEF2DLL camplains about DLLs not having exports 
-
-Version 2.00.523
-===========================
-(Made by JonathanM, 19/03/2004)
-
-1.	JonathanM
-	1.	Implemented the requirements:
-		REQ2632 - Configurability of the enforcement of capabilities
-		REQ2633 - Security violation diagnostic
-		REQ3142 - Associate Platform Security information with an executable.
-		See /cedar/generic/base/documentation/Base_How_To_Configure_Platform_Security_Settings.doc
-
-Version 2.00.522
-===========================
-(Made by JonathanM, 26/02/2004)
-
-1)	JonathanM
-	1)	Modifications made for implementation of
-		Change Request JDOD-5VUJ7F - Change in executable format of EKA2 binaries.
-	2)	Tools now use the sytax "cap1+cap2+cap3" to specify a named set of capabilities
-		(Rather than specifying a single hexadecimal number.)
-	3)	Added three new keywords to ROMBUILD:
-			PlatSecEnforcement
-			PlatSecDiagnostics
-			PlatSecDiasabledCaps cap1+cap2+cap3
-		these are used for specifying Platform Security settings which are then placed
-		in the ROM Header.
-
-Version 1.00.521
-================
-Made by DuskoJ, 16/02/2004
-
-1) Dusko
-	1) Fix for DEF042440 - elfdump creates a new file with zero length.
-
-
-Version 2.01.520
-================
-Made by AndrewJ, 13/02/2004
-
-1) StephanGu
-	Implemented CLCT-5VEK4P - "Binary search in ROFS 
-	together with 'expanding ROFS entries with UIDs'".
-	Changed Rofsbuild to provide a sorted array of offsets
-	in order to allow the file system to perform binary search
-	through the image.  Also expended the TRofsEntry structure
-	to include a copy of the file UID data.
-
-
-Version 2.01.519
-================
-Made by DuskoJ, 30/01/2004
-
-1) Jon
-	1) Fix for - DEF040324 PETRAN access violation whilst converting THUMB build EXEDLL
-	   (Further amendment).
-
-Version 2.01.518
-================
-Made by DuskoJ, 22/01/2004
-
-1) Kuldip
-	1) Fix for DEF40965 Changes to stop overwriting readonly attribute for directories.
-
-
-Version 2.01.517
-================
-Made by DuskoJ, 05/01/2004
-
-1) Kuldip
-	Fix for DEF039055  "Change in behaviour for 0 length files"
-
-Version 2.01.516
-================
-Made by DuskoJ, 19/12/2003
-
-1) Dusko
-	1)	fix for DEF039365 - Petran ignores -fixed keyword	
-
-
-Version 2.01.515
-================
-Made by Dusko, 17/12/2003
-
-1. Kuldip
-	1)	REQ1733, A3.2 Improved Command Line Build Tools
-        ROFSBUILD ROM flexing, Automatic sizing behaviour
-		Automatic XIP-extension OBEYFILE, header generation
-
-Version 2.01.514
-================
-Made by Dusko, 24/11/2003
-
-1. Dusko
-	1)	DEF039411  pediff does not ignore the header CRC 
-		File changed pediff.cpp
-
-Version 2.01.513
-================
-Made by Dusko, 03/11/2003
-
-1. Dusko
-	1.	fix for DEF039536 Non existing files referenced in  Tools_e32tools.mrp...
-
-
-1) William
-	1)	Added PE_DUMP to support the new EVALID.
-
-Version 2.01.512
-================
-Made by Dusko, 10/10/2003
-
-1. Dusko
-	1.	Zephyr,PRO0085,REQ1663, Remove dependencies on MSDEV	
-	  	Changes to BIN2COFF and  WVECONV in order to build with CW
-
-
-Version 2.01.511
-================
-Made by Dusko, 02/10/2003
-
-1. Dusko
-	1.	fix for DEF037065 Problem with error message from uidcrc
-
-Version 2.01.510
-================
-
-Made by Dennis, 24/09/2003
-
-1. Dennis
-	1.	ROMBUILD adds sorted offsets to directory structures to enable binary
-		searching of the ROM file system.
-	2.	Implemented CR ATHE-5PZEAU (Add Version Numbers to Symbian OS Executables).
-
-Version 1.00.505
-================
-Made by DuskoJ, 22/08/2003
-
-1) Morgan
-	Ported ROFSBUILD extension support from beech
-	1) 	Added ROFSBUILD extension support.  Start a ROFS extension with obey file 
-		commands
-			extensionrofs = <filename>
-			rofssize = <size>
-		Added support for ALIASing, HIDEing and RENAMEing.  Semantics and syntax
-		for these commands are the same as ROMBUILD.
-		Core image and extension can be joined together with 
-			tools\e32tools\rombuild\addextensions.pl
-		Added TRofsExtensionHeader to ROFS.H
-		Padding, Alignment and Repro assumptions: 
-		The extension assumes it will be added TRofsHeader::iMaxSize bytes
-		after the start of the core image.  It is assumed the max size of the core
-		image will be aligned appropriately for the underlying ROM device.
-		Core image has signature "ROFS" at offset 0, extension has signature
-		"ROFx" at offset 0 into extension (= iMaxSize after start of core image).
-
-2) Morgan
-	1)	Added rofsbuild\dumpdirs.pl - utility for dumping the ROFS directory
-		structure.
-	2)	Ported ROFSBUILD executable compression from beech
-
-3) Dusko	Changes to a number of e32tools components in order to build cleanly with CodeWarrior
-
-
-Version 1.00.504
-================
-Made by DuskoJ, 25/07/2003
-
-1. Jon
-	1. Fixed DEF036679 by adding copyright statements where appropriate.
-
-
-Version 2.00.503
-================
-
-1) Morgan
-	1) Removed ROMBUILD build warning
-
-Version 2.00.503
-================
-
-1) Dennis
-	
-	ROMBUILD changes:
-
-	1)	'kernelstackaddress' keyword removed. This is now always calculated by
-		ROMBUILD.
-	2)	Address allocation strategy modified. The initial stack is now placed
-		immediately after the kernel .data/.bss area. The kernel heap follows
-		the initial stack (as before). In the moving model, fixed process data
-		chunks are placed after the kernel heap (on chunk boundaries).
-	3)	TRomHeader::iKernStackAddress replaced with TRomHeader::iKernelLimit,
-		which gives the end of the kernel heap rounded up to a chunk boundary
-		except on the moving memory model where it is advanced past the space
-		reserved for fixed process data chunks.
-
-
-Version 2.00.502
-================
-
-1) Dennis
-	1)	Pulled out general E32Image file handling code into e32tools/e32image/...
-		directories. This includes compression/decompression and all stuff which
-		doesn't require	the native PE or ELF file.
-	2)	Merged the two versions of ROMBUILD. ROMBUILD.EXE now accepts E32Image
-		files derived from either PE or ELF. It no longer accepts the native
-		PE/ELF files directly. XIPRMBLD.EXE is no longer built.
-	3)	Added a special instruction (TST PC, #0) to the beginning of all EKA2
-		entry points. This is detected by PETRAN/ELFTRAN and the file marked as
-		having an EKA2 style entry point. The ELF-derived and JFormat flags have
-		been generalised into header format, import format and ABI fields. An
-		entry point type field has been added to distinguish EKA1 and EKA2 entry
-		points.
-	4)	Add 'nowrapper' keyword to ROMBUILD. If specified in OBY file it causes
-		the 256 byte wrapper to be omitted. This setting can still be overridden
-		on the command line.
-
-
-
-======================
-ELFDUMP version 1.0.0
-1) Dusko
-     1) Adding elfdump.cpp. Elfdump is required to be a standalone program     
-    	which can present an ELF object file in a form suitable for use with 
-    	EVALID. It prints hex dumps of relevant sections, directive section as 
-    	text and relocation information showing the symbol the name and of the 
-    	section in which the relocation occurs.
-
-Version 1.00.501
-================
-EKA2 Tools
-
-1) RobertJ
-	1) Support for compressed executables introduced. Source code for the compression
-	& decompression is in petran\szip. Changed PEDUMP to dump compressed executables
-	added -compress & -nocompress options to PETRAN
-	2) Bumped version number of written executables to 1.10
-	3) Added a new format bit to iFlags JFormat (Jetstream format)
-
-Version 1.00.500
-================
-EKA2 Tools
-
-1) Dennis
-	1) Added support for the x86 development target to PETRAN
-	2) Added various values to the ROM header for EKA2 in ROMBUILD
-2) William
-	1) Added -capability <mask> option to PETRAN. There isn't yet an iCapability field in the
-	   E32ImageHeader, but everything else is ready to go.
-
-
-================
-ROMBUILD version 2.05
-
-1) William
-	1)	Fixed defect ROS-52XF6E "ROMBUILD produces incorrect S-Record checksums" by getting the length
-		right (actually by checksumming the bytes we write instead of calculating the values twice).
-	2)	Disable the 3-byte address form of S-Record with a #define, since it upsets some external
-		tools and only benefitted serial download to M*Core.
-	3)	Fixed defect ROS-52ZED7 "ROMBUILD crashes if section 1 overflows in 2 section ROMs" by
-		checking for overflows in the right place.
-	4)	Made verification failure use Print(EError, ...) in all cases, so that it will cause a 
-		ROMBUILD failure rather than just a small complaint at the end of the log file.
-	5)	Extend checkstubs.pl to handle the R3UNUSED Thumb stubs, and update stubs.lst
-
-Todo
-handle section 1 DLLs linking to section 2 DLLs so that section 2 can be replaced
-respect the E32Image flags for dll static data and called entrypoints 
-			
-
-2) Chris
-	1)	Updated romimage.rtf to remove screensize keyword
-
-3) Nicolas (work done as part of CR JPAR-54XMZD)
-	1)	Added new keyword: DEBUGPORT.  It takes a numeric argument
-		which is a magic cookie as far as rombuild is concerned and
-		is stored in the ROM header for interpretation by the
-		kernel and bootstrap.  The default value is -1.
-	2)	Updated romimage.rtf to include DEBUGPORT.	
-
-
-================
-ROMBUILD version 2.04
-
-1) Nicolas
-	1)  Fixed bug where EPOC crashes during boot if there is a non-empty
-	    area after an empty one in the relocation table.
-	2)  Modified the way the kernel extensions list is built to
-	    ensure the extensions are always in the same order in the
-	    list as in the obey file even when some extensions are in
-	    areas and other aren't.  This is necessary because the
-	    kernel extension ordering in the obey file is important
-	    (for example an extension registering a power handler
-	    *must* be loaded after the extension that loads the power
-	    model).
-	3)  Fixed bug in AreaSet::AddArea() (overlap was not detected
-	    when an existing area is embedded in the new one).
-	4)  Overlap unit tests updated.
-	5)	Fixed bug in TDllExportInfo ctor: The ptr to the export directory in
-	  	the ROM buffer was wrong when the file was relocated to a non-default
-	  	area (iRunAddress / iImageAddr mismatch).
-
-
-================
-ROMBUILD version 2.03
-
-1) William
-	1)  Set the default srecordbase to zero, and remove the srecordbase validation.
-	2)  Added "data-align" attribute, and used it in the calculation of dataOffset for
-	    things sharing the SvData. It's not a great name, but it will do for now...
-	3)  Added "KeepIAT" attribute, which builds an old-style Import Address Table instead
-	    of pointing the stubs directly at the export data.  NB. this won't work for
-	    section 1 DLLs, because I haven't reinstated the machinery for putting the IAT into
-	    the second section.
-	4)  Fix defect CLE-4ZEJBB "rom building: fatal error when file to hide isn't found" by
-	    dealing with (aKeyword==EKeywordHide) before testing for !existingFile, and issuing
-	    a warning if the existing file wasn't found.
-	5)  Export checkstubs.pl to \epoc32\rom\tools
-
----------------------
-ROMBUILD version 2.02
-
-1) Nicolas
-
-	1) ROMBUILD: Introduced new area syntax (incompatible with the existing
-       scheme):
-
-		a) The "area <name> <start> <size>" statement declares an area
-		(there is no need to declare the default ROM area).
-
-		b) The "area=<name>" file attribute relocates individual files to
-		the designated area.
-
-		c) When invoking rombuild with -s, a summary of the free and used
-		space in each area is printed.
-
-		d) Areas can be used only in the first section of a sectioned ROM
-		and are forbidden in extension ROMs.
-
-		e) It is forbidden to patch a relocated file.
-
-	2) ROMBUILD: Introduced classes Area and AreaSet and associated
-       iterators to replace all the existing dynamic arrays and indexes
-       used to store the area-related state.  Unit tests for these are
-       built using r_t_areaset.mmp.  Refactored existing code (notably
-       E32Rom::LayoutRom()) to use those new classes.
-
-	3) ROMBUILD: Moved global variables from rombuild.cpp to r_global.cpp
-       to allow build of r_t_areaset.exe.  Made static the globals which
-       were used only in rombuild.cpp.
-
-	4) ROMBUILD: Merged TAddressSet into TAddressRange.  Renamed every
-       "i.*Set" variable to either "i.*Range" or "i.*Section" (previously
-       existing "i.*Section" variables have been suffixed with "Number").
-
-	5) ROMBUILD: Updated version number to 2.02.
-
-	6) HOST: Turned the various overloads of Val() into a template
-       function.
-
----------------------
-ROMBUILD version 2.01
-
-1) William
-	1)  Fixed bug in ParseArea() which reused the area address as the area length
-	2)  Allow for executables generated before GCC 530 by changing the assertion about 
-	    unexpected data. If it looks as though the rdata is after the IAT, then the whole
-	    of the E32ImageFile text area is included in the ROM.
-	3)  The rounding up for the ROM size to a multiple of a megabyte must not exceed the
-	    originally specified size.
-	4)  Increased the ROMBUILD version to 2.01
-
-Version 1.00.174
-================
-Made by William, 23/03/2001
-
-1) William
-	1)  Removed the old .ipr files associated with the predecessor to DISTRIBUTION.TXT
-	2)  Moved ROMBUILD.MMP into the ROMBUILD directory
-	3)  Gave ROMBUILD it's own major and minor version numbers - now 2.0
-	4)  Moved the collapsing routines into ROMBUILD\R_COLLAPSE.CPP
-	5)  Substantial rework of the way that the E32Image files are put into the ROM: it's now
-	    almost the case that the ROM layout is established before copying any data. The layout
-	    is expressed by setting up TAddressRange and TImageSection values in the TRomBuilderEntry,
-	    and the rest of the relocation and copying to the ROM image follows from those values.
-	6)  Change of approach on relocation: instead of relocating the file contents after copying
-	    into the ROM image, do the relocation beforehand. This allows the relocation to operate on
-	    a simple fixed layout (the one which PETRAN set up), and frees the ROM layout to be
-	    entirely different.
-	7)  Unified all the various ROM flavours: in particular the "areas" support is part of the
-	    normal layout process. The use of TAddressSets and their derived forms makes this
-	    pretty painless.
-	8)  Removed the Import Address Tables, saving ~240K in a Quartz 6.1 ROM. The import stubs
-	    are fixed up to point directly into the export directory for the relevant DLL. In two 
-	    section ROMs the export directories are now placed at the start of the upper section 
-	    to support patching: this was previously done using the import address tables.
-	9)  Various special case handling for the Primary has been reworked using generic support.
-	    In particular the primary now gets a default code alignment of 4K, which allows the 
-	    gap to be occupied by other files if the obey file is suitably arranged.
-	10) Area relocation is more pervasive than before. The import stubs in relocated executable
-	    no longer refer back to the unrelocated original contents of the area.
-	11) The sizes of the DLL reference tables are now reported in the log.
-	12) Fixed a bug which caused ROMBUILD to crash if a file was marked as "patched" in a 
-	    two section ROM.
-	13) Size information in the ROM is more consistent: the size in the ROM filesystem is always
-	    the length of the contiguous section beginning at the given address, and the size summary
-	    in the log file reports the SizeInRom() information for the file, which should always
-	    reflect the real cost in ROM of the file regardless of layout.
-
-Version 1.00.173
-================
-Made by Morgan, 08/03/2001
-
-1) Morgan
-	1)	Fixed ROMBUILD to accept DLLs with no imports and DLLs with no exports
-
-
-Version 1.00.172
-================
-Made by William, 07/12/2000
-
-1) William
-	1)  Introduced ROMBUILD support for extension ROMs, the deliverable from project PR0027.
-	    Lots of churn, but the key new data structure is the TRomNode which separates the
-	    ROM directory structure information from the individual files (TRomBuilderEntry). The
-	    TRomNodes handle the DLL name matching and are used to drive the multiple-variant clever
-	    directory structure operations.
-	2)  Reworked the ROMBUILD parsing strategy to remove the need for "files=", allowing the
-	    header statements and file statements to be mixed freely in the OBY file.
-	3)  Use the tables which now drive the ROMBUILD parsing to generate the help information.
-	4)  Don't create ROMBUILD.LOG unless processing an OBY file, and put extra useful information
-	    into the log. In particular, print a line include the ROM image name before processing
-	    the files and after writing the ROM image, e.g.
-
-	        Creating Rom image testrom.IMG
-		...
-	        Writing Rom image with repro header to file testrom.IMG
-
-	    Also report the "Writing" line to the screen, as a comfort to the user.
-	5)  Fix ROS-4RJPTK "ROMBUILD checksums are incorrect" by computing the checksum at the 
-	    right stage, and cross check to make sure it's still right when displaying the ROM stats.
-	    ROMs built with this version of ROMBUILD are likely to be different in up to 4 bytes
-	    at offsets 0x1A8 to 0x1AB (0xA8 to 0xAB for images without a REPRO header).
-	6)  Make "unicode" the default, and introduce sensible defaults for various other keywords.
-	7)  Remove the ROMBUILD support for bigendian images (it's still present in the files
-	    shared with PETRAN.
-	8)  Added dumpdirs.pl which prints out the ROM root directory structures.
-	9)  Added addextension.pl which concatenates a kernel ROM and an extension ROM, making a 
-	    combined image suitable for use with Brutus.
-	10) Try harder to continue reporting errors rather than stopping immediately. In particular,
-	    report all of the unresolved DLL linkages rather than just the first one.
-	11) Introduce new keywords "hide", "alias" and "rename" to manipulate the directory structure.
-	12) Added romimage.rtf documentation (from the BPK, but somewhat edited) and export it to
-	    \epoc32\engdoc\e32tools
-
-
-Version 1.00.171
-================
-Made by Nicolas, 19/10/2000
-
-1) William
-	1)  Rework internals of ROMBUILD to remove arrays indexed by file number.
-	    TRomBuilderEntry is now derived from E32ImageFile, and the various arrays
-	    have become member data in the associated TRomBuilderEntry - OO, dontcha just love it!
-	2)  Added -coff-header option, which could remove the need for bin2coff
-	3)  Use the .idata information to get the DLL ordinals, not the IAT. 
-	    This is preparation for the IAT removal idea, which involves turning the IAT into
-	    a table of pointers back to the associated stubs.
-	4)  Added a range check to TRomBuilderEntry::AddressOfOrdinal
-	5)  Added documentation about various forms of import stub, and checkstubs.pl which
-	    scans all of the stubs in a ROM to check that they lead to a function of the
-	    correct name.
-	6)  Introduced TAddressSet for recording the various addresses associated with
-	    code in a ROM (address of ROMBUILD.EXE working copy, address in ROM, execution address).
-	    Currently used for handling ImportAddressTable and DllRefTable and seems to work in
-	    a two-section Brutus ROM.
-	7)  Partial fix for EDNRFID-4J6DV3 "Corrupt reloc table generated"
-	    Allow for the possibility that there is only .bss with no .data when applying the
-	    heuristic for relocs that don't point into any known section.
-	    Fix printf format specifier typo by changing %0x8 -> %08x
-	8)  Added a verbose option to W32REPRO
-
-
-Version 1.00.170
-================
-Made by Dennis, 13/09/2000
-
-1) William
-	1)  Dust off the S-Record support in ROMBUILD
-	    Use the full 78-bytes available per line, and add support for the
-	    3-byte address form, since this is beneficial to M*Core Cogent.
-	2)  Use "srecordfilename=*" to mean "append .srec to romname and use that"
-	    Same approach for "romnameodd=*" and "romnameeven=*" filenames.
-	3)  Set the RomHeader iSize to be iSizeUsed rounded up to a megabyte. This is
-	    particularly beneficial on platforms which RAM-load a ROM image (Brutus, Cogent)
-	    because it allows the bootstrap to use only the amount of RAM really needed
-	    for the ROM image.
-	4)  Add "hide" keyword to ROMBUILD, as requested by a licensee. This stops the
-	    specified file from being included in the ROM directory, but doesn't stop other
-	    ROM files from linking to the hidden file. A consequence of hiding a DLL is that
-	    it can't be dynamically loaded, which means that you can't hide kernel extensions.
-
-
-Version 1.00.156
-================
-Made by Morgan, 5/7/2000
-
-1) Anon
-	1) Changes to ETOUCH
-	==== //EPOC/development/base/6.0/e32tools/ETOUCH/ETOUCH.CPP#1
-	@@ -3,6 +3,10 @@
-	 // Copyright (c) 1996-1999 Symbian Ltd.  All rights reserved.
-	 //
-
-	+#if defined(__VC32__)
-	+#pragma warning(disable : 4710)        // function '...' not expanded
-	+#endif
-	+
-
-
-Version 1.00.155
-================
-Made by Dennis 22-06-2000.
-
-1)	Dennis
-	1)	Modified W32REPRO so that the -HEX option only makes it receive in hex.
-		It always transmits in base 10. This is so it works with REPROC.
-	2)	Fixed bug in ROMBUILD - it didn't like files with no imports.
-
-Version 1.00.154
-================
-(Made by Alastair, 10.3.2000)
-
-1)	William
-	1)	Added M*Core support
-		Basically just another PE magic number and another TCpu code.
-
-Version 1.00.153
-================
-(Made by Pete, 24/02/2000)
-
-1)	William
-	1)	Updated PETRAN to report exports with value 0 as
-
-			WARNING: No export specified for ordinal 62
-
-		and promoted the non-zero exports from an unknown section to be errors.
-	2)	Added more information to the warning about failure to identify a section for relocation,
-		just in case it ever happens...
-
-2)	Simon
-	1)	Added bin2coff, a utility to add a coff header to a binary
-	  	image. Mainly for use with the cogent smartfirmware
-
-Version 1.00.152
-================
-(Made by Dennis, 19/01/2000)
-
-1)	William
-	1)	Updated W32REPRO usage statement to remove misleading limit on the baud rate
-		The baud rate is actually passed directly to the Win32 comms device, so it should
-		be possible to specify any baud rate supported by the device.
-	2)	Updated W32REPRO to add a -RAW option for use with Brutus REPROB (and others).
-		This tells W32REPRO not to expect a 256-byte header on the image, but it will
-		still pretend that there is one, as expected by the existing REPRO code.
-	3)	Updated W32REPRO to a -BOOT <boostrap_image> and -HEX options, to support
-		the Cirrus Logic board. The bootstrap is sent at 9600 baud before starting the
-		normal REPRO protocol, and -HEX changes the protocol to use base 16 rather than
-		base 10 for numbers transmitted between W32REPRO and the other end.
-	4)	Added W32REPRO protocol support for a new command 'D' which tells W32REPRO to
-		disconnect after a successful transfer: REPROB could usefully be extended to
-		send this command...
-
-2)	Morgan
-	1)	Fixed ROMBUILD so it gives appropriate errors if passed an empty file
-	2)	ROMBUILD.LOG reports inclusion of 256 ROM repro header (Defect EDN147097)
-	3)	Fixed EDN580686 Rombuild is not very tolerant
-	4)	Fixed EDN210727 PEDIFF returns stupid result codes
-		PEDIFF now returns 0 for identical files, and 2 for different files
-	5)	Improved PETRAN dump output (Fixed EDNGLAY-463LNN)
-
-
-Version 1.00.151
-================
-(Made by Morgan, 3/12/99)
-
-1)	Alastair
-	1)	Created a new utility, ERUNTEST.EXE, which will take a batch file
-		listing tests as generated by ABLD and run each test in turn, checking
-		whether each test has succeeded or not by checking the return value from
-		the process and also checking output to the EPOCWIND.OUT file in the
-		temporary directory.  ERUNTEST.EXE logs output to standard output.
-		Obviously this utility will only run WINS/WINC tests.  It must be invoked
-		from the directory in which the test executables reside.
-
-2)	Morgan
-	1)	Fixed some warnings
-
-
-Version 1.00.150
-================
-(Made by Morgan, 27/9/99)
-
-1)	Alastair
-	1)	Created new directory COLTAB and added COLTAB.CPP, BASEKEYS.TXT,
-		COMPKEYS.TXT and README.TXT.  COLTAB comes from Graham Asher, and is a
-		tool for writing the collation tables in COLLATE.CPP.  README.TXT
-		contains details of the URL from which data files BASEKEYS.TXT and
-		COMPKEYS.TXT were sourced.  Type COLTAB without any parameters for help,
-		and/or read the header in COLTAB.CPP.  Console APP COLTAB.EXE will be
-		built into \EPOC32\Tools\.
-
-2)	Malcolm
-	1)	Added code to allow the kernel debug mask to be set via the ROM.OBY
-		file via the new KERNELTRACE keyword.
-
-3)	Morgan
-	1)	ROMBUILD internal directory structure is now sorted wrt a unique
-		identifier for each Dir.  This (hopefully) fixes the reproducability
-		problems ("drifting-directories") experienced when building identical
-		Roms in different NT environments.
-
-
-Version 1.00.125
-================
-(Made by Morgan, 26/8/99)
-
-1)	Dennis
-	1)	Added "defaultstackreserve" keyword. The argument to this keyword is
-		added to the combined size of .data and .bss to determine the address
-		space to reserve for the $DAT chunk of a 'fixed' process. The value
-		defaults to zero for compatibility with previous versions.
-		Added "stackreserve" keyword to override the default setting on a
-		per-file basis.
-
-
-Version 1.00.124
-================
-(Made by Alastair, 2nd August 1999)
-
-1)	Jonathan
-	1)	Removed MAKSYM - moved to e32toolp.
-
-
-Version 1.00.123
-================
-(Made by Kal Patel, 22 July 1999)
-
-1) Morgan
-	1)	New ROMMASK.  Added a -verbose flag for logging, and added a -no-header
-		for Roms with no Epoc header.
-
-2) Malcolm
-   
-    1) Added Area support to ROMBUILD for Roxette.  This allows the
-       code to be fixed up to execute outside the rom where it's stored.
-       Relocation info is written into the rom and the bootstrap uses
-       this to copy the info out to its final location.  Any file can 
-       be in any arbitrary area.  This is only enabled in
-       singleprocess mode, since the same effect can be achieved with
-       an MMU on a real system.
-
-	   This is enabled by placing a "areas=<num>" line in the first
-	   section of the .oby file.  Then, in the files= section, the
-	   next tranche of files can be sent to another area with a
-	   directive like "area 0x81000000 0x100000" where the first value 
-	   is the address and the next the length. Up to <num> area lines
-	   can be in the file section.
-
-	   A relocation table is placed in ROM for the bootstrap.  Its
-	   address is stored in the romheader info that rombuild uses.
-	   The table is a list of <length> <src> <dest> triples, ending
-	   with a <0,0,0> tuple.
-
-	   Note that any bootstrap that uses this should not process a
-	   relocation table address of 0, as this maintains backwards
-	   compatability with old rombuilds which will put zero in the
-	   address location.
-
-3)	Alastair
-	1)	Removed all .DSP and .MAK files, now that makefiles are generated.
-	2)	Fixed minor typo in W32Repro.
-
-
-Version 1.00.122
-================
-(Made by Alastair, 12.7.99)
-
-1) Alastair
-	1)	Added fetcher definition file, E32TOOLS.FTC, to the group directory.
-	2)	Added William's new version of E32UID.CPP which no longer requires
-		WINDOWS.H.
-	3)	Added William's new UIDCRC.EXE, which provides a simple way to calculate
-		the checksum:
-
-			uidcrc <uid1> <uid2> <uid3> [<outputfile>]
-
-		This reads the three uids (using strtoul, so decimal and 0x9999 hex are 
-		found), computes the checksum, and either prints the 4 hex values to standard
-		output or creates <outputfile> as the 32 byte sequence which is the specified
-		UIDs and checksum in little-endian byte order.
-
-
-Version 1.00.121
-================
-(Made by Alastair, 16.6.99)
-
-1)	Alastair
-	1)	Fixed EDN459831 "Wveconv help is out of date" .
-	2)	Removed MAKTRAN, DEFMAKE and DEFTOOL.
-	3)	Converted all projects to MAKMAKE building for the new TOOLS platform.
-	4)	Changed zip of releasables onto the network - this is now called
-		TOOLS.<ver> rather than E32TOOLS.<ver>.  It also contains full paths to
-		the releasables so make sure you're in the root of your EPOC drive
-		before calling, say, "getrel e32tools tools 121".
-	5)	Updated MNT.CMD in various ways, including adding an MNT CHECKREL.
-	6)	Added dopcvs.pl and lock.pl to GROUP directory for use with MNT.BAT.
-
-
-Version 1.00.120
-================
-(Made by Morgan, 30th March 1999)
-
-1)	Morgan
-	1)	Fixed EDNGBON-46BQK4, "ROMBUILD "patched" keyword is broken".
-		(merged in from ER5 release E32TOOLS 110)
-	2)	Left a gap in the build numbers for ER5 maintenance releases
-	3)	Introduced a new version of ROMMASK.EXE.  The syntax has changed
-		from previous versions.  Type "ROMMASK" to see the new syntax.
-		For example, to produce a 10Meg image split into 8 and 2,
-		type the following:     
-rommask -rom p2rom.img -output rom.img -log rom.log -size 10 -section 8 -section 2
-		(You can leave off the final -section 2, and ROMMASK will do the
-		calculations for you.)
-		The output of Rommask will be "rom.log", and the 2 mask files
-		"rom.img" and "rom.im2"
-		ROMMASK still expects the image to contain a Psion 256byte header.
-
-
-Version 1.00.100
-================
-(Made by Morgan, 16th February 1999
-
-1)	Morgan
-	1)	Added the keyword 'srecordbase' to change the base address of
-		the motorola srecord output file.  (Defaults to address 0x0000)
-	2)	Fixed srecord output for big and little endians.
-	3)	Removed unused dependencies from MNT GETCOMPS
-
-
-Version 1.00.099
-================
-(Made by Jonathan, 8th February 1999)
-
-1)	Alastair
-	1)	Edited PETRAN.MAK so that sources depend upon
-	  	\Epoc32\Include\E32uid.h rather than ..\E32uid\E32uid.h. This
-		change should complete the fixing of bug EDN057832 "E32Tools won't
-		rebuild on my PC".
-
-2)	Jonathan
-	1)	Fixed ROMBUILD defect EDN853437 "Dual Boot ROM does not function on
-	  	Series 5" by applying Dennis' fix to fix up data as well as
-	  	executables in dual-boot images.
-
-
-Version 1.00.098
-================
-(Made by Jonathan, 1st February 1999)
-
-1)	Petteri
-	1)	Applied boilerplate copyright to sources.
-
-2)	Jonathan
-	1)	Fixed copyright message in executables.
-	2)	Removed odbc32.lib and odbccp32.lib from all .DSP and .MAK files
-	  	since these libraries are neither required nor always installed.
-
-
-Version 1.00.97
-===============
-(Made by Alastair, 28th January 1999)
-
-1)	Alastair
-	GENERAL
-	1)	Created and added VC5 .DSP files for all projects for debugging.
-	2)	Removed hard-coded drive letters from .DSP files.
-	3)	Re-generated makefiles from .DSP files.
-	4)	Reinstated E32UID directory containing files E32UID.CPP and STDAFX.H
-		required for building ROMBUILD, PEDIFF and PETRAN.
-	5)	Replaced hard-coded instances of 'R:' in MNT.CMD with '%s%'.
-	MAKSYM
-	1)	Added proper handling of two functions appearing at the same address in
-		a ROM.
-	2)	Removed an unnecessary destructor to prevent allocated memory being
-		deleted twice.
-	TMAKTRAN
-	1)	Removed MAKTRAN tests.
-	PEIGER, PREPRO
-	1)	Removed these executables.  Previously MNT.CMD attempted to unzip these
-		from S:\ptool\ and then zip them up again in the e32tools release zip
-		file.  Plans are afoot to provide these tools elsewhere, since we no
-		longer have access to S:.
-
-
-Version 1.00.096
-================
-(Made by Morgan, 21st January 1999)
-
-1)	Morgan
-	GENERAL
-	1)	Removed E32UID
-	2)	Converted all makefiles to VC5
-	3)	Built with VC5
-	ROMBUILD
-	4)	Rectified the drifting directory problem.  ROM images can now
-		be reproduced and validated reliably.
-	READTYPE
-	5)	Removed definitions for "true" and "false" so readtype will
-		compile with VC5.
-
-
-Version 0.01.095
-================
-(Made by Alastair, 18th August 1998)
-
-Morgan
-ROMBUILD
-1) Big-endian bug fix
-
-Alastair
-DEFMAKE
-1) Fixed Epoc S/W Problem SW1-141 - 'DEFMAKE adds an "E" to the end of
-   the generated DEF file'
-ROMBUILD
-1) Fixed Bluebell defect SW1-734 - "What do the tools have against August?".
-   A rom time of 08/08/2008 08:08:08 is now acceptable.
-
-
-Version 0.01.094
-================
-(Made by Jonathan, 10th June 1998)
-
-1)	Morgan
-	ROMBUILD
-	1)	Added extra info to log output.
-
-2)	Graham Asher
-	READTYPE
-	1)	New uniflds.txt and unidata2.txt from release 2.1 of the charater
-		database from Unicode Inc. Many additions and corrections have been
-		made. One of them fixes defect SW1-42 (User::UpperCase is wrong for
-		Greek final sigma (03C2) in the Unicode build) in the EPOC32
-		Software Problems database.
-	2)	Changes to readtype.cpp to accommodate the new character categories
-		in unidata2.txt.
-
-Version 0.01.093
-================
-(Made by Morgan, 15th May 1998)
-
-1) Dennis
-    ROMBUILD
-1)	Added support to ROMBUILD for multiple-boot ROMs:
- a)	Added keywords 'singlekernel' and 'multikernel' to declare whether a
-	single kernel ROM or multiple-kernel ROM is required (defaults to single).
- b)	Added keyword 'variant' to declare which files define hardware variants;
-	this keyword should be applied to the variant DLL (ECUST.DLL) of each
-	hardware variant to be supported.
- c)	Added keywords 'extension' and 'device'. These define kernel-mode DLLs
-	which may have global data, the address of which is generated by ROMBUILD.
-	'device' DLLs are simply LDDs or PDDs with global data.
-	'extension' DLLs are not yet supported by E32.
- d)	Files declared with one of the keywords
-		{primary, file, data, dll, variant, extension, device}
-	may have an additional hardware variant discriminator specified by means
-	of the syntax
-		file[0x05040001]=filename
-	The hardware variant discriminator (HWVD) is an 8-digit hex number whose
-	purpose is to specify which hardware variants the file is relevant to.
-	The top 16 bits indicate which conceptual layer the file belongs to:
-		0100=independent - file is required by all hardware variants
-		xx03=CPU-specific - file is required by all variants with same CPU
-		yyxx=ASIC/variant specific - file is required by all variants with
-			 CPU xx and ASIC yy.
-
-	The bottom 16 bits are only relevant in the last of these three cases.
-	They form a bit mask indicating which specific variants the file is
-	required for. A file declared with the variant keyword must be totally
-	variant-specific, i.e. must have only one bit set in the bit mask.
-	If the HWVD is not specified, a value of 01000000 is assumed, which means
-	that the file appears in all hardware variants.
-
-	Examples (from forthcoming Bluebell/Protea upgrade ROM):
-
-	primary[0504ffff] - kernel for EIGER
-	primary[0706ffff] - kernel for WINDERMERE (different CPU core and ASIC)
-	variant[05040001] - variant DLL for PROTEA
-	variant[07060001] - variant DLL for BLUEBELL v.1
-	variant[07060002] - variant DLL for BLUEBELL v.2 (for illustration)
-
-	Static linkage between files is now restricted by the HWVDs of those
-	files. It is possible for file A to link statically to file B iff
-	{variants V | V requires A} is a subset of {variants V | V requires B}.
-	For the example above, variant[0x05040001] can link to primary[0x0504ffff]
-	but not the other way round.
-
-	It is possible to have two or more files of the same name in the same
-	directory provided that they have HWVDs which are mutually exclusive, so
-	that the two files can never appear on the same machine. The HWVD is used
-	to determine which of the files to use to resolve any static linkage.
-
- e)	The ROM file system now has multiple root directories and directory trees,
-	one for each hardware variant supported by the ROM. This automatically
-	ensures that F32 only sees the files which are relevant to the hardware
-	on which it is running.
-
- f) DLLs declared with one of the keywords {variant, device, extension} can
-	have global data (.data and .bss) which will be allocated in the kernel
-	static data chunk after the kernel data itself.
-
-2)	The 'fixed' flag is now propagated through from PETRAN.
-
-3)	The 'kernstackaddress' keyword is now optional - if it is not present in
-	the obey file, ROMBUILD uses a default value of 
-	kerneldataaddress + Round(kernel-mode dataBss size) +
-		Sum over all fixed .EXEs(Round(DataBss size of .EXE file))
-	where Round(x) rounds up to the PDE size (1Mb on ARM).
-
-
-Version 0.01.092
-================
-(Made by Morgan, 25th February 1998)
-
-ROMBUILD
-1) Fixed the 'code-align' file attribute
-2) Forced the image file size to a multiple of 4k for the good of Rome.
-
-
-Version 0.01.091
-================
-(Made by Alastair, 18th February 1998)
-
-Removed MAKMAKE and BLDMAKE - these tools are now part of
-new project E32TOOLP.
-
-
-Version 0.01.090
-================
-(Made by Morgan, 13th February 1998)
-
-ROMBUILD
-1)	Added support for 'fix'ing LDDs with global static data in Rom.
-2)	The 'file=' specifier now honours the KNoCallEntryPoints flag in
-	the image header (as set by PETRAN).  This means all 'dll='
-	specifiers should be changed to 'file=' and MAKMAKE used to
-	control the entrypoint behaviour with the CALLDLLENTRYPOINTS
-	keyword.
-3)	Added a '-no-header' switch to suppress the Rom loader header.
-
-
-Version 0.01.089
-================
-(Made by Alastair, 9th February 1998)
-
-DEFMAKE
-1)  Changed defmake.exe so that it processes freeze files without
-    carraige returns at the end of the last line correctly. 
-    Fixes SW1-803.
-2)  Put in warning for unfrozen exports.
-
-MAKMAKE
-1)  Changed the warning generated if parameters appear with the
-    NOSTRICTDEF keyword so that it doesn't just appear when MAKMAKE
-    is invoked with the -V flag.  The NOSTRICTDEF keyword,
-    if required, should be used in addition to the DEFFILE keyword,
-    not instead of it.
-2)  Intermediate deffiles created by command-line makefiles no
-    longer have the basename extensions, eg D for narrow debug,
-	if the NOSTRICTDEF keyword is specified.	
-2)  Added warning for any SUBPROJECT keyword appearing before a
-    project has been specified with the PROJECT keyword.  This
-    is now necessary because MAKMAKE now stores SUBPROJECT directories
-    as absolute paths rather than paths relative to the PROJECT directory.
-    If a SUBPROJECT statement specifies a directory beginning with a
-    backslash, it will be treated as an absolute directory; otherwise
-    it will be treated as a directory relative to the PROJECT directory,
-    as before.
-3)  Added warnings for the non-existence of SYSTEMINCLUDE, USERINCLUDE,
-    \PROJECT, SUBPROJECT and \PROJECT\SUBPROJECT directories.
-4)  Put in START WINS .. END block option, NOBROWSEINFO, which can
-    be used to stop generation of .SBR and .BSC files for command-line
-    WINS and WINC builds.
-5)  Changed MAKMAKE.BAT so that the help for the batch command "CALL"
-    is no longer produced if MAKMAKE /? is typed.
-6)  Moved all makmake releasables out of \epoc32\tools\makmake into
-    \epoc32\tools.
-7)  Changed MAKMAKE.BAT over to using the -S PERL switch so that the
-    system path is searched for MAKMAKE.PL, then MAKMAKE.PL searches
-    for the modules it depends upon in whichever \epoc32\tools is
-    specified in the system path.  This means that makmake can be
-    installed on one drive and called to operate on .MMP files from
-    another.
-8)  The second UID for targettypes APP, LDD and PDD will now be added
-    if not present.
-9)  Restructured MAKMAKE and moved some functionality into new modules
-    to facilitate code reuse.  MAKMAKE and BLDMAKE now depend upon the
-    following shared modules
-    PARSECOM.PM, E32ENV.PM, E32TVER.PM, MODLOAD.PM, PATHUTL.PM, PREPFILE.PM.
-    MMP.PM and GENUTL.PM are currently only used by MAKMAKE but may be
-    useful for other purposes in the future.
-10)  Renamed MAKPREP.PM MAKDEPS.PM.
-
-
-BLDMAKE
-1)  Added warning that BLDMAKE ALL won't create batchfiles for preparing
-    IDE makefiles.
-  
-
-Version 0.01.088
-================
-(Made by Morgan, 29th January 1998)
-
-MAKMAKE
-1)	Inserted '-bigendian' on the PETRAN command line for BE builds
-
-PETRAN and ROMBUILD
-1)	Added -bigendian switches to both tools
-
-From Simon Lewis
-1)	Added a new file attribute 'code-align' to ROMBUILD
-2)	Added the switches '-align-const-section' and
-	'const-section-address-mask' to PETRAN
-
-
-Version 0.01.087
-================
-(Made by Alastair, 23th January 1998)
-
-MAKMAKE
-1)  Changed paths within created makefiles so that they are relative
-    to the directory where MAKMAKE was invoked rather than relative
-    to the makefile.  If you are using the /D makmake command-line
-    flag and invoking makmake from directory \[project]\group there
-    is therefore no longer a need to change directory to
-    \Epoc32\Make\[platform] before calling NMAKE.
-
-2)  Deffiles created by the build process in the build directories
-    now have the build-variant dependent U, D, and UD suffixes, and
-    are removed by a makmake -clean.
-
-3)  Changed handling of EXEDLL targettypes so that they can export
-    functions under MARM.  MAKMAKE will expect EXEDLL targettypes to
-    be function exporters for MARM if a deffile is specified in the
-    MMP file, otherwise it will make no use of the intermediate deffile
-    created during the build process.  This means that, until a fix for
-    dlltool becomes available from Cygnus, the first time functions are
-    frozen for EXEDLL targettypes for MARM it is necessary to build once,
-    put a deffile statement for MARM in the MMP file, put the intermediate
-    deffile where the MMP deffile statement expects the freeze file to be,
-    and build once again so that the target is frozen by ordinal.
-
-4)  Changed MAKMAKE warnings so they go to STDERR rather than STDOUT.
-
-5)  Added LONGBLDPATH keyword to MAKMAKE which inserts an extra directory
-    into the build path for a project.  The extra directory may be
-    specified as a parameter to the new keyword but will default
-    to the basename of the MMP file if the keyword is specified
-    without a parameter.
-
-6)  Added new TARGETTYPE, LIB, for creating static libraries.  This
-    is not yet implemented for MSVC5.0.  The object file compiled
-    from the first source file specified in the mmpfile is copied
-    into the target directory and given the same basename as the
-    target.  The behaviour for this keyword is not yet finalised.
-
-7)  Added new TARGETTYPE, IMPLIB, for creating import libraries
-    for DLLs with mutual imports.  Specify a new MMP file for
-    one of the DLLs, give the name of the DLL as the argument
-    for the TARGET keyword (so that the .LIB produced contains
-    the right DLL name) and set the TARGETTYPE as IMPLIB.
-    This is not yet implemented for IDE makefiles and the behaviour
-    for this keyword is not yet finalised.
-
-8)  Added handling of Win32 Resource files to command-line WINS
-    and VC4 and VC5 makefiles because the kernel uses one.
-
-9)  Added new MARM MMP file keywords to cater for unusual scenarios
-    START MARM
-    ALLOWDLLDATA // for dlls requiring static data
-	DATALINKADDRESS [address] // for relocation address for dll data
-    DLLNAME [dll basename for linking] // for dlls which are built
-    // as one thing but linked in the ROM as another
-	STACKSIZE // for stack size other than the default
-    END
-
-10) Added new module SARMBE.PM for creating big-endian single-process
-    arm makefiles
-
-11) Implemented more stringent checking of the format of UIDs in mmp files
-    and made sure dlls with null uids link as mydll.dll rather than
-    mydll[00000000].dll for consistency with rombuild.
-
-12) Made all relative paths in VC4 and VC5 makefiles absolute.
-
-BLDMAKE
-1)  Added new perl tool, bldmake, which creates batch files to
-    control the building of E32 and F32.  Type bldmake without
-    any parameters for options.
-
-
-Version 0.01.086
-================
-(Made by Alastair, 5th January 1998)
-
-DEFMAKE
-1)  Added .E32_UID and .rsrc to the list of recognised sections so that,
-    eg, "WARNING: Section '.E32_UID' removed" no longer appears during
-    WINS builds.
-
-MAKMAKE
-1)  Changed cl_arm.pm and cl_win.pm so that makmake -clean will remove
-    resource headers from \Epoc32\Include if a resource file is specified.
-
-Version 0.01.085
-================
-(Made by Alastair, 9th December 1997)
-
-MAKMAKE
-1)  Removed automatic addition of kernel32.lib and libc.lib to list
-    of Win32 libraries for WINC EXE targettypes as this addition is
-    apparently unnecessary.
-
-
-Version 0.01.084
-================
-(Made by Alastair, 9th December 1997)
-
-MAKMAKE
-1)  Changed handling of targettype EXE for WINC, VC4WINC and VC5WINC
-    platforms so that the LINK.EXE flag /subsystem:console is used
-    rather that /subsystem:windows, and kernel32.lib and libc.lib
-    are automatically added to the list of Win32 libraries to be linked
-    to.
-
-2)  Targettypes LDD and PDD makefiles for MSVC IDEs now require the
-    presence of \epoc32\include\lddwins.def and \epoc32\include\pddwins.def
-    respectively.
-
-
-Version 0.01.083
-================
-(Made by Alastair, 20th November 1997)
-
-Some Makmake Bug Fixes
-1)  Makmake invoked with the /CLEAN flag will now erase the autouid
-    object file if the Win32 autouid keyword is used.
-
-2)  Makmake now uses the environmental variable "INCLUDE" rather
-    than "MsDevDir" to decide which standard include directories
-    should be searched for Win32 header files if a project is
-    linking to Win32 libraries, so that the wrong standard
-    include directories aren't searched when creating MSVC5
-    project files.
-    Fixes SW1-698.
-
-3)  Fixed bug caused by CPP inserting a space after expanding
-    macros in .mmp files by taking the space out again.  This was
-    causing problems where, for example, a path specified as
-    "\EPOC32\RELEASE\WINS\APP.DEF" in the .mmp file would become
-    "\EPOC32\RELEASE\WINS \APP.DEF" after preprocessing prior
-    to creating a WINS makefile.  Lower case paths were not
-    affected.
-
-4)  Replaced link.exe flag
-    /EXPORT:?NewApplication@@YAPAVCApaApplication@@XZ,@1,NONAME
-    in VC4 and VC5 makefiles where the targettype is APP with the
-    flag /def:\EPOC32\RELEASE\WINS\APP.DEF, because the former flag
-    failed to ensure that the function in question was exported
-    at ordinal one.  This solution means that if no deffile is
-    specified in the .mmp file for an APP, \EPOC32\RELEASE\WINS\APP.DEF
-    must be present for the project to link.  Command-line Win32
-    makefiles will link properly without the presence of APP.DEF
-    because they use a defmake flag to ensure the function is
-    exported at the right ordinal.
-    Targettypes LDD and PDD will link by name in MSVC until
-    their deffiles are released to
-    \epoc32\release\wins or somewhere else suitable. 
-
-Version 0.01.082
-================
-(Made by Alastair, 12th November 1997)
-
-MAKMAKE
-1)  Added link-libraries and e(dll|exe) object as dependencies of
-    main target.  This cannot be done for MSVC IDE makefiles.
-    Fixes SW1-565.
-
-2)  Added new targettypes LDD and PDD.  A frozen first ordinal export,
-    the respective gate funtion for the targettype, is specified for
-    these targettypes and for targettype APP if no deffile is specified
-    for the project, otherwise the deffile controls the order of
-    exported functions.  This applies for all supported platforms.  Apart
-    from this feature, projects specifying one of these targettypes build
-    in the same way as projects with targettype DLL.
-    Fixes SW1-666.
-
-3)  Changed MAKMAKE help information so that the build version appears and
-    a list of platform choices appears.  This list of platforms is produced
-    by a search of .PM modules in \EPOC32\TOOLS\MAKMAKE for the comment line
-    "# Can call in makmake command line".  If the line is present in the module
-    then the basename of the module is added to the list.  This is a cheap way
-    of producing a list of available platforms while preserving MAKMAKE's
-    extensibility, and doesn't involve the loading of every .PM module and all
-    the modules that each one of those depends on.
-        The module controlling MAKMAKE help is loaded only when required and
-    provides a brief guide to MMP file syntax if makmake is invoked
-	    MAKMAKE /MMP {PLATFORM}
-    If PLATFORM is specified, syntax for the START .. END block relating to
-    the platform is displayed as well as platform-independent MMP syntax.
-    Fixes SW1-653.
-
-4)  The macros "WIN32" and "_WINDOWS" are now only used in compilation by MAKMAKE-
-    generated Win32 makefiles if the project's MMP file states that the project
-    needs to link to Win32 libraries by listing the libraries it needs with the
-    WIN32_LIBRARY keyword in a Win32 START .. END block. 
-    Fixes SW1-652.
-
-5)  New MMP file keyword - OBJECT - is available.  This keyword is intended to
-    be used by projects having access not to the source files but only the compiled
-    code for certain objects.  Specify the basename of the object only.  Created Win32
-    makefiles will expect object <basename>.OBJ to exist in the build directories
-    for a project, while MARM makefiles will look for <basename>.o.  These object
-    files will appear in the dependency list for the main target in command-line
-    makefiles - this is not possible in MSVC IDE makefiles.
-
-6)  Command-line makefiles now contain extra targets MAKEWORK, MAKEWORKDEB,
-    MAKEWORKREL, etc.  The build-specific targets are included in the list of
-    dependencies for the main makefile build-specific target, so that work
-    directories will be automatically created when building with command-line
-    makefiles if these directories do not already exist.  The new targets could
-    also be used to make the work directories for a project with NMAKE
-        e.g.  NMAKE /f <command line makefile> MAKEWORK
-    would create all the makefiles for a project for all builds.
-
-7)  Win32 command line makefiles now generate SBR and BSC browse files for DEBUG
-    builds so that if a DEBUG build of a project has already been done with a Win32
-    command line makefile, subsequent building of the DEBUG build of the project
-    within the MSVC IDE will not recompile everything to generate the browse files.
-
-8)  Added new module MAKPREP.PM to handle everything relating to MAKMAKE's use of
-    \EPOC32\GCC\BIN\CPP.EXE to generate lists of dependencies for source files.
-    This module now identifies missing system and user headers -
-          - if missing system headers have the extension .RSG or .MBG, the header is
-        listed as existing in \EPOC32\INCLUDE, so there is no longer a need for
-        MAKMAKE to generate a dummy resource header in \EPOC32\INCLUDE to fool CPP.
-          - platform modules can specify standard directories to search for missing
-       system headers.  This means, e.g., Win32 makefiles can specify the MSDEV include
-       directory for those projects linking to Win32 libraries.  If the missing system
-       header is found by the module in the standard directory, it will be left out
-       of the dependency list since the MSVC tools will know where to find it and it
-       can be trusted to be there and unchanged.
-          - if a missing system header fails to satisfy both the above tests then
-       makmake will issue a warning since the generated makefile will probably fail to
-       build.
- 	      - a warning is issued for any user headers not found in the user include or
-       system include paths, where the user include path is the source directory if no
-       user include paths are specified explicitly.
-
-9)  Processing of MMP files now involves a lot more syntax checking and produces
-    corresponding warnings, especially if MAKMAKE is invoked with the -V switch.
-
-10) MAKMAKE will now automatically generate WINS uid source files when creating Win32
-    makefiles, but only if the new keyword - AUTOUID - is specified in a Win32 START ..
-    END MMP file block.  The keyword is necessary since LINK.EXE would fail for projects
-    which already specified UIDS in the source code, so remove WINS UID specification in
-    the project's source code before using AUTOUID.  MAKMAKE works out UID 1 from a
-    project's targettype and takes UIDs 2 and 3, if specified, from the MMP file.  It
-    then creates the UID source file in the same directory as the MAKEFILE it is to create
-    with the name "<target basename>.UID.cpp".  The source file will look something like this
-
-        // Makmake-generated uid source file
-        #include <E32STD.H>
-        #pragma data_seg("E32_UID")
-        __WINS_UID(0x10000079,0x1000008D,0x100002C3)
-        #pragma data_seg()
-
-	The file will be created only if it doesn't already exist or if it is older than the
-    project's MMP file.
-
-11) In MARM makefiles, multiple calls to GNU tool "ar" to archive the object files for
-    a project prior to linking have been replaced by a single call to ar.  The single
-    call passes a script listing the object files to ar.  This changes speeds up the
-    archiving stage of MARM building considerably.
-
-12) Renamed MAKMAKE.CMD MAKMAKE.BAT for Windows 95 compatibility.
-
-13) Changed MSVC5 dependency generation to be the same as for other platforms,
-    but with system headers stripped out of the list later.  Before, vc5 dependencies
-    called CPP such that only user headers were generated.  This change means that
-    CPP will no longer fail if one of the user headers is expecting a macro definition
-    from a system header and forcing CPP to fail if it doesn't get it.
-
-14) Replaced relative with absolute filepaths where possible in CL_WIN.PM.
-
-15) Changed \e32tools\makmake\makmake.mak so that debug utilities like
-	the perl -w switch and use of module strict.pm apply for "DEB" builds.
-    of MAKMAKE only.
-
-16) Added SARM.PM module to be used by the base for building SARM makefiles.
-
-17) Improved path utilities module MAKPATH.PM to do more error checking
-    and handle extra functions.
-
-GROUP
-1)  Changed e32tools\group\mnt.cmd so that makmake is released in a way more similar
-    to other e32tools project - from \epoc32\build\e32tools\makmake\rel.
-
-
-Version 0.01.081
-================
-(Made by Morgan, 4th November 1997)
-
-ROMBUILD
-1)	Added fixed keyword for use with EXE files. This keyword results in the
-	file being loaded as a fixed address process. The data section base address
-	is allocated in the region between the kernel data address and the kernel
-	stack address. The multiprocess keyword can be used to specify the chunk
-	size; it defaults to 1Mb.
-
-PETRAN
-1)	Added -fixed and -moving options which set and clear KImageFixedAddressExe
-	flag respectively.
-
-2)	Added the following switches
-		-heap <min> <max>
-		-allowdlldata
-		-datalinkaddress <base>
-
-MAKSYM
-1)	Removed duplicate function address error message.
-
-
-Version 0.01.080
-================
-(Made by Alastair, 30th September 1997)
-
-MAKMAKE
-1)	Changed Makmake.pl so that if a project uses a resource file
-	and the resource header file is not yet present in \epoc32\include
-	a dummy header file will be created there so that MAKMAKE's generation
-	of dependencies does not assume that the missing header file is
-	in some other location.
-
-2)	Changed /Fd compiler flag in Ide_vc4.pm so that pdb files have the right
-	name rather than vc40.pdb. 
-
-
-Version 0.01.079
-================
-(Made by Morgan, 22nd September 1997)
-
-ROMBUILD
-1)	Integrated the code for building ROMs for the single process
-	version of E32.  Currently this code is protected with a
-	__SINGLE__ macro.
-	Use the keyword 'singleprocess <ChunkSize>' to generate a
-	single process ROM.  Default is 'multiprocess'.
-
-
-Version 0.01.078
-================
-(Made by Alastair, 15th September 1997)
-
-MAKMAKE
-
-0)	Forget to say about release 077 that \[project]\bwinc is the default
-	directory for which WINC def files are searched if the file specified
-	with the DEFFILE keyword has no path.
-
-1)	Improved MMP file reading so that a warning is generated if MAKMAKE
-	ignores a line because it doesn't recognise the syntax.
-
-2)	Makmake.pl - added new code to trap dependency generation errors.
-
-3)	Makmake.pl - minor changes required to support creation of MSVC5 project
-	files.
-
-4)	Added new modules VC5.PM and VC5WINC.PM to support MSVC5.  These modules
-	will create .DSP MSVC5 project control files.  When an MSVC5 .DSP file is
-	created with makmake project files with the following extensions will be
-	deleted - .dsw,.mak,.mdb,.ncb,.opt,.plg.  The new features of MSVC5 which
-	distinguish between header files belonging to the project and system header
-	files are supported.
-
-5)	Added new module MISA.PM to support MISA command-line makefiles.
-
-6)	Tidied up VC4.PM.
-
-7)	Changed MAKMAKE internal structure so that implementaion modules can
-	share modules controlling the layout of the makefile and other common
-	features.  This change does not affect the way that MAKMAKE is invoked.
-
-		VC5.PM and VC5WINC.PM share IDE_VC5.PM
-		VC4.PM and VC4WINC.PM share IDE_VC4.PM
-		WINS.PM and WINC.PM share CL_WIN.PM
-		MARM.PM and MISA.PM share CL_ARM.PM
-
-8)	Changed CL_WIN.PM and CL_MARM.PM to use an inline batch file in the
-	makefile for calling fc4bat to decide whether a resource header file
-	needs rewriting or not.  Previously, if fc4bat returned an error to
-	indicate that the header file should be rewritten, nmake would die.
-
-9)	Added Makmake.mak to \e32tools\makmake\ for building makmake source to
-	\epoc32\tools and \epoc32\tools\makmake in a way similar to C++ projects.
-
-10)	Changed all .PM modules to ensure that they return a true value
-	when loaded successfully.
-
-E32TOOLS MNT
-
-1)	Changed e32tools.rel file so that readtype.exe is released.
-
-2)	Updated MNT MAKEWORK and MNT GETBLD so that PGETBLD and MNT BLDALL will
-	now work on a clean drive.  Changed readtype.mak so that it searches
-	\epoc32\include rather than \e32\inc for system header files.
-	File \e32\inc\unicode.h needs to be listed in e32\inc\incc.prj 
-	at some point.
-
-3)  Modernised MNT BLDALL so that NMAKE is invoked with the /nologo flag.
-
-4)	Modernised MNT VALID so that pediff is used instead of fc /b for binary
-	file comparison.  Makmake is now included and e32uid.exe removed since it's
-	not used or released.
-
-
-Version 0.01.077
-================
-(Made by Alastair, 8th September 1997)
-
-MAKMAKE
-
-1)	Changed 1st stage of linking (by name) for WINS command-line builds so that
-	linking is not attemped incrementally to stop unnecessary warning appearing.
-
-2)	Added two new modules, WINC.PM and VC4WINC.PM, for use in creating WINC
-	command-line and IDE makefiles respectively.  For command-line makefiles,
-	type "makmake {options} [project] WINC;  for IDE makefiles, type
-	"makmake {options} [project] VC4WINC.  DIfferences between WINC and WINS
-	makefiles are slight - WINC appears where WINS would otherwise appear, and
-	WINC source files are preprocessed with the macros "__WINC__" and "__XCON__"
-	defined as well as all the usual WINS macros including "__WINS__".  Note that,
-	in line with the macro scheme applied to source files, MAKMAKE will preprocess
-	XXX.MMP files with macros "WINS" AND "WINC" defined when creating WINC makefiles,
-	so keywords within "#if defined(WINS) ... #endif" and "START WINS ... END" blocks
-	will apply for WINC builds too.  This scheme required changes to the way
-	MAKMAKE.PL processes START ... END blocks.
-
-3)	Removed possibility of passing extra macros to makmake for preprocessing XXX.MMP
-	files - this possibility was never documented and has never been requested so
-	is now presumed unnecessary.
-
-4)	Introduced keyword option which, if specified in XXX.MMP files, will cause
-	MAKMAKE to search for the same deffile for all build variants rather than
-	several files differentiated by suffixes "U","D" and "UD".	The new keyword
-	is "NOSTRICTDEF", originally enough.  Hopefully deffiles for LDDs and PDDs
-	can soon be done away with by having targettypes for LDDs and PDDs and having
-	MAKMAKE implementation modules pass the correct mangled names as 1st ordinal
-	command-line option arguments to DEFTOOL and DEFMAKE instead.
-
-5)	Changed resource handling to be entirely compatible with eikrs.bat - the basename
-	of XXX.RSS is used for XXX.R$(EPOCLANG) and all intermediate resource files.  This
-	change still does not fix SW1-204, for which a spec decision regarding the handling
-	of differing licensee resource file requirements is required.
-	
-
-Version 0.01.076
-================
-(Made by Alastair, 15th August 1997)
-
-MAKMAKE
-
-1)  Changed MARM and WINS modules so that rcomp is called to compile resources
-    directly rather than via eikrs.bat.  This change will mean that resources will
-    be compiled into the correct directory for MARM builds, and that the *.rss file
-	need no longer be in the same directory as the makefile.  This change addresses
-	SW1-204 and SW1-212.
-2)  The STRICTDEF keyword is no longer recognised by makmake.  Its function in
-	appending "D", "U", and "UD" to the base name of *.DEF files for DEB, UREL and
-	UDEB builds is now carried out by default.  There should now be a *.def file for
-	each of these build variants in use if any definition files are used at all.
-	This change addresses SW1-196.
-3)  Makmake.cmd has been improved.  If makmake fails, a basic perl operation will be
-	attempted.  If this fails, the user will be asked if the correct version of perl
-	is installed.  This change addresses SW1-345.
-
-Version 0.01.075
-================
-(Made by Alastair, 24th July 1997)
-
-DEFTOOL (from William Roberts)
-
-1)	Modified DEFTOOL.CPP and DEFTOOL.H
-	Basically just improved error reporting so that
-	a)	When it tells you that there are "frozen ordinals missing from supplied
-		def file" it also tells you which ordinal numbers have been lost.
-	b)	If your DLL exports functions that weren't in the freeze file then it
-		gives you a gentle warning, because that's not something which we'd 
-		want to allow in a release.
-
-MAKMAKE
-
-1)	Changed makmake so that target makefile is created in the current
-	working directory rather than the directory containing the *.mmp
-	file.
-2)  Added line of code to makpath.pm so that single dot directories
-	are stripped from paths.
-3)	Removed repeat occurrence of deffile flag in the link command for 
-	*.wins makefiles.
-4)	Changed RELGDB path macros for MARM makefiles so that they are prefixed
-	with ".\" rather than "..\\..<absolute path to makefile directory>".
-	This is a neater way to get them to expand to something textually different
-	from REL path macros while still specifying the same path.
-5)	Changed "ar q" lines within MARM makefiles to include 8 object files maximum
-	rather than 4 - this should improve efficiency without breaking limits on
-	command-line lengths.
-6)	Changed WINS.PM so that the $(LINK_OBJS) macro is used in the link command line
-	in *.wins makefiles rather than a list of all the objects concerned.
-7)	Changed MARM.PM so that the first stage of linking (by name) for a dll target
-	creates the dll in the build directory rather than the release directory.
-	The	second stage of linking (by number) creates a dll in the build directory
-	rather than the release directory too, overwriting the first dll.  Finally,
-	this target is petranned to the release directory and the dll left in the
-	build directory is deleted. This change solves the problem of nmake thinking
-	that the target has been successfully created when the build has failed
-	anywhere between the first link stage and the petranning stage, because of
-	the presence of an apparently up-to-date dll in the release directory.
-8)	Changed WINS.PM similarly so that *.wins makefiles do a two-stage link.  Defmake
-	is called between the two link stages with a "freeze" file if one is specified
-	with the DEFFILE statement (see below).  The defmake-created def file is then
-	used for the second-stage link (by number).  The first stage of linking creates
-	the target dll in the intermediate directory while the second stage creates the
-	final target dll in the target directory and the first dll is deleted.
-9)	Removed /NAME flag from MAKMAKE - no longer necessary due to (8).
-10)	Radically changed behaviour of MAKMAKE towards DEFFILE and FRZFILE statements
-	within *.mmp files.  There is no longer handling of FRZFILE statements.  As
-	before, if a DEFFILE statement is placed within an #if defined(WINS) ... #endif
-	block, the statement will be used by both WINS and VC4 makefiles but not MARM
-	makefiles, and vice versa if a #if defined(MARM) ... #endif block is used.  If
-	the file specified has no path, the file is assumed to be in directory 
-	\<project>\bwins\ for WINS and VC4 makefiles and \<project>\bmarm\ for MARM
-	makefiles.  For VC4 makefiles, the specified file is passed to LINK.EXE as 
-	before.  For WINS makefiles, the file is not used in the first stage of linking.
-	Defmake is called and uses the file as a freeze file in the creation of a new
-	deffile which will include any new exports produced by changes to the source code
-	for the project.  The new deffile created is used in the second stage of linking.
-	For MARM makefiles, the specified file works in much the same way as for WINS
-	makefiles.
-		In other words, the DEFFILE statement should now be used to specify "freeze"
-	files.  WINS *.def files were in effect "freeze" files anyway.  The choice of
-	"DEFFILE" rather than "FRZFILE" for the new statement within *.mmp file reflects
-	the widespread understanding of "def" vocabulary outside Psion.  For more
-	information, see the discussion on e32proposals - tools - makmake and frz files.
-		The STRICTDEF keyword is still required if differently-named "freeze" files
-	are required for different builds, but this requirement is under review together
-	with potential default directories for components not using directories
-	\<project>\bwins and \<project>\bmarm.  Note that if these directories are not
-	being used and files specified with the DEFFILE statement include a path then is
-	is essential to place DEFFILE statements with #if defines because WINS and VC4
-	builds should never use the same "freeze" file as MARM builds due to the compilers
-	mangling function names in different ways.
-11)	A file specified with the DEFFILE statement is now put in the list of 
-	dependencies for a target in WINS and MARM makefiles, but not yet VC4.
-12)	Changed MAKMAKE to allow for use of the WINDOWS API.  If you are using this API,
-	specify the windows libraries you wish to link to in *.mmp as follows
-
-	START WINS
-	BASEADDRESS		0x43500000
-	WIN32_LIBRARY	kernel32.lib gdi32.lib user32.lib
-	END
-
-		ie, put the WIN32_LIBRARY statement somewhere in a START WINS ... END block
-	and	list the libraries after it.  Please note that these START WINS ... END
-	blocks are very different from #if defined(WINS) ... #endif blocks.  Makmake
-	always preprocesses the *.mmp file when invoked, and later passes any text within
-	START ... END blocks onto the perl module specific to the platform in question.
-	When makmake is invoked with the VC4 argument, the *.mmp file is preprocessed
-	the WINS macro defined.
-13) Fixed bug causing AIF file subroutine to be ignored
-14)	Fixed bug causing path specified with TARGETPATH statement to be left out of
-	path to resource target for WINS makefiles.
-15) Changed resource file building command so that the base name of the target
-	resource file is the same as the base name of the releasable rather than
-	the base name of the file specified with the RESOURCE or SYSTEMRESOURCE
-	statement.
-16) Changed name for target AIF from the base name of the releasable + ".aif" to
-	the name specified by the AIF statement.
-18)	Changed code designed to warn the user if the version of perl they are using
-	is not supported by MAKMAKE so that it is activated before rather than after
-	compilation - untested.
-
-
-Version 0.01.074
-================
-(Made by Alastair, 1st July 1997)
-
-MAKMAKE
-1)  Fixed egregious error causing the content of LIBRARY
-    statements in *.MMP files to be ignored.  This error
-    is present in e32tools releases 071, 072 and 073.
-
-
-Version 0.01.073
-================
-(Made by Morgan, 18th June 1997)
-
-1) ROMBUILD
-   Added 'time' keyword for specifying the date/time stamp
-   in the rom header.
-   Syntax:
-      time=dd/mm/yyyy hh:mm:ss
-
-   Added 'reloc' file attribute to specify user process
-   data run address for Exes.
-
-   Added 'align' keyword to align files on particular
-   alignment boundries.
-
-
-Version 0.01.072
-================
-(Made by Alastair, 16th June 1997)
-
-MAKMAKE
-1)  Added line of code to makmake.pl so that makmake will refuse
-	to work with versions of PERL released prior to version 
-	5.003_07   .  To find out what version of PERL you are using,
-	type  perl -v<return>  in a DOS box.
-
-
-Version 0.01.071
-================
-(Made by Alastair, 9th June 1997)
-
-MAKMAKE
-1)  Added new preprocessor macro, __PSISOFT32__, defined for all
-	projects using MAKMAKE regardless of platform or build variant.
-
-
-Version 0.01.070
-================
-(Made by Matthew, 4th June 1997)
-
-Added new tool ROMMASK, for generating rom images suitable for masking.
-
-
-Version 0.01.069
-================
-(Made by Alastair, 4th June 1997)
-
-MAKMAKE
-
-1)      Fixed bugs causing _UNICODE macro to be output
-	without the initial underscore by marm.pm and
-	wins.pm.
-
-2)      Single call to gcc archiving tool "ar" replaced
-	by multiple call to avoid overriding of command-line
-	length limits for projects comprising many source
-	files.
-
-3)      Fixed bug in \e32tools\makmake\mnt.cmd so that
-	makpath.pm is copied to directory
-	\epoc32\tools\makmake.
-
-
-Version 0.01.068
-================
-(Made by Alastair, 2nd June 1997)
-
-MAKMAKE
-
-1)      Removals
-	makmake.txt - SDK documentation now available
-	revmak.pl - redundant
-	winsname.pm - redundant
-
-2)      Fixes
-
-a)      fixed dependency macro bug for VC4 platform
-b)      fixed problem with mmp file specification of
-	multiple subprojects
-c)      Other minor bug fixes
-
-3)      Internal Changes
-
-a)      Improved generation of dependencies
-b)      Improved path utility functions
-c)      Moved path utility functions out of makmake.pl to
-	new module "MAKPATH.PM"
-d)      Other structural changes
-
-4)      Command-Line invocation
-
-a)      Platform VC4 can now be specified to produce MSVC4.0
-	compatible makefiles - WINS platform now produces
-	makefiles incompatible with MSVC4.0 allowing greater
-	freedom for using nmake to build resource files, etc.
-	*.MMP files will still be preprocessed with the "WINS"
-	macro whether the platform is specified as WINS or VC4
-b)      New flag "/clean" - deletes all non-source files for the
-	project and platform specified.
-c)      New flag "/lang [language]" - sets a language for the
-	project and platform specified except for VC4.
-d)      New flag "/name" - doesn't add any /def:[deffile]
-	linker flags to WINS or VC4 makefiles.  No effect
-	on MARM makefiles.  This flag makes linking-by-name
-	builds possible for WINS.
-e)      Flags can now be specified anywhere on the command-line
-
-5)      *.MMP Files
-
-a)      New keyword "LANG [language]" - sets a language for
-	the project and platform specified except VC4.
-	This setting is overridden if the command-line language
-	flag is used.
-b)      New keyword "AIF [*.aif file]" - specifies an application
-	information file.  This keyword is subproject relative,
-	and merely copies the *.aif file to the target directory
-	at the moment (except for VC4).
-c)      New keyword "BITMAP [*.mbm file] [*.bmp files]" - specifies
-	a protea multi-bitmap target and compiles it to the target
-	directory using bmconv on the windows bitmap files (except
-	for VC4).  The keyword is subproject relative, so all
-	windows bitmaps files specified are expected to reside in
-	the current \PROJECT\SUBPROJECT directory.  This may not be
-	the required behaviour.
-d)      New "RESOURCE" keyword behaviour - eikrs.bat is invoked
-	for MARM and WINS platforms to compile the resource specified
-	to the target directory.  VC4 platform uses the keyword
-	parameter for information only.  If a language is specified
-	it is passed to eikrs.bat, defaults to "SC".
-e)      New keyword "SYSTEMRESOURCE [*.rss file]" - subproject
-	relative, behaves exactly as the RESOURCE keyword except
-	that for WINS the target resource is compiled to directory
-	\epoc32\release\wins\[build]\Z\system\data.  Ignored by
-	VC4.
-f)      New "TARGETTYPE" keyword option - "exedll".  This option
-	can be used to specify a target which will be built as
-	a dll under single-process platform WINS (or VC4), but as
-	an exe for multi-process platform MARM.
-g)      New keyword "STRICTDEPEND" - if specified, makmake will
-	generate dependencies for each source or resource specified
-	for all builds - DEB,UREL,RELGDB etc.  If sources are unlikely
-	to specify different include header files for different
-	builds then there is no need to specify this keyword and
-	dependencies will be generated once only for each source
-	file.
-h)      New "DEFFILE" keyword behaviour.  This keyword is no longer
-	platform-specific (within a "START [platform] ... END" block).
-	If the deffile is specified without a path, then makmake
-	will expect the deffile to live in directory "\PROJECT\BMARM"
-	for the MARM platform, and in "\PROJECT\BWINS" for WINS or VC4.
-	Note that currently the *.def file will be used in a call
-	to dlltool in MARM makefiles as follows:-
-		"dlltool --def [deffile] --output-def [created deffile]".
-	This behaviour is required for at least one project, and
-	different deffiles can be specified for different platforms
-	using "#if defined [platform]" within *.mmp files.
-i)      New keyword "FRZFILE [*.frz file]" - behaves the same as
-	"DEFFILE" keyword as regards paths.  A specified freeze file
-	is ignored by makmake when producing WINS or VC4 makefiles.
-	The file is used by MARM makefiles as follows
-		"ld -z [frzfile] [dlltool-created deffile]".
-j)      New keyword "STRICTDEF" - if this keyword is specified then
-	makmake assumes that, for each *.def or *.frz files specified,
-	there are actually as many of these files as there are
-	different build configurations for the project.  E.G. for
-	WINS makefiles, if a deffile is secified in a *.mmp file as
-	"DEFFILE mydef.def", then makmake will assume "mydefd.def",
-	"mydefu.def" and "mydefud.def" for DEB, UREL, and UDEB builds
-	respectively.  Though for MARM, a RELGDB build would look for
-	plain "mydef.def".
-
-6)      Output
-
-a)      Makmake for MARM will produce *.MARM makefiles.
-b)      Makmake for WINS will produce *.WINS makefiles.
-c)      Makmake for VC4 will produce *.MAK makefiles.
-d)      MARM and WINS makefiles are restructured to allow
-	the following example NMAKE command-line invocations
-
-		"NMAKE /f euactiv2.wins UREL"
-		"NMAKE /f euactiv2.marm UDEB"
-		"NMAKE /f euactiv2.wins CLEANDEB"
-		"NMAKE /f euactiv2.marm CLEAN"
-
-e)      Macros specifying target directories, language,
-	build directories and so on are produced at the
-	top of WINS and MARM makefiles.
-f)  RELGDB builds for MARM aim to put the executable
-	produced into \epoc32\release\marm\rel, and also use 
-	\epoc32\build\[project]\marm\rel as their building 
-	directory.
-g)      Gcc tool OBJCOPY produces a *.sym file for MARM debug
-	builds, including RELGDB.
-
-
-Version 0.01.067
-================
-(Made by Morgan, 19th May 1997)
-
-1) PEDIFF
-   Recognises time/date stamps in debug and export directories.
-   Ignores PETRAN version information in the header.
-
-2) PETRAN
-   Uids take the full 32bits.
-
-3) WVECONV
-   From \VNOTES\WVECONV.  S3a to S5 sound file converter.
-
-
-Version 0.01.066
-================
-(Made by Alastair, 9th May 1997)
-
-MAKMAKE
-
-1) Fixed bug causing extra "print " text to be produced
-   as part of the USERINCLUDES text outputted in verbose mode.
-
-2) Fixed bug causing makmake.pl to fail to produce the extension
-   of a target filename when requested by *.pm modules
-
-3) Fixed bug causing makmake to fail with an error report if
-   more than one flag is specified on the command line
-
-MAKSYM
-
-1) Added a few lines of extra code so that the base address of
-   a dll in the rom is printed to maksym.log when maksym cannot
-   find the corresponding *.map file.
-
-
-Version 0.01.065
-================
-(Made by Alastair, 6th May 1997)
-
-MAKMAKE
-
-1) reorganised to be more easily maintainable and extensible.
-
-2)      handles uid keyword in *.mmp file - uid1 is provided automatically,
-	uid's 2 and 3 are specified ... 
-
-UID <uid2> <uid3>
-
-in *.mmp file.
-
-3)      dependency generation section calls CPP with flag -MG so that
-	makmake responds gracefully to missing generated headers
-
-4)      *.mdp and *.ncb files are automatically deleted from directories
-	in which makmake is directed to create a wins makefile with the same
-	root.
-
-5)      petran is invoked from the arm makefile
-
-6)      invocation syntax simplified so that makmake is invoked 
-		makmake [flags] [mmp file root] [platform]
-	rather than
-		makmake [flags] [mmp file] [destination makefile] [platform]
-
-7)      makmake by default operates in quiet mode, verbose mode is invoked
-	using the new "/V" flag on the command-line
-
-8)      makmake will create the work directories rather than the makefile
-	if the new "/MAKEWORK" flag is used on the command-line
-
-9)      the "/q" flag for "del" commands is no longer added to marm makefiles
-	created with makmake
-
-10)     the DEFFILE keyword is no longer searched for within a START WINS ... END       
-	block, now it is platform independent though not yet utilised by the marm 
-	platform.
-
-11)     winsname.pm is not currently expected to work
-
-12)     PERL is no longer invoked with the -w debugger flag
-
-Version 0.01.064
-================
-(Made by Morgan, 16th April 1997)
-
-1)      ROMBUILD
-	Removed the checks for unicode-ness of Uid[0] on Exes/Dlls
-
-2)  W32REPRO
-	An NT version of PREPRO written by WilliamR
-
-
-Version 0.01.063
-================
-(Made by Morgan, 15th April 1997)
-
-1)      MAKTRAN
-	Changed over to the new (and slightly less mad) Uid scheme
-	introduced in E32(098).
-	Dlls now have a Uid[0] of 0x10000079
-	Exes now have a Uid[0] of 0x1000007A
-	Everything else is as before.
-
-
-Version 0.01.062
-================
-(Made by Graham Asher, 15th April 1997)
-
-READTYPE
-	Added this new tool, which writes the new file unitable.cpp, which contains
-	the Unicode character attribute information. I've put a full
-	explanation of how to use READTYPE in Notes under e32 software design.
-
-
-Version 0.01.061
-================
-(Made by Morgan, 13th April 1997)
-
-1)      ROMBUILD
-	1) Bug fix when using the -S switch with Rom patching
-	2) Added class TRomSectionHeader to the start of the
-	   second section of the Rom so sectioned Roms can have
-	   a separate build time, language variant, and checksum.
-	3) Added iRomSectionHeader member to TRomHeader to point
-	   at the start of the sectioned Rom and padded TRomHeader
-	   to 256 bytes.  This needs a new BOOTROM.BIN which will
-	   be released with E32(098)
-	4) Fixed a bug in the split rom verify code.
-	5) Fixed the overriding of Uids.
-
-
-Version 0.01.060
-================
-(Made by Morgan, 9th April 1997)
-
-1)      PETRAN
-	Fixed a PETRAN dumping bug when there are no .data relocations.
-
-2)      MAKTRAN
-	Bug fix for -P switch when no uid3 is specified.
-
-3)      DEFMAKE
-	Made the -S switch work when -Z is used.
-
-
-Version 0.01.059
-================
-(Made by Morgan, 7th April 1997)
-
-HIGHLIGHTS:
-	* MAKTRAN now produces PETRANned targets.
-	* Components should use the new -P switch instead of -U.
-	* Suggested minimum commandline for Dlls:
-	  MAKTRAN <src .MAK> <dest .ARM> -z<Your .FRZ> -p"-uid2 <Your Uid2> -uid3 <Your Uid3> -nocall"
-
-2)      MAKTRAN
-	1) Overhauled for releasing PETRANned components.
-	   -U switch has been removed and been replaced by new
-	   -P switch for specifying PETRAN command line arguments. Uid1
-	      will default to the correct uid for the build type unless
-		  you specify otherwise.
-
-
-Version 0.01.058
-================
-(Made by Morgan, 3rd April 1997)
-
-1)      ROMBUILD
-	1) Filenames can now be quoted ("") to include spaces.
-	2) More details provided when the Rom overflows.
-
-	NOTE: Currently there is a bug that occurs if the Rom 
-	is exactly the correct size (byte for byte) and sectioning
-	is being used.  It's harmless - I'll fix this in a release
-	soon.
-
-
-Version 0.01.057
-================
-(Made by Alastair, 2nd April 1997)
-
-1)      MAKMAKE
-	Fixed bug in wins.pm causing *.def files specified in *.mmp
-	files to be ignored by MSVC.
-	Included deftool flag -1 NewApplication__Fv for MARM makefiles
-	where the target is an APP.
-	
-	E32TOOLS GROUP MNT.CMD
-	Added lock, unlock and wholock parameters.
-
-
-Version 0.01.056
-================
-(Made by Alastair, 27th March 1997)
-
-Alastair:
-1)      MAKMAKE
-	MAKMAKE generates makefiles for WINS or MARM builds.
-	It is being released because the SDK example projects
-	now use it, and no longer use MAKTRAN.  Makmake is by no
-	means fully tested and is certainly not intended for 
-	incorporation into Epoc32 projects prior to V1 shipping.
-	Details of its use are roughly documented in file 
-	\e32tools\makmake\makmake.txt.
-	Use of makmake requires the installation of Perl 
-	from directory T:\UTIL\PERL.
-
-
-Version 0.01.055
-================
-(Made by Morgan, 20th March 1997)
-
-1) ROMBUILD
-   CheckSum bug fix.
-   Kernel alignment bug fix.
-
-
-Version 0.01.054
-================
-(Made by Morgan, 18th March 1997)
-
-1) ROMBUILD
-   Removed some unnecesary recurtion and tidied some dodgy code.
-   Loaded the files to Rom in the order they appear in the obey
-   file, rather than depth first order.
-   
-   Roms can now be sectioned into two parts allowing the upper
-   part of the rom to be switched for language variations and
-   file patching.  Both these processes require the original
-   releasables, original obey file, and any new releasables.
-   It is also advisable to supply the original Rom so the lower
-   section can be verified to be constant.
-
-   In a sectioned rom the directory structure, import address
-   tables, and Dll reference tables of all files in the first Rom
-   are placed after the section border.
-   The overhead of sectioning a Rom (over and above an unsectioned
-   one) is the space required to duplicate the import address
-   tables of files from the first section.
-   Last time I counted (B2) the iat's took up 42k.
-
-   The 32bit sum of all 32bit words in the second section is
-   always 0.  This means the iChecksum member in TRomHeader is
-   valid for the rom as a whole and for the first section in
-   isolation.
-   It is not possible to patch any files that are listed before
-   the primary or the secondary.  Doing this causes the position
-   of the kernel's/file-server's entry in the directory table to
-   move.  This may be fixed in a future release.
-
-   To section a Rom:
-      Use the keyword
-	 section <rom offset>
-      at the point in the obey file where you want the Rom to be
-      split.  All files before this line appear in the first
-	  (constant) section, and files after appear in the second
-	  (patch/language) section.
-
-   Patching a file in the second section:
-      Add file attribute 'patch[ed]' to the file to be patched.
-      (This will cull the file from the first section).
-      Supply a replacement file in the top section as required.
-	  Note, the original file is still required to guarantee
-	  consistency in the first section of Rom.
-	  Run ROMBUILD.
-
-   Supplying a language dependant file:
-      Put the file after the section keyword.
-	  Run ROMBUILD.
-
-   To verify the lower section of Rom has remained constant:
-      Specify the original Rom image on the command line with
-	  -r<FileName>
-
-
-Version 0.01.053
-================
-(Made by Morgan, 7th March 1997)
-
-1) ROMBUILD
-   Bug fix to 'screen' keyword
-
-
-Version 0.01.052
-================
-(Made by Morgan, 3rd March 1997)
-
-1) ROMBUILD
-   Bug fix for Exes/Dlls with no relocations in .text or .rdata
-   Check Uids for exporting .EXEs as well as .DLLs
-   New 'screen' keyword.  Default is: screen = 640x240x4
-
-2) MAKTRAN
-   Bug fix
-
-
-Version 0.01.051
-================
-(Made by Morgan, 13th January 1997)
-
-Alastair:
-1) MAKSYM
-   Generates a list of C++ symbols and their addresses in rom from
-   ROMBUILD.LOG and accompanying .MAP files.
-   MAKSYM ? for help.
-
-
-Version 0.01.050
-================
-(Made by Morgan, 6th January 1997)
-
-1) ROMBUILD
-   Incompatable with any E32 before 083.
-   Added some stuff to TRomHeader for the test department:
-   A language bitfield (64bits for specifying the languages supported
-   by the ROM), and a 32bit hardware identifier.
-   The languages are as defined by TLanguage in E32STD.H.  (ie Test
-   is bit 0,  English is bit 1, French is bit 2,  etc...)
-   Added two more obeyfile keywords for this.  Usage:
-   languages = <list of supported languages>
-   hardware = <n>
-
-   Rombuild now has a -? switch.
-
-
-Version 0.01.049
-================
-(Made by Morgan, 11th December 1996)
-
-1) MAKTRAN
-   Object files are now grouped on the ar (archive) command line to
-   speed up building.  By default they are grouped in 4s but this
-   can be changed by using the new -a<n> switch.
-
-2) ROMBUILD
-   More informative error information when a dll is exporting by
-   name.
-
-3) E32UID
-   Removed.
-
-
-Version 0.01.048
-================
-(Made by Morgan, 22nd November 1996)
-
-1) ROMBUILD
-   Added 128 bytes of space to TRomHeader which appears at the front
-   of the ROM.  This is to allow work on the StrongARM port to
-   progress.
-   Naturally, this makes ROMBUILD compatable with absolutely nothing.
-   So a new bootrom.bin will be released with E32(075).
-
-
-Version 0.01.047
-================
-(Made by Morgan, 1st November 1996)
-
-1) MAKTRAN
-   Another minor fix to deal with unusually shaped .MAK files.  This
-   time it's old link information stored in comment lines.
-   Added "-Wno-ctor-dtor-privacy" to CPPFLAGS.
-
-2) PEDIFF
-   Bug fix HA-283.  The final section in a PE file may be truncated
-   to its VirtualSize making the SizeOfRawData field of the header
-   inaccurate.  This was causing a problem in the release build but
-   not the debug build.
-   Fixed by padding the section data with zeros up to SizeOfRawData
-   bytes.
-
-3) ROMBUILD
-   Added a iTextSize member to TRomImageHeader.  Making this version
-   of rombuild incompatable with any E32 before build 075.
-
-
-Version 0.01.046
-================
-(Made by Morgan, 1st November 1996)
-
-1) MAKTRAN
-   Added support for include directories other than ..\inc and
-   \epoc32\include
-      
-
-Version 0.01.045
-================
-(Made by Morgan, 7th October 1996)
-
-1) MAKTRAN
-   Added a -U<Uid> switch to put the 3rd uid in the target's import
-   stub so the Dll/Exe exports as DllName[Uid].Ext
-   This enables you to use the type-safe static linking (based on the
-   Dll's 3rd Uid) in E32(070)/F32(036) and ROMBUILD(043).
-
-2) ROMBUILD
-   Officially PVCSed DW's patch to ROMBUILD(044) that disables
-   type-safe static linking and added a -type-safe-link option to
-   turn it back on.
-   I'll leave it that way until people get used to the idea (or until
-   someone comes up with a better plan).
-   Also added checks on the first Uid against
-   KNarrowDebugUid, KNarrowReleaseUid for Ascii builds and
-   KWideDebugUid, KWideReleaseUid for Unicode builds.  I havn't made
-   this dependent on the -type-safe-link option because executables
-   and dlls wont load if this Uid is not set correctly.
-
-
-Version 0.01.044
-================
-(Made by Morgan, 3rd October 1996)
-
-1) ROMBUILD
-   ROMBUILD can now take E32 Image (pre-PETRANned) files as well as
-   PE Format files as input.
-
-
-Version 0.01.043
-================
-(Made by Morgan, 2th October 1996)
-
-1) MAKTRAN
-   Better filename parsing for the -z option.
-
-2) PETRAN
-   Added a -priority option.  This takes a number or one of these
-   keywords: low, background, foreground, high, windowserver,
-   fileserver, realtime, supervisor.
-
-3) ROMBUILD
-   Added 'priority' inline keyword for EXEs.
-   Added checks for type-safe static linking of DLLs.
-
-5) E32UID
-   Jal:  Displays the psion copyright message and build.
-	 Renumbered Uids to be Uid0, Uid1, and Uid2.
-
-6) ALL
-   Redirected error output to stderr.
-   
-
-Version 0.01.042
-================
-(Made by Morgan, 14th September 1996)
-
-1) PREPRO, PEIGER
-   Changes to MNT.CMD to include the latest versions of
-   PREPRO and PEIGER in the E32TOOLS release.
-
-2) MAKTRAN
-   Minor bug fixes for -D defined symbols.
-
-3) E32UID
-   Added a -Q quiet switch.
-
-
-Version 0.01.041
-================
-(Made by Morgan, 14th September 1996)
-
-1) MAKTRAN
-   Added support for maktranning make files of static libraries.
-   There are added complications when using static libraries from
-   GCC:
-   You may find that any executables linked with a static library
-   produce reams of "bad relocation" errors from either PETRAN or
-   ROMBUILD.  At the moment, to work around this you will need to
-   modify 2 lines for each build in the MAKTRANed file.
-       $(LD) ... --whole-archive my_exe.in --no-whole-archive ... my_lib.lib
-   becomes:
-       $(LD) ... --whole-archive my_exe.in my_lib.lib --no-whole-archive ...
-   this has the effect of including all code from the static library
-   in your .EXE whether it is used or not, but it fixes the bad
-   relocations generated by the GCC linker.
-
-   MAKTRAN also propogates defined symbols from the MSVC4
-   Build/Settings dialog excluding:
-	      __WINS__,__VC32__,__EXE__,__DLL__,
-	      _UNICODE,WIN32,_WINDOWS
-
-2) DEFTOOL
-   No longer truncates your def file if it can't find the specified
-   freeze file.
-
-
-Version 0.01.040
-================
-(Made by Morgan, 2nd September 1996)
-
-!) ROMBUILD
-   Bug fix:  for EXEs/DLLs with no imports.
-   
-   The tab character is now treated as white space in obey files.
-   
-   Improved some error messages.
-
-   Removed the universally dispised 'nocallentrypoint' directive on
-   the grounds that it looked silly.
-   Executables specified with 'file=' do not have the entry points
-   called.  New keyword 'dll=' indicates that the entry points
-   should be called.
-
-   Fixed filename case dependency.
-
-2) MAKTRAN
-   Added the switches '--whole-archive' and '--no-whole-archive'
-   around the .in file on the linker command line to keep GCC happy.
-   This only effects EXEs - as DLLs did it already.
-
-
-Version 0.01.039
-================
-(Made by Morgan, 19th August 1996)
-
-1) MAKTRAN
-   Added Unicode and Debug (U,D) suffixes to DEF files to make the
-   filenames for each target different under the new directory
-   structure.
-   Freeze files have also been given the same treatment:  specifying
-   -z afile.frz
-   will use afile.frz, afileD.frz, afileU.frz, afileUD.frz
-   as freeze files for the respective builds.
-
-
-Version 0.01.038
-================
-(Made by Morgan, 2nd August 1996)
-
-1) MAKTRAN
-   New maktran for the new epoc32 directory structure.
-   -T option removed.  Template instantiation is automatic.
-   Dlls are auto-detected by looking for __DLL__ in the .MAK file,
-   but this can be overridden with -D (to force a DLL) and -E (to
-   force an EXE)
-   Bug fix:  MAKTRAN now deals with make files that do not have
-   their "Win32 Release" target first.
-
-2) ETOUCH
-   Replacement TOUCH program.
-
-3) ROMBUILD
-   Bug fix:  for data sections with no relocations
-
-4) PETRAN
-   Added -nocallentrypoints option (can be shortened to -nocall)
-   and   -callentrypoints   option (       shortened to -call)
-   Bug fix:  for executable files with no relocations
-
-
-Version 0.01.037
-================
-(Made by Morgan, 2nd August 1996)
-
-1) ROMBUILD
-   Yet another change that will break your rom if you don't pay
-   attention to the version numbers.  This build is intended to
-   work with E32 (065).
-   The format of the Dll reference table has changed, and now looks
-   like this:
-
-   class TDllRefTable
-      {
-   public:
-      TUint16 iFlags;
-      TUint16 iNumberOfEntries;
-      };
-   followed by iNumberOfEntries of these:
-   class TDllRefTableEntry
-      {
-   public:
-      TUint iEntryPoint;
-      TUint iDllRefTable;
-      };
-
-   Added another inline keyword "nocallentrypoint" to obey files.
-   When attached to a file it prevents the entry points of linked
-   Dlls being called.  This is used to save time during loading
-   when the Dll's entry points are trivial (=empty).
-
-2) Fiddled with the -s option.
-   -S        outputs the size summary to the screen and to the log
-   -SLog     outputs the size summary to the log only
-   -SScreen  outputs the size summary to the screen only
-
-3) Forced the primary's code section to start on a 4K page boundry
-   for obscure operating system reasons.
-   (ie, Getting the exception/interrupt vectors to land on a page
-   boundry so they can be easily mapped by the MMU to the address
-   where they are expected to be.)
-
-4) Added support for building Unicode roms.  The implementation for
-   writing Unicode filenames to ROM is temporarily dubious.
-   A Unicode rom is made by specifying the keyword 'unicode' in the
-   first section of the obey file.
-
-5) Added the keyword 'stop' so parsing of an obey file can
-   be stopped prematurely.
-   
-
-Version 0.01.036
-================
-(Made by Morgan, 11th July 1996)
-
-1) ROMBUILD
-   Support for generating split ROM images - added the optional
-   keywords:
-   romnameodd=<file name>
-   romnameeven=<file name>
-   resulting in two half-roms.  one containing all odd numbered
-   half-words (16bits) and one containing all the even half-words.
-
-   Checksums:
-   Added a checksum member to TRomHeader and an optional keyword
-   romchecksum=<n>
-   for obey files.  This results in a ROM where summing all 32 bit
-   words (ignoring overflows) will return n.  The default sum of
-   all ROM words is 0.
-
-   Checksums for the ROM and for split ROMs are now calculated and
-   reported in the log.  These checksums are calculated by summing
-   all 8bit bytes and taking the least significant 32 bits of the
-   result.
-
-
-Version 0.01.035
-================
-(Made by Morgan, 10th June 1996)
-
-1) MAKTRAN
-   Added a RELGDB target which pretends to be the REL target
-   while keeping the debug info.
-   This has the same effect as a REL build when the makefile is
-   generated with:
-   MAKTRAN -no-strip-symbols -g"-g -fno-omit-frame-pointer" src dest
-
-2) DEFMAKE, DEFTOOL
-   Added -2 switch to compliment the -f switch so you can specify
-   the second ordinal as well as the first without the need to mess
-   around with freeze files.
-   This allows us to accomadate DLLs with the UID function at 
-   ordinal 1, and the GateL function at ordinal 2.
-   Also added -1 switch which is the same as -f to keep things 
-   consistent.
-
-
-Version 0.01.034
-================
-(Made by Morgan, 26th June 1996)
-
-1) ROMBUILD
-   Added facility to output Motorola S format Records.
-   Use the optional keyword:
-   srecordfilename=<output filename>
-   in the first section of the obey file.
-
-2) MAKTRAN
-   gcc option -mcpu-arm710 is now -mcpu=arm710
-   Added -strip-symbols and -no-strip-symbols options.
-   These force the linker to keep or strip all symbol
-   information (including debug symbol info).  If both
-   are omitted then symbols are striped for release
-   builds only.
-
-
-Version 0.01.033
-================
-(Made by Morgan, 24th June 1996)
-
-1) MAKTRAN
-   The -m6 flag on the CPPFLAGS line has changed to
-   -mcpu-arm710 -mapcs-32
-   added -fvtable-thunks and
-   removed -fno-implicit-templates
-
-
-Version 0.01.032
-================
-(Made by Morgan, 20th June 1996)
-
-1) PETRAN, ROMBUILD
-   Bug fix:  Relocations for the .rdata section were 4 bytes out
-   when the executable had a .rdata section and no imports.
-
-   PETRAN now performs a sanity check on all virtual addresses, and
-   lists the dubious ones.
-
-2) MAKTRAN
-   Made the error messages more descriptive when the .MAK file
-   doesn't contain one of the expected targets.
-
-
-Version 0.01.031
-================
-(Made by Morgan, 12th June 1996)
-
-1) PEDIFF
-   syntax: PEDIFF pefile pefile
-	   PEDIFF -e32 e32imagefile e32imagefile
-   compares 2 PE/E32Image format files to see if they are identical
-   ignoring all time/date stamps
-
-2) PETRAN
-   Another change to the E32Image file format to add a time stamp.
-
-
-Version 0.01.030
-================
-(Made by Morgan, 11th June 1996)
-
-1) PETRAN, ROMBUILD
-   Fixes to supply more information for the ram loader.
-   (ie. the size of the import section)
-   Documentation for the E32 Image file format is available from
-   the 'E32Base' Notes database.
-
-
-Version 0.01.029
-================
-(Made by Morgan, 7th June 1996)
-
-1) PETRAN
-   Added the command line switches:
-     -stack <stack size>
-     -uid<n> <uid>
-   for setting the stack size and the file's uids
-
-   The output of PETRAN has changed to the new E32Image file
-   format giving a (seasonally adjusted) size reduction of between
-   20 and 40 bytes.
-
-2) ROMBUILD
-   Uses the new E32Image file format.
-   Added heap size, and uids to the file modifiers
-   file = <src PE file> <dest EPOC file> [attributes]*
-       where 'attributes' is
-       attrib = [r|s|h|R|S|H]+
-       stack = <stack size>
-       reloc = <specific relocation address>
-       heapmax = <heap size>
-       heapmin = <heap size>
-       uid<n> = <uid>
-   Files in the rom are now read-only (R) by default (use
-   attrib=r to make them read/write)
-
-   Made filename and import/export name compares case insensitive
-
-3) DEFMAKE
-   DEFMAKE now accepts Alpha CPU PE Files
-
-
-Version 0.01.028
-================
-(Made by Morgan, 30th May 1996)
-
-1) MAKTRAN
-   added a -g flag to pass extra parameters to the gcc command line
-   eg.
-   -g-fcheck-new
-   adds: -fcheck-new to CPPFLAGS and
-   -g"-fcheck-new -fsigned-char"
-   adds: -fcheck-new -fsigned-char
-
-
-Version 0.01.027
-================
-(Made by Morgan, 29th May 1996)
-
-1) ROMBUILD
-   Changed the format of the 'file' keyword to allow overriding of 
-   various file attributes.
-   New format is:
-   file = <src PE file> <dest EPOC file> [attributes]*
-       where 'attributes' is
-       attrib = [r|s|h]+
-       stack = <stack size>
-       reloc = <specific relocation address>
-
-   The -s switch now lists file sizes in the same order as files
-   occur in the obey file.
-
-   Fixed a problem with reading relocations when the PE format file
-   lies about the VirtualSize of the section.
-
-2) MAKTRAN
-   Removed the -s flag from the linking stage of debug builds
-   to keep gcc generated debug information.
-
-3) DEFTOOL
-   Improved error reporting.
-
-4) General
-   Removed the dependencies on TRomExeHeader and TRomDllHeader
-   (from the header files of E32(059)) which are now defunct
-   so the tools build properly with E32(060).
-   Removed some of the dead code left over from E32ROM
-
-
-Version 0.01.026
-================
-(Made by Morgan, 24th May 1996)
-
-1) ROMBUILD
-   Altered the size summary output to include data files.
-   Currently the files are listed in depth first directory
-   order.  I intend to change this so they appear in the
-   same order as they appear in the obey file.
-
-2) PETRAN
-   Fixed a bug that crashed the translator when the size of the
-   relocation section of an executable was a multiple of 0x200
-   (the PE format file alignment size.)
-
-3) MAKTRAN
-   Added a CLEAN target.
-
-
-Version 0.01.025
-================
-(Made by Morgan, 23rd May 1996)
-
-1) E32ROM has been killed
-
-2) ROMBUILD replaces E32ROM
-   Syntax: ROMBUILD [-v] [-s] obeyfilename
-   -v verbose flag
-   -s gives a size summary of all executables in the rom
-   Logged output appears in the file ROMBUILD.LOG
-
-   The obey files for ROMBUILD are slightly different:
-   The keyword 'resource' has been replaced with 'data' for
-   putting data files in rom.
-   A manditory keyword 'kernheapmax' has been added.
-   The 'version' keyword has the syntax Major[.Minor[(Build)]]
-
-3) PETRAN
-   Produces E32ImageFile format files from PEFiles.
-
-4) Jal,
-   E32UID
-   Attaches UIDs to WINS files.
-
-
-Version 0.01.024
-================
-(Made by Morgan, 14th May 1996)
-
-1) DEFMAKE, DEFTOOL and MAKTRAN
-   Added -z switch to specify a frozen def file.
-   The exports in the frozen def file appear first (and in order)
-   in the new def file.  All additional exports are added to the
-   end.
-   A warning will be give if an export in the frozen def file
-   does not appear in the executable being processed.
-
-
-Version 0.01.023
-================
-(Made by Morgan, 3rd May 1996)
-
-1) Jane
-   Added space for the Uid system to the Rom Exe and DLL headers.
-
-
-Version 0.01.022
-================
-(Made by Morgan, 1st May 1996)
-
-1) E32ROM:
-   Added path checking so now it is not possible to create
-   directories with the name ""
-   The version specified by the obey file is now put into the rom.
-
-2) MAKTRAN:
-   /f switch added to specify the name of the function to use as
-   the first ordinal in the dll. (only works with /d switch).
-   More looping bugs fixed.  This time in the Archive generation.
-   Added some meagre form of test suit:  DIFs good .ARM files
-   with files generated from the current version.
-   Put in the work-around for the "ld hardcoded to C:" problem.
-
-
-Version 0.01.021
-================
-(Made by Morgan, 23rd April 1996)
-
-1) MAKTRAN bug fixes:
-   Added gcc -g option to the debug builds to produce debug output.
-   Fixed HA-103:  Now rules are only output for .cpp files
-   Having a .. or a . in the path for a source file 
-   (eg SOURCE=.\T_BLOB.CPP) no longer puts MAKTRAN into an endless
-   loop.  Also using system variables in path specifiers
-   (eg {($INCLUDE)}"\AHeader.H" ) no longer fills your hard disk.
-   Source files with no dependancies now generate a target.
-
-
-Version 0.01.020
-================
-(Made by Morgan, 11th April 1996)
-
-   E32ROM:
-1) Jal,
-   The 'resource' option is fixed and the rom is given the correct
-   date.
-
-2) Jane,
-   Added an error message if you don't supply enough parameters on
-   any line in the files section.
-
-
-Version 0.01.019
-================
-(Made by Graham, 8th April, 1996)
-
-1) Changed MAKTRAN-created makefile compiler options:
-
-   Added -fno-implcit-templates
-   In the past GCC automatically instantiated template classes and
-   functions. We now want to take complete control of this, so all
-   such templates will have to be instantiated by hand. There is an
-   extra switch (/T) on the command line which enables automatic
-   template instantiation to be turned back on, but this should only
-   be used when compiling test programs. Releasable code should take
-   advantage of the reduction in ROM size which hand-instantiation
-   brings.
-
-   Removed -fvtable-thunks
-   Those programs which exploit multiple-inheritence should now work.
-
-   Added $(USERDEFS)
-   This enables you to add your own definitions to the build.
-   e.g. nmake /f elink.mak USERDEFS=-D_USE_LOG
-
-2) Changed MAKTRAN-created makefile linker options:
-
-   Added --no-whole-archive option
-   This should greatly improve the size and linking speed DLL's. In
-   order to exploit this, you must get the next release of the GCC
-   tools from the network. Do this by typing TOOLS GCC and making
-   sure that \GCC\BIN is in your path.
-
-3) Fixed a bug with MSVC .MAK files which contain custom builds
-
-
-Version 0.01.018
-================
-(Made by Morgan, 3rd April, 1996)
-
-1) Extended DEFTOOL to take a -f switch (takes the name of the
-   function to be ordinal 1).
-
-
-Version 0.01.017
-================
-(Made by Graham, 26th March, 1996)
-
-1) Fixed a bug in E32ROM which gave "relocation type not handled" in
-   the presence of .reloc sections which were an exact multiple of
-   256 bytes in length.
-
-2) Fixed the MAKTRAN "if exist xxx.in del xxx.in" bug
-
-3) Added DEB, UREL and UDEB builds to MAKTRAN make files
-
-Jane:
-
-4) Better error reporting in E32ROM.EXE
-
-
-Version 0.01.016
-================
-(Made by Graham, 19th March, 1996)
-
-1) Fixed a bug in targetting some test program make files.
-2) Changed "del xxx.in" to "if exist xxx.in del xxx.in"
-
-Lane:
-
-3) Changed the mechanism by which libraries to be linked are found.
-
-Jane:
-
-4) Further improvements to the error reporting for DEFMAKE.
-
-
-Version 0.01.015
-================
-(Made by Graham, 8th March, 1996)
-
-1) Changed all tools to display their version and build numbers.
-
-Jane:
-
-2) Fixed a couple of heap problems in E32ROM, and generally increased robustness. 
-   Will now print an error message if there are too many files for the ROM,
-   rather than scribbling all over your nice memory.
-
-3) Improved some of the error reporting for DEFMAKE.
-
-Version 0.01.014
-================
-(Made by Graham, 6th March, 1996)
-
-1) Changed MAKTRAN to accept makefiles which have depenencies ..\..\
-   away from their source directory.
-
-Version 0.01.013
-================
-(Made by Graham, 5th March, 1996)
-
-1) Changed MAKTRAN to accept makefiles which are completely relative to
-   the directory in which they reside. NB These makefiles cannot be
-   correctly translated if they are moved to a different directory.
-
-Version 0.01.012
-================
-(Made by Graham, 4th March, 1996)
-
-1) Changed MAKTRAN to assume DEFTOOL.EXE is in your path
-2) Changed MAKTRAN so that it correctly sets __DLL__ and __EXE__
-3) Changed MAKTRAN to handle specially named DLL's - .DEV .MTD etc
-4) Changed MAKTRAN to handle projects with non-compilable components
-5) Changed the mechanism by which MAKTRAN decides group and project.
-
-Version 0.01.011
-================
-(Made by Graham, 27th February, 1996)
-
-1) Changed E32ROM to give each .EXE an 8K Stack
-2) Fixed bugs in MAKTRAN to do with picking up the name of the target
-3) Removed --whole-archive from .EXE make files built by MAKTRAN
-
-Version 0.01.010
-================
-(Made by Jane, 26th February, 1996)
-
-1) Fixed mnd.cmd for command line builds
-
-Version 0.01.009
-================
-(Made by Jane, 23rd February, 1996)
-
-1) Switched to Visual C++ 4.0
-
-2) E32ROM - Added support for REM statement in obeyfiles
-
-3) E32ROM - Fixed an obeyfile init bug which became apparent under the new compiler
-
-4) DEFMAKE & E32ROM - added support for export table being in .rdata section, as it is
-   now with Visual C++. (Export table in .edata is still supported.)
-
-5) DEFMAKE - added -q option which surrounds symbols names in "". This is mostly needed by
-   gcc builds where all destructors have a full stop in their name.
-
-6) First release of MAKTRAN and DEFTOOL from Lane
-	MAKTRAN converts msvc .mak files to gcc format.
-	DEFTOOL is used by MAKTRAN to strip out garbage from .def files
-		and to insert "NONAME" as required by gcc.
-	For MAKTRAN usage type "MAKTRAN".
-
-7) E32ROM - in log now displays absolute ROM addresses rather than offsets, and for text only
-
-Version 0.01.008
-================
-(Made by Jane, 31st January, 1996)
-
-1) Removed support for old time class
-
-
-Version 0.01.007
-================
-(Made by Jane, 8th January, 1996)
-
-1) Changed to new time class
-
-
-Version 0.01.006
-================
-(Made by Jane, 21st December 1995)
-
-1) Added versions to tools
-
-2) E32ROM - Changed heap min size for apps to 32k.
-
-3) E32ROM - Exits with error if files fail to fixup due to importing by name
-
-
-Version 0.01.004/005
-====================
-(Made by Jane, 15th November 1995)
-
-1) Added -R option to DEFMAKE so that the omission of ??__Dbg names in the .DEF
-   (release 003, (1)) can be optional.
-
-2) DEFMAKE alone now prints the meaning of the switches as well as help text.
-
-Version 0.01.003
-================
-(Made by Jane, 7th November 1995)
-
-1) Changed DEFMAKE not to write any exports after it hits the first
-   ??__Dbg prefixed name, allowing me to automate the E32 build
-   completely.
-
-2) E32ROM - Added code to avoid overwriting the first byte of a file if presented
-   with an invalid RVA of 0. (Bug in Cygnus tools).
-
-Version 0.01.002
-================
-(Made by Jane, 2nd November 1995)
-
-1) Converted DEFMAKE to the new HOST scheme.
-
-2) Sorted MNT.CMD so E32ROM will actually build.
-
-
-Version 0.01.001
-================
-(Made by Jane, 1st November 1995)
-1) First release.
-
+Version 2.12.0 (ROFSBUILD)
+===============
+Released by Jason Cui, 13/06/2010
+	1)Large FAT image support in Rofsbuild
+
+Version 2.11.5 (ROFSBUILD)
+===============
+Released by Jason Cui, 10/06/2010
+	1)Empty Directory Support in FAT Image
+
+Version 2.10.5 (rofsbuild)
+===============
+Released by Lorence Wang, 01/06/2010
+	1) DPDEF145488 ROFSBUILD crash on extension image creation
+
+Version 1.1.1 (fixupsym.pl)
+===============
+Released by Lorence Wang, 12/05/2010
+	1) DPDEF145440 fixupsym cannot startup
+
+Version 2.17.3 (rombuild)
+Version 2.10.4 (rofsbuild)
+===============
+Released by Lorence Wang, 12/05/2010
+	1) DPDEF145436 ROMBUILD and ROFSBUILD cannot take OBY filename from command line
+
+Version 2.17.2 (rombuild)
+===============
+Released by Lorence Wang, 05/05/2010
+	1) DPDEF145420 rombuild fails on TB10.1 vasco_ui core image creation 
+
+Version 2.10.3 (rofsbuild)
+===============
+Released by Lorence Wang, 29/04/2010
+	1) DPDEF145380 Small letters are changing to capital letters in folder and file names 
+	2) DPDEF145381 Voide guidance file names are corrupted with following way
+
+Version 2.10.2 (rofsbuild)
+===============
+Released by Lorence Wang, 20/04/2010
+	1) DPDEF145346 rofsbuild crashs if ROFS partition is too small   
+
+Version 2.10.1 (rofsbuild)
+Version 2.17.1 (rombuild)
+===============
+Released by Ross Qin, 12/04/2010
+	1) DPDEF145300 Rombuild hangs in S60 2010wk13 vasco_ui rom building  
+	
+Version 2.10.0 (rofsbuild)
+Version 2.17.0 (rombuild)
+===============
+Released by Ross Qin, 09/04/2010
+	1) DPDEF145281 Paged meaning change 
+  
+Version 2.9.5 (rofsbuild)
+Version 2.16.1 (rombuild)
+===============
+Released by Ross Qin, 29/03/2010
+	1) RDPDEF145196	rombuild/rofsbuild has extension rom/rofs recognition issues 
+  
+Version 2.16.0 (rombuild)
+===============
+Released by Ross Qin, 26/03/2010
+	1) RM-RIM406-1232: BU: MAKSYMROFS Integration
+  
+Version 2.9.4  (rofsbuild)
+===============
+Released by Lorence Wang, 25/03/2010
+	1) DPDEF145165 S60 build break caused by latest Buildrom.
+
+Version 2.15.3 (rombuild)
+Version 2.9.3  (rofsbuild)
+===============
+Released by Zheng Shen, 16/03/2010
+	1) DPDEF144882  buildrom, rombuild,rofsbuil -keepgoing option
+
+Version 2.15.2 (rombuild)
+Version 2.9.2  (rofsbuild)
+Version 2.2 build(2) (readimage)
+===============
+Released by Zheng Shen, 10/03/2010
+	1) DPDEF144887  [System build] : NE1 smoketest not booting up for TB92SF_1069 vtb92sf build
+
+
+Version 2.15.1 (rombuild)
+Version 2.9.1  (rofsbuild)
+Version 2.2 build(1) (readimage)
+===============
+Released by Zheng Shen, 05/03/2010
+	1) DPDEF144535  remove -fastcompress option for rombuild/rofsbuild
+
+Version 2.15.0 (rombuild)
+Version 2.9.0  (rofsbuild)
+Version 2.2 build(0) (readimage)
+Version 1.1.0 (maksym)
+Version 1.1.0 (maksymrofs)
+Version 1.1.0 (hpsym)
+Version 1.1.0 (fixupsym)
+===============
+Released by Zheng Shen, 22/02/2010
+	1) DPDEF144562	Build Tools cannot be built in Linux
+
+Version 2.14.3 (rombuild)
+================
+(Made by Zheng Shen, 08/02/2010)
+  1. DPDEF143270 -compress=paged is not supported by buildrom/rombuild
+
+Version 2.14.3 (rombuild)
+================
+(Made by Marvin Shi, 25/01/2010)
+  1. DPDEF143859  Bitwise compatible bytepair algorithm update
+  
+Version 2.8.4 (rofsbuild)
+================
+(Made by Marvin Shi, 19/01/2009)
+  1. DPDEF143713 TSW error CSTI-7X4GHW: Buildtool creates invalid long names in FAT images 
+  2. DPDEF143834  Creating multiple rofs images encounters a problem and rofsbuild failed 
+  3. DPDEF143859  Bitwise compatible bytepair algorithm update 
+  
+Version 2.8.3 (rofsbuild)
+================
+(Made by Zheng Shen, 06/01/2009)
+  1. DEF143442 rofsbuild hangs occasionally with -symbols 
+
+Version 2.8.2 (rofsbuild)
+================
+(Made by Zheng Shen, 09/12/2009)
+  1. DPDEF143314 rofsbuild cannot generate FAT16 files 
+
+Version 1.0.1  (fixupsym)
+================
+(Made by Marvin Shi, 23/11/2009)
+ 1. DPDEF142869 Fixupsym failed for romutl.pm cannot be found 
+ 
+Version 2.14.2 (rombuild)
+================
+(Made by Marvin Shi, 18/11/2009)
+  1. DEF142972 buildrom produces garbled logs 
+  
+Version 2.8.1 (rofsbuild)
+================
+(Made by Marvin Shi, 17/11/2009)
+  1. DPDEF142921 TSW error CSTI-7X4GHW: Buildtool creates invalid long names in FAT images 
+  
+
+Version 2.8.0 (rofsbuild)
+================
+(Made by Marvin Shi, 13/11/2009)
+  1. RM-RIM406-1233: BU: MAKSYMROFS Integration
+Version 2.7.0 (rofsbuild)
+===============
+Made by Zhi Dou 03/11/2009
+
+1. RM-RIM406-1228: BU: ROFSBUILD Cache
+
+Version 2.14.1 (rombuild)
+===============
+Made by Zhi Dou 02/11/2009
+
+1. DEF142739 - rombuild.exe displays bogus error messages when trailing REM statement present
+
+Version 2.14.0 (rombuild)
+===============
+Made by Zhi Dou 26/10/2009
+
+1. RM-RIM406-1263: BU: Visual ROM Layout
+
+Version 2.13.4 (rombuild)
+===============
+Made by Zhi Dou 19/10/2009
+
+1. Minor change for copyright from SPL to EPL.
+
+Version 2.6.5 (rofsbuild)
+===============
+Made by Zhi Dou 19/10/2009
+
+1. Minor change for copyright from SPL to EPL.
+
+Version 2.6.4 (rofsbuild)
+===============
+Made by Zhi Dou 14/10/2009
+
+1. DPDEF142516 rofsbuild somtimes crash when building rofs image for tube with many times.
+
+Version 2.13.3 (rombuild)
+===============
+Made by Ross Qin 14/09/2009
+
+1. DPDEF141843 Coverity defects about Resource Leak and Delete Array. 
+
+Version 2.6.3 (rofsbuild)
+===============
+Made by Ross Qin 14/09/2009
+
+1. DPDEF141843 Coverity defects about Resource Leak and Delete Array. 
+
+Version 2.6.2 (rofsbuild)
+===============
+Made by Ross Qin 10/09/2009
+
+1.DPDEF141840 ROFSBUILD is not processing "-s<log|screen|both>" and "-loglevel<012>" correctly  
+
+Version 2.6.1 (rofsbuild)
+===============
+Made by Ross Qin 07/09/2009
+
+1.DPDEF141838 rofsbuild behaves differently from rombuild when invalid numbers given 
+
+Version 2.13.2 (rombuild)
+===============
+Made by Ross Qin 07/09/2009
+
+1.DPDEF141838 rofsbuild behaves differently from rombuild when invalid numbers given 
+2.DPDEF141291 Update unpaged memory overflow error message of rombuild.exe
+
+Version 2.13.1 (rombuild)
+===============
+Made by Ross Qin 03/09/2009
+
+1.DPDEF141685 Low error privilege for Kernel/variant/extension links to non-extension
+
+Version 2.6.0 (rofsbuild)
+===============
+Made by Ross Qin 26/08/2009
+
+1. REQ11940 Parallel processing - ROFSBUILD
+
+Version 2.13.0 (rombuild)
+===============
+Made by Ross Qin 26/08/2009
+
+1. REQ12560 Parallelise Content Preparation - ROMBUILD
+2. REQ13102 Parallelise Image Generation - ROMBUILD
+
+Version 2.1.603 (readimage)
+===============
+Made by Ross Qin 24/08/2009
+
+1. DPDEF141624 Coverity reports delete array in C++ without [] and deadcode.
+
+Version 2.12.2 (rombuild)
+===============
+Made by Ross Qin 24/08/2009
+
+1. DPDEF141624 Coverity reports delete array in C++ without [] and deadcode.
+
+Version 2.5.3 (rofsbuild)
+===============
+Made by Ross Qin 24/08/2009
+
+ 1. DPDEF141076 Memory leak in rofsbuild
+ 2. DPDEF141624 Coverity reports delete array in C++ without [] and deadcode.
+
+Version 2.1.602 (readimage)
+===============
+Made by Zhi Dou 19/08/2009
+
+  1. DPDEF141566 Textshell ROM fails to build due to 'cannot open obey file' 
+  
+Version 2.12.1 (rombuild)
+===============
+Made by Zhi Dou 19/08/2009
+
+  1. DPDEF141566 Textshell ROM fails to build due to 'cannot open obey file' 
+
+Version 2.5.1 (rofsbuild)
+===============
+Made by Zhi Dou 19/08/2009
+
+  1. DPDEF141566 Textshell ROM fails to build due to 'cannot open obey file' 
+  
+Version 2.5.0 (rofsbuild)
+===============
+Made by Zhi Dou 31/07/2009
+
+  1. PREQ2465's REQ12562 Byte-pair compression update
+  
+Version 2.12.0 (rombuild)
+===============
+Made by Zhi Dou 31/07/2009
+
+  1. PREQ2465's REQ12562 Byte-pair compression update
+
+Version 2.4.1 (rofsbuild)
+===============
+Made by Zhi Dou 29/07/2009
+
+  1. DPDEF141175 - Removal of the "-w" option in imgtools .mmp files results in a lot of warnings 
+  
+Version 2.11.2 (rombuild)
+===============
+Made by Zhi Dou 29/07/2009
+
+  1. DPDEF141175 - Removal of the "-w" option in imgtools .mmp files results in a lot of warnings 
+
+Version 2.11.1 (rombuild)
+===============
+Made by Zhi Dou 27/07/2009
+
+  1. DPDEF141013 ROMBUILD should prevent kernel extensions linking to user side 
+  
+Version 2.11.0 (rombuild)
+===============
+Made by Zhi Dou 21/07/2009
+
+  1. PREQ2465's REQ11939 Warnings for unpaged memory size overflows
+
+Version 2.10.0 (rombuild)
+===============
+Made by Zhi Dou 20/07/2009
+
+  1. REQ13110 HCR file in ROM (ROMBUILD)
+
+Version 2.4.0 (rofsbuild)
+===============
+Made by Zhi Dou 20/07/2009
+
+  1. REQ13111 HCR file in a separate NAND partition (ROFSBUILD)
+  
+Version 2.1.602
+===============
+Made by Vino Jose 10/07/2009
+
+1.	ChrisN
+	1.	MILESTONE: SymTB9.2, GT0419, MS3.36, DS.1815 PREQ2621 System Architecture Relocating header files - K&HS support
+
+Version 2.1.601
+===============
+Made by DeleOgunjumelo 15/01/2009
+
+1.	JonCo
+	1.	MILESTONE: Diran, GT0421, MS3.20, DS1210, REQ11822: WDP support for SBSv1
+	2.	MILESTONE: Diran, GT0421, MS3.20, DS1210, REQ11823: WDP support for romtools
+		PREQ1954 Writeable data paging: prototype release 
+
+Version 2.1.600
+===============
+Released by Kun Xu, 20/06/2008
+	1. DEF122540: Slight issue with readimage and sis files that specify a drive letter.
+
+Version 2.1.599
+===============
+Released by Kun Xu, 17/06/2008
+	1. DEF122721 READIMAGE:Files are extracted in 'reftsp.ini' directory for an ROFS image.
+
+Version 2.1.598
+===============
+Released by Kun Xu, 02/06/2008
+	1. DEF122243: ROMBuild deal with file contain line more than 255 characters incorrectly 
+
+Version 2.1.597
+===============
+Released by Kun Xu, 02/06/2008
+	1. DEF122827: Rom build failure with _ONENAND switch
+	2. DEF119470: ROFSBUILD hangs when an empty OBY file is passed as input
+	3. DEF122024: Many warnings when compiling readimage tool with MSVC++ 6.0
+	4. DEF122533: ROFSBUILD loglevel2 generates logs which don't work for interpretsis
+	
+Version 2.1.596
+===============
+Released by ReubenH, 12/05/2008
+	1. DEF115401: Incomplete validation of data in loader 
+
+Version 2.1.595
+===============
+Released by Mool Chand Tyagi, 13/12/2007
+	1. PDEF115166 	Symbian rombuild.exe work incorrectly when compression is used
+
+Version 2.1.594
+===============
+Released by Tamilarasu Byran, 04/12/2007
+	1. PDEF114692: elf2e32 - failed to report relocation data.
+
+Version 2.1.593
+===============
+Released by Tamilarasu Byran, 07/11/2007
+	1. DEF113140: Buildrom fails with error "Use the keyword 'romsize' " for extension ROFS image.
+
+Version 2.1.592
+===============
+Released by Madhu, 31/10/2007
+	1. PDEF107501: readimage is not able to display output of the patched dll.
+
+Version 2.1.591
+===============
+Released by Tamilarasu Byran, 26/10/2007
+	1. INC112577: Readimage tool crashes when run on S60 3.2 rom image.
+
+Version 2.1.590
+===============
+Released by Tamilarasu Byran, 25/10/2007
+	1. DEF107096: Postlinker ignores references to imports from the data segment.
+	2. DEF112586: Buildrom fails while building extension rofs image.
+
+Version 2.1.589
+===============
+Released by Saurabh, 11/10/2007
+	1.	INC112241: Operator precedence bug in Rombuild  
+
+Version 2.1.588
+===============
+Released by Moolchand, 10/10/2007
+	1.	PDEF109724: Rombuild/Rofsbuild should warn if dll or exe is located outside standard paths 
+
+Version 2.1.587
+===============
+Released by Saurabh, 03/10/2007
+	1.	DEF111903: Elf2e32 GT warning base e32  
+
+Version 2.1.586
+===============
+Released by Madhu, 28/09/2007
+	1.	PDEF102323: rofsbuild crashes without generating appropriate error message 
+
+Version 2.1.585
+===============
+Released by Tamilarasu Byran, 25/09/2007
+	1.	DEF111695: Data drive image generation failed
+	2.	DEF104630: elf2e32 crashes
+
+Version 2.1.584
+===============
+Released by AndrewSmi, 09/08/2007
+1.	AndrewSmi
+	1.	DEF110094: Run mode debug: debuggable keyword not supported for armv5_abiv1 in MCL
+
+Version 2.1.583
+===============
+Released by Tamilarasu Byran, 08/08/2007
+	1.	DEF106861: Specifying a compression method in buildrom doesn't work
+
+Version 2.1.582
+===============
+Released by MiguelB, 06/06/2007
+
+1.	Andrew Haigh
+	1.	PREQ1426: Added Debuggable bitfield to E32 header and associated changes
+
+
+Version 2.1.581
+===============
+Released by ???, dd/mm/yyyy
+1.  SivashankarN
+	1.	EC114: Core OS: Enhance File Server to solve 1085/1086 interoperability issue. 
+			Enhanced rofsbuild tools to handle the special attributes to create the rofs image
+
+Version 2.1.580
+===============
+Released by JonC, 03/04/2007
+
+	1) DEF104558 ELF2E32 should build dynamically for TOOLS2 rather than statically for TOOLS
+
+Version 2.1.579
+===============
+Released by KunalM, 27/03/2007
+
+	1) Seclib built as part of the system build
+
+Version 2.1.578
+===============
+Released by KunalM, 20/03/2007
+
+	1) ROM building tools (ROMBUILD,ROFSBUILD) ported to the TOOLS2 platform, under PREQ1182, MS3.1
+
+Version 2.00.577
+==========================
+(Made by SushmitaR, 19/03/2007)
+
+1) OlegI
+	DEFECT FIX: PDEF102522: DP: unhandled exception readimage.exe when using a XIP ROM paged core image 
+
+Version 2.1.576
+===============
+Released by KunalM, 06/03/2007
+
+	1) Build tools (elfdump,uidcrc) ported to the TOOLS2 platform, under PREQ1182, MS3.6.2
+	2) Seclib and Zlib added as pre-built libraries in the MCL for TOOLS2
+
+
+Version 2.00.575
+==========================
+(Made by JonathanM, 07/02/2007)
+
+1) JonathanM
+	DEFECT FIX: DEF101095: DP: Rofsbuild doesn't support paged, unpaged and pagingoverride keywords
+
+Version 2.00.574
+==========================
+(Made by Dusko, 12/12/2006)
+
+1) Dusko
+	DEF097419: DemandPaging:Keywords paged/unpaged are case sensitive
+
+Version 2.00.573
+==========================
+(Made by Dusko, 11/10/2006)
+
+1) Dusko
+	DEF095506: Change in behaviour for 0 length files (rofsbuild)
+
+Version 2.00.572
+==========================
+(Made by Dusko, 27/09/2006)
+
+1.	Dusko
+	DEF093537: Re-Introducing warnings when creating demand paged ROMs
+
+2.	RajeswariR
+	DEF087061 : PR0104 test failures - Incorrect function call, incorrect msg checking
+	DEF088937: Incorrect usage of $ChopSrcPath in cl_bpabi.pm.
+	DEF091008: ignorenoncallablefunction not supported in ABIV2 mode toolchain.
+	DEF093342: Symbol name for absent exports present in the DSO file.
+	DEF093344: ABIV2 fixup should not happen for export table relocation entries in postlinker.
+	DEF093345: Support for no exception compiler option in the ABIV2 mode toolchain.
+	DEF094731: Workaround to handle ARM linker veneer problem.	
+
+Version 2.00.571
+==========================
+(Made by RichardC, 13/09/2006)
+
+1.	RichardCo
+	1.	DEF093954: GetSecurityInfo does not support opening unicode filenames
+	2.	DEF092758: E32ImageFile::Open does not support opening unicode filenames
+
+Version 2.00.570
+==========================
+(Made by Dusko, 05/09/2006)
+
+1.	Dusko
+	INC088317 Elftran crashes during compilation of ARMV5 dll 
+
+Version 2.00.569
+==========================
+(Made by JonathanM, 01/09/2006)
+
+1.	DanH
+	1.	DEF091669: Several rombuild problems in demand paged roms.
+		Fixed various rombuild problems with different demand paging configurations, including
+		unhandled exceptions with certain edge cases and missing support for the 'alwayspage'
+		value for the pagingoverride keyword.
+
+Version 2.00.568
+==========================
+(Made by Dusko, 23/08/2006)
+
+1.	Dusko
+	DEF092459: Warnings when creating demand paged ROMs
+
+Version 2.00.567
+==========================
+(Made by ????, ??/??/2006)
+
+1.	AttilaV
+	1.	DEF090973: elf2e32 can't dump header of a byte pair compressed binary
+		Added missing image header wirting code fragment into e32imagefile.cpp 
+		E32ImageFile::WriteImage()method Bytepair compressed image generation branch.
+		Added new case: branch for display bytepair compression method in t the imgdump.cpp 
+		E32ImageFile::DumpHeader method. 
+
+	2.	DEF091564: Spurious warnings when using BytePair compression.
+		In \e32tools\e32image\e32image.cpp there are spuriou 'warning' messages whenever 
+		BytePair compression is used in "ostream& operator<<". These should be deleted. 
+
+Version 2.00.566
+==========================
+(Made by RobertJ, 20/07/2006)
+
+1.	DanH
+	1. 	DEF090813: Rofsbuild has warnings when creating demand paged ROMs
+		Added support for paged/unpaged attributes in rofsbuild. No action is taken with these 
+		attributes yet (not needed until "Code Paging" support is added) but the warnings have
+		been removed when DP ROMs are created.
+
+Version 2.00.565
+===========================
+(Made by DmitryL, 28/06/2006)
+
+1.	AttilaV
+	1.	DEF088473: ELF2E32 tool terminates if --compressionmethod bytepair CLI parameter presents
+		Fixed an uninitialised pointer use at create byte pair compressed executable image.
+
+
+Version 2.00.564
+===========================
+(Made by Dusko, 19/06/2006)
+
+1.	JohanG
+	DEF088447 Change in the rom log file format breaks CW debugging ...
+
+
+Version 2.00.563
+===========================
+(Made by Dusko, 19/06/2006)
+
+1.	JohanG
+	1.	DEF079348: ROMBUILD doesn't always fail cleanly on OOM
+	2.	DEF083206: elftran only dumps inferred relocations, not code or data
+
+
+Version 2.00.562
+===========================
+(Made by DjordjeK, 06/06/2006)
+
+1.	AttilaV
+	1.	DEF081770: The Loader should verify compression type.
+
+
+Version 2.00.561
+===========================
+(Made by DavidM, 26/05/2006)
+
+1.	AttilaV
+	Milestone: Argus,GT0286,MS3.2
+	Extended PETRAN, ELFTRAN, ELF2E32, ROMBUILD, ROFSBUILD to handle new compression method Byte Pair 
+	and new executable image compressed by the new compression
+
+
+Version 2.00.560
+===========================
+(Made by DuskoJ, 30/05/2006)
+1) SatyakamM
+	DEF083920: Rofsbuild crashes on using patchdata for ABIV2 DLL (ABIV1 works fine)
+
+Version 2.00.559
+===========================
+(Made by DuskoJ, 13/04/2006)
+1) Dusko
+	DEF083116 Validaterel always fails 
+
+Version 2.00.558
+===========================
+(Made by DuskoJ, 16/03/2006)
+1) JonC
+	DEF082002 - EVALID can't deal with case differences in ARMV5 DLL
+
+Version 2.00.557
+===========================
+(Made by JonathanM, 06/03/2006)
+
+1)	JonathanM
+	MILESTONE: Argus GT0286, MS3.1 PREQ209 Demand Paging Prototype.
+	First delivery of demand paging prototype. Delivery step DS204.
+
+Version 2.00.556
+===========================
+(Made by KuldipN, 08/02/2006)
+1) KuldipN
+	DEF078510 buildrom does not validate new XML files 
+	DEF077827 buildrom feature management - should disallow default ranges with extra flags 
+
+Version 2.00.555
+===========================
+(Made by DuskoJ, 24/01/2006)
+1) DuskoJ
+	DEF075849 Feature registry API returning error when featreg.cfg file is greater than 64KB
+	DEF077941 VA_* macros cannot be used with GCCE 
+
+Version 2.00.554
+===========================
+(Made by JonathanM, 04/01/2006)
+
+1) JonathanM
+	PREQ1030 - Kernel support for device driver test suites - Generic Logging Engine.
+	This adds support for the following keywords into ROMBUILD:
+		btrace, btracemode and btracebuffer
+	See base/documentation/Base_How_To_BTrace.doc
+
+Version 2.00.553
+===========================
+(Made by KuldipN, 21/10/2005)
+1) KuldipN
+	PREQ1086 - Device Feature Management (DS 069)
+Version 2.00.552
+===========================
+(Made by KuldipN, 12/10/2005)
+1) KuldipN
+	PREQ1028 - Plug-in compiler integration (DS 063)
+Version 2.00.551
+===========================
+(Made by KuldipN, 06/10/2005)
+1) KuldipN
+	PREQ1085 Flexible device ROM configuration
+Version 2.00.550
+===========================
+(Made by KuldipN, 14/09/2005)
+1) KuldipN
+	REQ5412: Enhance ROM tools compression options  (part of PREQ1192)
+
+Version 2.00.549
+===========================
+(Made by DuskoJ, 12/07/2005)
+1) RajeswariR
+	DEF065105 Using GCC-E should not require modification of existing bld.inf files
+	DEF063447 Postlinker crashes with unsupported outfile
+
+Version 2.00.548
+================
+(Made by JonC, 21/07/2005)
+1) JonC
+      PREQ1032 Hardware-dependent support for "VFP" floating point acceleration and accelerated maths functions
+
+Version 2.00.547
+===========================
+(Made by DuskoJ, 13/07/2005)
+1) Dusko
+	DEF063791 ROFSBUILD resets main ROFS file attributes when processing a ROFS extension
+
+Version 2.00.546
+===========================
+(Made by DuskoJ, 01/07/2005)
+
+1) Dusko
+	DEF062362 PE_DUMP does not report all significant content in NSIS files 
+	DEF064173 secdump.exe blows up when you try and use it 
+
+Version 2.00.545
+===========================
+(Made by KuldipN, 22/06/2005)
+
+1) KuldipN
+		DEF060825  PR0104: Addition of GCCE support to CodeWarrior 
+
+Version 2.00.544
+===========================
+(Made by KuldipN, 10/06/2005)
+
+1) KuldipN
+		DEF062125  PR104: Custom DLL generation is failing 
+
+Version 2.00.543
+===========================
+(Made by DuskoJ, 10/06/2005)
+
+1) Dusko
+		DEF061701 Petran.exe can crash on certain non E32 files
+
+Version 2.00.542
+===========================
+(Made by KuldipN, 27/05/2005)
+
+1) KuldipN
+	PREQ413   Changes to support the GCCE toolchain.
+      	PREQ414   Enable Commercial Compatible Compilers
+      	DEF061420 Elf2e32 Problems
+
+Version 2.00.541
+===========================
+(Made by DuskoJ, 27/05/2005)
+
+1) BalaT
+	DEF060837 RVCT2.2 emits unresolved symbols which ELFTRAN does not notice.
+
+
+Version 2.00.540
+===========================
+(Made by KuldipN, 11/05/2005)
+
+1) KuldipN
+	DEF060826 - PR0104 - PostLinker Memory Leaks
+
+Version 2.00.539
+===========================
+(Made by KuldipN, 3/05/2005)
+
+1) KuldipN
+	PREQ413 - Changes to support the GCCE toolchain.
+
+Version 2.00.538
+===========================
+(Made by BalaT, 1/04/2005)
+
+1) BalaT
+	DEF058002 - [System Build] Failed to build EIKCORE.DLL using RVCT2.2 
+
+Version 2.00.537
+===========================
+(Made by MiguelB, 1/03/2005)
+
+1) MiguelB
+	DEF055301 - ROFSBUILD, COREIMAGE keyword: problem with single-char files/directories 
+
+Version 2.00.536
+===========================
+(Made by Bala, 22/02/2005)
+1) Bala
+	PREQ1027 Submission of RVCT 2.2 Run-Time ABI Compliance to MCL
+
+Version 2.00.535
+===========================
+(Made by Dusko, 21/02/2005)
+
+1)	BalaT
+	DEF051265 Problems debugging .cia files in ARMV5 builds.
+
+Version 2.00.534
+===========================
+(Made by Dusko, 19/01/2005)
+
+1)	Dusko
+	DEF052809 - GENSTUB ERROR: can't open output file....
+
+Version 2.00.533
+===========================
+(Made by Dusko, 23/11/2004)
+
+1)	BalaT
+	1) DEF051128 - armv5 library build in parallel cause conflicts
+
+Version 2.00.532
+===========================
+(Made by KamranN, 11/11/2004)
+
+1)	KamranN
+	1)	Fix for defect DEF051421  Problems with binary search in ROFS  
+
+Version 2.00.531
+===========================
+(Made by Dusko, 08/10/2004)
+
+1)	BalaT
+	1) DEF047934 - ROMBUILD:EXE corrupts ROM directory of an extension ROM 
+
+Version 2.00.530
+===========================
+(Made by Dusko, 04/10/2004)
+
+1)	BalaT
+    1.	Fix for DEF046271 - EVALID cannot cope with differing temp paths present in some ARMV5 .lib files.
+
+Patch to Version 2.00.529
+===========================
+(Made by ???, ??/??/2004)
+
+1.	JonathanM
+	1.	Fix for -dump option in PETRAN.
+
+Patch to Version 2.00.529
+===========================
+(Made by MichaelP, 27/08/2004)
+
+1.	JonathanM
+	1.	Defect Fix: DEF048051 - ROMBUILD can when PlatSecEnforceSysBin is ON
+
+
+Version 2.00.529
+===========================
+(Made by KuldipN, 25/08/2004)
+
+1.	NaheedA
+	1.  DEF047579 - petran fails to report a corrupted input file.
+	2.  DEF046271 - EVALID cannot cope with differing temp paths present in some ARMV5 .lib files
+
+Patch to Version 2.00.528
+===========================
+(Made by JonathanM, 19/08/2004)
+
+1.	JonathanM
+	1.	Defect Fix: DEF048015 - [System Build] ROMs failed to build for MCL 03344 8.1b/9.0
+
+Version 2.00.528
+===========================
+(Made by DjordjeK, 18/08/2004)
+
+1.	JonathanM
+	1.	Added -dump option to PETRAN and ELFTRAN to select what information should
+		be displayed about an image file. This takes a string argument consisting
+		of letters to select the information to be dumped:
+			h	All header info
+			s	Platform Security info
+			c	Code section
+			d	Data section
+			e	Exports
+			i	Imports
+		These letters can be used in any combinations, e.g. "PETRAN -dump ie foo.exe"
+		will show all Imports and Exports of FOO.EXE
+
+Version 2.00.527
+===========================
+(Made by JonathanM, 26/07/2004)
+
+1.	JonathanM
+	1.	Added PlatSecEnforceSysBin setting to ROMBUILD which forces all binary files to
+		be placed under the \sys\bin\ directory.
+		Part of Yankee,GT0217,MS3.1.4 PS6.3.2 Ignore path information for binary files
+		within ROM build and loader.
+		
+Version 2.00.526
+===========================
+(Made by JonathanM, 26/05/2004)
+
+1.	DennisM
+	1.	Fixed defect DEF041434 EKA2 ROMBUILD can't build extension ROMs
+	2.	ROMBUILD now checks that kernel side code doesn't link to user side
+		code, and vice-versa.
+
+Version 2.00.525
+================
+Made by Dusko, 18/05/2004
+
+1) Dusko
+	1) Fix for DEF045146  EVALID does not correctly handle ARMV5 lib files or RVCT .MAP files.
+
+Version 2.00.524
+================
+Made by JonC, 29/04/2004
+
+1) Jon
+	Fixes for:
+	1) DEF044567 gendirective obtains ELF section header data incorrectly
+	2) DEF044048 RVCT version of DEF2DLL camplains about DLLs not having exports 
+
+Version 2.00.523
+===========================
+(Made by JonathanM, 19/03/2004)
+
+1.	JonathanM
+	1.	Implemented the requirements:
+		REQ2632 - Configurability of the enforcement of capabilities
+		REQ2633 - Security violation diagnostic
+		REQ3142 - Associate Platform Security information with an executable.
+		See /cedar/generic/base/documentation/Base_How_To_Configure_Platform_Security_Settings.doc
+
+Version 2.00.522
+===========================
+(Made by JonathanM, 26/02/2004)
+
+1)	JonathanM
+	1)	Modifications made for implementation of
+		Change Request JDOD-5VUJ7F - Change in executable format of EKA2 binaries.
+	2)	Tools now use the sytax "cap1+cap2+cap3" to specify a named set of capabilities
+		(Rather than specifying a single hexadecimal number.)
+	3)	Added three new keywords to ROMBUILD:
+			PlatSecEnforcement
+			PlatSecDiagnostics
+			PlatSecDiasabledCaps cap1+cap2+cap3
+		these are used for specifying Platform Security settings which are then placed
+		in the ROM Header.
+
+Version 1.00.521
+================
+Made by DuskoJ, 16/02/2004
+
+1) Dusko
+	1) Fix for DEF042440 - elfdump creates a new file with zero length.
+
+
+Version 2.01.520
+================
+Made by AndrewJ, 13/02/2004
+
+1) StephanGu
+	Implemented CLCT-5VEK4P - "Binary search in ROFS 
+	together with 'expanding ROFS entries with UIDs'".
+	Changed Rofsbuild to provide a sorted array of offsets
+	in order to allow the file system to perform binary search
+	through the image.  Also expended the TRofsEntry structure
+	to include a copy of the file UID data.
+
+
+Version 2.01.519
+================
+Made by DuskoJ, 30/01/2004
+
+1) Jon
+	1) Fix for - DEF040324 PETRAN access violation whilst converting THUMB build EXEDLL
+	   (Further amendment).
+
+Version 2.01.518
+================
+Made by DuskoJ, 22/01/2004
+
+1) Kuldip
+	1) Fix for DEF40965 Changes to stop overwriting readonly attribute for directories.
+
+
+Version 2.01.517
+================
+Made by DuskoJ, 05/01/2004
+
+1) Kuldip
+	Fix for DEF039055  "Change in behaviour for 0 length files"
+
+Version 2.01.516
+================
+Made by DuskoJ, 19/12/2003
+
+1) Dusko
+	1)	fix for DEF039365 - Petran ignores -fixed keyword	
+
+
+Version 2.01.515
+================
+Made by Dusko, 17/12/2003
+
+1. Kuldip
+	1)	REQ1733, A3.2 Improved Command Line Build Tools
+        ROFSBUILD ROM flexing, Automatic sizing behaviour
+		Automatic XIP-extension OBEYFILE, header generation
+
+Version 2.01.514
+================
+Made by Dusko, 24/11/2003
+
+1. Dusko
+	1)	DEF039411  pediff does not ignore the header CRC 
+		File changed pediff.cpp
+
+Version 2.01.513
+================
+Made by Dusko, 03/11/2003
+
+1. Dusko
+	1.	fix for DEF039536 Non existing files referenced in  Tools_e32tools.mrp...
+
+
+1) William
+	1)	Added PE_DUMP to support the new EVALID.
+
+Version 2.01.512
+================
+Made by Dusko, 10/10/2003
+
+1. Dusko
+	1.	Zephyr,PRO0085,REQ1663, Remove dependencies on MSDEV	
+	  	Changes to BIN2COFF and  WVECONV in order to build with CW
+
+
+Version 2.01.511
+================
+Made by Dusko, 02/10/2003
+
+1. Dusko
+	1.	fix for DEF037065 Problem with error message from uidcrc
+
+Version 2.01.510
+================
+
+Made by Dennis, 24/09/2003
+
+1. Dennis
+	1.	ROMBUILD adds sorted offsets to directory structures to enable binary
+		searching of the ROM file system.
+	2.	Implemented CR ATHE-5PZEAU (Add Version Numbers to Symbian OS Executables).
+
+Version 1.00.505
+================
+Made by DuskoJ, 22/08/2003
+
+1) Morgan
+	Ported ROFSBUILD extension support from beech
+	1) 	Added ROFSBUILD extension support.  Start a ROFS extension with obey file 
+		commands
+			extensionrofs = <filename>
+			rofssize = <size>
+		Added support for ALIASing, HIDEing and RENAMEing.  Semantics and syntax
+		for these commands are the same as ROMBUILD.
+		Core image and extension can be joined together with 
+			tools\e32tools\rombuild\addextensions.pl
+		Added TRofsExtensionHeader to ROFS.H
+		Padding, Alignment and Repro assumptions: 
+		The extension assumes it will be added TRofsHeader::iMaxSize bytes
+		after the start of the core image.  It is assumed the max size of the core
+		image will be aligned appropriately for the underlying ROM device.
+		Core image has signature "ROFS" at offset 0, extension has signature
+		"ROFx" at offset 0 into extension (= iMaxSize after start of core image).
+
+2) Morgan
+	1)	Added rofsbuild\dumpdirs.pl - utility for dumping the ROFS directory
+		structure.
+	2)	Ported ROFSBUILD executable compression from beech
+
+3) Dusko	Changes to a number of e32tools components in order to build cleanly with CodeWarrior
+
+
+Version 1.00.504
+================
+Made by DuskoJ, 25/07/2003
+
+1. Jon
+	1. Fixed DEF036679 by adding copyright statements where appropriate.
+
+
+Version 2.00.503
+================
+
+1) Morgan
+	1) Removed ROMBUILD build warning
+
+Version 2.00.503
+================
+
+1) Dennis
+	
+	ROMBUILD changes:
+
+	1)	'kernelstackaddress' keyword removed. This is now always calculated by
+		ROMBUILD.
+	2)	Address allocation strategy modified. The initial stack is now placed
+		immediately after the kernel .data/.bss area. The kernel heap follows
+		the initial stack (as before). In the moving model, fixed process data
+		chunks are placed after the kernel heap (on chunk boundaries).
+	3)	TRomHeader::iKernStackAddress replaced with TRomHeader::iKernelLimit,
+		which gives the end of the kernel heap rounded up to a chunk boundary
+		except on the moving memory model where it is advanced past the space
+		reserved for fixed process data chunks.
+
+
+Version 2.00.502
+================
+
+1) Dennis
+	1)	Pulled out general E32Image file handling code into e32tools/e32image/...
+		directories. This includes compression/decompression and all stuff which
+		doesn't require	the native PE or ELF file.
+	2)	Merged the two versions of ROMBUILD. ROMBUILD.EXE now accepts E32Image
+		files derived from either PE or ELF. It no longer accepts the native
+		PE/ELF files directly. XIPRMBLD.EXE is no longer built.
+	3)	Added a special instruction (TST PC, #0) to the beginning of all EKA2
+		entry points. This is detected by PETRAN/ELFTRAN and the file marked as
+		having an EKA2 style entry point. The ELF-derived and JFormat flags have
+		been generalised into header format, import format and ABI fields. An
+		entry point type field has been added to distinguish EKA1 and EKA2 entry
+		points.
+	4)	Add 'nowrapper' keyword to ROMBUILD. If specified in OBY file it causes
+		the 256 byte wrapper to be omitted. This setting can still be overridden
+		on the command line.
+
+
+
+======================
+ELFDUMP version 1.0.0
+1) Dusko
+     1) Adding elfdump.cpp. Elfdump is required to be a standalone program     
+    	which can present an ELF object file in a form suitable for use with 
+    	EVALID. It prints hex dumps of relevant sections, directive section as 
+    	text and relocation information showing the symbol the name and of the 
+    	section in which the relocation occurs.
+
+Version 1.00.501
+================
+EKA2 Tools
+
+1) RobertJ
+	1) Support for compressed executables introduced. Source code for the compression
+	& decompression is in petran\szip. Changed PEDUMP to dump compressed executables
+	added -compress & -nocompress options to PETRAN
+	2) Bumped version number of written executables to 1.10
+	3) Added a new format bit to iFlags JFormat (Jetstream format)
+
+Version 1.00.500
+================
+EKA2 Tools
+
+1) Dennis
+	1) Added support for the x86 development target to PETRAN
+	2) Added various values to the ROM header for EKA2 in ROMBUILD
+2) William
+	1) Added -capability <mask> option to PETRAN. There isn't yet an iCapability field in the
+	   E32ImageHeader, but everything else is ready to go.
+
+
+================
+ROMBUILD version 2.05
+
+1) William
+	1)	Fixed defect ROS-52XF6E "ROMBUILD produces incorrect S-Record checksums" by getting the length
+		right (actually by checksumming the bytes we write instead of calculating the values twice).
+	2)	Disable the 3-byte address form of S-Record with a #define, since it upsets some external
+		tools and only benefitted serial download to M*Core.
+	3)	Fixed defect ROS-52ZED7 "ROMBUILD crashes if section 1 overflows in 2 section ROMs" by
+		checking for overflows in the right place.
+	4)	Made verification failure use Print(EError, ...) in all cases, so that it will cause a 
+		ROMBUILD failure rather than just a small complaint at the end of the log file.
+	5)	Extend checkstubs.pl to handle the R3UNUSED Thumb stubs, and update stubs.lst
+
+Todo
+handle section 1 DLLs linking to section 2 DLLs so that section 2 can be replaced
+respect the E32Image flags for dll static data and called entrypoints 
+			
+
+2) Chris
+	1)	Updated romimage.rtf to remove screensize keyword
+
+3) Nicolas (work done as part of CR JPAR-54XMZD)
+	1)	Added new keyword: DEBUGPORT.  It takes a numeric argument
+		which is a magic cookie as far as rombuild is concerned and
+		is stored in the ROM header for interpretation by the
+		kernel and bootstrap.  The default value is -1.
+	2)	Updated romimage.rtf to include DEBUGPORT.	
+
+
+================
+ROMBUILD version 2.04
+
+1) Nicolas
+	1)  Fixed bug where EPOC crashes during boot if there is a non-empty
+	    area after an empty one in the relocation table.
+	2)  Modified the way the kernel extensions list is built to
+	    ensure the extensions are always in the same order in the
+	    list as in the obey file even when some extensions are in
+	    areas and other aren't.  This is necessary because the
+	    kernel extension ordering in the obey file is important
+	    (for example an extension registering a power handler
+	    *must* be loaded after the extension that loads the power
+	    model).
+	3)  Fixed bug in AreaSet::AddArea() (overlap was not detected
+	    when an existing area is embedded in the new one).
+	4)  Overlap unit tests updated.
+	5)	Fixed bug in TDllExportInfo ctor: The ptr to the export directory in
+	  	the ROM buffer was wrong when the file was relocated to a non-default
+	  	area (iRunAddress / iImageAddr mismatch).
+
+
+================
+ROMBUILD version 2.03
+
+1) William
+	1)  Set the default srecordbase to zero, and remove the srecordbase validation.
+	2)  Added "data-align" attribute, and used it in the calculation of dataOffset for
+	    things sharing the SvData. It's not a great name, but it will do for now...
+	3)  Added "KeepIAT" attribute, which builds an old-style Import Address Table instead
+	    of pointing the stubs directly at the export data.  NB. this won't work for
+	    section 1 DLLs, because I haven't reinstated the machinery for putting the IAT into
+	    the second section.
+	4)  Fix defect CLE-4ZEJBB "rom building: fatal error when file to hide isn't found" by
+	    dealing with (aKeyword==EKeywordHide) before testing for !existingFile, and issuing
+	    a warning if the existing file wasn't found.
+	5)  Export checkstubs.pl to \epoc32\rom\tools
+
+---------------------
+ROMBUILD version 2.02
+
+1) Nicolas
+
+	1) ROMBUILD: Introduced new area syntax (incompatible with the existing
+       scheme):
+
+		a) The "area <name> <start> <size>" statement declares an area
+		(there is no need to declare the default ROM area).
+
+		b) The "area=<name>" file attribute relocates individual files to
+		the designated area.
+
+		c) When invoking rombuild with -s, a summary of the free and used
+		space in each area is printed.
+
+		d) Areas can be used only in the first section of a sectioned ROM
+		and are forbidden in extension ROMs.
+
+		e) It is forbidden to patch a relocated file.
+
+	2) ROMBUILD: Introduced classes Area and AreaSet and associated
+       iterators to replace all the existing dynamic arrays and indexes
+       used to store the area-related state.  Unit tests for these are
+       built using r_t_areaset.mmp.  Refactored existing code (notably
+       E32Rom::LayoutRom()) to use those new classes.
+
+	3) ROMBUILD: Moved global variables from rombuild.cpp to r_global.cpp
+       to allow build of r_t_areaset.exe.  Made static the globals which
+       were used only in rombuild.cpp.
+
+	4) ROMBUILD: Merged TAddressSet into TAddressRange.  Renamed every
+       "i.*Set" variable to either "i.*Range" or "i.*Section" (previously
+       existing "i.*Section" variables have been suffixed with "Number").
+
+	5) ROMBUILD: Updated version number to 2.02.
+
+	6) HOST: Turned the various overloads of Val() into a template
+       function.
+
+---------------------
+ROMBUILD version 2.01
+
+1) William
+	1)  Fixed bug in ParseArea() which reused the area address as the area length
+	2)  Allow for executables generated before GCC 530 by changing the assertion about 
+	    unexpected data. If it looks as though the rdata is after the IAT, then the whole
+	    of the E32ImageFile text area is included in the ROM.
+	3)  The rounding up for the ROM size to a multiple of a megabyte must not exceed the
+	    originally specified size.
+	4)  Increased the ROMBUILD version to 2.01
+
+Version 1.00.174
+================
+Made by William, 23/03/2001
+
+1) William
+	1)  Removed the old .ipr files associated with the predecessor to DISTRIBUTION.TXT
+	2)  Moved ROMBUILD.MMP into the ROMBUILD directory
+	3)  Gave ROMBUILD it's own major and minor version numbers - now 2.0
+	4)  Moved the collapsing routines into ROMBUILD\R_COLLAPSE.CPP
+	5)  Substantial rework of the way that the E32Image files are put into the ROM: it's now
+	    almost the case that the ROM layout is established before copying any data. The layout
+	    is expressed by setting up TAddressRange and TImageSection values in the TRomBuilderEntry,
+	    and the rest of the relocation and copying to the ROM image follows from those values.
+	6)  Change of approach on relocation: instead of relocating the file contents after copying
+	    into the ROM image, do the relocation beforehand. This allows the relocation to operate on
+	    a simple fixed layout (the one which PETRAN set up), and frees the ROM layout to be
+	    entirely different.
+	7)  Unified all the various ROM flavours: in particular the "areas" support is part of the
+	    normal layout process. The use of TAddressSets and their derived forms makes this
+	    pretty painless.
+	8)  Removed the Import Address Tables, saving ~240K in a Quartz 6.1 ROM. The import stubs
+	    are fixed up to point directly into the export directory for the relevant DLL. In two 
+	    section ROMs the export directories are now placed at the start of the upper section 
+	    to support patching: this was previously done using the import address tables.
+	9)  Various special case handling for the Primary has been reworked using generic support.
+	    In particular the primary now gets a default code alignment of 4K, which allows the 
+	    gap to be occupied by other files if the obey file is suitably arranged.
+	10) Area relocation is more pervasive than before. The import stubs in relocated executable
+	    no longer refer back to the unrelocated original contents of the area.
+	11) The sizes of the DLL reference tables are now reported in the log.
+	12) Fixed a bug which caused ROMBUILD to crash if a file was marked as "patched" in a 
+	    two section ROM.
+	13) Size information in the ROM is more consistent: the size in the ROM filesystem is always
+	    the length of the contiguous section beginning at the given address, and the size summary
+	    in the log file reports the SizeInRom() information for the file, which should always
+	    reflect the real cost in ROM of the file regardless of layout.
+
+Version 1.00.173
+================
+Made by Morgan, 08/03/2001
+
+1) Morgan
+	1)	Fixed ROMBUILD to accept DLLs with no imports and DLLs with no exports
+
+
+Version 1.00.172
+================
+Made by William, 07/12/2000
+
+1) William
+	1)  Introduced ROMBUILD support for extension ROMs, the deliverable from project PR0027.
+	    Lots of churn, but the key new data structure is the TRomNode which separates the
+	    ROM directory structure information from the individual files (TRomBuilderEntry). The
+	    TRomNodes handle the DLL name matching and are used to drive the multiple-variant clever
+	    directory structure operations.
+	2)  Reworked the ROMBUILD parsing strategy to remove the need for "files=", allowing the
+	    header statements and file statements to be mixed freely in the OBY file.
+	3)  Use the tables which now drive the ROMBUILD parsing to generate the help information.
+	4)  Don't create ROMBUILD.LOG unless processing an OBY file, and put extra useful information
+	    into the log. In particular, print a line include the ROM image name before processing
+	    the files and after writing the ROM image, e.g.
+
+	        Creating Rom image testrom.IMG
+		...
+	        Writing Rom image with repro header to file testrom.IMG
+
+	    Also report the "Writing" line to the screen, as a comfort to the user.
+	5)  Fix ROS-4RJPTK "ROMBUILD checksums are incorrect" by computing the checksum at the 
+	    right stage, and cross check to make sure it's still right when displaying the ROM stats.
+	    ROMs built with this version of ROMBUILD are likely to be different in up to 4 bytes
+	    at offsets 0x1A8 to 0x1AB (0xA8 to 0xAB for images without a REPRO header).
+	6)  Make "unicode" the default, and introduce sensible defaults for various other keywords.
+	7)  Remove the ROMBUILD support for bigendian images (it's still present in the files
+	    shared with PETRAN.
+	8)  Added dumpdirs.pl which prints out the ROM root directory structures.
+	9)  Added addextension.pl which concatenates a kernel ROM and an extension ROM, making a 
+	    combined image suitable for use with Brutus.
+	10) Try harder to continue reporting errors rather than stopping immediately. In particular,
+	    report all of the unresolved DLL linkages rather than just the first one.
+	11) Introduce new keywords "hide", "alias" and "rename" to manipulate the directory structure.
+	12) Added romimage.rtf documentation (from the BPK, but somewhat edited) and export it to
+	    \epoc32\engdoc\e32tools
+
+
+Version 1.00.171
+================
+Made by Nicolas, 19/10/2000
+
+1) William
+	1)  Rework internals of ROMBUILD to remove arrays indexed by file number.
+	    TRomBuilderEntry is now derived from E32ImageFile, and the various arrays
+	    have become member data in the associated TRomBuilderEntry - OO, dontcha just love it!
+	2)  Added -coff-header option, which could remove the need for bin2coff
+	3)  Use the .idata information to get the DLL ordinals, not the IAT. 
+	    This is preparation for the IAT removal idea, which involves turning the IAT into
+	    a table of pointers back to the associated stubs.
+	4)  Added a range check to TRomBuilderEntry::AddressOfOrdinal
+	5)  Added documentation about various forms of import stub, and checkstubs.pl which
+	    scans all of the stubs in a ROM to check that they lead to a function of the
+	    correct name.
+	6)  Introduced TAddressSet for recording the various addresses associated with
+	    code in a ROM (address of ROMBUILD.EXE working copy, address in ROM, execution address).
+	    Currently used for handling ImportAddressTable and DllRefTable and seems to work in
+	    a two-section Brutus ROM.
+	7)  Partial fix for EDNRFID-4J6DV3 "Corrupt reloc table generated"
+	    Allow for the possibility that there is only .bss with no .data when applying the
+	    heuristic for relocs that don't point into any known section.
+	    Fix printf format specifier typo by changing %0x8 -> %08x
+	8)  Added a verbose option to W32REPRO
+
+
+Version 1.00.170
+================
+Made by Dennis, 13/09/2000
+
+1) William
+	1)  Dust off the S-Record support in ROMBUILD
+	    Use the full 78-bytes available per line, and add support for the
+	    3-byte address form, since this is beneficial to M*Core Cogent.
+	2)  Use "srecordfilename=*" to mean "append .srec to romname and use that"
+	    Same approach for "romnameodd=*" and "romnameeven=*" filenames.
+	3)  Set the RomHeader iSize to be iSizeUsed rounded up to a megabyte. This is
+	    particularly beneficial on platforms which RAM-load a ROM image (Brutus, Cogent)
+	    because it allows the bootstrap to use only the amount of RAM really needed
+	    for the ROM image.
+	4)  Add "hide" keyword to ROMBUILD, as requested by a licensee. This stops the
+	    specified file from being included in the ROM directory, but doesn't stop other
+	    ROM files from linking to the hidden file. A consequence of hiding a DLL is that
+	    it can't be dynamically loaded, which means that you can't hide kernel extensions.
+
+
+Version 1.00.156
+================
+Made by Morgan, 5/7/2000
+
+1) Anon
+	1) Changes to ETOUCH
+	==== //EPOC/development/base/6.0/e32tools/ETOUCH/ETOUCH.CPP#1
+	@@ -3,6 +3,10 @@
+	 // Copyright (c) 1996-1999 Symbian Ltd.  All rights reserved.
+	 //
+
+	+#if defined(__VC32__)
+	+#pragma warning(disable : 4710)        // function '...' not expanded
+	+#endif
+	+
+
+
+Version 1.00.155
+================
+Made by Dennis 22-06-2000.
+
+1)	Dennis
+	1)	Modified W32REPRO so that the -HEX option only makes it receive in hex.
+		It always transmits in base 10. This is so it works with REPROC.
+	2)	Fixed bug in ROMBUILD - it didn't like files with no imports.
+
+Version 1.00.154
+================
+(Made by Alastair, 10.3.2000)
+
+1)	William
+	1)	Added M*Core support
+		Basically just another PE magic number and another TCpu code.
+
+Version 1.00.153
+================
+(Made by Pete, 24/02/2000)
+
+1)	William
+	1)	Updated PETRAN to report exports with value 0 as
+
+			WARNING: No export specified for ordinal 62
+
+		and promoted the non-zero exports from an unknown section to be errors.
+	2)	Added more information to the warning about failure to identify a section for relocation,
+		just in case it ever happens...
+
+2)	Simon
+	1)	Added bin2coff, a utility to add a coff header to a binary
+	  	image. Mainly for use with the cogent smartfirmware
+
+Version 1.00.152
+================
+(Made by Dennis, 19/01/2000)
+
+1)	William
+	1)	Updated W32REPRO usage statement to remove misleading limit on the baud rate
+		The baud rate is actually passed directly to the Win32 comms device, so it should
+		be possible to specify any baud rate supported by the device.
+	2)	Updated W32REPRO to add a -RAW option for use with Brutus REPROB (and others).
+		This tells W32REPRO not to expect a 256-byte header on the image, but it will
+		still pretend that there is one, as expected by the existing REPRO code.
+	3)	Updated W32REPRO to a -BOOT <boostrap_image> and -HEX options, to support
+		the Cirrus Logic board. The bootstrap is sent at 9600 baud before starting the
+		normal REPRO protocol, and -HEX changes the protocol to use base 16 rather than
+		base 10 for numbers transmitted between W32REPRO and the other end.
+	4)	Added W32REPRO protocol support for a new command 'D' which tells W32REPRO to
+		disconnect after a successful transfer: REPROB could usefully be extended to
+		send this command...
+
+2)	Morgan
+	1)	Fixed ROMBUILD so it gives appropriate errors if passed an empty file
+	2)	ROMBUILD.LOG reports inclusion of 256 ROM repro header (Defect EDN147097)
+	3)	Fixed EDN580686 Rombuild is not very tolerant
+	4)	Fixed EDN210727 PEDIFF returns stupid result codes
+		PEDIFF now returns 0 for identical files, and 2 for different files
+	5)	Improved PETRAN dump output (Fixed EDNGLAY-463LNN)
+
+
+Version 1.00.151
+================
+(Made by Morgan, 3/12/99)
+
+1)	Alastair
+	1)	Created a new utility, ERUNTEST.EXE, which will take a batch file
+		listing tests as generated by ABLD and run each test in turn, checking
+		whether each test has succeeded or not by checking the return value from
+		the process and also checking output to the EPOCWIND.OUT file in the
+		temporary directory.  ERUNTEST.EXE logs output to standard output.
+		Obviously this utility will only run WINS/WINC tests.  It must be invoked
+		from the directory in which the test executables reside.
+
+2)	Morgan
+	1)	Fixed some warnings
+
+
+Version 1.00.150
+================
+(Made by Morgan, 27/9/99)
+
+1)	Alastair
+	1)	Created new directory COLTAB and added COLTAB.CPP, BASEKEYS.TXT,
+		COMPKEYS.TXT and README.TXT.  COLTAB comes from Graham Asher, and is a
+		tool for writing the collation tables in COLLATE.CPP.  README.TXT
+		contains details of the URL from which data files BASEKEYS.TXT and
+		COMPKEYS.TXT were sourced.  Type COLTAB without any parameters for help,
+		and/or read the header in COLTAB.CPP.  Console APP COLTAB.EXE will be
+		built into \EPOC32\Tools\.
+
+2)	Malcolm
+	1)	Added code to allow the kernel debug mask to be set via the ROM.OBY
+		file via the new KERNELTRACE keyword.
+
+3)	Morgan
+	1)	ROMBUILD internal directory structure is now sorted wrt a unique
+		identifier for each Dir.  This (hopefully) fixes the reproducability
+		problems ("drifting-directories") experienced when building identical
+		Roms in different NT environments.
+
+
+Version 1.00.125
+================
+(Made by Morgan, 26/8/99)
+
+1)	Dennis
+	1)	Added "defaultstackreserve" keyword. The argument to this keyword is
+		added to the combined size of .data and .bss to determine the address
+		space to reserve for the $DAT chunk of a 'fixed' process. The value
+		defaults to zero for compatibility with previous versions.
+		Added "stackreserve" keyword to override the default setting on a
+		per-file basis.
+
+
+Version 1.00.124
+================
+(Made by Alastair, 2nd August 1999)
+
+1)	Jonathan
+	1)	Removed MAKSYM - moved to e32toolp.
+
+
+Version 1.00.123
+================
+(Made by Kal Patel, 22 July 1999)
+
+1) Morgan
+	1)	New ROMMASK.  Added a -verbose flag for logging, and added a -no-header
+		for Roms with no Epoc header.
+
+2) Malcolm
+   
+    1) Added Area support to ROMBUILD for Roxette.  This allows the
+       code to be fixed up to execute outside the rom where it's stored.
+       Relocation info is written into the rom and the bootstrap uses
+       this to copy the info out to its final location.  Any file can 
+       be in any arbitrary area.  This is only enabled in
+       singleprocess mode, since the same effect can be achieved with
+       an MMU on a real system.
+
+	   This is enabled by placing a "areas=<num>" line in the first
+	   section of the .oby file.  Then, in the files= section, the
+	   next tranche of files can be sent to another area with a
+	   directive like "area 0x81000000 0x100000" where the first value 
+	   is the address and the next the length. Up to <num> area lines
+	   can be in the file section.
+
+	   A relocation table is placed in ROM for the bootstrap.  Its
+	   address is stored in the romheader info that rombuild uses.
+	   The table is a list of <length> <src> <dest> triples, ending
+	   with a <0,0,0> tuple.
+
+	   Note that any bootstrap that uses this should not process a
+	   relocation table address of 0, as this maintains backwards
+	   compatability with old rombuilds which will put zero in the
+	   address location.
+
+3)	Alastair
+	1)	Removed all .DSP and .MAK files, now that makefiles are generated.
+	2)	Fixed minor typo in W32Repro.
+
+
+Version 1.00.122
+================
+(Made by Alastair, 12.7.99)
+
+1) Alastair
+	1)	Added fetcher definition file, E32TOOLS.FTC, to the group directory.
+	2)	Added William's new version of E32UID.CPP which no longer requires
+		WINDOWS.H.
+	3)	Added William's new UIDCRC.EXE, which provides a simple way to calculate
+		the checksum:
+
+			uidcrc <uid1> <uid2> <uid3> [<outputfile>]
+
+		This reads the three uids (using strtoul, so decimal and 0x9999 hex are 
+		found), computes the checksum, and either prints the 4 hex values to standard
+		output or creates <outputfile> as the 32 byte sequence which is the specified
+		UIDs and checksum in little-endian byte order.
+
+
+Version 1.00.121
+================
+(Made by Alastair, 16.6.99)
+
+1)	Alastair
+	1)	Fixed EDN459831 "Wveconv help is out of date" .
+	2)	Removed MAKTRAN, DEFMAKE and DEFTOOL.
+	3)	Converted all projects to MAKMAKE building for the new TOOLS platform.
+	4)	Changed zip of releasables onto the network - this is now called
+		TOOLS.<ver> rather than E32TOOLS.<ver>.  It also contains full paths to
+		the releasables so make sure you're in the root of your EPOC drive
+		before calling, say, "getrel e32tools tools 121".
+	5)	Updated MNT.CMD in various ways, including adding an MNT CHECKREL.
+	6)	Added dopcvs.pl and lock.pl to GROUP directory for use with MNT.BAT.
+
+
+Version 1.00.120
+================
+(Made by Morgan, 30th March 1999)
+
+1)	Morgan
+	1)	Fixed EDNGBON-46BQK4, "ROMBUILD "patched" keyword is broken".
+		(merged in from ER5 release E32TOOLS 110)
+	2)	Left a gap in the build numbers for ER5 maintenance releases
+	3)	Introduced a new version of ROMMASK.EXE.  The syntax has changed
+		from previous versions.  Type "ROMMASK" to see the new syntax.
+		For example, to produce a 10Meg image split into 8 and 2,
+		type the following:     
+rommask -rom p2rom.img -output rom.img -log rom.log -size 10 -section 8 -section 2
+		(You can leave off the final -section 2, and ROMMASK will do the
+		calculations for you.)
+		The output of Rommask will be "rom.log", and the 2 mask files
+		"rom.img" and "rom.im2"
+		ROMMASK still expects the image to contain a Psion 256byte header.
+
+
+Version 1.00.100
+================
+(Made by Morgan, 16th February 1999
+
+1)	Morgan
+	1)	Added the keyword 'srecordbase' to change the base address of
+		the motorola srecord output file.  (Defaults to address 0x0000)
+	2)	Fixed srecord output for big and little endians.
+	3)	Removed unused dependencies from MNT GETCOMPS
+
+
+Version 1.00.099
+================
+(Made by Jonathan, 8th February 1999)
+
+1)	Alastair
+	1)	Edited PETRAN.MAK so that sources depend upon
+	  	\Epoc32\Include\E32uid.h rather than ..\E32uid\E32uid.h. This
+		change should complete the fixing of bug EDN057832 "E32Tools won't
+		rebuild on my PC".
+
+2)	Jonathan
+	1)	Fixed ROMBUILD defect EDN853437 "Dual Boot ROM does not function on
+	  	Series 5" by applying Dennis' fix to fix up data as well as
+	  	executables in dual-boot images.
+
+
+Version 1.00.098
+================
+(Made by Jonathan, 1st February 1999)
+
+1)	Petteri
+	1)	Applied boilerplate copyright to sources.
+
+2)	Jonathan
+	1)	Fixed copyright message in executables.
+	2)	Removed odbc32.lib and odbccp32.lib from all .DSP and .MAK files
+	  	since these libraries are neither required nor always installed.
+
+
+Version 1.00.97
+===============
+(Made by Alastair, 28th January 1999)
+
+1)	Alastair
+	GENERAL
+	1)	Created and added VC5 .DSP files for all projects for debugging.
+	2)	Removed hard-coded drive letters from .DSP files.
+	3)	Re-generated makefiles from .DSP files.
+	4)	Reinstated E32UID directory containing files E32UID.CPP and STDAFX.H
+		required for building ROMBUILD, PEDIFF and PETRAN.
+	5)	Replaced hard-coded instances of 'R:' in MNT.CMD with '%s%'.
+	MAKSYM
+	1)	Added proper handling of two functions appearing at the same address in
+		a ROM.
+	2)	Removed an unnecessary destructor to prevent allocated memory being
+		deleted twice.
+	TMAKTRAN
+	1)	Removed MAKTRAN tests.
+	PEIGER, PREPRO
+	1)	Removed these executables.  Previously MNT.CMD attempted to unzip these
+		from S:\ptool\ and then zip them up again in the e32tools release zip
+		file.  Plans are afoot to provide these tools elsewhere, since we no
+		longer have access to S:.
+
+
+Version 1.00.096
+================
+(Made by Morgan, 21st January 1999)
+
+1)	Morgan
+	GENERAL
+	1)	Removed E32UID
+	2)	Converted all makefiles to VC5
+	3)	Built with VC5
+	ROMBUILD
+	4)	Rectified the drifting directory problem.  ROM images can now
+		be reproduced and validated reliably.
+	READTYPE
+	5)	Removed definitions for "true" and "false" so readtype will
+		compile with VC5.
+
+
+Version 0.01.095
+================
+(Made by Alastair, 18th August 1998)
+
+Morgan
+ROMBUILD
+1) Big-endian bug fix
+
+Alastair
+DEFMAKE
+1) Fixed Epoc S/W Problem SW1-141 - 'DEFMAKE adds an "E" to the end of
+   the generated DEF file'
+ROMBUILD
+1) Fixed Bluebell defect SW1-734 - "What do the tools have against August?".
+   A rom time of 08/08/2008 08:08:08 is now acceptable.
+
+
+Version 0.01.094
+================
+(Made by Jonathan, 10th June 1998)
+
+1)	Morgan
+	ROMBUILD
+	1)	Added extra info to log output.
+
+2)	Graham Asher
+	READTYPE
+	1)	New uniflds.txt and unidata2.txt from release 2.1 of the charater
+		database from Unicode Inc. Many additions and corrections have been
+		made. One of them fixes defect SW1-42 (User::UpperCase is wrong for
+		Greek final sigma (03C2) in the Unicode build) in the EPOC32
+		Software Problems database.
+	2)	Changes to readtype.cpp to accommodate the new character categories
+		in unidata2.txt.
+
+Version 0.01.093
+================
+(Made by Morgan, 15th May 1998)
+
+1) Dennis
+    ROMBUILD
+1)	Added support to ROMBUILD for multiple-boot ROMs:
+ a)	Added keywords 'singlekernel' and 'multikernel' to declare whether a
+	single kernel ROM or multiple-kernel ROM is required (defaults to single).
+ b)	Added keyword 'variant' to declare which files define hardware variants;
+	this keyword should be applied to the variant DLL (ECUST.DLL) of each
+	hardware variant to be supported.
+ c)	Added keywords 'extension' and 'device'. These define kernel-mode DLLs
+	which may have global data, the address of which is generated by ROMBUILD.
+	'device' DLLs are simply LDDs or PDDs with global data.
+	'extension' DLLs are not yet supported by E32.
+ d)	Files declared with one of the keywords
+		{primary, file, data, dll, variant, extension, device}
+	may have an additional hardware variant discriminator specified by means
+	of the syntax
+		file[0x05040001]=filename
+	The hardware variant discriminator (HWVD) is an 8-digit hex number whose
+	purpose is to specify which hardware variants the file is relevant to.
+	The top 16 bits indicate which conceptual layer the file belongs to:
+		0100=independent - file is required by all hardware variants
+		xx03=CPU-specific - file is required by all variants with same CPU
+		yyxx=ASIC/variant specific - file is required by all variants with
+			 CPU xx and ASIC yy.
+
+	The bottom 16 bits are only relevant in the last of these three cases.
+	They form a bit mask indicating which specific variants the file is
+	required for. A file declared with the variant keyword must be totally
+	variant-specific, i.e. must have only one bit set in the bit mask.
+	If the HWVD is not specified, a value of 01000000 is assumed, which means
+	that the file appears in all hardware variants.
+
+	Examples (from forthcoming Bluebell/Protea upgrade ROM):
+
+	primary[0504ffff] - kernel for EIGER
+	primary[0706ffff] - kernel for WINDERMERE (different CPU core and ASIC)
+	variant[05040001] - variant DLL for PROTEA
+	variant[07060001] - variant DLL for BLUEBELL v.1
+	variant[07060002] - variant DLL for BLUEBELL v.2 (for illustration)
+
+	Static linkage between files is now restricted by the HWVDs of those
+	files. It is possible for file A to link statically to file B iff
+	{variants V | V requires A} is a subset of {variants V | V requires B}.
+	For the example above, variant[0x05040001] can link to primary[0x0504ffff]
+	but not the other way round.
+
+	It is possible to have two or more files of the same name in the same
+	directory provided that they have HWVDs which are mutually exclusive, so
+	that the two files can never appear on the same machine. The HWVD is used
+	to determine which of the files to use to resolve any static linkage.
+
+ e)	The ROM file system now has multiple root directories and directory trees,
+	one for each hardware variant supported by the ROM. This automatically
+	ensures that F32 only sees the files which are relevant to the hardware
+	on which it is running.
+
+ f) DLLs declared with one of the keywords {variant, device, extension} can
+	have global data (.data and .bss) which will be allocated in the kernel
+	static data chunk after the kernel data itself.
+
+2)	The 'fixed' flag is now propagated through from PETRAN.
+
+3)	The 'kernstackaddress' keyword is now optional - if it is not present in
+	the obey file, ROMBUILD uses a default value of 
+	kerneldataaddress + Round(kernel-mode dataBss size) +
+		Sum over all fixed .EXEs(Round(DataBss size of .EXE file))
+	where Round(x) rounds up to the PDE size (1Mb on ARM).
+
+
+Version 0.01.092
+================
+(Made by Morgan, 25th February 1998)
+
+ROMBUILD
+1) Fixed the 'code-align' file attribute
+2) Forced the image file size to a multiple of 4k for the good of Rome.
+
+
+Version 0.01.091
+================
+(Made by Alastair, 18th February 1998)
+
+Removed MAKMAKE and BLDMAKE - these tools are now part of
+new project E32TOOLP.
+
+
+Version 0.01.090
+================
+(Made by Morgan, 13th February 1998)
+
+ROMBUILD
+1)	Added support for 'fix'ing LDDs with global static data in Rom.
+2)	The 'file=' specifier now honours the KNoCallEntryPoints flag in
+	the image header (as set by PETRAN).  This means all 'dll='
+	specifiers should be changed to 'file=' and MAKMAKE used to
+	control the entrypoint behaviour with the CALLDLLENTRYPOINTS
+	keyword.
+3)	Added a '-no-header' switch to suppress the Rom loader header.
+
+
+Version 0.01.089
+================
+(Made by Alastair, 9th February 1998)
+
+DEFMAKE
+1)  Changed defmake.exe so that it processes freeze files without
+    carraige returns at the end of the last line correctly. 
+    Fixes SW1-803.
+2)  Put in warning for unfrozen exports.
+
+MAKMAKE
+1)  Changed the warning generated if parameters appear with the
+    NOSTRICTDEF keyword so that it doesn't just appear when MAKMAKE
+    is invoked with the -V flag.  The NOSTRICTDEF keyword,
+    if required, should be used in addition to the DEFFILE keyword,
+    not instead of it.
+2)  Intermediate deffiles created by command-line makefiles no
+    longer have the basename extensions, eg D for narrow debug,
+	if the NOSTRICTDEF keyword is specified.	
+2)  Added warning for any SUBPROJECT keyword appearing before a
+    project has been specified with the PROJECT keyword.  This
+    is now necessary because MAKMAKE now stores SUBPROJECT directories
+    as absolute paths rather than paths relative to the PROJECT directory.
+    If a SUBPROJECT statement specifies a directory beginning with a
+    backslash, it will be treated as an absolute directory; otherwise
+    it will be treated as a directory relative to the PROJECT directory,
+    as before.
+3)  Added warnings for the non-existence of SYSTEMINCLUDE, USERINCLUDE,
+    \PROJECT, SUBPROJECT and \PROJECT\SUBPROJECT directories.
+4)  Put in START WINS .. END block option, NOBROWSEINFO, which can
+    be used to stop generation of .SBR and .BSC files for command-line
+    WINS and WINC builds.
+5)  Changed MAKMAKE.BAT so that the help for the batch command "CALL"
+    is no longer produced if MAKMAKE /? is typed.
+6)  Moved all makmake releasables out of \epoc32\tools\makmake into
+    \epoc32\tools.
+7)  Changed MAKMAKE.BAT over to using the -S PERL switch so that the
+    system path is searched for MAKMAKE.PL, then MAKMAKE.PL searches
+    for the modules it depends upon in whichever \epoc32\tools is
+    specified in the system path.  This means that makmake can be
+    installed on one drive and called to operate on .MMP files from
+    another.
+8)  The second UID for targettypes APP, LDD and PDD will now be added
+    if not present.
+9)  Restructured MAKMAKE and moved some functionality into new modules
+    to facilitate code reuse.  MAKMAKE and BLDMAKE now depend upon the
+    following shared modules
+    PARSECOM.PM, E32ENV.PM, E32TVER.PM, MODLOAD.PM, PATHUTL.PM, PREPFILE.PM.
+    MMP.PM and GENUTL.PM are currently only used by MAKMAKE but may be
+    useful for other purposes in the future.
+10)  Renamed MAKPREP.PM MAKDEPS.PM.
+
+
+BLDMAKE
+1)  Added warning that BLDMAKE ALL won't create batchfiles for preparing
+    IDE makefiles.
+  
+
+Version 0.01.088
+================
+(Made by Morgan, 29th January 1998)
+
+MAKMAKE
+1)	Inserted '-bigendian' on the PETRAN command line for BE builds
+
+PETRAN and ROMBUILD
+1)	Added -bigendian switches to both tools
+
+From Simon Lewis
+1)	Added a new file attribute 'code-align' to ROMBUILD
+2)	Added the switches '-align-const-section' and
+	'const-section-address-mask' to PETRAN
+
+
+Version 0.01.087
+================
+(Made by Alastair, 23th January 1998)
+
+MAKMAKE
+1)  Changed paths within created makefiles so that they are relative
+    to the directory where MAKMAKE was invoked rather than relative
+    to the makefile.  If you are using the /D makmake command-line
+    flag and invoking makmake from directory \[project]\group there
+    is therefore no longer a need to change directory to
+    \Epoc32\Make\[platform] before calling NMAKE.
+
+2)  Deffiles created by the build process in the build directories
+    now have the build-variant dependent U, D, and UD suffixes, and
+    are removed by a makmake -clean.
+
+3)  Changed handling of EXEDLL targettypes so that they can export
+    functions under MARM.  MAKMAKE will expect EXEDLL targettypes to
+    be function exporters for MARM if a deffile is specified in the
+    MMP file, otherwise it will make no use of the intermediate deffile
+    created during the build process.  This means that, until a fix for
+    dlltool becomes available from Cygnus, the first time functions are
+    frozen for EXEDLL targettypes for MARM it is necessary to build once,
+    put a deffile statement for MARM in the MMP file, put the intermediate
+    deffile where the MMP deffile statement expects the freeze file to be,
+    and build once again so that the target is frozen by ordinal.
+
+4)  Changed MAKMAKE warnings so they go to STDERR rather than STDOUT.
+
+5)  Added LONGBLDPATH keyword to MAKMAKE which inserts an extra directory
+    into the build path for a project.  The extra directory may be
+    specified as a parameter to the new keyword but will default
+    to the basename of the MMP file if the keyword is specified
+    without a parameter.
+
+6)  Added new TARGETTYPE, LIB, for creating static libraries.  This
+    is not yet implemented for MSVC5.0.  The object file compiled
+    from the first source file specified in the mmpfile is copied
+    into the target directory and given the same basename as the
+    target.  The behaviour for this keyword is not yet finalised.
+
+7)  Added new TARGETTYPE, IMPLIB, for creating import libraries
+    for DLLs with mutual imports.  Specify a new MMP file for
+    one of the DLLs, give the name of the DLL as the argument
+    for the TARGET keyword (so that the .LIB produced contains
+    the right DLL name) and set the TARGETTYPE as IMPLIB.
+    This is not yet implemented for IDE makefiles and the behaviour
+    for this keyword is not yet finalised.
+
+8)  Added handling of Win32 Resource files to command-line WINS
+    and VC4 and VC5 makefiles because the kernel uses one.
+
+9)  Added new MARM MMP file keywords to cater for unusual scenarios
+    START MARM
+    ALLOWDLLDATA // for dlls requiring static data
+	DATALINKADDRESS [address] // for relocation address for dll data
+    DLLNAME [dll basename for linking] // for dlls which are built
+    // as one thing but linked in the ROM as another
+	STACKSIZE // for stack size other than the default
+    END
+
+10) Added new module SARMBE.PM for creating big-endian single-process
+    arm makefiles
+
+11) Implemented more stringent checking of the format of UIDs in mmp files
+    and made sure dlls with null uids link as mydll.dll rather than
+    mydll[00000000].dll for consistency with rombuild.
+
+12) Made all relative paths in VC4 and VC5 makefiles absolute.
+
+BLDMAKE
+1)  Added new perl tool, bldmake, which creates batch files to
+    control the building of E32 and F32.  Type bldmake without
+    any parameters for options.
+
+
+Version 0.01.086
+================
+(Made by Alastair, 5th January 1998)
+
+DEFMAKE
+1)  Added .E32_UID and .rsrc to the list of recognised sections so that,
+    eg, "WARNING: Section '.E32_UID' removed" no longer appears during
+    WINS builds.
+
+MAKMAKE
+1)  Changed cl_arm.pm and cl_win.pm so that makmake -clean will remove
+    resource headers from \Epoc32\Include if a resource file is specified.
+
+Version 0.01.085
+================
+(Made by Alastair, 9th December 1997)
+
+MAKMAKE
+1)  Removed automatic addition of kernel32.lib and libc.lib to list
+    of Win32 libraries for WINC EXE targettypes as this addition is
+    apparently unnecessary.
+
+
+Version 0.01.084
+================
+(Made by Alastair, 9th December 1997)
+
+MAKMAKE
+1)  Changed handling of targettype EXE for WINC, VC4WINC and VC5WINC
+    platforms so that the LINK.EXE flag /subsystem:console is used
+    rather that /subsystem:windows, and kernel32.lib and libc.lib
+    are automatically added to the list of Win32 libraries to be linked
+    to.
+
+2)  Targettypes LDD and PDD makefiles for MSVC IDEs now require the
+    presence of \epoc32\include\lddwins.def and \epoc32\include\pddwins.def
+    respectively.
+
+
+Version 0.01.083
+================
+(Made by Alastair, 20th November 1997)
+
+Some Makmake Bug Fixes
+1)  Makmake invoked with the /CLEAN flag will now erase the autouid
+    object file if the Win32 autouid keyword is used.
+
+2)  Makmake now uses the environmental variable "INCLUDE" rather
+    than "MsDevDir" to decide which standard include directories
+    should be searched for Win32 header files if a project is
+    linking to Win32 libraries, so that the wrong standard
+    include directories aren't searched when creating MSVC5
+    project files.
+    Fixes SW1-698.
+
+3)  Fixed bug caused by CPP inserting a space after expanding
+    macros in .mmp files by taking the space out again.  This was
+    causing problems where, for example, a path specified as
+    "\EPOC32\RELEASE\WINS\APP.DEF" in the .mmp file would become
+    "\EPOC32\RELEASE\WINS \APP.DEF" after preprocessing prior
+    to creating a WINS makefile.  Lower case paths were not
+    affected.
+
+4)  Replaced link.exe flag
+    /EXPORT:?NewApplication@@YAPAVCApaApplication@@XZ,@1,NONAME
+    in VC4 and VC5 makefiles where the targettype is APP with the
+    flag /def:\EPOC32\RELEASE\WINS\APP.DEF, because the former flag
+    failed to ensure that the function in question was exported
+    at ordinal one.  This solution means that if no deffile is
+    specified in the .mmp file for an APP, \EPOC32\RELEASE\WINS\APP.DEF
+    must be present for the project to link.  Command-line Win32
+    makefiles will link properly without the presence of APP.DEF
+    because they use a defmake flag to ensure the function is
+    exported at the right ordinal.
+    Targettypes LDD and PDD will link by name in MSVC until
+    their deffiles are released to
+    \epoc32\release\wins or somewhere else suitable. 
+
+Version 0.01.082
+================
+(Made by Alastair, 12th November 1997)
+
+MAKMAKE
+1)  Added link-libraries and e(dll|exe) object as dependencies of
+    main target.  This cannot be done for MSVC IDE makefiles.
+    Fixes SW1-565.
+
+2)  Added new targettypes LDD and PDD.  A frozen first ordinal export,
+    the respective gate funtion for the targettype, is specified for
+    these targettypes and for targettype APP if no deffile is specified
+    for the project, otherwise the deffile controls the order of
+    exported functions.  This applies for all supported platforms.  Apart
+    from this feature, projects specifying one of these targettypes build
+    in the same way as projects with targettype DLL.
+    Fixes SW1-666.
+
+3)  Changed MAKMAKE help information so that the build version appears and
+    a list of platform choices appears.  This list of platforms is produced
+    by a search of .PM modules in \EPOC32\TOOLS\MAKMAKE for the comment line
+    "# Can call in makmake command line".  If the line is present in the module
+    then the basename of the module is added to the list.  This is a cheap way
+    of producing a list of available platforms while preserving MAKMAKE's
+    extensibility, and doesn't involve the loading of every .PM module and all
+    the modules that each one of those depends on.
+        The module controlling MAKMAKE help is loaded only when required and
+    provides a brief guide to MMP file syntax if makmake is invoked
+	    MAKMAKE /MMP {PLATFORM}
+    If PLATFORM is specified, syntax for the START .. END block relating to
+    the platform is displayed as well as platform-independent MMP syntax.
+    Fixes SW1-653.
+
+4)  The macros "WIN32" and "_WINDOWS" are now only used in compilation by MAKMAKE-
+    generated Win32 makefiles if the project's MMP file states that the project
+    needs to link to Win32 libraries by listing the libraries it needs with the
+    WIN32_LIBRARY keyword in a Win32 START .. END block. 
+    Fixes SW1-652.
+
+5)  New MMP file keyword - OBJECT - is available.  This keyword is intended to
+    be used by projects having access not to the source files but only the compiled
+    code for certain objects.  Specify the basename of the object only.  Created Win32
+    makefiles will expect object <basename>.OBJ to exist in the build directories
+    for a project, while MARM makefiles will look for <basename>.o.  These object
+    files will appear in the dependency list for the main target in command-line
+    makefiles - this is not possible in MSVC IDE makefiles.
+
+6)  Command-line makefiles now contain extra targets MAKEWORK, MAKEWORKDEB,
+    MAKEWORKREL, etc.  The build-specific targets are included in the list of
+    dependencies for the main makefile build-specific target, so that work
+    directories will be automatically created when building with command-line
+    makefiles if these directories do not already exist.  The new targets could
+    also be used to make the work directories for a project with NMAKE
+        e.g.  NMAKE /f <command line makefile> MAKEWORK
+    would create all the makefiles for a project for all builds.
+
+7)  Win32 command line makefiles now generate SBR and BSC browse files for DEBUG
+    builds so that if a DEBUG build of a project has already been done with a Win32
+    command line makefile, subsequent building of the DEBUG build of the project
+    within the MSVC IDE will not recompile everything to generate the browse files.
+
+8)  Added new module MAKPREP.PM to handle everything relating to MAKMAKE's use of
+    \EPOC32\GCC\BIN\CPP.EXE to generate lists of dependencies for source files.
+    This module now identifies missing system and user headers -
+          - if missing system headers have the extension .RSG or .MBG, the header is
+        listed as existing in \EPOC32\INCLUDE, so there is no longer a need for
+        MAKMAKE to generate a dummy resource header in \EPOC32\INCLUDE to fool CPP.
+          - platform modules can specify standard directories to search for missing
+       system headers.  This means, e.g., Win32 makefiles can specify the MSDEV include
+       directory for those projects linking to Win32 libraries.  If the missing system
+       header is found by the module in the standard directory, it will be left out
+       of the dependency list since the MSVC tools will know where to find it and it
+       can be trusted to be there and unchanged.
+          - if a missing system header fails to satisfy both the above tests then
+       makmake will issue a warning since the generated makefile will probably fail to
+       build.
+ 	      - a warning is issued for any user headers not found in the user include or
+       system include paths, where the user include path is the source directory if no
+       user include paths are specified explicitly.
+
+9)  Processing of MMP files now involves a lot more syntax checking and produces
+    corresponding warnings, especially if MAKMAKE is invoked with the -V switch.
+
+10) MAKMAKE will now automatically generate WINS uid source files when creating Win32
+    makefiles, but only if the new keyword - AUTOUID - is specified in a Win32 START ..
+    END MMP file block.  The keyword is necessary since LINK.EXE would fail for projects
+    which already specified UIDS in the source code, so remove WINS UID specification in
+    the project's source code before using AUTOUID.  MAKMAKE works out UID 1 from a
+    project's targettype and takes UIDs 2 and 3, if specified, from the MMP file.  It
+    then creates the UID source file in the same directory as the MAKEFILE it is to create
+    with the name "<target basename>.UID.cpp".  The source file will look something like this
+
+        // Makmake-generated uid source file
+        #include <E32STD.H>
+        #pragma data_seg("E32_UID")
+        __WINS_UID(0x10000079,0x1000008D,0x100002C3)
+        #pragma data_seg()
+
+	The file will be created only if it doesn't already exist or if it is older than the
+    project's MMP file.
+
+11) In MARM makefiles, multiple calls to GNU tool "ar" to archive the object files for
+    a project prior to linking have been replaced by a single call to ar.  The single
+    call passes a script listing the object files to ar.  This changes speeds up the
+    archiving stage of MARM building considerably.
+
+12) Renamed MAKMAKE.CMD MAKMAKE.BAT for Windows 95 compatibility.
+
+13) Changed MSVC5 dependency generation to be the same as for other platforms,
+    but with system headers stripped out of the list later.  Before, vc5 dependencies
+    called CPP such that only user headers were generated.  This change means that
+    CPP will no longer fail if one of the user headers is expecting a macro definition
+    from a system header and forcing CPP to fail if it doesn't get it.
+
+14) Replaced relative with absolute filepaths where possible in CL_WIN.PM.
+
+15) Changed \e32tools\makmake\makmake.mak so that debug utilities like
+	the perl -w switch and use of module strict.pm apply for "DEB" builds.
+    of MAKMAKE only.
+
+16) Added SARM.PM module to be used by the base for building SARM makefiles.
+
+17) Improved path utilities module MAKPATH.PM to do more error checking
+    and handle extra functions.
+
+GROUP
+1)  Changed e32tools\group\mnt.cmd so that makmake is released in a way more similar
+    to other e32tools project - from \epoc32\build\e32tools\makmake\rel.
+
+
+Version 0.01.081
+================
+(Made by Morgan, 4th November 1997)
+
+ROMBUILD
+1)	Added fixed keyword for use with EXE files. This keyword results in the
+	file being loaded as a fixed address process. The data section base address
+	is allocated in the region between the kernel data address and the kernel
+	stack address. The multiprocess keyword can be used to specify the chunk
+	size; it defaults to 1Mb.
+
+PETRAN
+1)	Added -fixed and -moving options which set and clear KImageFixedAddressExe
+	flag respectively.
+
+2)	Added the following switches
+		-heap <min> <max>
+		-allowdlldata
+		-datalinkaddress <base>
+
+MAKSYM
+1)	Removed duplicate function address error message.
+
+
+Version 0.01.080
+================
+(Made by Alastair, 30th September 1997)
+
+MAKMAKE
+1)	Changed Makmake.pl so that if a project uses a resource file
+	and the resource header file is not yet present in \epoc32\include
+	a dummy header file will be created there so that MAKMAKE's generation
+	of dependencies does not assume that the missing header file is
+	in some other location.
+
+2)	Changed /Fd compiler flag in Ide_vc4.pm so that pdb files have the right
+	name rather than vc40.pdb. 
+
+
+Version 0.01.079
+================
+(Made by Morgan, 22nd September 1997)
+
+ROMBUILD
+1)	Integrated the code for building ROMs for the single process
+	version of E32.  Currently this code is protected with a
+	__SINGLE__ macro.
+	Use the keyword 'singleprocess <ChunkSize>' to generate a
+	single process ROM.  Default is 'multiprocess'.
+
+
+Version 0.01.078
+================
+(Made by Alastair, 15th September 1997)
+
+MAKMAKE
+
+0)	Forget to say about release 077 that \[project]\bwinc is the default
+	directory for which WINC def files are searched if the file specified
+	with the DEFFILE keyword has no path.
+
+1)	Improved MMP file reading so that a warning is generated if MAKMAKE
+	ignores a line because it doesn't recognise the syntax.
+
+2)	Makmake.pl - added new code to trap dependency generation errors.
+
+3)	Makmake.pl - minor changes required to support creation of MSVC5 project
+	files.
+
+4)	Added new modules VC5.PM and VC5WINC.PM to support MSVC5.  These modules
+	will create .DSP MSVC5 project control files.  When an MSVC5 .DSP file is
+	created with makmake project files with the following extensions will be
+	deleted - .dsw,.mak,.mdb,.ncb,.opt,.plg.  The new features of MSVC5 which
+	distinguish between header files belonging to the project and system header
+	files are supported.
+
+5)	Added new module MISA.PM to support MISA command-line makefiles.
+
+6)	Tidied up VC4.PM.
+
+7)	Changed MAKMAKE internal structure so that implementaion modules can
+	share modules controlling the layout of the makefile and other common
+	features.  This change does not affect the way that MAKMAKE is invoked.
+
+		VC5.PM and VC5WINC.PM share IDE_VC5.PM
+		VC4.PM and VC4WINC.PM share IDE_VC4.PM
+		WINS.PM and WINC.PM share CL_WIN.PM
+		MARM.PM and MISA.PM share CL_ARM.PM
+
+8)	Changed CL_WIN.PM and CL_MARM.PM to use an inline batch file in the
+	makefile for calling fc4bat to decide whether a resource header file
+	needs rewriting or not.  Previously, if fc4bat returned an error to
+	indicate that the header file should be rewritten, nmake would die.
+
+9)	Added Makmake.mak to \e32tools\makmake\ for building makmake source to
+	\epoc32\tools and \epoc32\tools\makmake in a way similar to C++ projects.
+
+10)	Changed all .PM modules to ensure that they return a true value
+	when loaded successfully.
+
+E32TOOLS MNT
+
+1)	Changed e32tools.rel file so that readtype.exe is released.
+
+2)	Updated MNT MAKEWORK and MNT GETBLD so that PGETBLD and MNT BLDALL will
+	now work on a clean drive.  Changed readtype.mak so that it searches
+	\epoc32\include rather than \e32\inc for system header files.
+	File \e32\inc\unicode.h needs to be listed in e32\inc\incc.prj 
+	at some point.
+
+3)  Modernised MNT BLDALL so that NMAKE is invoked with the /nologo flag.
+
+4)	Modernised MNT VALID so that pediff is used instead of fc /b for binary
+	file comparison.  Makmake is now included and e32uid.exe removed since it's
+	not used or released.
+
+
+Version 0.01.077
+================
+(Made by Alastair, 8th September 1997)
+
+MAKMAKE
+
+1)	Changed 1st stage of linking (by name) for WINS command-line builds so that
+	linking is not attemped incrementally to stop unnecessary warning appearing.
+
+2)	Added two new modules, WINC.PM and VC4WINC.PM, for use in creating WINC
+	command-line and IDE makefiles respectively.  For command-line makefiles,
+	type "makmake {options} [project] WINC;  for IDE makefiles, type
+	"makmake {options} [project] VC4WINC.  DIfferences between WINC and WINS
+	makefiles are slight - WINC appears where WINS would otherwise appear, and
+	WINC source files are preprocessed with the macros "__WINC__" and "__XCON__"
+	defined as well as all the usual WINS macros including "__WINS__".  Note that,
+	in line with the macro scheme applied to source files, MAKMAKE will preprocess
+	XXX.MMP files with macros "WINS" AND "WINC" defined when creating WINC makefiles,
+	so keywords within "#if defined(WINS) ... #endif" and "START WINS ... END" blocks
+	will apply for WINC builds too.  This scheme required changes to the way
+	MAKMAKE.PL processes START ... END blocks.
+
+3)	Removed possibility of passing extra macros to makmake for preprocessing XXX.MMP
+	files - this possibility was never documented and has never been requested so
+	is now presumed unnecessary.
+
+4)	Introduced keyword option which, if specified in XXX.MMP files, will cause
+	MAKMAKE to search for the same deffile for all build variants rather than
+	several files differentiated by suffixes "U","D" and "UD".	The new keyword
+	is "NOSTRICTDEF", originally enough.  Hopefully deffiles for LDDs and PDDs
+	can soon be done away with by having targettypes for LDDs and PDDs and having
+	MAKMAKE implementation modules pass the correct mangled names as 1st ordinal
+	command-line option arguments to DEFTOOL and DEFMAKE instead.
+
+5)	Changed resource handling to be entirely compatible with eikrs.bat - the basename
+	of XXX.RSS is used for XXX.R$(EPOCLANG) and all intermediate resource files.  This
+	change still does not fix SW1-204, for which a spec decision regarding the handling
+	of differing licensee resource file requirements is required.
+	
+
+Version 0.01.076
+================
+(Made by Alastair, 15th August 1997)
+
+MAKMAKE
+
+1)  Changed MARM and WINS modules so that rcomp is called to compile resources
+    directly rather than via eikrs.bat.  This change will mean that resources will
+    be compiled into the correct directory for MARM builds, and that the *.rss file
+	need no longer be in the same directory as the makefile.  This change addresses
+	SW1-204 and SW1-212.
+2)  The STRICTDEF keyword is no longer recognised by makmake.  Its function in
+	appending "D", "U", and "UD" to the base name of *.DEF files for DEB, UREL and
+	UDEB builds is now carried out by default.  There should now be a *.def file for
+	each of these build variants in use if any definition files are used at all.
+	This change addresses SW1-196.
+3)  Makmake.cmd has been improved.  If makmake fails, a basic perl operation will be
+	attempted.  If this fails, the user will be asked if the correct version of perl
+	is installed.  This change addresses SW1-345.
+
+Version 0.01.075
+================
+(Made by Alastair, 24th July 1997)
+
+DEFTOOL (from William Roberts)
+
+1)	Modified DEFTOOL.CPP and DEFTOOL.H
+	Basically just improved error reporting so that
+	a)	When it tells you that there are "frozen ordinals missing from supplied
+		def file" it also tells you which ordinal numbers have been lost.
+	b)	If your DLL exports functions that weren't in the freeze file then it
+		gives you a gentle warning, because that's not something which we'd 
+		want to allow in a release.
+
+MAKMAKE
+
+1)	Changed makmake so that target makefile is created in the current
+	working directory rather than the directory containing the *.mmp
+	file.
+2)  Added line of code to makpath.pm so that single dot directories
+	are stripped from paths.
+3)	Removed repeat occurrence of deffile flag in the link command for 
+	*.wins makefiles.
+4)	Changed RELGDB path macros for MARM makefiles so that they are prefixed
+	with ".\" rather than "..\\..<absolute path to makefile directory>".
+	This is a neater way to get them to expand to something textually different
+	from REL path macros while still specifying the same path.
+5)	Changed "ar q" lines within MARM makefiles to include 8 object files maximum
+	rather than 4 - this should improve efficiency without breaking limits on
+	command-line lengths.
+6)	Changed WINS.PM so that the $(LINK_OBJS) macro is used in the link command line
+	in *.wins makefiles rather than a list of all the objects concerned.
+7)	Changed MARM.PM so that the first stage of linking (by name) for a dll target
+	creates the dll in the build directory rather than the release directory.
+	The	second stage of linking (by number) creates a dll in the build directory
+	rather than the release directory too, overwriting the first dll.  Finally,
+	this target is petranned to the release directory and the dll left in the
+	build directory is deleted. This change solves the problem of nmake thinking
+	that the target has been successfully created when the build has failed
+	anywhere between the first link stage and the petranning stage, because of
+	the presence of an apparently up-to-date dll in the release directory.
+8)	Changed WINS.PM similarly so that *.wins makefiles do a two-stage link.  Defmake
+	is called between the two link stages with a "freeze" file if one is specified
+	with the DEFFILE statement (see below).  The defmake-created def file is then
+	used for the second-stage link (by number).  The first stage of linking creates
+	the target dll in the intermediate directory while the second stage creates the
+	final target dll in the target directory and the first dll is deleted.
+9)	Removed /NAME flag from MAKMAKE - no longer necessary due to (8).
+10)	Radically changed behaviour of MAKMAKE towards DEFFILE and FRZFILE statements
+	within *.mmp files.  There is no longer handling of FRZFILE statements.  As
+	before, if a DEFFILE statement is placed within an #if defined(WINS) ... #endif
+	block, the statement will be used by both WINS and VC4 makefiles but not MARM
+	makefiles, and vice versa if a #if defined(MARM) ... #endif block is used.  If
+	the file specified has no path, the file is assumed to be in directory 
+	\<project>\bwins\ for WINS and VC4 makefiles and \<project>\bmarm\ for MARM
+	makefiles.  For VC4 makefiles, the specified file is passed to LINK.EXE as 
+	before.  For WINS makefiles, the file is not used in the first stage of linking.
+	Defmake is called and uses the file as a freeze file in the creation of a new
+	deffile which will include any new exports produced by changes to the source code
+	for the project.  The new deffile created is used in the second stage of linking.
+	For MARM makefiles, the specified file works in much the same way as for WINS
+	makefiles.
+		In other words, the DEFFILE statement should now be used to specify "freeze"
+	files.  WINS *.def files were in effect "freeze" files anyway.  The choice of
+	"DEFFILE" rather than "FRZFILE" for the new statement within *.mmp file reflects
+	the widespread understanding of "def" vocabulary outside Psion.  For more
+	information, see the discussion on e32proposals - tools - makmake and frz files.
+		The STRICTDEF keyword is still required if differently-named "freeze" files
+	are required for different builds, but this requirement is under review together
+	with potential default directories for components not using directories
+	\<project>\bwins and \<project>\bmarm.  Note that if these directories are not
+	being used and files specified with the DEFFILE statement include a path then is
+	is essential to place DEFFILE statements with #if defines because WINS and VC4
+	builds should never use the same "freeze" file as MARM builds due to the compilers
+	mangling function names in different ways.
+11)	A file specified with the DEFFILE statement is now put in the list of 
+	dependencies for a target in WINS and MARM makefiles, but not yet VC4.
+12)	Changed MAKMAKE to allow for use of the WINDOWS API.  If you are using this API,
+	specify the windows libraries you wish to link to in *.mmp as follows
+
+	START WINS
+	BASEADDRESS		0x43500000
+	WIN32_LIBRARY	kernel32.lib gdi32.lib user32.lib
+	END
+
+		ie, put the WIN32_LIBRARY statement somewhere in a START WINS ... END block
+	and	list the libraries after it.  Please note that these START WINS ... END
+	blocks are very different from #if defined(WINS) ... #endif blocks.  Makmake
+	always preprocesses the *.mmp file when invoked, and later passes any text within
+	START ... END blocks onto the perl module specific to the platform in question.
+	When makmake is invoked with the VC4 argument, the *.mmp file is preprocessed
+	the WINS macro defined.
+13) Fixed bug causing AIF file subroutine to be ignored
+14)	Fixed bug causing path specified with TARGETPATH statement to be left out of
+	path to resource target for WINS makefiles.
+15) Changed resource file building command so that the base name of the target
+	resource file is the same as the base name of the releasable rather than
+	the base name of the file specified with the RESOURCE or SYSTEMRESOURCE
+	statement.
+16) Changed name for target AIF from the base name of the releasable + ".aif" to
+	the name specified by the AIF statement.
+18)	Changed code designed to warn the user if the version of perl they are using
+	is not supported by MAKMAKE so that it is activated before rather than after
+	compilation - untested.
+
+
+Version 0.01.074
+================
+(Made by Alastair, 1st July 1997)
+
+MAKMAKE
+1)  Fixed egregious error causing the content of LIBRARY
+    statements in *.MMP files to be ignored.  This error
+    is present in e32tools releases 071, 072 and 073.
+
+
+Version 0.01.073
+================
+(Made by Morgan, 18th June 1997)
+
+1) ROMBUILD
+   Added 'time' keyword for specifying the date/time stamp
+   in the rom header.
+   Syntax:
+      time=dd/mm/yyyy hh:mm:ss
+
+   Added 'reloc' file attribute to specify user process
+   data run address for Exes.
+
+   Added 'align' keyword to align files on particular
+   alignment boundries.
+
+
+Version 0.01.072
+================
+(Made by Alastair, 16th June 1997)
+
+MAKMAKE
+1)  Added line of code to makmake.pl so that makmake will refuse
+	to work with versions of PERL released prior to version 
+	5.003_07   .  To find out what version of PERL you are using,
+	type  perl -v<return>  in a DOS box.
+
+
+Version 0.01.071
+================
+(Made by Alastair, 9th June 1997)
+
+MAKMAKE
+1)  Added new preprocessor macro, __PSISOFT32__, defined for all
+	projects using MAKMAKE regardless of platform or build variant.
+
+
+Version 0.01.070
+================
+(Made by Matthew, 4th June 1997)
+
+Added new tool ROMMASK, for generating rom images suitable for masking.
+
+
+Version 0.01.069
+================
+(Made by Alastair, 4th June 1997)
+
+MAKMAKE
+
+1)      Fixed bugs causing _UNICODE macro to be output
+	without the initial underscore by marm.pm and
+	wins.pm.
+
+2)      Single call to gcc archiving tool "ar" replaced
+	by multiple call to avoid overriding of command-line
+	length limits for projects comprising many source
+	files.
+
+3)      Fixed bug in \e32tools\makmake\mnt.cmd so that
+	makpath.pm is copied to directory
+	\epoc32\tools\makmake.
+
+
+Version 0.01.068
+================
+(Made by Alastair, 2nd June 1997)
+
+MAKMAKE
+
+1)      Removals
+	makmake.txt - SDK documentation now available
+	revmak.pl - redundant
+	winsname.pm - redundant
+
+2)      Fixes
+
+a)      fixed dependency macro bug for VC4 platform
+b)      fixed problem with mmp file specification of
+	multiple subprojects
+c)      Other minor bug fixes
+
+3)      Internal Changes
+
+a)      Improved generation of dependencies
+b)      Improved path utility functions
+c)      Moved path utility functions out of makmake.pl to
+	new module "MAKPATH.PM"
+d)      Other structural changes
+
+4)      Command-Line invocation
+
+a)      Platform VC4 can now be specified to produce MSVC4.0
+	compatible makefiles - WINS platform now produces
+	makefiles incompatible with MSVC4.0 allowing greater
+	freedom for using nmake to build resource files, etc.
+	*.MMP files will still be preprocessed with the "WINS"
+	macro whether the platform is specified as WINS or VC4
+b)      New flag "/clean" - deletes all non-source files for the
+	project and platform specified.
+c)      New flag "/lang [language]" - sets a language for the
+	project and platform specified except for VC4.
+d)      New flag "/name" - doesn't add any /def:[deffile]
+	linker flags to WINS or VC4 makefiles.  No effect
+	on MARM makefiles.  This flag makes linking-by-name
+	builds possible for WINS.
+e)      Flags can now be specified anywhere on the command-line
+
+5)      *.MMP Files
+
+a)      New keyword "LANG [language]" - sets a language for
+	the project and platform specified except VC4.
+	This setting is overridden if the command-line language
+	flag is used.
+b)      New keyword "AIF [*.aif file]" - specifies an application
+	information file.  This keyword is subproject relative,
+	and merely copies the *.aif file to the target directory
+	at the moment (except for VC4).
+c)      New keyword "BITMAP [*.mbm file] [*.bmp files]" - specifies
+	a protea multi-bitmap target and compiles it to the target
+	directory using bmconv on the windows bitmap files (except
+	for VC4).  The keyword is subproject relative, so all
+	windows bitmaps files specified are expected to reside in
+	the current \PROJECT\SUBPROJECT directory.  This may not be
+	the required behaviour.
+d)      New "RESOURCE" keyword behaviour - eikrs.bat is invoked
+	for MARM and WINS platforms to compile the resource specified
+	to the target directory.  VC4 platform uses the keyword
+	parameter for information only.  If a language is specified
+	it is passed to eikrs.bat, defaults to "SC".
+e)      New keyword "SYSTEMRESOURCE [*.rss file]" - subproject
+	relative, behaves exactly as the RESOURCE keyword except
+	that for WINS the target resource is compiled to directory
+	\epoc32\release\wins\[build]\Z\system\data.  Ignored by
+	VC4.
+f)      New "TARGETTYPE" keyword option - "exedll".  This option
+	can be used to specify a target which will be built as
+	a dll under single-process platform WINS (or VC4), but as
+	an exe for multi-process platform MARM.
+g)      New keyword "STRICTDEPEND" - if specified, makmake will
+	generate dependencies for each source or resource specified
+	for all builds - DEB,UREL,RELGDB etc.  If sources are unlikely
+	to specify different include header files for different
+	builds then there is no need to specify this keyword and
+	dependencies will be generated once only for each source
+	file.
+h)      New "DEFFILE" keyword behaviour.  This keyword is no longer
+	platform-specific (within a "START [platform] ... END" block).
+	If the deffile is specified without a path, then makmake
+	will expect the deffile to live in directory "\PROJECT\BMARM"
+	for the MARM platform, and in "\PROJECT\BWINS" for WINS or VC4.
+	Note that currently the *.def file will be used in a call
+	to dlltool in MARM makefiles as follows:-
+		"dlltool --def [deffile] --output-def [created deffile]".
+	This behaviour is required for at least one project, and
+	different deffiles can be specified for different platforms
+	using "#if defined [platform]" within *.mmp files.
+i)      New keyword "FRZFILE [*.frz file]" - behaves the same as
+	"DEFFILE" keyword as regards paths.  A specified freeze file
+	is ignored by makmake when producing WINS or VC4 makefiles.
+	The file is used by MARM makefiles as follows
+		"ld -z [frzfile] [dlltool-created deffile]".
+j)      New keyword "STRICTDEF" - if this keyword is specified then
+	makmake assumes that, for each *.def or *.frz files specified,
+	there are actually as many of these files as there are
+	different build configurations for the project.  E.G. for
+	WINS makefiles, if a deffile is secified in a *.mmp file as
+	"DEFFILE mydef.def", then makmake will assume "mydefd.def",
+	"mydefu.def" and "mydefud.def" for DEB, UREL, and UDEB builds
+	respectively.  Though for MARM, a RELGDB build would look for
+	plain "mydef.def".
+
+6)      Output
+
+a)      Makmake for MARM will produce *.MARM makefiles.
+b)      Makmake for WINS will produce *.WINS makefiles.
+c)      Makmake for VC4 will produce *.MAK makefiles.
+d)      MARM and WINS makefiles are restructured to allow
+	the following example NMAKE command-line invocations
+
+		"NMAKE /f euactiv2.wins UREL"
+		"NMAKE /f euactiv2.marm UDEB"
+		"NMAKE /f euactiv2.wins CLEANDEB"
+		"NMAKE /f euactiv2.marm CLEAN"
+
+e)      Macros specifying target directories, language,
+	build directories and so on are produced at the
+	top of WINS and MARM makefiles.
+f)  RELGDB builds for MARM aim to put the executable
+	produced into \epoc32\release\marm\rel, and also use 
+	\epoc32\build\[project]\marm\rel as their building 
+	directory.
+g)      Gcc tool OBJCOPY produces a *.sym file for MARM debug
+	builds, including RELGDB.
+
+
+Version 0.01.067
+================
+(Made by Morgan, 19th May 1997)
+
+1) PEDIFF
+   Recognises time/date stamps in debug and export directories.
+   Ignores PETRAN version information in the header.
+
+2) PETRAN
+   Uids take the full 32bits.
+
+3) WVECONV
+   From \VNOTES\WVECONV.  S3a to S5 sound file converter.
+
+
+Version 0.01.066
+================
+(Made by Alastair, 9th May 1997)
+
+MAKMAKE
+
+1) Fixed bug causing extra "print " text to be produced
+   as part of the USERINCLUDES text outputted in verbose mode.
+
+2) Fixed bug causing makmake.pl to fail to produce the extension
+   of a target filename when requested by *.pm modules
+
+3) Fixed bug causing makmake to fail with an error report if
+   more than one flag is specified on the command line
+
+MAKSYM
+
+1) Added a few lines of extra code so that the base address of
+   a dll in the rom is printed to maksym.log when maksym cannot
+   find the corresponding *.map file.
+
+
+Version 0.01.065
+================
+(Made by Alastair, 6th May 1997)
+
+MAKMAKE
+
+1) reorganised to be more easily maintainable and extensible.
+
+2)      handles uid keyword in *.mmp file - uid1 is provided automatically,
+	uid's 2 and 3 are specified ... 
+
+UID <uid2> <uid3>
+
+in *.mmp file.
+
+3)      dependency generation section calls CPP with flag -MG so that
+	makmake responds gracefully to missing generated headers
+
+4)      *.mdp and *.ncb files are automatically deleted from directories
+	in which makmake is directed to create a wins makefile with the same
+	root.
+
+5)      petran is invoked from the arm makefile
+
+6)      invocation syntax simplified so that makmake is invoked 
+		makmake [flags] [mmp file root] [platform]
+	rather than
+		makmake [flags] [mmp file] [destination makefile] [platform]
+
+7)      makmake by default operates in quiet mode, verbose mode is invoked
+	using the new "/V" flag on the command-line
+
+8)      makmake will create the work directories rather than the makefile
+	if the new "/MAKEWORK" flag is used on the command-line
+
+9)      the "/q" flag for "del" commands is no longer added to marm makefiles
+	created with makmake
+
+10)     the DEFFILE keyword is no longer searched for within a START WINS ... END       
+	block, now it is platform independent though not yet utilised by the marm 
+	platform.
+
+11)     winsname.pm is not currently expected to work
+
+12)     PERL is no longer invoked with the -w debugger flag
+
+Version 0.01.064
+================
+(Made by Morgan, 16th April 1997)
+
+1)      ROMBUILD
+	Removed the checks for unicode-ness of Uid[0] on Exes/Dlls
+
+2)  W32REPRO
+	An NT version of PREPRO written by WilliamR
+
+
+Version 0.01.063
+================
+(Made by Morgan, 15th April 1997)
+
+1)      MAKTRAN
+	Changed over to the new (and slightly less mad) Uid scheme
+	introduced in E32(098).
+	Dlls now have a Uid[0] of 0x10000079
+	Exes now have a Uid[0] of 0x1000007A
+	Everything else is as before.
+
+
+Version 0.01.062
+================
+(Made by Graham Asher, 15th April 1997)
+
+READTYPE
+	Added this new tool, which writes the new file unitable.cpp, which contains
+	the Unicode character attribute information. I've put a full
+	explanation of how to use READTYPE in Notes under e32 software design.
+
+
+Version 0.01.061
+================
+(Made by Morgan, 13th April 1997)
+
+1)      ROMBUILD
+	1) Bug fix when using the -S switch with Rom patching
+	2) Added class TRomSectionHeader to the start of the
+	   second section of the Rom so sectioned Roms can have
+	   a separate build time, language variant, and checksum.
+	3) Added iRomSectionHeader member to TRomHeader to point
+	   at the start of the sectioned Rom and padded TRomHeader
+	   to 256 bytes.  This needs a new BOOTROM.BIN which will
+	   be released with E32(098)
+	4) Fixed a bug in the split rom verify code.
+	5) Fixed the overriding of Uids.
+
+
+Version 0.01.060
+================
+(Made by Morgan, 9th April 1997)
+
+1)      PETRAN
+	Fixed a PETRAN dumping bug when there are no .data relocations.
+
+2)      MAKTRAN
+	Bug fix for -P switch when no uid3 is specified.
+
+3)      DEFMAKE
+	Made the -S switch work when -Z is used.
+
+
+Version 0.01.059
+================
+(Made by Morgan, 7th April 1997)
+
+HIGHLIGHTS:
+	* MAKTRAN now produces PETRANned targets.
+	* Components should use the new -P switch instead of -U.
+	* Suggested minimum commandline for Dlls:
+	  MAKTRAN <src .MAK> <dest .ARM> -z<Your .FRZ> -p"-uid2 <Your Uid2> -uid3 <Your Uid3> -nocall"
+
+2)      MAKTRAN
+	1) Overhauled for releasing PETRANned components.
+	   -U switch has been removed and been replaced by new
+	   -P switch for specifying PETRAN command line arguments. Uid1
+	      will default to the correct uid for the build type unless
+		  you specify otherwise.
+
+
+Version 0.01.058
+================
+(Made by Morgan, 3rd April 1997)
+
+1)      ROMBUILD
+	1) Filenames can now be quoted ("") to include spaces.
+	2) More details provided when the Rom overflows.
+
+	NOTE: Currently there is a bug that occurs if the Rom 
+	is exactly the correct size (byte for byte) and sectioning
+	is being used.  It's harmless - I'll fix this in a release
+	soon.
+
+
+Version 0.01.057
+================
+(Made by Alastair, 2nd April 1997)
+
+1)      MAKMAKE
+	Fixed bug in wins.pm causing *.def files specified in *.mmp
+	files to be ignored by MSVC.
+	Included deftool flag -1 NewApplication__Fv for MARM makefiles
+	where the target is an APP.
+	
+	E32TOOLS GROUP MNT.CMD
+	Added lock, unlock and wholock parameters.
+
+
+Version 0.01.056
+================
+(Made by Alastair, 27th March 1997)
+
+Alastair:
+1)      MAKMAKE
+	MAKMAKE generates makefiles for WINS or MARM builds.
+	It is being released because the SDK example projects
+	now use it, and no longer use MAKTRAN.  Makmake is by no
+	means fully tested and is certainly not intended for 
+	incorporation into Epoc32 projects prior to V1 shipping.
+	Details of its use are roughly documented in file 
+	\e32tools\makmake\makmake.txt.
+	Use of makmake requires the installation of Perl 
+	from directory T:\UTIL\PERL.
+
+
+Version 0.01.055
+================
+(Made by Morgan, 20th March 1997)
+
+1) ROMBUILD
+   CheckSum bug fix.
+   Kernel alignment bug fix.
+
+
+Version 0.01.054
+================
+(Made by Morgan, 18th March 1997)
+
+1) ROMBUILD
+   Removed some unnecesary recurtion and tidied some dodgy code.
+   Loaded the files to Rom in the order they appear in the obey
+   file, rather than depth first order.
+   
+   Roms can now be sectioned into two parts allowing the upper
+   part of the rom to be switched for language variations and
+   file patching.  Both these processes require the original
+   releasables, original obey file, and any new releasables.
+   It is also advisable to supply the original Rom so the lower
+   section can be verified to be constant.
+
+   In a sectioned rom the directory structure, import address
+   tables, and Dll reference tables of all files in the first Rom
+   are placed after the section border.
+   The overhead of sectioning a Rom (over and above an unsectioned
+   one) is the space required to duplicate the import address
+   tables of files from the first section.
+   Last time I counted (B2) the iat's took up 42k.
+
+   The 32bit sum of all 32bit words in the second section is
+   always 0.  This means the iChecksum member in TRomHeader is
+   valid for the rom as a whole and for the first section in
+   isolation.
+   It is not possible to patch any files that are listed before
+   the primary or the secondary.  Doing this causes the position
+   of the kernel's/file-server's entry in the directory table to
+   move.  This may be fixed in a future release.
+
+   To section a Rom:
+      Use the keyword
+	 section <rom offset>
+      at the point in the obey file where you want the Rom to be
+      split.  All files before this line appear in the first
+	  (constant) section, and files after appear in the second
+	  (patch/language) section.
+
+   Patching a file in the second section:
+      Add file attribute 'patch[ed]' to the file to be patched.
+      (This will cull the file from the first section).
+      Supply a replacement file in the top section as required.
+	  Note, the original file is still required to guarantee
+	  consistency in the first section of Rom.
+	  Run ROMBUILD.
+
+   Supplying a language dependant file:
+      Put the file after the section keyword.
+	  Run ROMBUILD.
+
+   To verify the lower section of Rom has remained constant:
+      Specify the original Rom image on the command line with
+	  -r<FileName>
+
+
+Version 0.01.053
+================
+(Made by Morgan, 7th March 1997)
+
+1) ROMBUILD
+   Bug fix to 'screen' keyword
+
+
+Version 0.01.052
+================
+(Made by Morgan, 3rd March 1997)
+
+1) ROMBUILD
+   Bug fix for Exes/Dlls with no relocations in .text or .rdata
+   Check Uids for exporting .EXEs as well as .DLLs
+   New 'screen' keyword.  Default is: screen = 640x240x4
+
+2) MAKTRAN
+   Bug fix
+
+
+Version 0.01.051
+================
+(Made by Morgan, 13th January 1997)
+
+Alastair:
+1) MAKSYM
+   Generates a list of C++ symbols and their addresses in rom from
+   ROMBUILD.LOG and accompanying .MAP files.
+   MAKSYM ? for help.
+
+
+Version 0.01.050
+================
+(Made by Morgan, 6th January 1997)
+
+1) ROMBUILD
+   Incompatable with any E32 before 083.
+   Added some stuff to TRomHeader for the test department:
+   A language bitfield (64bits for specifying the languages supported
+   by the ROM), and a 32bit hardware identifier.
+   The languages are as defined by TLanguage in E32STD.H.  (ie Test
+   is bit 0,  English is bit 1, French is bit 2,  etc...)
+   Added two more obeyfile keywords for this.  Usage:
+   languages = <list of supported languages>
+   hardware = <n>
+
+   Rombuild now has a -? switch.
+
+
+Version 0.01.049
+================
+(Made by Morgan, 11th December 1996)
+
+1) MAKTRAN
+   Object files are now grouped on the ar (archive) command line to
+   speed up building.  By default they are grouped in 4s but this
+   can be changed by using the new -a<n> switch.
+
+2) ROMBUILD
+   More informative error information when a dll is exporting by
+   name.
+
+3) E32UID
+   Removed.
+
+
+Version 0.01.048
+================
+(Made by Morgan, 22nd November 1996)
+
+1) ROMBUILD
+   Added 128 bytes of space to TRomHeader which appears at the front
+   of the ROM.  This is to allow work on the StrongARM port to
+   progress.
+   Naturally, this makes ROMBUILD compatable with absolutely nothing.
+   So a new bootrom.bin will be released with E32(075).
+
+
+Version 0.01.047
+================
+(Made by Morgan, 1st November 1996)
+
+1) MAKTRAN
+   Another minor fix to deal with unusually shaped .MAK files.  This
+   time it's old link information stored in comment lines.
+   Added "-Wno-ctor-dtor-privacy" to CPPFLAGS.
+
+2) PEDIFF
+   Bug fix HA-283.  The final section in a PE file may be truncated
+   to its VirtualSize making the SizeOfRawData field of the header
+   inaccurate.  This was causing a problem in the release build but
+   not the debug build.
+   Fixed by padding the section data with zeros up to SizeOfRawData
+   bytes.
+
+3) ROMBUILD
+   Added a iTextSize member to TRomImageHeader.  Making this version
+   of rombuild incompatable with any E32 before build 075.
+
+
+Version 0.01.046
+================
+(Made by Morgan, 1st November 1996)
+
+1) MAKTRAN
+   Added support for include directories other than ..\inc and
+   \epoc32\include
+      
+
+Version 0.01.045
+================
+(Made by Morgan, 7th October 1996)
+
+1) MAKTRAN
+   Added a -U<Uid> switch to put the 3rd uid in the target's import
+   stub so the Dll/Exe exports as DllName[Uid].Ext
+   This enables you to use the type-safe static linking (based on the
+   Dll's 3rd Uid) in E32(070)/F32(036) and ROMBUILD(043).
+
+2) ROMBUILD
+   Officially PVCSed DW's patch to ROMBUILD(044) that disables
+   type-safe static linking and added a -type-safe-link option to
+   turn it back on.
+   I'll leave it that way until people get used to the idea (or until
+   someone comes up with a better plan).
+   Also added checks on the first Uid against
+   KNarrowDebugUid, KNarrowReleaseUid for Ascii builds and
+   KWideDebugUid, KWideReleaseUid for Unicode builds.  I havn't made
+   this dependent on the -type-safe-link option because executables
+   and dlls wont load if this Uid is not set correctly.
+
+
+Version 0.01.044
+================
+(Made by Morgan, 3rd October 1996)
+
+1) ROMBUILD
+   ROMBUILD can now take E32 Image (pre-PETRANned) files as well as
+   PE Format files as input.
+
+
+Version 0.01.043
+================
+(Made by Morgan, 2th October 1996)
+
+1) MAKTRAN
+   Better filename parsing for the -z option.
+
+2) PETRAN
+   Added a -priority option.  This takes a number or one of these
+   keywords: low, background, foreground, high, windowserver,
+   fileserver, realtime, supervisor.
+
+3) ROMBUILD
+   Added 'priority' inline keyword for EXEs.
+   Added checks for type-safe static linking of DLLs.
+
+5) E32UID
+   Jal:  Displays the psion copyright message and build.
+	 Renumbered Uids to be Uid0, Uid1, and Uid2.
+
+6) ALL
+   Redirected error output to stderr.
+   
+
+Version 0.01.042
+================
+(Made by Morgan, 14th September 1996)
+
+1) PREPRO, PEIGER
+   Changes to MNT.CMD to include the latest versions of
+   PREPRO and PEIGER in the E32TOOLS release.
+
+2) MAKTRAN
+   Minor bug fixes for -D defined symbols.
+
+3) E32UID
+   Added a -Q quiet switch.
+
+
+Version 0.01.041
+================
+(Made by Morgan, 14th September 1996)
+
+1) MAKTRAN
+   Added support for maktranning make files of static libraries.
+   There are added complications when using static libraries from
+   GCC:
+   You may find that any executables linked with a static library
+   produce reams of "bad relocation" errors from either PETRAN or
+   ROMBUILD.  At the moment, to work around this you will need to
+   modify 2 lines for each build in the MAKTRANed file.
+       $(LD) ... --whole-archive my_exe.in --no-whole-archive ... my_lib.lib
+   becomes:
+       $(LD) ... --whole-archive my_exe.in my_lib.lib --no-whole-archive ...
+   this has the effect of including all code from the static library
+   in your .EXE whether it is used or not, but it fixes the bad
+   relocations generated by the GCC linker.
+
+   MAKTRAN also propogates defined symbols from the MSVC4
+   Build/Settings dialog excluding:
+	      __WINS__,__VC32__,__EXE__,__DLL__,
+	      _UNICODE,WIN32,_WINDOWS
+
+2) DEFTOOL
+   No longer truncates your def file if it can't find the specified
+   freeze file.
+
+
+Version 0.01.040
+================
+(Made by Morgan, 2nd September 1996)
+
+!) ROMBUILD
+   Bug fix:  for EXEs/DLLs with no imports.
+   
+   The tab character is now treated as white space in obey files.
+   
+   Improved some error messages.
+
+   Removed the universally dispised 'nocallentrypoint' directive on
+   the grounds that it looked silly.
+   Executables specified with 'file=' do not have the entry points
+   called.  New keyword 'dll=' indicates that the entry points
+   should be called.
+
+   Fixed filename case dependency.
+
+2) MAKTRAN
+   Added the switches '--whole-archive' and '--no-whole-archive'
+   around the .in file on the linker command line to keep GCC happy.
+   This only effects EXEs - as DLLs did it already.
+
+
+Version 0.01.039
+================
+(Made by Morgan, 19th August 1996)
+
+1) MAKTRAN
+   Added Unicode and Debug (U,D) suffixes to DEF files to make the
+   filenames for each target different under the new directory
+   structure.
+   Freeze files have also been given the same treatment:  specifying
+   -z afile.frz
+   will use afile.frz, afileD.frz, afileU.frz, afileUD.frz
+   as freeze files for the respective builds.
+
+
+Version 0.01.038
+================
+(Made by Morgan, 2nd August 1996)
+
+1) MAKTRAN
+   New maktran for the new epoc32 directory structure.
+   -T option removed.  Template instantiation is automatic.
+   Dlls are auto-detected by looking for __DLL__ in the .MAK file,
+   but this can be overridden with -D (to force a DLL) and -E (to
+   force an EXE)
+   Bug fix:  MAKTRAN now deals with make files that do not have
+   their "Win32 Release" target first.
+
+2) ETOUCH
+   Replacement TOUCH program.
+
+3) ROMBUILD
+   Bug fix:  for data sections with no relocations
+
+4) PETRAN
+   Added -nocallentrypoints option (can be shortened to -nocall)
+   and   -callentrypoints   option (       shortened to -call)
+   Bug fix:  for executable files with no relocations
+
+
+Version 0.01.037
+================
+(Made by Morgan, 2nd August 1996)
+
+1) ROMBUILD
+   Yet another change that will break your rom if you don't pay
+   attention to the version numbers.  This build is intended to
+   work with E32 (065).
+   The format of the Dll reference table has changed, and now looks
+   like this:
+
+   class TDllRefTable
+      {
+   public:
+      TUint16 iFlags;
+      TUint16 iNumberOfEntries;
+      };
+   followed by iNumberOfEntries of these:
+   class TDllRefTableEntry
+      {
+   public:
+      TUint iEntryPoint;
+      TUint iDllRefTable;
+      };
+
+   Added another inline keyword "nocallentrypoint" to obey files.
+   When attached to a file it prevents the entry points of linked
+   Dlls being called.  This is used to save time during loading
+   when the Dll's entry points are trivial (=empty).
+
+2) Fiddled with the -s option.
+   -S        outputs the size summary to the screen and to the log
+   -SLog     outputs the size summary to the log only
+   -SScreen  outputs the size summary to the screen only
+
+3) Forced the primary's code section to start on a 4K page boundry
+   for obscure operating system reasons.
+   (ie, Getting the exception/interrupt vectors to land on a page
+   boundry so they can be easily mapped by the MMU to the address
+   where they are expected to be.)
+
+4) Added support for building Unicode roms.  The implementation for
+   writing Unicode filenames to ROM is temporarily dubious.
+   A Unicode rom is made by specifying the keyword 'unicode' in the
+   first section of the obey file.
+
+5) Added the keyword 'stop' so parsing of an obey file can
+   be stopped prematurely.
+   
+
+Version 0.01.036
+================
+(Made by Morgan, 11th July 1996)
+
+1) ROMBUILD
+   Support for generating split ROM images - added the optional
+   keywords:
+   romnameodd=<file name>
+   romnameeven=<file name>
+   resulting in two half-roms.  one containing all odd numbered
+   half-words (16bits) and one containing all the even half-words.
+
+   Checksums:
+   Added a checksum member to TRomHeader and an optional keyword
+   romchecksum=<n>
+   for obey files.  This results in a ROM where summing all 32 bit
+   words (ignoring overflows) will return n.  The default sum of
+   all ROM words is 0.
+
+   Checksums for the ROM and for split ROMs are now calculated and
+   reported in the log.  These checksums are calculated by summing
+   all 8bit bytes and taking the least significant 32 bits of the
+   result.
+
+
+Version 0.01.035
+================
+(Made by Morgan, 10th June 1996)
+
+1) MAKTRAN
+   Added a RELGDB target which pretends to be the REL target
+   while keeping the debug info.
+   This has the same effect as a REL build when the makefile is
+   generated with:
+   MAKTRAN -no-strip-symbols -g"-g -fno-omit-frame-pointer" src dest
+
+2) DEFMAKE, DEFTOOL
+   Added -2 switch to compliment the -f switch so you can specify
+   the second ordinal as well as the first without the need to mess
+   around with freeze files.
+   This allows us to accomadate DLLs with the UID function at 
+   ordinal 1, and the GateL function at ordinal 2.
+   Also added -1 switch which is the same as -f to keep things 
+   consistent.
+
+
+Version 0.01.034
+================
+(Made by Morgan, 26th June 1996)
+
+1) ROMBUILD
+   Added facility to output Motorola S format Records.
+   Use the optional keyword:
+   srecordfilename=<output filename>
+   in the first section of the obey file.
+
+2) MAKTRAN
+   gcc option -mcpu-arm710 is now -mcpu=arm710
+   Added -strip-symbols and -no-strip-symbols options.
+   These force the linker to keep or strip all symbol
+   information (including debug symbol info).  If both
+   are omitted then symbols are striped for release
+   builds only.
+
+
+Version 0.01.033
+================
+(Made by Morgan, 24th June 1996)
+
+1) MAKTRAN
+   The -m6 flag on the CPPFLAGS line has changed to
+   -mcpu-arm710 -mapcs-32
+   added -fvtable-thunks and
+   removed -fno-implicit-templates
+
+
+Version 0.01.032
+================
+(Made by Morgan, 20th June 1996)
+
+1) PETRAN, ROMBUILD
+   Bug fix:  Relocations for the .rdata section were 4 bytes out
+   when the executable had a .rdata section and no imports.
+
+   PETRAN now performs a sanity check on all virtual addresses, and
+   lists the dubious ones.
+
+2) MAKTRAN
+   Made the error messages more descriptive when the .MAK file
+   doesn't contain one of the expected targets.
+
+
+Version 0.01.031
+================
+(Made by Morgan, 12th June 1996)
+
+1) PEDIFF
+   syntax: PEDIFF pefile pefile
+	   PEDIFF -e32 e32imagefile e32imagefile
+   compares 2 PE/E32Image format files to see if they are identical
+   ignoring all time/date stamps
+
+2) PETRAN
+   Another change to the E32Image file format to add a time stamp.
+
+
+Version 0.01.030
+================
+(Made by Morgan, 11th June 1996)
+
+1) PETRAN, ROMBUILD
+   Fixes to supply more information for the ram loader.
+   (ie. the size of the import section)
+   Documentation for the E32 Image file format is available from
+   the 'E32Base' Notes database.
+
+
+Version 0.01.029
+================
+(Made by Morgan, 7th June 1996)
+
+1) PETRAN
+   Added the command line switches:
+     -stack <stack size>
+     -uid<n> <uid>
+   for setting the stack size and the file's uids
+
+   The output of PETRAN has changed to the new E32Image file
+   format giving a (seasonally adjusted) size reduction of between
+   20 and 40 bytes.
+
+2) ROMBUILD
+   Uses the new E32Image file format.
+   Added heap size, and uids to the file modifiers
+   file = <src PE file> <dest EPOC file> [attributes]*
+       where 'attributes' is
+       attrib = [r|s|h|R|S|H]+
+       stack = <stack size>
+       reloc = <specific relocation address>
+       heapmax = <heap size>
+       heapmin = <heap size>
+       uid<n> = <uid>
+   Files in the rom are now read-only (R) by default (use
+   attrib=r to make them read/write)
+
+   Made filename and import/export name compares case insensitive
+
+3) DEFMAKE
+   DEFMAKE now accepts Alpha CPU PE Files
+
+
+Version 0.01.028
+================
+(Made by Morgan, 30th May 1996)
+
+1) MAKTRAN
+   added a -g flag to pass extra parameters to the gcc command line
+   eg.
+   -g-fcheck-new
+   adds: -fcheck-new to CPPFLAGS and
+   -g"-fcheck-new -fsigned-char"
+   adds: -fcheck-new -fsigned-char
+
+
+Version 0.01.027
+================
+(Made by Morgan, 29th May 1996)
+
+1) ROMBUILD
+   Changed the format of the 'file' keyword to allow overriding of 
+   various file attributes.
+   New format is:
+   file = <src PE file> <dest EPOC file> [attributes]*
+       where 'attributes' is
+       attrib = [r|s|h]+
+       stack = <stack size>
+       reloc = <specific relocation address>
+
+   The -s switch now lists file sizes in the same order as files
+   occur in the obey file.
+
+   Fixed a problem with reading relocations when the PE format file
+   lies about the VirtualSize of the section.
+
+2) MAKTRAN
+   Removed the -s flag from the linking stage of debug builds
+   to keep gcc generated debug information.
+
+3) DEFTOOL
+   Improved error reporting.
+
+4) General
+   Removed the dependencies on TRomExeHeader and TRomDllHeader
+   (from the header files of E32(059)) which are now defunct
+   so the tools build properly with E32(060).
+   Removed some of the dead code left over from E32ROM
+
+
+Version 0.01.026
+================
+(Made by Morgan, 24th May 1996)
+
+1) ROMBUILD
+   Altered the size summary output to include data files.
+   Currently the files are listed in depth first directory
+   order.  I intend to change this so they appear in the
+   same order as they appear in the obey file.
+
+2) PETRAN
+   Fixed a bug that crashed the translator when the size of the
+   relocation section of an executable was a multiple of 0x200
+   (the PE format file alignment size.)
+
+3) MAKTRAN
+   Added a CLEAN target.
+
+
+Version 0.01.025
+================
+(Made by Morgan, 23rd May 1996)
+
+1) E32ROM has been killed
+
+2) ROMBUILD replaces E32ROM
+   Syntax: ROMBUILD [-v] [-s] obeyfilename
+   -v verbose flag
+   -s gives a size summary of all executables in the rom
+   Logged output appears in the file ROMBUILD.LOG
+
+   The obey files for ROMBUILD are slightly different:
+   The keyword 'resource' has been replaced with 'data' for
+   putting data files in rom.
+   A manditory keyword 'kernheapmax' has been added.
+   The 'version' keyword has the syntax Major[.Minor[(Build)]]
+
+3) PETRAN
+   Produces E32ImageFile format files from PEFiles.
+
+4) Jal,
+   E32UID
+   Attaches UIDs to WINS files.
+
+
+Version 0.01.024
+================
+(Made by Morgan, 14th May 1996)
+
+1) DEFMAKE, DEFTOOL and MAKTRAN
+   Added -z switch to specify a frozen def file.
+   The exports in the frozen def file appear first (and in order)
+   in the new def file.  All additional exports are added to the
+   end.
+   A warning will be give if an export in the frozen def file
+   does not appear in the executable being processed.
+
+
+Version 0.01.023
+================
+(Made by Morgan, 3rd May 1996)
+
+1) Jane
+   Added space for the Uid system to the Rom Exe and DLL headers.
+
+
+Version 0.01.022
+================
+(Made by Morgan, 1st May 1996)
+
+1) E32ROM:
+   Added path checking so now it is not possible to create
+   directories with the name ""
+   The version specified by the obey file is now put into the rom.
+
+2) MAKTRAN:
+   /f switch added to specify the name of the function to use as
+   the first ordinal in the dll. (only works with /d switch).
+   More looping bugs fixed.  This time in the Archive generation.
+   Added some meagre form of test suit:  DIFs good .ARM files
+   with files generated from the current version.
+   Put in the work-around for the "ld hardcoded to C:" problem.
+
+
+Version 0.01.021
+================
+(Made by Morgan, 23rd April 1996)
+
+1) MAKTRAN bug fixes:
+   Added gcc -g option to the debug builds to produce debug output.
+   Fixed HA-103:  Now rules are only output for .cpp files
+   Having a .. or a . in the path for a source file 
+   (eg SOURCE=.\T_BLOB.CPP) no longer puts MAKTRAN into an endless
+   loop.  Also using system variables in path specifiers
+   (eg {($INCLUDE)}"\AHeader.H" ) no longer fills your hard disk.
+   Source files with no dependancies now generate a target.
+
+
+Version 0.01.020
+================
+(Made by Morgan, 11th April 1996)
+
+   E32ROM:
+1) Jal,
+   The 'resource' option is fixed and the rom is given the correct
+   date.
+
+2) Jane,
+   Added an error message if you don't supply enough parameters on
+   any line in the files section.
+
+
+Version 0.01.019
+================
+(Made by Graham, 8th April, 1996)
+
+1) Changed MAKTRAN-created makefile compiler options:
+
+   Added -fno-implcit-templates
+   In the past GCC automatically instantiated template classes and
+   functions. We now want to take complete control of this, so all
+   such templates will have to be instantiated by hand. There is an
+   extra switch (/T) on the command line which enables automatic
+   template instantiation to be turned back on, but this should only
+   be used when compiling test programs. Releasable code should take
+   advantage of the reduction in ROM size which hand-instantiation
+   brings.
+
+   Removed -fvtable-thunks
+   Those programs which exploit multiple-inheritence should now work.
+
+   Added $(USERDEFS)
+   This enables you to add your own definitions to the build.
+   e.g. nmake /f elink.mak USERDEFS=-D_USE_LOG
+
+2) Changed MAKTRAN-created makefile linker options:
+
+   Added --no-whole-archive option
+   This should greatly improve the size and linking speed DLL's. In
+   order to exploit this, you must get the next release of the GCC
+   tools from the network. Do this by typing TOOLS GCC and making
+   sure that \GCC\BIN is in your path.
+
+3) Fixed a bug with MSVC .MAK files which contain custom builds
+
+
+Version 0.01.018
+================
+(Made by Morgan, 3rd April, 1996)
+
+1) Extended DEFTOOL to take a -f switch (takes the name of the
+   function to be ordinal 1).
+
+
+Version 0.01.017
+================
+(Made by Graham, 26th March, 1996)
+
+1) Fixed a bug in E32ROM which gave "relocation type not handled" in
+   the presence of .reloc sections which were an exact multiple of
+   256 bytes in length.
+
+2) Fixed the MAKTRAN "if exist xxx.in del xxx.in" bug
+
+3) Added DEB, UREL and UDEB builds to MAKTRAN make files
+
+Jane:
+
+4) Better error reporting in E32ROM.EXE
+
+
+Version 0.01.016
+================
+(Made by Graham, 19th March, 1996)
+
+1) Fixed a bug in targetting some test program make files.
+2) Changed "del xxx.in" to "if exist xxx.in del xxx.in"
+
+Lane:
+
+3) Changed the mechanism by which libraries to be linked are found.
+
+Jane:
+
+4) Further improvements to the error reporting for DEFMAKE.
+
+
+Version 0.01.015
+================
+(Made by Graham, 8th March, 1996)
+
+1) Changed all tools to display their version and build numbers.
+
+Jane:
+
+2) Fixed a couple of heap problems in E32ROM, and generally increased robustness. 
+   Will now print an error message if there are too many files for the ROM,
+   rather than scribbling all over your nice memory.
+
+3) Improved some of the error reporting for DEFMAKE.
+
+Version 0.01.014
+================
+(Made by Graham, 6th March, 1996)
+
+1) Changed MAKTRAN to accept makefiles which have depenencies ..\..\
+   away from their source directory.
+
+Version 0.01.013
+================
+(Made by Graham, 5th March, 1996)
+
+1) Changed MAKTRAN to accept makefiles which are completely relative to
+   the directory in which they reside. NB These makefiles cannot be
+   correctly translated if they are moved to a different directory.
+
+Version 0.01.012
+================
+(Made by Graham, 4th March, 1996)
+
+1) Changed MAKTRAN to assume DEFTOOL.EXE is in your path
+2) Changed MAKTRAN so that it correctly sets __DLL__ and __EXE__
+3) Changed MAKTRAN to handle specially named DLL's - .DEV .MTD etc
+4) Changed MAKTRAN to handle projects with non-compilable components
+5) Changed the mechanism by which MAKTRAN decides group and project.
+
+Version 0.01.011
+================
+(Made by Graham, 27th February, 1996)
+
+1) Changed E32ROM to give each .EXE an 8K Stack
+2) Fixed bugs in MAKTRAN to do with picking up the name of the target
+3) Removed --whole-archive from .EXE make files built by MAKTRAN
+
+Version 0.01.010
+================
+(Made by Jane, 26th February, 1996)
+
+1) Fixed mnd.cmd for command line builds
+
+Version 0.01.009
+================
+(Made by Jane, 23rd February, 1996)
+
+1) Switched to Visual C++ 4.0
+
+2) E32ROM - Added support for REM statement in obeyfiles
+
+3) E32ROM - Fixed an obeyfile init bug which became apparent under the new compiler
+
+4) DEFMAKE & E32ROM - added support for export table being in .rdata section, as it is
+   now with Visual C++. (Export table in .edata is still supported.)
+
+5) DEFMAKE - added -q option which surrounds symbols names in "". This is mostly needed by
+   gcc builds where all destructors have a full stop in their name.
+
+6) First release of MAKTRAN and DEFTOOL from Lane
+	MAKTRAN converts msvc .mak files to gcc format.
+	DEFTOOL is used by MAKTRAN to strip out garbage from .def files
+		and to insert "NONAME" as required by gcc.
+	For MAKTRAN usage type "MAKTRAN".
+
+7) E32ROM - in log now displays absolute ROM addresses rather than offsets, and for text only
+
+Version 0.01.008
+================
+(Made by Jane, 31st January, 1996)
+
+1) Removed support for old time class
+
+
+Version 0.01.007
+================
+(Made by Jane, 8th January, 1996)
+
+1) Changed to new time class
+
+
+Version 0.01.006
+================
+(Made by Jane, 21st December 1995)
+
+1) Added versions to tools
+
+2) E32ROM - Changed heap min size for apps to 32k.
+
+3) E32ROM - Exits with error if files fail to fixup due to importing by name
+
+
+Version 0.01.004/005
+====================
+(Made by Jane, 15th November 1995)
+
+1) Added -R option to DEFMAKE so that the omission of ??__Dbg names in the .DEF
+   (release 003, (1)) can be optional.
+
+2) DEFMAKE alone now prints the meaning of the switches as well as help text.
+
+Version 0.01.003
+================
+(Made by Jane, 7th November 1995)
+
+1) Changed DEFMAKE not to write any exports after it hits the first
+   ??__Dbg prefixed name, allowing me to automate the E32 build
+   completely.
+
+2) E32ROM - Added code to avoid overwriting the first byte of a file if presented
+   with an invalid RVA of 0. (Bug in Cygnus tools).
+
+Version 0.01.002
+================
+(Made by Jane, 2nd November 1995)
+
+1) Converted DEFMAKE to the new HOST scheme.
+
+2) Sorted MNT.CMD so E32ROM will actually build.
+
+
+Version 0.01.001
+================
+(Made by Jane, 1st November 1995)
+1) First release.
+
--- a/imgtools/romtools/group/romtools.mrp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/group/romtools.mrp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,9 +1,9 @@
 #component name "romtools"
 
 component dev_build_imgtools_romtools
-source  \src\tools\dev\build\imgtools\romtools
-binary  \src\tools\dev\build\imgtools\romtools\group all
-exports \src\tools\dev\build\imgtools\romtools\group 
+source  \src\tools\build\imgtools\romtools
+binary  \src\tools\build\imgtools\romtools\group all
+exports \src\tools\build\imgtools\romtools\group 
 
 binary	\epoc32\release\tools2\rel\rombuild.exe
 binary	\epoc32\release\tools2\rel\rofsbuild.exe
--- a/imgtools/romtools/maksym/fixupsym.pl	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/maksym/fixupsym.pl	Tue Jun 29 14:52:54 2010 +0800
@@ -1,470 +1,470 @@
-#
-# Copyright (c) 1999-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-# Relinks the debug exe/dlls in a ROM if the make file is present
-#
-
-require 5.003_07;
-use strict;
-no strict 'vars';
-use English;
-use Cwd;
-use FindBin;		# for FindBin::Bin
-
-my $PerlLibPath;    # fully qualified pathname of the directory containing our Perl modules
-
-BEGIN {
-# check user has a version of perl that will cope
-	require 5.005_03;
-# establish the path to the Perl libraries: currently the same directory as this script
-	$PerlLibPath = $FindBin::Bin;	# X:/epoc32/tools
-	$PerlLibPath =~ s/\//\\/g;	# X:\epoc32\tools
-	$PerlLibPath .= "\\";
-}
-
-use lib $PerlLibPath;
-use Modload;
-Load_SetModulePath($PerlLibPath);
-
-# Globals
-my $debug = 0;
-my $rombuild;
-my @executables = ( 'euser' );
-
-cwd =~ /^(.:)/o;
-my $drive = $1;
-
-# get EPOCROOT for searching directories
-my $epocroot = lc $ENV{EPOCROOT};
-
-&args;
-&main;
-
-exit 0;
-
-
-#
-# main
-#
-sub main
-  {
-	my $file;
-	my $text;
-	my $data;
-	my $bss;
-	my $textlen;
-	my $datalen;
-	my $bsslen;
-
-	open (ROM, "<$rombuild")
-	  or die "ERROR: Can't open rombuild log file \"$rombuild\"\n";
-
-	die "ERROR: \"$rombuild\" isn't a rombuild log file\n"
-	  unless ((<ROM> =~ /^ROMBUILD/) || (<ROM> =~ /^ROMBUILD/));
-	
-	# build up a hash of all the make files indexed by build and exe name
-	#
-	# do this in a more directed way based on the map files for the
-	# executables we are interested in.
-
-	%map = ();
-	&dirsearch($epocroot . "EPOC32\\", "BUILD");
-
-	while (<ROM>)
-	  {
-		if (/^Writing Rom image/)
-		  {
-		  # stop at end of first ROM, ignoring any extension ROMs
-		  # This is necessary because the same file could appear
-		  # at different places in different extensions.
-		  #
-		  last;
-		  } 
-		if (/^Processing file (.*)/)
-		  {
-			my $datalen;
-			my $skip;
-			
-			$file = lc $1;
-			$text = $bss = $data = $datalen = 0;
-			
-			# Work out final addresses of sections
-			while (defined($_=<ROM>) && !/^$/)
-			  {
-				if (/^Code start addr:\s+(\w+)/)
-				  {
-					$text = hex($1);
-				  }
-				elsif (/^DataBssLinearBase:\s+(\w+)/)
-				  {
-					$data = hex($1);
-				  }
-				elsif (/^Code size:\s+(\w+)/)
-				  {
-					$textlen = hex($1);
-				  }
-				elsif (/^Data size:\s+(\w+)/)
-				  {
-					$datalen = hex($1);
-					$bss = $data + $datalen;
-				  }
-				elsif (/^BssSize:\s+(\w+)/)
-				  {
-					$bsslen = hex($1);
-				  }
-			  }
-			
-			# Sanity check - text section can't be zero (other sections may be)
-			die "ERROR: Can't find rombuild info for \"$file\"\n"
-			  if (!$text);
-			
-			# get the build and exe name
-			# protect $epocroot with \Q and \E to stop it 
-			# using \ as a special character
-			if ($file =~ /^\Q$epocroot\Eepoc32\\release\\(.*)\\(.*)\\(.*)$/o)
-			  {
-				$build = lc $1;
-				$debrel = uc $2;
-				$executablefile = lc $3;
-			  }
-			
-			# Only relink this file if it's kernel-side or matches the regexp
-			if ($build =~ /^(M|S)/i)
-			  {
-				$skip = 0;
-			  }
-			else
-			  {
-				$skip = 1;
-				foreach $re (@executables)
-				  {
-					$skip = 0 if ($file =~ /$re/i);
-				  }
-			  }
-			print "$file - skipped\n" if ($skip && $debug);
-			next if ($skip);
-
-			if (! defined $map{"$build $executablefile"})
-			    {
-			    print "$file - no makefile\n";
-			    next;
-			    }
-			if ($debrel ne "UDEB")
-			    {
-			    print "$file - can't fixup $debrel\n";
-			    next;
-			    }
-
-			# relink this file
-			print "$file";
-			
-			# lookup the makefile name
-			($makepath, $workdir) = @{$map{"$build $executablefile"}};
-
-			# only relink if we have a makefile
-			if ($makepath && $workdir)
-			  {
-				# optimisation: don't relink if already at correct address
-				$file =~ /(.+\.)[^\.]+/;
-				my $symfile = $drive.$1."sym";
-				my $buf;
-				my $elffile;
-				open SYMFILE, $symfile or print"\nCannot open $symfile\n";	
-				read SYMFILE, $buf, 4;
-				if ($buf =~/^\x7F\x45\x4C\x46/){
-					$elffile = $buf;
-				}
-				close SYMFILE;
-				if ($elffile){
-					if ((-e $file) && (-e $symfile) &&
-						open (CHILD, "fromelf -v $symfile |"))
-					{
-						my $oldtext;
-						my $olddata;
-						my $foundcode = 0;
-						my $founddata = 0;
-						while (<CHILD>)
-						{
-							if (/ER_RO/)
-							{
-								$foundcode = 1;
-							}
-							if (/ER_RW/)
-							{
-								$founddata = 1;
-							}
-                
-							if (/Addr : 0x\w+/)
-							{
-								$_=~tr/0-9//dc;
-								if ($founddata == 1)
-								{
-									$founddata = 0;
-									$olddata = hex($_);
-								}
-                
-								if ($foundcode == 1)
-								{
-									$foundcode = 0;
-									$oldtext = hex($_);
-								}
-							}
-						}
-						close CHILD;
-						$skip = 1 if ((!$textlen || ($text == $oldtext)) && (!$datalen || ($data == $olddata)));
-					}
-				}
-				else {
-					if ((-e $file) && (-e $symfile) &&
-						open (CHILD, "objdump --headers $symfile |"))
-					{
-						my $oldtext;
-						my $olddata;
-						my $oldbss;
-						while (<CHILD>)
-						{
-							if (/^\s+\d+\s+(\.\w+)\s+[0-9a-fA-F]+\s+([0-9a-fA-F]+)\s/)
-							{
-								if ($1 eq '.text')
-								{
-									$oldtext = hex($2);
-								}
-								elsif ($1 eq '.data')
-								{
-									$olddata = hex($2);
-								}
-								elsif ($1 eq '.bss')
-								{
-									$oldbss = hex($2);
-								}
-							}
-						}
-						close CHILD;
-						$skip = 1 if ((!$textlen || ($text == $oldtext)) &&
-									(!$datalen || ($data == $olddata)) &&
-									(!$bsslen	 || ($bss  == $oldbss)));
-						print " - current" if ($skip && $debug);
-					}
-				}
-				
-				if (!$skip)
-				  {
-					chdir $workdir
-					  or die "Can't cd to build directory \"$workdir\"\n";
-
-					# save executable in case relink fails
-					rename $file, "$file.bak"
-					  or die "Can't rename \"$file\": $ERRNO\n"
-						if -e $file;
-						
-						$makepath = &fixMakefile($makepath);
-						my $command;
-						if ($elffile){
-							if($makepath =~ /\.gcce/i){
-								$command =
-									sprintf ("make -r -s -f \"$makepath\" $debrel " .
-									"USERLDFLAGS=\"-Ttext 0x%lx -Tdata 0x%lx\"", $text, $data);
-							}
-							else {
-								$command =
-									sprintf ("make -r -s -f \"$makepath\" $debrel " .
-									"USERLDFLAGS=\"--ro-base 0x%lx --rw-base 0x%lx\"", $text, $data);
-							}
-						}
-						else {
-							$command =
-								sprintf ("make -r -s -f \"$makepath\" $debrel " .
-								"USERLDFLAGS=\"--image-base 0 -Ttext 0x%lx " .
-								"-Tdata 0x%lx -Tbss 0x%lx\"",
-								$text, $data, $bss);
-						}
-						print "\n\"$command\"" if ($debug);
-
-					open (CHILD, "$command |")
-					  or die "\nERROR: Can't run \"$command\": $ERRNO\n";
-					close CHILD;
-
-					unlink $makepath;
-					if (-e $file)
-					  {
-						unlink "$file.bak";
-					  }
-					else	# relink failed for some reason - restore saved
-					  {
-						rename "$file.bak", $file;
-					  }
-				  }
-
-				print "\n";
-			  }
-			else
-			  {
-				print " - can't fixup\n";
-			  }
-		  }
-	  }
-	close ROM;
-  }
-
-#
-# args - get command line args
-#
-sub args
-  {
-	my $arg;
-	my @args;
-	my $flag;
-	
-	&help if (!@ARGV);
-	
-	while (@ARGV)
-	  {
-		$arg = shift @ARGV;
-		
-		if ($arg=~/^[\-\/](\S*)$/)
-		  {
-			$flag=$1;
-			
-			if ($flag=~/^[\?h]$/i)
-			  {
-				&help;
-			  }
-			else
-			  {
-				print "\nERROR: Unknown flag \"-$flag\"\n";
-				&usage;
-				exit 1;
-			  }
-		  }
-		else
-		  {
-			push @args,$arg;
-		  }
-	  }
-	
-	$rombuild = shift @args;
-	
-	if (@args)
-	  {
-		foreach $file (@args)
-		  {
-			push @executables, quotemeta($file);
-		  }
-	  }
-  }
-
-
-# recursive directory search
-sub dirsearch
-	{
-	my ($input_path, $dir) = @_;
-	my $searchpath = "$input_path$dir\\";
-	my $workdir;
-
-	return unless (opendir DIRHANDLE, $searchpath);
-	my @allfiles = grep !/^\.\.?$/, readdir DIRHANDLE;
-	closedir DIRHANDLE;
-
-	# Breadth first search: scan files and collect list of subdirectories
-	my @dirlist;
-	foreach $entry (@allfiles)
-		{
-		my $entrypath = "$searchpath$entry";
-		if (-d $entrypath)
-			{
-			# don't look in udeb & urel directories which contain objects and binaries
-			push @dirlist, $entry unless ($entry =~ /(deb|rel)$/i);
-			}
-		elsif ($entry =~ /$dir$/i)
-			{
-			# ARM4/xxx.ARM4 => generated makefile
-			my $liney;
-			open (FILE, "<$entrypath");
-			while ($liney=<FILE>)
-				{
-				if ($liney =~ /^\# CWD\s(.+)\\/)
-					{
-					$workdir = lc $1;
-					}
-				if ($liney =~ /^\# Target\s(.*)$/)
-					{
-					my $target = lc $1;
- 
-					# add to the hash table
-					my $build = lc $dir;
-					$map{"$build $target"} = [lc "$entrypath", $workdir];
-					$workdir = undef;
-					last;
-					}
-				}
-			close FILE;
-			}
-		}
-	undef @allfiles;
-	# Now process the subdirectories...
-	foreach $entry (@dirlist)
-		{
-		&dirsearch ($searchpath,$entry);
-		}
-	undef @dirlist;
-	}
-	
-sub help ()
-  {
-	my $build;
-	
-	&Load_ModuleL('E32TPVER');
-	print "\nfixupsym - " .
-	  "Fix up executables with locations taken from a ROM image (Build ",
-	  &E32tpver, ")\n";
-	&usage;
-	exit 0;
-  }
-	
-sub usage ()
-  {
-	print <<EOF
-		  
-Usage:
-  fixupsym <logfile> [<executables>]
-
-Where:
-  <logfile>     Log file from rombuild tool.
-  <executables> Names of additional executables to fix up.
-                ASSP-specific executables and EUSER are always included.
-
-Example:
-  fixupsym rombuild.log efile efsrv .fsy
-EOF
-  ;
-	exit 0;
-  }
-sub fixMakefile()
-  {
-	my $makefile = shift @_;
-	my $tmpMakfile = $makefile.".TMP";
-	open (FILEIN, $makefile) or die "Can't open file \"$makefile\" \n";
-	open (FILEOUT, ">".$tmpMakfile) or die "Can't create file \"$tmpMakfile\" \n";
-	while(<FILEIN>) {
-		if ($_ =~ /^\s*elf2e32/){
-			print FILEOUT "#".$_;
-		}
-		else {
-			print FILEOUT $_;
-		}
-	}
-	close FILEIN;
-	close FILEOUT;
-	$tmpMakfile;
-  }
+#
+# Copyright (c) 1999-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+# Relinks the debug exe/dlls in a ROM if the make file is present
+#
+
+require 5.003_07;
+use strict;
+no strict 'vars';
+use English;
+use Cwd;
+use FindBin;		# for FindBin::Bin
+
+my $PerlLibPath;
+
+BEGIN {
+# check user has a version of perl that will cope
+	require 5.005_03;
+	$PerlLibPath = $FindBin::Bin;	
+}
+
+use lib $PerlLibPath;
+
+use romutl;
+
+# Version
+my $MajorVersion = 1;
+my $MinorVersion = 1;
+my $PatchVersion = 1;
+
+# Globals
+my $debug = 0;
+my $rombuild;
+my @executables = ( 'euser' );
+
+cwd =~ /^(.:)/o;
+my $drive = $1;
+
+# get EPOCROOT for searching directories
+my $epocroot = lc &get_epocroot;
+
+&args;
+&main;
+
+exit 0;
+
+
+#
+# main
+#
+sub main
+  {
+	my $file;
+	my $text;
+	my $data;
+	my $bss;
+	my $textlen;
+	my $datalen;
+	my $bsslen;
+
+	open (ROM, "<$rombuild")
+	  or die "ERROR: Can't open rombuild log file \"$rombuild\"\n";
+
+	die "ERROR: \"$rombuild\" isn't a rombuild log file\n"
+	  unless ((<ROM> =~ /^ROMBUILD/) || (<ROM> =~ /^ROMBUILD/));
+	
+	# build up a hash of all the make files indexed by build and exe name
+	#
+	# do this in a more directed way based on the map files for the
+	# executables we are interested in.
+
+	%map = ();
+	&dirsearch($epocroot . "EPOC32\\", "BUILD");
+
+	while (<ROM>)
+	  {
+		if (/^Writing Rom image/)
+		  {
+		  # stop at end of first ROM, ignoring any extension ROMs
+		  # This is necessary because the same file could appear
+		  # at different places in different extensions.
+		  #
+		  last;
+		  } 
+		if (/^Processing file (.*)/)
+		  {
+			my $datalen;
+			my $skip;
+			
+			$file = lc $1;
+			$text = $bss = $data = $datalen = 0;
+			
+			# Work out final addresses of sections
+			while (defined($_=<ROM>) && !/^$/)
+			  {
+				if (/^Code start addr:\s+(\w+)/)
+				  {
+					$text = hex($1);
+				  }
+				elsif (/^DataBssLinearBase:\s+(\w+)/)
+				  {
+					$data = hex($1);
+				  }
+				elsif (/^Code size:\s+(\w+)/)
+				  {
+					$textlen = hex($1);
+				  }
+				elsif (/^Data size:\s+(\w+)/)
+				  {
+					$datalen = hex($1);
+					$bss = $data + $datalen;
+				  }
+				elsif (/^BssSize:\s+(\w+)/)
+				  {
+					$bsslen = hex($1);
+				  }
+			  }
+			
+			# Sanity check - text section can't be zero (other sections may be)
+			die "ERROR: Can't find rombuild info for \"$file\"\n"
+			  if (!$text);
+			
+			# get the build and exe name
+			# protect $epocroot with \Q and \E to stop it 
+			# using \ as a special character
+			if ($file =~ /^\Q$epocroot\Eepoc32\\release\\(.*)\\(.*)\\(.*)$/o)
+			  {
+				$build = lc $1;
+				$debrel = uc $2;
+				$executablefile = lc $3;
+			  }
+			
+			# Only relink this file if it's kernel-side or matches the regexp
+			if ($build =~ /^(M|S)/i)
+			  {
+				$skip = 0;
+			  }
+			else
+			  {
+				$skip = 1;
+				foreach $re (@executables)
+				  {
+					$skip = 0 if ($file =~ /$re/i);
+				  }
+			  }
+			print "$file - skipped\n" if ($skip && $debug);
+			next if ($skip);
+
+			if (! defined $map{"$build $executablefile"})
+			    {
+			    print "$file - no makefile\n";
+			    next;
+			    }
+			if ($debrel ne "UDEB")
+			    {
+			    print "$file - can't fixup $debrel\n";
+			    next;
+			    }
+
+			# relink this file
+			print "$file";
+			
+			# lookup the makefile name
+			($makepath, $workdir) = @{$map{"$build $executablefile"}};
+
+			# only relink if we have a makefile
+			if ($makepath && $workdir)
+			  {
+				# optimisation: don't relink if already at correct address
+				$file =~ /(.+\.)[^\.]+/;
+				my $symfile = $drive.$1."sym";
+				my $buf;
+				my $elffile;
+				open SYMFILE, $symfile or print"\nCannot open $symfile\n";	
+				read SYMFILE, $buf, 4;
+				if ($buf =~/^\x7F\x45\x4C\x46/){
+					$elffile = $buf;
+				}
+				close SYMFILE;
+				if ($elffile){
+					if ((-e $file) && (-e $symfile) &&
+						open (CHILD, "fromelf -v $symfile |"))
+					{
+						my $oldtext;
+						my $olddata;
+						my $foundcode = 0;
+						my $founddata = 0;
+						while (<CHILD>)
+						{
+							if (/ER_RO/)
+							{
+								$foundcode = 1;
+							}
+							if (/ER_RW/)
+							{
+								$founddata = 1;
+							}
+                
+							if (/Addr : 0x\w+/)
+							{
+								$_=~tr/0-9//dc;
+								if ($founddata == 1)
+								{
+									$founddata = 0;
+									$olddata = hex($_);
+								}
+                
+								if ($foundcode == 1)
+								{
+									$foundcode = 0;
+									$oldtext = hex($_);
+								}
+							}
+						}
+						close CHILD;
+						$skip = 1 if ((!$textlen || ($text == $oldtext)) && (!$datalen || ($data == $olddata)));
+					}
+				}
+				else {
+					if ((-e $file) && (-e $symfile) &&
+						open (CHILD, "objdump --headers $symfile |"))
+					{
+						my $oldtext;
+						my $olddata;
+						my $oldbss;
+						while (<CHILD>)
+						{
+							if (/^\s+\d+\s+(\.\w+)\s+[0-9a-fA-F]+\s+([0-9a-fA-F]+)\s/)
+							{
+								if ($1 eq '.text')
+								{
+									$oldtext = hex($2);
+								}
+								elsif ($1 eq '.data')
+								{
+									$olddata = hex($2);
+								}
+								elsif ($1 eq '.bss')
+								{
+									$oldbss = hex($2);
+								}
+							}
+						}
+						close CHILD;
+						$skip = 1 if ((!$textlen || ($text == $oldtext)) &&
+									(!$datalen || ($data == $olddata)) &&
+									(!$bsslen	 || ($bss  == $oldbss)));
+						print " - current" if ($skip && $debug);
+					}
+				}
+				
+				if (!$skip)
+				  {
+					chdir $workdir
+					  or die "Can't cd to build directory \"$workdir\"\n";
+
+					# save executable in case relink fails
+					rename $file, "$file.bak"
+					  or die "Can't rename \"$file\": $ERRNO\n"
+						if -e $file;
+						
+						$makepath = &fixMakefile($makepath);
+						my $command;
+						if ($elffile){
+							if($makepath =~ /\.gcce/i){
+								$command =
+									sprintf ("make -r -s -f \"$makepath\" $debrel " .
+									"USERLDFLAGS=\"-Ttext 0x%lx -Tdata 0x%lx\"", $text, $data);
+							}
+							else {
+								$command =
+									sprintf ("make -r -s -f \"$makepath\" $debrel " .
+									"USERLDFLAGS=\"--ro-base 0x%lx --rw-base 0x%lx\"", $text, $data);
+							}
+						}
+						else {
+							$command =
+								sprintf ("make -r -s -f \"$makepath\" $debrel " .
+								"USERLDFLAGS=\"--image-base 0 -Ttext 0x%lx " .
+								"-Tdata 0x%lx -Tbss 0x%lx\"",
+								$text, $data, $bss);
+						}
+						print "\n\"$command\"" if ($debug);
+
+					open (CHILD, "$command |")
+					  or die "\nERROR: Can't run \"$command\": $ERRNO\n";
+					close CHILD;
+
+					unlink $makepath;
+					if (-e $file)
+					  {
+						unlink "$file.bak";
+					  }
+					else	# relink failed for some reason - restore saved
+					  {
+						rename "$file.bak", $file;
+					  }
+				  }
+
+				print "\n";
+			  }
+			else
+			  {
+				print " - can't fixup\n";
+			  }
+		  }
+	  }
+	close ROM;
+  }
+
+#
+# args - get command line args
+#
+sub args
+  {
+	my $arg;
+	my @args;
+	my $flag;
+	
+	&help if (!@ARGV);
+	
+	while (@ARGV)
+	  {
+		$arg = shift @ARGV;
+		
+		if ($arg=~/^[\-](\S*)$/)
+		  {
+			$flag=$1;
+			
+			if ($flag=~/^[\?h]$/i)
+			  {
+				&help;
+			  }
+			else
+			  {
+				print "\nERROR: Unknown flag \"-$flag\"\n";
+				&usage;
+				exit 1;
+			  }
+		  }
+		else
+		  {
+			push @args,$arg;
+		  }
+	  }
+	
+	$rombuild = shift @args;
+	
+	if (@args)
+	  {
+		foreach $file (@args)
+		  {
+			push @executables, quotemeta($file);
+		  }
+	  }
+  }
+
+
+# recursive directory search
+sub dirsearch
+	{
+	my ($input_path, $dir) = @_;
+	my $searchpath = "$input_path$dir\\";
+	my $workdir;
+
+	return unless (opendir DIRHANDLE, $searchpath);
+	my @allfiles = grep !/^\.\.?$/, readdir DIRHANDLE;
+	closedir DIRHANDLE;
+
+	# Breadth first search: scan files and collect list of subdirectories
+	my @dirlist;
+	foreach $entry (@allfiles)
+		{
+		my $entrypath = "$searchpath$entry";
+		if (-d $entrypath)
+			{
+			# don't look in udeb & urel directories which contain objects and binaries
+			push @dirlist, $entry unless ($entry =~ /(deb|rel)$/i);
+			}
+		elsif ($entry =~ /$dir$/i)
+			{
+			# ARM4/xxx.ARM4 => generated makefile
+			my $liney;
+			open (FILE, "<$entrypath");
+			while ($liney=<FILE>)
+				{
+				if ($liney =~ /^\# CWD\s(.+)\\/)
+					{
+					$workdir = lc $1;
+					}
+				if ($liney =~ /^\# Target\s(.*)$/)
+					{
+					my $target = lc $1;
+ 
+					# add to the hash table
+					my $build = lc $dir;
+					$map{"$build $target"} = [lc "$entrypath", $workdir];
+					$workdir = undef;
+					last;
+					}
+				}
+			close FILE;
+			}
+		}
+	undef @allfiles;
+	# Now process the subdirectories...
+	foreach $entry (@dirlist)
+		{
+		&dirsearch ($searchpath,$entry);
+		}
+	undef @dirlist;
+	}
+	
+sub help ()
+  {
+	my $build;
+	
+	print "\nfixupsym - " .
+	  "Fix up executables with locations taken from a ROM image V${MajorVersion}.${MinorVersion}.${PatchVersion}\n";
+	&usage;
+	exit 0;
+  }
+	
+sub usage ()
+  {
+	print <<EOF
+		  
+Usage:
+  fixupsym <logfile> [<executables>]
+
+Where:
+  <logfile>     Log file from rombuild tool.
+  <executables> Names of additional executables to fix up.
+                ASSP-specific executables and EUSER are always included.
+
+Example:
+  fixupsym rombuild.log efile efsrv .fsy
+EOF
+  ;
+	exit 0;
+  }
+sub fixMakefile()
+  {
+	my $makefile = shift @_;
+	my $tmpMakfile = $makefile.".TMP";
+	open (FILEIN, $makefile) or die "Can't open file \"$makefile\" \n";
+	open (FILEOUT, ">".$tmpMakfile) or die "Can't create file \"$tmpMakfile\" \n";
+	while(<FILEIN>) {
+		if ($_ =~ /^\s*elf2e32/){
+			print FILEOUT "#".$_;
+		}
+		else {
+			print FILEOUT $_;
+		}
+	}
+	close FILEIN;
+	close FILEOUT;
+	$tmpMakfile;
+  }
--- a/imgtools/romtools/maksym/hpsym.pl	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/maksym/hpsym.pl	Tue Jun 29 14:52:54 2010 +0800
@@ -1,196 +1,189 @@
-#
-# Copyright (c) 1999-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-# munge maksym.log into form suitable for an HP logic analyser
-# History
-# 0.1	08/06/99	First release.
-# 0.2	09/06/99	Always include symbols from E32 and device drivers.
-# 0.3	15/06/99	Added rombase flag & argument.
-# 0.4	11/11/99	Remove c++filt step. Ensure symbols don't contain spaces.
-#
-
-# Globals
-my $rombase = 0x50000000;
-my @executables = ( 'euser' );
-
-my $maksym = 'maksym.log';
-my $gpa = 'symbols.gpa';
-my $arg;
-my $skip;
-
-# Standard e32toolp path scanning
-use FindBin;		# for FindBin::Bin
-
-my $PerlLibPath;    # fully qualified pathname of the directory containing our Perl modules
-
-BEGIN {
-# check user has a version of perl that will cope
-	require 5.005_03;
-# establish the path to the Perl libraries: currently the same directory as this script
-	$PerlLibPath = $FindBin::Bin;	# X:/epoc32/tools
-	$PerlLibPath =~ s/\//\\/g;	# X:\epoc32\tools
-	$PerlLibPath .= "\\";
-}
-
-use lib $PerlLibPath;
-use Modload;
-Load_SetModulePath($PerlLibPath);
-
-if (@ARGV)
-  {
-	$maksym = shift;
-	if ($maksym =~ /^-[h\?]$/i)
-	  {
-		&help;
-	  }
-	elsif ($maksym =~ /^(-r)/i)
-	  {
-		if (@ARGV)
-		  {
-			$rombase=hex(shift);
-			if (@ARGV)
-			  {
-				$maksym = shift;
-			  }
-			else
-			  {
-				print "\nError: missing <infile> argument.\n";
-				&usage;
-				exit 1;
-			  }
-		  }
-		else
-		  {
-			print "\nError: rombase flag '-r' requires an argument.\n";
-			&usage;
-			exit 1;
-		  }
-	  }
-	elsif ($maksym =~ /^(-.*)/)
-	  {
-		print "\nError: invalid flag '$1'\n.";
-		&usage;
-		exit 1;
-	  }
-
-	if (@ARGV)
-	  {
-		my $file;
-
-		$gpa = shift;
-		
-		foreach $file (@ARGV)
-		  {
-			push @executables, quotemeta($file);
-		  }
-	  }
-  }
-else
-  {
-	&help;
-  }
-		
-open (GPA, ">$gpa") or die "Can't write to '$gpa'";
-open (LOG, "$maksym") or die "Can't read '$maksym'";
-
-while (<LOG>)
-  {
-	if (/^From\s+\S+\\(.+)\\.+\\(.+)$/)
-	  {
-		# Found a new file
-		$abi = $1;
-		$file = $2;
-
-		# Decode this file if it's kernel-side or matches the supplied regexp
-		if ($abi =~ /^(M|S)/i)
-		  {
-			$skip = 0;
-		  }
-		else
-		  {
-			$skip = 1;
-			foreach $re (@executables)
-			  {
-				$skip = 0 if ($file =~ /$re/i);
-			  }
-		  }
-		print "$file\n" if not $skip;
-	  }
-	elsif (!/^$/ && !$skip)
-	  {
-		/^(\S*)\s*(\S*)\s*(.*)$/;
-		$addr=hex($1) - $rombase;
-		$len=(hex($2)<0) ? 4 : hex($2);
-		$name = $3;
-		$name =~ s/\(.*//;		# remove arguments and any const qualifier
-
-		# remove spaces from symbol names
-		if ($name =~ 'global constructors keyed to (.*)')
-		  {
-			$name = $1.'_CTOR';
-		  }
-		elsif ($name =~ 'global destructors keyed to (.*)')
-		  {
-			$name = $1.'_DTOR';
-		  }
-		elsif ($name =~ '(.*) virtual table')
-		  {
-			$name = $1.'_VTBL';
-		  }
-		else
-		  {
-			$name =~ s/ /_/g;
-		  }
-		print GPA "$name\t", sprintf('%08x', $addr), '..',
-		  sprintf('%08x', $addr+$len-1), "\n";
-	  }
-  }
-
-close LOG;
-close GPA;
-exit 0;
-
-
-sub help ()
-  {
-	my $build;
-
-	&Load_ModuleL('E32TPVER');
-	print "\nhpsym - Produce symbolic info in \"HP GPA Symbol File Format\"" .
-	  " suitable for use\n        with a HP logic analyser (Build ",
-	  &E32tpver, ")\n";
-	&usage;
-	exit 0;
-  }
-
-sub usage ()
-  {
-	print <<EOF
-
-Usage:
-  hpsym [-r <rombase>] <logfile> [<outfile> [<executables>]]
-
-Where:
-  <rombase>     Offset in hex of logical address from physical address of ROM.
-                Defaults to 50000000. Use 0 for single-process builds.
-  <logfile>     Log from maksym tool.
-  <outfile>     Output filename. Default is 'symbols.gpa'. Use - for stdout.
-  <executables> Names of additional executables to list the symbols of.
-                ASSP-specific executables and EUSER are always included.
-
-Example:
-  hpsym maksym.log symbols.gpa efile efsrv .fsy
-
-EOF
-  }
+#
+# Copyright (c) 1999-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+# munge maksym.log into form suitable for an HP logic analyser
+# History
+# 0.1	08/06/99	First release.
+# 0.2	09/06/99	Always include symbols from E32 and device drivers.
+# 0.3	15/06/99	Added rombase flag & argument.
+# 0.4	11/11/99	Remove c++filt step. Ensure symbols don't contain spaces.
+#
+
+# Globals
+my $rombase = 0x50000000;
+my @executables = ( 'euser' );
+
+my $maksym = 'maksym.log';
+my $gpa = 'symbols.gpa';
+my $arg;
+my $skip;
+
+# Standard e32toolp path scanning
+use FindBin;		# for FindBin::Bin
+
+BEGIN {
+# check user has a version of perl that will cope
+	require 5.005_03;
+}
+
+# Version
+my $MajorVersion = 1;
+my $MinorVersion = 1;
+my $PatchVersion = 0;
+
+if (@ARGV)
+  {
+	$maksym = shift;
+	if ($maksym =~ /^-[h\?]$/i)
+	  {
+		&help;
+	  }
+	elsif ($maksym =~ /^(-r)/i)
+	  {
+		if (@ARGV)
+		  {
+			$rombase=hex(shift);
+			if (@ARGV)
+			  {
+				$maksym = shift;
+			  }
+			else
+			  {
+				print "\nError: missing <infile> argument.\n";
+				&usage;
+				exit 1;
+			  }
+		  }
+		else
+		  {
+			print "\nError: rombase flag '-r' requires an argument.\n";
+			&usage;
+			exit 1;
+		  }
+	  }
+	elsif ($maksym =~ /^(-.*)/)
+	  {
+		print "\nError: invalid flag '$1'\n.";
+		&usage;
+		exit 1;
+	  }
+
+	if (@ARGV)
+	  {
+		my $file;
+
+		$gpa = shift;
+		
+		foreach $file (@ARGV)
+		  {
+			push @executables, quotemeta($file);
+		  }
+	  }
+  }
+else
+  {
+	&help;
+  }
+		
+open (GPA, ">$gpa") or die "Can't write to '$gpa'";
+open (LOG, "$maksym") or die "Can't read '$maksym'";
+
+while (<LOG>)
+  {
+	if (/^From\s+\S+\\(.+)\\.+\\(.+)$/)
+	  {
+		# Found a new file
+		$abi = $1;
+		$file = $2;
+
+		# Decode this file if it's kernel-side or matches the supplied regexp
+		if ($abi =~ /^(M|S)/i)
+		  {
+			$skip = 0;
+		  }
+		else
+		  {
+			$skip = 1;
+			foreach $re (@executables)
+			  {
+				$skip = 0 if ($file =~ /$re/i);
+			  }
+		  }
+		print "$file\n" if not $skip;
+	  }
+	elsif (!/^$/ && !$skip)
+	  {
+		/^(\S*)\s*(\S*)\s*(.*)$/;
+		$addr=hex($1) - $rombase;
+		$len=(hex($2)<0) ? 4 : hex($2);
+		$name = $3;
+		$name =~ s/\(.*//;		# remove arguments and any const qualifier
+
+		# remove spaces from symbol names
+		if ($name =~ 'global constructors keyed to (.*)')
+		  {
+			$name = $1.'_CTOR';
+		  }
+		elsif ($name =~ 'global destructors keyed to (.*)')
+		  {
+			$name = $1.'_DTOR';
+		  }
+		elsif ($name =~ '(.*) virtual table')
+		  {
+			$name = $1.'_VTBL';
+		  }
+		else
+		  {
+			$name =~ s/ /_/g;
+		  }
+		print GPA "$name\t", sprintf('%08x', $addr), '..',
+		  sprintf('%08x', $addr+$len-1), "\n";
+	  }
+  }
+
+close LOG;
+close GPA;
+exit 0;
+
+
+sub help ()
+  {
+	my $build;
+
+	print "\nhpsym - Produce symbolic info in \"HP GPA Symbol File Format\"" .
+	  " suitable for use\n        with a HP logic analyser V${MajorVersion}.${MinorVersion}.${PatchVersion}\n";
+	&usage;
+	exit 0;
+  }
+
+sub usage ()
+  {
+	print <<EOF
+
+Usage:
+  hpsym [-r <rombase>] <logfile> [<outfile> [<executables>]]
+
+Where:
+  <rombase>     Offset in hex of logical address from physical address of ROM.
+                Defaults to 50000000. Use 0 for single-process builds.
+  <logfile>     Log from maksym tool.
+  <outfile>     Output filename. Default is 'symbols.gpa'. Use - for stdout.
+  <executables> Names of additional executables to list the symbols of.
+                ASSP-specific executables and EUSER are always included.
+
+Example:
+  hpsym maksym.log symbols.gpa efile efsrv .fsy
+
+EOF
+  }
--- a/imgtools/romtools/maksym/maksym.pl	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/maksym/maksym.pl	Tue Jun 29 14:52:54 2010 +0800
@@ -1,408 +1,397 @@
-#
-# Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-# Produces symbolic information given a ROM image
-#
-
-require 5.003_07;
-no strict 'vars';
-use English;
-use FindBin;		# for FindBin::Bin
-
-my $PerlLibPath;    # fully qualified pathname of the directory containing our Perl modules
-
-BEGIN {
-    # check user has a version of perl that will cope require 5.005_03;
-    # establish the path to the Perl libraries: currently the same directory as this script
-    $PerlLibPath = $FindBin::Bin; # X:/epoc32/tools
-    $PerlLibPath =~ s/\//\\/g;	# X:\epoc32\tools
-    $PerlLibPath .= "\\";
-}
-
-use lib $PerlLibPath;
-use Modload;
-Load_SetModulePath($PerlLibPath);
-
-# Globals
-my $maksym = "";
-my $rombuild;
-my $debug = 0;
-
-&args;
-&main;
-
-exit 0;
-
-sub CompareAddrs()
-{
-    return -1 if ($a < $b);
-    return 1 if ($a > $b);
-    return 0;
-}
-
-#
-# main
-#
-sub main()
-{
-  my $file;
-  my $mapfile;
-  my $mapfile2;
-  my $text;
-  my $data;
-  my $bss;
-  my $textsize;
-  my $datasize;
-  my $bsssize;
-  my $totaldatasize;
-  my $totalsize;
-
-  open (ROM, "<$rombuild")
-    or die "ERROR: Can't open rombuild log file \"$rombuild\"\n";
-  if ($maksym ne "") {
-    open (SYM, ">$maksym")
-      or die "ERROR: Can't open output file \"$maksym\"\n";
-    print "Creating $maksym...\n";
-  }
-
-  while (<ROM>) {
-    # Start of ROM
-    if (/^Creating Rom image (\S*)/) {
-      if ($maksym eq "") {
-	# For backwards compatibility, replace trailing .img with .symbol
-	# if no trailing .img, just append .symbol anyway
-	$maksym = $1;
-	$maksym =~ s/(\.img)?$/.symbol/i;
-	close SYM;
-	open (SYM, ">$maksym")
-	  or die "ERROR: Can't open output file \"$maksym\"\n";
-	print "\nCreating $maksym...\n";
-      }
-      next;
-    }
-    # end of ROM
-    if (/^Writing Rom image/) {
-      close SYM;
-      $maksym = "";
-      next;
-    }
-    # Data file
-    if (/^Reading resource (.*) to rom linear address (.*)/) {
-      $file = $1;
-      my $data = hex($2);
-      $file =~ /([^\\]+)$/;
-      printf SYM "\nFrom    $file\n\n%08x    0000    $1\n", $data;
-    }
-    # Executable file
-    elsif (/^Processing file (.*)/) {
-      $file = $1;
-      $text = 0;
-      $data = 0;
-      $bss = 0;
-      $textsize = 0;
-      $datasize = 0;
-      $bsssize = 0;
-      $totaldatasize = 0;
-
-      # Work out final addresses of sections
-      while (defined($_=<ROM>) && !/^$/) {
-	if (/^Size:\s+(\w+)/) {
-	  $totalsize = hex($1);
-	} elsif (/^Code start addr:\s+(\w+)/) {
-	  $text = hex($1);
-	} elsif (/^Data start addr:\s+(\w+)/) {
-	  $data = hex($1);
-	} elsif (/^DataBssLinearBase:\s+(\w+)/) {
-	  $bss = hex($1);
-	} elsif (/^Text size:\s+(\w+)/) {
-	  $textsize = hex($1);
-	} elsif (/^Data size:\s+(\w+)/) {
-	  $datasize = hex($1);
-	} elsif (/^Bsssize:\s+(\w+)/) {
-	  $bsssize = hex($1);
-	} elsif (/^Total data size:\s+(\w+)/) {
-	  $totaldatasize = hex($1);
-	}
-      }
-
-      # Sanity check - text section can't be zero
-      die "ERROR: Can't find rombuild info for \"$file\"\n"
-	if (!$text);
-
-      print SYM "\nFrom    $file\n\n";
-
-      # Look in map file for symbols in .text and relocate them
-      $mapfile2 = $file.".map";
-      $mapfile = $file;
-      $mapfile =~ s/\.\w+$/\.map/;
-      if (!(open (MAP, "$mapfile2") || open (MAP, "$mapfile"))) {
-	print "$file\nWarning: Can't open \"$mapfile2\" or \"$mapfile\"\n";
-	$file =~ /([^\\]+)$/;
-	printf SYM "%08x    %04x    $1\n", $text, $totalsize;
-      } else {
-	local $/ = undef;
-	my (@maplines) = split(/\n/, <MAP>);
-	close MAP;
-	# See if we're dealing with the RVCT output
-	if ($maplines[0] =~ /^ARM Linker/) {
-	  print "$file\n";
-	 
-		my %syms;
-		my @hasharray;
-		# Starts from begining of map file.		
-		while (@maplines) {
-		  $_ = shift @maplines;
-		  if (/Global Symbols/) {
-		    last;
-		  } elsif (!/(ARM Code|Thumb Code)/) {
-		    next;
-		  }
-		# name address type size section
-		if (/^\s*(.+)\s*(0x\S+)\s+(ARM Code|Thumb Code)\s+[^\d]*(\d+)\s+(.*)$/) {
-			# Check for static methods in local symbols section.
-			my $sym = $1;
-			my $addr = hex($2);
-			my $size = sprintf("%04x",$4);
-			my $section = $5;
-			$size = sprintf("%04x", 8) if ($section =~ /\(StubCode\)/);
-			if(exists($syms{$addr})) {
-				push @{ $syms{$addr} }, "$size    $sym $section";	   
-			}
-			elsif ($addr > 0){
-				@hasharray = "$size    $sym $section";
-				$syms{$addr} = [@hasharray];
-			}
-		}
-		}	
-	
-	  foreach (@maplines) {
-	    # name address ignore size section
-	    if (/^\s*(.+)\s*(0x\S+)\s+[^\d]*(\d+)\s+(.*)$/) {
-	      my $sym = $1;
-	      my $addr = hex($2);
-	      my $size = sprintf("%04x",$3);
-	      my $section = $4;
-	      $size = sprintf("%04x", 8) if ($section =~ /\(StubCode\)/);
-		  if(exists($syms{$addr})) {
-			push @{ $syms{$addr} }, "$size    $sym $section";	   
-		  }
-	      elsif ($addr > 0) {
-			@hasharray = "$size    $sym $section"; 
-			$syms{$addr} = [@hasharray];
-		  }
-	    }
-	  } # end of foreach
-
-	  # .text gets linked at 0x00008000
-	  # .data gets linked at 0x00400000
-	  my $srctext = hex(8000);
-	  my $srcdata = hex(400000);
-	  my $j; 
-	  # Write symbols in address order
-	  my @addrs = sort CompareAddrs keys %syms;
-	  for ($i = 0; $i < @addrs ; $i++) {
-	    my $thisaddr = $addrs[$i];
-	    my $romaddr = 0;
-	    # see if its in the text segment
-		if ($thisaddr >= $srctext && $thisaddr <= ($srctext+$textsize)) {
-	      $romaddr = $thisaddr-$srctext+$text;
-	    } elsif ( $data && ( $thisaddr >= $srcdata && $thisaddr <= ($srcdata+$datasize))) {
-	      # its in the data segment
-	      # is it from .data or .bss
-
-  			# confusingly (?) $bss is the right value to use here
-			# since we're interested in where the data gets copied to
-			# in RAM rather than where it sits in ROM
-		$romaddr = $thisaddr-$srcdata+$bss;
-	      } elsif ( $bss && ( $thisaddr >= $srcdata && $thisaddr <= ($srcdata+$totaldatasize))) {
-				# its BSS
-		$romaddr = $thisaddr-$srcdata+$bss;
-	      } else {
-		my $errsym = $syms{$thisaddr}[0];
-		my $erraddr = sprintf("%08x", $thisaddr);
-		print "WARNING: Symbol $errsym @ $erraddr not in text or data segments\n";
-		print "WARNING: The map file for binary $file is out-of-sync with the binary itself\n\n";
-		next;
-	      }
-
-	    printf SYM "%08x    %s\n", $romaddr, $_ for @{$syms{$addrs[$i]}};
-	  } # end of for.
-        # See if we're dealing with the GCC output
-	} elsif ($maplines[0] =~ /^Archive member included/) {
-	  
-	  my $imgtext;
-	  my $textlen;
-	  my %syms;
-	  my $stubhex=1;
-
-	  # Find text section
-	  while (@maplines) {
-	      $_ = shift @maplines;
-	      last if /^\.text\s+/;
-	  }
-
-	  /^\.text\s+(\w+)\s+(\w+)/
-			or die "ERROR: Can't get .text section info for \"$file\"\n";
-
-		    $imgtext=hex($1);
-		    $textlen=hex($2);
-
-		    print "$file\n";
-
-		# Slurp symbols 'til the end of the text section
-		foreach (@maplines) {
-
-			# blank line marks the end of the text section
-			last if (/^$/);
-
-			# .text <addr> <len>  <library(member)>
-			# .text$something
-			#       <addr> <len>  <library(member)>
-			#       <addr> <len>  LONG 0x0
-
-			if (/^\s(\.text)?\s+(0x\w+)\s+(0x\w+)\s+(.*)$/io) {
-				my $address = hex($2);
-				my $length = hex($3);
-				my $libraryfile = $4;
-				next if ($libraryfile =~ /^LONG 0x/);
-				$syms{$address+$length} = ' ';	# impossible symbol as end marker
-
-				# EUSER.LIB(ds01423.o)
-				# EUSER.LIB(C:/TEMP/d1000s_01423.o)
-				if ($libraryfile =~ /.*lib\(.*d\d*s_?\d{5}.o\)$/io) {
-					$stubhex=$address;
-				}
-				next;
-			}
-
-			#  <addr>  <symbol name possibly including spaces>
-			if (/^\s+(\w+)\s\s+([a-zA-Z_].+)/o) {
-				my $addr = hex($1);
-				my $symbol = $2;
-				$symbol = "stub $symbol" if ($addr == $stubhex);
-				$syms{$addr} = $symbol;
-				next;
-			}
-		}
-
-		# Write symbols in address order
-		@addrs = sort CompareAddrs keys %syms;
-		for ($i = 0; $i < @addrs - 1; $i++) {
-			my $symbol = $syms{$addrs[$i]};
-			next if ($symbol eq ' ');
-			printf SYM "%08x    %04x    %s\n",
-			$addrs[$i]-$imgtext+$text, $addrs[$i+1]-$addrs[$i], $symbol;
-		}
-		# last address assumed to be imgtext+lentext
-
-		close MAP;
-	}
-	# Must be x86 output
-	else {
-		while (@maplines) {
-	      $_ = shift @maplines;
-	      last if /^  Address/;
-		}
-	    shift @maplines;
-	    
-	    my ($lastname, $lastaddr);
-		while (@maplines) {
-	      $_ = shift @maplines;
-	      last unless /^ 0001:(\w+)\s+(\S+)/;
-		  my ($addr, $name) = (hex $1, $2);
-		  if ($lastname) {
-			  my $size = $addr - $lastaddr;
-			  printf SYM "%08x    %04x    %s\n", $lastaddr + $text, $size, $lastname;
-		  }
-		  ($lastname, $lastaddr) = ($name, $addr);
-	    }	    
-	    printf SYM "%08x    %04x    %s\n", $lastaddr + $text, 0, $lastname if $lastname;
-	}
-	
-	    }
-	  }
-	}
-    close SYM;
-    close ROM;
-}
-
-#
-# args - get command line args
-#
-sub args
-{
-    my $arg;
-    my @args;
-    my $flag;
-
-    &help if (!@ARGV);
-
-    while (@ARGV) {
-	$arg = shift @ARGV;
-
-	if ($arg=~/^[\-\/](\S*)$/) {
-	    $flag=$1;
-
-	    if ($flag=~/^[\?h]$/i) {
-		&help;
-	    } elsif ($flag=~/^d$/i) {
-		$debug = 1;
-	    } else {
-		print "\nERROR: Unknown flag \"-$flag\"\n";
-		&usage;
-		exit 1;
-	    }
-	} else {
-	    push @args,$arg;
-	}
-    }
-
-    if (@args) {
-	$rombuild = shift @args;
-	if (@args) {
-	    $maksym = shift @args;
-	    if (@args) {
-		print "\nERROR: Incorrect argument(s) \"@args\"\n";
-		&usage;
-		exit 1;
-	    }
-	}
-    }
-}
-
-sub help ()
-{
-    my $build;
-
-    &Load_ModuleL('E32TPVER');
-    print "\nmaksym - Produce symbolic information given a ROM image (Build ",
-	&E32tpver, ")\n";
-    &usage;
-    exit 0;
-}
-
-sub usage ()
-{
-    print <<EOF
-
-Usage:
-  maksym <logfile> [<outfile>]
-
-Where:
-  <logfile>   Log file from rombuild tool.
-  <outfile>   Output file. Defaults to imagename.symbol.
-EOF
-    ;
-    exit 0;
-}
+#
+# Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+# Produces symbolic information given a ROM image
+#
+
+require 5.003_07;
+no strict 'vars';
+use English;
+use FindBin;		# for FindBin::Bin
+
+# Version
+my $MajorVersion = 1;
+my $MinorVersion = 1;
+my $PatchVersion = 0;
+
+# Globals
+my $maksym = "";
+my $rombuild;
+my $debug = 0;
+
+&args;
+&main;
+
+exit 0;
+
+sub CompareAddrs()
+{
+    return -1 if ($a < $b);
+    return 1 if ($a > $b);
+    return 0;
+}
+
+#
+# main
+#
+sub main()
+{
+  my $file;
+  my $mapfile;
+  my $mapfile2;
+  my $text;
+  my $data;
+  my $bss;
+  my $textsize;
+  my $datasize;
+  my $bsssize;
+  my $totaldatasize;
+  my $totalsize;
+
+  open (ROM, "<$rombuild")
+    or die "ERROR: Can't open rombuild log file \"$rombuild\"\n";
+  if ($maksym ne "") {
+    open (SYM, ">$maksym")
+      or die "ERROR: Can't open output file \"$maksym\"\n";
+    print "Creating $maksym...\n";
+  }
+
+  while (<ROM>) {
+    # Start of ROM
+    if (/^Creating Rom image (\S*)/) {
+      if ($maksym eq "") {
+	# For backwards compatibility, replace trailing .img with .symbol
+	# if no trailing .img, just append .symbol anyway
+	$maksym = $1;
+	$maksym =~ s/(\.img)?$/.symbol/i;
+	close SYM;
+	open (SYM, ">$maksym")
+	  or die "ERROR: Can't open output file \"$maksym\"\n";
+	print "\nCreating $maksym...\n";
+      }
+      next;
+    }
+    # end of ROM
+    if (/^Writing Rom image/) {
+      close SYM;
+      $maksym = "";
+      next;
+    }
+    # Data file
+    if (/^Reading resource (.*) to rom linear address (.*)/) {
+      $file = $1;
+      my $data = hex($2);
+      $file =~ /([^\\]+)$/;
+      printf SYM "\nFrom    $file\n\n%08x    0000    $1\n", $data;
+    }
+    # Executable file
+    elsif (/^Processing file (.*)/) {
+      $file = $1;
+      $text = 0;
+      $data = 0;
+      $bss = 0;
+      $textsize = 0;
+      $datasize = 0;
+      $bsssize = 0;
+      $totaldatasize = 0;
+
+      # Work out final addresses of sections
+      while (defined($_=<ROM>) && !/^$/) {
+	if (/^Size:\s+(\w+)/) {
+	  $totalsize = hex($1);
+	} elsif (/^Code start addr:\s+(\w+)/) {
+	  $text = hex($1);
+	} elsif (/^Data start addr:\s+(\w+)/) {
+	  $data = hex($1);
+	} elsif (/^DataBssLinearBase:\s+(\w+)/) {
+	  $bss = hex($1);
+	} elsif (/^Text size:\s+(\w+)/) {
+	  $textsize = hex($1);
+	} elsif (/^Data size:\s+(\w+)/) {
+	  $datasize = hex($1);
+	} elsif (/^Bsssize:\s+(\w+)/) {
+	  $bsssize = hex($1);
+	} elsif (/^Total data size:\s+(\w+)/) {
+	  $totaldatasize = hex($1);
+	}
+      }
+
+      # Sanity check - text section can't be zero
+      die "ERROR: Can't find rombuild info for \"$file\"\n"
+	if (!$text);
+
+      print SYM "\nFrom    $file\n\n";
+
+      # Look in map file for symbols in .text and relocate them
+      $mapfile2 = $file.".map";
+      $mapfile = $file;
+      $mapfile =~ s/\.\w+$/\.map/;
+      if (!(open (MAP, "$mapfile2") || open (MAP, "$mapfile"))) {
+	print "$file\nWarning: Can't open \"$mapfile2\" or \"$mapfile\"\n";
+	$file =~ /([^\\]+)$/;
+	printf SYM "%08x    %04x    $1\n", $text, $totalsize;
+      } else {
+	local $/ = undef;
+	my (@maplines) = split(/\n/, <MAP>);
+	close MAP;
+	# See if we're dealing with the RVCT output
+	if ($maplines[0] =~ /^ARM Linker/) {
+	  print "$file\n";
+	 
+		my %syms;
+		my @hasharray;
+		# Starts from begining of map file.		
+		while (@maplines) {
+		  $_ = shift @maplines;
+		  if (/Global Symbols/) {
+		    last;
+		  } elsif (!/(ARM Code|Thumb Code)/) {
+		    next;
+		  }
+		# name address type size section
+		if (/^\s*(.+)\s*(0x\S+)\s+(ARM Code|Thumb Code)\s+[^\d]*(\d+)\s+(.*)$/) {
+			# Check for static methods in local symbols section.
+			my $sym = $1;
+			my $addr = hex($2);
+			my $size = sprintf("%04x",$4);
+			my $section = $5;
+			$size = sprintf("%04x", 8) if ($section =~ /\(StubCode\)/);
+			if(exists($syms{$addr})) {
+				push @{ $syms{$addr} }, "$size    $sym $section";	   
+			}
+			elsif ($addr > 0){
+				@hasharray = "$size    $sym $section";
+				$syms{$addr} = [@hasharray];
+			}
+		}
+		}	
+	
+	  foreach (@maplines) {
+	    # name address ignore size section
+	    if (/^\s*(.+)\s*(0x\S+)\s+[^\d]*(\d+)\s+(.*)$/) {
+	      my $sym = $1;
+	      my $addr = hex($2);
+	      my $size = sprintf("%04x",$3);
+	      my $section = $4;
+	      $size = sprintf("%04x", 8) if ($section =~ /\(StubCode\)/);
+		  if(exists($syms{$addr})) {
+			push @{ $syms{$addr} }, "$size    $sym $section";	   
+		  }
+	      elsif ($addr > 0) {
+			@hasharray = "$size    $sym $section"; 
+			$syms{$addr} = [@hasharray];
+		  }
+	    }
+	  } # end of foreach
+
+	  # .text gets linked at 0x00008000
+	  # .data gets linked at 0x00400000
+	  my $srctext = hex(8000);
+	  my $srcdata = hex(400000);
+	  my $j; 
+	  # Write symbols in address order
+	  my @addrs = sort CompareAddrs keys %syms;
+	  for ($i = 0; $i < @addrs ; $i++) {
+	    my $thisaddr = $addrs[$i];
+	    my $romaddr = 0;
+	    # see if its in the text segment
+		if ($thisaddr >= $srctext && $thisaddr <= ($srctext+$textsize)) {
+	      $romaddr = $thisaddr-$srctext+$text;
+	    } elsif ( $data && ( $thisaddr >= $srcdata && $thisaddr <= ($srcdata+$datasize))) {
+	      # its in the data segment
+	      # is it from .data or .bss
+
+  			# confusingly (?) $bss is the right value to use here
+			# since we're interested in where the data gets copied to
+			# in RAM rather than where it sits in ROM
+		$romaddr = $thisaddr-$srcdata+$bss;
+	      } elsif ( $bss && ( $thisaddr >= $srcdata && $thisaddr <= ($srcdata+$totaldatasize))) {
+				# its BSS
+		$romaddr = $thisaddr-$srcdata+$bss;
+	      } else {
+		my $errsym = $syms{$thisaddr}[0];
+		my $erraddr = sprintf("%08x", $thisaddr);
+		print "WARNING: Symbol $errsym @ $erraddr not in text or data segments\n";
+		print "WARNING: The map file for binary $file is out-of-sync with the binary itself\n\n";
+		next;
+	      }
+
+	    printf SYM "%08x    %s\n", $romaddr, $_ for @{$syms{$addrs[$i]}};
+	  } # end of for.
+        # See if we're dealing with the GCC output
+	} elsif ($maplines[0] =~ /^Archive member included/) {
+	  
+	  my $imgtext;
+	  my $textlen;
+	  my %syms;
+	  my $stubhex=1;
+
+	  # Find text section
+	  while (@maplines) {
+	      $_ = shift @maplines;
+	      last if /^\.text\s+/;
+	  }
+
+	  /^\.text\s+(\w+)\s+(\w+)/
+			or die "ERROR: Can't get .text section info for \"$file\"\n";
+
+		    $imgtext=hex($1);
+		    $textlen=hex($2);
+
+		    print "$file\n";
+
+		# Slurp symbols 'til the end of the text section
+		foreach (@maplines) {
+
+			# blank line marks the end of the text section
+			last if (/^$/);
+
+			# .text <addr> <len>  <library(member)>
+			# .text$something
+			#       <addr> <len>  <library(member)>
+			#       <addr> <len>  LONG 0x0
+
+			if (/^\s(\.text)?\s+(0x\w+)\s+(0x\w+)\s+(.*)$/io) {
+				my $address = hex($2);
+				my $length = hex($3);
+				my $libraryfile = $4;
+				next if ($libraryfile =~ /^LONG 0x/);
+				$syms{$address+$length} = ' ';	# impossible symbol as end marker
+
+				# EUSER.LIB(ds01423.o)
+				# EUSER.LIB(C:/TEMP/d1000s_01423.o)
+				if ($libraryfile =~ /.*lib\(.*d\d*s_?\d{5}.o\)$/io) {
+					$stubhex=$address;
+				}
+				next;
+			}
+
+			#  <addr>  <symbol name possibly including spaces>
+			if (/^\s+(\w+)\s\s+([a-zA-Z_].+)/o) {
+				my $addr = hex($1);
+				my $symbol = $2;
+				$symbol = "stub $symbol" if ($addr == $stubhex);
+				$syms{$addr} = $symbol;
+				next;
+			}
+		}
+
+		# Write symbols in address order
+		@addrs = sort CompareAddrs keys %syms;
+		for ($i = 0; $i < @addrs - 1; $i++) {
+			my $symbol = $syms{$addrs[$i]};
+			next if ($symbol eq ' ');
+			printf SYM "%08x    %04x    %s\n",
+			$addrs[$i]-$imgtext+$text, $addrs[$i+1]-$addrs[$i], $symbol;
+		}
+		# last address assumed to be imgtext+lentext
+
+		close MAP;
+	}
+	# Must be x86 output
+	else {
+		while (@maplines) {
+	      $_ = shift @maplines;
+	      last if /^  Address/;
+		}
+	    shift @maplines;
+	    
+	    my ($lastname, $lastaddr);
+		while (@maplines) {
+	      $_ = shift @maplines;
+	      last unless /^ 0001:(\w+)\s+(\S+)/;
+		  my ($addr, $name) = (hex $1, $2);
+		  if ($lastname) {
+			  my $size = $addr - $lastaddr;
+			  printf SYM "%08x    %04x    %s\n", $lastaddr + $text, $size, $lastname;
+		  }
+		  ($lastname, $lastaddr) = ($name, $addr);
+	    }	    
+	    printf SYM "%08x    %04x    %s\n", $lastaddr + $text, 0, $lastname if $lastname;
+	}
+	
+	    }
+	  }
+	}
+    close SYM;
+    close ROM;
+}
+
+#
+# args - get command line args
+#
+sub args
+{
+    my $arg;
+    my @args;
+    my $flag;
+
+    &help if (!@ARGV);
+
+    while (@ARGV) {
+	$arg = shift @ARGV;
+
+	if ($arg=~/^[\-](\S*)$/) {
+	    $flag=$1;
+
+	    if ($flag=~/^[\?h]$/i) {
+		&help;
+	    } elsif ($flag=~/^d$/i) {
+		$debug = 1;
+	    } else {
+		print "\nERROR: Unknown flag \"-$flag\"\n";
+		&usage;
+		exit 1;
+	    }
+	} else {
+	    push @args,$arg;
+	}
+    }
+
+    if (@args) {
+	$rombuild = shift @args;
+	if (@args) {
+	    $maksym = shift @args;
+	    if (@args) {
+		print "\nERROR: Incorrect argument(s) \"@args\"\n";
+		&usage;
+		exit 1;
+	    }
+	}
+    }
+}
+
+sub help ()
+{
+    my $build;
+
+    print "\nmaksym - Produce symbolic information given a ROM image V${MajorVersion}.${MinorVersion}.${PatchVersion}\n";
+    &usage;
+    exit 0;
+}
+
+sub usage ()
+{
+    print <<EOF
+
+Usage:
+  maksym <logfile> [<outfile>]
+
+Where:
+  <logfile>   Log file from rombuild tool.
+  <outfile>   Output file. Defaults to imagename.symbol.
+EOF
+    ;
+    exit 0;
+}
--- a/imgtools/romtools/maksym/maksymrofs.pl	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/maksym/maksymrofs.pl	Tue Jun 29 14:52:54 2010 +0800
@@ -1,409 +1,385 @@
-#
-# Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-# All rights reserved.
-# This component and the accompanying materials are made available
-# under the terms of the License "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: 
-# Produces symbolic information given a ROFS log file and .map files for relevant binary files
-#
-
-require 5.003_07;
-no strict 'vars';
-use English;
-use FindBin;		# for FindBin::Bin
-
-my $PerlLibPath;    # fully qualified pathname of the directory containing our Perl modules
-
-BEGIN {
-    # check user has a version of perl that will cope require 5.005_03;
-    # establish the path to the Perl libraries: currently the same directory as this script
-    $PerlLibPath = $FindBin::Bin; # X:/epoc32/tools
-    $PerlLibPath =~ s/\//\\/g;	# X:\epoc32\tools
-    $PerlLibPath .= "\\";
-}
-
-use lib $PerlLibPath;
-use Modload;
-Load_SetModulePath($PerlLibPath);
-
-# Globals
-my $maksym = "";
-my $rofsbuild;
-my $debug = 0;
-
-&args;
-&main;
-exit 0;
-
-sub CompareAddrs()
-{
-    return -1 if ($a < $b);
-    return 1 if ($a > $b);
-    return 0;
-}
-
-#
-# main
-#
-sub main()
-{
-	open (ROFS, "<$rofsbuild") or die "ERROR: Can't open rofsbuild log file \"$rofsbuild\"\n";
-	if ($maksym ne "") 
-	{
-		open (SYM, ">$maksym") or die "ERROR: Can't open output file \"$maksym\"\n";
-   		print "Creating $maksym...\n"
-	}
-	
-	my $curretnLine;
-	while ($currentLine = <ROFS>) 	
-	{
-		# Check that the given log file is from a rofs image and set up the name for the symbol file
-		if ($currentLine =~ /^Creating Rofs image (\S*)/) 
-		{
-			if ($maksym eq "") 
-			{
-				# For backwards compatibility, replace trailing .img with .symbol
-				# if no trailing .img, just append .symbol anyway
-				$maksym = $1;
-				$maksym =~ s/(\.img)?$/.symbol/i;
-				close SYM;
-				open (SYM, ">$maksym") or die "ERROR: Can't open output file \"$maksym\"\n";
-				print "\nCreating $maksym...\n"
-			}
-			next;
-		}
-		
-		# found at end of file
-		if ($currentLine =~ /^Writing Rom image/) 
-		{
-			close SYM;
-			$maksym = "";
-			next;
-		}
-		
-		# Data file
-		if ($currentLine =~ /^File \'(.*)\' size: \S+\s*$/) 
-		{
-			my $file = $1;
-			$file =~ /([^\\]+)$/;
-			printf SYM "\nFrom    $file\n\n00000000    0000    $1\n";
-		}
-
-		# Executable file
-		elsif ($currentLine =~ /^Compressed executable File \'(.*)\' size: \S+\s*, mode:\S+\s*$/) 
-		{
-			ProcessCompressedLine($1);
-		}
-	}
-	close SYM;
-	close ROFS;
-}
-
-sub ProcessCompressedLine
-{
-	my ($file) = @_;
-
-	my $mapfile;
-	my $mapfile2;
-	print SYM "\nFrom    $file\n\n";
-
-	# Look in map file for symbols in .text and relocate them
-	$mapfile2 = $file.".map";			
-	$mapfile = $file;
-	$mapfile =~ s/\.\w+$/\.map/;			
-	if (!(open (MAP, "$mapfile2") || open (MAP, "$mapfile"))) 
-	{
-		print "$file\nWarning: Can't open \"$mapfile2\" or \"$mapfile\"\n";
-		# couldn't find map file so output in format that is used for non-binary files
-		my $BinSize = GetSizeFromBinFile($file);
-		$file =~ /([^\\]+)$/;
-		printf "00000000    %04x    $1\n", $BinSize;
-		printf SYM "00000000    %04x    $1\n", $BinSize;
-	} 
-	else 
-	{
-		my @maplines;
-		while ($_ = <MAP>) 
-		{
-			push @maplines, $_;
-		}
-		close MAP;
-		# See if we're dealing with the RVCT output
-		if ($file =~m/ARMV5/i) 
-		{
-			ProcessArmv5File($file, \@maplines);
-		} 
-		elsif( ($file =~ /GCCE/i) || ($file =~ /ARM4/i) )
-		{
-			ProcessGcceOrArm4File($file, \@maplines);
-		}
-		else
-		{
-			print "\nWarning: cannot determine linker type used to create $file\n";
-			$file =~ /([^\\]+)$/;
-			printf SYM "00000000    0000    $1\n";
-		}
-	}
-}
-
-sub ProcessArmv5File
-{
-	my ($file, $mapLines) = @_;
-	my @maplines = @$mapLines;
-	if ($maplines[0] !~ /^ARM Linker/) 
-	{
-		print "\nWarning: expecting $file to be generated by ARM linker\n";
-		# file not in format produced by ARMV5 linker so treat file as non-binary file
-		$file =~ /([^\\]+)$/;
-		printf SYM "00000000    0000    $1\n";
-	}
-	else
-	{
-		# scroll down to the global symbols
-		while ($_ = shift @maplines) 
-		{
-			if ($_ =~ /Global Symbols/) 
-			{
-				last;
-			}
-		}
-
-		my %syms;
-		my $baseOffset; # offset to subtract from each address so that the first entry has address 0x0
-
-		foreach (@maplines) 
-		{
-			# name address ignore size section
-			if (/^\s*(.+)\s*(0x\S+)\s+[^\d]*(\d+)\s+(.*)$/) 
-			{
-				my $sym = $1;
-				my $addr = hex($2);
-				my $size = sprintf("%04x",$3);
-				my $section = $4;
-				$size = sprintf("%04x", 8) if ($section =~ /\(StubCode\)/);
-				
-				# it is possible that there will be more than one entry in a log file for a
-				# particular address, this is because aliases are included.
-				# The following code checks that the correct function (i.e. the one with
-				# non-zero size) is being included in the symbol file.
-				if(exists $syms{$addr})
-				{ # an entry at this address exists, replace if it is an alias
-					if( ($size != 0) && ($addr > 0) )
-					{
-						if( ! defined $baseOffset )
-						{
-							$baseOffset = $addr;
-						}
-						$syms{$addr - $baseOffset} = "$size    $sym $section";
-					}
-				}
-				else
-				{ # no entry at this address so create one regardless of whether size is zero
-					if( $addr > 0 )
-					{
-						if( ! defined $baseOffset )
-						{
-							$baseOffset = $addr;
-						}	
-						$syms{$addr - $baseOffset} = "$size    $sym $section";
-					}
-				}
-
-			}
-		}
-
-		# Write symbols in address order
-		my @addrs = sort CompareAddrs keys %syms;
-		for ($i = 0; $i < @addrs ; $i++) 
-		{
-			my $thisaddr = $addrs[$i];
-			printf SYM "%08x    %s\n",
-			$thisaddr, $syms{$thisaddr};
-		}
-	}
-}
-
-sub ProcessGcceOrArm4File
-{
-	my ($file, $mapLines) = @_;
-	my @maplines = @$mapLines;
-	my %syms;
-	my $stubhex=1;
-
-	# Find text section
-	while (($_ = shift @maplines) && !(/^\.text\s+/)) 
-	{
-	}
-
-	/^\.text\s+(\w+)\s+\w+/ or die "ERROR: Can't get .text section info for \"$file\"\n";
-
-	my $imgtext=hex($1);
-
-	# Slurp symbols 'til the end of the text section
-	foreach (@maplines) 
-	{
-
-		# blank line marks the end of the text section
-		last if (/^$/);
-
-		# .text <addr> <len>  <library(member)>
-		# .text$something
-		#       <addr> <len>  <library(member)>
-		#       <addr> <len>  LONG 0x0
-
-		if (/^\s(\.text)?\s+(0x\w+)\s+(0x\w+)\s+(.*)$/io) 
-		{
-			my $address = hex($2);
-			my $length = hex($3);
-			my $libraryfile = $4;
-			next if ($libraryfile =~ /^LONG 0x/);
-			
-			$syms{$address+$length} = ' ';	# impossible symbol as end marker
-
-			#set $stubhex value as $address if there is a match
-			if ($libraryfile =~ /.*lib\(.*d\d*s_?\d{5}.o\)$/io) 
-			{
-				$stubhex=$address;
-			}
-			next;
-		}
-
-		#  <addr>  <symbol name possibly including spaces>
-		if (/^\s+(\w+)\s\s+([a-zA-Z_].+)/o) 
-		{
-			my $addr = hex($1);
-			my $symbol = $2;
-			$symbol = "stub $symbol" if ($addr == $stubhex);
-			$syms{$addr} = $symbol;
-			next;
-		}
-	}				
-
-	# Write symbols in address order
-	@addrs = sort CompareAddrs keys %syms;
-	for ($i = 0; $i < @addrs - 1; $i++) 
-	{
-		my $symbol = $syms{$addrs[$i]};
-		next if ($symbol eq ' ');
-		printf SYM "%08x    %04x    %s\n",
-		$addrs[$i] - $imgtext, $addrs[$i+1]-$addrs[$i], $symbol;
-	}
-	# last address assumed to be imgtext+lentext
-
-	close MAP;
-}
-
-#
-# args - get command line args
-#
-sub args
-{
-	my $arg;
-	my @args;
-	my $flag;
-
-	&help if (!@ARGV);
-
-	while (@ARGV) 
-	{
-		$arg = shift @ARGV;
-
-		if ($arg=~/^[\-\/](\S*)$/) 
-		{
-			$flag=$1;
-
-			if ($flag=~/^[\?h]$/i) 
-			{
-				&help;
-			}
-			elsif ($flag=~/^d$/i) 
-			{
-				$debug = 1;
-			}
-		       	else 
-			{
-				print "\nERROR: Unknown flag \"-$flag\"\n";
-				&usage;
-				exit 1;
-			}
-		}
-		else 
-		{
-			push @args,$arg;
-		}
-	}
-
-	if (@args)
-	{
-		$rofsbuild = shift @args;
-		if (@args) 
-		{
-			$maksym = shift @args;
-			if (@args) 
-			{
-				print "\nERROR: Incorrect argument(s) \"@args\"\n";
-				&usage;
-				exit 1;
-			}
-		}
-	}
-}
-
-sub help ()
-{
-	my $build;
-
-	&Load_ModuleL('E32TPVER');
-	print "\nmaksymrofs - Produce symbolic information given a ROFS image (Build ",
-	&E32tpver, ")\n";
-	&usage;
-	exit 0;
-}
-
-sub usage ()
-{
-    print <<EOF
-
-Usage:
-  maksymrofs <logfile> [<outfile>]
-
-Where:
-  <logfile>   Log file from rofsbuild tool.
-  <outfile>   Output file. Defaults to imagename.symbol.
-EOF
-    ;
-    exit 0;
-}
-
-sub GetSizeFromBinFile ()
-{
-   my ($file) = @_;
-   my $tmpfile = "temp.info";
-   system("readimage $file -o $tmpfile");
-   return 0 if (!-e $tmpfile);
-   
-   open (TMP, "<$tmpfile");
-   my $line;
-   my $size = 0;
-   while ($line = <TMP>)
-   {
-      print $line;
-      if ($line =~ /^Code size\W+(\w+)$/)
-      {
-        $size = hex($1);
-        last;
-      }
-   }
-   close TMP;
-   unlink $tmpfile;
-   return $size;
-}
-
+#
+# Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "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: 
+# Produces symbolic information given a ROFS log file and .map files for relevant binary files
+#
+
+require 5.003_07;
+no strict 'vars';
+use English;
+use FindBin;		# for FindBin::Bin
+
+# Version
+my $MajorVersion = 1;
+my $MinorVersion = 1;
+my $PatchVersion = 0;
+
+# Globals
+my $maksym = "";
+my $rofsbuild;
+my $debug = 0;
+
+&args;
+&main;
+exit 0;
+
+sub CompareAddrs()
+{
+    return -1 if ($a < $b);
+    return 1 if ($a > $b);
+    return 0;
+}
+
+#
+# main
+#
+sub main()
+{
+	open (ROFS, "<$rofsbuild") or die "ERROR: Can't open rofsbuild log file \"$rofsbuild\"\n";
+	if ($maksym ne "") 
+	{
+		open (SYM, ">$maksym") or die "ERROR: Can't open output file \"$maksym\"\n";
+   		print "Creating $maksym...\n"
+	}
+	
+	my $curretnLine;
+	while ($currentLine = <ROFS>) 	
+	{
+		# Check that the given log file is from a rofs image and set up the name for the symbol file
+		if ($currentLine =~ /^Creating Rofs image (\S*)/) 
+		{
+			if ($maksym eq "") 
+			{
+				# For backwards compatibility, replace trailing .img with .symbol
+				# if no trailing .img, just append .symbol anyway
+				$maksym = $1;
+				$maksym =~ s/(\.img)?$/.symbol/i;
+				close SYM;
+				open (SYM, ">$maksym") or die "ERROR: Can't open output file \"$maksym\"\n";
+				print "\nCreating $maksym...\n"
+			}
+			next;
+		}
+		
+		# found at end of file
+		if ($currentLine =~ /^Writing Rom image/) 
+		{
+			close SYM;
+			$maksym = "";
+			next;
+		}
+		
+		# Data file
+		if ($currentLine =~ /^File \'(.*)\' size: \S+\s*$/) 
+		{
+			my $file = $1;
+			$file =~ /([^\\]+)$/;
+			printf SYM "\nFrom    $file\n\n00000000    0000    $1\n";
+		}
+
+		# Executable file
+		elsif ($currentLine =~ /^Compressed executable File \'(.*)\' size: \S+\s*, mode:\S+\s*$/) 
+		{
+			ProcessCompressedLine($1);
+		}
+	}
+	close SYM;
+	close ROFS;
+}
+
+sub ProcessCompressedLine
+{
+	my ($file) = @_;
+
+	my $mapfile;
+	my $mapfile2;
+	print SYM "\nFrom    $file\n\n";
+
+	# Look in map file for symbols in .text and relocate them
+	$mapfile2 = $file.".map";			
+	$mapfile = $file;
+	$mapfile =~ s/\.\w+$/\.map/;			
+	if (!(open (MAP, "$mapfile2") || open (MAP, "$mapfile"))) 
+	{
+		print "$file\nWarning: Can't open \"$mapfile2\" or \"$mapfile\"\n";
+		# couldn't find map file so output in format that is used for non-binary files
+		my $BinSize = GetSizeFromBinFile($file);
+		$file =~ /([^\\]+)$/;
+		printf "00000000    %04x    $1\n", $BinSize;
+		printf SYM "00000000    %04x    $1\n", $BinSize;
+	} 
+	else 
+	{
+		my @maplines;
+		while ($_ = <MAP>) 
+		{
+			push @maplines, $_;
+		}
+		close MAP;
+		# See if we're dealing with the RVCT output
+		if ($file =~m/ARMV5/i) 
+		{
+			ProcessArmv5File($file, \@maplines);
+		} 
+		elsif( ($file =~ /GCCE/i) || ($file =~ /ARM4/i) )
+		{
+			ProcessGcceOrArm4File($file, \@maplines);
+		}
+		else
+		{
+			print "\nWarning: cannot determine linker type used to create $file\n";
+			$file =~ /([^\\]+)$/;
+			printf SYM "00000000    0000    $1\n";
+		}
+	}
+}
+
+sub ProcessArmv5File
+{
+	my ($file, $mapLines) = @_;
+	my @maplines = @$mapLines;
+	if ($maplines[0] !~ /^ARM Linker/) 
+	{
+		print "\nWarning: expecting $file to be generated by ARM linker\n";
+		# file not in format produced by ARMV5 linker so treat file as non-binary file
+		$file =~ /([^\\]+)$/;
+		printf SYM "00000000    0000    $1\n";
+	}
+	else
+	{
+		# scroll down to the global symbols
+		while ($_ = shift @maplines) 
+		{
+			if ($_ =~ /Global Symbols/) 
+			{
+				last;
+			}
+		}
+
+		my %syms;
+		my $baseOffset; # offset to subtract from each address so that the first entry has address 0x0
+
+		foreach (@maplines) 
+		{
+			# name address ignore size section
+			if (/^\s*(.+)\s*(0x\S+)\s+[^\d]*(\d+)\s+(.*)$/) 
+			{
+				my $sym = $1;
+				my $addr = hex($2);
+				my $size = sprintf("%04x",$3);
+				my $section = $4;
+				$size = sprintf("%04x", 8) if ($section =~ /\(StubCode\)/);
+				
+				# it is possible that there will be more than one entry in a log file for a
+				# particular address, this is because aliases are included.
+				# The following code checks that the correct function (i.e. the one with
+				# non-zero size) is being included in the symbol file.
+                                if($addr > 0) {
+                                    if( ! defined $baseOffset ) {
+                                        $baseOffset = $addr;
+                                    }
+                                    # no entry at this address so create one regardless of whether size is zero
+                                    # an entry at this address exists, replace if it is an alias
+                                    if( (! exists $syms{$addr-$baseOffset}) || !($size eq "0000")) {
+                                        $syms{$addr - $baseOffset} = "$size    $sym $section";
+                                    }
+                                }
+			}
+		}
+
+		# Write symbols in address order
+		my @addrs = sort CompareAddrs keys %syms;
+		for ($i = 0; $i < @addrs ; $i++) 
+		{
+			my $thisaddr = $addrs[$i];
+			printf SYM "%08x    %s\n",
+			$thisaddr, $syms{$thisaddr};
+		}
+	}
+}
+
+sub ProcessGcceOrArm4File
+{
+	my ($file, $mapLines) = @_;
+	my @maplines = @$mapLines;
+	my %syms;
+	my $stubhex=1;
+
+	# Find text section
+	while (($_ = shift @maplines) && !(/^\.text\s+/)) 
+	{
+	}
+
+	/^\.text\s+(\w+)\s+\w+/ or die "ERROR: Can't get .text section info for \"$file\"\n";
+
+	my $imgtext=hex($1);
+
+	# Slurp symbols 'til the end of the text section
+	foreach (@maplines) 
+	{
+
+		# blank line marks the end of the text section
+		last if (/^$/);
+
+		# .text <addr> <len>  <library(member)>
+		# .text$something
+		#       <addr> <len>  <library(member)>
+		#       <addr> <len>  LONG 0x0
+
+		if (/^\s(\.text)?\s+(0x\w+)\s+(0x\w+)\s+(.*)$/io) 
+		{
+			my $address = hex($2);
+			my $length = hex($3);
+			my $libraryfile = $4;
+			next if ($libraryfile =~ /^LONG 0x/);
+			
+			$syms{$address+$length} = ' ';	# impossible symbol as end marker
+
+			#set $stubhex value as $address if there is a match
+			if ($libraryfile =~ /.*lib\(.*d\d*s_?\d{5}.o\)$/io) 
+			{
+				$stubhex=$address;
+			}
+			next;
+		}
+
+		#  <addr>  <symbol name possibly including spaces>
+		if (/^\s+(\w+)\s\s+([a-zA-Z_].+)/o) 
+		{
+			my $addr = hex($1);
+			my $symbol = $2;
+			$symbol = "stub $symbol" if ($addr == $stubhex);
+			$syms{$addr} = $symbol;
+			next;
+		}
+	}				
+
+	# Write symbols in address order
+	@addrs = sort CompareAddrs keys %syms;
+	for ($i = 0; $i < @addrs - 1; $i++) 
+	{
+		my $symbol = $syms{$addrs[$i]};
+		next if ($symbol eq ' ');
+		printf SYM "%08x    %04x    %s\n",
+		$addrs[$i] - $imgtext, $addrs[$i+1]-$addrs[$i], $symbol;
+	}
+	# last address assumed to be imgtext+lentext
+
+	close MAP;
+}
+
+#
+# args - get command line args
+#
+sub args
+{
+	my $arg;
+	my @args;
+	my $flag;
+
+	&help if (!@ARGV);
+
+	while (@ARGV) 
+	{
+		$arg = shift @ARGV;
+
+		if ($arg=~/^[\-](\S*)$/) 
+		{
+			$flag=$1;
+
+			if ($flag=~/^[\?h]$/i) 
+			{
+				&help;
+			}
+			elsif ($flag=~/^d$/i) 
+			{
+				$debug = 1;
+			}
+		       	else 
+			{
+				print "\nERROR: Unknown flag \"-$flag\"\n";
+				&usage;
+				exit 1;
+			}
+		}
+		else 
+		{
+			push @args,$arg;
+		}
+	}
+
+	if (@args)
+	{
+		$rofsbuild = shift @args;
+		if (@args) 
+		{
+			$maksym = shift @args;
+			if (@args) 
+			{
+				print "\nERROR: Incorrect argument(s) \"@args\"\n";
+				&usage;
+				exit 1;
+			}
+		}
+	}
+}
+
+sub help ()
+{
+	my $build;
+
+	print "\nmaksymrofs - Produce symbolic information given a ROFS image V${MajorVersion}.${MinorVersion}.${PatchVersion}\n";
+	&usage;
+	exit 0;
+}
+
+sub usage ()
+{
+    print <<EOF
+
+Usage:
+  maksymrofs <logfile> [<outfile>]
+
+Where:
+  <logfile>   Log file from rofsbuild tool.
+  <outfile>   Output file. Defaults to imagename.symbol.
+EOF
+    ;
+    exit 0;
+}
+
+sub GetSizeFromBinFile ()
+{
+   my ($file) = @_;
+   my $tmpfile = "temp.info";
+   system("readimage $file -o $tmpfile");
+   return 0 if (!-e $tmpfile);
+   
+   open (TMP, "<$tmpfile");
+   my $line;
+   my $size = 0;
+   while ($line = <TMP>)
+   {
+      print $line;
+      if ($line =~ /^Code size\W+(\w+)$/)
+      {
+        $size = hex($1);
+        last;
+      }
+   }
+   close TMP;
+   unlink $tmpfile;
+   return $size;
+}
+
--- a/imgtools/romtools/readimage/inc/common.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/readimage/inc/common.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,104 +1,110 @@
-/*
-* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef __IMAGE_READER_COMMON_H_
-#define __IMAGE_READER_COMMON_H_
-
-#include <string>
-#include <iostream>
-#include <iomanip>
-#ifdef __MSVCDOTNET__ 
-#include <ctype.h>
-#endif
-
-using namespace std ;
-
-#include <e32std.h>
-#include <e32std_private.h>
-#include <e32rom.h>
-#include <u32std.h>
-#include <f32file.h>
-
-#include "e32image.h"
-
-#define EXIT_SUCCESS 0
-#define EXIT_FAILURE 1
-
-extern ostream *out;
-
-#define DLL_UID1	10000079
-#define EXE_UID1	1000007a
-
-typedef enum EImageType
-{
-	EUNKNOWN_IMAGE,
-	EROM_IMAGE,
-	EROMX_IMAGE,
-	EROFS_IMAGE,
-	EROFX_IMAGE,
-	//more here...
-	EE32_IMAGE,
-    //EBAREROM_IMAGE is introduced for handling bare ROM image (an image without loader header)
-    EBAREROM_IMAGE
-};
-
-#define DIR_SEPARATOR  "/"
-#define DUMP_HDR_FLAG			0x1
-#define DUMP_VERBOSE_FLAG		0x2
-#define DUMP_DIR_ENTRIES_FLAG	0x4
-#define DUMP_E32_IMG_FLAG		0x8
-
-#define LOG_IMAGE_CONTENTS_FLAG	0x10
-#define EXTRACT_FILES_FLAG		0x20
-#define MODE_SIS2IBY			0x40
-#define RECURSIVE_FLAG			0x80
-#define EXTRACT_FILE_SET_FLAG	0x100
-
-// maximum buffer size.
-#define _MAX_BUFFER_SIZE_		128 
-
-class ReaderUtil
-{
-public:
-	static bool IsExecutable(TUint8* Uids1);
-};
-
-class ImageReaderException
-{
-public:
-	ImageReaderException(const char* aFile, const char* aErrMessage);
-	virtual ~ImageReaderException(){}
-	virtual void Report();
-
-	string iImgFileName;
-	string iErrMessage;
-};
-
-class ImageReaderUsageException : public ImageReaderException
-{
-public:
-	ImageReaderUsageException(const char* aFile, const char* aErrMessage);
-	void Report();
-};
-
-ostream& DumpInHex(char* aDesc, TUint32 aData, bool aContinue = false,TUint aDataWidth=8,\
-				   char aFiller='0', TUint aMaxDescWidth=28);
-
-#endif //__IMAGE_READER_COMMON_H_
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef __IMAGE_READER_COMMON_H_
+#define __IMAGE_READER_COMMON_H_
+
+#include <string>
+#include <iostream>
+#include <iomanip>
+#ifdef __MSVCDOTNET__ 
+#include <ctype.h>
+#endif
+ 
+
+#include <e32std.h>
+#include <e32std_private.h>
+#include <e32rom.h>
+#include <u32std.h>
+#include <f32file.h>
+
+#include "e32image.h"
+
+#define EXIT_SUCCESS 0
+#define EXIT_FAILURE 1
+
+extern ostream *out;
+
+#define DLL_UID1	10000079
+#define EXE_UID1	1000007a
+
+typedef enum EImageType
+{
+	EUNKNOWN_IMAGE,
+	EROM_IMAGE,
+	EROMX_IMAGE,
+	EROFS_IMAGE,
+	EROFX_IMAGE,
+	//more here...
+	EE32_IMAGE,
+    //EBAREROM_IMAGE is introduced for handling bare ROM image (an image without loader header)
+    EBAREROM_IMAGE
+};
+#ifdef __LINUX__
+const char SLASH_CHAR1 = '/' ;
+const char SLASH_CHAR2 = '\\' ;
+#define MKDIR(a)		mkdir(a,0777)
+#else
+const char SLASH_CHAR1 = '\\' ;
+const char SLASH_CHAR2 = '/' ;
+#define MKDIR(a)		mkdir(a)
+#endif
+#define DUMP_HDR_FLAG			0x1
+#define DUMP_VERBOSE_FLAG		0x2
+#define DUMP_DIR_ENTRIES_FLAG	0x4
+#define DUMP_E32_IMG_FLAG		0x8
+
+#define LOG_IMAGE_CONTENTS_FLAG	0x10
+#define EXTRACT_FILES_FLAG		0x20
+#define MODE_SIS2IBY			0x40
+#define RECURSIVE_FLAG			0x80
+#define EXTRACT_FILE_SET_FLAG	0x100
+
+// maximum buffer size.
+#define _MAX_BUFFER_SIZE_		256 
+
+class ReaderUtil
+{
+public:
+	static bool IsExecutable(TUint8* Uids1);
+};
+
+class ImageReaderException
+{
+public:
+	ImageReaderException(const char* aFile, const char* aErrMessage);
+	virtual ~ImageReaderException(){}
+	virtual void Report();
+
+	string iImgFileName;
+	string iErrMessage;
+};
+
+class ImageReaderUsageException : public ImageReaderException
+{
+public:
+	ImageReaderUsageException(const char* aFile, const char* aErrMessage);
+	void Report();
+};
+
+ostream& DumpInHex(char* aDesc, TUint32 aData, bool aContinue = false,TUint aDataWidth=8,\
+				   char aFiller='0', TUint aMaxDescWidth=28);
+
+#endif //__IMAGE_READER_COMMON_H_
--- a/imgtools/romtools/readimage/inc/e32_image_reader.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/readimage/inc/e32_image_reader.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,43 +1,43 @@
-/*
-* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef __E32_IMAGE_READER__
-#define __E32_IMAGE_READER__
-
-#include "image_reader.h"
-
-class E32ImageReader : public ImageReader
-{
-public:
-	E32ImageReader();
-	E32ImageReader(char* aFile);
-	~E32ImageReader();
-
-	void ReadImage();
-	void ProcessImage();
-	void Validate();
-	void Dump();
-	static void DumpE32Attributes(E32ImageFile& aE32Image);
-
-	E32ImageFile	*iE32Image;
-};
-
-#endif //__E32_IMAGE_READER__
-
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef __E32_IMAGE_READER__
+#define __E32_IMAGE_READER__
+
+#include "image_reader.h"
+
+class E32ImageReader : public ImageReader
+{
+public:
+	E32ImageReader();
+	E32ImageReader(const char* aFile);
+	~E32ImageReader();
+
+	void ReadImage();
+	void ProcessImage();
+	void Validate();
+	void Dump();
+	static void DumpE32Attributes(E32ImageFile& aE32Image);
+
+	E32ImageFile	*iE32Image;
+};
+
+#endif //__E32_IMAGE_READER__
+
--- a/imgtools/romtools/readimage/inc/image_handler.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/readimage/inc/image_handler.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,57 +1,57 @@
-/*
-* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef __IMAGE_HANDLER_H__
-#define __IMAGE_HANDLER_H__
-
-#include "image_reader.h"
-#include "sisutils.h"
-
-
-const unsigned int KRomBase = 0x80000000;
-const unsigned int KRomBaseMaxLimit = 0x82000000;
-
-
-
-class ImageHandler
-{
-public:
-	ImageHandler();
-	~ImageHandler();
-
-	void		ProcessArgs(int argc, char**argv);
-
-	void		HandleInputFiles();
-	EImageType	ReadMagicWord();
-    EImageType  ReadBareImage(ifstream& aIfs);
-	void		PrintUsage();
-	void		PrintVersion();
-	void		SetInputFile(char* aFile) { iInputFileName = aFile;}
-
-private:
-	ImageReader *iReader;
-	string		iInputFileName;
-	string		iOutFile;
-	TUint		iOptions;
-
-	SisUtils	*iSisUtils;
-};
-
-#endif //__IMAGE_HANDLER_H__
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef __IMAGE_HANDLER_H__
+#define __IMAGE_HANDLER_H__
+
+#include "image_reader.h"
+#include "sisutils.h"
+
+
+const unsigned int KRomBase = 0x80000000;
+const unsigned int KRomBaseMaxLimit = 0x82000000;
+
+
+
+class ImageHandler
+{
+public:
+	ImageHandler();
+	~ImageHandler();
+
+	void		ProcessArgs(int argc, char*argv[]);
+
+	void		HandleInputFiles();
+	EImageType	ReadMagicWord();
+    EImageType  ReadBareImage(ifstream& aIfs);
+	void		PrintUsage();
+	void		PrintVersion();
+	void		SetInputFile(const string& aFile) { iInputFileName = aFile;}
+
+private:
+	ImageReader *iReader;
+	string	iInputFileName;
+	string	iOutFile;
+	TUint		iOptions;
+
+	SisUtils	*iSisUtils;
+};
+
+#endif //__IMAGE_HANDLER_H__
--- a/imgtools/romtools/readimage/inc/image_reader.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/readimage/inc/image_reader.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,76 +1,81 @@
-/*
-* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef __IMAGE_READER__
-#define __IMAGE_READER__
-
-#if defined(__VC32__) && (_MSC_VER < 1300)
-#pragma warning(disable:4786) // std::map etc overflow debug symbol length :(
-#endif
-
-
-#include "common.h"
-#include <direct.h>
-#include <map>
-
-typedef struct tag_FILEINFO
-{
-	TUint32 iOffset;
-	TUint32 iSize;
-}FILEINFO, *PFILEINFO;
-
-typedef std::map<std::string, PFILEINFO> FILEINFOMAP;
-
-class ImageReader
-{
-public:
-	ImageReader(const char* aFile);
-	virtual ~ImageReader();
-	
-	virtual void ReadImage()	= 0;
-	virtual void ProcessImage() = 0;
-	virtual void Validate()		= 0;
-	virtual void Dump()			= 0;
-	
-	virtual void ExtractImageContents(){}
-	void DumpData(TUint* aData, TUint aLength);
-
-	void SetDisplayOptions(TUint32);
-	bool DisplayOptions(TUint32);
-
-	void ExtractFile(TUint aOffset, TInt aSize, const char* aFileName, const char* aPath, char* aFilePath,char* aData = NULL);
-	void FindAndInsertString(string& aSrcStr,string& aDelimiter,string& aAppStr);
-	void FindAndReplaceString(string& aSrcStr, string& aDelimiter, string& aReplStr);
-	void CreateSpecifiedDir(char* aSrcPath,const char* aDelimiter);
-	TBool IsDrive(char* aStr);
-
-	virtual void GetFileInfo(FILEINFOMAP& /*fileInfoMap */){}
-	void ExtractFileSet(char* aData);
-	int FileNameMatch(string aPattern, string aFileName, int aRecursiveFlag);
-
-	TUint32	iDisplayOptions;
-	string	iImgFileName;
-	static string  iZdrivePath;
-	static string  iLogFileName;
-	static string  iE32ImgFileName;
-	static string  iPattern;
-};
-
-#endif //__IMAGE_READER__
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef __IMAGE_READER__
+#define __IMAGE_READER__
+
+#if defined(__VC32__) && (_MSC_VER < 1300)
+#pragma warning(disable:4786) // map etc overflow debug symbol length :(
+#endif
+
+
+#include "common.h"
+#ifdef WIN32
+#include <direct.h>
+#else
+#include <unistd.h>
+#include <sys/stat.h>
+#endif
+#include <map>
+
+typedef struct tag_FILEINFO
+{
+	TUint32 iOffset;
+	TUint32 iSize;
+}FILEINFO, *PFILEINFO;
+
+typedef map<string, PFILEINFO> FILEINFOMAP;
+
+class ImageReader
+{
+public:
+	ImageReader(const char* aFile);
+	virtual ~ImageReader();
+	
+	virtual void ReadImage()	= 0;
+	virtual void ProcessImage() = 0;
+	virtual void Validate()		= 0;
+	virtual void Dump()			= 0;
+	
+	virtual void ExtractImageContents(){}
+	void DumpData(TUint* aData, TUint aLength);
+
+	void SetDisplayOptions(TUint32);
+	bool DisplayOptions(TUint32);
+
+	void ExtractFile(TUint aOffset, TInt aSize, const char* aFileName,const char* aPath,const char* aFilePath,const char* aData = NULL);
+	void FindAndInsertString(string& aSrcStr,string& aDelimiter,string& aAppStr);
+	void FindAndReplaceString(string& aSrcStr, string& aDelimiter, string& aReplStr);
+ 
+	void CreateSpecifiedDir(const string& aSrcPath);  
+
+	virtual void GetFileInfo(FILEINFOMAP& /*fileInfoMap */){}
+	void ExtractFileSet(const char* aData);
+	int FileNameMatch(const string& aPattern, const string& aFileName, int aRecursiveFlag);
+
+	TUint32	iDisplayOptions;
+	string	iImgFileName;
+	static string  iZdrivePath;
+	static string  iLogFileName;
+	static string  iE32ImgFileName;
+	static string  iPattern;
+};
+
+#endif //__IMAGE_READER__
--- a/imgtools/romtools/readimage/inc/rofs_image_reader.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/readimage/inc/rofs_image_reader.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,87 +1,87 @@
-/*
-* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef __ROFS_IMAGE_READER__
-#define __ROFS_IMAGE_READER__
-
-#include <stdio.h>
-#include "image_reader.h"
-#include "e32def.h"
-#include "e32cmn.h"
-#include "e32std.h"
-#include "rofs.h"
-#include "r_romnode.h"
-#include "r_coreimage.h"
-#include "f32file.h"
-
-extern TUint gCompressionMethod;
-
-class CCoreImage;
-class RCoreImageReader;
-class TRofsHeader;
-class TExtensionRofsHeader;
-class TRomNode;
-
-class RofsImage : public CCoreImage
-{
-public:
-	RofsImage(RCoreImageReader *aReader);
-	TInt			ProcessImage();
-
-	TRofsHeader				*iRofsHeader;
-	TExtensionRofsHeader	*iRofsExtnHeader;
-	long					iAdjustment;
-	RCoreImageReader::TImageType iImageType;
-};
-
-class RofsImageReader : public ImageReader
-{
-public:
-	RofsImageReader(char* aFile);
-	~RofsImageReader();
-
-	void ReadImage();
-	void ProcessImage();
-	void Validate();
-	void Dump();
-	void DumpHeader();
-	void DumpDirStructure();
-	void DumpFileAttributes();
-	void MarkNodes();
-	void SetSeek(streampos aOff, ios::seek_dir aStartPos=ios::beg);
-	void ExtractImageContents();
-	void CheckFileExtension(char* aFileName,TRomBuilderEntry* aEntry,TRomNode* aNode,ofstream& aLogFile );
-	void GetCompleteNodePath(TRomNode* aNode,string& aName,char* aAppStr);
-	void WriteEntryToFile(char* aFileName,TRomNode* aNode,ofstream& aLogFile);
-
-	void GetFileInfo(FILEINFOMAP &aFileMap);
-	TUint32 GetImageSize();
-
-private:
-	CCoreImage			*iImage;
-	RCoreImageReader	*iImageReader;
-	
-	TRomNode			*iRootDirEntry;
-
-	ifstream			*iInputFile;
-};
-
-#endif //__ROFS_IMAGE_READER__
-
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef __ROFS_IMAGE_READER__
+#define __ROFS_IMAGE_READER__
+
+#include <stdio.h>
+#include "image_reader.h"
+#include "e32def.h"
+#include "e32cmn.h"
+#include "e32std.h"
+#include "rofs.h"
+#include "r_romnode.h"
+#include "r_coreimage.h"
+#include "f32file.h"
+
+extern TUint gCompressionMethod;
+
+class CCoreImage;
+class RCoreImageReader;
+class TRofsHeader;
+class TExtensionRofsHeader;
+class TRomNode;
+
+class RofsImage : public CCoreImage
+{
+public:
+	RofsImage(RCoreImageReader *aReader);
+	TInt			ProcessImage();
+
+	TRofsHeader				*iRofsHeader;
+	TExtensionRofsHeader	*iRofsExtnHeader;
+	long					iAdjustment;
+	RCoreImageReader::TImageType iImageType;
+};
+
+class RofsImageReader : public ImageReader
+{
+public:
+	RofsImageReader(const char* aFile);
+	~RofsImageReader();
+
+	void ReadImage();
+	void ProcessImage();
+	void Validate();
+	void Dump();
+	void DumpHeader();
+	void DumpDirStructure();
+	void DumpFileAttributes();
+	void MarkNodes();
+	void SetSeek(streampos aOff, ios_base::seek_dir aStartPos=ios_base::beg);
+	void ExtractImageContents();
+	void CheckFileExtension(const char* aFileName,TRomBuilderEntry* aEntry,TRomNode* aNode,ofstream& aLogFile );
+	void GetCompleteNodePath(TRomNode* aNode,string& aName);
+	void WriteEntryToFile(const char* aFileName,TRomNode* aNode,ofstream& aLogFile);
+
+	void GetFileInfo(FILEINFOMAP &aFileMap);
+	TUint32 GetImageSize();
+
+private:
+	CCoreImage			*iImage;
+	RCoreImageReader	*iImageReader;
+	
+	TRomNode			*iRootDirEntry;
+
+	std::ifstream			*iInputFile;
+};
+
+#endif //__ROFS_IMAGE_READER__
+
--- a/imgtools/romtools/readimage/inc/rom_image_reader.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/readimage/inc/rom_image_reader.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,141 +1,138 @@
-/*
-* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef __ROM_IMAGE_READER__
-#define __ROM_IMAGE_READER__
-
-#include "image_reader.h"
-
-class TRomLoaderHeader;
-#include <wchar.h>
-class RomImageFSEntry 
-{
-public:
-	RomImageFSEntry (const char* aName) ;
-	virtual ~RomImageFSEntry() ;
-	virtual bool IsDirectory() = 0;
-	const char *Name() { return iName.c_str();}
-
-	string iName;
-	string iPath;
-	RomImageFSEntry 	*iSibling;
-	RomImageFSEntry 	*iChildren;
-};
-
-class RomImageFileEntry : public RomImageFSEntry 
-{
-public:
-	RomImageFileEntry(const char* aName) : RomImageFSEntry(aName), iExecutable(true)
-	{
-	}
-
-	bool IsDirectory() {
-		return false;
-	}
-	
-	union ImagePtr
-	{
-		TRomImageHeader		*iRomFileEntry;
-		TLinAddr			iDataFileAddr;
-	}ImagePtr;
-
-	TRomEntry		*iTRomEntryPtr;
-
-	bool iExecutable;
-};
-
-class RomImageDirEntry : public RomImageFSEntry
-{
-public:
-	RomImageDirEntry(const char* aName) : RomImageFSEntry(aName)
-	{
-	}
-
-	bool IsDirectory()
-	{
-		return true;
-	}
-
-};
-
-
-class RomImageHeader
-{
-public:
-	RomImageHeader(char* aHdr, EImageType aImgType = EROM_IMAGE );
-	TRomLoaderHeader	*iLoaderHdr;
-	TRomHeader			*iRomHdr;
-	TExtensionRomHeader	*iExtRomHdr;
-	
-	void DumpRomHdr();
-	void DumpRomXHdr();
-};
-
-class RomImageReader : public ImageReader
-{
-public:
-	RomImageReader(const char* aFile, EImageType aImgType = EROM_IMAGE );
-	~RomImageReader();
-
-	void ReadImage();
-	void ProcessImage();
-	void BuildDir(TRomDir *aDir, RomImageFSEntry* aPaFSEntry); 
-
-	void AddChild(RomImageFSEntry *aParent, RomImageFSEntry *aChild, TRomEntry* aRomEntry);
-	void Name(string& aName, const wchar_t* aUnicodeName, TUint aLen);
-	void Validate();
-	void Dump();
-	void DumpTree();
-	void DumpSubTree(RomImageFSEntry* aFsEntry);
-	void DumpImage(RomImageFileEntry*);
-	void DumpAttribs(RomImageFSEntry* aFsEntry);
-	void DumpDirStructure();
-	void DumpDirStructure(RomImageFSEntry*, int &aPadding);
-	void ExtractImageContents();
-	void TraverseImage(RomImageFSEntry*  aEntity,ofstream& aFile);
-	void CheckFileExtension(RomImageFSEntry*  aEntity,ofstream& aFile);
-	void LogRomEnrtyToFile(const char* aPath,const char* aEntityName,ofstream& aFile);
-
-	void GetFileInfo(FILEINFOMAP &aFileMap);
-	void ProcessDirectory(RomImageFSEntry *aEntity, FILEINFOMAP &aFileMap);
-	TUint32 GetImageSize();
-	
-	TUint32 GetImageCompressionType(); 
-
-	TLinAddr GetRomBase();
-	TUint GetHdrSize();
-	TLinAddr GetRootDirList();
-
-	RomImageHeader			*iImageHeader; 
-	RomImageFSEntry			*iRomImageRootDirEntry;
-
-protected:	
-	void					ReadData(char* aBuffer, TUint aLength);	
-
-	ifstream				iFile ;
-	TUint32					iRomSize ;
-	char*					iHeaderBuffer ;
-	char*					iRomLayoutData ; 
-	EImageType				iImgType; 
-
-};
-
-#endif //__ROM_IMAGE_READER__
-
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef __ROM_IMAGE_READER__
+#define __ROM_IMAGE_READER__
+
+#include "image_reader.h"
+
+class TRomLoaderHeader; 
+class RomImageFSEntry 
+{
+public:
+	RomImageFSEntry (const char* aName) ;
+	virtual ~RomImageFSEntry() ;
+	virtual bool IsDirectory() const = 0;
+	const char *Name() { return iName.c_str();}
+
+	string iName;
+	string iPath;
+	RomImageFSEntry 	*iSibling;
+	RomImageFSEntry 	*iChildren;
+};
+
+class RomImageFileEntry : public RomImageFSEntry 
+{
+public:
+	RomImageFileEntry(const char* aName) : RomImageFSEntry(aName), iExecutable(true)
+	{
+	}
+
+	bool IsDirectory() const {
+		return false;
+	}
+	
+	union ImagePtr
+	{
+		TRomImageHeader		*iRomFileEntry;
+		TLinAddr			iDataFileAddr;
+	}ImagePtr;
+
+	TRomEntry		*iTRomEntryPtr;
+
+	bool iExecutable;
+};
+
+class RomImageDirEntry : public RomImageFSEntry
+{
+public:
+	RomImageDirEntry(const char* aName) : RomImageFSEntry(aName)
+	{
+	}
+
+	bool IsDirectory() const {
+		return true;
+	}
+
+};
+
+
+class RomImageHeader
+{
+public:
+	RomImageHeader(char* aHdr, EImageType aImgType = EROM_IMAGE );
+	TRomLoaderHeader	*iLoaderHdr;
+	TRomHeader			*iRomHdr;
+	TExtensionRomHeader	*iExtRomHdr;
+	
+	void DumpRomHdr();
+	void DumpRomXHdr();
+};
+
+class RomImageReader : public ImageReader
+{
+public:
+	RomImageReader(const char* aFile, EImageType aImgType = EROM_IMAGE );
+	~RomImageReader();
+
+	void ReadImage();
+	void ProcessImage();
+	void BuildDir(TRomDir *aDir, RomImageFSEntry* aPaFSEntry); 
+
+	void AddChild(RomImageFSEntry *aParent, RomImageFSEntry *aChild, TRomEntry* aRomEntry); 
+	void Validate();
+	void Dump();
+	void DumpTree();
+	void DumpSubTree(RomImageFSEntry* aFsEntry);
+	void DumpImage(RomImageFileEntry*);
+	void DumpAttribs(RomImageFSEntry* aFsEntry);
+	void DumpDirStructure();
+	void DumpDirStructure(RomImageFSEntry*, int &aPadding);
+	void ExtractImageContents();
+	void TraverseImage(RomImageFSEntry*  aEntity,ofstream& aFile);
+	void CheckFileExtension(RomImageFSEntry*  aEntity,ofstream& aFile);
+	void LogRomEnrtyToFile(const char* aPath,const char* aEntityName,ofstream& aFile);
+
+	void GetFileInfo(FILEINFOMAP &aFileMap);
+	void ProcessDirectory(RomImageFSEntry *aEntity, FILEINFOMAP &aFileMap);
+	TUint32 GetImageSize();
+	
+	TUint32 GetImageCompressionType(); 
+
+	TLinAddr GetRomBase();
+	TUint GetHdrSize();
+	TLinAddr GetRootDirList();
+
+	RomImageHeader			*iImageHeader; 
+	RomImageFSEntry			*iRomImageRootDirEntry;
+
+protected:	
+	void					ReadData(char* aBuffer, TUint aLength);	
+
+	ifstream				iFile ;
+	TUint32					iRomSize ;
+	char*					iHeaderBuffer ;
+	char*					iRomLayoutData ; 
+	EImageType				iImgType; 
+
+};
+
+#endif //__ROM_IMAGE_READER__
+
--- a/imgtools/romtools/readimage/src/common.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/readimage/src/common.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,74 +1,64 @@
-/*
-* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent 
-* @released
-*
-*/
-
-
-#include "common.h"
- 
-ImageReaderException::ImageReaderException(const char* aFile, const char* aErrMessage) : \
-	iImgFileName(aFile), iErrMessage(aErrMessage)
-{
-}
-
-void ImageReaderException::Report()
-{
-	*out << "Error : " << iImgFileName.c_str() << " : " << iErrMessage.c_str() << endl;
-}
-
-ImageReaderUsageException::ImageReaderUsageException(const char* /* aOption */,const char* aErrMessage) : \
-	ImageReaderException("", aErrMessage)
-{
-}
-
-void ImageReaderUsageException::Report()
-{
-	*out << "Usage Error:" << iErrMessage.c_str() << endl;
-}
-
-ostream& DumpInHex(char* aDesc, TUint32 aData, bool aContinue, TUint aDataWidth, \
-				   char aFiller, TUint aMaxDescWidth)
-{
-	TUint aDescLen = strlen(aDesc);
-	
-	*out << aDesc;
-	if( !aContinue )
-	{
-		while( aDescLen < aMaxDescWidth ){
-			*out << ".";
-			aDescLen++;
-		}
-	}
-	out->width(aDataWidth);
-	out->fill(aFiller);
-	
-	*out << hex << aData;
-
-	return *out;
-}
-
-bool ReaderUtil::IsExecutable(TUint8* Uids1)
-{
-	//In the little-endian world
-	if( Uids1[3] == 0x10 && Uids1[2] == 0x0 && Uids1[1] == 0x0 )
-	{
-		if(Uids1[0] == 0x79 || Uids1[0] == 0x7a)
-			return true;
-	}
-	return false;
-}
-
+/*
+* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+#include "common.h"
+
+bool gCache = false;
+ 
+ImageReaderException::ImageReaderException(const char* aFile, const char* aErrMessage) : 
+	iImgFileName(aFile), iErrMessage(aErrMessage) {
+}
+
+void ImageReaderException::Report() {
+	*out << "Error : " << iImgFileName.c_str() << " : " << iErrMessage.c_str() << endl;
+}
+
+ImageReaderUsageException::ImageReaderUsageException(const char* /* aOption */,const char* aErrMessage) :  
+	ImageReaderException("", aErrMessage) {
+}
+
+void ImageReaderUsageException::Report() {
+	*out << "Usage Error:" << iErrMessage.c_str() << endl;
+}
+
+ostream& DumpInHex(char* aDesc, TUint32 aData, bool aContinue, TUint aDataWidth, char aFiller, TUint aMaxDescWidth) {
+	TUint aDescLen = strlen(aDesc);
+	
+	*out << aDesc;
+	if( !aContinue ) {
+		while( aDescLen < aMaxDescWidth ){
+			*out << ".";
+			aDescLen++;
+		}
+	}
+	out->width(aDataWidth);
+	out->fill(aFiller);
+	
+	*out << hex << aData;
+
+	return *out;
+}
+
+bool ReaderUtil::IsExecutable(TUint8* Uids1) {
+	//In the little-endian world
+	if( Uids1[3] == 0x10 && Uids1[2] == 0x0 && Uids1[1] == 0x0 ) {
+		if(Uids1[0] == 0x79 || Uids1[0] == 0x7a)
+			return true;
+	}
+	return false;
+}
+
--- a/imgtools/romtools/readimage/src/e32_image_reader.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/readimage/src/e32_image_reader.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,133 +1,133 @@
-/*
-* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent 
-* @released
-*
-*/
-
-
-#include "e32_image_reader.h"
-
-E32ImageReader::E32ImageReader(char *aFile):ImageReader(aFile)
-{
-}
-
-E32ImageReader::E32ImageReader():ImageReader(NULL)
-{
-}
-
-
-E32ImageReader::~E32ImageReader()
-{
-	delete iE32Image;
-}
-
-void E32ImageReader::ReadImage()
-{
-	ifstream aIf(iImgFileName.c_str(), ios::binary | ios::in);
-	if( !aIf.is_open() )
-	{
-		throw ImageReaderException(iImgFileName.c_str(), "Cannot open file ");
-	}
-
-	iE32Image = new E32ImageFile();
-
-	TUint32			aSz;
-
-	aIf.seekg(0,ios::end);
-	aSz = aIf.tellg();
-
-	iE32Image->Adjust(aSz);
-	iE32Image->iFileSize = aSz;
-
-	aIf.seekg(0,ios::beg);
-	aIf >> *iE32Image;
-}
-
-void E32ImageReader::Validate()
-{
-}
-
-void E32ImageReader::ProcessImage()
-{
-}
-
-void E32ImageReader::Dump()
-{
-	*out << "Image Name................." << iImgFileName.c_str() << endl;
-	DumpE32Attributes(*iE32Image);
-}
-
-void E32ImageReader::DumpE32Attributes(E32ImageFile& aE32Image)
-{
-	bool aContinue = true;
-
-	DumpInHex("Size", aE32Image.iSize ) << endl;
-	DumpInHex("Uids",aE32Image.iOrigHdr->iUid1);
-	DumpInHex(" ",aE32Image.iOrigHdr->iUid2, aContinue);
-	DumpInHex(" ",aE32Image.iOrigHdr->iUid3, aContinue);
-	DumpInHex(" ",aE32Image.iOrigHdr->iUidChecksum, aContinue) << endl;
-
-	
-	DumpInHex("Entry point", aE32Image.iOrigHdr->iEntryPoint ) << endl;
-	DumpInHex("Code start addr" ,aE32Image.iOrigHdr->iCodeBase)<< endl;
-	DumpInHex("Data start addr" ,aE32Image.iOrigHdr->iDataBase) << endl;
-	DumpInHex("Text size" ,aE32Image.iOrigHdr->iTextSize) << endl;
-	DumpInHex("Code size" ,aE32Image.iOrigHdr->iCodeSize) << endl;
-	DumpInHex("Data size" ,aE32Image.iOrigHdr->iDataSize) << endl;
-	DumpInHex("Bss size" ,aE32Image.iOrigHdr->iBssSize) << endl;
-	DumpInHex("Total data size" ,(aE32Image.iOrigHdr->iBssSize + aE32Image.iOrigHdr->iDataSize)) << endl;
-	DumpInHex("Heap min" ,aE32Image.iOrigHdr->iHeapSizeMin) << endl;
-	DumpInHex("Heap max" ,aE32Image.iOrigHdr->iHeapSizeMax) << endl;
-	DumpInHex("Stack size" ,aE32Image.iOrigHdr->iStackSize) << endl;
-	DumpInHex("Export directory" ,aE32Image.iOrigHdr->iExportDirOffset) << endl;
-	DumpInHex("Export dir count" ,aE32Image.iOrigHdr->iExportDirCount) << endl;
-	DumpInHex("Flags" ,aE32Image.iOrigHdr->iFlags) << endl;
-
-	TUint aHeaderFmt = E32ImageHeader::HdrFmtFromFlags(aE32Image.iOrigHdr->iFlags);
-
-	if (aHeaderFmt >= KImageHdrFmt_V)
-	{
-		//
-		// Important. Don't change output format of following security info
-		// because this is relied on by used by "Symbian Signed".
-		//
-		E32ImageHeaderV* v = aE32Image.iHdr;
-		DumpInHex("Secure ID", v->iS.iSecureId) << endl;
-		DumpInHex("Vendor ID", v->iS.iVendorId) << endl;
-		DumpInHex("Capability", v->iS.iCaps[1]);
-		DumpInHex(" ", v->iS.iCaps[0], aContinue) << endl;
-
-	}
-
-	*out << "Tools Version..............." << dec << (TUint)aE32Image.iOrigHdr->iToolsVersion.iMajor;
-	*out << ".";
-	out->width (2);
-	*out << dec << (TUint)aE32Image.iOrigHdr->iToolsVersion.iMinor ;
-	*out << "(" << dec << aE32Image.iOrigHdr->iToolsVersion.iBuild << ")" << endl;
-
-	*out << "Module Version.............." << dec << (aE32Image.iOrigHdr->iModuleVersion >> 16) << endl;
-	DumpInHex("Compression", aE32Image.iOrigHdr->iCompressionType) << endl;
-
-	if( aHeaderFmt >= KImageHdrFmt_V )
-	{
-		E32ImageHeaderV* v = aE32Image.iHdr;
-		DumpInHex("Exception Descriptor", v->iExceptionDescriptor) << endl;
-		DumpInHex("Code offset", v->iCodeOffset) << endl;
-	}
-
-	*out << "Priority...................." << dec << aE32Image.iOrigHdr->iProcessPriority << endl;
-	DumpInHex("Dll ref table size", aE32Image.iOrigHdr->iDllRefTableCount) << endl << endl << endl;
-}
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent 
+* @released
+*
+*/
+
+
+#include "e32_image_reader.h"
+
+E32ImageReader::E32ImageReader(const char* aFile):ImageReader(aFile)
+{
+}
+
+E32ImageReader::E32ImageReader():ImageReader("")
+{
+}
+
+
+E32ImageReader::~E32ImageReader()
+{
+	delete iE32Image;
+}
+
+void E32ImageReader::ReadImage()
+{
+	ifstream aIf(iImgFileName.c_str(), ios_base::binary | ios_base::in);
+	if( !aIf.is_open() )
+	{
+		throw ImageReaderException(iImgFileName.c_str(), "Cannot open file ");
+	}
+
+	iE32Image = new E32ImageFile();
+
+	TUint32			aSz;
+
+	aIf.seekg(0,ios_base::end);
+	aSz = aIf.tellg();
+
+	iE32Image->Adjust(aSz);
+	iE32Image->iFileSize = aSz;
+
+	aIf.seekg(0,ios_base::beg);
+	aIf >> *iE32Image;
+}
+
+void E32ImageReader::Validate()
+{
+}
+
+void E32ImageReader::ProcessImage()
+{
+}
+
+void E32ImageReader::Dump()
+{
+	*out << "Image Name................." << iImgFileName.c_str() << endl;
+	DumpE32Attributes(*iE32Image);
+}
+
+void E32ImageReader::DumpE32Attributes(E32ImageFile& aE32Image)
+{
+	bool aContinue = true;
+
+	DumpInHex("Size", aE32Image.iSize ) << endl;
+	DumpInHex("Uids",aE32Image.iOrigHdr->iUid1);
+	DumpInHex(" ",aE32Image.iOrigHdr->iUid2, aContinue);
+	DumpInHex(" ",aE32Image.iOrigHdr->iUid3, aContinue);
+	DumpInHex(" ",aE32Image.iOrigHdr->iUidChecksum, aContinue) << endl;
+
+	
+	DumpInHex("Entry point", aE32Image.iOrigHdr->iEntryPoint ) << endl;
+	DumpInHex("Code start addr" ,aE32Image.iOrigHdr->iCodeBase)<< endl;
+	DumpInHex("Data start addr" ,aE32Image.iOrigHdr->iDataBase) << endl;
+	DumpInHex("Text size" ,aE32Image.iOrigHdr->iTextSize) << endl;
+	DumpInHex("Code size" ,aE32Image.iOrigHdr->iCodeSize) << endl;
+	DumpInHex("Data size" ,aE32Image.iOrigHdr->iDataSize) << endl;
+	DumpInHex("Bss size" ,aE32Image.iOrigHdr->iBssSize) << endl;
+	DumpInHex("Total data size" ,(aE32Image.iOrigHdr->iBssSize + aE32Image.iOrigHdr->iDataSize)) << endl;
+	DumpInHex("Heap min" ,aE32Image.iOrigHdr->iHeapSizeMin) << endl;
+	DumpInHex("Heap max" ,aE32Image.iOrigHdr->iHeapSizeMax) << endl;
+	DumpInHex("Stack size" ,aE32Image.iOrigHdr->iStackSize) << endl;
+	DumpInHex("Export directory" ,aE32Image.iOrigHdr->iExportDirOffset) << endl;
+	DumpInHex("Export dir count" ,aE32Image.iOrigHdr->iExportDirCount) << endl;
+	DumpInHex("Flags" ,aE32Image.iOrigHdr->iFlags) << endl;
+
+	TUint aHeaderFmt = E32ImageHeader::HdrFmtFromFlags(aE32Image.iOrigHdr->iFlags);
+
+	if (aHeaderFmt >= KImageHdrFmt_V)
+	{
+		//
+		// Important. Don't change output format of following security info
+		// because this is relied on by used by "Symbian Signed".
+		//
+		E32ImageHeaderV* v = aE32Image.iHdr;
+		DumpInHex("Secure ID", v->iS.iSecureId) << endl;
+		DumpInHex("Vendor ID", v->iS.iVendorId) << endl;
+		DumpInHex("Capability", v->iS.iCaps[1]);
+		DumpInHex(" ", v->iS.iCaps[0], aContinue) << endl;
+
+	}
+
+	*out << "Tools Version..............." << dec << (TUint)aE32Image.iOrigHdr->iToolsVersion.iMajor;
+	*out << ".";
+	out->width (2);
+	*out << dec << (TUint)aE32Image.iOrigHdr->iToolsVersion.iMinor ;
+	*out << "(" << dec << aE32Image.iOrigHdr->iToolsVersion.iBuild << ")" << endl;
+
+	*out << "Module Version.............." << dec << (aE32Image.iOrigHdr->iModuleVersion >> 16) << endl;
+	DumpInHex("Compression", aE32Image.iOrigHdr->iCompressionType) << endl;
+
+	if( aHeaderFmt >= KImageHdrFmt_V )
+	{
+		E32ImageHeaderV* v = aE32Image.iHdr;
+		DumpInHex("Exception Descriptor", v->iExceptionDescriptor) << endl;
+		DumpInHex("Code offset", v->iCodeOffset) << endl;
+	}
+
+	*out << "Priority...................." << dec << aE32Image.iOrigHdr->iProcessPriority << endl;
+	DumpInHex("Dll ref table size", aE32Image.iOrigHdr->iDllRefTableCount) << endl << endl << endl;
+}
--- a/imgtools/romtools/readimage/src/image_handler.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/readimage/src/image_handler.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,492 +1,432 @@
-/*
-* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent 
-* @released
-*
-*/
-
-
-#include "image_handler.h"
-#include "r_obey.h"
-#include "r_romnode.h"
-#include "r_coreimage.h"
-#include "rofs_image_reader.h"
-#include "rom_image_reader.h"
-#include "e32_image_reader.h"
-#include "e32rom.h"
-#include "h_ver.h"
-#include "sis2iby.h"
-#include <time.h>
-
-ECompression gCompress=ECompressionUnknown;
-ostream *out = &cout;
-string ImageReader::iE32ImgFileName = "";
-string ImageReader::iZdrivePath = "";
-string ImageReader::iLogFileName = "";
-string ImageReader::iPattern = "";
-
-string SisUtils::iOutputPath = ".";
-string SisUtils::iExtractPath = ".";
-
-ImageHandler::ImageHandler() : iReader(NULL) ,iOptions(0), iSisUtils(NULL)
-{
-}
-
-ImageHandler::~ImageHandler()
-{
-	if(iReader)
-		delete iReader;
-
-	if(iSisUtils)
-		delete iSisUtils;
-}
-
-
-void ImageHandler::ProcessArgs(int argc, char**argv)
-{
-	if( argc < 2)
-	{
-		throw ImageReaderUsageException("", "");
-	}
-
-	bool aOutFileGiven = false;
-	int aPos = 1;
-
-	while( argc > aPos )
-	{
-		if(argv[aPos][0] == '-')
-		{
-			switch(argv[aPos][1])
-			{
-			case 'd':
-			case 'D':
-				//dump header info
-				iOptions |= DUMP_HDR_FLAG;
-				break;
-			case 'e':
-			case 'E':
-				iOptions |= DUMP_E32_IMG_FLAG;
-				if(argv[aPos+1])
-					ImageReader::iE32ImgFileName = string(argv[aPos+1]);
-				else 
-					throw ImageReaderUsageException("Usage error", argv[aPos]);
-				aPos++;
-				break;
-			case 'h':
-			case 'H':
-				PrintUsage();
-				exit(EXIT_SUCCESS);
-			case 'o':
-			case 'O':
-				{
-					if(argv[aPos][2])
-					{
-						if((stricmp(argv[aPos],"-OUTDIR")==0))
-						{
-							if(argv[aPos+1])
-							{
-								SisUtils::iOutputPath = string(argv[aPos+1]);
-							}
-							else
-								throw ImageReaderUsageException("Usage Error", argv[aPos]);
-
-							aPos++;
-						}
-						else
-							throw ImageReaderUsageException("Usage Error", argv[aPos]);
-					}
-					else
-					{
-						aOutFileGiven = true;
-						if( argv[aPos+1] )
-						{
-							// unless using iOutFile.c_str() immediately after 
-							// iOutFile = argv[aPos+1];
-							// iOutFile will not be assign correctly,
-							// is it a defect of gcc 3.4.5 ?
-							iOutFile = string(argv[aPos+1]);						
-							aPos++;
-						}
-					}
-				}
-				break;
-			case 'r':
-			case 'R':
-				{
-					if(argv[aPos][2])
-						throw ImageReaderUsageException("Usage Error", argv[aPos]);
-
-					iOptions |= RECURSIVE_FLAG;
-				}
-				break;
-			case 's':
-			case 'S':
-				{
-					if(argv[aPos][2])
-					{
-						if(stricmp(argv[aPos],"-SIS2IBY")==0)
-						{
-							iOptions |= MODE_SIS2IBY;
-						}
-						else
-							throw ImageReaderUsageException("Usage Error", argv[aPos]);
-					}
-					else
-						iOptions |= DUMP_DIR_ENTRIES_FLAG;
-				}
-				break;
-			case 't':
-			case 'T':
-				{
-					if((stricmp(argv[aPos],"-TMPDIR")==0))
-					{
-						if(argv[aPos+1])
-						{
-							SisUtils::iExtractPath = string(argv[aPos+1]);
-						}
-						else
-							throw ImageReaderUsageException("Usage Error", argv[aPos]);
-
-						aPos++;
-					}
-					else
-						throw ImageReaderUsageException("Usage Error", argv[aPos]);
-				}
-				break;
-			case 'v':
-			case 'V':
-				{
-					if(argv[aPos][2])
-						throw ImageReaderUsageException("Usage Error", argv[aPos]);
-
-					iOptions |= DUMP_VERBOSE_FLAG;
-				}
-				break;
-			case 'l':
-			case 'L':
-				{
-					if(argv[aPos+1])
-					{
-						ImageReader::iLogFileName = string(argv[aPos+1]);
-					}
-					else
-						throw ImageReaderUsageException("Usage error", argv[aPos]);
-					iOptions |= LOG_IMAGE_CONTENTS_FLAG;
-					aPos++;
-				}
-				break;
-			case 'x':
-			case 'X':
-				{
-					if(argv[aPos+1] && (!argv[aPos][2]))
-					{
-						ImageReader::iPattern = string(argv[aPos+1]);
-					}
-					else
-						throw ImageReaderUsageException("Usage error", argv[aPos]);
-
-					iOptions |= EXTRACT_FILE_SET_FLAG;
-					aPos++;
-				}
-				break;
-			case 'z':
-			case 'Z':
-				{
-					if(argv[aPos+1])
-						ImageReader::iZdrivePath = string(argv[aPos+1]);
-					else
-						throw ImageReaderUsageException("Usage error", argv[aPos]);
-					
-					iOptions |= EXTRACT_FILES_FLAG;
-					aPos++;
-				}
-				break;
-			default:
-				throw ImageReaderUsageException("Invalid command", argv[aPos]);
-				break;
-			}
-		}
-		else
-		{
-			if(!iInputFileName.empty())
-			{
-				throw ImageReaderUsageException("Invalid command", "Multiple input file not supported");
-			}
-
-			SetInputFile(argv[aPos]);
-		}
-		aPos++;
-	}
-
-	if( aOutFileGiven && !(iOptions & MODE_SIS2IBY) )
-	{
-		ofstream* rdout = new ofstream(iOutFile.c_str(), ios::out | ios::trunc);
-		if( !rdout->is_open()){
-			delete rdout ;
-			rdout = NULL ;
-			throw ImageReaderException((char*)iOutFile.c_str(), "Unable to open File");
-		}
-		out = rdout ;
-	}
-
-	// Disable -z option if -x option is passed
-	if( (iOptions & EXTRACT_FILE_SET_FLAG) && (iOptions & EXTRACT_FILES_FLAG) )
-	{
-		iOptions &= ~(EXTRACT_FILES_FLAG);
-	}
-
-	// -r option should be used along with -x option
-	if( (iOptions & RECURSIVE_FLAG) && !(iOptions & EXTRACT_FILE_SET_FLAG) )
-	{
-		throw ImageReaderUsageException("Usage error", "-r should be used with -x");
-	}
-}
-
-EImageType ImageHandler::ReadMagicWord()
-{
- 
-#if defined(__TOOLS2__) || defined(__MSVCDOTNET__)
-	ifstream file(iInputFileName.c_str(), ios_base::in | ios_base::binary );
-#else
-	ifstream file(iInputFileName.c_str(), ios::in | ios::binary | ios::nocreate);
-#endif
-	
-	EImageType retVal = EUNKNOWN_IMAGE;
-
-	if( !file.is_open() )
-	{
-		throw ImageReaderException((char*)iInputFileName.c_str(), "Cannot open file ");
-	}
-
-	TUint8 magicWords[16];
-	file.read(reinterpret_cast<char*>(magicWords),16);
-
-	if(0 == memcmp(magicWords,"ROFS",4)) {		 
-		retVal = EROFS_IMAGE; 			
-	}else if(0 == memcmp(magicWords,"ROFx",4)) {
-		retVal = EROFX_IMAGE;
-	}
-	else if(0 == memcmp(magicWords,"EPOC",4) && 0 == memcmp(&magicWords[8],"ROM",3) ) {		 
-		retVal = EROM_IMAGE; 
-	}
-	else {
-		E32ImageFile	aE32;
-		TUint32			aSz;
-		file.seekg(0,ios::end);
-		aSz = file.tellg();
-		file.seekg(0,ios::beg);			 
-		aE32.Adjust(aSz);
-		aE32.iFileSize = aSz;
-		file  >> aE32;
-	
-		if(aE32.iError == KErrNone){
-			retVal = EE32_IMAGE;
-		}
-		else {
-			TExtensionRomHeader exRomHeader;
-			file.seekg(0, ios::beg);
-			file.read(reinterpret_cast<char*>(&exRomHeader), sizeof(TExtensionRomHeader));
-			TUint zeroTime = time(0);
-			// aExtensionRomHeader.iTime and aExtensionRomHeader.iKernelTime are 
-			// in microseconds. So convert them to seconds and see if these are 
-			// valid times e.g. a time(in seconds) after midnight Jan 1st, 1970
-			TUint imgTime = exRomHeader.iTime / 1000000;
-			TUint kernImgTime = exRomHeader.iKernelTime / 1000000;
-			if( imgTime >= zeroTime && kernImgTime >= zeroTime) {
-				//Check if the padding in the header has value 0xff
-				retVal = EROMX_IMAGE;
-				for(int i = sizeof(exRomHeader.iPad) - 1 ; i >= 0 ; i--){
-					if(0xff != exRomHeader.iPad[i]){
-						retVal = EUNKNOWN_IMAGE;
-						break ;
-					}
-				}  
-			}
-		}		 
-	}   
-	
-	if(retVal == EUNKNOWN_IMAGE){
-		file.seekg(0,ios::beg);
-        retVal = ReadBareImage(file);
-	}
-
-	file.close();
-
-	return retVal;
-}
-
-
-/**
- * @fn ImageHandler::ReadBareImage
- * @brief this function processes image type under the condition of that if an image is given without header which means the image is not self-described
- * @return type of the image.
- * @note this function is introduced for handling issues raised by DEF129908
- */
-EImageType ImageHandler::ReadBareImage(ifstream& aIfs)
-{
-    TRomHeader romHdr ; 
-    aIfs.read(reinterpret_cast<char*>(&romHdr),sizeof(TRomHeader)); 
-
-    return ((romHdr.iRomBase >= KRomBase ) && 
-		(romHdr.iRomRootDirectoryList > KRomBase ) &&
-       (romHdr.iRomBase < KRomBaseMaxLimit ) && 
-	   (romHdr.iRomRootDirectoryList < KRomBaseMaxLimit)) ? EBAREROM_IMAGE : EUNKNOWN_IMAGE;
-     
-}
-
-
-void ImageHandler::HandleInputFiles()
-{
-	if(!(iOptions & MODE_SIS2IBY))
-	{
-		EImageType imgType = ReadMagicWord();
-		
-		switch(imgType)
-		{
-		case EROFS_IMAGE:
-		case EROFX_IMAGE:
-			iReader = new RofsImageReader((char*)iInputFileName.c_str());
-			break;
-		case EROM_IMAGE:
-			iReader = new RomImageReader((char*)iInputFileName.c_str());
-			break;
-        case EBAREROM_IMAGE:
-            iReader = new RomImageReader((char*)iInputFileName.c_str(), EBAREROM_IMAGE);
-            break;
-		case EROMX_IMAGE:
-			iReader = new RomImageReader((char*)iInputFileName.c_str(), EROMX_IMAGE);
-			break;
-		case EE32_IMAGE:
-			iReader = new E32ImageReader((char*)iInputFileName.c_str());
-			break;
-		default:
-			{
-            throw ImageReaderException((char*)iInputFileName.c_str(), "Unknown Type of Image file");
-			}
-			break;
-		}
-
-		if(iReader)
-		{
-			iReader->ReadImage();
-			iReader->ProcessImage();
-			iReader->Validate();
-			iReader->SetDisplayOptions( iOptions );
-			iReader->ExtractImageContents();
-			iReader->Dump();
-		}
-	}
-	else
-	{
-		if(iInputFileName.empty())
-		{
-			throw SisUtilsException("Usage Error", "No SIS file passed");
-		}
-
-		iSisUtils = new Sis2Iby((char*)iInputFileName.c_str());
-
-		if(iSisUtils)
-		{
-			if(iOptions & DUMP_VERBOSE_FLAG)
-			{
-				iSisUtils->SetVerboseMode();
-			}
-
-			iSisUtils->ProcessSisFile();
-			iSisUtils->GenerateOutput();
-		}
-		else
-		{
-			throw SisUtilsException("Error:", "Cannot create Sis2Iby object");
-		}
-	}
-}
-
-void ImageHandler::PrintVersion()
-{
-	*out << "\nReadimage - reader for Rom, Rofs and E32 images V";
-	out->width(1);
-	*out << MajorVersion << ".";
-	out->width(2);
-	out->fill('0');
-	*out << MinorVersion << " (";
-	out->width(3);
-	*out << Build  << ") " << endl;
-	*out << Copyright;
-}
-
-void ImageHandler::PrintUsage()
-{
-	PrintVersion();
-	const char aUsage[] = 
-		"Usage: readImage [options] [<-sis2iby> [sis-options]] <filename>\n\n"
-		"Options: With no options, it prints the files and directories in image\n"
-		"       -o      output file name\n"
-		"       -d      dump header information(default)\n"
-		"       -s      dump the directory structure\n"
-		"       -v      dump image headers and directory structure\n"
-		"       -e xxx  dump the xxx e32 image within the entire image when used along with -v or -s option\n"
-		"       -h      this message\n"
-		"       -z xxx  extract all the file(s) from the given image to xxx location\n"
-		"       -l xxx  log the image contents on to xxx file\n"
-		"       -x xxx  extract single or set of files as given in xxx from the given image\n"
-		"       -r      recursively extract files from the sub-directories when used along with -x option\n\n"
-		"SIS-options: Option -sis2iby changes the mode to generate IBY from SIS file\n"
-		"       -sis2iby      generates iby file for the given SIS file\n"
-		"       -tmpdir xxx   extract all sis file contents to xxx location\n"
-		"       -outdir xxx   generates the iby file(s) to xxx location\n"
-		"       -v            verbose output\n";
-	*out << aUsage << endl;
-}
-
-int main(int argc, char** argv)
-{
-	ImageHandler aIh;
-	int retVal = EXIT_SUCCESS;
-	try
-	{
-		aIh.ProcessArgs(argc, argv);
-		aIh.HandleInputFiles();
-	}
-	catch(ImageReaderUsageException& aIre)
-	{
-		if(argc >= 2)
-		{
-			//This is a usage error and has to be reported
-			//Otherwise, it is called just to display the usage
-			aIre.Report();
-		}
-		aIh.PrintUsage();
-		retVal = EXIT_FAILURE;
-	}
-	catch(ImageReaderException& aIre)
-	{
-		aIre.Report();
-		retVal = EXIT_FAILURE;
-	}
-	catch(SisUtilsException& aSUe)
-	{
-		aSUe.Report();
-		retVal = EXIT_FAILURE;
-	}
-	
-	if(out != &cout){
-		ofstream* rdout = static_cast<ofstream*>(out) ;
-		rdout->close() ;
-		delete rdout ; 
-	}
-
-	return retVal;
-}
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent 
+* @released
+*
+*/
+
+
+#include "image_handler.h"
+#include "r_obey.h"
+#include "r_romnode.h"
+#include "r_coreimage.h"
+#include "rofs_image_reader.h"
+#include "rom_image_reader.h"
+#include "e32_image_reader.h"
+#include "e32rom.h"
+#include "h_ver.h"
+#include "sis2iby.h"
+#include <time.h>
+
+ECompression gCompress=ECompressionUnknown;
+ostream *out = &cout;
+string ImageReader::iE32ImgFileName = "";
+string ImageReader::iZdrivePath = "";
+string ImageReader::iLogFileName = "";
+string ImageReader::iPattern = "";
+
+string SisUtils::iOutputPath = ".";
+string SisUtils::iExtractPath = ".";
+
+ImageHandler::ImageHandler() : iReader(NULL) ,iOptions(0), iSisUtils(NULL) {
+}
+
+ImageHandler::~ImageHandler() {
+	if(iReader)
+		delete iReader;
+
+	if(iSisUtils)
+		delete iSisUtils;
+}
+
+
+void ImageHandler::ProcessArgs(int argc, char*argv[]) {
+	if( argc < 2) {
+		throw ImageReaderUsageException("", "");
+	}
+
+	bool aOutFileGiven = false;
+	int index = 1; 
+	
+	while( argc > index ) {
+		char* arg = argv[index]; 
+		if(arg[0] == '-') {
+			switch(0x20 | arg[1]) {
+			case 'd': 
+				//dump header info
+				iOptions |= DUMP_HDR_FLAG;
+				break;
+			case 'e': 
+				iOptions |= DUMP_E32_IMG_FLAG; 
+				++index ;
+				if(index < argc) {
+					arg = argv[index];
+					ImageReader::iE32ImgFileName = string(arg);
+				}
+				else 
+					throw ImageReaderUsageException("Usage error", arg);
+				
+				break;
+			case 'h': 
+				PrintUsage();
+				exit(EXIT_SUCCESS);
+			case 'o':  
+				if(arg[2]) {
+					if((stricmp(arg,"-OUTDIR")==0)) {
+						++index;
+						if(index < argc) {
+							arg = argv[index];
+							SisUtils::iOutputPath = string(arg);
+						}
+						else
+							throw ImageReaderUsageException("Usage Error", arg); 
+					}
+					else
+						throw ImageReaderUsageException("Usage Error", arg);
+				}
+				else {
+					aOutFileGiven = true;
+					++index;				
+					if( index < argc ) {
+						// unless using iOutFile.c_str() immediately after 
+						// iOutFile = argv[index+1];
+						// iOutFile will not be assign correctly,
+						// is it a defect of gcc 3.4.5 ? 
+						arg = argv[index];
+						iOutFile = string(arg); 
+					}
+					else
+						throw ImageReaderUsageException("Usage Error", arg); 
+				}
+				 
+				break;
+			case 'r': 				 
+				if(arg[2])
+					throw ImageReaderUsageException("Usage Error", arg);
+				iOptions |= RECURSIVE_FLAG;				 
+				break;
+			case 's': 				
+				if(arg[2]) {
+					if(stricmp(arg,"-SIS2IBY")==0) {
+						iOptions |= MODE_SIS2IBY;
+					}
+					else
+						throw ImageReaderUsageException("Usage Error", arg);
+				}
+				else
+					iOptions |= DUMP_DIR_ENTRIES_FLAG;
+				
+				break;
+			case 't': 				 
+				if((stricmp(argv[index],"-TMPDIR")==0)) {
+					++index;
+					if( index < argc ) {  
+						arg = argv[index];
+						SisUtils::iExtractPath = string(arg);
+					}
+					else
+						throw ImageReaderUsageException("Usage Error", arg); 
+				}
+				else
+					throw ImageReaderUsageException("Usage Error", arg);
+				 
+				break;
+			case 'v':  
+				if(arg[2])
+					throw ImageReaderUsageException("Usage Error", arg);
+				iOptions |= DUMP_VERBOSE_FLAG; 
+				break;
+			case 'l': 
+				++index;
+				if(index < argc) {
+					arg = argv[index];
+					ImageReader::iLogFileName = string(arg);
+				}
+				else
+					throw ImageReaderUsageException("Usage error", arg);
+				iOptions |= LOG_IMAGE_CONTENTS_FLAG;
+				 
+				break;
+			case 'x': 
+				++index;
+				if(index < argc && 0 == arg[2]) {
+					arg = argv[index];
+					ImageReader::iPattern = string(arg);
+				}
+				else
+					throw ImageReaderUsageException("Usage error", arg);
+
+				iOptions |= EXTRACT_FILE_SET_FLAG; 
+				 
+				break;
+			case 'z': 
+				++index;
+				if(index < argc ){
+					arg = argv[index];
+					ImageReader::iZdrivePath = string(arg);
+				}
+				else
+					throw ImageReaderUsageException("Usage error", arg);					
+				iOptions |= EXTRACT_FILES_FLAG; 
+				
+				break;
+			default:
+				throw ImageReaderUsageException("Invalid command", arg);
+				break;
+			}
+		}
+		else {
+			if(!iInputFileName.empty()) {
+				throw ImageReaderUsageException("Invalid command", "Multiple input file not supported");
+			}
+
+			SetInputFile(string(arg));
+		}
+		index++;
+	}
+
+	if( aOutFileGiven && !(iOptions & MODE_SIS2IBY) ) {
+		ofstream* rdout = new ofstream(iOutFile.c_str(), ios_base::out | ios_base::trunc);
+		if( !rdout->is_open()){
+			delete rdout ;
+			rdout = NULL ;
+			throw ImageReaderException(iOutFile.c_str(), "Unable to open File");
+		}
+		out = rdout ;
+	}
+
+	// Disable -z option if -x option is passed
+	if( (iOptions & EXTRACT_FILE_SET_FLAG) && (iOptions & EXTRACT_FILES_FLAG) ) {
+		iOptions &= ~(EXTRACT_FILES_FLAG);
+	}
+
+	// -r option should be used along with -x option
+	if( (iOptions & RECURSIVE_FLAG) && !(iOptions & EXTRACT_FILE_SET_FLAG) ) {
+		throw ImageReaderUsageException("Usage error", "-r should be used with -x");
+	}
+}
+
+EImageType ImageHandler::ReadMagicWord() {
+	ifstream file(iInputFileName.c_str(), ios_base::in | ios_base::binary );
+	
+	EImageType retVal = EUNKNOWN_IMAGE;
+
+	if( !file.is_open() ) {
+		throw ImageReaderException(iInputFileName.c_str(), "Cannot open file ");
+	}
+
+	TUint8 magicWords[16];
+	file.read(reinterpret_cast<char*>(magicWords),16);
+
+	if(0 == memcmp(magicWords,"ROFS",4)) {		 
+		retVal = EROFS_IMAGE; 			
+	}else if(0 == memcmp(magicWords,"ROFx",4)) {
+		retVal = EROFX_IMAGE;
+	}
+	else if(0 == memcmp(magicWords,"EPOC",4) && 0 == memcmp(&magicWords[8],"ROM",3) ) {		 
+		retVal = EROM_IMAGE; 
+	}
+	else {
+		E32ImageFile	aE32;
+		TUint32			aSz;
+		file.seekg(0,ios_base::end);
+		aSz = file.tellg();
+		file.seekg(0,ios_base::beg);			 
+		aE32.Adjust(aSz);
+		aE32.iFileSize = aSz;
+		file  >> aE32;
+	
+		if(aE32.iError == KErrNone){
+			retVal = EE32_IMAGE;
+		}
+		else {
+			TExtensionRomHeader exRomHeader;
+			file.seekg(0, ios_base::beg);
+			file.read(reinterpret_cast<char*>(&exRomHeader), sizeof(TExtensionRomHeader));
+			TUint zeroTime = time(0);
+			// aExtensionRomHeader.iTime and aExtensionRomHeader.iKernelTime are 
+			// in microseconds. So convert them to seconds and see if these are 
+			// valid times e.g. a time(in seconds) after midnight Jan 1st, 1970
+			TUint imgTime = exRomHeader.iTime / 1000000;
+			TUint kernImgTime = exRomHeader.iKernelTime / 1000000;
+			if( imgTime >= zeroTime && kernImgTime >= zeroTime) {
+				//Check if the padding in the header has value 0xff
+				retVal = EROMX_IMAGE;
+				for(int i = sizeof(exRomHeader.iPad) - 1 ; i >= 0 ; i--){
+					if(0xff != exRomHeader.iPad[i]){
+						retVal = EUNKNOWN_IMAGE;
+						break ;
+					}
+				}  
+			}
+		}		 
+	}   
+	
+	if(retVal == EUNKNOWN_IMAGE){
+		file.seekg(0,ios_base::beg);
+        retVal = ReadBareImage(file);
+	}
+
+	file.close();
+
+	return retVal;
+}
+
+
+/**
+ * @fn ImageHandler::ReadBareImage
+ * @brief this function processes image type under the condition of that if an image is given without header which means the image is not self-described
+ * @return type of the image.
+ * @note this function is introduced for handling issues raised by DEF129908
+ */
+EImageType ImageHandler::ReadBareImage(ifstream& aIfs) {
+    TRomHeader romHdr ; 
+    aIfs.read(reinterpret_cast<char*>(&romHdr),sizeof(TRomHeader)); 
+
+    return ((romHdr.iRomBase >= KRomBase ) && 
+		(romHdr.iRomRootDirectoryList > KRomBase ) &&
+       (romHdr.iRomBase < KRomBaseMaxLimit ) && 
+	   (romHdr.iRomRootDirectoryList < KRomBaseMaxLimit)) ? EBAREROM_IMAGE : EUNKNOWN_IMAGE;
+     
+}
+
+
+void ImageHandler::HandleInputFiles() {
+	if(!(iOptions & MODE_SIS2IBY)) {
+		EImageType imgType = ReadMagicWord();
+		
+		switch(imgType)
+		{
+		case EROFS_IMAGE:
+		case EROFX_IMAGE:
+			iReader = new RofsImageReader(iInputFileName.c_str());
+			break;
+		case EROM_IMAGE:
+			iReader = new RomImageReader(iInputFileName.c_str());
+			break;
+        case EBAREROM_IMAGE:
+            iReader = new RomImageReader(iInputFileName.c_str(), EBAREROM_IMAGE);
+            break;
+		case EROMX_IMAGE:
+			iReader = new RomImageReader(iInputFileName.c_str(), EROMX_IMAGE);
+			break;
+		case EE32_IMAGE:
+			iReader = new E32ImageReader(iInputFileName.c_str());
+			break;
+		default:
+			{
+            throw ImageReaderException(iInputFileName.c_str(), "Unknown Type of Image file");
+			}
+			break;
+		}
+
+		if(iReader) {
+			iReader->ReadImage();
+			iReader->ProcessImage();
+			iReader->Validate();
+			iReader->SetDisplayOptions( iOptions );
+			iReader->ExtractImageContents();
+			iReader->Dump();
+		}
+	}
+	else {
+		if(iInputFileName.empty()) {
+			throw SisUtilsException("Usage Error", "No SIS file passed");
+		}
+
+		iSisUtils = new Sis2Iby(iInputFileName.c_str());
+
+		if(iSisUtils) {
+			if(iOptions & DUMP_VERBOSE_FLAG) {
+				iSisUtils->SetVerboseMode();
+			}
+
+			iSisUtils->ProcessSisFile();
+			iSisUtils->GenerateOutput();
+		}
+		else {
+			throw SisUtilsException("Error:", "Cannot create Sis2Iby object");
+		}
+	}
+}
+
+void ImageHandler::PrintVersion() {
+	*out << "\nReadimage - reader for Rom, Rofs and E32 images V";
+	out->width(1);
+	*out << MajorVersion << ".";
+	out->width(2);
+	out->fill('0');
+	*out << MinorVersion << " (";
+	out->width(3);
+	*out << Build  << ") " << endl;
+	*out << Copyright;
+}
+
+void ImageHandler::PrintUsage() {
+	PrintVersion();
+	const char aUsage[] = 
+		"Usage: readImage [options] [<-sis2iby> [sis-options]] <filename>\n\n"
+		"Options: With no options, it prints the files and directories in image\n"
+		"       -o      output file name\n"
+		"       -d      dump header information(default)\n"
+		"       -s      dump the directory structure\n"
+		"       -v      dump image headers and directory structure\n"
+		"       -e xxx  dump the xxx e32 image within the entire image when used along with -v or -s option\n"
+		"       -h      this message\n"
+		"       -z xxx  extract all the file(s) from the given image to xxx location\n"
+		"       -l xxx  log the image contents on to xxx file\n"
+		"       -x xxx  extract single or set of files as given in xxx from the given image\n"
+		"       -r      recursively extract files from the sub-directories when used along with -x option\n\n"
+		"SIS-options: Option -sis2iby changes the mode to generate IBY from SIS file\n"
+		"       -sis2iby      generates iby file for the given SIS file\n"
+		"       -tmpdir xxx   extract all sis file contents to xxx location\n"
+		"       -outdir xxx   generates the iby file(s) to xxx location\n"
+		"       -v            verbose output\n";
+	*out << aUsage << endl;
+}
+
+int main(int argc, char* argv[]) {
+	ImageHandler aIh;
+	int retVal = EXIT_SUCCESS;
+	try {
+		aIh.ProcessArgs(argc, argv);
+		aIh.HandleInputFiles();
+	}
+	catch(ImageReaderUsageException& aIre) {
+		if(argc >= 2) {
+			//This is a usage error and has to be reported
+			//Otherwise, it is called just to display the usage
+			aIre.Report();
+		}
+		aIh.PrintUsage();
+		retVal = EXIT_FAILURE;
+	}
+	catch(ImageReaderException& aIre) {
+		aIre.Report();
+		retVal = EXIT_FAILURE;
+	}
+	catch(SisUtilsException& aSUe) {
+		aSUe.Report();
+		retVal = EXIT_FAILURE;
+	}
+	
+	if(out != &cout){
+		ofstream* rdout = static_cast<ofstream*>(out) ;
+		rdout->close() ;
+		delete rdout ; 
+	}
+
+	return retVal;
+}
--- a/imgtools/romtools/readimage/src/image_reader.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/readimage/src/image_reader.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,504 +1,477 @@
-/*
-* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent 
-* @released
-*
-*/
-
-
-#include "image_reader.h"
-
-ImageReader::ImageReader(const char* aFile) : iDisplayOptions(0),iImgFileName(aFile)
-{
-}
-
-ImageReader::~ImageReader()
-{
-}
-
-void ImageReader::SetDisplayOptions(TUint32 aFlag)
-{
-	iDisplayOptions |= aFlag;
-}
-
-bool ImageReader::DisplayOptions(TUint32 aFlag)
-{
-	return ((iDisplayOptions & aFlag) != 0);
-}
-
-void ImageReader::DumpData(TUint* aData, TUint aLength)
-{
-	TUint *p=aData;
-	TUint i=0;
-	char line[256];
-	char *cp=(char*)aData;
-	TUint j=0;
-	memset(line,' ',sizeof(line));
-	while (i<aLength)
-		{
-		TUint ccount=0;
-		char* linep=&line[8*5+2];
-		*out<< "0x";
-		out->width(6);
-		out->fill('0');
-		*out << i << ":";
-		while (i<aLength && ccount<4)
-			{
-			*out<< " ";
-			out->width(8);
-			out->fill('0');
-			*out << *p++;
-			i+=4;
-			ccount++;
-			for (j=0; j<4; j++)
-				{
-				char c=*cp++;
-				if (c<32)
-					{
-					c = '.';
-					}
-				*linep++ = c;
-				}
-			}
-		*linep = '\0';
-		*out << line+(ccount*5) << endl;
-		}
-	}
-
-
-
-/** 
-Function to extract specified file from a given image. 
-
-@internalComponent
-@released
- 
-@param aOffset - starting offset of the file in the image.
-@param aSize - size of the file in the image.
-@param aFileName - name of the file.
-@param aPath - full path of the file inside image.
-@param aFilePath - path where file has to be extracted.
-*/
-void ImageReader::ExtractFile(TUint aOffset,TInt aSize,const char* aFileName,const char* aPath,char* aFilePath,char* aData)
-{
-	// concatenate path where specified file needs to be extracted with
-	// path where file is located in the image.
-	string fullPath( aFilePath );
-	string delimiter( "\\" );
-	string appStr( "\\\\" );
-	fullPath.append( aPath );
-	
-	// replace all the occurrence of slash with double slash. 
-	FindAndInsertString( fullPath, delimiter, delimiter );
-	// now terminate the string with double slash.
-	fullPath.append( appStr );
-
-	// create specified directory where file needs to be extracted.
-	CreateSpecifiedDir( &fullPath[0], appStr.c_str() );
-
-	// concatenate path information with the filename
-	fullPath.append( aFileName );
-
-	// create an output stream to extract the specified file.
-	ofstream outfile (fullPath.c_str(), ios::out | ios::binary);
-	// create an input stream by opening the specified image file.
-	ifstream infile(ImageReader::iImgFileName.c_str(),ios::in|ios::binary);
-
-	//declare a buffer to store the data.
-	char* buffer = new char[aSize];
-
-	if(aData != NULL)
-	{
-		memcpy(buffer, aData + aOffset, aSize);
-	}
-	else if(infile.is_open())
-	{
-		// place the get pointer for the current input stream to offset bytes away from origin.
-		infile.seekg(aOffset,ios::beg);
-		//read number of bytes specified by the variable size 
-		//from the stream and place it on to buffer.
-		infile.read(buffer,aSize);
-		//close the input stream after reading.
-		infile.close();
-	}
-	else
-	{
-		throw ImageReaderException(ImageReader::iImgFileName.c_str(), "Failed to open the image file");
-	}
-
-	if(outfile.is_open())
-	{
-		//writes number of bytes specified by the variable size 
-		//from buffer to the current output stream.
-		outfile.write(buffer,aSize);
-		//close the output stream after writing.
-		outfile.close();
-	}
-	else
-	{
-		throw ImageReaderException(aFileName, "Failed to extract the file");
-	}
-
-	//delete the buffer.
-	delete[] buffer;
-}
-
-/** 
-Function to create a given directory. 
-
-@internalComponent
-@released
-
-@param aSrcPath - path of the directory that needs to be created.
-@param aDelimiter - delimiter.
-*/
-void ImageReader::CreateSpecifiedDir(char* aSrcPath,const char* aDelimiter)
-{
-	char* currWorkingDir = new char[_MAX_BUFFER_SIZE_];
-	string origPath;
-
-	origPath.assign(aSrcPath);
-
-
-	// get the current working directory and store in buffer.
-	if( _getcwd(currWorkingDir,_MAX_BUFFER_SIZE_) == NULL )
-	{
-		// throw an exception if unable to get current working directory information.
-		throw ImageReaderException((char*)ImageReader::iImgFileName.c_str(), "Failed to get the current working directory");
-	}
-	else
-	{
-		char* cPtr = strtok(aSrcPath,aDelimiter);
-
-		// check whether cPtr is a drive or a directory.
-		if(IsDrive(cPtr))
-		{
-			// if yes, then change the directory to cPtr.
-			string changeToDrive ;
-			changeToDrive.assign(cPtr);
-			changeToDrive.append(aDelimiter);
-			
-			// change the current working directory to the specified directory.
-			if( _chdir(changeToDrive.c_str()) )
-			{
-				// throw an exception if unable to change the directory specified.
-				throw ImageReaderException((char*)ImageReader::iImgFileName.c_str(), "Failed to change to the directory specified");
-			}
-		}
-		else
-		{
-			// if not,then create a cPtr directory. 
-			_mkdir(cPtr);
-			// change the current working directory to cPtr.
-			_chdir(cPtr);
-		}
-		// repeat till cPtr is NULL.
-		while (cPtr!=NULL)
-		{
-			if (cPtr = strtok(NULL,aDelimiter))
-			{
-				// create the directory.
-				_mkdir(cPtr);
-				// change current working directory.
-				_chdir(cPtr);
-			}
-		}
-		// revert back the working directory.
-		_chdir(currWorkingDir);
-		// replace the source path with the original path information.
-		strcpy(aSrcPath,origPath.c_str());
-		delete[] currWorkingDir;
-	}
-}
-
-
-/** 
-Function to check whether the given string is a drive or a folder.
-
-@internalComponent
-@released
-
-@param aStr - string to be checked.
-@return - returns True if the given string is a drive else returns false.
-*/
-TBool ImageReader::IsDrive(char* aStr)
-{
-	TInt strlength = strlen(aStr);
-	//check for the last character in a given string,
-	//if the last character is colon then return true else false.
-	if(!strcmp(&aStr[strlength - 1],":"))
-	{
-		return true;
-	}
-	else
-	{
-		return false;
-	}
-}
-
-
-/** 
-Function to insert a given string with a delimiter.
-
-@internalComponent
-@released
-
-@param aSrcStr - string to be modified.
-@param aDelimiter - string to be checked.
-@param aAppStr - string to be inserted with the delimiter.
-*/
-void ImageReader::FindAndInsertString(string& aSrcStr,string& aDelimiter,string& aAppStr)
-{
-	string::size_type loc = 0;
-	string::size_type pos =0;
-	while(( pos = aSrcStr.find( aDelimiter, loc ) ) != ( string::npos ) )
-	{
-		if( pos != string::npos )
-		{
-			aSrcStr.insert(pos,aAppStr);
-			loc = pos + aAppStr.length() + 1;
-		}
-	}
-}
-
-/** 
-Function to replace a delimiter with a given string.
-
-@internalComponent
-@released
-
-@param aSrcStr - string to be modified.
-@param aDelimiter - string to be checked.
-@param aReplStr - string to be replaced with the delimiter.
-*/
-void ImageReader::FindAndReplaceString( string& aSrcStr, string& aDelimiter, string& aReplStr )
-{
-	string::size_type loc = 0;
-	string::size_type pos =0;
-	while(( pos = aSrcStr.find( aDelimiter,loc) ) != ( string::npos ) )
-	{
-		if( pos != string::npos )
-		{
-			aSrcStr.replace( pos, aReplStr.length(),aReplStr );
-			loc = pos + aReplStr.length() + 1;
-		}
-	}
-}
-
-/** 
-Function to extract individual or a subset of file.
-
-@internalComponent
-@released
-
-@param aData - ROM/ROFS image buffer pointer.
-*/
-void ImageReader::ExtractFileSet(char* aData)
-{
-	FILEINFOMAP fileInfoMap;
-	string dirSep(DIR_SEPARATOR), backSlash("\\"), Pattern;
-	TUint extfileCount = 0, noWcardFlag = 0, pos;
-
-	//Get the filelist map
-	GetFileInfo(fileInfoMap);
-
-	//Check for wildcards
-	pos = iPattern.rfind("\\");
-	if(pos == string::npos)
-	{
-		pos = iPattern.rfind("/");
-		if(pos == string::npos)
-			pos = 0;
-	}
-	pos = iPattern.find_first_of("*?", pos);
-	if(pos == string::npos)
-	{
-		noWcardFlag = 1;
-	}
-
-	//Process the map
-	if(fileInfoMap.size() > 0)
-	{
-		FILEINFOMAP::iterator begin = fileInfoMap.begin();
-		FILEINFOMAP::iterator end = fileInfoMap.end();
-
-		// Replace all backslashes with forward slashes
-		Pattern = iPattern;
-		FindAndReplaceString(Pattern, backSlash, dirSep);
-
-		// Insert root directory at the beginning if it is not there
-		pos = Pattern.find_first_not_of(" ", 0);
-		if(pos != string::npos)
-		{
-			if(Pattern.at(pos) != *DIR_SEPARATOR)
-				Pattern.insert(pos, dirSep);
-		}
-
-		// Assign CWD for destination path if it is empty
-		if(ImageReader::iZdrivePath.empty())
-			ImageReader::iZdrivePath.assign(".");
-
-		while(begin != end)
-		{
-			int status = 0;
-			PFILEINFO pInfo = 0;
-			string fileName = (*begin).first;
-			pInfo = (*begin).second;
-
-			// First match
-			status = FileNameMatch(Pattern, fileName, (iDisplayOptions & RECURSIVE_FLAG));
-
-			// If no match
-			if((!status) && noWcardFlag)
-			{
-				string newPattern(Pattern);
-
-				// Add * at the end
-				if(newPattern.at(Pattern.length()-1) != *DIR_SEPARATOR)
-				{
-					newPattern.append(DIR_SEPARATOR);
-				}
-				newPattern += "*";
-				status = FileNameMatch(newPattern, fileName, (iDisplayOptions & RECURSIVE_FLAG));
-
-				// If it matches update the pattern and reset wildcard flag
-				if(status)
-				{
-					Pattern = newPattern;
-					noWcardFlag = 0;
-				}
-			}
-
-			if(status)
-			{
-				// Extract the file
-
-				// Separarate the path and file name
-				string fullPath = fileName.substr(0, fileName.rfind(DIR_SEPARATOR));
-				string file = fileName.substr(fileName.rfind(DIR_SEPARATOR)+1, fileName.length());
-				FindAndReplaceString(fullPath, dirSep, backSlash);
-
-				// Extract only those files exists in the image
-				if(pInfo->iSize && pInfo->iOffset)
-				{
-					ExtractFile(pInfo->iOffset, pInfo->iSize, file.c_str(), fullPath.c_str() , 
-						&ImageReader::iZdrivePath[0], aData);
-
-					extfileCount++;
-				}
-			}
-
-			if(pInfo)
-				delete pInfo;
-			++begin;
-		}
-		fileInfoMap.clear();
-	}
-
-	// Throw error if the extracted file count is zero
-	if(!extfileCount)
-	{
-		throw ImageReaderException((char*)ImageReader::iImgFileName.c_str(), "No matching files found for the given pattern");
-	}
-}
-
-/** 
-To match the given file name aganist the given pattern with wildcards
-
-@internalComponent
-@released
-
-@param aPattern - input filename pattern.
-@param aFileName - input file name.
-@param aRecursiveFlag - recursive search flag.
-*/
-int ImageReader::FileNameMatch(string aPattern, string aFileName, int aRecursiveFlag)
-{
-	const char *InputString = aFileName.c_str();
-	const char *Pattern = aPattern.c_str();
-	const char *CurrPattern = 0, *CurrString = 0;
-	
-	// If the input is empty then return false
-	if((aPattern.empty()) || (!InputString))
-		return 0;
-
-	// First candidate match
-	// Step 1: Look for the exact matches between the input pattern and the given file-name till 
-	//         the first occurrence of wildcard character (*). This should also skip a character 
-	//         from matching for the occurrence of wildcard character(?) in the pattern.
-	while ((*InputString) && (*Pattern != '*')) 
-	{
-		if ((toupper(*Pattern) != toupper(*InputString)) && (*Pattern != '?')) 
-		{
-			return 0;
-		}
-		Pattern++;
-		InputString++;
-	}
-	
-	// Wildcard match
-	// Step 2: Now the input string (file-name) should be checked against the wildcard characters (* and ?). 
-	//         Skip the input string if the pattern points to wildcard character(*). Do the exact match for 
-	//         other characters in the patterns except the wildcard character(?). The path-separator should be 
-	//         considered as non-match for non-recursive option.
-	while (*InputString) 
-	{
-		if ((*Pattern == '*')) 
-		{
-			if (!*++Pattern) 
-			{
-				// If recursive flag is set then this case matches for any character of the input string
-				// from the current position
-				if(aRecursiveFlag)
-					return 1;
-			}
-
-			// Update the current pattern and the current inputstring
-			CurrPattern = Pattern;
-			CurrString = InputString+1;			
-		} 
-		else if ((toupper(*Pattern) == toupper(*InputString)) || (*Pattern == '?')) 
-		{
-			// Exact match for the path separator
-			// So recursively call the function to look for the exact path level match
-			if(*Pattern == '/')
-				return FileNameMatch(Pattern, InputString, aRecursiveFlag);
-
-			// Exact match so increment both
-			Pattern++;
-			InputString++;
-		} 
-		else if ((*InputString == *DIR_SEPARATOR) && (!aRecursiveFlag))
-		{
-			// Inputstring points to path separator and it is not expected here for non-recursive case
-			return 0;
-		}
-		else
-		{
-			// Default case where it matches for the wildcard character *
-			Pattern = CurrPattern;
-			InputString = CurrString++;
-		}
-	}
-	
-	// Leave any more stars in the pattern
-	while (*Pattern == '*') 
-	{
-		Pattern++;
-	}
-	
-	// Return the status
-	return !*Pattern;
-}
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent 
+* @released
+*
+*/
+
+
+#include "image_reader.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <boost/filesystem.hpp>
+ 
+using namespace boost::filesystem;
+ImageReader::ImageReader(const char* aFile) : iDisplayOptions(0),iImgFileName(aFile) {
+}
+
+ImageReader::~ImageReader() {
+}
+
+void ImageReader::SetDisplayOptions(TUint32 aFlag) {
+	iDisplayOptions |= aFlag;
+}
+
+bool ImageReader::DisplayOptions(TUint32 aFlag) {
+	return ((iDisplayOptions & aFlag) != 0);
+}
+
+void ImageReader::DumpData(TUint* aData, TUint aLength) {
+	TUint *p=aData;
+	TUint i=0;
+	char line[256];
+	char *cp=(char*)aData;
+	TUint j=0;
+	memset(line,' ',sizeof(line));
+	while (i<aLength) {
+		TUint ccount=0;
+		char* linep=&line[8*5+2];
+		*out<< "0x";
+		out->width(6);
+		out->fill('0');
+		*out << i << ":";
+		while (i<aLength && ccount<4) {
+			*out<< " ";
+			out->width(8);
+			out->fill('0');
+			*out << *p++;
+			i+=4;
+			ccount++;
+			for (j=0; j<4; j++) {
+				char c=*cp++;
+				if (c<32) {
+					c = '.';
+					}
+				*linep++ = c;
+				}
+			}
+		*linep = '\0';
+		*out << line+(ccount*5) << endl;
+		}
+	}
+
+
+
+/** 
+Function to extract specified file from a given image. 
+
+@internalComponent
+@released
+ 
+@param aOffset - starting offset of the file in the image.
+@param aSize - size of the file in the image.
+@param aFileName - name of the file.
+@param aPath - full path of the file inside image.
+@param aFilePath - path where file has to be extracted.
+*/
+void ImageReader::ExtractFile(TUint aOffset,TInt aSize,const char* aFileName,const char* aPath,const char* aFilePath,const char* aData) {
+	// concatenate path where specified file needs to be extracted with
+	// path where file is located in the image.
+	string fullPath( aFilePath );
+	if(*aPath != SLASH_CHAR1 && *aPath != SLASH_CHAR2){
+		char ch = aFilePath[fullPath.length() - 1];
+		if(ch != SLASH_CHAR1 && ch != SLASH_CHAR2)
+			fullPath += SLASH_CHAR1 ;		
+	}
+	int startImagePath = (int)fullPath.length();
+	fullPath += aPath ;	 
+	
+	// create specified directory where file needs to be extracted. 
+	// to lower
+	char* data = const_cast<char*>(fullPath.data() + startImagePath);
+	for(; *data != 0 ; data++){
+		if(*data >= 'A' && *data <= 'Z'){
+			*data |= 0x20 ;
+		}
+	}
+	CreateSpecifiedDir(fullPath);
+
+	data -- ;
+	if(*data != SLASH_CHAR1)
+		fullPath += SLASH_CHAR1 ; 
+	
+	// concatenate path information with the filename	
+	fullPath +=  aFileName ;
+
+	// create an output stream to extract the specified file.  
+	ofstream outfile (fullPath.c_str(), ios_base::out | ios_base::binary);
+	// create an input stream by opening the specified image file.
+	ifstream infile(ImageReader::iImgFileName.c_str(),ios_base::in|ios_base::binary);
+
+	//declare a buffer to store the data.
+	char* buffer = new char[aSize];
+
+	if(aData != NULL){
+		memcpy(buffer, aData + aOffset, aSize);
+	}
+	else if(infile.is_open()) {
+		// place the get pointer for the current input stream to offset bytes away from origin.
+		infile.seekg(aOffset,ios_base::beg);
+		//read number of bytes specified by the variable size 
+		//from the stream and place it on to buffer.
+		infile.read(buffer,aSize);
+		//close the input stream after reading.
+		infile.close();
+	}
+	else 	{
+		throw ImageReaderException(ImageReader::iImgFileName.c_str(), "Failed to open the image file");
+	}
+
+	if(outfile.is_open()) {
+		//writes number of bytes specified by the variable size 
+		//from buffer to the current output stream.
+		outfile.write(buffer,aSize);
+		//close the output stream after writing.
+		outfile.close();
+	}
+	else {
+		throw ImageReaderException(aFileName, "Failed to extract the file");
+	}
+
+	//delete the buffer.
+	delete[] buffer;
+}
+ 
+/** 
+Function to create a given directory. 
+
+@internalComponent
+@released
+
+@param aSrcPath - path of the directory that needs to be created. 
+*/
+void ImageReader::CreateSpecifiedDir(const string& aSrcPath) {	 
+	 char* currWorkingDir = new char[PATH_MAX];
+	int len = aSrcPath.length() ;
+	const char* origPath = aSrcPath.c_str();	 
+	char* path = new char[len + 2]; 
+
+	memcpy(path,origPath,len);
+	if(path[len - 1] != SLASH_CHAR1 && path[len - 1] != SLASH_CHAR2){
+		path[len] = SLASH_CHAR1 ;
+		len ++ ;
+	}
+	path[len] = 0; 
+	char* start = path;
+	char* end  = path + len ;
+	char errMsg[400]  ;
+	*errMsg = 0;
+	char* dirEnd ;
+	
+	// get the current working directory and store in buffer.
+	if( getcwd(currWorkingDir,PATH_MAX) == NULL ) {		 
+		// throw an exception if unable to get current working directory information.
+		snprintf(errMsg,400,"Failed to get the current working directory") ;
+		goto L_EXIT;
+	}
+#ifdef WIN32
+//check dir 
+	if(isalpha(start[0]) && start[1] == ':'){
+		char ch = start[3] ;
+		start[3] = 0;
+		if(chdir(start)) {
+			snprintf(errMsg, 400 ,"Failed to change to the directory \"%s\".",path);
+			goto L_EXIT;
+		}
+		start[3] = ch ;
+		start += 3 ;		 
+	}
+	else if(*start == SLASH_CHAR1 || *start == SLASH_CHAR2){
+		if(chdir("\\")){
+			snprintf(errMsg, 400 ,"Failed to change to the directory \"\\\".");
+			goto L_EXIT;
+		}
+		start ++ ;
+	}
+#else
+	if(*start == SLASH_CHAR1 || *start == SLASH_CHAR2){
+		if(chdir("/")) {
+			snprintf(errMsg, 400 ,"Failed to change to the directory \"/\".");
+			goto L_EXIT;
+		}
+		start ++ ;
+	}	
+#endif
+	dirEnd = start ;
+
+	while( start < end ) {		
+		while(*dirEnd != SLASH_CHAR1 && *dirEnd != SLASH_CHAR2)
+			dirEnd ++ ;
+		*dirEnd =  0 ;
+		
+		if(!exists(start)) {  
+			MKDIR(start);
+		}   
+		if(chdir(start)){
+			snprintf(errMsg, 400 ,"Failed to change to the directory \"%s\".",path);
+			goto L_EXIT;
+		}
+		*dirEnd = SLASH_CHAR1;
+		start = dirEnd + 1;
+		dirEnd = start ;		 
+	} 
+L_EXIT:
+	chdir(currWorkingDir);
+	delete[] currWorkingDir;
+	delete [] path;
+	if(*errMsg)
+	 throw ImageReaderException(ImageReader::iImgFileName.c_str(), errMsg); 
+}
+
+ 
+ 
+
+
+/** 
+Function to insert a given string with a delimiter.
+
+@internalComponent
+@released
+
+@param aSrcStr - string to be modified.
+@param aDelimiter - string to be checked.
+@param aAppStr - string to be inserted with the delimiter.
+*/
+void ImageReader::FindAndInsertString(string& aSrcStr,string& aDelimiter,string& aAppStr) {
+	string::size_type loc = 0;
+	string::size_type pos =0;
+	while(( pos = aSrcStr.find( aDelimiter, loc ) ) != ( string::npos ) ) {
+		if( pos != string::npos ) {
+			aSrcStr.insert(pos,aAppStr);
+			loc = pos + aAppStr.length() + 1;
+		}
+	}
+}
+
+/** 
+Function to replace a delimiter with a given string.
+
+@internalComponent
+@released
+
+@param aSrcStr - string to be modified.
+@param aDelimiter - string to be checked.
+@param aReplStr - string to be replaced with the delimiter.
+*/
+void ImageReader::FindAndReplaceString( string& aSrcStr, string& aDelimiter, string& aReplStr ) {
+	string::size_type loc = 0;
+	string::size_type pos =0;
+	while(( pos = aSrcStr.find( aDelimiter,loc) ) != ( string::npos ) ) {
+		if( pos != string::npos ) {
+			aSrcStr.replace( pos, aReplStr.length(),aReplStr );
+			loc = pos + aReplStr.length() + 1;
+		}
+	}
+}
+
+/** 
+Function to extract individual or a subset of file.
+
+@internalComponent
+@released
+
+@param aData - ROM/ROFS image buffer pointer.
+*/
+void ImageReader::ExtractFileSet(const char* aData) {
+	FILEINFOMAP fileInfoMap; 
+	TUint extfileCount = 0, noWcardFlag = 0 ;
+
+	//Get the filelist map
+	GetFileInfo(fileInfoMap);
+
+	//Check for wildcards
+	const char* patternStr = iPattern.c_str();
+	TInt dp = iPattern.length() - 1;
+	while(dp >= 0){
+		if(patternStr[dp] == SLASH_CHAR1 || patternStr[dp] == SLASH_CHAR2)
+			break ;
+		dp -- ;
+	} 
+	size_t pos = iPattern.find_first_of("*?",dp + 1);
+	if(pos == string::npos) 
+		noWcardFlag = 1; 
+
+	//Process the map
+	if(fileInfoMap.size() > 0) {
+		FILEINFOMAP::iterator begin = fileInfoMap.begin();
+		FILEINFOMAP::iterator end = fileInfoMap.end();
+
+		// Replace all backslashes with forward slashes
+		string pat(iPattern);
+		for(size_t n = 0 ; n < iPattern.length(); n++){
+			if(patternStr[n] == SLASH_CHAR2)
+				pat[n] = SLASH_CHAR1 ;
+		}
+	 
+		// Insert root directory at the beginning if it is not there
+		pos = pat.find_first_not_of(" ", 0);
+		if(pos != string::npos) {
+			if(pat.at(pos) != SLASH_CHAR1)
+				pat.insert(pos, 1,SLASH_CHAR1);
+		}
+
+		// Assign CWD for destination path if it is empty
+		if(ImageReader::iZdrivePath.empty())
+			ImageReader::iZdrivePath.assign(".");
+
+		while(begin != end) {
+		 
+			string fileName((*begin).first);
+			PFILEINFO pInfo = (*begin).second;
+
+			// First match
+			int status = FileNameMatch(pat, fileName, (iDisplayOptions & RECURSIVE_FLAG));
+
+			// If no match
+			if((!status) && noWcardFlag) {
+				string newPattern(pat);
+
+				// Add * at the end
+				if(newPattern.at(pat.length()-1) != SLASH_CHAR1) {
+					newPattern += SLASH_CHAR1;
+				}
+				newPattern += "*";
+				status = FileNameMatch(newPattern, fileName, (iDisplayOptions & RECURSIVE_FLAG));
+
+				// If it matches update the pattern and reset wildcard flag
+				if(status) {
+					pat = newPattern;
+					noWcardFlag = 0;
+				}
+			}
+
+			if(status) {
+				// Extract the file
+
+				// Separarate the path and file name
+				int slash_pos = fileName.rfind(SLASH_CHAR1);
+				string fullPath = fileName.substr(0,slash_pos );
+				string file = fileName.substr(slash_pos + 1, fileName.length());
+				//FindAndReplaceString(fullPath, dirSep, backSlash);
+				char* fpStr = const_cast<char*>(fullPath.c_str());
+				for(size_t m = 0 ; m < fullPath.length() ; m++){
+					if(fpStr[m] == SLASH_CHAR2)
+						fpStr[m] = SLASH_CHAR1 ;
+				}
+
+				// Extract only those files exists in the image
+				if(pInfo->iSize && pInfo->iOffset) {
+					ExtractFile(pInfo->iOffset, pInfo->iSize, file.c_str(), fullPath.c_str() , 
+						ImageReader::iZdrivePath.c_str(), aData);
+
+					extfileCount++;
+				}
+			}
+
+			if(pInfo)
+				delete pInfo;
+			++begin;
+		}
+		fileInfoMap.clear();
+	}
+
+	// Throw error if the extracted file count is zero
+	if(!extfileCount) {
+		throw ImageReaderException(ImageReader::iImgFileName.c_str(), "No matching files found for the given pattern");
+	}
+}
+
+/** 
+To match the given file name aganist the given pattern with wildcards
+
+@internalComponent
+@released
+
+@param aPattern - input filename pattern.
+@param aFileName - input file name.
+@param aRecursiveFlag - recursive search flag.
+*/
+int ImageReader::FileNameMatch(const string& aPattern, const string&  aFileName, int aRecursiveFlag) {
+	const char *InputString = aFileName.c_str();
+	const char *Pattern = aPattern.c_str();
+	const char *CurrPattern = 0, *CurrString = 0;
+	
+	// If the input is empty then return false
+	if((aPattern.empty()) || (!InputString))
+		return 0;
+
+	// First candidate match
+	// Step 1: Look for the exact matches between the input pattern and the given file-name till 
+	//         the first occurrence of wildcard character (*). This should also skip a character 
+	//         from matching for the occurrence of wildcard character(?) in the pattern.
+	while ((*InputString) && (*Pattern != '*'))  {
+		if ((toupper(*Pattern) != toupper(*InputString)) && (*Pattern != '?'))  {
+			return 0;
+		}
+		Pattern++;
+		InputString++;
+	}
+	
+	// Wildcard match
+	// Step 2: Now the input string (file-name) should be checked against the wildcard characters (* and ?). 
+	//         Skip the input string if the pattern points to wildcard character(*). Do the exact match for 
+	//         other characters in the patterns except the wildcard character(?). The path-separator should be 
+	//         considered as non-match for non-recursive option.
+	while (*InputString) {
+		if ((*Pattern == '*')) {
+			if (!*++Pattern) {
+				// If recursive flag is set then this case matches for any character of the input string
+				// from the current position
+				if(aRecursiveFlag)
+					return 1;
+			}
+
+			// Update the current pattern and the current inputstring
+			CurrPattern = Pattern;
+			CurrString = InputString+1;			
+		} 
+		else if ((toupper(*Pattern) == toupper(*InputString)) || (*Pattern == '?')) {
+			// Exact match for the path separator
+			// So recursively call the function to look for the exact path level match
+			if(*Pattern == SLASH_CHAR1)
+				return FileNameMatch(Pattern, InputString, aRecursiveFlag);
+
+			// Exact match so increment both
+			Pattern++;
+			InputString++;
+		} 
+		else if ((*InputString == SLASH_CHAR1) && (!aRecursiveFlag)) {
+			// Inputstring points to path separator and it is not expected here for non-recursive case
+			return 0;
+		}
+		else {
+			// Default case where it matches for the wildcard character *
+			Pattern = CurrPattern;
+			InputString = CurrString++;
+		}
+	}
+	
+	// Leave any more stars in the pattern
+	while (*Pattern == '*')  
+		Pattern++; 
+	
+	// Return the status
+	return !*Pattern;
+}
--- a/imgtools/romtools/readimage/src/rofs_image_reader.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/readimage/src/rofs_image_reader.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,616 +1,539 @@
-/*
-* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent 
-* @released
-*
-*/
-
-#include "common.h"
-#include "r_obey.h"
-#include "rofs_image_reader.h"
-#include "e32_image_reader.h"
-
-RofsImage::RofsImage(RCoreImageReader *aReader) : CCoreImage(aReader) ,
-iRofsHeader(0), iRofsExtnHeader(0),iAdjustment(0),  iImageType(RCoreImageReader::E_UNKNOWN)
-{
-}
-
-RofsImageReader::RofsImageReader(char* aFile) : ImageReader(aFile), iInputFile(0)
-{
-	iImageReader = new RCoreImageReader(aFile);
-	iImage = new RofsImage(iImageReader);
-}
-
-RofsImageReader::~RofsImageReader()
-{
-	if(iInputFile)
-		iInputFile->close();
-	delete iInputFile;
-	delete iImage;
-	delete iImageReader;
-}
-
-void RofsImageReader::SetSeek(streampos aOff, ios::seek_dir aStartPos)
-{
-	if(!iInputFile)
-		return;
-
-	iInputFile->seekg(aOff, aStartPos);
-}
-
-void RofsImageReader::ReadImage()
-{
-	if(!iImageReader->Open())
-	{
-		throw ImageReaderException((char*)(iImageReader->Filename()), "Failed to open Image File");
-	}
-}
-
-void RofsImageReader::Validate()
-{
-}
-
-TInt RofsImage::ProcessImage()
-{
-	int result = CreateRootDir();
-	if (result == KErrNone)
-	{
-		if (iReader->Open())
-		{
-			iImageType = iReader->ReadImageType();
-			if (iImageType == RCoreImageReader::E_ROFS)
-			{
-				iRofsHeader = new TRofsHeader;
-				result = iReader->ReadCoreHeader(*iRofsHeader);
-				if (result != KErrNone)
-					return result;
-				
-				SaveDirInfo(*iRofsHeader);
-				result = ProcessDirectory(0);
-			}
-#if defined(__TOOLS2__) || defined(__MSVCDOTNET__)
-			else if (iImageType == RCoreImageReader::E_ROFX)
-#else
-			else if (iImageType == RCoreImageReader::TImageType::E_ROFX)
-#endif
-			{
-				iRofsExtnHeader = new TExtensionRofsHeader ;
-				result = iReader->ReadExtensionHeader(*iRofsExtnHeader);
-				if(result != KErrNone)
-					return result;
-
-				long filePos = iReader->FilePosition();
-				iAdjustment = iRofsExtnHeader->iDirTreeOffset - filePos;
-
-				SaveDirInfo(*iRofsExtnHeader);
-				result = ProcessDirectory(iAdjustment);
-			}
-			else
-			{
-				result = KErrNotSupported;
-			}
-		}
-		else
-		{
-			result = KErrGeneral;
-		}
-	}
-
-	return result;
-}
-
-void RofsImageReader::ProcessImage()
-{
-	iImage->ProcessImage();
-	iRootDirEntry = iImage->RootDirectory();
-}
-
-void RofsImageReader::Dump()
-{
-	if( !((iDisplayOptions & EXTRACT_FILES_FLAG) || (iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG) ||
-		(iDisplayOptions & EXTRACT_FILE_SET_FLAG)) )
-	{
-		
-		MarkNodes();
-		if(iDisplayOptions & DUMP_HDR_FLAG)
-		{
-			DumpHeader();
-		}
-		if( (iDisplayOptions & DUMP_DIR_ENTRIES_FLAG) ||
-			(iDisplayOptions & DUMP_VERBOSE_FLAG) )
-		{
-			DumpDirStructure();
-			DumpFileAttributes();
-		}
-	}
-}
-
-void RofsImageReader::DumpHeader()
-{
-	*out << "Image Name................." << iImgFileName.c_str() << endl;
-
-	int aPos = 0;
-
-	if( ((RofsImage*)iImage)->iImageType == RCoreImageReader::E_ROFS)
-	{
-		*out << "ROFS Image" << endl;
-
-		*out << "Image Signature..........." ;
-		while(aPos < K_ID_SIZE)
-		{
-			*out << ((RofsImage*)iImage)->iRofsHeader->iIdentifier[aPos++];
-		}
-		*out << endl << endl;
-
-		TUint aTotalDirSz = ((RofsImage*)iImage)->iRofsHeader->iDirTreeSize +
-							((RofsImage*)iImage)->iRofsHeader->iDirFileEntriesSize;
-		(*out).width(8);
-
-		*out << "Directory block size: 0x" << hex << ((RofsImage*)iImage)->iRofsHeader->iDirTreeSize << endl;
-		*out <<	"File block size:      0x" << hex << ((RofsImage*)iImage)->iRofsHeader->iDirFileEntriesSize << endl;
-		*out << "Total directory size: 0x" << hex << ( aTotalDirSz ) << endl;
-		*out << "Total image size:     0x" << hex << ((RofsImage*)iImage)->iRofsHeader->iImageSize << endl;
-	}
-	else if(((RofsImage*)iImage)->iImageType == RCoreImageReader::E_ROFX)
-	{
-		*out << "Extension ROFS Image" << endl;
-		*out << "Image Signature..........." ;
-		while(aPos < K_ID_SIZE)
-		{
-			*out << ((RofsImage*)iImage)->iRofsExtnHeader->iIdentifier[aPos++];
-		}
-		*out << endl << endl;
-
-		TUint aTotalDirSz = ((RofsImage*)iImage)->iRofsExtnHeader->iDirTreeSize +
-						((RofsImage*)iImage)->iRofsExtnHeader->iDirFileEntriesSize;
-		out->width(8);
-
-		*out << "Directory block size: 0x" << hex << ((RofsImage*)iImage)->iRofsExtnHeader->iDirTreeSize << endl;
-		*out <<	"File block size:      0x" << hex << ((RofsImage*)iImage)->iRofsExtnHeader->iDirFileEntriesSize << endl;
-		*out << "Total directory size: 0x" << hex << ( aTotalDirSz ) << endl;
-		*out << "Total image size:     0x" << hex << ((RofsImage*)iImage)->iRofsExtnHeader->iImageSize << endl;
-	}
-}
-
-void RofsImageReader::DumpDirStructure()
-{
-	 
-	*out << "Directory Listing" << endl;
-	*out << "=================" << endl; 
-	iImage->Display(out);
-
-}
-
-void RofsImageReader::MarkNodes()
-{
-	TRomNode *aNode = iRootDirEntry->NextNode();
-
-	while( aNode )
-	{
-		if(aNode->iEntry)
-		{
-			if( ReaderUtil::IsExecutable(aNode->iEntry->iUids) )
-			{
-				aNode->iEntry->iExecutable = true;
-			}
-			else
-			{
-				aNode->iEntry->iExecutable = false;
-			}
-		}
-		aNode = aNode->NextNode();
-	}
-}
-
-void RofsImageReader::DumpFileAttributes()
-{
-	TRomNode *aNode = iRootDirEntry->NextNode();
-	E32ImageFile	aE32Img;
-	streampos		aFileOffset;
-	string			iPath;
-	
-	while( aNode )
-	{
-		if( aNode->IsFile() )
-		{
-			if( !iInputFile )
-			{
-				// Open the image file once and to access the E32 images within,#
-				// seek to the file offsets...
-				iInputFile = new ifstream( (char*)(iImageReader->Filename()), ios::binary|ios::in);
-				
-				if(!iInputFile->is_open())
-				{
-					throw ImageReaderException((char*)iImageReader->Filename(), "Failed to open file");
-				}
-			}
-
-			try 
-			{
-				if( aNode->iEntry->iExecutable)
-				{
-					aFileOffset = 0;
-					if( ((RofsImage*)iImage)->iImageType == RCoreImageReader::E_ROFX)
-					{
-						if((TUint)aNode->iEntry->iFileOffset > ((RofsImage*)iImage)->iRofsExtnHeader->iDirTreeOffset)
-						{
-							//This is set only for files within this extended ROFS
-							aFileOffset = aNode->iEntry->iFileOffset - ((RofsImage*)iImage)->iAdjustment;
-						}
-					}
-					else
-					{
-						//This is set only for files within ROFS
-						aFileOffset = aNode->iEntry->iFileOffset;
-					}
-
-					if( aFileOffset )
-					{
-						SetSeek(aFileOffset , ios::beg);
-						memset(&aE32Img, 0, sizeof(aE32Img));
-						aE32Img.Adjust(aNode->iSize);
-						aE32Img.iFileSize = aNode->iSize;
-						if( iInputFile->fail())
-						{
-							// Check why is the fail bit set causing all subsequent
-							// istream operations to fail.
-							// For now, clear the fail bit...
-							iInputFile->clear();
-						}
-						*iInputFile >> aE32Img;
-						if(aE32Img.iError != KErrNone)
-						{
-							throw int (0);
-						}
-					}
-				}
-			}
-			catch(...)
-			{
-				// Just in case this was't a valid E32 image and the E32 reader didn't 
-				// catch it...
-				
-				string aStr("Failed to read contents of ");
-				aStr.append((char*)aNode->iName);
-
-				throw ImageReaderException((char*)iImageReader->Filename(), (char*)aStr.c_str());
-			}
-
-			*out << "********************************************************************" << endl;
-			iPath.assign((char*)aNode->iName);	
-			GetCompleteNodePath(aNode,iPath,"/");
-			*out << "File........................" << iPath.c_str() << endl;
-			if( aNode->iEntry->iExecutable )
-			{
-				if(aFileOffset)
-				{
-					// When its an E32 Image...
-					E32ImageReader::DumpE32Attributes(aE32Img);
-					if( iDisplayOptions & DUMP_E32_IMG_FLAG){
-						if(stricmp(iE32ImgFileName.c_str(), (const char*)aNode->iName) == 0){
-							TUint aSectionOffset = aE32Img.iOrigHdr->iCodeOffset;
-							TUint* aCodeSection = (TUint*)(aE32Img.iData + aSectionOffset);
-							*out << "\nCode (Size=0x" << hex << aE32Img.iOrigHdr->iCodeSize << ")" << endl;
-							DumpData(aCodeSection, aE32Img.iOrigHdr->iCodeSize);
-
-							aSectionOffset = aE32Img.iOrigHdr->iDataOffset;
-							TUint* aDataSection = (TUint*)(aE32Img.iData + aSectionOffset);
-							if( aE32Img.iOrigHdr->iDataSize){
-								*out << "\nData (Size=0x" << hex << aE32Img.iOrigHdr->iDataSize << ")" << endl;
-								DumpData(aDataSection, aE32Img.iOrigHdr->iDataSize);
-							}
-						}
-					}
-				}
-				else
-				{
-					*out << "Image "<< aNode->iName << " not in the extended ROFS " << iImgFileName.c_str() << endl;
-				}
-			}
-		}
-
-		aNode = aNode->NextNode();
-	}
-}
-
-
-/** 
-Function iterates through all the entries in the image.If the entry is a file,
-then it makes a call to GetFileExtension to check for the extension.
-
-@internalComponent
-@released
-*/
-void RofsImageReader::ExtractImageContents()
-{
-	if( (iDisplayOptions & EXTRACT_FILE_SET_FLAG) )
-	{
-		ImageReader::ExtractFileSet(NULL);
-	}
-
-	if( iDisplayOptions & EXTRACT_FILES_FLAG || iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG  )
-	{
-		// get the next Node 
-		TRomNode *nextNode = iRootDirEntry->NextNode();
-		// current Node.
-		TRomNode *currNode = iRootDirEntry;
-		// name of the log file.
-		string  logFile;
-		// output stream for the log file.
-		ofstream oFile;
-
-		if( iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG ){		 
-			if( ImageReader::iZdrivePath.compare("")){
-				// create a string to hold path information.
-				string filePath;
-				string delimiter;
-				delimiter.assign("\\");
-				filePath.assign( ImageReader::iZdrivePath );
-				// replace backslash with double backslash. 
-				FindAndInsertString(filePath,delimiter,delimiter);
-				logFile.assign(filePath);
-				// create specified directory.
-				CreateSpecifiedDir(&filePath[0],"\\\\");
-				logFile.append("\\\\");
-				logFile.append(ImageReader::iLogFileName);
-			}
-			else {				
-				logFile.assign(ImageReader::iLogFileName);
-			}
-
-			// open the specified file in append mode.
-			oFile.open(logFile.c_str(),ios::out|ios::app);
-
-			if(!oFile.is_open()) {
-				throw ImageReaderException((char*)ImageReader::iLogFileName.c_str(), "Failed to open the log file");
-			}
-		}
-
-		while( nextNode ){
-			if(nextNode->IsDirectory())	{
-				// if next node is a directory set current node as next node.
-				currNode = nextNode;
-			}
-			else {
-				// get file extension
-				CheckFileExtension((char*) nextNode->iName,nextNode->iEntry,currNode,oFile);
-			}
-			nextNode = nextNode->NextNode();
-		}
-
-		if(oFile.is_open()) oFile.close(); 
-
-	}
-}
-
-
-/** 
-Function to get check extension of the given file.If the extension of the file is "sis"
-then call ExtractFile function to extract the file from the image.  
-
-@internalComponent
-@released
-
-@param aFile	- file name. 
-@param aEntry	- entry of the file in image.
-@param aNode	- current node.
-@param aLogFile	- output stream.
-*/
-void RofsImageReader::CheckFileExtension(char* aFileName,TRomBuilderEntry* aEntry,TRomNode* aNode,ofstream& aLogFile)
-{
-	//create a string to hold path information.
-	string path;
-	// check whether the node has parent 
-	if(aNode->GetParent())
-	{
-		// get the complete path 
-		path.assign( (char*)aNode->iName );
-		GetCompleteNodePath( aNode, path, "\\\\" );
-	}
-	else
-	{
-		// else path is the current path
-		path.assign("");
-	}
-	if( iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG && iDisplayOptions & EXTRACT_FILES_FLAG )
-	{
-	 
-		size_t pos = string(aFileName).find_last_of(".");
-
-		const char* extName = "";
-		if(pos != string::npos)
-			extName = aFileName + pos + 1;	 
-		if ( 0 == stricmp(extName,"SIS") || 0 == stricmp(extName,"DAT")) {
-			// if the two strings are same then extract the corresponding file.
-			ImageReader::ExtractFile(aEntry->iFileOffset,aEntry->RealFileSize(),aFileName,path.c_str(),&ImageReader::iZdrivePath[0]);
-		}
-		else {
-			// log the entry path information on to the specified file.
-			WriteEntryToFile(aFileName,aNode,aLogFile);
-		}	 
-	}
-	else if( iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG ) {
-		// log the entry path information on to the specified file.
-		WriteEntryToFile(aFileName,aNode,aLogFile);
-	}
-	else {
-		// if the two strings are same then extract the corresponding file.
-		ImageReader::ExtractFile(aEntry->iFileOffset,aEntry->RealFileSize(),aFileName,path.c_str(),&ImageReader::iZdrivePath[0]);
-	}
-}
-
-/** 
-Function to get the complete path information of a file from an image.
-
-@internalComponent
-@released
-
-@param aNode	- starting offset of the file in the image.
-@param aName	- name of the current entry in the image.
-@param aAppStr	- string to append.
-@return - returns full path of the given file.
-*/
-void RofsImageReader::GetCompleteNodePath(TRomNode* aNode,string& aName,char* aAppStr)
-{
-	// check if the entry has a parent.
-	TRomNode* NodeParent = aNode->GetParent();
-	if(NodeParent)
-	{
-		string str( (char*)NodeParent->iName );
-		str.append( aAppStr );
-		str.append( aName );
-		aName = str;
-		GetCompleteNodePath(NodeParent,aName,aAppStr);
-	}
-}
-
-
-/** 
-Function to write the rom entry to an output stream.
-
-@internalComponent
-@released
-
-@param aNode		- starting offset of the file in the image.
-@param aFileName	- name of the current entry in the image.
-@param aLogFile		- output stream.
-*/
-void RofsImageReader::WriteEntryToFile(char* aFileName,TRomNode* aNode,ofstream& aLogFile)
-{
-	//create a string to hold path information.
-	string path;
-	
-	if(aNode->GetParent())
-	{
-		// get the complete path 
-		path.assign( (char*)aNode->iName );
-		GetCompleteNodePath( aNode, path, "\\" );
-	}
-	else
-	{
-		// else path is the current path
-		path.assign("");
-	}
-	
-	if(aLogFile.is_open())
-	{
-		aLogFile.seekp(0,ios::end);
-		aLogFile<<path.c_str()<<"\\"<<aFileName<<"\n";
-	}
-}
-
-/** 
-Function to get the directory structure information.
-
-@internalComponent
-@released
-
-@param aFileMap		- map of filename with its size and offset values.
-*/
-void RofsImageReader::GetFileInfo(FILEINFOMAP &aFileMap)
-{
-	// get the next Node 
-	TRomNode *nextNode = iRootDirEntry->NextNode();
-	// current Node.
-	TRomNode *currNode = iRootDirEntry;
-	// image size
-	TUint32 imgSize = GetImageSize();
-
-	while(nextNode)
-	{
-		if(nextNode->IsDirectory())
-		{
-			// if next node is a directory set current node as next node.
-			currNode = nextNode;
-		}
-		else
-		{
-			PFILEINFO fileInfo = new FILEINFO;
-			//create a string to hold path information.
-			string fileName;
-			TUint32 aFileOffset = 0;
-
-			// check whether the node has parent 
-			if(currNode->GetParent())
-			{
-				if( !((currNode->GetParent() == currNode->FirstNode()) && !(currNode->IsDirectory())) )
-				{
-					// get the complete path 
-					fileName.assign( (char*)currNode->iName );
-					GetCompleteNodePath( currNode, fileName, (char*)DIR_SEPARATOR );
-				}
-			}
-			else
-			{
-				// else path is the current path
-				fileName.assign("");
-			}
-			fileName.append(DIR_SEPARATOR);
-			fileName.append((char*)nextNode->iName);
-
-			// get the size of the entity.
-			fileInfo->iSize = nextNode->iEntry->RealFileSize();
-
-			// get the offset of the entity.
-			if( ((RofsImage*)iImage)->iImageType == RCoreImageReader::E_ROFX)
-			{
-				if((TUint)nextNode->iEntry->iFileOffset > ((RofsImage*)iImage)->iRofsExtnHeader->iDirTreeOffset)
-				{
-					//This is set only for files within this extended ROFS
-					aFileOffset = nextNode->iEntry->iFileOffset - ((RofsImage*)iImage)->iAdjustment;
-				}
-			}
-			else
-			{
-				//This is set only for files within ROFS
-				aFileOffset = nextNode->iEntry->iFileOffset;
-			}
-
-			fileInfo->iOffset = aFileOffset;
-
-			if((!fileInfo->iOffset) || ((fileInfo->iOffset + fileInfo->iSize) > imgSize))
-			{
-				fileInfo->iOffset = 0;
-				fileInfo->iSize = 0;
-			}
-
-			aFileMap[fileName] = fileInfo;
-		}
-
-		nextNode = nextNode->NextNode();
-	}
-}
-
-/** 
-Function to get the ROFS image size.
-
-@internalComponent
-@released
-*/
-TUint32 RofsImageReader::GetImageSize()
-{
-	TUint32 result = 0;
-
-	if( ((RofsImage*)iImage)->iImageType == RCoreImageReader::E_ROFS)
-	{
-		result = ((RofsImage*)iImage)->iRofsHeader->iImageSize;
-	}
-	else if(((RofsImage*)iImage)->iImageType == RCoreImageReader::E_ROFX)
-	{
-		result = ((RofsImage*)iImage)->iRofsExtnHeader->iImageSize;
-	}
-
-	return result;
-}
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent 
+* @released
+*
+*/
+
+#include "common.h"
+#include "r_obey.h"
+#include "rofs_image_reader.h"
+#include "e32_image_reader.h"
+
+RofsImage::RofsImage(RCoreImageReader *aReader) : CCoreImage(aReader) ,
+iRofsHeader(0), iRofsExtnHeader(0),iAdjustment(0),  iImageType(RCoreImageReader::E_UNKNOWN) {
+}
+
+RofsImageReader::RofsImageReader(const char* aFile) : ImageReader(aFile), iInputFile(0) {
+	iImageReader = new RCoreImageReader(aFile);
+	iImage = new RofsImage(iImageReader);
+}
+
+RofsImageReader::~RofsImageReader() {
+	if(iInputFile)
+		iInputFile->close();
+	delete iInputFile;
+	delete iImage;
+	delete iImageReader;
+}
+
+void RofsImageReader::SetSeek(streampos aOff, ios_base::seek_dir aStartPos) {
+	if(!iInputFile)
+		return;
+
+	iInputFile->seekg(aOff, aStartPos);
+}
+
+void RofsImageReader::ReadImage() {
+	if(!iImageReader->Open()) {
+		throw ImageReaderException((iImageReader->Filename()), "Failed to open Image File");
+	}
+}
+
+void RofsImageReader::Validate() {
+}
+
+TInt RofsImage::ProcessImage() {
+	int result = CreateRootDir();
+	if (result == KErrNone) {
+		if (iReader->Open()) {
+			iImageType = iReader->ReadImageType();
+			if (iImageType == RCoreImageReader::E_ROFS) {
+				iRofsHeader = new TRofsHeader;
+				result = iReader->ReadCoreHeader(*iRofsHeader);
+				if (result != KErrNone)
+					return result;
+				
+				SaveDirInfo(*iRofsHeader);
+				result = ProcessDirectory(0);
+			}
+
+			else if (iImageType == RCoreImageReader::E_ROFX) {
+				iRofsExtnHeader = new TExtensionRofsHeader ;
+				result = iReader->ReadExtensionHeader(*iRofsExtnHeader);
+				if(result != KErrNone)
+					return result;
+
+				long filePos = iReader->FilePosition();
+				iAdjustment = iRofsExtnHeader->iDirTreeOffset - filePos;
+
+				SaveDirInfo(*iRofsExtnHeader);
+				result = ProcessDirectory(iAdjustment);
+			}
+			else {
+				result = KErrNotSupported;
+			}
+		}
+		else {
+			result = KErrGeneral;
+		}
+	}
+
+	return result;
+}
+
+void RofsImageReader::ProcessImage() {
+	iImage->ProcessImage();
+	iRootDirEntry = iImage->RootDirectory();
+}
+
+void RofsImageReader::Dump() {
+	if( !((iDisplayOptions & EXTRACT_FILES_FLAG) || (iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG) ||
+		(iDisplayOptions & EXTRACT_FILE_SET_FLAG)) ) {
+		
+		MarkNodes();
+		if(iDisplayOptions & DUMP_HDR_FLAG) {
+			DumpHeader();
+		}
+		if( (iDisplayOptions & DUMP_DIR_ENTRIES_FLAG) ||
+			(iDisplayOptions & DUMP_VERBOSE_FLAG) ) {
+			DumpDirStructure();
+			DumpFileAttributes();
+		}
+	}
+}
+
+void RofsImageReader::DumpHeader() {
+	*out << "Image Name................." << iImgFileName.c_str() << endl;
+
+	int aPos = 0;
+
+	if( ((RofsImage*)iImage)->iImageType == RCoreImageReader::E_ROFS) {
+		*out << "ROFS Image" << endl;
+
+		*out << "Image Signature..........." ;
+		while(aPos < K_ID_SIZE) {
+			*out << ((RofsImage*)iImage)->iRofsHeader->iIdentifier[aPos++];
+		}
+		*out << endl << endl;
+
+		TUint aTotalDirSz = ((RofsImage*)iImage)->iRofsHeader->iDirTreeSize +
+							((RofsImage*)iImage)->iRofsHeader->iDirFileEntriesSize;
+		(*out).width(8);
+
+		*out << "Directory block size: 0x" << hex << ((RofsImage*)iImage)->iRofsHeader->iDirTreeSize << endl;
+		*out <<	"File block size:      0x" << hex << ((RofsImage*)iImage)->iRofsHeader->iDirFileEntriesSize << endl;
+		*out << "Total directory size: 0x" << hex << ( aTotalDirSz ) << endl;
+		*out << "Total image size:     0x" << hex << ((RofsImage*)iImage)->iRofsHeader->iImageSize << endl;
+	}
+	else if(((RofsImage*)iImage)->iImageType == RCoreImageReader::E_ROFX) {
+		*out << "Extension ROFS Image" << endl;
+		*out << "Image Signature..........." ;
+		while(aPos < K_ID_SIZE) {
+			*out << ((RofsImage*)iImage)->iRofsExtnHeader->iIdentifier[aPos++];
+		}
+		*out << endl << endl;
+
+		TUint aTotalDirSz = ((RofsImage*)iImage)->iRofsExtnHeader->iDirTreeSize +
+						((RofsImage*)iImage)->iRofsExtnHeader->iDirFileEntriesSize;
+		out->width(8);
+
+		*out << "Directory block size: 0x" << hex << ((RofsImage*)iImage)->iRofsExtnHeader->iDirTreeSize << endl;
+		*out <<	"File block size:      0x" << hex << ((RofsImage*)iImage)->iRofsExtnHeader->iDirFileEntriesSize << endl;
+		*out << "Total directory size: 0x" << hex << ( aTotalDirSz ) << endl;
+		*out << "Total image size:     0x" << hex << ((RofsImage*)iImage)->iRofsExtnHeader->iImageSize << endl;
+	}
+}
+
+void RofsImageReader::DumpDirStructure() {
+	 
+	*out << "Directory Listing" << endl;
+	*out << "=================" << endl; 
+	iImage->Display(out);
+
+}
+
+void RofsImageReader::MarkNodes() {
+	TRomNode *aNode = iRootDirEntry->NextNode();
+
+	while( aNode ) {
+		if(aNode->iEntry) {
+			if( ReaderUtil::IsExecutable(aNode->iEntry->iUids) ) {
+				aNode->iEntry->iExecutable = true;
+			}
+			else {
+				aNode->iEntry->iExecutable = false;
+			}
+		}
+		aNode = aNode->NextNode();
+	}
+}
+
+void RofsImageReader::DumpFileAttributes() {
+	TRomNode *aNode = iRootDirEntry->NextNode();
+	E32ImageFile	aE32Img;
+	size_t		aFileOffset;
+	std::string			iPath;
+	
+	while( aNode ) {
+		if( aNode->IsFile() ) {
+			if( !iInputFile ) {
+				// Open the image file once and to access the E32 images within,#
+				// seek to the file offsets...
+				iInputFile = new ifstream( (iImageReader->Filename()), ios_base::binary|ios_base::in);
+				
+				if(!iInputFile->is_open()) {
+					throw ImageReaderException(iImageReader->Filename(), "Failed to open file");
+				}
+			}
+
+			try  {
+				if( aNode->iEntry->iExecutable) {
+					aFileOffset = 0;
+					if( ((RofsImage*)iImage)->iImageType == RCoreImageReader::E_ROFX) {
+						if((TUint)aNode->iEntry->iFileOffset > ((RofsImage*)iImage)->iRofsExtnHeader->iDirTreeOffset) {
+							//This is set only for files within this extended ROFS
+							aFileOffset = aNode->iEntry->iFileOffset - ((RofsImage*)iImage)->iAdjustment;
+						}
+					}
+					else {
+						//This is set only for files within ROFS
+						aFileOffset = aNode->iEntry->iFileOffset;
+					}
+
+					if( aFileOffset ) {
+						SetSeek(aFileOffset , ios_base::beg);
+						memset(&aE32Img, 0, sizeof(aE32Img));
+						aE32Img.Adjust(aNode->iSize);
+						aE32Img.iFileSize = aNode->iSize;
+						if( iInputFile->fail()) {
+							// Check why is the fail bit set causing all subsequent
+							// istream operations to fail.
+							// For now, clear the fail bit...
+							iInputFile->clear();
+						}
+						*iInputFile >> aE32Img;
+						if(aE32Img.iError != KErrNone) {
+							throw int (0);
+						}
+					}
+				}
+			}
+			catch(...) {
+				// Just in case this was't a valid E32 image and the E32 reader didn't 
+				// catch it...
+				
+				string aStr("Failed to read contents of ");
+				aStr.append(aNode->iName);
+
+				throw ImageReaderException(iImageReader->Filename(), aStr.c_str());
+			}
+
+			*out << "********************************************************************" << endl;
+			//iPath.assign(aNode->iName);	
+			GetCompleteNodePath(aNode,iPath);
+			*out << "File........................" << iPath.c_str() << endl;
+			if( aNode->iEntry->iExecutable ) {
+				if(aFileOffset) {
+					// When its an E32 Image...
+					E32ImageReader::DumpE32Attributes(aE32Img);
+					if( iDisplayOptions & DUMP_E32_IMG_FLAG){
+						if(stricmp(iE32ImgFileName.c_str(), (const char*)aNode->iName) == 0){
+							TUint aSectionOffset = aE32Img.iOrigHdr->iCodeOffset;
+							TUint* aCodeSection = (TUint*)(aE32Img.iData + aSectionOffset);
+							*out << "\nCode (Size=0x" << hex << aE32Img.iOrigHdr->iCodeSize << ")" << endl;
+							DumpData(aCodeSection, aE32Img.iOrigHdr->iCodeSize);
+
+							aSectionOffset = aE32Img.iOrigHdr->iDataOffset;
+							TUint* aDataSection = (TUint*)(aE32Img.iData + aSectionOffset);
+							if( aE32Img.iOrigHdr->iDataSize){
+								*out << "\nData (Size=0x" << hex << aE32Img.iOrigHdr->iDataSize << ")" << endl;
+								DumpData(aDataSection, aE32Img.iOrigHdr->iDataSize);
+							}
+						}
+					}
+				}
+				else {
+					*out << "Image "<< aNode->iName << " not in the extended ROFS " << iImgFileName.c_str() << endl;
+				}
+			}
+		}
+
+		aNode = aNode->NextNode();
+	}
+}
+
+
+/** 
+Function iterates through all the entries in the image.If the entry is a file,
+then it makes a call to GetFileExtension to check for the extension.
+
+@internalComponent
+@released
+*/
+void RofsImageReader::ExtractImageContents() {
+	if( (iDisplayOptions & EXTRACT_FILE_SET_FLAG) ) {
+		ImageReader::ExtractFileSet(NULL);
+	}
+
+	if( iDisplayOptions & EXTRACT_FILES_FLAG || iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG  ) {
+		// get the next Node 
+		TRomNode *nextNode = iRootDirEntry->NextNode();
+		// current Node.
+		TRomNode *currNode = iRootDirEntry;
+		// name of the log file.
+		string  logFile;
+		// output stream for the log file.
+		ofstream oFile;
+
+		if( iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG ){		 
+			if( ImageReader::iZdrivePath.compare("")){
+				// create specified directory.
+				CreateSpecifiedDir(ImageReader::iZdrivePath); 
+				int len = ImageReader::iZdrivePath.length() ;
+				const char* z = ImageReader::iZdrivePath.c_str();
+				logFile = "";
+				for(int i = 0 ; i < len ; i++){
+					if(z[i] == SLASH_CHAR2)
+						logFile += SLASH_CHAR1;
+					else
+						logFile += z[i];
+				}
+				len -- ;
+				if(z[len] != SLASH_CHAR1)
+					logFile += SLASH_CHAR1;
+				logFile += ImageReader::iLogFileName ;
+			}
+			else {				
+				logFile.assign(ImageReader::iLogFileName);
+			}
+
+			// open the specified file in append mode.
+			oFile.open(logFile.c_str(),ios_base::out|ios_base::app);
+
+			if(!oFile.is_open()) {
+				throw ImageReaderException(ImageReader::iLogFileName.c_str(), "Failed to open the log file");
+			}
+		}
+
+		while( nextNode ){
+			if(nextNode->IsDirectory())	{
+				// if next node is a directory set current node as next node.
+				currNode = nextNode;
+			}
+			else {
+				// get file extension
+				CheckFileExtension( nextNode->iName,nextNode->iEntry,currNode,oFile);
+			}
+			nextNode = nextNode->NextNode();
+		}
+
+		if(oFile.is_open()) oFile.close(); 
+
+	}
+}
+
+
+/** 
+Function to get check extension of the given file.If the extension of the file is "sis"
+then call ExtractFile function to extract the file from the image.  
+
+@internalComponent
+@released
+
+@param aFile	- file name. 
+@param aEntry	- entry of the file in image.
+@param aNode	- current node.
+@param aLogFile	- output stream.
+*/
+void RofsImageReader::CheckFileExtension(const char* aFileName,TRomBuilderEntry* aEntry,TRomNode* aNode,ofstream& aLogFile) {
+	//create a string to hold path information.
+	string path;
+	// check whether the node has parent 
+	if(aNode->GetParent()) {
+		// get the complete path  
+		GetCompleteNodePath( aNode, path );
+	}
+	else {
+		// else path is the current path
+		path.assign("");
+	}
+	if( iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG && iDisplayOptions & EXTRACT_FILES_FLAG ) {
+	 
+		const char* extName = strrchr(aFileName ,'.');	  
+		if ( extName && (0 == stricmp(extName,".SIS") || 0 == stricmp(extName,".DAT"))) {
+			// if the two strings are same then extract the corresponding file.
+			ImageReader::ExtractFile(aEntry->iFileOffset,aEntry->RealFileSize(),aFileName,path.c_str(),ImageReader::iZdrivePath.c_str());
+		}
+		else {
+			// log the entry path information on to the specified file.
+			WriteEntryToFile(aFileName,aNode,aLogFile);
+		}	 
+	}
+	else if( iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG ) {
+		// log the entry path information on to the specified file.
+		WriteEntryToFile(aFileName,aNode,aLogFile);
+	}
+	else {
+		// if the two strings are same then extract the corresponding file.
+		ImageReader::ExtractFile(aEntry->iFileOffset,aEntry->RealFileSize(),aFileName,path.c_str(),ImageReader::iZdrivePath.c_str());
+	}
+}
+
+/** 
+Function to get the complete path information of a file from an image.
+
+@internalComponent
+@released
+
+@param aNode	- starting offset of the file in the image.
+@param aName	- name of the current entry in the image.
+@param aAppStr	- string to append.
+@return - returns full path of the given file.
+*/
+void RofsImageReader::GetCompleteNodePath(TRomNode* aNode,string& aName) {
+	// check if the entry has a parent.
+	 
+	aName = "";
+	while(aNode) {
+		aName.insert(0,aNode->iName);		
+		aNode = aNode->GetParent();
+		if(aNode)
+			aName.insert((size_t)0,(size_t)1,SLASH_CHAR1);
+	}
+}
+
+
+/** 
+Function to write the rom entry to an output stream.
+
+@internalComponent
+@released
+
+@param aNode		- starting offset of the file in the image.
+@param aFileName	- name of the current entry in the image.
+@param aLogFile		- output stream.
+*/
+void RofsImageReader::WriteEntryToFile(const char* aFileName,TRomNode* aNode,ofstream& aLogFile) {
+	//create a string to hold path information.
+	string path("");
+	
+	if(aNode->GetParent()) {
+		// get the complete path 
+		GetCompleteNodePath( aNode, path);
+		
+	}
+	else {
+		// else path is the current path
+		path.assign("");
+	}
+	
+	if(aLogFile.is_open()) {
+		aLogFile.seekp(0,ios_base::end);
+		aLogFile<<path.c_str()<<SLASH_CHAR1<<aFileName<< endl;
+	}
+}
+
+/** 
+Function to get the directory structure information.
+
+@internalComponent
+@released
+
+@param aFileMap		- map of filename with its size and offset values.
+*/
+void RofsImageReader::GetFileInfo(FILEINFOMAP &aFileMap) {
+	// get the next Node 
+	TRomNode *nextNode = iRootDirEntry->NextNode();
+	// current Node.
+	TRomNode *currNode = iRootDirEntry;
+	// image size
+	TUint32 imgSize = GetImageSize();
+
+	while(nextNode) {
+		if(nextNode->IsDirectory()) {
+			// if next node is a directory set current node as next node.
+			currNode = nextNode;
+		}
+		else {
+			PFILEINFO fileInfo = new FILEINFO;
+			//create a string to hold path information.
+			string fileName;
+			TUint32 aFileOffset = 0;
+
+			// check whether the node has parent 
+			if(currNode->GetParent()) {
+				if( !((currNode->GetParent() == currNode->FirstNode()) && !(currNode->IsDirectory())) ) {
+					// get the complete path 
+					 
+					GetCompleteNodePath( currNode, fileName );
+					fileName += SLASH_CHAR1;
+					fileName.append(nextNode->iName);
+				}
+			}
+			else {
+				// else path is the current path
+				fileName.assign(nextNode->iName);
+			}
+			
+			
+
+			// get the size of the entity.
+			fileInfo->iSize = nextNode->iEntry->RealFileSize();
+
+			// get the offset of the entity.
+			if( ((RofsImage*)iImage)->iImageType == RCoreImageReader::E_ROFX) {
+				if((TUint)nextNode->iEntry->iFileOffset > ((RofsImage*)iImage)->iRofsExtnHeader->iDirTreeOffset) {
+					//This is set only for files within this extended ROFS
+					aFileOffset = nextNode->iEntry->iFileOffset - ((RofsImage*)iImage)->iAdjustment;
+				}
+			}
+			else {
+				//This is set only for files within ROFS
+				aFileOffset = nextNode->iEntry->iFileOffset;
+			}
+
+			fileInfo->iOffset = aFileOffset;
+
+			if((!fileInfo->iOffset) || ((fileInfo->iOffset + fileInfo->iSize) > imgSize)) {
+				fileInfo->iOffset = 0;
+				fileInfo->iSize = 0;
+			}
+
+			aFileMap[fileName] = fileInfo;
+		}
+
+		nextNode = nextNode->NextNode();
+	}
+}
+
+/** 
+Function to get the ROFS image size.
+
+@internalComponent
+@released
+*/
+TUint32 RofsImageReader::GetImageSize() {
+	TUint32 result = 0;
+
+	if( ((RofsImage*)iImage)->iImageType == RCoreImageReader::E_ROFS) {
+		result = ((RofsImage*)iImage)->iRofsHeader->iImageSize;
+	}
+	else if(((RofsImage*)iImage)->iImageType == RCoreImageReader::E_ROFX) {
+		result = ((RofsImage*)iImage)->iRofsExtnHeader->iImageSize;
+	}
+
+	return result;
+}
--- a/imgtools/romtools/readimage/src/rom_image_reader.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/readimage/src/rom_image_reader.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,953 +1,913 @@
-/*
-* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent 
-* @released
-*
-*/
-
-#include <e32rom.h>
-#include "rom_image_reader.h"
-#include "r_rom.h"
-
-void InflateUnCompress(unsigned char* source, int sourcesize, unsigned char* dest, int destsize);
-RomImageFSEntry::RomImageFSEntry (const char* aName) : iName(aName), iSibling(0), iChildren(0) {
-}
-RomImageFSEntry::~RomImageFSEntry() {
-	if(iChildren){
-		delete iChildren;
-		iChildren = NULL ;
-	}
-	if(iSibling){
-		delete iSibling ;
-		iSibling = NULL ;
-	}	
-}
-
-//Rom Image header 
-RomImageHeader::RomImageHeader(char* aHdr, EImageType aImgType)
-{
-	switch( aImgType)
-	{
-	case EROM_IMAGE:
-		iLoaderHdr = (TRomLoaderHeader*)aHdr;
-		iRomHdr = (TRomHeader*)(aHdr + sizeof(TRomLoaderHeader));
-		iExtRomHdr = 0;
-		break;
-
-	case EROMX_IMAGE:
-		iExtRomHdr = (TExtensionRomHeader*)(aHdr);
-		iRomHdr = 0;
-		iLoaderHdr = 0;
-		break;
-        
-    case EBAREROM_IMAGE:
-        iLoaderHdr = 0;
-        iRomHdr = (TRomHeader*)aHdr;
-        iExtRomHdr = 0;
-        break;
-   default:
-   		iExtRomHdr = 0;
-		iRomHdr = 0;
-		iLoaderHdr = 0;
-   	break ;
-	}
-}
-
-
-void RomImageHeader::DumpRomHdr()
-{
-    if(iLoaderHdr)
-        *out << "ROM Image " << endl << endl;
-    else
-        *out << "Bare ROM Image" << endl << endl;
-	TUint aPos = 0;
-	bool aContinue = true;
-	
-	*out << "Image Signature .................";
-
-    if(iLoaderHdr){
-        TText *aRomName =  reinterpret_cast<TText *>(iLoaderHdr) ;
-        while (aPos < KRomNameSize) {
-            *out << (char)aRomName[aPos++];
-        }
-    }
-
-	*out << endl << endl;
-
-	DumpInHex("Timestamp", (iRomHdr->iTime >> 32)) ;
-	DumpInHex(" ", (iRomHdr->iTime &0xffffffff), aContinue) << endl;
-
-	DumpInHex("RomBase", iRomHdr->iRomBase) << endl;
-
-	DumpInHex("RomSize", iRomHdr->iRomSize) << endl;
-	DumpInHex("KernelDataAddress", iRomHdr->iKernDataAddress) << endl;
-	DumpInHex("KernelLimit", iRomHdr->iKernelLimit) << endl;
-	DumpInHex("PrimaryFile", iRomHdr->iPrimaryFile) << endl;
-	DumpInHex("SecondaryFile", iRomHdr->iSecondaryFile) << endl;
-	DumpInHex("CheckSum", iRomHdr->iCheckSum) << endl;
-	DumpInHex("Hardware", iRomHdr->iHardware) << endl;
-
-	DumpInHex("Language", (TUint)(iRomHdr->iLanguage >> 32));
-	DumpInHex(" ", ((TUint)(iRomHdr->iLanguage & 0xffffffff)), aContinue) <<endl;
-
-	DumpInHex("KernelConfigFlags", iRomHdr->iKernelConfigFlags) << endl;
-	DumpInHex("RomExceptionSearchTable", iRomHdr->iRomExceptionSearchTable) << endl;
-	DumpInHex("RomHeaderSize", iRomHdr->iRomHeaderSize) << endl;
-	DumpInHex("RomSectionHeader", iRomHdr->iRomSectionHeader) << endl;
-	DumpInHex("TotalSvDataSize", iRomHdr->iTotalSvDataSize) << endl;
-	DumpInHex("VariantFile", iRomHdr->iVariantFile) << endl;
-	DumpInHex("ExtensionFile", iRomHdr->iExtensionFile) << endl;
-	DumpInHex("RelocInfo", iRomHdr->iRelocInfo) << endl;
-	DumpInHex("OldTraceMask", iRomHdr->iOldTraceMask) << endl;
-	DumpInHex("UserDataAddress", iRomHdr->iUserDataAddress) << endl;
-	DumpInHex("TotalUserDataSize", iRomHdr->iTotalUserDataSize) << endl;
-	DumpInHex("DebugPort", iRomHdr->iDebugPort) << endl;
-	
-	DumpInHex("Version", iRomHdr->iVersion.iMajor, false, 2);
-	DumpInHex(".", iRomHdr->iVersion.iMinor, aContinue, 2);
-	DumpInHex("(" ,iRomHdr->iVersion.iBuild, aContinue, 2);
-	*out << ")" << endl;
-
-	DumpInHex("CompressionType", iRomHdr->iCompressionType) << endl;
-	DumpInHex("CompressedSize", iRomHdr->iCompressedSize) << endl;
-	DumpInHex("UncompressedSize", iRomHdr->iUncompressedSize) << endl;
-	DumpInHex("HcrFileAddress", iRomHdr->iHcrFileAddress) << endl;
-	
-	DumpInHex("DisabledCapabilities", iRomHdr->iDisabledCapabilities[0]);
-	DumpInHex(" ", iRomHdr->iDisabledCapabilities[1], aContinue) << endl;
-
-	DumpInHex("TraceMask", iRomHdr->iTraceMask[0]);
-	aPos = 1;
-	while( aPos < (TUint)KNumTraceMaskWords)
-	{
-		if(iRomHdr->iTraceMask[aPos])
-		{
-			DumpInHex(" ", iRomHdr->iTraceMask[aPos++], aContinue);
-		}
-		else
-		{
-			DumpInHex(" ", iRomHdr->iTraceMask[aPos++], aContinue, 1);
-		}
-
-	}
-
-	*out << endl << endl;
-
-}
-void RomImageHeader::DumpRomXHdr()
-{
-	*out << "Extension ROM Image" << endl << endl;
-	bool aContinue = true;
-	
-	DumpInHex("Timestamp", (iExtRomHdr->iTime >> 32)) ;
-	DumpInHex(" ", (iExtRomHdr->iTime &0xffffffff), aContinue) << endl;
-
-	DumpInHex("RomBase", iExtRomHdr->iRomBase) << endl;
-
-	DumpInHex("RomSize", iExtRomHdr->iRomSize) << endl;
-	DumpInHex("CheckSum", iExtRomHdr->iCheckSum) << endl;
-	
-	DumpInHex("Version", iExtRomHdr->iVersion.iMajor, false, 2);
-	DumpInHex(".", iExtRomHdr->iVersion.iMinor, aContinue, 2);
-	DumpInHex("(" ,iExtRomHdr->iVersion.iBuild, aContinue, 2);
-	*out << ")" << endl;
-
-	DumpInHex("CompressionType", iExtRomHdr->iCompressionType) << endl;
-	DumpInHex("CompressedSize", iExtRomHdr->iCompressedSize) << endl;
-	DumpInHex("UncompressedSize", iExtRomHdr->iUncompressedSize) << endl;
-	
-	*out << endl << endl;
-
-}
-//Rom Image reader
-RomImageReader::RomImageReader(const char* aFile, EImageType aImgType) :
-ImageReader(aFile), iImageHeader(0),
-iRomSize(0),iHeaderBuffer(0),
-iRomLayoutData(0),iImgType(aImgType)
-{
-	iRomImageRootDirEntry = new RomImageDirEntry("");
-}
-
-RomImageReader::~RomImageReader()
-{
-	if(iFile.is_open())
-		iFile.close();
-	if(iHeaderBuffer)
-		delete []iHeaderBuffer;
-	if(iRomLayoutData)
-		delete []iRomLayoutData;  
-	delete iRomImageRootDirEntry;
-
-	
-}
-
-void RomImageReader::ReadImage()
-{
-	if(iFile.is_open()) return ;
-	iFile.open(iImgFileName.c_str(), ios::binary | ios::in);
-	if( !iFile.is_open() ) {
-		throw ImageReaderException(iImgFileName.c_str(), "Cannot open file ");
-	}	
-	
-	TUint headerSize = GetHdrSize() ;	
-	if(headerSize > 0){
-		iHeaderBuffer = new char[headerSize];
-		iFile.read(iHeaderBuffer,headerSize);
-	}	
-}
- 
-void RomImageReader::Validate()
-{
-}
-
-TUint32 RomImageReader::GetImageCompressionType()
-{
-	if(iImageHeader->iRomHdr )// iImageType == EROM_IMAGE
-		return iImageHeader->iRomHdr->iCompressionType;
-	else
-		return iImageHeader->iExtRomHdr->iCompressionType;
-}
-
- 
-TLinAddr RomImageReader::GetRomBase()
-{
-	if(iImageHeader->iRomHdr )// iImageType == EROM_IMAGE
-		return iImageHeader->iRomHdr->iRomBase ;
-	else
-		return iImageHeader->iExtRomHdr->iRomBase;
-}
-
-TLinAddr RomImageReader::GetRootDirList()
-{
-	if(iImageHeader->iRomHdr )// iImageType == EROM_IMAGE
-		return iImageHeader->iRomHdr->iRomRootDirectoryList;
-	else
-		return iImageHeader->iExtRomHdr->iRomRootDirectoryList;
-}
-
-TUint RomImageReader::GetHdrSize()
-{
-	TUint headerSize = 0;
-	if(EROM_IMAGE == iImgType){
-		headerSize = sizeof(TRomLoaderHeader) + sizeof(TRomHeader);
-	}else if(EROMX_IMAGE == iImgType){
-		headerSize = sizeof(TExtensionRomHeader);
-	}else if(EBAREROM_IMAGE == iImgType){
-		headerSize = sizeof(TRomHeader);
-	}
-	return headerSize;
-}
- 
- 
-static const TInt KIOBytes = 0x100000;
-// reading a huge buffer at a time is very slow, reading 1MB bytes at a time is much faster
-void RomImageReader::ReadData(char* aBuffer, TUint aLength)
-{
-	TUint readBytes = 0 ;
-	while(readBytes < aLength){
-		TUint toRead = KIOBytes;
-		if(readBytes + toRead > aLength)
-			toRead = aLength - readBytes ;
-		iFile.read(&aBuffer[readBytes],toRead);
-		readBytes += toRead ;
-	}	
-}
-void RomImageReader::ProcessImage()
-{
-	if(iRomLayoutData) return ;
-	iImageHeader = new RomImageHeader(iHeaderBuffer, iImgType);
-
-	iFile.seekg(0, ios::end);
-	// fileSize
-	TUint fileSize = iFile.tellg(); 
-
-	//let's skip the RomLoaderHeader
-	TUint romDataBegin = (EROM_IMAGE == iImgType) ? sizeof(TRomLoaderHeader) : 0 ; 
-	iFile.seekg(romDataBegin,ios::beg);	
-
-	if(EROMX_IMAGE == iImgType){// EROMX_IMAGE, just set the iUnpagedRomBuffer		
-		if(GetImageCompressionType() == KUidCompressionDeflate){
-			TUint32 readLen = fileSize - sizeof(TExtensionRomHeader) ; 
-			iRomSize = iImageHeader->iExtRomHdr->iUncompressedSize ;	 
-			iRomLayoutData = new char[iRomSize];
-			char* temp = new char[readLen];
-			// header is not compressed.
-			iFile.read(iRomLayoutData,sizeof(TExtensionRomHeader)); 
-			ReadData(temp ,readLen);
-			TUint8* uncompressDest = reinterpret_cast<TUint8*>(iRomLayoutData + sizeof(TExtensionRomHeader));
-			InflateUnCompress(reinterpret_cast<TUint8*>(temp),readLen,uncompressDest,iRomSize - sizeof(TExtensionRomHeader));
-			delete []temp ;	 
-			
-		}else{
-			iRomSize = fileSize  ;
-			iRomLayoutData = new char[iRomSize]; 
-			ReadData(iRomLayoutData,iRomSize);
-		}	 
-	} // end EROMX_IMAGE
-	else {
-		 //EROM_IMAGE or EBAREROM_IMAGE
-		const TInt KPageSize = 0x1000; 
-		TRomHeader *hdr = iImageHeader->iRomHdr; 
-		iRomSize = hdr->iUncompressedSize ; 
-		iRomLayoutData = new char[iRomSize]; 
-		char* curDataPointer = iRomLayoutData ;
-		TUint totalReadBytes = 0;
-		bool hasPageableSec = (hdr->iPageableRomStart > 0 && hdr->iPageableRomSize > 0) ;
-		
-		// read data before unpaged 
-		ReadData(curDataPointer,hdr->iCompressedUnpagedStart); 
-		curDataPointer += hdr->iCompressedUnpagedStart ; 
-		totalReadBytes += hdr->iCompressedUnpagedStart;		
-
-		// read the unpaged part, if compressed , then decompress		 
-		if(GetImageCompressionType() == KUidCompressionDeflate){
-			char* temp = new char[hdr->iUnpagedCompressedSize];
-			ReadData(temp,hdr->iUnpagedCompressedSize);
-			totalReadBytes += hdr->iUnpagedCompressedSize;
-			InflateUnCompress(reinterpret_cast<TUint8*>(temp),hdr->iUnpagedCompressedSize,reinterpret_cast<TUint8*>(curDataPointer) ,hdr->iUnpagedUncompressedSize);
-			delete []temp ;			
-		}else{
-			TUint unpagedSeclen ;
-			if(hasPageableSec) { // there is paged section 
-				unpagedSeclen = hdr->iPageableRomStart - hdr->iCompressedUnpagedStart;
-			}else{
-				unpagedSeclen = iRomSize - hdr->iCompressedUnpagedStart;
-			}
-			ReadData(curDataPointer,unpagedSeclen);			 
-			totalReadBytes += unpagedSeclen ;
-		}
-		curDataPointer = iRomLayoutData + totalReadBytes; 
-		//if there is a paged section , read and extract it 
-
-		// read the paged section,
-		if(hasPageableSec){		
-			if((TUint)(hdr->iPageableRomStart + hdr->iPageableRomSize) > iRomSize){
-					throw ImageReaderException("Incorrect values of ROM header fields.", "");
-			}
-			if(0 == hdr->iRomPageIndex){ //
-				// no compression for paged section ,just read it 			 
-				iFile.read(curDataPointer,iRomSize - totalReadBytes);
-			}
-			else{
-				//aligment calculation
-				TUint pagedSecOffset = (totalReadBytes + KPageSize - 1) & (~(KPageSize - 1));
-				if(pagedSecOffset > totalReadBytes){
-					// there are gap bytes between unpaged and paged sections
-					iFile.read(curDataPointer,pagedSecOffset - totalReadBytes);
-					curDataPointer = iRomLayoutData + pagedSecOffset;
-				}
-				TUint pagedIndexCount = ( hdr->iUncompressedSize + KPageSize - 1) / KPageSize;
-				// how many bytes ?
-				// the page index table include the unpaged part ;
-				TUint firstPagedIndexTblItem = hdr->iPageableRomStart / KPageSize;
-			 
-				TUint tempBufLen = KPageSize << 8;
-				char* readBuffer = new char[tempBufLen]; 
-			 
-				TUint8* src,*srcNext = NULL;
-				SRomPageInfo* pageInfo = reinterpret_cast<SRomPageInfo*>(&iRomLayoutData[hdr->iRomPageIndex]);
-				CBytePair bp(EFalse);
-				for(TUint i = firstPagedIndexTblItem ; i < pagedIndexCount ; i+= 256){
-					TUint endIndex = i + 255 ;
-					if(endIndex >= pagedIndexCount)
-						endIndex = pagedIndexCount - 1;
-					TUint readLen = pageInfo[endIndex].iDataStart + pageInfo[endIndex].iDataSize - pageInfo[i].iDataStart ; 
-					iFile.read(readBuffer,readLen);
-					src = reinterpret_cast<TUint8*>(readBuffer);
-					for(TUint j = i ; j <= endIndex ; j++){
-						switch(pageInfo[j].iCompressionType)
-						{
-						case SRomPageInfo::EBytePair:
-							{
-							TInt unpacked = bp.Decompress(reinterpret_cast<TUint8*>(curDataPointer), KPageSize, src, pageInfo[j].iDataSize, srcNext);
-							if (unpacked < 0) {
-								delete []readBuffer;
-								throw ImageReaderException("Corrupted BytePair compressed ROM image", "");
-							}
-							curDataPointer += unpacked;
-							break ;
-							}
-						case SRomPageInfo::ENoCompression:
-							memcpy(curDataPointer,src,pageInfo[j].iDataSize);
-							curDataPointer +=  pageInfo[j].iDataSize ;
-							break ;
-						default:
-							delete []readBuffer;
-							throw ImageReaderException("Undefined compression type", "");
-							break ;
-						
-						}
-						src += pageInfo[j].iDataSize; 
-					} // end for(TUint j = i ; j <= endIndex ; j++) 
-				} // end for(TUint i = firstPagedIndexTblItem ; i < pagedIndexCount ; i+= 256) 
-				delete []readBuffer ;
-			}// else
-			 
-		} // if(hasPageableSec)  
-
-	}
-	TUint32 offset = GetRootDirList() - GetRomBase(); 
-	TRomRootDirectoryList* rootDirList = reinterpret_cast<TRomRootDirectoryList*>(iRomLayoutData + offset );
-	TInt dirCount = rootDirList->iNumRootDirs ; 
-	string tempName ;
-	for(TInt i = 0 ; i < dirCount ; i++) {
-		offset = rootDirList->iRootDir[i].iAddressLin - GetRomBase(); 
-		TRomDir* romDir = reinterpret_cast<TRomDir*>(iRomLayoutData + offset);		
-		Name(tempName,reinterpret_cast<const wchar_t *>(romDir->iEntry.iName),romDir->iEntry.iNameLength); 		 
-		BuildDir(romDir, iRomImageRootDirEntry);		 
-	}
- 
-}
- 
- 
-void RomImageReader::BuildDir(TRomDir* aDir, RomImageFSEntry* aPaFSEntry)
-{	 
-	
-	TInt processBytes = 0 ;
-	TInt totalDirBytes = aDir->iSize - sizeof(aDir->iSize);
-	TRomEntry* entry = &aDir->iEntry;
-	RomImageFSEntry *fsEntry ;
-	string name ;
-	const char* pritableName = "";
-
-	while(processBytes < totalDirBytes){
-		Name(name,reinterpret_cast<const wchar_t *>(entry->iName),entry->iNameLength);
-		pritableName = name.c_str(); 
-		if(entry->iAtt & 0x10) { // is a directory
-			fsEntry = new RomImageDirEntry(pritableName); 
-			AddChild(aPaFSEntry,fsEntry,NULL);
-			TUint offset = entry->iAddressLin - GetRomBase();
-			TRomDir* subFolder = reinterpret_cast<TRomDir*>(iRomLayoutData + offset);		 
-			BuildDir(subFolder,fsEntry); 
-		}
-		else{
-			fsEntry = new RomImageFileEntry(pritableName); 
-			AddChild(aPaFSEntry,fsEntry,entry);
-		} 
-		// increase the processedBytes
-		processBytes += (entry->iNameLength << 1) +  reinterpret_cast<TInt>(entry->iName) - reinterpret_cast<TInt>(entry); 
-
-		//align to next 4 bytes
-		processBytes = (processBytes + 3) & ( ~3 ); 
-		// get next entry
-		entry =  reinterpret_cast<TRomEntry*>( reinterpret_cast<char*>(&aDir->iEntry) + processBytes);
-	} 
-	
-}
-
-void RomImageReader::AddChild(RomImageFSEntry *aParent, RomImageFSEntry *aChild, TRomEntry* aRomEntry)
-{
-	if(!aParent->iChildren)
-		aParent->iChildren = aChild;
-	else {
-		RomImageFSEntry *aLast = aParent->iChildren;
-
-		while(aLast->iSibling)
-			aLast = aLast->iSibling;
-		aLast->iSibling = aChild;
-	}
-
-	if(!aChild->IsDirectory()) { 
-		RomImageFileEntry* file = static_cast<RomImageFileEntry*>(aChild);
-		file->iTRomEntryPtr = aRomEntry;
-
-		if(aRomEntry->iAddressLin > GetRomBase()) {
-			TUint32 offset = aRomEntry->iAddressLin - GetRomBase();	 
-		 
-			TRomImageHeader* imgHdr = reinterpret_cast<TRomImageHeader*>(iRomLayoutData + offset);
-			 
-			file->ImagePtr.iRomFileEntry = imgHdr;
-
-			TUint8 aUid1[4];
-			memcpy(aUid1, &file->ImagePtr.iRomFileEntry->iUid1, 4);
-
-			if( ReaderUtil::IsExecutable(aUid1) ) {
-				file->iExecutable = true;
-			}
-			else {
-				file->iExecutable = false;
-				file->ImagePtr.iDataFileAddr = aRomEntry->iAddressLin;
-			}
-		}
-		else {
-			file->ImagePtr.iRomFileEntry = NULL; 
-		}
-	}
-
-	if(aParent != iRomImageRootDirEntry) {
-		aChild->iPath = aParent->iPath;
-		aChild->iPath += DIR_SEPARATOR;
-		aChild->iPath += aParent->iName.c_str();
-	}
-}
-
-void RomImageReader::Name(string& aName, const wchar_t* aUnicodeName, TUint aLen)
-{
-	char* temp = (char*)_alloca((aLen << 1) + 1) ;
-	size_t n = wcsrtombs(temp,&aUnicodeName,aLen,NULL);
-	if(n == (size_t)-1){ // the unicode string can not be coverted.
-		aName = "???";
-	}
-	temp[n] = 0;
-	if(n > 0)
-		aName.assign(temp,n) ;
-	else
-		aName = "";
- 
-}
-
-void RomImageReader::DumpTree()
-{
-	RomImageFSEntry* aFsEntry = iRomImageRootDirEntry;
-	if( aFsEntry->iChildren ) 
-		DumpSubTree(aFsEntry->iChildren); 
-}
-
-void RomImageReader::DumpDirStructure()
-{
-	*out << "Directory Listing" << endl;
-	*out << "=================" << endl;
-	int aPadding = 0;
-	if( iRomImageRootDirEntry ){
-		DumpDirStructure(iRomImageRootDirEntry, aPadding);
-	}	
-	*out << endl << endl;
-}
-
-void RomImageReader::DumpDirStructure(RomImageFSEntry* aEntry, int &aPadding)
-{
-	if(!aEntry)
-		return;
-
-	int aPadLen = 2 * aPadding;//scaling for legibility
-	for (int i = 0; i < aPadLen; i++)
-		*out << " ";
-
-	*out << aEntry->Name() << endl;
-
-	if( aEntry->iChildren){
-		aPadding++;
-		DumpDirStructure(aEntry->iChildren, aPadding);
-		aPadding--;
-	}
-	DumpDirStructure(aEntry->iSibling, aPadding);
-}
-
-void RomImageReader::DumpSubTree(RomImageFSEntry* aFsEntry)
-{
-	if(!aFsEntry)
-		return;
-
-	if( aFsEntry->iChildren ){
-		DumpSubTree(aFsEntry->iChildren);
-	}
-
-	if( aFsEntry->iSibling )
-		DumpSubTree(aFsEntry->iSibling);
-
-	RomImageFSEntry *aEntry = aFsEntry;
-	
-	if(!aEntry->IsDirectory()) {
-		*out << "********************************************************************" << endl;
-		*out << "File........................" << aEntry->iPath.c_str() << DIR_SEPARATOR << aEntry->Name() << endl;
-
-		if( ((RomImageFileEntry*)aEntry)->iExecutable )	{
-			DumpImage((RomImageFileEntry*)aEntry);
-		}
-		else{
-			*out << "Linear Addr................." << ((RomImageFileEntry*)aEntry)->ImagePtr.iDataFileAddr << endl;
-		}
-	}
-}
-
-void RomImageReader::DumpImage(RomImageFileEntry * aEntry)
-{
-	bool aContinue = true;
-
-	DumpInHex("Load Address", aEntry->iTRomEntryPtr->iAddressLin) << endl;
-	DumpInHex("Size", aEntry->iTRomEntryPtr->iSize) << endl;
-
-	TRomImageHeader		*aRomImgEntry = aEntry->ImagePtr.iRomFileEntry;
-
-	if( !aRomImgEntry )
-		return;
-	//UIDs
-	DumpInHex("Uids", aRomImgEntry->iUid1);
-	DumpInHex(" ", aRomImgEntry->iUid2, aContinue);
-	DumpInHex(" ", aRomImgEntry->iUid3, aContinue);
-	DumpInHex(" ", aRomImgEntry->iUidChecksum, aContinue) << endl;
-
-	DumpInHex("Entry point", aRomImgEntry->iEntryPoint) << endl;
-	DumpInHex("Code start addr", aRomImgEntry->iCodeAddress) << endl;
-	DumpInHex("Data start addr", aRomImgEntry->iDataAddress) << endl;
-	DumpInHex("DataBssLinearBase", aRomImgEntry->iDataBssLinearBase) << endl;
-	DumpInHex("Text size", aRomImgEntry->iTextSize) << endl;
-	DumpInHex("Code size", aRomImgEntry->iCodeSize) << endl;
-	DumpInHex("Data size", aRomImgEntry->iDataSize) << endl;
-	DumpInHex("Bss size", (aRomImgEntry->iBssSize)) << endl;
-	DumpInHex("Total data size", aRomImgEntry->iTotalDataSize) << endl;
-	DumpInHex("Heap min", aRomImgEntry->iHeapSizeMin) << endl;
-	DumpInHex("Heap max", aRomImgEntry->iHeapSizeMax) << endl;
-	DumpInHex("Stack size", aRomImgEntry->iStackSize) << endl;
-
-	TDllRefTable *aRefTbl = NULL;
-
-	if( aRomImgEntry->iDllRefTable ) {
-		TUint32 aOff = (TUint32)aRomImgEntry->iDllRefTable - iImageHeader->iRomHdr->iRomBase;
-		aRefTbl = (TDllRefTable*) ((char*)iImageHeader->iRomHdr + aOff);
-		TUint32 aVirtualAddr = (TUint32)aRefTbl->iEntry[0];
-		DumpInHex("Dll ref table", aVirtualAddr) << endl;
-	}
-
-	DumpInHex("Export directory", aRomImgEntry->iExportDir) << endl;
-	DumpInHex("Export dir count", aRomImgEntry->iExportDirCount) << endl;
-	DumpInHex("Hardware variant", aRomImgEntry->iHardwareVariant) << endl;
-	DumpInHex("Flags", aRomImgEntry->iFlags) << endl;
-	DumpInHex("Secure ID", aRomImgEntry->iS.iSecureId) << endl;
-	DumpInHex("Vendor ID", aRomImgEntry->iS.iVendorId) << endl;
-
-	DumpInHex("Capability", aRomImgEntry->iS.iCaps[1]);
-	DumpInHex(" ", aRomImgEntry->iS.iCaps[0], aContinue) << endl;
-	
-	*out << "Tools Version..............." << dec << (TUint)aRomImgEntry->iToolsVersion.iMajor;
-	*out << "." ; 
-	out->width(2) ;
-	out->fill('0');
-	*out << dec << (TUint)aRomImgEntry->iToolsVersion.iMinor ;
-	*out << "(" << dec << aRomImgEntry->iToolsVersion.iBuild << ")";
-	*out << endl;
-
-	*out << "Module Version.............." << dec << (aRomImgEntry->iModuleVersion >> 16) << endl;
-	DumpInHex("Exception Descriptor", aRomImgEntry->iExceptionDescriptor) << endl;
-	*out << "Priority...................." << dec << aRomImgEntry->iPriority << endl;
-
-	if( aRefTbl )
-		DumpInHex("Dll ref table size", aRefTbl->iNumberOfEntries*8) << endl;
-	else
-		DumpInHex("Dll ref table size", 0) << endl;
-
-	if( iDisplayOptions & DUMP_E32_IMG_FLAG){
-		if(stricmp(iE32ImgFileName.c_str(), aEntry->Name()) == 0){
-			TUint aSectionOffset = aRomImgEntry->iCodeAddress - iImageHeader->iRomHdr->iRomBase;
-			TUint* aCodeSection = (TUint*)((char*)iImageHeader->iRomHdr + aSectionOffset);
-			*out << "\nCode (Size=0x" << hex << aRomImgEntry->iCodeSize << ")" << endl;
-			DumpData(aCodeSection, aRomImgEntry->iCodeSize);
-
-			aSectionOffset = aRomImgEntry->iDataAddress - iImageHeader->iRomHdr->iRomBase;
-			TUint* aDataSection = (TUint*)((char*)iImageHeader->iRomHdr + aSectionOffset);
-			if( aRomImgEntry->iDataSize){
-				*out << "\nData (Size=0x" << hex << aRomImgEntry->iDataSize << ")" << endl;
-				DumpData(aDataSection, aRomImgEntry->iDataSize);
-			}
-		}
-	}
-
-	*out << endl << endl;
-}
-
-void RomImageReader::DumpAttribs(RomImageFSEntry* aFsEntry)
-{
- 
-// a larger rom image cause stack overflow under visual studio if we use recursion algorithm here.
-// can gcc compiler guarantee this overflow will never be happen ?
- 	if( aFsEntry->iChildren )
-		DumpAttribs(aFsEntry->iChildren);
-
-	if(aFsEntry->iSibling)
-		DumpAttribs(aFsEntry->iSibling);
-	if(aFsEntry->IsDirectory()) return ;
-	RomImageFileEntry* file = static_cast<RomImageFileEntry*>(aFsEntry);
-	if(!file->iExecutable) return ; 
-	TRomImageHeader* aRomImgEntry = file->ImagePtr.iRomFileEntry;
-
-	if( !aRomImgEntry)  return; 
-	
-	const char* prefix ;
-	if(aRomImgEntry->iFlags & KRomImageFlagPrimary){
-		prefix = "Primary";
-	}
-	else if(aRomImgEntry->iFlags & KRomImageFlagVariant){
-		prefix = "Variant";
-	}
-	else if(aRomImgEntry->iFlags & KRomImageFlagExtension){
-		prefix = "Extension";
-	}
-	else if(aRomImgEntry->iFlags & KRomImageFlagDevice){
-		prefix = "Device";
-	}
-	else
-		return;
-
-	out->width(10);
-	out->fill(' '); 
-	*out << left << prefix;
-	out->width(40);	
-	*out << right << file->Name() << "[" ;
-	DumpInHex( "", aRomImgEntry->iHardwareVariant, true) << "] ";
-	DumpInHex( " DataSize=", (aRomImgEntry->iBssSize + aRomImgEntry->iDataSize), true) << endl;
-	
-}
-
-void RomImageReader::Dump()
-{
-	if( !((iDisplayOptions & EXTRACT_FILES_FLAG) || 
-		(iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG) ||
-		(iDisplayOptions & EXTRACT_FILE_SET_FLAG)) ) {
-		*out << "Image Name................." << iImgFileName.c_str() << endl;
-
-		if( iImageHeader->iRomHdr )
-		iImageHeader->DumpRomHdr();
-		else
-		iImageHeader->DumpRomXHdr();
-
-		DumpAttribs(iRomImageRootDirEntry);
-		*out << endl ;
-
-		if(iDisplayOptions & DUMP_VERBOSE_FLAG) {
-			DumpDirStructure();
-			DumpTree();
-		}
-
-		if(iDisplayOptions & DUMP_DIR_ENTRIES_FLAG) {
-			DumpDirStructure();
-		}
-	}
-}
-
-
-/** 
-Function iterates through all the entries in the image 
-by making a call to TraverseImage function.
-
-@internalComponent
-@released
-*/
-void RomImageReader::ExtractImageContents()
-{
-	if( (iDisplayOptions & EXTRACT_FILE_SET_FLAG) )
-	{
-		//TODO:
-		ImageReader::ExtractFileSet(iRomLayoutData);
-	}
-
-	if( iDisplayOptions & EXTRACT_FILES_FLAG || iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG )
-	{
-		if(iRomImageRootDirEntry)
-		{
-			// name of the log file.
-			string logFile;
-			// output stream for the log file.
-			ofstream oFile;
-			
-			if( iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG){
-				if( ImageReader::iZdrivePath.compare("")){
-					// create a string to hold path information.
-					string filePath(ImageReader::iZdrivePath);
-					string delimiter("\\"); 
-					// replace backslash with double backslash. 
-					FindAndInsertString(filePath,delimiter,delimiter);
-					logFile = filePath;
-					// create specified directory.
-					CreateSpecifiedDir(&filePath[0],"\\\\");
-					logFile.append("\\\\");
-					logFile.append(ImageReader::iLogFileName);
-				}
-				else
-				{				
-					logFile = ImageReader::iLogFileName;
-				}
-				// open the specified file in append mode.
-				oFile.open(logFile.c_str() ,ios::out|ios::app);
-
-				if(!oFile.is_open()){
-					throw ImageReaderException((char*)ImageReader::iLogFileName.c_str(), "Failed to open the log file");
-				}
-			}
-			TraverseImage(iRomImageRootDirEntry,oFile);
-			if(oFile.is_open())  oFile.close();  
-		}
-	}
-}
-
-
-/** 
-Function to traverse entire image and check for an entity.If the entity found in the image is a file 
-then it makes a call to CheckFileExtension to check for extension.
-
-@internalComponent
-@released
-
-@param aEntity		- pointer to the entry in rom image.
-@param aFile		- output stream.
-*/
-void RomImageReader::TraverseImage(RomImageFSEntry*  aEntity,ofstream& aFile)
-{
-	if(!aEntity->IsDirectory())	{
-		CheckFileExtension(aEntity,aFile);
-	}
-	
- 	if (aEntity->iChildren)	{
-		TraverseImage(aEntity->iChildren,aFile);
-	}
-
-	if (aEntity->iSibling)	{
-		TraverseImage(aEntity->iSibling,aFile);
-	}
-}
-
-
-/** 
-Function to get check extension of the given file.If the extension of the file is "sis"
-then call ExtractFile function to extract the file from the image.  
-
-@internalComponent
-@released
-
-@param aEntity		- pointer to the entry in rom image.
-@param aFile		- output stream.
-*/
-void RomImageReader::CheckFileExtension(RomImageFSEntry*  aEntity,ofstream& aFile)
-{
-	RomImageFileEntry*	romEntry = (RomImageFileEntry*)aEntity;
-	// get the size of the entity.
-	TUint32 size = romEntry->iTRomEntryPtr->iSize;
-	// get the offset of the entity.
-	TUint32 offset =  romEntry->iTRomEntryPtr->iAddressLin - GetRomBase() ;
-
-	const char* fileName = aEntity->iName.c_str();
-
-	// create a string to hold the path information.
-	string romfilePath(romEntry->iPath);
-	string forwardSlash("/");
-	string slash("\\");  
-	//replace slash with double backward slash.
-	FindAndReplaceString( romfilePath, forwardSlash, slash );
-	
-	if( iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG && iDisplayOptions & EXTRACT_FILES_FLAG ) {
-		// get the position.
-		size_t pos = aEntity->iName.find_last_of(".");
-		
-		const char* extName = fileName + ( pos + 1 );
-		if ( !stricmp(extName ,"SIS")	||  !stricmp(extName ,"DAT") ) {
-			// if the two strings are same then extract the corresponding file.
-			ImageReader::ExtractFile(offset,size,fileName,&romfilePath[0],&ImageReader::iZdrivePath[0],iRomLayoutData);
-		}
-		else {
-			LogRomEnrtyToFile(romfilePath.c_str(),fileName,aFile);
-		}
-	}
-	else if( iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG ) {
-		LogRomEnrtyToFile(romfilePath.c_str(),fileName,aFile);
-	}
-	else {
-		if(romEntry->iExecutable) {
-			size += sizeof(TRomImageHeader);
-		}
-		// extract the corresponding file. 
-		ImageReader::ExtractFile(offset,size,fileName,&romfilePath[0],&ImageReader::iZdrivePath[0],iRomLayoutData);
-	}
-}
-
-
-/** 
-Function to log the rom entry to a specified file. 
-
-@internalComponent
-@released
-
-@param aPath		- Complete path of an entity.
-@param aEntityName	- Entity name. 
-@param aFile		- output stream.
-*/
-void RomImageReader::LogRomEnrtyToFile(const char* aPath,const char* aEntityName,ofstream& aFile)
-{
-	if(aFile.is_open())
-	{
-		aFile.seekp(0,ios::end);
-		aFile<<aPath<<"\\"<<aEntityName<<"\n";
-	}
-}
-
-
-/** 
-Function to read the directory structure details of te ROM image.  
-
-@internalComponent
-@released
-
-@param aEntity		- pointer to the entry in rom image.
-@param aFileMap		- map of filename with its size and offset values.
-@param aImgSize		- Image size
-*/
-void RomImageReader::ProcessDirectory(RomImageFSEntry *aEntity, FILEINFOMAP &aFileMap)
-{
-	if(!aEntity->IsDirectory()) { 
-
-		RomImageFileEntry*	romEntry = (RomImageFileEntry*)aEntity;
-
-		PFILEINFO fileInfo = new FILEINFO;
-
-		// get the size of the entity.
-		fileInfo->iSize = romEntry->iTRomEntryPtr->iSize;
-		// get the offset of the entity.
-		fileInfo->iOffset = (romEntry->iTRomEntryPtr->iAddressLin - GetRomBase()); 
-
-		if(romEntry->iExecutable) {
-			fileInfo->iSize += sizeof(TRomImageHeader);
-		}
-
-		if((fileInfo->iOffset + fileInfo->iSize) > iRomSize) {
-			fileInfo->iOffset = 0;
-			fileInfo->iSize = 0;
-		}
-
-		string fileName(romEntry->iPath);
-		fileName.append(DIR_SEPARATOR);
-		fileName.append(aEntity->iName);
-
-		aFileMap[fileName] = fileInfo;
-	}
-	
- 	if (aEntity->iChildren) {
-		ProcessDirectory(aEntity->iChildren, aFileMap);
-	}
-
-	if (aEntity->iSibling) {
-		ProcessDirectory(aEntity->iSibling, aFileMap);
-	}
-}
-
-/** 
-Function to read the directory structure details of te ROM image.  
-
-@internalComponent
-@released
-
-@param aFileMap		- map of filename with its size and offset values.
-*/
-void RomImageReader::GetFileInfo(FILEINFOMAP &aFileMap) {
-	ProcessDirectory(iRomImageRootDirEntry, aFileMap);
-}
-
-/** 
-Function to get the ROM image size.
-
-@internalComponent
-@released
-*/
-TUint32 RomImageReader::GetImageSize() {
-	return iRomSize;
-}
-
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent 
+* @released
+*
+*/
+
+#include <e32rom.h>
+#include "rom_image_reader.h"
+#include "r_rom.h"
+#ifdef __LINUX__
+#define _alloca alloca 
+#endif
+#include "utf16string.h"
+void InflateUnCompress(unsigned char* source, int sourcesize, unsigned char* dest, int destsize);
+RomImageFSEntry::RomImageFSEntry (const char* aName) : iName(aName), iSibling(0), iChildren(0) {
+}
+RomImageFSEntry::~RomImageFSEntry() {
+	if(iChildren){
+		delete iChildren;
+		iChildren = NULL ;
+	}
+	if(iSibling){
+		delete iSibling ;
+		iSibling = NULL ;
+	}	
+}
+
+//Rom Image header 
+RomImageHeader::RomImageHeader(char* aHdr, EImageType aImgType) {
+	switch( aImgType) {
+	case EROM_IMAGE:
+		iLoaderHdr = (TRomLoaderHeader*)aHdr;
+		iRomHdr = (TRomHeader*)(aHdr + sizeof(TRomLoaderHeader));
+		iExtRomHdr = 0;
+		break;
+
+	case EROMX_IMAGE:
+		iExtRomHdr = (TExtensionRomHeader*)(aHdr);
+		iRomHdr = 0;
+		iLoaderHdr = 0;
+		break;
+
+	case EBAREROM_IMAGE:
+		iLoaderHdr = 0;
+		iRomHdr = (TRomHeader*)aHdr;
+		iExtRomHdr = 0;
+		break;
+	default:
+		iExtRomHdr = 0;
+		iRomHdr = 0;
+		iLoaderHdr = 0;
+		break ;
+	}
+}
+
+
+void RomImageHeader::DumpRomHdr() {
+	if(iLoaderHdr)
+		*out << "ROM Image " << endl << endl;
+	else
+		*out << "Bare ROM Image" << endl << endl;
+	TUint aPos = 0;
+	bool aContinue = true;
+
+	*out << "Image Signature .................";
+
+	if(iLoaderHdr){     
+		char temp[KRomNameSize + 1];
+		memcpy(temp,reinterpret_cast<char*>(iLoaderHdr),KRomNameSize);        
+		temp[KRomNameSize] = 0;
+		*out << temp;
+	}
+
+	*out << endl << endl;
+
+	DumpInHex("Timestamp", (iRomHdr->iTime >> 32)) ;
+	DumpInHex(" ", (iRomHdr->iTime &0xffffffff), aContinue) << endl;
+
+	DumpInHex("RomBase", iRomHdr->iRomBase) << endl;
+
+	DumpInHex("RomSize", iRomHdr->iRomSize) << endl;
+	DumpInHex("KernelDataAddress", iRomHdr->iKernDataAddress) << endl;
+	DumpInHex("KernelLimit", iRomHdr->iKernelLimit) << endl;
+	DumpInHex("PrimaryFile", iRomHdr->iPrimaryFile) << endl;
+	DumpInHex("SecondaryFile", iRomHdr->iSecondaryFile) << endl;
+	DumpInHex("CheckSum", iRomHdr->iCheckSum) << endl;
+	DumpInHex("Hardware", iRomHdr->iHardware) << endl;
+
+	DumpInHex("Language", (TUint)(iRomHdr->iLanguage >> 32));
+	DumpInHex(" ", ((TUint)(iRomHdr->iLanguage & 0xffffffff)), aContinue) <<endl;
+
+	DumpInHex("KernelConfigFlags", iRomHdr->iKernelConfigFlags) << endl;
+	DumpInHex("RomExceptionSearchTable", iRomHdr->iRomExceptionSearchTable) << endl;
+	DumpInHex("RomHeaderSize", iRomHdr->iRomHeaderSize) << endl;
+	DumpInHex("RomSectionHeader", iRomHdr->iRomSectionHeader) << endl;
+	DumpInHex("TotalSvDataSize", iRomHdr->iTotalSvDataSize) << endl;
+	DumpInHex("VariantFile", iRomHdr->iVariantFile) << endl;
+	DumpInHex("ExtensionFile", iRomHdr->iExtensionFile) << endl;
+	DumpInHex("RelocInfo", iRomHdr->iRelocInfo) << endl;
+	DumpInHex("OldTraceMask", iRomHdr->iOldTraceMask) << endl;
+	DumpInHex("UserDataAddress", iRomHdr->iUserDataAddress) << endl;
+	DumpInHex("TotalUserDataSize", iRomHdr->iTotalUserDataSize) << endl;
+	DumpInHex("DebugPort", iRomHdr->iDebugPort) << endl;
+
+	DumpInHex("Version", iRomHdr->iVersion.iMajor, false, 2);
+	DumpInHex(".", iRomHdr->iVersion.iMinor, aContinue, 2);
+	DumpInHex("(" ,iRomHdr->iVersion.iBuild, aContinue, 2);
+	*out << ")" << endl;
+
+	DumpInHex("CompressionType", iRomHdr->iCompressionType) << endl;
+	DumpInHex("CompressedSize", iRomHdr->iCompressedSize) << endl;
+	DumpInHex("UncompressedSize", iRomHdr->iUncompressedSize) << endl;
+	DumpInHex("HcrFileAddress", iRomHdr->iHcrFileAddress) << endl;
+
+	DumpInHex("DisabledCapabilities", iRomHdr->iDisabledCapabilities[0]);
+	DumpInHex(" ", iRomHdr->iDisabledCapabilities[1], aContinue) << endl;
+
+	DumpInHex("TraceMask", iRomHdr->iTraceMask[0]);
+	aPos = 1;
+	while( aPos < (TUint)KNumTraceMaskWords) {
+		if(iRomHdr->iTraceMask[aPos]) {
+			DumpInHex(" ", iRomHdr->iTraceMask[aPos++], aContinue);
+		}
+		else {
+			DumpInHex(" ", iRomHdr->iTraceMask[aPos++], aContinue, 1);
+		}
+
+	}
+
+	*out << endl << endl;
+
+}
+void RomImageHeader::DumpRomXHdr() {
+	*out << "Extension ROM Image" << endl << endl;
+	bool aContinue = true;
+
+	DumpInHex("Timestamp", (iExtRomHdr->iTime >> 32)) ;
+	DumpInHex(" ", (iExtRomHdr->iTime &0xffffffff), aContinue) << endl;
+
+	DumpInHex("RomBase", iExtRomHdr->iRomBase) << endl;
+
+	DumpInHex("RomSize", iExtRomHdr->iRomSize) << endl;
+	DumpInHex("CheckSum", iExtRomHdr->iCheckSum) << endl;
+
+	DumpInHex("Version", iExtRomHdr->iVersion.iMajor, false, 2);
+	DumpInHex(".", iExtRomHdr->iVersion.iMinor, aContinue, 2);
+	DumpInHex("(" ,iExtRomHdr->iVersion.iBuild, aContinue, 2);
+	*out << ")" << endl;
+
+	DumpInHex("CompressionType", iExtRomHdr->iCompressionType) << endl;
+	DumpInHex("CompressedSize", iExtRomHdr->iCompressedSize) << endl;
+	DumpInHex("UncompressedSize", iExtRomHdr->iUncompressedSize) << endl;
+
+	*out << endl << endl;
+
+}
+//Rom Image reader
+RomImageReader::RomImageReader(const char* aFile, EImageType aImgType) :
+ImageReader(aFile), iImageHeader(0),
+iRomSize(0),iHeaderBuffer(0),
+iRomLayoutData(0),iImgType(aImgType) {
+	iRomImageRootDirEntry = new RomImageDirEntry("");
+}
+
+RomImageReader::~RomImageReader() {
+	if(iFile.is_open())
+		iFile.close();
+	if(iHeaderBuffer)
+		delete []iHeaderBuffer;
+	if(iRomLayoutData)
+		delete []iRomLayoutData;  
+	delete iRomImageRootDirEntry;
+
+
+}
+
+void RomImageReader::ReadImage() {
+	if(iFile.is_open()) return ;
+	iFile.open(iImgFileName.c_str(), ios_base::binary | ios_base::in);
+	if( !iFile.is_open() ) {
+		throw ImageReaderException(iImgFileName.c_str(), "Cannot open file ");
+	}	
+
+	TUint headerSize = GetHdrSize() ;	
+	if(headerSize > 0){
+		iHeaderBuffer = new char[headerSize];
+		iFile.read(iHeaderBuffer,headerSize);
+	}	
+}
+
+void RomImageReader::Validate() {
+}
+
+TUint32 RomImageReader::GetImageCompressionType() {
+	if(iImageHeader->iRomHdr )// iImageType == EROM_IMAGE
+		return iImageHeader->iRomHdr->iCompressionType;
+	else
+		return iImageHeader->iExtRomHdr->iCompressionType;
+}
+
+
+TLinAddr RomImageReader::GetRomBase() {
+	if(iImageHeader->iRomHdr )// iImageType == EROM_IMAGE
+		return iImageHeader->iRomHdr->iRomBase ;
+	else
+		return iImageHeader->iExtRomHdr->iRomBase;
+}
+
+TLinAddr RomImageReader::GetRootDirList() {
+	if(iImageHeader->iRomHdr )// iImageType == EROM_IMAGE
+		return iImageHeader->iRomHdr->iRomRootDirectoryList;
+	else
+		return iImageHeader->iExtRomHdr->iRomRootDirectoryList;
+}
+
+TUint RomImageReader::GetHdrSize() {
+	TUint headerSize = 0;
+	if(EROM_IMAGE == iImgType){
+		headerSize = sizeof(TRomLoaderHeader) + sizeof(TRomHeader);
+	}else if(EROMX_IMAGE == iImgType){
+		headerSize = sizeof(TExtensionRomHeader);
+	}else if(EBAREROM_IMAGE == iImgType){
+		headerSize = sizeof(TRomHeader);
+	}
+	return headerSize;
+}
+
+
+static const TInt KIOBytes = 0x100000;
+// reading a huge buffer at a time is very slow, reading 1MB bytes at a time is much faster
+void RomImageReader::ReadData(char* aBuffer, TUint aLength) {
+	TUint readBytes = 0 ;
+	while(readBytes < aLength){
+		TUint toRead = KIOBytes;
+		if(readBytes + toRead > aLength)
+			toRead = aLength - readBytes ;
+		iFile.read(&aBuffer[readBytes],toRead);
+		readBytes += toRead ;
+	}	
+}
+void RomImageReader::ProcessImage() {
+	if(iRomLayoutData) return ;
+	iImageHeader = new RomImageHeader(iHeaderBuffer, iImgType);
+
+	iFile.seekg(0, ios_base::end);
+	// fileSize
+	TUint fileSize = iFile.tellg(); 
+
+	//let's skip the RomLoaderHeader
+	TUint romDataBegin = (EROM_IMAGE == iImgType) ? sizeof(TRomLoaderHeader) : 0 ; 
+	iFile.seekg(romDataBegin,ios_base::beg);	
+
+	if(EROMX_IMAGE == iImgType){// EROMX_IMAGE, just set the iUnpagedRomBuffer		
+		if(GetImageCompressionType() == KUidCompressionDeflate){
+			TUint32 readLen = fileSize - sizeof(TExtensionRomHeader) ; 
+			iRomSize = iImageHeader->iExtRomHdr->iUncompressedSize ;	 
+			iRomLayoutData = new char[iRomSize];
+			char* temp = new char[readLen];
+			// header is not compressed.
+			iFile.read(iRomLayoutData,sizeof(TExtensionRomHeader)); 
+			ReadData(temp ,readLen);
+			TUint8* uncompressDest = reinterpret_cast<TUint8*>(iRomLayoutData + sizeof(TExtensionRomHeader));
+			InflateUnCompress(reinterpret_cast<TUint8*>(temp),readLen,uncompressDest,iRomSize - sizeof(TExtensionRomHeader));
+			delete []temp ;	 
+
+		}else{
+			iRomSize = fileSize  ;
+			iRomLayoutData = new char[iRomSize]; 
+			ReadData(iRomLayoutData,iRomSize);
+		}	 
+	} // end EROMX_IMAGE
+	else {
+		//EROM_IMAGE or EBAREROM_IMAGE
+		const TInt KPageSize = 0x1000; 
+		TRomHeader *hdr = iImageHeader->iRomHdr; 
+		iRomSize = hdr->iUncompressedSize ; 
+		iRomLayoutData = new char[iRomSize]; 
+		char* curDataPointer = iRomLayoutData ;
+		TUint totalReadBytes = 0;
+		bool hasPageableSec = (hdr->iPageableRomStart > 0 && hdr->iPageableRomSize > 0) ;
+
+		// read data before unpaged 
+		ReadData(curDataPointer,hdr->iCompressedUnpagedStart); 
+		curDataPointer += hdr->iCompressedUnpagedStart ; 
+		totalReadBytes += hdr->iCompressedUnpagedStart;		
+
+		// read the unpaged part, if compressed , then decompress		 
+		if(GetImageCompressionType() == KUidCompressionDeflate){
+			char* temp = new char[hdr->iUnpagedCompressedSize];
+			ReadData(temp,hdr->iUnpagedCompressedSize);
+			totalReadBytes += hdr->iUnpagedCompressedSize;
+			InflateUnCompress(reinterpret_cast<TUint8*>(temp),hdr->iUnpagedCompressedSize,reinterpret_cast<TUint8*>(curDataPointer) ,hdr->iUnpagedUncompressedSize);
+			delete []temp ;			
+		}else{
+			TUint unpagedSeclen ;
+			if(hasPageableSec) { // there is paged section 
+				unpagedSeclen = hdr->iPageableRomStart - hdr->iCompressedUnpagedStart;
+			}else{
+				unpagedSeclen = iRomSize - hdr->iCompressedUnpagedStart;
+			}
+			ReadData(curDataPointer,unpagedSeclen);			 
+			totalReadBytes += unpagedSeclen ;
+		}
+		curDataPointer = iRomLayoutData + totalReadBytes; 
+		//if there is a paged section , read and extract it 
+
+		// read the paged section,
+		if(hasPageableSec){		
+			if((TUint)(hdr->iPageableRomStart + hdr->iPageableRomSize) > iRomSize){
+				throw ImageReaderException("Incorrect values of ROM header fields.", "");
+			}
+			if(0 == hdr->iRomPageIndex){ //
+				// no compression for paged section ,just read it 			 
+				iFile.read(curDataPointer,iRomSize - totalReadBytes);
+			}
+			else{
+				//aligment calculation
+				TUint pagedSecOffset = (totalReadBytes + KPageSize - 1) & (~(KPageSize - 1));
+				if(pagedSecOffset > totalReadBytes){
+					// there are gap bytes between unpaged and paged sections
+					iFile.read(curDataPointer,pagedSecOffset - totalReadBytes);
+					curDataPointer = iRomLayoutData + pagedSecOffset;
+				}
+				TUint pagedIndexCount = ( hdr->iUncompressedSize + KPageSize - 1) / KPageSize;
+				// how many bytes ?
+				// the page index table include the unpaged part ;
+				TUint firstPagedIndexTblItem = hdr->iPageableRomStart / KPageSize;
+
+				TUint tempBufLen = KPageSize << 8;
+				char* readBuffer = new char[tempBufLen]; 
+
+				TUint8* src,*srcNext = NULL;
+				SRomPageInfo* pageInfo = reinterpret_cast<SRomPageInfo*>(&iRomLayoutData[hdr->iRomPageIndex]);
+				CBytePair bpe;
+				for(TUint i = firstPagedIndexTblItem ; i < pagedIndexCount ; i+= 256){
+					TUint endIndex = i + 255 ;
+					if(endIndex >= pagedIndexCount)
+						endIndex = pagedIndexCount - 1;
+					TUint readLen = pageInfo[endIndex].iDataStart + pageInfo[endIndex].iDataSize - pageInfo[i].iDataStart ; 
+					iFile.read(readBuffer,readLen);
+					src = reinterpret_cast<TUint8*>(readBuffer);
+					for(TUint j = i ; j <= endIndex ; j++){
+						switch(pageInfo[j].iCompressionType) {
+						case SRomPageInfo::EBytePair: {
+							TInt unpacked = bpe.Decompress(reinterpret_cast<TUint8*>(curDataPointer), KPageSize, src, pageInfo[j].iDataSize, srcNext);
+							if (unpacked < 0) {
+								delete []readBuffer;
+								throw ImageReaderException("Corrupted BytePair compressed ROM image", "");
+							}
+							curDataPointer += unpacked;
+							break ;
+													  }
+						case SRomPageInfo::ENoCompression:
+							memcpy(curDataPointer,src,pageInfo[j].iDataSize);
+							curDataPointer +=  pageInfo[j].iDataSize ;
+							break ;
+						default:
+							delete []readBuffer;
+							throw ImageReaderException("Undefined compression type", "");
+							break ;
+
+						}
+						src += pageInfo[j].iDataSize; 
+					} // end for(TUint j = i ; j <= endIndex ; j++) 
+				} // end for(TUint i = firstPagedIndexTblItem ; i < pagedIndexCount ; i+= 256) 
+				delete []readBuffer ;
+			}// else
+
+		} // if(hasPageableSec)  
+
+	}
+	TUint32 offset = GetRootDirList() - GetRomBase(); 
+	TRomRootDirectoryList* rootDirList = reinterpret_cast<TRomRootDirectoryList*>(iRomLayoutData + offset );
+	TInt dirCount = rootDirList->iNumRootDirs ; 
+	string tempName ;
+	for(TInt i = 0 ; i < dirCount ; i++) {
+		offset = rootDirList->iRootDir[i].iAddressLin - GetRomBase(); 
+		TRomDir* romDir = reinterpret_cast<TRomDir*>(iRomLayoutData + offset);	
+		UTF16String unistr(reinterpret_cast<const TUint16*>(romDir->iEntry.iName),romDir->iEntry.iNameLength); 
+		if(!unistr.ToUTF8(tempName)) //not utf16?
+			tempName.assign(reinterpret_cast<const char*>(romDir->iEntry.iName),romDir->iEntry.iNameLength) ;
+		BuildDir(romDir, iRomImageRootDirEntry);		 
+	}
+
+}
+
+
+void RomImageReader::BuildDir(TRomDir* aDir, RomImageFSEntry* aPaFSEntry)
+{	 
+
+	TInt processBytes = 0 ;
+	TInt totalDirBytes = aDir->iSize - sizeof(aDir->iSize);
+	TRomEntry* entry = &aDir->iEntry;
+	RomImageFSEntry *fsEntry ;
+	string pritableName ; 
+
+	while(processBytes < totalDirBytes){ 
+		UTF16String unistr(reinterpret_cast<const TUint16*>(entry->iName),entry->iNameLength);
+		if(!unistr.ToUTF8(pritableName)) 
+			pritableName.assign(reinterpret_cast<const char*>(entry->iName),entry->iNameLength);
+		if(entry->iAtt & 0x10) { // is a directory
+			fsEntry = new RomImageDirEntry(pritableName.c_str()); 
+			AddChild(aPaFSEntry,fsEntry,NULL);
+			TUint offset = entry->iAddressLin - GetRomBase();
+			TRomDir* subFolder = reinterpret_cast<TRomDir*>(iRomLayoutData + offset);		 
+			BuildDir(subFolder,fsEntry); 
+		}
+		else{
+			fsEntry = new RomImageFileEntry(pritableName.c_str()); 
+			AddChild(aPaFSEntry,fsEntry,entry);
+		} 
+		// increase the processedBytes
+		processBytes += (entry->iNameLength << 1) +  reinterpret_cast<TInt>(entry->iName) - reinterpret_cast<TInt>(entry); 
+
+		//align to next 4 bytes
+		processBytes = (processBytes + 3) & ( ~3 ); 
+		// get next entry
+		entry =  reinterpret_cast<TRomEntry*>( reinterpret_cast<char*>(&aDir->iEntry) + processBytes);
+	} 
+
+}
+
+void RomImageReader::AddChild(RomImageFSEntry *aParent, RomImageFSEntry *aChild, TRomEntry* aRomEntry) {
+	if(!aParent->iChildren)
+		aParent->iChildren = aChild;
+	else {
+		RomImageFSEntry *aLast = aParent->iChildren;
+
+		while(aLast->iSibling)
+			aLast = aLast->iSibling;
+		aLast->iSibling = aChild;
+	}
+
+	if(!aChild->IsDirectory()) { 
+		RomImageFileEntry* file = static_cast<RomImageFileEntry*>(aChild);
+		file->iTRomEntryPtr = aRomEntry;
+
+		if(aRomEntry->iAddressLin > GetRomBase()) {
+			TUint32 offset = aRomEntry->iAddressLin - GetRomBase();	 
+
+			TRomImageHeader* imgHdr = reinterpret_cast<TRomImageHeader*>(iRomLayoutData + offset);
+
+			file->ImagePtr.iRomFileEntry = imgHdr;
+
+			TUint8 aUid1[4];
+			memcpy(aUid1, &file->ImagePtr.iRomFileEntry->iUid1, 4);
+
+			if( ReaderUtil::IsExecutable(aUid1) ) {
+				file->iExecutable = true;
+			}
+			else {
+				file->iExecutable = false;
+				file->ImagePtr.iDataFileAddr = aRomEntry->iAddressLin;
+			}
+		}
+		else {
+			file->ImagePtr.iRomFileEntry = NULL; 
+		}
+	}
+
+	if(aParent != iRomImageRootDirEntry) {
+		aChild->iPath = aParent->iPath;
+		aChild->iPath += SLASH_CHAR1;
+		aChild->iPath += aParent->iName.c_str();
+	}
+}
+
+void RomImageReader::DumpTree() {
+	RomImageFSEntry* aFsEntry = iRomImageRootDirEntry;
+	if( aFsEntry->iChildren ) 
+		DumpSubTree(aFsEntry->iChildren); 
+}
+
+void RomImageReader::DumpDirStructure() {
+	*out << "Directory Listing" << endl;
+	*out << "=================" << endl;
+	int aPadding = 0;
+	if( iRomImageRootDirEntry ){
+		DumpDirStructure(iRomImageRootDirEntry, aPadding);
+	}	
+	*out << endl << endl;
+}
+
+void RomImageReader::DumpDirStructure(RomImageFSEntry* aEntry, int &aPadding) {
+	if(!aEntry)
+		return;
+
+	int aPadLen = 2 * aPadding;//scaling for legibility
+	for (int i = 0; i < aPadLen; i++)
+		*out << " ";
+
+	*out << aEntry->Name() << endl;
+
+	if( aEntry->iChildren){
+		aPadding++;
+		DumpDirStructure(aEntry->iChildren, aPadding);
+		aPadding--;
+	}
+	DumpDirStructure(aEntry->iSibling, aPadding);
+}
+
+void RomImageReader::DumpSubTree(RomImageFSEntry* aFsEntry) {
+	if(!aFsEntry)
+		return;
+
+	if( aFsEntry->iChildren ){
+		DumpSubTree(aFsEntry->iChildren);
+	}
+
+	if( aFsEntry->iSibling )
+		DumpSubTree(aFsEntry->iSibling);
+
+	RomImageFSEntry *aEntry = aFsEntry;
+
+	if(!aEntry->IsDirectory()) {
+		*out << "********************************************************************" << endl;
+		*out << "File........................" << aEntry->iPath.c_str() << SLASH_CHAR1 << aEntry->Name() << endl;
+
+		if( ((RomImageFileEntry*)aEntry)->iExecutable )	{
+			DumpImage((RomImageFileEntry*)aEntry);
+		}
+		else{
+			*out << "Linear Addr................." << ((RomImageFileEntry*)aEntry)->ImagePtr.iDataFileAddr << endl;
+		}
+	}
+}
+
+void RomImageReader::DumpImage(RomImageFileEntry * aEntry) {
+	bool aContinue = true;
+
+	DumpInHex("Load Address", aEntry->iTRomEntryPtr->iAddressLin) << endl;
+	DumpInHex("Size", aEntry->iTRomEntryPtr->iSize) << endl;
+
+	TRomImageHeader		*aRomImgEntry = aEntry->ImagePtr.iRomFileEntry;
+
+	if( !aRomImgEntry )
+		return;
+	//UIDs
+	DumpInHex("Uids", aRomImgEntry->iUid1);
+	DumpInHex(" ", aRomImgEntry->iUid2, aContinue);
+	DumpInHex(" ", aRomImgEntry->iUid3, aContinue);
+	DumpInHex(" ", aRomImgEntry->iUidChecksum, aContinue) << endl;
+
+	DumpInHex("Entry point", aRomImgEntry->iEntryPoint) << endl;
+	DumpInHex("Code start addr", aRomImgEntry->iCodeAddress) << endl;
+	DumpInHex("Data start addr", aRomImgEntry->iDataAddress) << endl;
+	DumpInHex("DataBssLinearBase", aRomImgEntry->iDataBssLinearBase) << endl;
+	DumpInHex("Text size", aRomImgEntry->iTextSize) << endl;
+	DumpInHex("Code size", aRomImgEntry->iCodeSize) << endl;
+	DumpInHex("Data size", aRomImgEntry->iDataSize) << endl;
+	DumpInHex("Bss size", (aRomImgEntry->iBssSize)) << endl;
+	DumpInHex("Total data size", aRomImgEntry->iTotalDataSize) << endl;
+	DumpInHex("Heap min", aRomImgEntry->iHeapSizeMin) << endl;
+	DumpInHex("Heap max", aRomImgEntry->iHeapSizeMax) << endl;
+	DumpInHex("Stack size", aRomImgEntry->iStackSize) << endl;
+
+	TDllRefTable *aRefTbl = NULL;
+
+	if( aRomImgEntry->iDllRefTable ) {
+		TUint32 aOff = (TUint32)aRomImgEntry->iDllRefTable - iImageHeader->iRomHdr->iRomBase;
+		aRefTbl = (TDllRefTable*) ((char*)iImageHeader->iRomHdr + aOff);
+		TUint32 aVirtualAddr = (TUint32)aRefTbl->iEntry[0];
+		DumpInHex("Dll ref table", aVirtualAddr) << endl;
+	}
+
+	DumpInHex("Export directory", aRomImgEntry->iExportDir) << endl;
+	DumpInHex("Export dir count", aRomImgEntry->iExportDirCount) << endl;
+	DumpInHex("Hardware variant", aRomImgEntry->iHardwareVariant) << endl;
+	DumpInHex("Flags", aRomImgEntry->iFlags) << endl;
+	DumpInHex("Secure ID", aRomImgEntry->iS.iSecureId) << endl;
+	DumpInHex("Vendor ID", aRomImgEntry->iS.iVendorId) << endl;
+
+	DumpInHex("Capability", aRomImgEntry->iS.iCaps[1]);
+	DumpInHex(" ", aRomImgEntry->iS.iCaps[0], aContinue) << endl;
+
+	*out << "Tools Version..............." << dec << (TUint)aRomImgEntry->iToolsVersion.iMajor;
+	*out << "." ; 
+	out->width(2) ;
+	out->fill('0');
+	*out << dec << (TUint)aRomImgEntry->iToolsVersion.iMinor ;
+	*out << "(" << dec << aRomImgEntry->iToolsVersion.iBuild << ")";
+	*out << endl;
+
+	*out << "Module Version.............." << dec << (aRomImgEntry->iModuleVersion >> 16) << endl;
+	DumpInHex("Exception Descriptor", aRomImgEntry->iExceptionDescriptor) << endl;
+	*out << "Priority...................." << dec << aRomImgEntry->iPriority << endl;
+
+	if( aRefTbl )
+		DumpInHex("Dll ref table size", aRefTbl->iNumberOfEntries*8) << endl;
+	else
+		DumpInHex("Dll ref table size", 0) << endl;
+
+	if( iDisplayOptions & DUMP_E32_IMG_FLAG){
+		if(stricmp(iE32ImgFileName.c_str(), aEntry->Name()) == 0){
+			TUint aSectionOffset = aRomImgEntry->iCodeAddress - iImageHeader->iRomHdr->iRomBase;
+			TUint* aCodeSection = (TUint*)((char*)iImageHeader->iRomHdr + aSectionOffset);
+			*out << "\nCode (Size=0x" << hex << aRomImgEntry->iCodeSize << ")" << endl;
+			DumpData(aCodeSection, aRomImgEntry->iCodeSize);
+
+			aSectionOffset = aRomImgEntry->iDataAddress - iImageHeader->iRomHdr->iRomBase;
+			TUint* aDataSection = (TUint*)((char*)iImageHeader->iRomHdr + aSectionOffset);
+			if( aRomImgEntry->iDataSize){
+				*out << "\nData (Size=0x" << hex << aRomImgEntry->iDataSize << ")" << endl;
+				DumpData(aDataSection, aRomImgEntry->iDataSize);
+			}
+		}
+	}
+
+	*out << endl << endl;
+}
+
+void RomImageReader::DumpAttribs(RomImageFSEntry* aFsEntry) {
+
+	// a larger rom image cause stack overflow under visual studio if we use recursion algorithm here.
+	// can gcc compiler guarantee this overflow will never be happen ?
+	if( aFsEntry->iChildren )
+		DumpAttribs(aFsEntry->iChildren);
+
+	if(aFsEntry->iSibling)
+		DumpAttribs(aFsEntry->iSibling);
+	if(aFsEntry->IsDirectory()) return ;
+	RomImageFileEntry* file = static_cast<RomImageFileEntry*>(aFsEntry);
+	if(!file->iExecutable) return ; 
+	TRomImageHeader* aRomImgEntry = file->ImagePtr.iRomFileEntry;
+
+	if( !aRomImgEntry)  return; 
+
+	const char* prefix ;
+	if(aRomImgEntry->iFlags & KRomImageFlagPrimary){
+		prefix = "Primary";
+	}
+	else if(aRomImgEntry->iFlags & KRomImageFlagVariant){
+		prefix = "Variant";
+	}
+	else if(aRomImgEntry->iFlags & KRomImageFlagExtension){
+		prefix = "Extension";
+	}
+	else if(aRomImgEntry->iFlags & KRomImageFlagDevice){
+		prefix = "Device";
+	}
+	else
+		return;
+
+	out->width(10);
+	out->fill(' '); 
+	*out << left << prefix;
+	out->width(40);	
+	*out << right << file->Name() << "[" ;
+	DumpInHex( "", aRomImgEntry->iHardwareVariant, true) << "] ";
+	DumpInHex( " DataSize=", (aRomImgEntry->iBssSize + aRomImgEntry->iDataSize), true) << endl;
+
+}
+
+void RomImageReader::Dump() {
+	if( !((iDisplayOptions & EXTRACT_FILES_FLAG) || 
+		(iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG) ||
+		(iDisplayOptions & EXTRACT_FILE_SET_FLAG)) ) {
+			*out << "Image Name................." << iImgFileName.c_str() << endl;
+
+			if( iImageHeader->iRomHdr )
+				iImageHeader->DumpRomHdr();
+			else
+				iImageHeader->DumpRomXHdr();
+
+			DumpAttribs(iRomImageRootDirEntry);
+			*out << endl ;
+
+			if(iDisplayOptions & DUMP_VERBOSE_FLAG) {
+				DumpDirStructure();
+				DumpTree();
+			}
+
+			if(iDisplayOptions & DUMP_DIR_ENTRIES_FLAG) {
+				DumpDirStructure();
+			}
+	}
+}
+
+
+/** 
+Function iterates through all the entries in the image 
+by making a call to TraverseImage function.
+
+@internalComponent
+@released
+*/
+void RomImageReader::ExtractImageContents() {
+	if( (iDisplayOptions & EXTRACT_FILE_SET_FLAG) ) { 
+		ImageReader::ExtractFileSet(iRomLayoutData);
+	}
+
+	if( iDisplayOptions & EXTRACT_FILES_FLAG || iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG ) {
+		if(iRomImageRootDirEntry) {
+			// name of the log file.
+			string logFile;
+			// output stream for the log file. 
+			ofstream oFile;
+
+			if( iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG){
+				if( ImageReader::iZdrivePath.compare("")){				 
+					// create specified directory.
+					CreateSpecifiedDir(ImageReader::iZdrivePath); 
+					int len = ImageReader::iZdrivePath.length() ;
+					const char* z = ImageReader::iZdrivePath.c_str();
+					logFile = "";
+					for(int i = 0 ; i < len ; i++){
+						if(z[i] == SLASH_CHAR2)
+							logFile += SLASH_CHAR1;
+						else
+							logFile += z[i];
+					}
+					len -- ;
+					if(z[len] != SLASH_CHAR1)
+						logFile += SLASH_CHAR1;
+					logFile += ImageReader::iLogFileName ;
+				}
+				else {				
+					logFile = ImageReader::iLogFileName;
+				}
+				// open the specified file in append mode.
+				oFile.open(logFile.c_str() ,ios_base::out|ios_base::app);
+
+				if(!oFile.is_open()){
+					throw ImageReaderException(ImageReader::iLogFileName.c_str(), "Failed to open the log file");
+				}
+			}
+			TraverseImage(iRomImageRootDirEntry,oFile);
+			if(oFile.is_open())  oFile.close();  
+		}
+	}
+}
+
+
+/** 
+Function to traverse entire image and check for an entity.If the entity found in the image is a file 
+then it makes a call to CheckFileExtension to check for extension.
+
+@internalComponent
+@released
+
+@param aEntity		- pointer to the entry in rom image.
+@param aFile		- output stream.
+*/
+void RomImageReader::TraverseImage(RomImageFSEntry*  aEntity,ofstream& aFile) {
+	if(!aEntity->IsDirectory())	{
+		CheckFileExtension(aEntity,aFile);
+	}
+
+	if (aEntity->iChildren)	{
+		TraverseImage(aEntity->iChildren,aFile);
+	}
+
+	if (aEntity->iSibling)	{
+		TraverseImage(aEntity->iSibling,aFile);
+	}
+}
+
+
+/** 
+Function to get check extension of the given file.If the extension of the file is "sis"
+then call ExtractFile function to extract the file from the image.  
+
+@internalComponent
+@released
+
+@param aEntity		- pointer to the entry in rom image.
+@param aFile		- output stream.
+*/
+void RomImageReader::CheckFileExtension(RomImageFSEntry*  aEntity,ofstream& aFile) {
+	RomImageFileEntry*	romEntry = (RomImageFileEntry*)aEntity;
+	// get the size of the entity.
+	TUint32 size = romEntry->iTRomEntryPtr->iSize;
+	// get the offset of the entity.
+	TUint32 offset =  romEntry->iTRomEntryPtr->iAddressLin - GetRomBase() ;
+
+	const char* fileName = aEntity->iName.c_str();
+
+	// create a string to hold the path information.
+	string romfilePath(romEntry->iPath);
+	int len = romfilePath.length();
+	char* str = const_cast<char*>(romfilePath.c_str());
+	for(int i = 0 ; i < len ; i++){
+		if(str[i] == SLASH_CHAR2)
+			str[i] = SLASH_CHAR1;
+	}
+	if(str[len - 1] != SLASH_CHAR1)
+		romfilePath += SLASH_CHAR1;
+
+	if( iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG && iDisplayOptions & EXTRACT_FILES_FLAG ) {
+		// get the position.
+		size_t pos = aEntity->iName.find_last_of(".");
+
+		const char* extName = fileName + ( pos + 1 );
+		if ( !stricmp(extName ,"SIS")	||  !stricmp(extName ,"DAT") ) {
+			// if the two strings are same then extract the corresponding file.
+			ImageReader::ExtractFile(offset,size,fileName,romfilePath.c_str(),ImageReader::iZdrivePath.c_str(),iRomLayoutData);
+		}
+		else {
+			LogRomEnrtyToFile(romfilePath.c_str(),fileName,aFile);
+		}
+	}
+	else if( iDisplayOptions & LOG_IMAGE_CONTENTS_FLAG ) {
+		LogRomEnrtyToFile(romfilePath.c_str(),fileName,aFile);
+	}
+	else {
+		if(romEntry->iExecutable) {
+			size += sizeof(TRomImageHeader);
+		}
+		// extract the corresponding file. 
+		ImageReader::ExtractFile(offset,size,fileName,romfilePath.c_str(),ImageReader::iZdrivePath.c_str(),iRomLayoutData);
+	}
+}
+
+
+/** 
+Function to log the rom entry to a specified file. 
+
+@internalComponent
+@released
+
+@param aPath		- Complete path of an entity.
+@param aEntityName	- Entity name. 
+@param aFile		- output stream.
+*/
+void RomImageReader::LogRomEnrtyToFile(const char* aPath,const char* aEntityName,ofstream& aFile) {
+	if(aFile.is_open()) {
+		aFile.seekp(0,ios_base::end);
+		aFile<<aPath <<aEntityName << endl;
+	}
+}
+
+
+/** 
+Function to read the directory structure details of te ROM image.  
+
+@internalComponent
+@released
+
+@param aEntity		- pointer to the entry in rom image.
+@param aFileMap		- map of filename with its size and offset values.
+@param aImgSize		- Image size
+*/
+void RomImageReader::ProcessDirectory(RomImageFSEntry *aEntity, FILEINFOMAP &aFileMap) {
+	if(!aEntity->IsDirectory()) { 
+
+		RomImageFileEntry*	romEntry = (RomImageFileEntry*)aEntity;
+
+		PFILEINFO fileInfo = new FILEINFO;
+
+		// get the size of the entity.
+		fileInfo->iSize = romEntry->iTRomEntryPtr->iSize;
+		// get the offset of the entity.
+		fileInfo->iOffset = (romEntry->iTRomEntryPtr->iAddressLin - GetRomBase()); 
+
+		if(romEntry->iExecutable) {
+			fileInfo->iSize += sizeof(TRomImageHeader);
+		}
+
+		if((fileInfo->iOffset + fileInfo->iSize) > iRomSize) {
+			fileInfo->iOffset = 0;
+			fileInfo->iSize = 0;
+		}
+
+		string fileName(romEntry->iPath);
+		fileName += SLASH_CHAR1;
+		fileName.append(aEntity->iName);
+		aFileMap[fileName] = fileInfo;
+	}
+
+	if (aEntity->iChildren) {
+		ProcessDirectory(aEntity->iChildren, aFileMap);
+	}
+
+	if (aEntity->iSibling) {
+		ProcessDirectory(aEntity->iSibling, aFileMap);
+	}
+}
+
+/** 
+Function to read the directory structure details of te ROM image.  
+
+@internalComponent
+@released
+
+@param aFileMap		- map of filename with its size and offset values.
+*/
+void RomImageReader::GetFileInfo(FILEINFOMAP &aFileMap) {
+	ProcessDirectory(iRomImageRootDirEntry, aFileMap);
+}
+
+/** 
+Function to get the ROM image size.
+
+@internalComponent
+@released
+*/
+TUint32 RomImageReader::GetImageSize() {
+	return iRomSize;
+}
+
--- a/imgtools/romtools/rofsbuild/r_build.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rofsbuild/r_build.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,1415 +1,1313 @@
-/*
-* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent * @released
-*
-*/
-
-
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-#include <e32std.h>
-#include <e32std_private.h>
-#include <e32rom.h>
-#include <u32std.h>
-#include <e32uid.h>
-#include <f32file.h>
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-	#include <iomanip>
-	#include <strstream>
-#else //!__MSVCDOTNET__
-	#include <iomanip.h>
-#endif //__MSVCDOTNET__
-
-#ifdef _L
-#undef _L
-#endif
-
-#include "h_utl.h"
-#include "r_obey.h"
-#include "rofs.h"
-#include "e32image.h"
-#include "patchdataprocessor.h"
-
-extern TUint checkSum(const void* aPtr);
-
-extern ECompression gCompress;
-extern TUint gCompressionMethod;
-extern TInt  gCodePagingOverride;
-extern TInt  gDataPagingOverride;
-extern TInt  gLogLevel;
-TBool gDriveImage=EFalse;	// for drive image support.
-
-
-TInt TRomNode::Count=0;
-TRomNode* TRomNode::TheFirstNode = NULL;
-TRomNode* TRomNode::TheLastNode = NULL;
-
-// introduced for data drive files' attribute
-TUint8 TRomNode::sDefaultInitialAttr = (TUint8)KEntryAttReadOnly;
-
-struct SortableEntry
-	{
-	TRofsEntry* iEntry;
-	TBool iIsDir;
-	TUint16 iOffset;
-	};
-
-int compare(const void* l, const void* r)
-	{
-	const SortableEntry* left  = (const SortableEntry*)l;
-	const SortableEntry* right = (const SortableEntry*)r;
-	if (left->iIsDir)
-		{
-		if (!right->iIsDir)
-			return -1;	// dir < file
-		}
-	else
-		{
-		if (right->iIsDir)
-			return +1;	// file > dir
-		}
-
-	// both the same type of entry, sort by name
-	// must first convert to an 8 bit string
-	// array and NULL terminate it.
-	char temp1[500];
-	char temp2[500];
-
-
-TInt i=0;
-	for (i = 0; i < left->iEntry->iNameLength; i++)
-		{
-		temp1[i]=(char) left->iEntry->iName[i];
-		}
-	temp1[i]=0;
-
-	for (i = 0; i < right->iEntry->iNameLength; i++)
-		{
-		temp2[i]=(char) right->iEntry->iName[i];
-		}
-	temp2[i]=0;
-
-	return stricmp((const char*)&temp1[0], (const char*)&temp2[0]);
-	}
-
-TRomNode::TRomNode(TText* aName, TRomBuilderEntry* aEntry)
-//
-// Constructor
-//
-	:
-	iNextNode(NULL),
-	iParent(NULL), iSibling(0), iChild(0), iNextNodeForSameFile(0), 
-	iTotalDirectoryBlockSize(0),
-	iTotalFileBlockSize(0),
-	iImagePosition(0),
-	iFileBlockPosition(0),
-	iAtt(sDefaultInitialAttr),
-	iAttExtra(0xFF),
-	iHidden(EFalse),
-	iEntry(aEntry),
-	iFileStartOffset(0), 
-	iSize(0), 
-	iOverride(0),
-	iFileUpdate(EFalse),
-    iAlias(false)
-	{
-	iName = (TText*)NormaliseFileName((const char*)aName);
-	iIdentifier=TRomNode::Count++;
-
-	// Add this node to the flat linked list
-	if( !TheFirstNode )
-		{
-		TheFirstNode = this;
-		}
-	else
-		{
-		TheLastNode->iNextNode = this;
-		}
-	TheLastNode = this;
-
-	if (iEntry)
-		{
-		iEntry->SetRomNode(this);
-		}
-	else
-		{
-		iAtt = (TUint8)KEntryAttDir;
-		}
-	}
-
-TRomNode::~TRomNode()
-	{
-	if (iEntry && !iAlias)
-        {
-		delete iEntry;
-        }
-    iEntry = 0;
-	if(iName)
-		free(iName);
-    iName = 0;
-	}
-
-TRomNode *TRomNode::FindInDirectory(TText *aName)
-//
-// Check if the TRomNode for aName exists in aDir, and if so, return it.
-//
-	{
-
-	TRomNode *entry=iChild; // first subdirectory or file
-	while (entry)
-		{
-		if ((stricmp((const char *)aName, (const char *)entry->iName))==0) 
-			return entry;
-		else
-			entry=entry->iSibling;
-		}
-	return 0;
-	}
-
-
-
-TInt indend = 0;
-
-void indendStructure(TInt i)
-       {
-	while(i > 0)
-	   {
-	     cout << "    ";
-	     i--;
-	   }
-       };  
-
-// displays the directory structure
-void TRomNode::DisplayStructure(ostream* aOut)
-	{
-	  indendStructure(indend);
-      *aOut  << iName << "\n";
-	  if (iChild)
-	    {
-	      indend++; 
-	      iChild->DisplayStructure(aOut);
-	      indend--;
-	    }
-	  if (iSibling)
-	    iSibling->DisplayStructure(aOut);
-	}
-
-
-void TRomNode::deleteTheFirstNode()
-{
-
-	TheFirstNode = NULL;
-}
-
-
-void TRomNode::InitializeCount()
-{
-	Count = 0;
-}
-void TRomNode::displayFlatList()
-{
-	TRomNode* current =	TheFirstNode;
-	TInt i = 0;
-	while(current)
-	{
-		i++;
-		cout <<  "\n" << i <<": " << current->iName << endl;
-		current = current->NextNode();
-	}
-
-	}
-
-
-
-void TRomNode::AddFile(TRomNode* aChild)
-	{
-	if (iEntry)
-		{
-		Print(EError, "Adding subdirectory to a file!!!\n");
-		return;
-		}
-	Add(aChild);
-	}
-
-TRomNode* TRomNode::NewSubDir(TText *aName)
-	{
-	if (iEntry)
-		{
-		Print(EError, "Adding subdirectory to a file!!!\n");
-		return 0;
-		}
-
-	TRomNode* node = new TRomNode(aName );
-	if (node==0)
-		{
-		Print(EError, "TRomNode::NewNode: Out of memory\n");
-		return 0;
-		}
-	node->iParent = this;
-	Add(node);
-	return node;
-	}
-
-void TRomNode::Add(TRomNode* aChild)
-	{
-	if (iChild) // this node is a non-empty directory
-		{
-		TRomNode* dir = iChild; // find where to link in the new node
-		while (dir->iSibling)
-			dir = dir->iSibling;
-		dir->iSibling = aChild;
-		}
-	else
-		iChild = aChild; // else just set it up as the child of the dir
-	aChild->iSibling = 0;
-	aChild->iParent = this;
-	}
-
-TInt TRomNode::SetAttExtra(TText *anAttWord, TRomBuilderEntry* aFile, enum EKeyword aKeyword)
-//
-// Set the file extra attribute byte from the letters passed
-// Note: The iAttExtra bits are inverted. '0' represent enabled
-//
-	{
-	iAttExtra=0xFF;
-	if (anAttWord==0 || anAttWord[0]=='\0')
-		return Print(EError, "Missing argument for keyword 'exattrib'.\n");
-	for (TText *letter=anAttWord;*letter!=0;letter++)
-		{
-		switch (*letter)
-			{
-		case 'u':
-			iAttExtra |= (KEntryAttUnique >> 23);	// '1' represents disabled in iAttExtra
-			break;
-		case 'U':
-			iAttExtra &= ~(KEntryAttUnique >> 23);	// '0' represent enabled in iAttExtra
-			break;
-		default:
-			return Print(EError, "Unrecognised exattrib - '%c'.\n", *letter);
-			break;
-			}
-		}
-
-	if((~iAttExtra & (KEntryAttUnique >> 23))!=0)	// If the unique file attribute is set
-		{
-		if(aKeyword==EKeywordFile || aKeyword==EKeywordData)	// If the Keyword is File or Data
-			{
-				if(strlen(aFile->iFileName) > (KMaxFileName-KRofsMangleNameLength)) // check whether we have enough space to add the mangle tage
-					return Print(EError, "Lengthy filename with unique attribute to name mangle.\n");
-			}
-		else	// for all other keywords
-			return Print(EError, "exattrib field not allowed for entries except data and file.\n");
-		}
-	return KErrNone;
-	}
-
-
-TInt TRomNode::SetAtt(TText *anAttWord)
-//
-// Set the file attribute byte from the letters passed
-//
-	{
-	iAtt=0;
-	if (anAttWord==0 || anAttWord[0]=='\0')
-		return Print(EError, "Missing argument for keyword 'attrib'.\n");
-	for (TText *letter=anAttWord;*letter!=0;letter++)
-		{
-		switch (*letter)
-			{
-		case 'R':
-		case 'w':
-			iAtt |= KEntryAttReadOnly;
-			break;
-		case 'r':
-		case 'W':
-			iAtt &= ~KEntryAttReadOnly;
-			break;
-		case 'H':
-			iAtt |= KEntryAttHidden;
-			break;
-		case 'h':
-			iAtt &= ~KEntryAttHidden;
-			break;
-		case 'S':
-			iAtt |= KEntryAttSystem;
-			break;
-		case 's':
-			iAtt &= ~KEntryAttSystem;
-			break;
-		default:
-			return Print(EError, "Unrecognised attrib - '%c'.\n", *letter);
-			break;
-			}
-		}
-	return KErrNone;
-	}
-
-
-
-TInt TRomNode::CalculateEntrySize() const
-	// Calculates the amount of ROM space required to hold
-	// this entry. The return is the actual size of the TRofsEntry
-	// structure, not rounded up
-	{
-	TInt requiredSizeBytes = KRofsEntryHeaderSize +	NameLengthUnicode();
-	return requiredSizeBytes;
-	}
-
-TInt TRomNode::CalculateDirectoryEntrySize( TInt& aDirectoryBlockSize,
-										    TInt& aFileBlockSize )
-	// Calculates the total size of the TRofsDir structure required
-	// for this directory and the size of the files block. Traverses all the
-	// children adding their entry sizes. The result is not rounded up.
-	//
-	// On return aDirectoryBlockSize is the number of bytes required for the
-	//	main directory structure. aFileBlockSize is the number of bytes
-	//	required to hold the list of files.
-	//
-	// Returns KErrNone on success
-	{
-
-	TInt offsetBytes=0;
-	TInt padBytes=0;
-	if( 0 == iTotalDirectoryBlockSize )
-		{
-		// need to calculate by walking children	
-		if( !iChild )
-			{
-			return Print(EError, "TRomNode structure corrupt\n");
-			}
-
-		TInt dirBlockSize = KRofsDirHeaderSize;
-		TInt fileBlockSize = 0;
-		TInt fileCount=0;
-		TInt dirCount=0;
-
-		TRomNode* node = iChild;
-		while (node)
-			{
-			TInt entrySize = node->CalculateEntrySize();
-			if( node->IsDirectory() )
-				{
-				dirBlockSize += (4 - dirBlockSize) & 3;	// pad to next word boundary
-				dirBlockSize += entrySize;
-				dirCount++;
-				}
-			else
-				{
-				fileBlockSize += (4 - fileBlockSize) & 3;	// pad to next word boundary
-				fileBlockSize += entrySize;
-				fileCount++;
-				}
-			node = node->iSibling;
-			}
-		
-		offsetBytes = ((fileCount + dirCount) * 2) + 4; //the +4 are the two offset counts,
-		padBytes = offsetBytes % 4;
-
-		iTotalDirectoryBlockSize = dirBlockSize;
-		iTotalFileBlockSize = fileBlockSize;
-		}
-
-	aDirectoryBlockSize = iTotalDirectoryBlockSize + offsetBytes + padBytes;
-	aFileBlockSize = iTotalFileBlockSize;
-	return KErrNone;
-	}
-
-/**
-Place the files and it's attributes (incase of executables)
-Called for both rofs and datadrive creation.
- 
-@param aDest   - Destination buffer.
-@param aOffset - offset value, used for rofs only.
-@param aMaxSize- Maximum size required for rofs.
-  
-@return - Returns the number of bytes placed or a -ve error code.
-*/ 
-TInt TRomNode::PlaceFile( TUint8* &aDest, TUint aOffset, TUint aMaxSize, CBytePair *aBPE )
-	//
-	// Place the file into the ROM image, making any necessary conversions
-	// along the way.
-	//
-	// Returns the number of bytes placed or a -ve error code.
-	{
-
-	TInt size=0;
-	
-	// file hasn't been placed for drive image. 
-	if(gDriveImage)
-	{
-		size = iEntry->PlaceFile(aDest,aMaxSize,aBPE);
-		iSize = size;
-	}
-	else
-	{
-		if (iEntry->iHidden)
-			iFileStartOffset = KFileHidden;
-		else
-		{
-                    if (iEntry->iFileOffset==0)
-                    {
-                        // file hasn't been placed
-                        size = iEntry->PlaceFile( aDest, aMaxSize, aBPE );
-                        if (size>=0)
-                            iEntry->iFileOffset = aOffset;
-                    }
-                    else {
-                        iFileStartOffset = (TInt)iEntry;
-                    }
-		}
-	}
-
-	// Deal with any override attributes
-	// (omit paging overrides as these are dealt with in TRomBuilderEntry::PlaceFile
-	//  and may also be legitimately specified for non-executable files in ROM)
-	if( iOverride&~(KOverrideCodeUnpaged|KOverrideCodePaged|KOverrideDataUnpaged|KOverrideDataPaged) )
-		{
-		E32ImageHeaderV* hdr = (E32ImageHeaderV*)aDest;
-
-		TUint hdrfmt = hdr->HeaderFormat();
-		if (hdrfmt != KImageHdrFmt_V)
-			{
-			Print(EError,"%s: Can't load old format binary\n", iEntry->iFileName);
-			return KErrNotSupported;
-			}
-		
-		// First need to check that it's a real image header
-		if( (TUint)size > sizeof(E32ImageHeader) )
-			{
-			if( ((TInt)hdr->iSignature == 0x434f5045u) && ((TInt)hdr->iUid1 == KExecutableImageUidValue || (TInt)hdr->iUid1 == KDynamicLibraryUidValue) )
-				{
-				// Should check the CRC as well here...
-				// Something for later
-
-				// Ok, it looks like an image header
-				if( iOverride & KOverrideStack )
-					{
-					hdr->iStackSize = iStackSize;
-					}
-				if( iOverride & KOverrideHeapMin )
-					{
-					hdr->iHeapSizeMin = iHeapSizeMin;
-					}
-				if( iOverride & KOverrideHeapMax )
-					{
-					hdr->iHeapSizeMax = iHeapSizeMax;
-					}
-				if( iOverride & KOverrideFixed )
-					{
-					if( hdr->iFlags & KImageDll )
-						{
-						Print(EError,"%s: Can't used FIXED keyword on a DLL\n", iEntry->iFileName);
-						return KErrNotSupported;
-						}
-					hdr->iFlags |= KImageFixedAddressExe;
-					}
-				if( iOverride & (KOverrideUid1|KOverrideUid2|KOverrideUid3))
-					{
-					if (iOverride & KOverrideUid1)
-						{
-						hdr->iUid1 = iUid1;
-						}
-					if (iOverride & KOverrideUid2)
-						{
-						hdr->iUid2 = iUid2;
-						}
-					if (iOverride & KOverrideUid3)
-						{
-						hdr->iUid3 = iUid3;
-						}
-					// Need to re-checksum the UIDs
-					TUidType ut(TUidType(TUid::Uid(hdr->iUid1), TUid::Uid(hdr->iUid2), TUid::Uid(hdr->iUid3)));
-					hdr->iUidChecksum =  (checkSum(((TUint8*)&ut)+1)<<16)|checkSum(&ut);
-					}
-				if( iOverride & KOverridePriority )
-					{
-					hdr->iProcessPriority = (TUint16)iPriority;
-					}
-				if( iOverride & KOverrideCapability )
-					{
-					hdr->iS.iCaps = iCapability;
-					}
-
-				// Need to re-CRC the header
-				hdr->iHeaderCrc = KImageCrcInitialiser;
-				TUint32 crc = 0;
-				TInt hdrsz = hdr->TotalSize();
-				HMem::Crc32(crc, hdr, hdrsz);
-				hdr->iHeaderCrc = crc;
-				}
-			}
-		}
-
-	return size;
-	}
-
-TInt TRomNode::CountFileAndDir(TInt& aFileCount, TInt& aDirCount)
-	{
-	//
-	// Count the number of file and directory entries for this node
-	//
-	TRomNode* node = iChild;
-
-	aFileCount=0;
-	aDirCount=0;
-	while( node )
-		{
-		if( node->IsFile() )
-			{
-			aFileCount++;
-			}
-		else
-			{
-			aDirCount++;
-			}
-
-		node = node->iSibling;
-		}
-	return KErrNone;
-	}
-
-TInt TRomNode::Place( TUint8* aDestBase )
-	//
-	// Writes this directory entry out to the image.
-	// The image starts at aDestBase.
-	// The position in the image must already have been set with SetImagePosition()
-	// and SetFileBlockPosition().
-	// Returns KErrNone on success
-	//
-	{
-	TUint8* dirBlockBase = aDestBase + iImagePosition;
-	TUint8* fileBlockBase = aDestBase + iFileBlockPosition;
-
-	TRofsDir* pDir = (TRofsDir*)dirBlockBase;
-	pDir->iFirstEntryOffset = KRofsDirFirstEntryOffset;
-	pDir->iFileBlockAddress = iFileBlockPosition;
-	pDir->iFileBlockSize = iTotalFileBlockSize;
-	pDir->iStructSize = (TUint16)iTotalDirectoryBlockSize;
-
-	TRofsEntry* pDirEntry = &(pDir->iSubDir);
-	TRofsEntry* pFileEntry = (TRofsEntry*)fileBlockBase;
-
-	TInt dirCount;
-	TInt fileCount;
-	TInt index = 0;
-	CountFileAndDir(fileCount, dirCount);
-
-	SortableEntry* array = new SortableEntry[fileCount + dirCount];
-	TRomNode* node = iChild;
-
-	while( node )
-		{
-		TRofsEntry* entry;
-
-		if( node->IsFile() )
-			{
-			entry = pFileEntry;
-
-			//Offset in 32bit words from start of file block
-			array[index].iOffset = (TUint16) ((((TUint8*) entry) - fileBlockBase) >> 2);
-			array[index].iIsDir = EFalse;
-			}
-		else
-			{
-			entry = pDirEntry;
-
-			//Offset in 32bit words from start of directory block
-			array[index].iOffset = (TUint16) ((((TUint8*) entry) - dirBlockBase) >> 2);
-			array[index].iIsDir = ETrue;
-			}
-		array[index].iEntry = entry;
-		index++;
-
-		entry->iNameOffset = KRofsEntryNameOffset;
-		entry->iAtt = node->iAtt;
-		entry->iAttExtra = node->iAttExtra;
-
-		TInt entryLen = KRofsEntryHeaderSize;
-		entryLen += node->NameCpy( (char*)&entry->iName, entry->iNameLength );
-		entryLen += (4 - entryLen) & 3;	// round up to nearest word
-		entry->iStructSize = (TUint16)entryLen;
-
-
-		if( node->IsFile() )
-			{
-			// node is a file, entry points to the file
-			// write an entry out into the file block
-			pFileEntry->iFileAddress = node->iFileStartOffset;
-			node->iAtt &= ~KEntryAttDir;
-			pFileEntry->iFileSize = node->iEntry->RealFileSize();
-			memcpy(&pFileEntry->iUids[0], &node->iEntry->iUids[0], sizeof(pFileEntry->iUids));
-			pFileEntry = (TRofsEntry*)( (TUint8*)pFileEntry + entryLen );
-			}
-		else
-			{
-			// node is a subdirectory, entry points to directory
-			pDirEntry->iFileAddress = node->iImagePosition;
-			node->iAtt |= KEntryAttDir;
-			
-			// the size is just the size of the directory block
-			pDirEntry->iFileSize = node->iTotalDirectoryBlockSize;
-			pDirEntry = (TRofsEntry*)( (TUint8*)pDirEntry + entryLen );
-			}
-
-		node = node->iSibling;
-		}
-
-	qsort(array,fileCount + dirCount,sizeof(SortableEntry),&compare);
-
-	//Now copy the contents of sorted array to the image
-	TUint16* currentPtr = (TUint16*) (dirBlockBase + iTotalDirectoryBlockSize);
-
-	*currentPtr=(TUint16)dirCount;
-	currentPtr++;
-	*currentPtr=(TUint16)fileCount;
-	currentPtr++;
-
-	for (index = 0; index < (fileCount + dirCount); index++)
-		{
-		*currentPtr = array[index].iOffset;
-		currentPtr++;
-		}
-	delete[] array;
-	return KErrNone;
-	}
-
-
-
-void TRomNode::Remove(TRomNode* aChild)
-	{
-	if (iChild==0)
-		{
-		Print(EError, "Removing file from a file!!!\n");
-		return;
-		}
-	if (iChild==aChild) // first child in this directory
-		{
-		iChild = aChild->iSibling;
-		aChild->iSibling = 0;
-		if(iChild==0)
-			{
-				iParent->Remove(this);
-				TRomNode * current = TheFirstNode;
-				TRomNode * prev = current;
-				while(current != this)
-					{
-						prev = current;
-						current = current->NextNode();
-					}
-				prev->SetNextNode(current->NextNode());
-				delete this;
-			}
-		return;
-		}
-	TRomNode* prev = iChild;
-	while (prev->iSibling && prev->iSibling != aChild)
-		prev = prev->iSibling;
-	if (prev==0)
-		{
-		Print(EError, "Attempting to remove file not in this directory!!!\n");
-		return;
-		}
-	prev->iSibling = aChild->iSibling;
-	aChild->iSibling = 0;
-	}
-
-void TRomNode::CountDirectory(TInt& aFileCount, TInt& aDirCount)
-	{
-	TRomNode *current=iChild;
-	while(current)
-		{
-		if (current->iChild)
-			aDirCount++;
-		else
- 			aFileCount++;
-	current=current->iSibling;
-		}
-	}
-
- void TRomNode::Destroy()
-//
-// Follow the TRomNode tree, destroying it
-//
-	{
-
- 	TRomNode *current = this; // root has no siblings
-	while (current)
-		{
-		if (current->iChild)
-			current->iChild->Destroy();
-		TRomNode* prev=current;
-		current=current->iSibling;
-		delete prev;
-        prev = 0;
-		}
- 	}
-
-
-
-
-TInt TRomNode::NameCpy(char* aDest, TUint8& aUnicodeLength )
-//
-// Safely copy a file name in the rom entry
-// Returns the number of bytes used. Write the length in unicode characters
-// into aUnicodeLength.
-//
-	{
-
-	if ((aDest==NULL) || (iName==NULL))
-		return 0;
-	const unsigned char* pSourceByte = (const unsigned char*)iName;
-	unsigned char* pTargetByte=(unsigned char*)aDest;
-	for (;;)
-		{
-		const TUint sourceByte=*pSourceByte;
-		if (sourceByte==0)
-			{
-			break;
-			}
-		if ((sourceByte&0x80)==0)
-			{
-			*pTargetByte=(unsigned char)sourceByte;
-			++pTargetByte;
-			*pTargetByte=0;
-			++pTargetByte;
-			++pSourceByte;
-			}
-		else if ((sourceByte&0xe0)==0xc0)
-			{
-			++pSourceByte;
-			const TUint secondSourceByte=*pSourceByte;
-			if ((secondSourceByte&0xc0)!=0x80)
-				{
-				Print(EError, "Bad UTF-8 '%s'", iName);
-				exit(671);
-				}
-			*pTargetByte=(unsigned char)((secondSourceByte&0x3f)|((sourceByte&0x03)<<6));
-			++pTargetByte;
-			*pTargetByte=(unsigned char)((sourceByte>>2)&0x07);
-			++pTargetByte;
-			++pSourceByte;
-			}
-		else if ((sourceByte&0xf0)==0xe0)
-			{
-			++pSourceByte;
-			const TUint secondSourceByte=*pSourceByte;
-			if ((secondSourceByte&0xc0)!=0x80)
-				{
-				Print(EError, "Bad UTF-8 '%s'", iName);
-				exit(672);
-				}
-			++pSourceByte;
-			const TUint thirdSourceByte=*pSourceByte;
-			if ((thirdSourceByte&0xc0)!=0x80)
-				{
-				Print(EError, "Bad UTF-8 '%s'", iName);
-				exit(673);
-				}
-			*pTargetByte=(unsigned char)((thirdSourceByte&0x3f)|((secondSourceByte&0x03)<<6));
-			++pTargetByte;
-			*pTargetByte=(unsigned char)(((secondSourceByte>>2)&0x0f)|((sourceByte&0x0f)<<4));
-			++pTargetByte;
-			++pSourceByte;
-			}
-		else
-			{
-			Print(EError, "Bad UTF-8 '%s'", iName);
-			exit(674);
-			}
-		}
-	const TInt numberOfBytesInTarget=(pTargetByte-(unsigned char*)aDest); // this number excludes the trailing null-terminator
-	if (numberOfBytesInTarget%2!=0)
-		{
-		Print(EError, "Internal error");
-		exit(675);
-		}
-	aUnicodeLength = (TUint8)(numberOfBytesInTarget/2); // returns the length of aDest (in UTF-16 characters for Unicode, not bytes)
-	return numberOfBytesInTarget;
-	}
-
-
-TInt TRomNode::NameLengthUnicode() const
-//
-// Find the unicode lenght of the name
-//
-	{
-
-	if (iName==NULL)
-		return 0;
-
-	const unsigned char* pSourceByte = (const unsigned char*)iName;
-	TInt len = 0;
-	for (;;)
-		{
-		const TUint sourceByte=*pSourceByte;
-		if (sourceByte==0)
-			{
-			break;
-			}
-		if ((sourceByte&0x80)==0)
-			{
-			len += 2;
-			++pSourceByte;
-			}
-		else if ((sourceByte&0xe0)==0xc0)
-			{
-			++pSourceByte;
-			const TUint secondSourceByte=*pSourceByte;
-			if ((secondSourceByte&0xc0)!=0x80)
-				{
-				Print(EError, "Bad UTF-8 '%s'", iName);
-				exit(671);
-				}
-			len += 2;
-			++pSourceByte;
-			}
-		else if ((sourceByte&0xf0)==0xe0)
-			{
-			++pSourceByte;
-			const TUint secondSourceByte=*pSourceByte;
-			if ((secondSourceByte&0xc0)!=0x80)
-				{
-				Print(EError, "Bad UTF-8 '%s'", iName);
-				exit(672);
-				}
-			++pSourceByte;
-			const TUint thirdSourceByte=*pSourceByte;
-			if ((thirdSourceByte&0xc0)!=0x80)
-				{
-				Print(EError, "Bad UTF-8 '%s'", iName);
-				exit(673);
-				}
-			len += 2;
-			++pSourceByte;
-			}
-		else
-			{
-			Print(EError, "Bad UTF-8 '%s'", iName);
-			exit(674);
-			}
-		}
-	return len;
-	}
-
-
-void TRomNode::AddNodeForSameFile(TRomNode* aPreviousNode, TRomBuilderEntry* aFile)
-	{
-	// sanity checking
-	if (iNextNodeForSameFile != 0 || iEntry != aFile || (aPreviousNode && aPreviousNode->iEntry != iEntry))
-		{
-		Print(EError, "Adding Node for same file: TRomNode structure corrupted\n");
-		exit(666);
-		}
-	iNextNodeForSameFile = aPreviousNode;
-	}
-
-
-
-
-
-//**************************************
-// TRomBuilderEntry
-//**************************************
-
-
-
-TRomBuilderEntry::TRomBuilderEntry(const char *aFileName,TText *aName)
-//
-// Constructor
-//
-:iFirstDllDataEntry(0),	iName(0),iFileName(0),iNext(0), iNextInArea(0),
-iExecutable(EFalse), iFileOffset(EFalse), iCompressEnabled(0),
-iHidden(0), iRomNode(0), iRealFileSize(0)		 
-{
-	if (aFileName)
-   		iFileName = NormaliseFileName(aFileName);
-	if (aName)
-		iName = (TText*)NormaliseFileName((const char*)aName);
-	memset(iUids,0 ,sizeof(TCheckedUid));
-}
-	
-TRomBuilderEntry::~TRomBuilderEntry()
-//
-// Destructor
-//
-	{
-	if(iFileName)
-	{
-	free(iFileName);
-	}
-	iFileName = 0;
-	if(iName)
-	{
-	free(iName);
-	}
-	}
-
-void TRomBuilderEntry::SetRomNode(TRomNode* aNode)
-	{
-	aNode->AddNodeForSameFile(iRomNode, this);
-	iRomNode = aNode;
-	}
-
-
-TInt isNumber(TText *aString)
-	{
-	if (aString==NULL)
-		return 0;
-	if (strlen((char *)aString)==0)
-		return 0;
-	return isdigit(aString[0]);
-	}
-
-TInt getNumber(TText *aStr)
-	{
-	TUint a;
-	#ifdef __TOOLS2__
-	istringstream val((char *)aStr);
-	#else
-	istrstream val((char *)aStr,strlen((char *)aStr));
-	#endif
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-	val >> setbase(0);
-#endif //__MSVCDOTNET__
-
-	val >> a;
-	return a;
-	}
-
-
-TInt TRomBuilderEntry::PlaceFile( TUint8* &aDest,TUint aMaxSize, CBytePair *aBPE )
-	//
-	// Place the file in ROM. Since we don't support compression yet all
-	// we have to do is read the file into memory
-	// compress it, if it isn't already compressed.
-	//
-	// Returns the number of bytes used, or -ve error code
-	{
-	TUint compression = 0;
-	TBool executable = iExecutable;
-	Print(ELog,"Reading file %s to image\n", iFileName );
-	TUint32 size=HFile::GetLength((TText*)iFileName);
-	if (size==0)
-		Print(EWarning, "File %s does not exist or is 0 bytes in length.\n",iFileName);
-        if (aDest == NULL) {
-            aMaxSize = size*2;
-            aMaxSize = (aMaxSize>0) ? aMaxSize : 2;
-            aDest = new TUint8[aMaxSize];
-        }
-
-	if (executable)
-		{
-		// indicate if the image will overflow without compression
-	TBool overflow;
-			if(size>aMaxSize)
-			overflow = ETrue;
-		else
-			overflow = EFalse;
-
-		// try to compress this executable
-		E32ImageFile f(aBPE);
-		TInt r = f.Open(iFileName);
-		// is it really a valid E32ImageFile?
-		if (r != KErrNone)
-			{
-			Print(EWarning, "File '%s' is not a valid executable.  Placing file as data.\n", iFileName);
-			executable = EFalse;
-			}
-		else
-			{
-
-			if(iRomNode->iOverride & KOverrideDllData)
-			{
-				DllDataEntry *aDllEntry = iRomNode->iEntry->GetFirstDllDataEntry();
-				TLinAddr* aExportTbl;
-				void *aLocation;
-				TUint aDataAddr;
-				char *aCodeSeg, *aDataSeg;
-
-				aExportTbl = (TLinAddr*)((char*)f.iData + f.iOrigHdr->iExportDirOffset);
-
-				// const data symbol may belong in the Code section. If the address lies within the Code or data section limits, 
-				// get the corresponding location and update it.While considering the Data section limits
-				// don't include the Bss section, as it doesn't exist as yet in the image.
-				while( aDllEntry ){
-					if(aDllEntry->iOrdinal != (TUint32)-1){
-						if(aDllEntry->iOrdinal < 1 || aDllEntry->iOrdinal > (TUint)f.iOrigHdr->iExportDirCount){
-							Print(EWarning, "Invalid ordinal %d specified for DLL %s\n", aDllEntry->iOrdinal, iRomNode->iName);
-							aDllEntry = aDllEntry->NextDllDataEntry();
-							continue;
-						}
-					
-				//	Get the address of the data field via the export table.
-					aDataAddr = (TInt32)(aExportTbl[aDllEntry->iOrdinal - 1] + aDllEntry->iOffset);
-					if( aDataAddr >= f.iOrigHdr->iCodeBase && aDataAddr <= (f.iOrigHdr->iCodeBase + f.iOrigHdr->iCodeSize)){
-						aCodeSeg = (char*)(f.iData + f.iOrigHdr->iCodeOffset);
-						aLocation = (void*)(aCodeSeg + aDataAddr - f.iOrigHdr->iCodeBase );
-						memcpy(aLocation, &aDllEntry->iNewValue, aDllEntry->iSize);
-					}
-					else if(aDataAddr >= f.iOrigHdr->iDataBase && aDataAddr <= (f.iOrigHdr->iDataBase + f.iOrigHdr->iDataSize)){
-						aDataSeg = (char*)(f.iData + f.iOrigHdr->iDataOffset);
-						aLocation = (void*)(aDataSeg + aDataAddr - f.iOrigHdr->iDataBase );
-						memcpy(aLocation, &aDllEntry->iNewValue, aDllEntry->iSize);
-					}
-					else
-					{
-						Print(EWarning, "Patchdata failed as address pointed by ordinal %d of DLL %s doesn't lie within Code or Data section limits\n", aDllEntry->iOrdinal, iRomNode->iName);
-					}
-					}
-					else if(aDllEntry->iDataAddress != (TLinAddr)-1){
-						aDataAddr = aDllEntry->iDataAddress + aDllEntry->iOffset;
-					if( aDataAddr >= f.iOrigHdr->iCodeBase && aDataAddr <= (f.iOrigHdr->iCodeBase + f.iOrigHdr->iCodeSize)){
-						aCodeSeg = (char*)(f.iData + f.iOrigHdr->iCodeOffset);
-						aLocation = (void*)(aCodeSeg + aDataAddr - f.iOrigHdr->iCodeBase );
-						memcpy(aLocation, &aDllEntry->iNewValue, aDllEntry->iSize);
-					}
-					else if(aDataAddr >= f.iOrigHdr->iDataBase && aDataAddr <= (f.iOrigHdr->iDataBase + f.iOrigHdr->iDataSize)){
-						aDataSeg = (char*)(f.iData + f.iOrigHdr->iDataOffset);
-						aLocation = (void*)(aDataSeg + aDataAddr - f.iOrigHdr->iDataBase );
-						memcpy(aLocation, &aDllEntry->iNewValue, aDllEntry->iSize);
-					}
-					else
-					{
-						Print(EWarning, "Patchdata failed as address 0x%x of DLL %s doesn't lie within Code or Data section limits\n", aDllEntry->iOrdinal, iRomNode->iName);
-					}
-					}
-					aDllEntry = aDllEntry->NextDllDataEntry();
-					}
-			}
-
-			compression = f.iHdr->CompressionType();
-			Print(ELog,"Original file:'%s' is compressed by method:%08x\n", iFileName, compression);
-
-
-			TUint32 oldFileComp;
-			TUint32 newFileComp;
-
-			if(compression)
-			{
-				// The E32 image in release directory is compressed
-				oldFileComp = compression;
-			}
-			else
-			{
-				// The E32 image in release directory is uncompressed
-				oldFileComp = 0;
-			}
-
-			if( iCompressEnabled != ECompressionUnknown)
-			{
-				// The new state would be as stated in obey file, i.e. 
-				// filecompress or fileuncompress
-				newFileComp = gCompressionMethod;
-			}
-			else if (gCompress != ECompressionUnknown)
-			{
-				// The new state would be as stated set globally
-				newFileComp = gCompressionMethod;
-			}
-			else
-			{
-				// When not known if compression is to be applied or not,
-				// set it same as that of the E32 image in release directory
-				newFileComp = oldFileComp;
-			}
-
-			if(!gDriveImage)
-			{
-				// overide paging flags...
-				E32ImageHeaderV* h=f.iHdr;
-				if (iRomNode->iOverride & KOverrideCodePaged)
-					{
-					h->iFlags &= ~KImageCodeUnpaged;
-					h->iFlags |= KImageCodePaged;
-					}
-				if (iRomNode->iOverride & KOverrideCodeUnpaged)
-					{
-					h->iFlags |= KImageCodeUnpaged;
-					h->iFlags &= ~KImageCodePaged;
-					}
-				if (iRomNode->iOverride & KOverrideDataPaged)
-					{
-					h->iFlags &= ~KImageDataUnpaged;
-					h->iFlags |= KImageDataPaged;
-					}
-				if (iRomNode->iOverride & KOverrideDataUnpaged)
-					{
-					h->iFlags |= KImageDataUnpaged;
-					h->iFlags &= ~KImageDataPaged;
-					}
-
-				// apply global paging override...
-				switch(gCodePagingOverride)
-					{
-				case EKernelConfigPagingPolicyNoPaging:
-					h->iFlags |= KImageCodeUnpaged;
-					h->iFlags &= ~KImageCodePaged;
-					break;
-				case EKernelConfigPagingPolicyAlwaysPage:
-					h->iFlags |= KImageCodePaged;
-					h->iFlags &= ~KImageCodeUnpaged;
-					break;
-				case EKernelConfigPagingPolicyDefaultUnpaged:
-					if(!(h->iFlags&(KImageCodeUnpaged|KImageCodePaged)))
-						h->iFlags |= KImageCodeUnpaged;
-					break;
-				case EKernelConfigPagingPolicyDefaultPaged:
-					if(!(h->iFlags&(KImageCodeUnpaged|KImageCodePaged)))
-						h->iFlags |= KImageCodePaged;
-					break;
-					}
-				switch(gDataPagingOverride)
-					{
-				case EKernelConfigPagingPolicyNoPaging:
-					h->iFlags |= KImageDataUnpaged;
-					h->iFlags &= ~KImageDataPaged;
-					break;
-				case EKernelConfigPagingPolicyAlwaysPage:
-					h->iFlags |= KImageDataPaged;
-					h->iFlags &= ~KImageDataUnpaged;
-					break;
-				case EKernelConfigPagingPolicyDefaultUnpaged:
-					if(!(h->iFlags&(KImageDataUnpaged|KImageDataPaged)))
-						h->iFlags |= KImageDataUnpaged;
-					break;
-				case EKernelConfigPagingPolicyDefaultPaged:
-					if(!(h->iFlags&(KImageDataUnpaged|KImageDataPaged)))
-						h->iFlags |= KImageDataPaged;
-					break;
-					}
-				f.UpdateHeaderCrc();
-
-				// make sure paged code has correct compression type...
-				if(h->iFlags&KImageCodePaged)
-					{
-					if(newFileComp!=0)
-						newFileComp = KUidCompressionBytePair;
-					}
-			}
-
-			if ( oldFileComp != newFileComp )
-				{
-				
-				if( newFileComp == 0)
-					{
-					Print(ELog,"Decompressing executable '%s'\n", iFileName);
-					f.iHdr->iCompressionType = 0;
-					}
-				else
-					{
-					Print(ELog,"Compressing executable '%s' with method:%08x\n", iFileName, newFileComp);
-					f.iHdr->iCompressionType = newFileComp;
-					}
-				f.UpdateHeaderCrc();
-				if (overflow)
-					{
-					char * buffer = new char [size];
-					// need to check if the compressed file will fit in the image
-   					#if defined(__LINUX__)
- 					ostrstream os((char*)aDest, aMaxSize, (ios::openmode)(ios::out+ios::binary));
-					#elif defined(__TOOLS2__) && defined (_STLP_THREADS)
-  					ostrstream os((char*)buffer, size,(ios::out+ios::binary));
-  					#elif defined( __TOOLS2__)
-   					ostrstream os((char*)buffer, size,(ios::out+ios::binary));
-					#else
-					ostrstream os( (char*)buffer, size, (ios::out+ios::binary));
-					#endif
-					os << f;
-					TUint compressedSize = os.pcount();
-					if (compressedSize <= aMaxSize)
-						overflow = EFalse;	
-					delete[] buffer;
-					}
-				}
-			if (overflow)
-				{
-				Print(EError, "Can't fit '%s' in image\n", iFileName);
-				Print(EError, "Overflowed by approximately 0x%x bytes.\n", size - aMaxSize);
-				exit(667);
-				}
-  			#if defined(__TOOLS2__) && defined (_STLP_THREADS)
-  			ostrstream os((char*)aDest, aMaxSize,(ios::out+ios::binary));
-  			#elif __TOOLS2__
-			ostrstream os((char*)aDest, aMaxSize, (std::_Ios_Openmode)(ios::out+ios::binary));
-			#else
-			ostrstream os((char*)aDest, aMaxSize, (ios::out+ios::binary));
-			#endif
-			os << f;
-			size = os.pcount();
-			compression = f.iHdr->CompressionType();
-			memcpy(&iUids[0], aDest, sizeof(iUids));
-			}
-		}
-	if (!executable)
-		{
-		if ( size > aMaxSize )
-			{
-			Print(EError, "Can't fit '%s' in image\n", iFileName);
-			Print(EError, "Overflowed by approximately 0x%x bytes.\n", size - aMaxSize);
-			exit(667);
-			}
-		size = HFile::Read((TText*)iFileName, (TAny *)aDest);
-                TUint32 Uidslen = (size > sizeof(iUids)) ? sizeof(iUids) : size;
-                memcpy(&iUids[0], aDest, Uidslen);
-		}
-
-	if (compression)
-		Print(ELog,"Compressed executable File '%s' size: %08x, mode:%08x\n", iFileName, size, compression);
-	else if (iExecutable)
-		Print(ELog,"Executable File '%s' size: %08x\n", iFileName, size);
-	else
-		Print(ELog,"File '%s' size: %08x\n", iFileName, size);
-	iRealFileSize = size;	// required later when directory is written
-	
-	return size;
-	}
-
-
-TRomNode* TRomNode::CopyDirectory(TRomNode*& aLastExecutable)
-	{
-
-	if (iHidden && iChild==0)
-		{
-		// Hidden file - do not copy (as it wouldn't be visible in the ROM filestructure)
-		if (iSibling)
-			return iSibling->CopyDirectory(aLastExecutable);
-		else
-			return 0;
-		}
-
-	TRomNode* copy = new TRomNode(iName);
-	if(aLastExecutable==0)
-		aLastExecutable = copy;		// this must be the root of the structure
-	// recursively copy the sub-structures
-	if (iChild)
-		copy->iChild = iChild->CopyDirectory(aLastExecutable);
-	if (iSibling)
-		copy->iSibling = iSibling->CopyDirectory(aLastExecutable);
-	copy->Clone(this);
-	return copy;
-	}
-
-
-
-
-void TRomNode::Clone(TRomNode* aOriginal)
-	{
-	iAtt = aOriginal->iAtt;
-	iAttExtra = aOriginal->iAttExtra;
-	iEntry = aOriginal->iEntry;
-	iHidden = aOriginal->iHidden;
-	iFileStartOffset = aOriginal->iFileStartOffset;
-	iSize = aOriginal->iSize;
-	iParent = aOriginal->iParent;
-    iAlias = aOriginal->iAlias;
-	}
-
-
-void TRomNode::Alias(TRomNode* aNode)
-	{
-	  // sanity checking
-	if (aNode->iEntry == 0) 
-	{
-		Print(EError, "Aliasing: TRomNode structure corrupted\n");
-		exit(666);
-	}
-	Clone(aNode);
-	iEntry = aNode->iEntry;
-	if (iEntry)
-		{
-		iEntry->SetRomNode(this);
-		}
-    iAlias = true;
-	}
-
-
-void TRomNode::Rename(TRomNode *aOldParent, TRomNode* aNewParent, TText* aNewName)
-	{
-	aOldParent->Remove(this);
-	aNewParent->Add(this);
-	delete [] iName;
-	iName = new TText[strlen((const char *)aNewName)+1];
-	strcpy ((char *)iName, (const char *)aNewName);
-	}
-
-TInt TRomNode::FullNameLength(TBool aIgnoreHiddenAttrib) const
-	{
-	TInt l = 0;
-	// aIgnoreHiddenAttrib is used to find the complete file name length as 
-	// in ROM of a hidden file.
-	if (iParent && ( !iHidden || aIgnoreHiddenAttrib))
-		l = iParent->FullNameLength() + 1;
-	l += strlen((const char*)iName);
-	return l;
-	}
-
-TInt TRomNode::GetFullName(char* aBuf, TBool aIgnoreHiddenAttrib) const
-	{
-	TInt l = 0;
-	TInt nl = strlen((const char*)iName);
-	// aIgnoreHiddenAttrib is used to find the complete file name as in ROM of a hidden file.
-	if (iParent && ( !iHidden || aIgnoreHiddenAttrib))
-		l = iParent->GetFullName(aBuf);
-	char* b = aBuf + l;
-	if (l)
-		*b++ = '\\', ++l;
-	memcpy(b, iName, nl);
-	b += nl;
-	*b = 0;
-	l += nl;
-	return l;
-	}
-
-// Fuction to return first node in the patchdata linked list
-DllDataEntry *TRomBuilderEntry::GetFirstDllDataEntry() const
-{
-	if (iFirstDllDataEntry)
-	{
-		return iFirstDllDataEntry;
-	}
-	else
-	{
-		return NULL;
-	}
-}
-
-// Fuction to set first node in the patchdata linked list
-void TRomBuilderEntry::SetFirstDllDataEntry(DllDataEntry *aDllDataEntry)
-{
-	iFirstDllDataEntry = aDllDataEntry;	
-}
-void TRomBuilderEntry::DisplaySize(TPrintType aWhere)
-{
-	TBool aIgnoreHiddenAttrib = ETrue;
-	TInt aLen = iRomNode->FullNameLength(aIgnoreHiddenAttrib);
-	char *aBuf = new char[aLen+1];
-	if(gLogLevel & LOG_LEVEL_FILE_DETAILS)
-		{
-		iRomNode->GetFullName(aBuf, aIgnoreHiddenAttrib);
-		if(iFileName)
-			Print(aWhere, "%s\t%d\t%s\t%s\n", iFileName, RealFileSize(), (iRomNode->iHidden || iHidden)?"hidden":"", aBuf);
-		else
-			Print(aWhere, "%s\t%s\n", (iRomNode->iHidden || iHidden)?"hidden":"", aBuf);
-		}
-	else
-		{
-		if(iFileName)
-			Print(aWhere, "%s\t%d\n", iFileName, RealFileSize());
-		}
-
-}
+/*
+* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent * @released
+*
+*/
+
+
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <e32std.h>
+#include <e32std_private.h>
+#include <e32rom.h>
+#include <u32std.h>
+#include <e32uid.h>
+#include <f32file.h>
+#include <malloc.h>
+#include <map>
+#include <queue> 
+#include <iomanip>
+#include <strstream>
+#include "utf16string.h"
+#ifdef _L
+#undef _L
+#endif
+#ifdef __LINUX__
+#define _alloca alloca
+#endif
+
+#include "h_utl.h"
+#include "r_obey.h"
+#include "rofs.h"
+#include "e32image.h"
+#include "patchdataprocessor.h"
+
+#include <filesystem.hpp>
+#include <thread/thread.hpp>
+#include <thread/mutex.hpp>
+#include <thread/condition_variable.hpp>
+
+#include "cache/cacheexception.hpp"
+#include "cache/cacheentry.hpp"
+#include "cache/cache.hpp"
+#include "cache/cachegenerator.hpp"
+#include "cache/cachevalidator.hpp"
+#include "cache/cacheablelist.hpp"
+#include "cache/cachemanager.hpp"
+
+extern TUint checkSum(const void* aPtr);
+
+extern ECompression gCompress;
+extern TUint gCompressionMethod;
+extern TInt  gCodePagingOverride;
+extern TInt  gDataPagingOverride;
+extern TInt  gLogLevel;
+extern bool gCache;
+TBool gDriveImage=EFalse;	// for drive image support.
+
+
+TInt TRomNode::Count=0;
+TRomNode* TRomNode::TheFirstNode = NULL;
+TRomNode* TRomNode::TheLastNode = NULL;
+
+// introduced for data drive files' attribute
+TUint8 TRomNode::sDefaultInitialAttr = (TUint8)KEntryAttReadOnly;
+
+struct SortableEntry
+	{
+	TRofsEntry* iEntry;
+	TBool iIsDir;
+	TUint16 iOffset;
+	};
+
+int compare(const void* l, const void* r)
+	{
+	const SortableEntry* left  = (const SortableEntry*)l;
+	const SortableEntry* right = (const SortableEntry*)r;
+	if (left->iIsDir)
+		{
+		if (!right->iIsDir)
+			return -1;	// dir < file
+		}
+	else
+		{
+		if (right->iIsDir)
+			return +1;	// file > dir
+		}
+
+	// both the same type of entry, sort by name
+	// must first convert to an 8 bit string
+	// array and NULL terminate it.
+	char temp1[500];
+	char temp2[500];
+
+
+TInt i=0;
+	for (i = 0; i < left->iEntry->iNameLength; i++)
+		{
+		temp1[i]=(char) left->iEntry->iName[i];
+		}
+	temp1[i]=0;
+
+	for (i = 0; i < right->iEntry->iNameLength; i++)
+		{
+		temp2[i]=(char) right->iEntry->iName[i];
+		}
+	temp2[i]=0;
+
+	return stricmp((const char*)&temp1[0], (const char*)&temp2[0]);
+	}
+
+TRomNode::TRomNode(const char* aName, TRomBuilderEntry* aEntry)
+//
+// Constructor
+//
+	:
+	iNextNode(NULL),
+	iParent(NULL), iSibling(0), iChild(0), iNextNodeForSameFile(0),
+	iTotalDirectoryBlockSize(0),
+	iTotalFileBlockSize(0),
+	iImagePosition(0),
+	iFileBlockPosition(0),
+	iAtt(sDefaultInitialAttr),
+	iAttExtra(0xFF),
+	iHidden(EFalse),
+	iEntry(aEntry),
+	iFileStartOffset(0),
+	iSize(0),
+	iOverride(0),
+	iFileUpdate(EFalse),
+    iAlias(false)
+	{
+	iName = NormaliseFileName(aName);
+	iIdentifier=TRomNode::Count++;
+
+	// Add this node to the flat linked list
+	if( !TheFirstNode )
+		{
+		TheFirstNode = this;
+		}
+	else
+		{
+		TheLastNode->iNextNode = this;
+		}
+	TheLastNode = this;
+
+	if (iEntry)
+		{
+		iEntry->SetRomNode(this);
+		}
+	else
+		{
+		iAtt = (TUint8)KEntryAttDir;
+		}
+	}
+
+TRomNode::~TRomNode() {
+	if (iEntry && !iAlias)
+		delete iEntry; 
+	if(iName)
+		delete []iName ;
+}
+//
+// Check if the TRomNode for aName exists in aDir, and if so, return it.
+//
+TRomNode *TRomNode::FindInDirectory(const char *aName) const{
+	TRomNode *entry=iChild; // first subdirectory or file
+	while (entry) {
+		if ((stricmp(aName, entry->iName)) == 0)
+			return entry;
+		else
+			entry=entry->iSibling;
+	}
+	return 0;
+}
+
+
+
+TInt indend = 0;
+
+void indendStructure(TInt i)
+       {
+	while(i > 0)
+	   {
+	     cout << "    ";
+	     i--;
+	   }
+       };
+
+// displays the directory structure
+void TRomNode::DisplayStructure(ostream* aOut)
+	{
+	  indendStructure(indend);
+      *aOut  << iName << "\n";
+	  if (iChild)
+	    {
+	      indend++;
+	      iChild->DisplayStructure(aOut);
+	      indend--;
+	    }
+	  if (iSibling)
+	    iSibling->DisplayStructure(aOut);
+	}
+
+
+void TRomNode::deleteTheFirstNode()
+{
+
+	TheFirstNode = NULL;
+}
+
+
+void TRomNode::InitializeCount()
+{
+	Count = 0;
+}
+void TRomNode::displayFlatList()
+{
+	TRomNode* current =	TheFirstNode;
+	TInt i = 0;
+	while(current)
+	{
+		i++;
+		cout <<  "\n" << i <<": " << current->iName << endl;
+		current = current->NextNode();
+	}
+
+	}
+
+
+
+void TRomNode::AddFile(TRomNode* aChild)
+	{
+	if (iEntry)
+		{
+		Print(EError, "Adding subdirectory to a file!!!\n");
+		return;
+		}
+	Add(aChild);
+	}
+
+TRomNode* TRomNode::NewSubDir(const char *aName) {
+	if (iEntry) {
+		Print(EError, "Adding subdirectory to a file!!!\n");
+		return 0;
+	}
+
+	TRomNode* node = new TRomNode(aName);
+	if (node==0){
+		Print(EError, "TRomNode::NewNode: Out of memory\n");
+		return 0;
+	}
+	node->iParent = this;
+	Add(node);
+	return node;
+	}
+
+void TRomNode::Add(TRomNode* aChild) {
+	if (iChild){ // this node is a non-empty directory
+		
+		TRomNode* dir = iChild; // find where to link in the new node
+		while (dir->iSibling)
+			dir = dir->iSibling;
+		dir->iSibling = aChild;
+	}
+	else
+		iChild = aChild; // else just set it up as the child of the dir
+	aChild->iSibling = 0;
+	aChild->iParent = this;
+	}
+//
+// Set the file extra attribute byte from the letters passed
+// Note: The iAttExtra bits are inverted. '0' represent enabled
+//
+TInt TRomNode::SetAttExtra(char *anAttWord, TRomBuilderEntry* aFile, enum EKeyword aKeyword){
+	iAttExtra=0xFF;
+	if (anAttWord==0 || anAttWord[0]=='\0')
+		return Print(EError, "Missing argument for keyword 'exattrib'.\n");
+	for (char *letter=anAttWord;*letter!=0;letter++)
+		{
+		switch (*letter)
+			{
+		case 'u':
+			iAttExtra |= (KEntryAttUnique >> 23);	// '1' represents disabled in iAttExtra
+			break;
+		case 'U':
+			iAttExtra &= ~(KEntryAttUnique >> 23);	// '0' represent enabled in iAttExtra
+			break;
+		default:
+			return Print(EError, "Unrecognised exattrib - '%c'.\n", *letter);
+			break;
+			}
+		}
+
+	if((~iAttExtra & (KEntryAttUnique >> 23))!=0)	// If the unique file attribute is set
+		{
+		if(aKeyword==EKeywordFile || aKeyword==EKeywordData)	// If the Keyword is File or Data
+			{
+				if(strlen(aFile->iFileName) > (KMaxFileName-KRofsMangleNameLength)) // check whether we have enough space to add the mangle tage
+					return Print(EError, "Lengthy filename with unique attribute to name mangle.\n");
+			}
+		else	// for all other keywords
+			return Print(EError, "exattrib field not allowed for entries except data and file.\n");
+		}
+	return KErrNone;
+	}
+
+
+TInt TRomNode::SetAtt(char *anAttWord)
+//
+// Set the file attribute byte from the letters passed
+//
+	{
+	iAtt=0;
+	if (anAttWord==0 || anAttWord[0]=='\0')
+		return Print(EError, "Missing argument for keyword 'attrib'.\n");
+	for (char *letter=anAttWord;*letter!=0;letter++)
+		{
+		switch (*letter)
+			{
+		case 'R':
+		case 'w':
+			iAtt |= KEntryAttReadOnly;
+			break;
+		case 'r':
+		case 'W':
+			iAtt &= ~KEntryAttReadOnly;
+			break;
+		case 'H':
+			iAtt |= KEntryAttHidden;
+			break;
+		case 'h':
+			iAtt &= ~KEntryAttHidden;
+			break;
+		case 'S':
+			iAtt |= KEntryAttSystem;
+			break;
+		case 's':
+			iAtt &= ~KEntryAttSystem;
+			break;
+		default:
+			return Print(EError, "Unrecognised attrib - '%c'.\n", *letter);
+			break;
+			}
+		}
+	return KErrNone;
+	}
+
+
+// Calculates the amount of ROM space required to hold
+// this entry. The return is the actual size of the TRofsEntry
+// structure, not rounded up
+TInt TRomNode::CalculateEntrySize() const {
+	UTF16String unistr(iName);
+	TInt requiredSizeBytes = KRofsEntryHeaderSize +	unistr.bytes();
+	return requiredSizeBytes;
+	}
+
+TInt TRomNode::CalculateDirectoryEntrySize( TInt& aDirectoryBlockSize,
+										    TInt& aFileBlockSize )
+	// Calculates the total size of the TRofsDir structure required
+	// for this directory and the size of the files block. Traverses all the
+	// children adding their entry sizes. The result is not rounded up.
+	//
+	// On return aDirectoryBlockSize is the number of bytes required for the
+	//	main directory structure. aFileBlockSize is the number of bytes
+	//	required to hold the list of files.
+	//
+	// Returns KErrNone on success
+	{
+
+	TInt offsetBytes=0;
+	TInt padBytes=0;
+	if( 0 == iTotalDirectoryBlockSize )
+		{
+		// need to calculate by walking children
+		if( !iChild )
+			{
+			return Print(EError, "TRomNode structure corrupt\n");
+			}
+
+		TInt dirBlockSize = KRofsDirHeaderSize;
+		TInt fileBlockSize = 0;
+		TInt fileCount=0;
+		TInt dirCount=0;
+
+		TRomNode* node = iChild;
+		while (node)
+			{
+			TInt entrySize = node->CalculateEntrySize();
+			if( node->IsDirectory() )
+				{
+				dirBlockSize += (4 - dirBlockSize) & 3;	// pad to next word boundary
+				dirBlockSize += entrySize;
+				dirCount++;
+				}
+			else
+				{
+				fileBlockSize += (4 - fileBlockSize) & 3;	// pad to next word boundary
+				fileBlockSize += entrySize;
+				fileCount++;
+				}
+			node = node->iSibling;
+			}
+
+		offsetBytes = ((fileCount + dirCount) * 2) + 4; //the +4 are the two offset counts,
+		padBytes = offsetBytes % 4;
+
+		iTotalDirectoryBlockSize = dirBlockSize;
+		iTotalFileBlockSize = fileBlockSize;
+		}
+
+	aDirectoryBlockSize = iTotalDirectoryBlockSize + offsetBytes + padBytes;
+	aFileBlockSize = iTotalFileBlockSize;
+	return KErrNone;
+	}
+
+/**
+Place the files and it's attributes (incase of executables)
+Called for both rofs and datadrive creation.
+
+@param aDest   - Destination buffer.
+@param aOffset - offset value, used for rofs only.
+@param aMaxSize- Maximum size required for rofs.
+
+@return - Returns the number of bytes placed or a -ve error code.
+*/
+TInt TRomNode::PlaceFile( TUint8* &aDest, TUint aOffset, TUint aMaxSize, CBytePair *aBPE ){
+	//
+	// Place the file into the ROM image, making any necessary conversions
+	// along the way.
+	//
+	// Returns the number of bytes placed or a -ve error code.
+	
+
+	TInt size=0;
+
+	// file hasn't been placed for drive image.
+	if(gDriveImage)
+	{
+		size = iEntry->PlaceFile(aDest,aMaxSize,aBPE);
+		iSize = size;
+	}
+	else
+	{
+		if (iEntry->iHidden)
+			iFileStartOffset = KFileHidden;
+		else
+		{
+                    if (iEntry->iFileOffset==0)
+                    {
+                        // file hasn't been placed
+                        size = iEntry->PlaceFile( aDest, aMaxSize, aBPE );
+                        if (size>=0)
+                            iEntry->iFileOffset = aOffset;
+                    }
+                    else {
+                        iFileStartOffset = (TInt)iEntry;
+                    }
+		}
+	}
+
+	// Deal with any override attributes
+	// (omit paging overrides as these are dealt with in TRomBuilderEntry::PlaceFile
+	//  and may also be legitimately specified for non-executable files in ROM)
+	if( iOverride&~(KOverrideCodeUnpaged|KOverrideCodePaged|KOverrideDataUnpaged|KOverrideDataPaged) )
+		{
+		E32ImageHeaderV* hdr = (E32ImageHeaderV*)aDest;
+
+		TUint hdrfmt = hdr->HeaderFormat();
+		if (hdrfmt != KImageHdrFmt_V)
+			{
+			Print(EError,"%s: Can't load old format binary\n", iEntry->iFileName);
+			return KErrNotSupported;
+			}
+
+		// First need to check that it's a real image header
+		if( (TUint)size > sizeof(E32ImageHeader) )
+			{
+			if( ((TInt)hdr->iSignature == 0x434f5045u) && ((TInt)hdr->iUid1 == KExecutableImageUidValue || (TInt)hdr->iUid1 == KDynamicLibraryUidValue) )
+				{
+				// Should check the CRC as well here...
+				// Something for later
+
+				// Ok, it looks like an image header
+				if( iOverride & KOverrideStack )
+					{
+					hdr->iStackSize = iStackSize;
+					}
+				if( iOverride & KOverrideHeapMin )
+					{
+					hdr->iHeapSizeMin = iHeapSizeMin;
+					}
+				if( iOverride & KOverrideHeapMax )
+					{
+					hdr->iHeapSizeMax = iHeapSizeMax;
+					}
+				if( iOverride & KOverrideFixed )
+					{
+					if( hdr->iFlags & KImageDll )
+						{
+						Print(EError,"%s: Can't used FIXED keyword on a DLL\n", iEntry->iFileName);
+						return KErrNotSupported;
+						}
+					hdr->iFlags |= KImageFixedAddressExe;
+					}
+				if( iOverride & (KOverrideUid1|KOverrideUid2|KOverrideUid3))
+					{
+					if (iOverride & KOverrideUid1)
+						{
+						hdr->iUid1 = iUid1;
+						}
+					if (iOverride & KOverrideUid2)
+						{
+						hdr->iUid2 = iUid2;
+						}
+					if (iOverride & KOverrideUid3)
+						{
+						hdr->iUid3 = iUid3;
+						}
+					// Need to re-checksum the UIDs
+					TUidType ut(TUidType(TUid::Uid(hdr->iUid1), TUid::Uid(hdr->iUid2), TUid::Uid(hdr->iUid3)));
+					hdr->iUidChecksum =  (checkSum(((TUint8*)&ut)+1)<<16)|checkSum(&ut);
+					}
+				if( iOverride & KOverridePriority )
+					{
+					hdr->iProcessPriority = (TUint16)iPriority;
+					}
+				if( iOverride & KOverrideCapability )
+					{
+					hdr->iS.iCaps = iCapability;
+					}
+
+				// Need to re-CRC the header
+				hdr->iHeaderCrc = KImageCrcInitialiser;
+				TUint32 crc = 0;
+				TInt hdrsz = hdr->TotalSize();
+				HMem::Crc32(crc, hdr, hdrsz);
+				hdr->iHeaderCrc = crc;
+				}
+			}
+		}
+
+	return size;
+	}
+
+TInt TRomNode::CountFileAndDir(TInt& aFileCount, TInt& aDirCount)
+	{
+	//
+	// Count the number of file and directory entries for this node
+	//
+	TRomNode* node = iChild;
+
+	aFileCount=0;
+	aDirCount=0;
+	while( node )
+		{
+		if( node->IsFile() )
+			{
+			aFileCount++;
+			}
+		else
+			{
+			aDirCount++;
+			}
+
+		node = node->iSibling;
+		}
+	return KErrNone;
+	}
+
+TInt TRomNode::Place( TUint8* aDestBase )
+	//
+	// Writes this directory entry out to the image.
+	// The image starts at aDestBase.
+	// The position in the image must already have been set with SetImagePosition()
+	// and SetFileBlockPosition().
+	// Returns KErrNone on success
+	//
+	{
+	TUint8* dirBlockBase = aDestBase + iImagePosition;
+	TUint8* fileBlockBase = aDestBase + iFileBlockPosition;
+
+	TRofsDir* pDir = (TRofsDir*)dirBlockBase;
+	pDir->iFirstEntryOffset = KRofsDirFirstEntryOffset;
+	pDir->iFileBlockAddress = iFileBlockPosition;
+	pDir->iFileBlockSize = iTotalFileBlockSize;
+	pDir->iStructSize = (TUint16)iTotalDirectoryBlockSize;
+
+	TRofsEntry* pDirEntry = &(pDir->iSubDir);
+	TRofsEntry* pFileEntry = (TRofsEntry*)fileBlockBase;
+
+	TInt dirCount;
+	TInt fileCount;
+	TInt index = 0;
+	CountFileAndDir(fileCount, dirCount);
+
+	SortableEntry* array = new SortableEntry[fileCount + dirCount];
+	TRomNode* node = iChild;
+
+	while( node )
+		{
+		TRofsEntry* entry;
+
+		if( node->IsFile() )
+			{
+			entry = pFileEntry;
+
+			//Offset in 32bit words from start of file block
+			array[index].iOffset = (TUint16) ((((TUint8*) entry) - fileBlockBase) >> 2);
+			array[index].iIsDir = EFalse;
+			}
+		else
+			{
+			entry = pDirEntry;
+
+			//Offset in 32bit words from start of directory block
+			array[index].iOffset = (TUint16) ((((TUint8*) entry) - dirBlockBase) >> 2);
+			array[index].iIsDir = ETrue;
+			}
+		array[index].iEntry = entry;
+		index++;	 
+		entry->iNameOffset = KRofsEntryNameOffset; 
+		entry->iAtt = node->iAtt;
+		entry->iAttExtra = node->iAttExtra;
+
+		TInt entryLen = KRofsEntryHeaderSize;
+		UTF16String unistr(node->iName);
+		if(!unistr.IsEmpty()){
+			entry->iNameLength = unistr.length();
+			memcpy(entry->iName,unistr.c_str(),unistr.bytes());
+			entryLen += unistr.bytes() ; 
+		}
+		entryLen += (4 - entryLen) & 3;	// round up to nearest word
+		entry->iStructSize = (TUint16)entryLen;
+
+		if( node->IsFile() )
+			{
+			// node is a file, entry points to the file
+			// write an entry out into the file block
+			pFileEntry->iFileAddress = node->iFileStartOffset;
+			node->iAtt &= ~KEntryAttDir;
+			pFileEntry->iFileSize = node->iEntry->RealFileSize();
+			memcpy(&pFileEntry->iUids[0], &node->iEntry->iUids[0], sizeof(pFileEntry->iUids));
+			pFileEntry = (TRofsEntry*)( (TUint8*)pFileEntry + entryLen );
+			}
+		else
+			{
+			// node is a subdirectory, entry points to directory
+			pDirEntry->iFileAddress = node->iImagePosition;
+			node->iAtt |= KEntryAttDir;
+
+			// the size is just the size of the directory block
+			pDirEntry->iFileSize = node->iTotalDirectoryBlockSize;
+			pDirEntry = (TRofsEntry*)( (TUint8*)pDirEntry + entryLen );
+			}
+
+		node = node->iSibling;
+		}
+
+	qsort(array,fileCount + dirCount,sizeof(SortableEntry),&compare);
+
+	//Now copy the contents of sorted array to the image
+	TUint16* currentPtr = (TUint16*) (dirBlockBase + iTotalDirectoryBlockSize);
+
+	*currentPtr=(TUint16)dirCount;
+	currentPtr++;
+	*currentPtr=(TUint16)fileCount;
+	currentPtr++;
+
+	for (index = 0; index < (fileCount + dirCount); index++)
+		{
+		*currentPtr = array[index].iOffset;
+		currentPtr++;
+		}
+	delete[] array;
+	return KErrNone;
+	}
+
+
+
+void TRomNode::Remove(TRomNode* aChild)
+	{
+	if (iChild==0)
+		{
+		Print(EError, "Removing file from a file!!!\n");
+		return;
+		}
+	if (iChild==aChild) // first child in this directory
+		{
+		iChild = aChild->iSibling;
+		aChild->iSibling = 0;
+		if(iChild==0)
+			{
+				iParent->Remove(this);
+				TRomNode * current = TheFirstNode;
+				TRomNode * prev = current;
+				while(current != this)
+					{
+						prev = current;
+						current = current->NextNode();
+					}
+				prev->SetNextNode(current->NextNode());
+				delete this;
+			}
+		return;
+		}
+	TRomNode* prev = iChild;
+	while (prev->iSibling && prev->iSibling != aChild)
+		prev = prev->iSibling;
+	if (prev==0)
+		{
+		Print(EError, "Attempting to remove file not in this directory!!!\n");
+		return;
+		}
+	prev->iSibling = aChild->iSibling;
+	aChild->iSibling = 0;
+	}
+
+void TRomNode::CountDirectory(TInt& aFileCount, TInt& aDirCount)
+	{
+	TRomNode *current=iChild;
+	while(current)
+		{
+		if (current->iChild)
+			aDirCount++;
+		else
+ 			aFileCount++;
+	current=current->iSibling;
+		}
+	}
+
+//
+// Follow the TRomNode tree, destroying it
+//
+void TRomNode::Destroy() {
+ 	TRomNode *current = this; // root has no siblings
+	while (current)
+		{
+		if (current->iChild)
+			current->iChild->Destroy();
+		TRomNode* prev=current;
+		current=current->iSibling;
+		delete prev;
+        prev = 0;
+		}
+ }
+
+ 
+
+ 
+void TRomNode::AddNodeForSameFile(TRomNode* aPreviousNode, TRomBuilderEntry* aFile)
+	{
+	// sanity checking
+	if (iNextNodeForSameFile != 0 || iEntry != aFile || (aPreviousNode && aPreviousNode->iEntry != iEntry))
+		{
+		Print(EError, "Adding Node for same file: TRomNode structure corrupted\n");
+		exit(666);
+		}
+	iNextNodeForSameFile = aPreviousNode;
+	}
+
+
+
+
+
+//**************************************
+// TRomBuilderEntry
+//**************************************
+
+
+//
+// Constructor
+//
+TRomBuilderEntry::TRomBuilderEntry(const char *aFileName,const char *aName):
+iFirstDllDataEntry(0),	iName(0),iFileName(0),iNext(0), iNextInArea(0),
+iExecutable(EFalse), iFileOffset(EFalse), iCompressEnabled(0),
+iHidden(0), iRomNode(0), iRealFileSize(0)
+{
+	if (aFileName)
+   		iFileName = NormaliseFileName(aFileName);
+	if (aName)
+		iName = NormaliseFileName(aName);
+	memset(iUids,0 ,sizeof(TCheckedUid));
+}
+//
+// Destructor
+//
+TRomBuilderEntry::~TRomBuilderEntry() {
+	if(iFileName) {
+		delete []iFileName;
+		iFileName = 0;
+	}
+	
+	if(iName) {
+		delete []iName;
+		iName = 0 ;
+	}
+}
+
+void TRomBuilderEntry::SetRomNode(TRomNode* aNode)
+	{
+	aNode->AddNodeForSameFile(iRomNode, this);
+	iRomNode = aNode;
+	}
+
+//
+// Place the file in ROFS. Since we don't support compression yet all
+// we have to do is read the file into memory
+// compress it, if it isn't already compressed.
+//
+// Returns the number of bytes used, or -ve error code
+TInt TRomBuilderEntry::PlaceFile( TUint8* &aDest,TUint aMaxSize, CBytePair *aBPE ){
+
+
+	TUint compression = 0;
+	TBool executable = iExecutable;
+	Print(ELog,"Reading file %s to image\n", iFileName );
+	TUint32 size = HFile::GetLength(iFileName);
+	if (size==0)
+		Print(EWarning, "File %s does not exist or is 0 bytes in length.\n",iFileName);
+	if (aDest == NULL) {
+		aMaxSize = size << 1;
+		aMaxSize = (aMaxSize>0) ? aMaxSize : 2;
+		aDest = new TUint8[aMaxSize];
+   }
+
+	if (executable)
+	{
+		// indicate if the image will overflow without compression
+		TBool overflow;
+		if(size>aMaxSize)
+			overflow = ETrue;
+		else
+			overflow = EFalse;
+
+		// try to compress this executable
+		E32ImageFile f(aBPE);
+		TInt r = f.Open(iFileName);
+		// is it really a valid E32ImageFile?
+		if (r != KErrNone)
+		{
+			Print(EWarning, "File '%s' is not a valid executable.  Placing file as data.\n", iFileName);
+			executable = EFalse;
+		}
+		else
+		{
+
+			if(iRomNode->iOverride & KOverrideDllData)
+			{
+				DllDataEntry *aDllEntry = iRomNode->iEntry->GetFirstDllDataEntry();
+				TLinAddr* aExportTbl;
+				void *aLocation;
+				TUint aDataAddr;
+				char *aCodeSeg, *aDataSeg;
+
+				aExportTbl = (TLinAddr*)((char*)f.iData + f.iOrigHdr->iExportDirOffset);
+
+				// const data symbol may belong in the Code section. If the address lies within the Code or data section limits,
+				// get the corresponding location and update it.While considering the Data section limits
+				// don't include the Bss section, as it doesn't exist as yet in the image.
+				while( aDllEntry ){
+					if(aDllEntry->iOrdinal != (TUint32)-1){
+						if(aDllEntry->iOrdinal < 1 || aDllEntry->iOrdinal > (TUint)f.iOrigHdr->iExportDirCount){
+							Print(EWarning, "Invalid ordinal %d specified for DLL %s\n", aDllEntry->iOrdinal, iRomNode->iName);
+							aDllEntry = aDllEntry->NextDllDataEntry();
+							continue;
+						}
+
+						//	Get the address of the data field via the export table.
+						aDataAddr = (TInt32)(aExportTbl[aDllEntry->iOrdinal - 1] + aDllEntry->iOffset);
+						if( aDataAddr >= f.iOrigHdr->iCodeBase && aDataAddr <= (f.iOrigHdr->iCodeBase + f.iOrigHdr->iCodeSize)){
+							aCodeSeg = (char*)(f.iData + f.iOrigHdr->iCodeOffset);
+							aLocation = (void*)(aCodeSeg + aDataAddr - f.iOrigHdr->iCodeBase );
+							memcpy(aLocation, &aDllEntry->iNewValue, aDllEntry->iSize);
+						}
+						else if(aDataAddr >= f.iOrigHdr->iDataBase && aDataAddr <= (f.iOrigHdr->iDataBase + f.iOrigHdr->iDataSize)){
+							aDataSeg = (char*)(f.iData + f.iOrigHdr->iDataOffset);
+							aLocation = (void*)(aDataSeg + aDataAddr - f.iOrigHdr->iDataBase );
+							memcpy(aLocation, &aDllEntry->iNewValue, aDllEntry->iSize);
+						}
+						else
+						{
+							Print(EWarning, "Patchdata failed as address pointed by ordinal %d of DLL %s doesn't lie within Code or Data section limits\n", aDllEntry->iOrdinal, iRomNode->iName);
+						}
+					}
+					else if(aDllEntry->iDataAddress != (TLinAddr)-1){
+						aDataAddr = aDllEntry->iDataAddress + aDllEntry->iOffset;
+						if( aDataAddr >= f.iOrigHdr->iCodeBase && aDataAddr <= (f.iOrigHdr->iCodeBase + f.iOrigHdr->iCodeSize)){
+							aCodeSeg = (char*)(f.iData + f.iOrigHdr->iCodeOffset);
+							aLocation = (void*)(aCodeSeg + aDataAddr - f.iOrigHdr->iCodeBase );
+							memcpy(aLocation, &aDllEntry->iNewValue, aDllEntry->iSize);
+						}
+						else if(aDataAddr >= f.iOrigHdr->iDataBase && aDataAddr <= (f.iOrigHdr->iDataBase + f.iOrigHdr->iDataSize)){
+							aDataSeg = (char*)(f.iData + f.iOrigHdr->iDataOffset);
+							aLocation = (void*)(aDataSeg + aDataAddr - f.iOrigHdr->iDataBase );
+							memcpy(aLocation, &aDllEntry->iNewValue, aDllEntry->iSize);
+						}
+						else
+						{
+							Print(EWarning, "Patchdata failed as address 0x%x of DLL %s doesn't lie within Code or Data section limits\n", aDllEntry->iOrdinal, iRomNode->iName);
+						}
+					}
+					aDllEntry = aDllEntry->NextDllDataEntry();
+				}
+			}
+
+			compression = f.iHdr->CompressionType();
+			Print(ELog,"Original file:'%s' is compressed by method:%08x\n", iFileName, compression);
+
+
+			TUint32 oldFileComp;
+			TUint32 newFileComp;
+
+			if(compression)
+			{
+				// The E32 image in release directory is compressed
+				oldFileComp = compression;
+			}
+			else
+			{
+				// The E32 image in release directory is uncompressed
+				oldFileComp = 0;
+			}
+
+			if( iCompressEnabled != ECompressionUnknown)
+			{
+				// The new state would be as stated in obey file, i.e.
+				// filecompress or fileuncompress
+				newFileComp = gCompressionMethod;
+			}
+			else if (gCompress != ECompressionUnknown)
+			{
+				// The new state would be as stated set globally
+				newFileComp = gCompressionMethod;
+			}
+			else
+			{
+				// When not known if compression is to be applied or not,
+				// set it same as that of the E32 image in release directory
+				newFileComp = oldFileComp;
+			}
+
+			if(!gDriveImage)
+			{
+				// overide paging flags...
+				E32ImageHeaderV* h=f.iHdr;
+				if (iRomNode->iOverride & KOverrideCodePaged)
+				{
+					h->iFlags &= ~KImageCodeUnpaged;
+					h->iFlags |= KImageCodePaged;
+				}
+				if (iRomNode->iOverride & KOverrideCodeUnpaged)
+				{
+					h->iFlags |= KImageCodeUnpaged;
+					h->iFlags &= ~KImageCodePaged;
+				}
+				if (iRomNode->iOverride & KOverrideDataPaged)
+				{
+					h->iFlags &= ~KImageDataUnpaged;
+					h->iFlags |= KImageDataPaged;
+				}
+				if (iRomNode->iOverride & KOverrideDataUnpaged)
+				{
+					h->iFlags |= KImageDataUnpaged;
+					h->iFlags &= ~KImageDataPaged;
+				}
+
+				// apply global paging override...
+				switch(gCodePagingOverride)
+				{
+				case EKernelConfigPagingPolicyNoPaging:
+					h->iFlags |= KImageCodeUnpaged;
+					h->iFlags &= ~KImageCodePaged;
+					break;
+				case EKernelConfigPagingPolicyAlwaysPage:
+					h->iFlags |= KImageCodePaged;
+					h->iFlags &= ~KImageCodeUnpaged;
+					break;
+				case EKernelConfigPagingPolicyDefaultUnpaged:
+					if(!(h->iFlags&(KImageCodeUnpaged|KImageCodePaged)))
+						h->iFlags |= KImageCodeUnpaged;
+					break;
+				case EKernelConfigPagingPolicyDefaultPaged:
+					if(!(h->iFlags&(KImageCodeUnpaged|KImageCodePaged)))
+						h->iFlags |= KImageCodePaged;
+					break;
+				}
+				switch(gDataPagingOverride)
+				{
+				case EKernelConfigPagingPolicyNoPaging:
+					h->iFlags |= KImageDataUnpaged;
+					h->iFlags &= ~KImageDataPaged;
+					break;
+				case EKernelConfigPagingPolicyAlwaysPage:
+					h->iFlags |= KImageDataPaged;
+					h->iFlags &= ~KImageDataUnpaged;
+					break;
+				case EKernelConfigPagingPolicyDefaultUnpaged:
+					if(!(h->iFlags&(KImageDataUnpaged|KImageDataPaged)))
+						h->iFlags |= KImageDataUnpaged;
+					break;
+				case EKernelConfigPagingPolicyDefaultPaged:
+					if(!(h->iFlags&(KImageDataUnpaged|KImageDataPaged)))
+						h->iFlags |= KImageDataPaged;
+					break;
+				}
+				f.UpdateHeaderCrc();
+
+				// make sure paged code has correct compression type...
+				if(h->iFlags&KImageCodePaged)
+				{
+					if(newFileComp!=0)
+						newFileComp = KUidCompressionBytePair;
+				}
+			}
+
+			if ( oldFileComp != newFileComp )
+			{
+
+				if( newFileComp == 0)
+				{
+					Print(ELog,"Decompressing executable '%s'\n", iFileName);
+					f.iHdr->iCompressionType = 0;
+				}
+				else
+				{
+					Print(ELog,"Compressing executable '%s' with method:%08x\n", iFileName, newFileComp);
+					f.iHdr->iCompressionType = newFileComp;
+				}
+				f.UpdateHeaderCrc();
+				if (overflow)
+				{
+					// need to check if the compressed file will fit in the image
+					//TODO the checking will slow down the build process, should do it later along with the writing on aDest.
+					TUint32 compressedSize;
+					char * buffer = new char [size];
+#if defined(__LINUX__)
+					ostrstream os((char*)aDest, aMaxSize, (ios_base::openmode)(ios_base::out+ios_base::binary));
+#elif defined(__TOOLS2__) && defined (_STLP_THREADS)
+					ostrstream os((char*)buffer, size,(ios_base::out+ios_base::binary));
+#elif defined( __TOOLS2__)
+					ostrstream os((char*)buffer, size,(ios_base::out+ios_base::binary));
+#else
+					ostrstream os( (char*)buffer, size, (ios_base::out+ios_base::binary));
+#endif
+					os << f;
+					compressedSize = os.pcount();
+					delete[] buffer;
+					if (compressedSize <= aMaxSize)
+						overflow = EFalse;
+				}
+			}
+			if (overflow)
+			{
+				Print(EError, "Can't fit '%s' in image\n", iFileName);
+				Print(EError, "Overflowed by approximately 0x%x bytes.\n", size - aMaxSize);
+				exit(667);
+			}
+
+			//try to use cached version where possible.
+			if(gCache && !gDriveImage && !(iRomNode->iAlias) && (iRomNode->iEntry->iExecutable) && !(iRomNode->iOverride & KOverrideDllData))
+			{
+				//retrive cached version.
+				size_t len = strlen(iFileName) + 1;
+				char* temp = (char*)_alloca(len);
+				memcpy(temp,iFileName,len);
+				CacheEntry* entryref = CacheManager::GetInstance()->GetE32ImageFileRepresentation(temp , compression); 
+				if(entryref)
+				{
+					size = entryref->GetCachedFileBufferLen();
+					memcpy(aDest, entryref->GetCachedFileBuffer(), size);
+					memcpy(aDest,f.iHdr,sizeof(E32ImageHeaderV));
+					compression = atoi(entryref->GetCachedFileCompressionID());
+					memcpy(&iUids[0], aDest, sizeof(iUids));
+					if (compression)
+						Print(ELog,"Compressed executable File '%s' size: %08x, mode:%08x\n", iFileName, size, compression);
+					else if (iExecutable)
+						Print(ELog,"Executable File '%s' size: %08x\n", iFileName, size);
+					else
+						Print(ELog,"File '%s' size: %08x\n", iFileName, size);
+					iRealFileSize = size;	// required later when directory is written
+
+					return size;
+				}
+			}
+
+#if defined(__TOOLS2__) && defined (_STLP_THREADS)
+			ostrstream os((char*)aDest, aMaxSize,(ios_base::out+ios_base::binary));
+#elif __TOOLS2__
+			ostrstream os((char*)aDest, aMaxSize, (_Ios_Openmode)(ios_base::out+ios_base::binary));
+#else
+			ostrstream os((char*)aDest, aMaxSize, (ios_base::out+ios_base::binary));
+#endif
+			os << f;
+			size = os.pcount();
+
+			//save the decompressed/recompressed executable into the cache if it's enabled.
+			if(gCache && !gDriveImage && !(iRomNode->iAlias) && (iRomNode->iEntry->iExecutable) && !(iRomNode->iOverride & KOverrideDllData))
+			{
+				CacheEntry* newentryref = new (nothrow) CacheEntry();
+				if(newentryref)
+				{
+					boost::filesystem::path originalfilepath(iFileName);
+					time_t originalcreationtime = last_write_time(originalfilepath);
+					newentryref->SetOriginalFileCreateTime(&originalcreationtime);
+					newentryref->SetOriginalFileCompression(f.iHdr->CompressionType());
+					size_t len = strlen(iFileName) + 1;					
+					char* originalfilename = (char*)_alloca(len);
+					memcpy(originalfilename,iFileName,len);
+					CacheManager::GetInstance()->NormalizeFilename(originalfilename);
+					newentryref->SetOriginalFilename(originalfilename); 
+					newentryref->SetCachedFileCompression(compression);
+					string cachedfilename(".rofs.");
+					cachedfilename += newentryref->GetCachedFileCompressionID();
+					cachedfilename += ".";
+					cachedfilename += iFileName;
+					size_t slashpos;
+					while(((slashpos=cachedfilename.find("/"))!=string::npos) || ((slashpos=cachedfilename.find("\\"))!=string::npos))
+						cachedfilename.replace(slashpos, 1, 1, '.');
+					cachedfilename.insert(0, "/");
+					cachedfilename.insert(0, CacheManager::GetInstance()->GetCacheRoot());
+					newentryref->SetCachedFilename(cachedfilename.c_str());
+					newentryref->SetCachedFileBuffer((char*)aDest, size);
+					try
+					{
+						size_t len = strlen(iFileName) + 1;
+						char* temp = (char*)_alloca(len);
+						memcpy(temp,iFileName,len);
+						CacheManager::GetInstance()->Invalidate(temp, newentryref); 
+					}
+					catch (CacheException ce)
+					{
+						Print(EWarning, "Cache brings up an exception (%s) when processes %s\r\n", ce.GetErrorMessage(), iFileName);
+					}
+				}
+			}
+
+			compression = f.iHdr->CompressionType();
+			memcpy(&iUids[0], aDest, sizeof(iUids));
+		}
+	}
+	if (!executable)
+	{
+		if ( size > aMaxSize )
+		{
+			Print(EError, "Can't fit '%s' in image\n", iFileName);
+			Print(EError, "Overflowed by approximately 0x%x bytes.\n", size - aMaxSize);
+			exit(667);
+		}
+		size = HFile::Read(iFileName, (TAny *)aDest);
+		TUint32 Uidslen = (size > sizeof(iUids)) ? sizeof(iUids) : size;
+		memcpy(&iUids[0], aDest, Uidslen);
+	}
+
+	if (compression)
+		Print(ELog,"Compressed executable File '%s' size: %08x, mode:%08x\n", iFileName, size, compression);
+	else if (iExecutable)
+		Print(ELog,"Executable File '%s' size: %08x\n", iFileName, size);
+	else
+		Print(ELog,"File '%s' size: %08x\n", iFileName, size);
+	iCompressEnabled = compression;
+	iRealFileSize = size;	// required later when directory is written
+
+	return size;
+}
+
+
+TRomNode* TRomNode::CopyDirectory(TRomNode*& aLastExecutable)
+	{
+
+	if (iHidden && iChild==0)
+		{
+		// Hidden file - do not copy (as it wouldn't be visible in the ROM filestructure)
+		if (iSibling)
+			return iSibling->CopyDirectory(aLastExecutable);
+		else
+			return 0;
+		}
+
+	TRomNode* copy = new TRomNode(iName);
+	if(aLastExecutable==0)
+		aLastExecutable = copy;		// this must be the root of the structure
+	// recursively copy the sub-structures
+	if (iChild)
+		copy->iChild = iChild->CopyDirectory(aLastExecutable);
+	if (iSibling)
+		copy->iSibling = iSibling->CopyDirectory(aLastExecutable);
+	copy->Clone(this);
+	return copy;
+	}
+
+
+
+
+void TRomNode::Clone(TRomNode* aOriginal)
+	{
+	iAtt = aOriginal->iAtt;
+	iAttExtra = aOriginal->iAttExtra;
+	iEntry = aOriginal->iEntry;
+	iHidden = aOriginal->iHidden;
+	iFileStartOffset = aOriginal->iFileStartOffset;
+	iSize = aOriginal->iSize;
+	iParent = aOriginal->iParent;
+    iAlias = aOriginal->iAlias;
+	}
+
+
+void TRomNode::Alias(TRomNode* aNode)
+	{
+	  // sanity checking
+	if (aNode->iEntry == 0)
+	{
+		Print(EError, "Aliasing: TRomNode structure corrupted\n");
+		exit(666);
+	}
+	Clone(aNode);
+	iEntry = aNode->iEntry;
+	if (iEntry)
+		{
+		iEntry->SetRomNode(this);
+		}
+    iAlias = true;
+	}
+
+
+void TRomNode::Rename(TRomNode *aOldParent, TRomNode* aNewParent, const char* aNewName) {
+	aOldParent->Remove(this);
+	aNewParent->Add(this);
+	delete [] iName;
+	size_t len = strlen(aNewName)+1;
+	iName = new char[len];
+	memcpy (iName, aNewName,len);
+}
+
+TInt TRomNode::FullNameLength(TBool aIgnoreHiddenAttrib) const
+	{
+	TInt l = 0;
+	// aIgnoreHiddenAttrib is used to find the complete file name length as
+	// in ROM of a hidden file.
+	if (iParent && ( !iHidden || aIgnoreHiddenAttrib))
+		l = iParent->FullNameLength() + 1;
+	l += strlen((const char*)iName);
+	return l;
+	}
+
+TInt TRomNode::GetFullName(char* aBuf, TBool aIgnoreHiddenAttrib) const
+	{
+	TInt l = 0;
+	TInt nl = strlen((const char*)iName);
+	// aIgnoreHiddenAttrib is used to find the complete file name as in ROM of a hidden file.
+	if (iParent && ( !iHidden || aIgnoreHiddenAttrib))
+		l = iParent->GetFullName(aBuf);
+	char* b = aBuf + l;
+	if (l)
+		*b++ = '\\', ++l;
+	memcpy(b, iName, nl);
+	b += nl;
+	*b = 0;
+	l += nl;
+	return l;
+	}
+
+// Fuction to return first node in the patchdata linked list
+DllDataEntry *TRomBuilderEntry::GetFirstDllDataEntry() const
+{
+	if (iFirstDllDataEntry)
+	{
+		return iFirstDllDataEntry;
+	}
+	else
+	{
+		return NULL;
+	}
+}
+
+// Fuction to set first node in the patchdata linked list
+void TRomBuilderEntry::SetFirstDllDataEntry(DllDataEntry *aDllDataEntry)
+{
+	iFirstDllDataEntry = aDllDataEntry;
+}
+void TRomBuilderEntry::DisplaySize(TPrintType aWhere)
+{
+	TBool aIgnoreHiddenAttrib = ETrue;
+	TInt aLen = iRomNode->FullNameLength(aIgnoreHiddenAttrib);
+	char *aBuf = new char[aLen+1];
+	if(gLogLevel & LOG_LEVEL_FILE_DETAILS)
+		{
+		iRomNode->GetFullName(aBuf, aIgnoreHiddenAttrib);
+		if(iFileName)
+			Print(aWhere, "%s\t%d\t%s\t%s\n", iFileName, RealFileSize(), (iRomNode->iHidden || iHidden)?"hidden":"", aBuf);
+		else
+			Print(aWhere, "%s\t%s\n", (iRomNode->iHidden || iHidden)?"hidden":"", aBuf);
+		}
+	else
+		{
+		if(iFileName)
+			Print(aWhere, "%s\t%d\n", iFileName, RealFileSize());
+		}
+
+}
--- a/imgtools/romtools/rofsbuild/r_coreimage.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rofsbuild/r_coreimage.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,699 +1,614 @@
-/*
-* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include <string.h>
-#include "h_utl.h"
-
-#include <e32std.h>
-#include <e32std_private.h>
-#include "rofs.h"
-
-#include "r_obey.h"
-#include "r_coreimage.h"
-
-// -----------------------------------------------------------
-//  RCoreImageReader
-// -----------------------------------------------------------
-
-/**
-Constructs reader for the specified file.
-
-@param aFilename Filename for core image file
-*/
-	RCoreImageReader::RCoreImageReader(char* aFilename) : 
-			iImageType(E_UNKNOWN), iCoreImage(0), iFilename(aFilename)
-	{
-	}
-
-/**
-Closes the core image file if it was opened.
-*/
-RCoreImageReader::~RCoreImageReader() 
-	{
-	if (iCoreImage)
-		fclose(iCoreImage);
-	iCoreImage = 0;
-	}
-
-/**
-Opens the image file that was specified at construction.
-
-@return ETrue if file was opened successfully otherwise returns EFalse
-*/
-TBool RCoreImageReader::Open()
-	{
-	iCoreImage = fopen(iFilename, "rb");
-	if (!iCoreImage)
-		{
-		Print(EError, "Cannot open image file %s\n", iFilename);
-		return EFalse;
-		}
-	return ETrue;
-	}
-
-/**
-Reads the image type from the core image file. It reads the value from the
-file and then translates it into the internal enum used for processing 
-the images. 
-
-@return Image type
-*/
-RCoreImageReader::TImageType RCoreImageReader::ReadImageType() 
-	{
-	iImageType = E_UNKNOWN;
-	if ( ReadIdentifier() == KErrNone)
-		{
-		if (iIdentifier[0] == 'R' &&
-				iIdentifier[1] == 'O' &&
-				iIdentifier[2] == 'F')
-			{
-			if (iIdentifier[3] == 'S')
-				iImageType = E_ROFS;
-			else if (iIdentifier[3] == 'x')
-				iImageType = E_ROFX;
-			}
-		}
-	return iImageType;
-	}
-
-/** 
-Reads the 4 byte image type identifier from the core image file.
-
-@return KErrNone for successful read or error number if failed 
-*/
-TInt RCoreImageReader::ReadIdentifier()
-	{
-	int itemsRead = fread(&iIdentifier, sizeof(TUint8), K_ID_SIZE, iCoreImage);
-	TInt result = ImageError(itemsRead,  K_ID_SIZE, "Read Identifier");
-	if (result != KErrNone)
-		{
-		iIdentifier[0] = 0;
-		}
-	return result;
-	}
-
-/**
-Reads the core header from the image file.
-
-@param aHeader space for the header read from the file. Only valid if KErrNone is returned.
-@return KErrNone for successful read or error number if failed 
-*/
-TInt RCoreImageReader::ReadCoreHeader(TRofsHeader& aHeader) 
-	{
-	int itemsRead = fread (&aHeader.iHeaderSize, 
-			(sizeof(TRofsHeader)) - K_ID_SIZE*sizeof(TUint8), 1, iCoreImage);
-	TInt result = ImageError(itemsRead, 1, "Read Core Header");
-	if (result == KErrNone)
-		{
-		// copy the previously read identifier into the header
-		for (int i=0; i<K_ID_SIZE; i++)
-			aHeader.iIdentifier[i] = iIdentifier[i];
-		}
-	return result;
-	}
-
-/**
-Reads the extension header from the image file.
-
-@param aHeader space for the header read from the file. Only valid if KErrNone is returned.
-@return KErrNone for successful read or error number if failed 
-*/
-TInt RCoreImageReader::ReadExtensionHeader(TExtensionRofsHeader& aHeader)
-	{
-	int itemsRead = fread (&aHeader.iHeaderSize, 
-			(sizeof(TExtensionRofsHeader)) - K_ID_SIZE*sizeof(TUint8), 1, iCoreImage);
-	TInt result = ImageError(itemsRead, 1, "Read Extension Header");
-	if (result == KErrNone)
-		{
-		// copy the previously read identifier into the header
-		for (int i=0; i<K_ID_SIZE; i++)
-			aHeader.iIdentifier[i] = iIdentifier[i];
-		}
-	return result;
-	}
-
-/**
-Moves the actual file position to the specified location.
-
-@param aFilePos Desired location for the new position
-*/
-void RCoreImageReader::SetFilePosition(long aFilePos)
-	{
-	fseek(iCoreImage, aFilePos, 0);
-	}
-
-/**
-Validates whether the supplied file position exists in the core image file. 
-It is not sufficient to just move to the required position in the file, 
-but a read needs to be performed as well to ensure that the position exists.
-The method preserves the current file position.
-
-@param aFilePos Desired File Position
-@return ETrue if desired file position exists in file else EFalse
-*/
-TBool RCoreImageReader::IsValidPosition(long aFilePos)
-	{
-	TBool valid = EFalse;
-	long currentPos = ftell(iCoreImage); // save current position
-	
-	int result = fseek(iCoreImage, aFilePos, 0);
-	if (result == 0)
-		{
-		int dummy;
-		int itemsRead = fread(&dummy, sizeof(dummy), 1, iCoreImage);
-
-		if (!ferror(iCoreImage) && !feof(iCoreImage) && result==0 && itemsRead == 1)
-			valid = ETrue;
-		}
-	fseek(iCoreImage, currentPos, 0); // return to previous position
-	return valid;
-	}
-
-/**
-Reads a directory entry from the current position in the core image file. This
-method does not read the variable length TRofsEntry part of the directory entry.
-TRofsEntry does not exist for all directory entries. This is read later by 
-other methods
-
-@param aDir memory where the directory entry is read from the file. This is only valid if KErrNone is returned.
-@return KErrNone for successful read or error number if failed 
-*/
-TInt RCoreImageReader::ReadDirEntry(TRofsDir& aDir)
-	{
-	// read directory without the associated TRofsEntry. The TRofsEntry 
-	// is read later when handling subdirectories
-	int bytesRead = sizeof(TRofsDir) - sizeof(TRofsEntry);
-	int itemsRead = fread (&aDir, bytesRead , 1, iCoreImage);
-	if (ImageError(itemsRead, 1, "Read Dir") == KErrNone)
-		return bytesRead;
-	else
-		return 0;
-	}
-
-/**
-Reads a directory entry from the specified position in the core image file.
-This method moves the position of the file to the specified value and then
-uses the other ReadDirEntry method to read the directory entry
-
-@param aDir memory where the directory entry is read from the file. This is only valid if KErrNone is returned.
-@param aFilePos position in the core image file where the directory
-entry is located
-@return KErrNone for successful read or error number if failed 
-@see RCoreImageReader::ReadDirEntry(TRofsDir* aDir)
-*/
-TInt RCoreImageReader::ReadDirEntry(TRofsDir& aDir, long aFilePos)
-	{
-	SetFilePosition(aFilePos);
-	return ReadDirEntry(aDir);
-	}
-
-/**
-Reads a TRofsEntry from the current file position within the core image.
-
-@param aEntry memory to be used for reading the data from the file. This is only valid if the size returned is greater than zero
-@return size of the entry read
-*/
-TInt RCoreImageReader::ReadRofEntry(TRofsEntry& aEntry)
-	{
-	// need to work out how big entry needs to be from the Struct Size
-	// in TRofsEntry
-	int itemsRead = fread(&aEntry.iStructSize, sizeof(TUint16), 1, iCoreImage);
-	int result = ImageError(itemsRead, 1, "Read Entry Size");
-	if (result == KErrNone)
-		{
-		// read rest of entry excluding the iStructSize
-		itemsRead = fread(&aEntry.iUids[0], sizeof(TRofsEntry) -sizeof(TUint16), 
-				          1, iCoreImage);
-		result = ImageError(itemsRead, 1, "Rest of Entry");
-		// return length read - this include includes iStructSize and first char of name
-		if (result == KErrNone)
-			return sizeof(TRofsEntry);	
-		}
-	return 0;
-	}
-
-/**
-Reads a TRofsEntry from the specified position within the core image
-
-@param aEntry memory to be used for reading the data from the file. This is only valid if the size returned is greater than zero
-@param aFilePos position in the core image file where the entry is located
-@return size of the entry read
-*/
-TInt RCoreImageReader::ReadRofEntry(TRofsEntry& aEntry, long aFilePos)
-	{
-	fseek(iCoreImage, aFilePos, 0);
-	return ReadRofEntry(aEntry);
-	}
-
-/**
-Reads a name of the specified length from the core image file.
-
-@param aName memory for the name read from the file. Only valid if KErrNone is returned
-@param aLength length of name to be read
-@return KErrNone for successful read or error number if failed 
-*/
-TInt RCoreImageReader::ReadRofEntryName(TUint16* aName, int aLength)
-	{
-	int itemsRead = fread(aName, sizeof(TUint16), aLength, iCoreImage);
-	return ImageError(itemsRead, aLength, "Rof Entry Name");
-	}
-
-/**
-Provides the current file position in the core image file.
-
-@return Current file position
-*/
-long  RCoreImageReader::FilePosition()
-	{
-	return ftell(iCoreImage);
-	}
-
-/** 
-Provides the name of the core image file being read.
-
-@return Core image Filename
-*/
-TText* RCoreImageReader::Filename()
-	{
-	return (TText *)iFilename;
-	}
-
-/**
-Determines whether the last read from the file was valid or not.
-It checks that the number of items read where the same number as expected,
-that there are no file errors and that the end of file was not reached. If an
-error is found than a message is printed and the appropriate error number is 
-returned.
-
-@param aItemsRead Number of items read
-@param aExpected Number of items expected to have been read
-@param aInfo Used by the caller to identify where the error occurred.
-@return Error number. KErrNone is returned if there are no errors.
-*/
-TInt RCoreImageReader::ImageError(int aItemsRead, int aExpected, char *aInfo)
-	{
-	if (aItemsRead != aExpected)
-		{
-		Print(EError, "Read From Core Image Failed (%s) \n", aInfo);
-		return KErrCorrupt;
-		}
-	if (int errnum = ferror(iCoreImage))
-		{
-		Print(EError, "Core Image File Error (%s) : %d\n", aInfo, errnum);
-		return KErrCorrupt;
-		}
-	if (feof(iCoreImage))
-		{
-		Print(EError, "Premature End of File Detected (%s)\n", aInfo);
-		return KErrEof;
-		}
-	return KErrNone;
-	}
-
-// -----------------------------------------------------------
-//  CCoreImage 
-// -----------------------------------------------------------
-
-/**
-Initialises the reader to be used for accessing the core image file
-
-@param aReader Reader to be used for accessing the core image file
-*/
-CCoreImage::CCoreImage(RCoreImageReader* aReader) : iReader(aReader),
-	iRootDirectory(0), iFileEntries(0), iDirTreeOffset(0),
-	iDirTreeSize(0), iDirFileEntriesOffset(0),
-iDirFileEntriesSize(0), iRomFileName(0), iImageSize(0)
-	{
-	}
-
-/**
-Deletes the directory tree that was created from the core image.
-*/
-CCoreImage::~CCoreImage()
-	{
-	delete iRootDirectory;
-	iRootDirectory=0;
-	}
-
-
-/**
-Creates the node to be used as the root directory of the directory tree.
-
-@return KErrNone for successful read or error number if failed 
-*/
-TInt CCoreImage::CreateRootDir()
-	{
-	iRootDirectory = new TRomNode((TText*)"");
-	if (iRootDirectory == 0 )
-		return KErrNoMemory;
-	return KErrNone;
-	}
-
-/**
-Processes the core image file to produce a directory tree.
-
-@return KErrNone for successful read or error number if failed 
-*/
-TInt CCoreImage::ProcessImage()
-	{
-	iRomFileName = iReader->Filename();
-	int result = CreateRootDir();
-	if (result == KErrNone)
-		{
-		if (iReader->Open())
-			{
-			RCoreImageReader::TImageType imageType = iReader->ReadImageType();
-			if (imageType == RCoreImageReader::E_ROFS)
-				{
-				TRofsHeader header;
-				result = iReader->ReadCoreHeader(header);
-				if (result == KErrNone)
-					{
-					SaveDirInfo(header);
-					result = ProcessDirectory(0);
-					}
-				}
-			else
-				result = KErrNotSupported;
-			}
-		else
-			result = KErrGeneral;
-		}
-	return result;
-	}
-
-/**
-Processes the directory in the core image file.
-
-@param aAdjustment The difference between offsets in the core image directory and
-@return KErrNone for successful read or error number if failed 
-*/
-TInt CCoreImage::ProcessDirectory(long aAdjustment)
-	{
-	long filePos = iDirTreeOffset - aAdjustment;
-	TDirectoryEntry *firstDir = new TDirectoryEntry(filePos, iReader, iRootDirectory);
-	if (firstDir == 0)
-		return KErrNoMemory;
-	TInt result = firstDir->Process(aAdjustment);
-	delete firstDir;
-	return result;
-	}
-
-/**
-Saves directory information from core image header for later usage.
-
-@param aHeader Header containing information to be saved
-*/
-void CCoreImage::SaveDirInfo(TRofsHeader& aHeader)
-	{
-	iDirTreeOffset = aHeader.iDirTreeOffset;
-	iDirTreeSize = aHeader.iDirTreeSize;
-	iDirFileEntriesOffset = aHeader.iDirFileEntriesOffset;
-	iDirFileEntriesSize = aHeader.iDirFileEntriesSize;
-	iImageSize = aHeader.iMaxImageSize;
-	}
-
-/**
-Saves directory information from extension image header for later usage.
-
-@param aHeader Header containing information to be saved
-*/
-void CCoreImage::SaveDirInfo(TExtensionRofsHeader& aHeader)
-	{
-	iDirTreeOffset = aHeader.iDirTreeOffset;
-	iDirTreeSize = aHeader.iDirTreeSize;
-	iDirFileEntriesOffset = aHeader.iDirFileEntriesOffset;
-	iDirFileEntriesSize = aHeader.iDirFileEntriesSize;
-	iImageSize = aHeader.iMaxImageSize;
-	}
-
-/**
-Displays the directory tree. This is used for debug purposes only.
-*/
-void CCoreImage::Display(ostream* aOut)
-	{
-	iRootDirectory->DisplayStructure(aOut);
-	}
-
-/**
-Reads offset where directory tree starts in core image.
-
-@return offset of directory tree in image
-*/
-long CCoreImage::DirTreeOffset()
-	{
-	return iDirTreeOffset;
-	}
-
-TRomNode* CCoreImage::CopyDirectory(TRomNode*& aSourceDirectory)
-	{
-	return iRootDirectory->CopyDirectory(aSourceDirectory);
-	}
-
-TRomNode* CCoreImage::RootDirectory()
-	{
-	return iRootDirectory;
-	}
-
-void CCoreImage::SetRootDirectory(TRomNode* aDir)
-	{
-	iRootDirectory = aDir;
-	}
-
-TText* CCoreImage::RomFileName()
-	{
-	return iRomFileName;
-	}
-
-TInt CCoreImage::Size()
-	{
-	return iImageSize;
-	}
-
-// -----------------------------------------------------------
-//  TDirectoryEntry 
-// -----------------------------------------------------------
-
-/**
-Initialises the directory entry
-
-@param aFilePos Position within file where the directory entry is located
-@param aReader Handle used to access the file;
-@param aDir The TRomNode associated with this directory
-*/
-TDirectoryEntry::TDirectoryEntry(long aFilePos, RCoreImageReader* aReader, 
-		TRomNode* aDir) :
-			iReader(aReader),  iCurrentDir(aDir),iFilePos(aFilePos),
-			iAdjustment(0) 
-	{
-	}
-
-/**
-Empty destructor.
-*/
-TDirectoryEntry::~TDirectoryEntry()
-	{
-	}
-
-/**
-Processes the current directory entry. If the directory has any files it will 
-create the appropriate file entries in the directory tree. If the directory 
-has any subdirectories it will create nodes in the directory tree and will 
-create an TDirectoryEntry and then use that to process the subdirectory
-
-@param aAdjustment The difference between offsets in the core image directory and
-the actual position in the file
-*/
-TInt TDirectoryEntry::Process(long aAdjustment)
-	{
-	TRofsDir dir;
-	iAdjustment = aAdjustment;
-	long dirStartPos = iFilePos;
-	int result = KErrNone;
-	int dirSize = iReader->ReadDirEntry(dir, iFilePos);
-	if (dirSize != 0)
-		{
-		if (dir.iFileBlockAddress != 0)
-			{
-			// directory has files in it
-			result = AddFiles(dir.iFileBlockAddress-iAdjustment, dir.iFileBlockSize);
-			}
-		if (result == KErrNone && dir.iStructSize > dirSize)
-			{
-			// directory has subdirectories
-			result = AddSubDirs(dirStartPos + dir.iStructSize);
-			}
-		}
-	else 
-		result = KErrGeneral;
-
-	return result;
-	}
-
-/**
-Processes the subdirectories in the current directory. For each subdirectory
-a TDirectoryEntry is created and is then used to process the directory
-
-@param aEndDirPos Position where the directory block finishes. This is to determine when all subdirectories have been processed
-*/
-TInt TDirectoryEntry::AddSubDirs(long aEndDirPos)
-	{
-	TRofsEntry entry;
-	iFilePos = iReader->FilePosition();
-	TInt result = KErrNone;
-	while (iFilePos < aEndDirPos && result == KErrNone)
-		{
-		TInt size = iReader->ReadRofEntry(entry, iFilePos);
-		if (size >0)
-			{
-			TText* nameStr = GetName(entry.iName[0], entry.iNameLength);
-			if (nameStr !=0)
-				{
-				TRomNode *dir = iCurrentDir->NewSubDir(nameStr);
-				TDirectoryEntry *subDir = new TDirectoryEntry(
-						entry.iFileAddress-iAdjustment, iReader, dir);
-				if (subDir != 0)
-					{
-					// now process the subdirectory
-					subDir->Process(iAdjustment);
-					iFilePos += entry.iStructSize;
-					// round to nearest word boundary
-					iFilePos += (4-entry.iStructSize) & 3;
-					}
-				else
-					result = KErrNoMemory;
-
-                if (subDir)
-                {
-                    delete subDir;
-                }
-				}
-			else
-				result = KErrNoMemory;
-			if(nameStr != 0)
-				delete [] nameStr;
-			}
-		else
-			{
-			result = KErrGeneral;
-			}
-		}
-	return result;
-	}
-
-/**
-Processes a file entries block in the directory and creates the appropriate 
-nodes for each file in the block
-
-@param aStartPosition start for file block in the core image file
-@param aSize size of the file entries block
-*/
-TInt TDirectoryEntry::AddFiles(long aStartPosition, int aSize )
-	{
-	long savedPosition = iReader->FilePosition();
-	long currentPos = aStartPosition;
-	iReader->SetFilePosition(aStartPosition);
-	long endPos = aStartPosition+aSize;
-	TRofsEntry entry;
-	TInt result = KErrNone;
-	while (currentPos < endPos && result == KErrNone)	
-		{
-		TInt size = iReader->ReadRofEntry(entry, currentPos);
-		if (size > 0)
-			{
-			TText *nameStr = GetName(entry.iName[0], entry.iNameLength);
-			if (nameStr != 0)
-				{
-				result = CreateFileEntry(nameStr, entry);
-				currentPos += entry.iStructSize;
-				}
-			else
-				result = KErrNoMemory;
-			if(nameStr != 0)
-			    delete [] nameStr;
-			}
-		else
-			{
-			result = KErrGeneral;
-			}
-		}
-	iReader->SetFilePosition(savedPosition);
-	return result;
-	}
-
-/** 
-Creates a new node for a file entry and the associated TRomBuilderEntry.
-
-@param aNameStr Name of the file entry to be created
-@param aFileAddress Address of file in the core image
-@param aFileSize Size of the file
-*/
-TInt TDirectoryEntry::CreateFileEntry(TText* aNameStr, TRofsEntry& aRofsEntry)
-	{
-	TRomBuilderEntry *fileEntry = new TRomBuilderEntry(0,aNameStr);
-	if (fileEntry == 0)
-		return KErrNoMemory;
-
-	memcpy(&fileEntry->iUids[0], &aRofsEntry.iUids[0], sizeof(fileEntry->iUids));
-	fileEntry->iFileOffset = aRofsEntry.iFileAddress;
-	fileEntry->SetRealFileSize(aRofsEntry.iFileSize);
-	TRomNode *file = new TRomNode(aNameStr, fileEntry);
-	file->iSize = aRofsEntry.iFileSize;
-	if (file == 0)
-		{
-		delete fileEntry;
-		return KErrNoMemory;
-		}
-	file->iAtt = aRofsEntry.iAtt;
-	file->iAttExtra = aRofsEntry.iAttExtra;
-	iCurrentDir->AddFile(file);
-	return KErrNone;
-	}
-
-/**
-Gets the name of a file or directory from the core image. The first character
-of the name has already been read.
-
-@param aFirstChar first character of name (already read by TRofsEntry)
-@param aLength Length of name to be read (including the first character)
-*/
-TText* TDirectoryEntry::GetName(TUint16 aFirstChar, TInt aLength)
-	{
-	TText *nameStr = 0;
-	TUint16* name = new TUint16[aLength];
-	if (name !=0)
-		{
-		name[0] = aFirstChar;
-		TInt result = iReader->ReadRofEntryName(&name[1], aLength-1);
-		if (result == KErrNone)
-			{
-			nameStr = new TText[aLength+1];
-			if (nameStr != 0)
-				{
-				for (int i=0; i< aLength; i++)
-					{
-					nameStr[i] = (TText) name[i];
-					}
-				nameStr[aLength]=0;
-				}
-			}
-		delete [] name;
-		}
-	return nameStr;
-	}
-
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#include <string.h>
+#include "h_utl.h"
+
+#include <e32std.h>
+#include <e32std_private.h>
+#include "rofs.h"
+
+#include "r_obey.h"
+#include "r_coreimage.h"
+#include "utf16string.h"
+// -----------------------------------------------------------
+//  RCoreImageReader
+// -----------------------------------------------------------
+
+/**
+Constructs reader for the specified file.
+
+@param aFilename Filename for core image file
+*/
+RCoreImageReader::RCoreImageReader(const char* aFilename) : 
+iImageType(E_UNKNOWN),  iFilename(aFilename) {
+}
+
+/**
+Closes the core image file if it was opened.
+*/
+RCoreImageReader::~RCoreImageReader()  {
+	if (iCoreImage.is_open())
+		iCoreImage.close(); 
+}
+
+/**
+Opens the image file that was specified at construction.
+
+@return ETrue if file was opened successfully otherwise returns EFalse
+*/
+TBool RCoreImageReader::Open() {
+	if(iCoreImage.is_open()) {
+		iCoreImage.seekg(0,ios_base::beg);
+	}else{
+		iCoreImage.open(iFilename.c_str(), ios_base::in + ios_base::binary);
+		if (!iCoreImage.is_open()) {
+			Print(EError, "Cannot open image file %s\n", iFilename.c_str());
+			return EFalse;
+		}
+	}
+
+	return ETrue;
+}
+
+/**
+Reads the image type from the core image file. It reads the value from the
+file and then translates it into the internal enum used for processing 
+the images. 
+
+@return Image type
+*/
+RCoreImageReader::TImageType RCoreImageReader::ReadImageType()  {
+	iImageType = E_UNKNOWN;
+	iCoreImage.seekg(0,ios_base::beg);
+	if ( ReadIdentifier() == KErrNone) {
+		if (iIdentifier[0] == 'R' &&
+			iIdentifier[1] == 'O' &&
+			iIdentifier[2] == 'F') {
+			if (iIdentifier[3] == 'S')
+				iImageType = E_ROFS;
+			else if (iIdentifier[3] == 'x')
+				iImageType = E_ROFX;
+		}
+	}
+	return iImageType;
+}
+
+/** 
+Reads the 4 byte image type identifier from the core image file.
+
+@return KErrNone for successful read or error number if failed 
+*/
+TInt RCoreImageReader::ReadIdentifier() {
+
+	iCoreImage.read(reinterpret_cast<char*>(&iIdentifier[0]),K_ID_SIZE);
+	TInt result = ImageError(iCoreImage.gcount(),  K_ID_SIZE, "Read Identifier");
+	if (result != KErrNone) {
+		iIdentifier[0] = 0;
+	}
+	return result;
+}
+
+/**
+Reads the core header from the image file.
+
+@param aHeader space for the header read from the file. Only valid if KErrNone is returned.
+@return KErrNone for successful read or error number if failed 
+*/
+TInt RCoreImageReader::ReadCoreHeader(TRofsHeader& aHeader)  {
+	int bytesRead  =  sizeof(TRofsHeader) - K_ID_SIZE; 
+	iCoreImage.read(reinterpret_cast<char*>(&aHeader.iHeaderSize),bytesRead ); 
+	TInt result = ImageError(iCoreImage.gcount(),bytesRead, "Read Core Header");
+	if (result == KErrNone) {
+		// copy the previously read identifier into the header
+		for (int i=0; i<K_ID_SIZE; i++)
+			aHeader.iIdentifier[i] = iIdentifier[i];
+	}
+	return result;
+}
+
+/**
+Reads the extension header from the image file.
+
+@param aHeader space for the header read from the file. Only valid if KErrNone is returned.
+@return KErrNone for successful read or error number if failed 
+*/
+TInt RCoreImageReader::ReadExtensionHeader(TExtensionRofsHeader& aHeader) {
+	int bytesRead =  sizeof(TExtensionRofsHeader) - K_ID_SIZE; 
+	iCoreImage.read(reinterpret_cast<char*>(&aHeader.iHeaderSize),bytesRead); 
+	TInt result = ImageError(iCoreImage.gcount(),bytesRead,  "Read Extension Header");
+	if (result == KErrNone) {
+		// copy the previously read identifier into the header
+		for (int i=0; i<K_ID_SIZE; i++)
+			aHeader.iIdentifier[i] = iIdentifier[i];
+	}
+	return result;
+}
+
+/**
+Moves the actual file position to the specified location.
+
+@param aFilePos Desired location for the new position
+*/
+void RCoreImageReader::SetFilePosition(size_t aFilePos) {
+	iCoreImage.seekg(aFilePos, ios_base::beg);
+}
+
+/**
+Validates whether the supplied file position exists in the core image file. 
+It is not sufficient to just move to the required position in the file, 
+but a read needs to be performed as well to ensure that the position exists.
+The method preserves the current file position.
+
+@param aFilePos Desired File Position
+@return ETrue if desired file position exists in file else EFalse
+*/
+TBool RCoreImageReader::IsValidPosition(size_t aFilePos) {
+	TBool valid = EFalse;
+	size_t currentPos = iCoreImage.tellg(); // save current position	
+	iCoreImage.seekg(aFilePos, ios_base::beg);
+	if (!iCoreImage.fail() && !iCoreImage.eof() ) {
+		int dummy;
+		iCoreImage.read(reinterpret_cast<char*>(&dummy), sizeof(dummy));
+		int bytesRead = iCoreImage.gcount();
+		if(bytesRead == sizeof(dummy) && !iCoreImage.fail() || !iCoreImage.eof())
+			valid = ETrue;
+	}
+	iCoreImage.seekg(currentPos, ios_base::beg); // return to previous position
+	return valid;
+}
+
+/**
+Reads a directory entry from the current position in the core image file. This
+method does not read the variable length TRofsEntry part of the directory entry.
+TRofsEntry does not exist for all directory entries. This is read later by 
+other methods
+
+@param aDir memory where the directory entry is read from the file. This is only valid if KErrNone is returned.
+@return KErrNone for successful read or error number if failed 
+*/
+TInt RCoreImageReader::ReadDirEntry(TRofsDir& aDir) {
+	// read directory without the associated TRofsEntry. The TRofsEntry 
+	// is read later when handling subdirectories
+	int bytesRead = sizeof(TRofsDir) - sizeof(TRofsEntry);
+	iCoreImage.read(reinterpret_cast<char*>(&aDir), bytesRead);
+	if (ImageError(iCoreImage.gcount(), bytesRead, "Read Dir") == KErrNone)
+		return bytesRead;
+	else
+		return 0;
+}
+
+/**
+Reads a directory entry from the specified position in the core image file.
+This method moves the position of the file to the specified value and then
+uses the other ReadDirEntry method to read the directory entry
+
+@param aDir memory where the directory entry is read from the file. This is only valid if KErrNone is returned.
+@param aFilePos position in the core image file where the directory
+entry is located
+@return KErrNone for successful read or error number if failed 
+@see RCoreImageReader::ReadDirEntry(TRofsDir* aDir)
+*/
+TInt RCoreImageReader::ReadDirEntry(TRofsDir& aDir, size_t aFilePos) {
+	SetFilePosition(aFilePos);
+	return ReadDirEntry(aDir);
+}
+
+/**
+Reads a TRofsEntry from the current file position within the core image.
+
+@param aEntry memory to be used for reading the data from the file. This is only valid if the size returned is greater than zero
+@return size of the entry read
+*/
+TInt RCoreImageReader::ReadRofEntry(TRofsEntry& aEntry) {
+	// need to work out how big entry needs to be from the Struct Size
+	// in TRofsEntry
+	iCoreImage.read(reinterpret_cast<char*>(&aEntry.iStructSize), sizeof(TUint16));
+	int result = ImageError(iCoreImage.gcount(), sizeof(TUint16), "Read Entry Size");
+	if (result == KErrNone) {
+		// read rest of entry excluding the iStructSize
+		int bytesRead = sizeof(TRofsEntry) -sizeof(TUint16);
+		iCoreImage.read(reinterpret_cast<char*>(&aEntry.iUids[0]),bytesRead);
+		result = ImageError(iCoreImage.gcount(), bytesRead, "Rest of Entry");
+		// return length read - this include includes iStructSize and first char of name
+		if (result == KErrNone)
+			return sizeof(TRofsEntry);	
+	}
+	return 0;
+}
+
+/**
+Reads a TRofsEntry from the specified position within the core image
+
+@param aEntry memory to be used for reading the data from the file. This is only valid if the size returned is greater than zero
+@param aFilePos position in the core image file where the entry is located
+@return size of the entry read
+*/
+TInt RCoreImageReader::ReadRofEntry(TRofsEntry& aEntry, size_t aFilePos) {
+	SetFilePosition(aFilePos);
+	return ReadRofEntry(aEntry);
+}
+
+/**
+Reads a name of the specified length from the core image file.
+
+@param aName memory for the name read from the file. Only valid if KErrNone is returned
+@param aLength length of name to be read
+@return KErrNone for successful read or error number if failed 
+*/
+TInt RCoreImageReader::ReadRofEntryName(TUint16* aName, int aLength) {
+	int bytesRead = aLength << 1;	
+	iCoreImage.read(reinterpret_cast<char*>(aName), bytesRead);
+	return ImageError(iCoreImage.gcount(), bytesRead, "Rof Entry Name");
+}
+
+/**
+Provides the current file position in the core image file.
+
+@return Current file position
+*/
+size_t  RCoreImageReader::FilePosition() {
+	return iCoreImage.tellg();
+}
+
+/** 
+Provides the name of the core image file being read.
+
+@return Core image Filename
+*/
+const char* RCoreImageReader::Filename() const {
+	return iFilename.c_str();
+}
+
+/**
+Determines whether the last read from the file was valid or not.
+It checks that the number of items read where the same number as expected,
+that there are no file errors and that the end of file was not reached. If an
+error is found than a message is printed and the appropriate error number is 
+returned.
+
+@param aItemsRead Number of items read
+@param aExpected Number of items expected to have been read
+@param aInfo Used by the caller to identify where the error occurred.
+@return Error number. KErrNone is returned if there are no errors.
+*/
+TInt RCoreImageReader::ImageError(int aItemsRead, int aExpected, char *aInfo) {
+	if (aItemsRead != aExpected) {
+		Print(EError, "Read From Core Image Failed (%s) \n", aInfo);
+		return KErrCorrupt;
+	} 
+	if (iCoreImage.eof()) {
+		Print(EError, "Premature End of File Detected (%s)\n", aInfo);
+		return KErrEof;
+	}
+	return KErrNone;
+}
+
+// -----------------------------------------------------------
+//  CCoreImage 
+// -----------------------------------------------------------
+
+/**
+Initialises the reader to be used for accessing the core image file
+
+@param aReader Reader to be used for accessing the core image file
+*/
+CCoreImage::CCoreImage(RCoreImageReader* aReader) : iReader(aReader),
+iRootDirectory(0), iFileEntries(0), iDirTreeOffset(0),
+iDirTreeSize(0), iDirFileEntriesOffset(0),
+iDirFileEntriesSize(0), iImageSize(0) {
+}
+
+/**
+Deletes the directory tree that was created from the core image.
+*/
+CCoreImage::~CCoreImage() {
+	if(iRootDirectory){
+		iRootDirectory->Destroy() ;
+		iRootDirectory = 0 ;
+	} 
+}
+
+
+/**
+Creates the node to be used as the root directory of the directory tree.
+
+@return KErrNone for successful read or error number if failed 
+*/
+TInt CCoreImage::CreateRootDir() {
+	iRootDirectory = new TRomNode("");
+	if (iRootDirectory == 0 )
+		return KErrNoMemory;
+	return KErrNone;
+}
+
+/**
+Processes the core image file to produce a directory tree.
+
+@return KErrNone for successful read or error number if failed 
+*/
+TInt CCoreImage::ProcessImage() {
+	iRomFileName = iReader->Filename();
+	int result = CreateRootDir();
+	if (result == KErrNone) {
+		if (iReader->Open()) {
+			RCoreImageReader::TImageType imageType = iReader->ReadImageType();
+			if (imageType == RCoreImageReader::E_ROFS) {
+				TRofsHeader header;
+				result = iReader->ReadCoreHeader(header);
+				if (result == KErrNone) {
+					SaveDirInfo(header);
+					result = ProcessDirectory(0);
+				}
+			}
+			else
+				result = KErrNotSupported;
+		}
+		else
+			result = KErrGeneral;
+	}
+	return result;
+}
+
+/**
+Processes the directory in the core image file.
+
+@param aAdjustment The difference between offsets in the core image directory and
+@return KErrNone for successful read or error number if failed 
+*/
+TInt CCoreImage::ProcessDirectory(long aAdjustment) {
+	long filePos = iDirTreeOffset - aAdjustment;
+	TDirectoryEntry *firstDir = new TDirectoryEntry(filePos, iReader, iRootDirectory);
+	if (firstDir == 0)
+		return KErrNoMemory;
+	TInt result = firstDir->Process(aAdjustment);
+	delete firstDir;
+	return result;
+}
+
+/**
+Saves directory information from core image header for later usage.
+
+@param aHeader Header containing information to be saved
+*/
+void CCoreImage::SaveDirInfo(TRofsHeader& aHeader) {
+	iDirTreeOffset = aHeader.iDirTreeOffset;
+	iDirTreeSize = aHeader.iDirTreeSize;
+	iDirFileEntriesOffset = aHeader.iDirFileEntriesOffset;
+	iDirFileEntriesSize = aHeader.iDirFileEntriesSize;
+	iImageSize = aHeader.iMaxImageSize;
+}
+
+/**
+Saves directory information from extension image header for later usage.
+
+@param aHeader Header containing information to be saved
+*/
+void CCoreImage::SaveDirInfo(TExtensionRofsHeader& aHeader) {
+	iDirTreeOffset = aHeader.iDirTreeOffset;
+	iDirTreeSize = aHeader.iDirTreeSize;
+	iDirFileEntriesOffset = aHeader.iDirFileEntriesOffset;
+	iDirFileEntriesSize = aHeader.iDirFileEntriesSize;
+	iImageSize = aHeader.iMaxImageSize;
+}
+
+/**
+Displays the directory tree. This is used for debug purposes only.
+*/
+void CCoreImage::Display(ostream* aOut) {
+	iRootDirectory->DisplayStructure(aOut);
+}
+
+/**
+Reads offset where directory tree starts in core image.
+
+@return offset of directory tree in image
+*/
+long CCoreImage::DirTreeOffset() {
+	return iDirTreeOffset;
+}
+
+TRomNode* CCoreImage::CopyDirectory(TRomNode*& aSourceDirectory) {
+	return iRootDirectory->CopyDirectory(aSourceDirectory);
+}
+
+TRomNode* CCoreImage::RootDirectory() {
+	return iRootDirectory;
+}
+
+void CCoreImage::SetRootDirectory(TRomNode* aDir) {
+	iRootDirectory = aDir;
+}
+
+const char* CCoreImage::RomFileName() const {
+	return iRomFileName.c_str();
+}
+
+TInt CCoreImage::Size() const {
+	return iImageSize;
+}
+
+// -----------------------------------------------------------
+//  TDirectoryEntry 
+// -----------------------------------------------------------
+
+/**
+Initialises the directory entry
+
+@param aFilePos Position within file where the directory entry is located
+@param aReader Handle used to access the file;
+@param aDir The TRomNode associated with this directory
+*/
+TDirectoryEntry::TDirectoryEntry(long filePos, RCoreImageReader* aReader,  TRomNode* aDir) :
+iReader(aReader),  iCurrentDir(aDir),iFilePos(filePos),
+iAdjustment(0)  {
+}
+
+/**
+Empty destructor.
+*/
+TDirectoryEntry::~TDirectoryEntry() {
+}
+
+/**
+Processes the current directory entry. If the directory has any files it will 
+create the appropriate file entries in the directory tree. If the directory 
+has any subdirectories it will create nodes in the directory tree and will 
+create an TDirectoryEntry and then use that to process the subdirectory
+
+@param aAdjustment The difference between offsets in the core image directory and
+the actual position in the file
+*/
+TInt TDirectoryEntry::Process(long aAdjustment) {
+	TRofsDir dir;
+	iAdjustment = aAdjustment;
+	long dirStartPos = iFilePos;
+	int result = KErrNone;
+	int dirSize = iReader->ReadDirEntry(dir, iFilePos);
+	if (dirSize != 0) {
+		if (dir.iFileBlockAddress != 0) {
+			// directory has files in it
+			result = AddFiles(dir.iFileBlockAddress-iAdjustment, dir.iFileBlockSize);
+		}
+		if (result == KErrNone && dir.iStructSize > dirSize) {
+			// directory has subdirectories
+			result = AddSubDirs(dirStartPos + dir.iStructSize);
+		}
+	}
+	else 
+		result = KErrGeneral;
+
+	return result;
+}
+
+/**
+Processes the subdirectories in the current directory. For each subdirectory
+a TDirectoryEntry is created and is then used to process the directory
+
+@param aEndDirPos Position where the directory block finishes. This is to determine when all subdirectories have been processed
+*/
+TInt TDirectoryEntry::AddSubDirs(long aEndDirPos) {
+	TRofsEntry entry;
+	iFilePos = iReader->FilePosition();
+	TInt result = KErrNone;
+	string name ;
+	while (iFilePos < aEndDirPos && result == KErrNone) {
+		TInt size = iReader->ReadRofEntry(entry, iFilePos);
+		UTF16String uniName ;
+		if (size >0) {
+			TUint16* nameBuf = uniName.Alloc(entry.iNameLength);
+			*nameBuf = entry.iName[0];
+			result = iReader->ReadRofEntryName(&nameBuf[1],entry.iNameLength - 1);
+			if(result != KErrNone){ 
+				return result ;
+			} 
+			if (uniName.ToUTF8(name)) { 
+				TRomNode *dir = iCurrentDir->NewSubDir(name.c_str());
+				TDirectoryEntry *subDir = new TDirectoryEntry(
+					entry.iFileAddress-iAdjustment, iReader, dir);
+				if (subDir != 0) {
+					// now process the subdirectory
+					subDir->Process(iAdjustment);
+					iFilePos += entry.iStructSize;
+					// round to nearest word boundary
+					iFilePos += (4-entry.iStructSize) & 3;
+				}
+				else
+					result = KErrNoMemory;
+
+				if (subDir) {
+					delete subDir;
+				}
+			}
+			else
+				result = KErrNoMemory;
+		}
+		else {
+			result = KErrGeneral;
+		}
+	}
+	return result;
+}
+
+/**
+Processes a file entries block in the directory and creates the appropriate 
+nodes for each file in the block
+
+@param aStartPosition start for file block in the core image file
+@param aSize size of the file entries block
+*/
+TInt TDirectoryEntry::AddFiles(long aStartPosition, int aSize ) {
+	long savedPosition = iReader->FilePosition();
+	long currentPos = aStartPosition;
+	iReader->SetFilePosition(aStartPosition);
+	long endPos = aStartPosition+aSize;
+	TRofsEntry entry;
+	TInt result = KErrNone;
+	string name ;
+	UTF16String uniName;
+	while (currentPos < endPos && result == KErrNone)	 {
+		TInt size = iReader->ReadRofEntry(entry, currentPos);
+		if (size > 0) {
+			TUint16* nameBuf = uniName.Alloc(entry.iNameLength);
+			*nameBuf = entry.iName[0] ;			
+			result = iReader->ReadRofEntryName(&nameBuf[1],entry.iNameLength - 1);
+			if(result != KErrNone){ 
+				return result ;
+			}  
+			if (uniName.ToUTF8(name)) {
+				result = CreateFileEntry(name.c_str(), entry);
+				currentPos += entry.iStructSize;
+			}
+			else
+				result = KErrNoMemory;
+		}
+		else {
+			result = KErrGeneral;
+		}
+	}
+	iReader->SetFilePosition(savedPosition);
+	return result;
+}
+
+/** 
+Creates a new node for a file entry and the associated TRomBuilderEntry.
+
+@param aNameStr Name of the file entry to be created
+@param aFileAddress Address of file in the core image
+@param aFileSize Size of the file
+*/
+TInt TDirectoryEntry::CreateFileEntry(const char* aNameStr, TRofsEntry& aRofsEntry) {
+	TRomBuilderEntry *fileEntry = new TRomBuilderEntry(0,aNameStr);
+	if (fileEntry == 0)
+		return KErrNoMemory;
+
+	memcpy(&fileEntry->iUids[0], &aRofsEntry.iUids[0], sizeof(fileEntry->iUids));
+	fileEntry->iFileOffset = aRofsEntry.iFileAddress;
+	fileEntry->SetRealFileSize(aRofsEntry.iFileSize);
+	TRomNode *file = new TRomNode(aNameStr, fileEntry);
+	file->iSize = aRofsEntry.iFileSize;
+	if (file == 0) {
+		delete fileEntry;
+		return KErrNoMemory;
+	}
+	file->iAtt = aRofsEntry.iAtt;
+	file->iAttExtra = aRofsEntry.iAttExtra;
+	iCurrentDir->AddFile(file);
+	return KErrNone;
+}
+
--- a/imgtools/romtools/rofsbuild/r_coreimage.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rofsbuild/r_coreimage.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,204 +1,206 @@
-/*
-* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifndef __R_COREIMAGE_H__
-#define __R_COREIMAGE_H__
-
-class TRomNode;
-class E32Rofs;
-
-/**
-@internalComponent
-
-MRofsImage is the interface used to access information held within an image.
-This interface used to remove the dependency between processing of 
-extensions and kernel commands in the obey file
-*/
-class MRofsImage
-	{
-public:
-	/** Gets the root directory node from the image
-
-	   @return TRomNode* the first node in the directory tree
-	 */
-	virtual TRomNode* RootDirectory() = 0;
-
-	/** Copies the specified directory tree.
-
-	   @param aSourceDirectory The directory that is to be copied
-	   @return The copied directory tree.
-	 */
-	virtual TRomNode* CopyDirectory(TRomNode*& aSourceDirectory)=0;
-	/** Sets the root directory to be the specified node.
-
-	   @param aDir The node that is to be set as the root directory
-	 */
-	virtual void SetRootDirectory(TRomNode* aDir) = 0;
-	/** Gets the filename of the core image 
-
-	    @returns The filename of the core image file 
-	 */
-	virtual TText* RomFileName() = 0;
-	/** Gets the size of the image file
-
-	   @returns size of file
-	 */
-	virtual TInt Size() = 0;
-	};
-
-const int K_ID_SIZE=4; /** Size of the image header identifier */
-
-/** 
-@internalComponent
-
-Provides the access the actual core image file. All file operations to the 
-core image file are through this class.
-*/
-class RCoreImageReader
-	{
-public:
-	/** Image Type read from header of image file */
-	enum TImageType 
-		{
-		/** Format of file has not been recognised */
-		E_UNKNOWN, 
-		/** File is a core RofsImage file */
-		E_ROFS, 
-		/** File is an extension RofsImage file */
-		E_ROFX
-		};
-
-	RCoreImageReader(char *aFilename);
-	~RCoreImageReader();
-	TBool Open();
-	TImageType ReadImageType();
-	TInt ReadCoreHeader(TRofsHeader& aHeader);
-	TInt ReadExtensionHeader(TExtensionRofsHeader& aHeader);
-
-	TInt ReadDirEntry(TRofsDir& aDir);
-	TInt ReadDirEntry(TRofsDir& aDir, long aFilePos);
-
-	long FilePosition();
-	void SetFilePosition(long aFilePos);
-
-	TInt ReadRofEntry(TRofsEntry& aEntry);
-	TInt ReadRofEntry(TRofsEntry& aEntry, long aFilePos);
-	TInt ReadRofEntryName(TUint16* aName, int aLength);
-	TBool IsValidPosition(long filePos);
-	TText* Filename();
-private:
-	TInt ReadIdentifier();
-	TInt ImageError(int aBytesRead, int aExpected, char* aInfo);
-
-	/** Image type of the file being read */
-	TImageType iImageType;
-	/** File handle of core image being read */
-	FILE* iCoreImage;
-	/** Filename of core image file */
-	char* iFilename;
-	/** Image type identifier read from image header */
-	TUint8 iIdentifier[K_ID_SIZE];
-	};
-
-/** 
-
-@internalComponent
-
-Processes the core image file to create a directory tree.
-It is used when the coreimage option has been specified either
-on the command line or in the obey file. It implements the MRofsImage 
-so it can be used by the extension image processing.
-*/
-class CCoreImage : public MRofsImage
-	{
-public:
-	CCoreImage(RCoreImageReader* aReader);
-	virtual TInt ProcessImage();
-	void Display(ostream* aOut);
-	virtual ~CCoreImage();
-
-	// Implementation of MRofsImage
-	TRomNode* RootDirectory();
-	TRomNode* CopyDirectory(TRomNode*& aSourceDirectory);
-	void SetRootDirectory(TRomNode* aDir);
-	TText* RomFileName();
-	TInt Size();
-
-protected:
-	void SaveDirInfo(TRofsHeader& header);
-	void SaveDirInfo(TExtensionRofsHeader& header);
-	TInt ProcessDirectory(long aAdjustment);
-	TInt CreateRootDir();
-	long DirTreeOffset();
-
-	/** used to read the core image file*/
-	RCoreImageReader *iReader;
-private:
-	/** The node for the root directory */
-	TRomNode *iRootDirectory;
-	/** The first node in list of file entries */
-	TRomBuilderEntry *iFileEntries;
-	/** Offset to the directory tree in the core image */
-	long iDirTreeOffset;
-	/** Size of the directory tree in the core image */
-	long iDirTreeSize;
-	/** Offset to the file entries of the directory in the core image */
-	long iDirFileEntriesOffset;
-	/** Size of the file entries block of the directory */
-	long iDirFileEntriesSize;
-	/** Filename of the rom image file */
-	TText* iRomFileName;
-	/** Size of image */
-	TInt iImageSize;
-	};
-
-/**
-@internalComponent
-
-Used for handling a single directory entry in the core image. This class allows
-the directory tree to be created recursively.
-*/
-class TDirectoryEntry
-	{
-public:
-	TDirectoryEntry(long filePos, RCoreImageReader* aReader, TRomNode* aCurrentDir);
-	~TDirectoryEntry();
-	TInt Process(long adjustment);
-private:
-	TInt CreateFileEntry(TText* aName, TRofsEntry& aRofsEntry);
-	TInt AddSubDirs(long endDirPos);
-	TInt AddFiles(long startPos, int size);
-	TText* GetName(TUint16 aFirstChar, TInt aLength);
-
-	/** Handle to core image file */
-	RCoreImageReader* iReader;
-	/** Node for the current directory */
-	TRomNode* iCurrentDir;
-	/** Current position in the file */
-	long iFilePos;
-	/** 
-	 The references in the extension directory tree are relative the core 
-	 image and not the actual offset in the file. This variable holds the 
-	 difference between the entries in the directory tree and the actual file
-	 position. This allows the same methods to be used for both core and
-	 extension images.
-	 */
-	long iAdjustment;
-	};
-
-#endif
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifndef __R_COREIMAGE_H__
+#define __R_COREIMAGE_H__
+
+class TRomNode;
+class E32Rofs;
+
+/**
+@internalComponent
+
+MRofsImage is the interface used to access information held within an image.
+This interface used to remove the dependency between processing of 
+extensions and kernel commands in the obey file
+*/
+class MRofsImage
+	{
+public:
+	/** Gets the root directory node from the image
+
+	   @return TRomNode* the first node in the directory tree
+	 */
+	virtual TRomNode* RootDirectory() = 0;
+
+	/** Copies the specified directory tree.
+
+	   @param aSourceDirectory The directory that is to be copied
+	   @return The copied directory tree.
+	 */
+	virtual TRomNode* CopyDirectory(TRomNode*& aSourceDirectory)=0;
+	/** Sets the root directory to be the specified node.
+
+	   @param aDir The node that is to be set as the root directory
+	 */
+	virtual void SetRootDirectory(TRomNode* aDir) = 0;
+	/** Gets the filename of the core image 
+
+	    @returns The filename of the core image file 
+	 */
+	virtual const char* RomFileName() const = 0;
+	/** Gets the size of the image file
+
+	   @returns size of file
+	 */
+	virtual TInt Size() const = 0;
+#ifdef __LINUX__
+	virtual ~MRofsImage(){}
+#endif
+	};
+
+const int K_ID_SIZE=4; /** Size of the image header identifier */
+
+/** 
+@internalComponent
+
+Provides the access the actual core image file. All file operations to the 
+core image file are through this class.
+*/
+class RCoreImageReader
+	{
+public:
+	/** Image Type read from header of image file */
+	enum TImageType 
+		{
+		/** Format of file has not been recognised */
+		E_UNKNOWN, 
+		/** File is a core RofsImage file */
+		E_ROFS, 
+		/** File is an extension RofsImage file */
+		E_ROFX
+		};
+
+	RCoreImageReader(const char *aFilename);
+	~RCoreImageReader();
+	TBool Open();
+	TImageType ReadImageType();
+	TInt ReadCoreHeader(TRofsHeader& aHeader);
+	TInt ReadExtensionHeader(TExtensionRofsHeader& aHeader);
+
+	TInt ReadDirEntry(TRofsDir& aDir);
+	TInt ReadDirEntry(TRofsDir& aDir, size_t aFilePos);
+
+	size_t FilePosition();
+	void SetFilePosition(size_t aFilePos);
+
+	TInt ReadRofEntry(TRofsEntry& aEntry);
+	TInt ReadRofEntry(TRofsEntry& aEntry, size_t aFilePos);
+	TInt ReadRofEntryName(TUint16* aName, int aLength);
+	TBool IsValidPosition(size_t aFilePos);
+	const char* Filename() const ;
+private:
+	TInt ReadIdentifier();
+	TInt ImageError(int aBytesRead, int aExpected, char* aInfo);
+
+	/** Image type of the file being read */
+	TImageType iImageType;
+	/** File object of core image being read */
+	ifstream iCoreImage;
+	/** Filename of core image file */
+	string iFilename;
+	/** Image type identifier read from image header */
+	TUint8 iIdentifier[K_ID_SIZE];
+	};
+
+/** 
+
+@internalComponent
+
+Processes the core image file to create a directory tree.
+It is used when the coreimage option has been specified either
+on the command line or in the obey file. It implements the MRofsImage 
+so it can be used by the extension image processing.
+*/
+class CCoreImage : public MRofsImage
+	{
+public:
+	CCoreImage(RCoreImageReader* aReader);
+	virtual TInt ProcessImage();
+	void Display(ostream* aOut);
+	virtual ~CCoreImage();
+
+	// Implementation of MRofsImage
+	TRomNode* RootDirectory();
+	TRomNode* CopyDirectory(TRomNode*& aSourceDirectory);
+	void SetRootDirectory(TRomNode* aDir);
+	const char* RomFileName() const;
+	TInt Size() const;
+
+protected:
+	void SaveDirInfo(TRofsHeader& header);
+	void SaveDirInfo(TExtensionRofsHeader& header);
+	TInt ProcessDirectory(long aAdjustment);
+	TInt CreateRootDir();
+	long DirTreeOffset();
+
+	/** used to read the core image file*/
+	RCoreImageReader *iReader;
+private:
+	/** The node for the root directory */
+	TRomNode *iRootDirectory;
+	/** The first node in list of file entries */
+	TRomBuilderEntry *iFileEntries;
+	/** Offset to the directory tree in the core image */
+	long iDirTreeOffset;
+	/** Size of the directory tree in the core image */
+	long iDirTreeSize;
+	/** Offset to the file entries of the directory in the core image */
+	long iDirFileEntriesOffset;
+	/** Size of the file entries block of the directory */
+	long iDirFileEntriesSize;
+	/** Filename of the rom image file */
+	string iRomFileName;
+	/** Size of image */
+	TInt iImageSize;
+	};
+
+/**
+@internalComponent
+
+Used for handling a single directory entry in the core image. This class allows
+the directory tree to be created recursively.
+*/
+class TDirectoryEntry
+	{
+public:
+	TDirectoryEntry(long filePos, RCoreImageReader* aReader, TRomNode* aCurrentDir);
+	~TDirectoryEntry();
+	TInt Process(long adjustment);
+private:
+	TInt CreateFileEntry(const char* aName, TRofsEntry& aRofsEntry);
+	TInt AddSubDirs(long endDirPos);
+	TInt AddFiles(long startPos, int size);
+
+	/** Handle to core image file */
+	RCoreImageReader* iReader;
+	/** Node for the current directory */
+	TRomNode* iCurrentDir;
+	/** Current position in the file */
+	long iFilePos;
+	/** 
+	 The references in the extension directory tree are relative the core 
+	 image and not the actual offset in the file. This variable holds the 
+	 difference between the entries in the directory tree and the actual file
+	 position. This allows the same methods to be used for both core and
+	 extension images.
+	 */
+	long iAdjustment;
+	};
+
+#endif
--- a/imgtools/romtools/rofsbuild/r_driveimage.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rofsbuild/r_driveimage.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,569 +1,186 @@
-/*
-* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent * @released
-* Driveimage class implementation.
-*
-*/
-
-
-#include <stdlib.h>
-#include <string>
-
-#ifndef __LINUX__
-	#include <windows.h>
-	#include <direct.h>
-#else
-	#include <dirent.h>
-#endif
-
-#ifdef __TOOLS2__
-	#include <sys/stat.h>
-	#include <sys/types.h>
-	using namespace std;
-#endif
-
-#include <f32file.h>
-#include "h_utl.h"
-#include "r_obey.h"
-#include "r_romnode.h"
-#include "r_rofs.h"
-#include "r_driveimage.h"
-
-extern TBool gFastCompress;
-
-// File format supported by Rofsbuild
-DriveFileFormatSupported CDriveImage::iFormatType[] =
-	{
-		{"FAT16",EFAT16},
-		{"FAT32",EFAT32},
-		{0,EFATINVALID}
-	};
-
-
-/**
-File format conversion from char* to coresponding enum value.
-
-@param aUserFileFormat - pointer to user entered file format.
-@param aDriveFileFormat - Reference to actual variable.
-*/
-TBool CDriveImage::FormatTranslation(TText* aUserFileFormat,enum TFileSystem& aDriveFileFormat)
-	{
-	struct DriveFileFormatSupported* strPointer = iFormatType;
-	for( ; (strPointer->iDriveFileFormat) != '\0' ; ++strPointer )
-		{
-		if(!strcmp((char*)aUserFileFormat,strPointer->iDriveFileFormat))
-			{
-			aDriveFileFormat = strPointer->iFileSystem;
-			return ETrue;
-			}
-		}	
-	return EFalse;
-	}
-
-
-/**
-Constructor: CDriveImage class 
-
-@param aObey - pointer to Drive obey file.
-*/
-CDriveImage::CDriveImage(CObeyFile *aObey)
-	: iObey( aObey ),iParentInnerList(0),iListReference(0),iTempDirName(NULL), iData(0)
-	{
-	}
-
-
-/**
-Destructor: CDriveImage class 
-
-Release the resources allocated in heap.
-*/
-CDriveImage::~CDriveImage()
-	{
-	iNodeAddStore.clear();
-	iNodeList.clear();
-	if(iData)
-		delete[] iData;
-	if(iTempDirName)
-		delete[] iTempDirName;
-	}
-
-
-/**
-Creates the STL list to interface with file system module.
-Creates the Temp folder for placing the executables
-   (those changed,due to user option like compression,un-compression & fileattribute)
-Updates the excutable options (file attributes, compression etc)
-
-@return Status - 'KErrNone' - successfully done above operations.
-                 'KErrNoMemory' - Not able to allocate the memory.
-				 'KErrGeneral' - Unable to done the above operations.
-*/
-TInt CDriveImage::CreateList()
-	{
-
-	TRomNode* pRootDir = iObey->iRootDirectory;
-	TInt16 dirCheck = 1;
-	TInt retStatus = 0;
-
-	// For Creating the temp folder.	
-	iTempDirName = new char[KMaxGenBuffer];
-	if(!iTempDirName)
-		return KErrNoMemory;
-
-	// Create the temp folder.
-	// Check for folder exist, if exist it loops until dir created or loop exit.
-	while(dirCheck)
-		{
-		sprintf(iTempDirName,"%s%05d","temp",dirCheck);
-#ifdef __LINUX__
-		retStatus = mkdir((char*)iTempDirName,0777);
-#else
-		retStatus = mkdir((char*)iTempDirName);
-#endif
-		if(!retStatus)
-			break;	
-
-		++dirCheck;
-		}
-
-	if(!dirCheck)
-		{
-		Print(EError,"Unable to Create the temp folder,Check directory settings.\n");
-		if(iTempDirName)
-			{
-			delete[] iTempDirName;
-			iTempDirName = 0;
-			}
-		return KErrCancel;
-		}
-
-	// Construct the file options.
-	if(ConstructOptions() != KErrNone)
-		{
-		return KErrGeneral;
-		}
-
-	// Construct the List.
-	if((GenTreeTraverse(pRootDir,KNodeTypeRoot)) != KErrNone )
-		{
-		return KErrGeneral;
-		}
-
-	return KErrNone;
-	}
-
-
-/**
-Creates the Image/Call to file system module.
-
-Updates the required operations to generate the data drive images.
-Deletes the temp folder if created.
-Calls the file system modules with required parameters.
-
-@param alogfile - Logfile name required for file system module.
-@return Status(r) - returns the status of file system module.
-                   'KErrGeneral' - Unable to done the above operations properly.
-*/
-TInt CDriveImage::CreateImage(TText* alogfile)
-	{
-
-	TInt retStatus = 0;
-	retStatus = CreateList();
-
-	if((retStatus == KErrCancel) || (retStatus == KErrNoMemory))
-		return KErrGeneral;
-
-	if(retStatus != KErrNone)
-		{
-		Print(EError,"Insufficent Memory/Not able to generate the Structure\n");
-		if(DeleteTempFolder((char*)iTempDirName) != KErrNone )
-			{
-			Print(EWarning,"Not able to delete the temp folder : %s",iTempDirName);
-			}
-		return KErrGeneral;
-		}
-
-	// Close log file.
-	H.CloseLogFile();		
-	
-	// Convert fileformat to corresponding enum value.
-	enum TFileSystem fileFormat = (TFileSystem)0;
-	FormatTranslation(iObey->iDriveFileFormat,fileFormat);
-
-	// Call to file system module. create the image.
-	if(iObey->iDataSize)
-		retStatus = CFileSystemInterFace::CreateFilesystem(&iNodeList,fileFormat,
-														(char*)iObey->iDriveFileName,
-														(char*)alogfile,
-														iObey->iConfigurableFatAttributes,																											
-														iObey->iDataSize); 
-	else
-		retStatus = CFileSystemInterFace::CreateFilesystem(&iNodeList,fileFormat,
-														(char*)iObey->iDriveFileName,
-														(char*)alogfile,
-														iObey->iConfigurableFatAttributes);														; 
-
-	//delete the temp folder.
-	if(DeleteTempFolder((char*)iTempDirName) != KErrNone )
-		{
-		cout << "Warning: Not able to delete the temp folder : " << iTempDirName << "\n" ;
-		}
-	
-	return 	retStatus;
-	}
-
-
-
-/**
-Delete the temp directory.
-
-@param aTempDirName - Temporory folder name to be deleted.
-@return Status(r) - returns the status.
-                   'KErrGeneral' - Unable to done the above operations properly.
-				   'KErrNone' - successfully deleted the folder.
-*/
-TInt CDriveImage::DeleteTempFolder(char* aTempDirName)
-	{
-
-	TInt fileDeleted = 1;
-	std::string dirPath(aTempDirName); 
-	std::string fileName(aTempDirName); 
-
-#ifdef __LINUX__
-
-	// Open directory
-	DIR *dirHandler = opendir(aTempDirName);
-	struct dirent *dirEntry;
-
-	if(!dirHandler)
-		return KErrGeneral;
-
-	dirPath.append("/");
-	fileName.append("/");
-
-	// Go through each entry
-	while(dirEntry = readdir(dirHandler))
-		{
-		if(dirEntry->d_type != DT_DIR) 
-			{
-			fileName.append((char*)dirEntry->d_name);
-			remove(fileName.c_str());
-			fileName.assign(dirPath);
-			}
-		}
-	//Close dir
-	if(!closedir(dirHandler))
-		{
-		fileDeleted = rmdir(aTempDirName);
-		}
-#else
-
-	WIN32_FIND_DATA FindFileData;
-	HANDLE hFind = INVALID_HANDLE_VALUE;
-
-	dirPath.append("\\*");
-	fileName.append("\\");
-	
-	// find the first file
-	hFind = FindFirstFile(dirPath.c_str(),&FindFileData);
-
-	if(hFind == INVALID_HANDLE_VALUE) 
-		return KErrGeneral;
-	
-	dirPath.assign(fileName);   
-
-	do
-	{
-	// Check for directory or file.
-	if(!(FindFileData.dwFileAttributes  & FILE_ATTRIBUTE_DIRECTORY))
-		{
-		// Delete the file.
-		fileName.append((char*)FindFileData.cFileName);
-		remove(fileName.c_str());
-		fileName.assign(dirPath);
-		}
-	} while(FindNextFile(hFind,&FindFileData));
-
-	FindClose(hFind);
-					
-	if(ERROR_NO_MORE_FILES != GetLastError())
-		{
-		cout << "Warning: FindNextFile error. Error is " << GetLastError() << "\n" ;
-		}
-
-	fileDeleted = _rmdir(aTempDirName);
-
-#endif
-
-	if(!fileDeleted)
-		return KErrNone;
-	else
-		return KErrGeneral;
-	}
-
-
-/**
-General Tree Traverse to create the List.
-Recursive call to update the list.
-
-@param anode - Current Node in the tree.
-@param anodeType - Node type(root,child,sibling)
-
-@return r - returns 'KErrNoMemory' if fails to generate the list or memory not allocated.
-            or 'KErrNone'
-*/
-TInt CDriveImage::GenTreeTraverse(TRomNode* anode,enum KNodeType anodeType)    
-	{
-	 
-	TInt r =0;			
-	if((r = CreateDirOrFileEntry(anode,anodeType)) != KErrNone) 
-		return KErrNoMemory;
-	 
-	if(anode->Currentchild())
-		{
-		if((r = GenTreeTraverse(anode->Currentchild(),KNodeTypeChild)) != KErrNone)
-			return KErrNoMemory;
-			
-		if(iNodeAddStore.size())	
-			iNodeAddStore.pop_back();
-
-		--iListReference;
-		}
-
-	if(anode->Currentsibling())
-		{
-		if((r = GenTreeTraverse(anode->Currentsibling(),KNodeTypeSibling)) != KErrNone)
-			return KErrNoMemory;
-		}
-	return r;
-	}
-
-
-/**
-Generate the List. required for drive image creation.
-Hidden file node is not placed in list.
-
-@param atempnode - Current Node in the tree.
-@param aType - Node type(root,child,sibling)
-
-@return r - returns 'KErrNoMemory' if memory is not allocated or 'KErrNone'
-*/
-TInt CDriveImage::CreateDirOrFileEntry(TRomNode* atempnode,enum KNodeType aType)    
-	{
-
-	CDirectory* iDirectory = new CDirectory((char*)atempnode->iName);
-	if(!iDirectory)									
-		return KErrNoMemory;
-		
-	char attrib = 0 ;
-	if(atempnode->iAtt & KEntryAttReadOnly)
-		attrib |= EAttrReadOnly ;
-	if(atempnode->iAtt & KEntryAttHidden)
-		attrib |= EAttrHidden ;
-	if(atempnode->iAtt & KEntryAttSystem)
-		attrib |= EAttrSystem ;
-		
-
-	// for files only.
-	if(atempnode->iEntry)
-		{
-		iDirectory->SetEntryAttribute(attrib);
-
-		// don't place the hidden files to list.
-		if(!atempnode->iHidden)	
-			{
-			iDirectory->SetFilePath(atempnode->iEntry->iFileName);
-			iDirectory->SetFileSize(atempnode->iSize);
-			}
-		else
-			{
-			iNodeAddStore.push_back((void*)iParentInnerList);
-			++iListReference;
-			return KErrNone;  
-			}	
-		}
-	else
-		iDirectory->SetEntryAttribute(attrib | EAttrDirectory);
-
-
-	switch(aType)
-		{
-		case KNodeTypeRoot:
-			iDirectory->SetEntryAttribute(EAttrVolumeId);
-			iNodeList.push_back(iDirectory);	
-			iParentInnerList = iDirectory->GetEntryList(); 
-			break;
-					
-		case KNodeTypeChild:
-			iNodeAddStore.push_back((void*)iParentInnerList);
-			++iListReference;
-			iParentInnerList->push_back(iDirectory);
-			iParentInnerList = iDirectory->GetEntryList(); 
-			break;
-
-		case KNodeTypeSibling:									
-			iParentInnerList =(std::list<CDirectory*> *)(iNodeAddStore[iListReference-1]);
-			iParentInnerList->push_back(iDirectory);
-			iParentInnerList = iDirectory->GetEntryList();
-			break;
-
-		default: 
-			break;
-		}
-	return KErrNone;                                             
-	}
-
-
-/**
-Traverses all entries and update compress/uncompress and file attribute options.
-
-Place executables in temp folder.(if changed)
-Hidden file node is not placed in temp folder.
-
-@return r - returns 'KErrNoMemory/KErrGeneral' if fails to update the options or memory
-            not allocated or else 'KErrNone' for Succesfully operation.
-*/
-TInt CDriveImage::ConstructOptions() 
-	{
-
-	TInt32 len = 0;
-	TRomNode* node = TRomNode::FirstNode();
-        CBytePair bpe(gFastCompress);
-	
-	while(node)
-		{
-		// Don't do anything for hidden files.
-		if(node->IsFile() && (!node->iHidden))
-			{
-		
-			TInt32 size=HFile::GetLength((TText*)node->iEntry->iFileName);    
-			if(size <= 0)
-				{
-				Print(EWarning,"File %s does not exist or is 0 bytes in length.\n",node->iEntry->iFileName);
-				}
-			node->iSize = size;
-			if(node->iEntry->iExecutable && (size > 0))
-				{
-				
-				if((node->iFileUpdate) || (node->iOverride))
-					{
-					iData = new char[(size * 2)];
-					if(!iData)
-						return KErrNoMemory;
-					
-					HMem::Set(iData, 0xff, (size * 2));
-                                        TUint8* aData = (TUint8*)iData;
-					len = node->PlaceFile(aData,0,(size * 2),&bpe);
-					if(len < KErrNone)
-						{	
-						delete[] iData;
-						iData = 0;
-						return KErrGeneral;
-						}
-						
-					// Place the file in Newly created Folder. 
-					TInt r = PlaceFileTemporary(len,node);
-					delete[] iData;
-					iData = 0;
-
-					if(r != KErrNone)
-						{
-						return r;
-						}
-					} // file update end.
-				}
-			} // is file end
-		node = node->NextNode();
-		}
-	return KErrNone;
-	}
-
-
-/**
-Place the modified exe's(e32 format) in Temp Folder. 
-Place executables in temp folder.(if changed)
-
-@param afileSize    - No. of bytes to be palced in the file.
-@param acurrentNode - file node, to modify its source path.
-
-@return r - returns 'KErrNoMemory' if fails to allocate the memory.
-            or 'KErrNone'
-*/
-TInt CDriveImage::PlaceFileTemporary(const TInt afileSize,TRomNode* acurrentNode) 
-	{
-
-	TInt randomValue = 0;
-	char randomString[KMaxGenBuffer] = "\0";
-	unsigned char* fileSourcePath = acurrentNode->iEntry->iName;
-	std::string newFileName;
-
-	do
-		{
-		newFileName.append(iTempDirName);
-		newFileName.append("/");
-
-		if(!randomValue)	
-			{
-			newFileName.append((char*)fileSourcePath);
-			}
-		else
-			{  
-			newFileName.append(randomString);
-			newFileName.append((char*)fileSourcePath);
-			}
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-		ifstream test(newFileName.c_str());
-#else //!__MSVCDOTNET__
-		ifstream test(newFileName.c_str(), ios::nocreate);
-#endif //__MSVCDOTNET__
-
-		if (!test)
-			{
-			test.close();
-			ofstream driveFile((char *)newFileName.c_str(),ios::binary);
-			if (!driveFile)
-				{
-				Print(EError,"Cannot open file %s for output\n",newFileName.c_str());
-				return KErrGeneral;
-				}
-
-			driveFile.write(iData,afileSize);
-			driveFile.close();
-
-			// Update the new source path.
-			delete[] acurrentNode->iEntry->iFileName;
-			acurrentNode->iEntry->iFileName = new char[ strlen(newFileName.c_str()) + 1 ];
-			if(!acurrentNode->iEntry->iFileName)
-				return KErrNoMemory;
-				
-			strcpy(acurrentNode->iEntry->iFileName,newFileName.c_str());
-			break;
-			}
-
-		test.close();
-		newFileName.erase();
-		++randomValue;
-		sprintf(randomString,"%d",randomValue);
-	
-		}
-	while(randomValue);
-
-	return KErrNone;
-	}
-
-
-
-
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent * @released
+* Driveimage class implementation.
+*
+*/
+
+
+#include <stdlib.h>
+#include <string>
+#include "fsnode.h"
+#include "fatimagegenerator.h"
+#include <boost/filesystem.hpp>
+#include <stack>
+#include <utility>
+#include <new>
+using namespace boost ;
+#ifdef __LINUX__
+	
+	#include <dirent.h>
+	#ifndef MKDIR
+		#define MKDIR(a)	mkdir(a,0777)
+	#endif
+#else
+	#ifdef _STLP_INTERNAL_WINDOWS_H
+	#define __INTERLOCKED_DECLARED
+	#endif
+	#include <windows.h>
+	#include <direct.h>
+	#ifndef MKDIR
+		#define MKDIR		mkdir
+	#endif
+#endif
+#include <sys/stat.h>
+#include <sys/types.h>
+using namespace std;
+
+
+#include <f32file.h>
+#include "h_utl.h"
+#include "r_obey.h"
+#include "r_romnode.h"
+#include "r_rofs.h"
+#include "r_driveimage.h"
+ 
+/**
+Constructor: CDriveImage class 
+
+@param aObey - pointer to Drive obey file.
+*/
+CDriveImage::CDriveImage(CObeyFile *aObey)
+	: iObey( aObey )
+{
+}
+
+
+CDriveImage::~CDriveImage()
+{
+ 
+}
+/**
+	* 
+  */
+TFSNode* CDriveImage::PrepareFileSystem(TRomNode* aRomNode){ 
+	TUint8 attrib ;
+	TFSNode* root = 0;
+	TRomNode* romNode = aRomNode;
+	stack<pair<TRomNode*,TFSNode*> > nodesStack ;
+	TFSNode* parentFS = 0 ;
+	TFSNode* curFS = 0;
+	bool err = false ;
+    while(1) {
+        attrib = 0 ;
+        if(romNode->iAtt & KEntryAttReadOnly)
+			attrib |= ATTR_READ_ONLY ;
+		if(romNode->iAtt & KEntryAttHidden)
+			attrib |= ATTR_HIDDEN ;
+		if(romNode->iAtt & KEntryAttSystem)
+			attrib |= ATTR_SYSTEM ;  
+		if(romNode->IsDirectory()) {		  
+			curFS = new(std::nothrow)  TFSNode(parentFS,romNode->iName,attrib | ATTR_DIRECTORY);
+			if(!curFS){
+					err = true ;
+					break ;
+			} 
+			if(!root) root = curFS ;  
+			time_t now = time(NULL); 
+			curFS->Init(now,now,now,0); 
+			TRomNode* child = romNode->Currentchild();
+			if(child){
+				TRomNode* sibling = romNode->Currentsibling(); 
+				if(sibling)
+					nodesStack.push(make_pair(sibling,parentFS));
+				romNode = child ;
+				parentFS = curFS ;
+				continue ;
+			}			
+		}
+		else { // file             
+				curFS = new(std::nothrow) TFSNode(parentFS,romNode->iEntry->iName,attrib,romNode->iEntry->iFileName);
+				if(!curFS){
+					err = true ;
+					break ;
+				} 
+					
+				if(!root) root = curFS ;  
+				struct stat statbuf ;
+				stat(romNode->iEntry->iFileName, &statbuf);             
+				curFS->Init(statbuf.st_ctime,statbuf.st_atime,statbuf.st_mtime,statbuf.st_size);   
+		 
+		}
+		
+		TRomNode* sibling = romNode->Currentsibling(); 
+		if(sibling) {
+			romNode = sibling ; 
+		}
+		else { 
+			if(nodesStack.empty()) {
+				break ;
+			}
+			else {
+				romNode = nodesStack.top().first;
+				parentFS = nodesStack.top().second ;
+				nodesStack.pop() ;
+				
+			}
+		}		
+    }
+	if(err) {
+		if(root) delete root ;
+		return NULL ;
+	}
+    return root ;
+} 
+
+/**
+Creates the Image/Call to file system module.
+
+Updates the required operations to generate the data drive images.
+Deletes the temp folder if created.
+Calls the file system modules with required parameters.
+
+@param alogfile - Logfile name required for file system module.
+@return Status(r) - returns the status of file system module.
+                   'KErrGeneral' - Unable to done the above operations properly.
+*/
+TInt CDriveImage::CreateImage(const char* alogfile) {
+	
+	TSupportedFatType fst = EFatUnknown ;
+	if(stricmp(iObey->iDriveFileFormat,"FAT16") == 0)
+	    fst = EFat16 ;
+	else if(stricmp(iObey->iDriveFileFormat,"FAT32") == 0)
+	        fst = EFat32 ;
+	if(EFatUnknown == fst){
+        Print(EError,"Unsupported FAT type : %s",iObey->iDriveFileFormat);
+        return KErrGeneral ;
+	}
+	 
+	TFatImgGenerator generator(fst,iObey->iConfigurableFatAttributes);
+	
+	if(!generator.IsValid()){
+	    return KErrGeneral; 
+	}
+	TFSNode* root = PrepareFileSystem(iObey->iRootDirectory);
+	if(!root)
+	    return KErrGeneral;
+	
+ 
+	TInt retVal = generator.Execute(root,iObey->iDriveFileName) ? KErrNone : KErrGeneral;
+	
+	delete root ;
+		
+	return 	retVal;
+}
--- a/imgtools/romtools/rofsbuild/r_driveimage.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rofsbuild/r_driveimage.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,94 +1,58 @@
-/*
-* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent * @released
-* DriveImage class declaration.
-*
-*/
-
-
-#ifndef __R_DRIVEIMAGE_H__
-#define __R_DRIVEIMAGE_H__
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-	#include <fstream>
-#else //!__MSVCDOTNET__
-	#include <fstream.h>
-#endif 
-
-#include "filesysteminterface.h" 
-#include <vector>
-
-typedef std::vector<void*> EntryReferenceVector;
-typedef	std::list<CDirectory*> EntryList; 
-
-const TInt KMaxGenBuffer=0x14;  
-
-// Node Type.
-enum KNodeType
-	{
-	KNodeTypeNone=0,		
-	KNodeTypeRoot,
-	KNodeTypeChild,
-	KNodeTypeSibling
-	};
-
-// File Format Supported.
-struct DriveFileFormatSupported
-	{
-	const char* iDriveFileFormat;
-	enum TFileSystem iFileSystem;
-	};
-
-// Image creation class.
-class CDriveImage
-	{
-public:
-	CDriveImage(CObeyFile *aObey);
-	~CDriveImage();
-	TInt CreateImage(TText* alogfile);
-	static TBool FormatTranslation(TText* aUserFileFormat,enum TFileSystem& aDriveFileFormat);
-
-private:
-
-	TInt CreateList();
-	TInt GenTreeTraverse(TRomNode* anode,enum KNodeType anodeType);    
-	TInt CreateDirOrFileEntry(TRomNode* atempnode,enum KNodeType aType);   
-	TInt ConstructOptions();
-	TInt PlaceFileTemporary(const TInt afileSize,TRomNode* acurrentNode); 
-	TInt DeleteTempFolder(char* aTempDirName);
-
-private:
-
-	// Holds the address of CObeyFile object. used to get the object information.
-	CObeyFile *iObey;
-	// Container required for file sysem module.
-	EntryList iNodeList;
-	// Pointer for nested Container.
-	EntryList *iParentInnerList;
-
-	// For temp storge of Container address.
-	EntryReferenceVector iNodeAddStore;
-
-	// For file format support.
-	static DriveFileFormatSupported iFormatType[];
-	// Reference variable used for converting tree to list.
-	TInt iListReference;
-	// Holds temp folder name. 
-	char *iTempDirName;
-	// Pointer to buffer, which will be used for compression/un-compression purpose.
-	char *iData;
-	};
-
-#endif
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent * @released
+* DriveImage class declaration.
+*
+*/
+
+
+#ifndef __R_DRIVEIMAGE_H__
+#define __R_DRIVEIMAGE_H__
+
+#include <fstream> 
+#include <vector>
+
+const TInt KMaxGenBuffer=0x14;  
+
+// Node Type.
+enum KNodeType
+	{
+	KNodeTypeNone=0,		
+	KNodeTypeRoot,
+	KNodeTypeChild,
+	KNodeTypeSibling
+	};
+
+// File Format Supported.
+
+class TFSNode ;
+// Image creation class.
+class CDriveImage
+	{
+public:
+	CDriveImage(CObeyFile *aObey);
+	~CDriveImage();
+	TInt CreateImage(const char* alogfile);
+	
+private:
+ 
+	TFSNode* PrepareFileSystem(TRomNode* aRomNode); 	
+	// Holds the address of CObeyFile object. used to get the object information.
+	CObeyFile *iObey;	  
+	 
+	 
+	};
+
+#endif
--- a/imgtools/romtools/rofsbuild/r_driveutl.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rofsbuild/r_driveutl.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,98 +1,98 @@
-/*
-* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent * @released
-* Driveimage general utilities.
-*
-*/
-
-
-#include <string.h>
-#include <stdlib.h>
-#include <time.h>
-
-#include <e32err.h>
-#include "h_utl.h"
-#include "r_driveutl.h"
-
-/**
-Derive log file name from the given driveobey file name(it could be absolute path)
-        and update with .log extn.
-Checks the validity of driveobey file name before creating the log file name.
-
-@param adriveobeyFileName - Drive obey file.
-@param &apadlogfile       - Reference to log file name.
-  
-@return - returns 'ErrorNone' if log file created, otherwise returns Error.
-*/ 
-TInt Getlogfile(TText *aDriveObeyFileName,TText* &aPadLogFile)
-	{
-
-	if(!(*aDriveObeyFileName))
-		return KErrGeneral;
-
-	// Validate the user entered driveoby file name.
-	char* logFile = (char*)aDriveObeyFileName;
-
-#ifdef __LINUX__
-	logFile = strrchr(logFile,'/');
-#else
-	while(*logFile)
-		{
-		if(*logFile == '/')
-			*logFile = '\\';
-		logFile++;
-		}
-	logFile = (char*)aDriveObeyFileName;
-	logFile = strrchr(logFile,'\\');
-#endif
-	
-	if(logFile)
-		++logFile;
-	else
-		logFile = (char*)aDriveObeyFileName;
-
-	TInt len = strlen(logFile);
-	if(!len)
-		return KErrGeneral;
-
-	// Allocates the memory for log file name.
-	aPadLogFile = new TText[(len)+5]; 
-	if(!aPadLogFile)
-		return KErrNoMemory;
-
-	// Create the log file name.
-	strcpy((char*)aPadLogFile,logFile);
-	strcat((char*)aPadLogFile,".LOG");
-				
-	return  KErrNone;
-	}
-
-/**
-Time Stamp for Log file.
-*/ 
-TAny GetLocalTime(TAny)
-	{
-	struct tm *aNewTime = NULL;
-	time_t aTime = 0;
-
-	time(&aTime);
-	aNewTime = localtime(&aTime);
-
-	/* Print the local time as a string */
-	if(aNewTime)
-		Print(ELog,"%s\n", asctime(aNewTime));
-	else
-		Print(ELog,"Error : Getting Local Time\n");
-	}
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent * @released
+* Driveimage general utilities.
+*
+*/
+
+
+#include <string.h>
+#include <stdlib.h>
+#include <time.h>
+
+#include <e32err.h>
+#include "h_utl.h"
+#include "r_driveutl.h"
+
+/**
+Derive log file name from the given driveobey file name(it could be absolute path)
+        and update with .log extn.
+Checks the validity of driveobey file name before creating the log file name.
+
+@param adriveobeyFileName - Drive obey file.
+@param &apadlogfile       - Reference to log file name.
+  
+@return - returns 'ErrorNone' if log file created, otherwise returns Error.
+*/ 
+TInt Getlogfile(char *aDriveObeyFileName,char* &aPadLogFile)
+	{
+
+	if(!(*aDriveObeyFileName))
+		return KErrGeneral;
+
+	// Validate the user entered driveoby file name.
+	char* logFile = (char*)aDriveObeyFileName;
+
+#ifdef __LINUX__
+	logFile = strrchr(logFile,'/');
+#else
+	while(*logFile)
+		{
+		if(*logFile == '/')
+			*logFile = '\\';
+		logFile++;
+		}
+	logFile = (char*)aDriveObeyFileName;
+	logFile = strrchr(logFile,'\\');
+#endif
+	
+	if(logFile)
+		++logFile;
+	else
+		logFile = (char*)aDriveObeyFileName;
+
+	TInt len = strlen(logFile);
+	if(!len)
+		return KErrGeneral;
+
+	// Allocates the memory for log file name.
+	aPadLogFile = new char[(len)+5]; 
+	if(!aPadLogFile)
+		return KErrNoMemory;
+
+	// Create the log file name.
+	strcpy((char*)aPadLogFile,logFile);
+	strcat((char*)aPadLogFile,".LOG");
+				
+	return  KErrNone;
+	}
+
+/**
+Time Stamp for Log file.
+*/ 
+TAny GetLocalTime(TAny)
+	{
+	struct tm *aNewTime = NULL;
+	time_t aTime = 0;
+
+	time(&aTime);
+	aNewTime = localtime(&aTime);
+
+	/* Print the local time as a string */
+	if(aNewTime)
+		Print(ELog,"%s\n", asctime(aNewTime));
+	else
+		Print(ELog,"Error : Getting Local Time\n");
+	}
--- a/imgtools/romtools/rofsbuild/r_driveutl.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rofsbuild/r_driveutl.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,29 +1,29 @@
-/*
-* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent * @released
-* Utility functions for DriveImage.
-*
-*/
-
-
-#ifndef __R_DRIVEUTL_H__
-#define __R_DRIVEUTL_H__
-
-#include <e32def.h>
-
-TInt Getlogfile(TText *aDriveObeyFileName,TText* &aPadLogFile);
-TAny GetLocalTime(TAny);
-
-#endif
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent * @released
+* Utility functions for DriveImage.
+*
+*/
+
+
+#ifndef __R_DRIVEUTL_H__
+#define __R_DRIVEUTL_H__
+
+#include <e32def.h>
+
+TInt Getlogfile(char *aDriveObeyFileName,char* &aPadLogFile);
+TAny GetLocalTime(TAny);
+
+#endif
--- a/imgtools/romtools/rofsbuild/r_obey.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rofsbuild/r_obey.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,2274 +1,2061 @@
-/*
-* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent * @released
-* Rofsbuild Obey file class and its reader class.
-*
-*/
-
-
-#include <string.h>
-
-#ifdef __VC32__
- #ifdef __MSVCDOTNET__
-  #include <strstream>
-  #include <iomanip>
- #else //__MSVCDOTNET__
-  #include <strstrea.h>
-  #include <iomanip.h>
- #endif  //__MSVCDOTNET__
-#else // !__VC32__
-#ifdef __TOOLS2__
-	#include <sstream>
-	#include <iomanip>
-	#include <sys/stat.h>
-	using namespace std;
-#else
-	#include <strstrea.h>
-	#include <iomanip.h>
-#endif
- 
-#endif //__VC32__
-
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <time.h>
-#include <assert.h>
-#include <errno.h>
-
-#include <e32std.h>
-#include <e32std_private.h>
-#include <e32rom.h>
-#include <u32std.h>
-#include <f32file.h>
-
-#include "h_utl.h"
-#include "r_obey.h"
-#include "r_coreimage.h"
-#include "patchdataprocessor.h"
-#include "filesysteminterface.h" 
-#include "r_driveimage.h"
-
-extern TInt gCodePagingOverride;
-extern TInt gDataPagingOverride;
-extern ECompression gCompress;
-extern TBool gEnableStdPathWarning; // Default to not warn if destination path provided for a file is not in standard path.
-
-
-
-#define _P(word)	word, sizeof(word)-1	// match prefix, optionally followed by [HWVD]
-#define _K(word)	word, 0					// match whole word
-
-const ObeyFileKeyword ObeyFileReader::iKeywords[] =
-{
-	{_K("file"),		2,-2, EKeywordFile, "File to be copied into ROFS"},
-	{_K("data"),		2,-2, EKeywordData, "same as file"},
-
-	{_K("rofsname"),	1, 1, EKeywordRofsName, "output file for ROFS image"},
-	{_K("romsize"),		1, 1, EKeywordRomSize, "size of ROM image"}, 
-	{_P("hide"),	    2, -1, EKeywordHide, "Exclude named file from ROM directory structure"},
-	{_P("alias"),	    2, -2, EKeywordAlias, "Create alias for existing file in ROM directory structure"},
-	{_P("rename"),	    2, -2, EKeywordRename, "Change the name of a file in the ROM directory structure"},
-	{_K("rofssize"),		1, 1, EKeywordRofsSize, "maximum size of ROFS image"},
-	{_K("romchecksum"),	1, 1, EKeywordRofsChecksum, "desired 32-bit checksum value for the whole image"},
-	{_K("version"),		1, 1, EKeywordVersion, "ROFS image version number"},
-	{_K("time"),	    1,-1, EKeywordTime, "ROFS image timestamp"},
-	{_K("extensionrofs"),1+2, 1, EKeywordExtensionRofs, "Start of definition of optional Extension ROFS"},
-	{_K("extensionrofsname"),1, 1, EKeywordCoreRofsName, "ROFS image on which extension ROFS is based"},
-	{_K("rem"),			0, 0, EKeywordNone, "comment"},
-	{_K("stop"),		0, 0, EKeywordNone, "Terminates OBEY file prematurely"},
-	{_K("romchecksum"),	1, 1, EKeywordRomChecksum, "desired 32-bit checksum value for the whole ROFS image"},
-	{_K("coreimage"),	1, 1, EKeywordCoreImage, "Core image to be used for extension directory structure"},
-	{_K("autosize"),	1, 1, EKeywordRofsAutoSize, "Automatically adjust maximum image size to actual used"},
-	{_K("pagingoverride"),	1, 1, EKeywordPagingOverride, "Overide the demand paging attributes for every file in ROM, NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
-	{_K("codepagingoverride"),	1, 1, EKeywordCodePagingOverride, "Overide the code paging attributes for every file in ROM, NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
-	{_K("datapagingoverride"),	1, 1, EKeywordDataPagingOverride, "Overide the data paging attributes for every file in ROM, NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
-	{_K("dataimagename"),1, 1,EKeywordDataImageName, "Data Drive image file name"},
-	{_K("dataimagefilesystem"),1, 1,EKeywordDataImageFileSystem, "Drive image file system format"},
-	{_K("dataimagesize"),1, 1,EKeywordDataImageSize, "Maximum size of Data Drive image"},
-	{_K("volume"),1, -1,EKeywordDataImageVolume, "Volume Label of Data Drive image"},
-	{_K("sectorsize"),1, 1,EKeywordDataImageSectorSize, "Sector size(in bytes) of Data Drive image"},
-	{_K("fattable"),1, 1,EKeywordDataImageNoOfFats, "Number of FATs in the Data Drive image"},
-	// things we don't normally report in the help information
-	{_K("trace"),		1, 1, EKeywordTrace, "(ROMBUILD activity trace flags)"},
-	{_K("filecompress"),2, -2,EKeywordFileCompress,"Non-XIP Executable to be loaded into the ROM compressed" },
-	{_K("fileuncompress"),2, -2,EKeywordFileUncompress,"Non-XIP Executable to be loaded into the ROM uncompressed" },
-	{_K("patchdata"),2, 5,EKeywordPatchDllData, "Patch exported data"},
-	{_K("imagename"), 1, 1, EKeywordSmrImageName, "output file for SMR image"},
-	{_K("hcrdata"), 1, 1, EKeywordSmrFileData, "file data for HCR SMR image"},
-	{_K("formatversion"), 1, 1, EKeywordSmrFormatVersion, "format version for HCR SMR image"},
-	{_K("payloadflags"), 1, 1, EKeywordSmrFlags, "payload flags for the HCR SMR image"},
-	{_K("payloaduid"), 1, 1, EKeywordSmrUID, "payload UID for the HCR SMR image"},
-	{0,0,0,0,EKeywordNone,""}
-};
-
-extern TInt isNumber(TText *aString);
-extern TInt getNumber(TText *aStr);
-
-void ObeyFileReader::KeywordHelp() // static
-	{
-	cout << "Obey file keywords:\n";
-
-	const ObeyFileKeyword* k=0;
-	for (k=iKeywords; k->iKeyword!=0; k++)
-		{
-		if (k->iHelpText==0)
-			continue;
-		if (k->iHelpText[0]=='(' && !H.iVerbose)
-			continue;	// don't normally report things in (parentheses)
-
-		char buf[32];
-		sprintf(buf, "%-20s", k->iKeyword);
-		if (k->iKeywordLength)
-			memcpy(buf+k->iKeywordLength,"[HWVD]",6);
-		if (H.iVerbose)
-			sprintf(buf+20,"%2d",k->iNumArgs);
-		cout << "    " << buf << " " << k->iHelpText << endl;
-		}
-	cout << endl;
-
-	cout << "File attributes:\n";
-
-	const FileAttributeKeyword* f=0;
-	for (f=iAttributeKeywords; f->iKeyword!=0; f++)
-		{
-		if (f->iHelpText==0)
-			continue;
-		if (f->iHelpText[0]=='(' && !H.iVerbose)
-			continue;	// don't normally report things in (parentheses)
-
-		char buf[32];
-		sprintf(buf, "%-20s", f->iKeyword);
-		if (H.iVerbose)
-			sprintf(buf+20,"%2d",k->iNumArgs);
-		cout << "    " << buf << " " << f->iHelpText << endl;
-		}
-	cout << endl;
-	}
-
-ObeyFileReader::ObeyFileReader(TText* aFileName):
-iObeyFile(0),iMark(0), iMarkLine(0), iCurrentMark(0), iCurrentLine(0), imaxLength(0)
-	{
-
-	iFileName = new TText[strlen((const char *)aFileName)+1];
-	strcpy((char *)iFileName,(const char *)aFileName);
-	iNumWords = 0 ;
-	for(unsigned int i = 0 ; i < KNumWords ; i++)
-		iWord[i] = 0 ;
-	iSuffix = new TText();
-	iLine = 0 ;
-	iCurrentObeyStatement = 0 ;
-	 }
-
-
-ObeyFileReader::~ObeyFileReader()
-	{
-	if (iObeyFile)
-		fclose(iObeyFile);
-	iObeyFile=0;
-	delete [] iFileName;
-	delete [] iLine;
-	delete [] iCurrentObeyStatement;
-	}
-
-TBool ObeyFileReader::Open()
-//
-// Open the file & return a status
-//
-{
-    if (!iFileName)
-    {
-        return EFalse;
-    }
-
-    iObeyFile = fopen((const char *)iFileName,"r");
-    if (!iObeyFile)
-    {
-        Print(EError,"Cannot open obey file %s\n",iFileName);
-        return EFalse;
-    }
-    if (SetLineLengthBuffer() != KErrNone)
-    {
-        Print(EError,"Insufficent Memory to Continue.");	
-        return EFalse;
-    }
-    return ETrue;
-}
-   
- TInt ObeyFileReader::SetLineLengthBuffer()
- // Get the Max Line length for the given obey file and allocate the buffer.
- 	{
-	char ch = '\0';
- 	TInt length = 0;
-		
-	Rewind();
- 	while ((ch = (char)fgetc(iObeyFile)) != EOF)
- 		{
- 		length++;
-		if (ch == '\n')
-			{
- 			if (length > imaxLength)
- 				imaxLength = length;
- 			length = 0;				
- 			}
- 		}
-	
-	if (length > imaxLength)
- 		imaxLength = length;
-		
-	if (0 == imaxLength)
-		{
-		Print(EError,"Empty obey file passed as input.");
-		exit(-1);
-		}			
-	else if (imaxLength < 2)
-		{
-		Print(EError,"Invalid obey file passed as input.");
-		exit(-1);
-		}
-		
-	Rewind();
- 	iLine = new TText[imaxLength+1];
- 	
- 	if(!iLine)
- 		return KErrNoMemory;
- 
- 	return KErrNone;
- 	}
-
-void ObeyFileReader::Mark()
-	{
-
-	iMark = iCurrentMark;
-	iMarkLine = iCurrentLine-1;
-	}
-
-void ObeyFileReader::MarkNext()
-	{
-
-	iMark = ftell(iObeyFile);
-	iMarkLine = iCurrentLine;
-	}
-
-void ObeyFileReader::Rewind()
-	{
-	
-	fseek(iObeyFile,iMark,SEEK_SET);
-	iCurrentMark = iMark;
-	iCurrentLine = iMarkLine;
-	}
-
-void ObeyFileReader::CopyWord(TInt aIndex, TText*& aString)
-	{
-	aString = new TText[strlen((const char *)iWord[aIndex])+1];
-	strcpy((char *)aString, (const char *)iWord[aIndex]);
-	}
-
-TInt ObeyFileReader::ReadAndParseLine()
-	{
-	if (feof(iObeyFile))
-		return KErrEof;
-	iCurrentLine++;
-	iCurrentMark = ftell(iObeyFile);
-	iLine[0]='\0';
-	fgets((char*)iLine,imaxLength+1,iObeyFile);
-	iCurrentObeyStatement = new TText[imaxLength+1];
-	strcpy((char*)iCurrentObeyStatement,(char*)iLine);
-	iNumWords = Parse();
-	return KErrNone;
-	}
-
-TInt ObeyFileReader::NextLine(TInt aPass, enum EKeyword& aKeyword)
-	{
-
-NextLine:
-	TInt err = ReadAndParseLine();
-	if (err == KErrEof)
-		return KErrEof;
-	if (iNumWords == 0 || stricmp((const char*)iWord[0], "rem")==0)
-		goto NextLine;
-	if (stricmp((const char*)iWord[0], "stop")==0)
-		return KErrEof;
-
-	const ObeyFileKeyword* k=0;
-	for (k=iKeywords; k->iKeyword!=0; k++)
-		{
-		if (k->iKeywordLength == 0)
-			{
-			// Exact case-insensitive match on keyword
-			if (stricmp((const char*)iWord[0], k->iKeyword) != 0)
-				continue;
-			iSuffix = 0;
-			}
-		else
-			{
-			// Prefix match
-			if (strnicmp((const char*)iWord[0], k->iKeyword, k->iKeywordLength) != 0)
-				continue;
-			// Suffix must be empty, or a variant number in []
-			iSuffix = iWord[0]+k->iKeywordLength;
-			if (*iSuffix != '\0' && *iSuffix != '[')
-				continue;
-			}
-		// found a match
-		if ((k->iPass & aPass) == 0)
-			goto NextLine;
-		if (k->iNumArgs>=0 && (1+k->iNumArgs != iNumWords))
-			{
-			Print(EError, "Incorrect number of arguments for keyword %s on line %d.\n",
-				iWord[0], iCurrentLine);
-			goto NextLine;
-			}
-		if (k->iNumArgs<0 && (1-k->iNumArgs > iNumWords))
-			{
-			Print(EError, "Too few arguments for keyword %s on line %d.\n",
-				iWord[0], iCurrentLine);
-			goto NextLine;
-			}
-		
-		aKeyword = k->iKeywordEnum;
-		return KErrNone;
-		}
-	if (aPass == 1)
-		Print(EWarning, "Unknown keyword '%s'.  Line %d ignored\n", iWord[0], iCurrentLine);
-	goto NextLine;
-	}
-
-inline TBool ObeyFileReader::IsGap(char ch)
-	{
-	return (ch==' ' || ch=='=' || ch=='\t');
-	}
-
-TInt ObeyFileReader::Parse()
-//
-// splits a line into words, and returns the number of words found
-//
-	{
-
-	TInt i;
-	TText *letter=iLine;
-	TText *end=iLine+strlen((char *)iLine);
-	for (i=0; (TUint)i<KNumWords; i++)
-		iWord[i]=end;
-
-	enum TState {EInWord, EInQuotedWord, EInGap};
-	TState state=EInGap;
-
-	i=0;
-	while ((TUint)i<KNumWords && letter<end)
-		{
-		char ch=*letter;
-		if (ch==0)
-			break;
-		if (ch=='\n')
-			{
-			*letter='\0';	// remove trailing newline left by fgets
-			break;
-			}
-		switch (state)
-			{
-		case EInGap:
-			if (ch=='\"')
-				{
-				if (letter[1]!=0 && letter[1]!='\"')
-					iWord[i++]=letter+1;
-				state=EInQuotedWord;
-				}
-			else if (!IsGap(ch))
-				{
-				iWord[i++]=letter;
-				state=EInWord;
-				}
-			else
-				*letter=0;
-			break;
-		case EInWord:
-			if (ch=='\"')
-				{
-				*letter=0;
-				if (letter[1]!=0 && letter[1]!='\"')
-					iWord[i++]=letter+1;
-				state=EInQuotedWord;
-				}
-			else if (IsGap(ch))
-				{
-				*letter=0;
-				state=EInGap;
-				}
-			break;
-		case EInQuotedWord:
-			if (ch=='\"')
-				{
-				*letter=0;
-				state=EInGap;
-				}
-			break;
-			}
-		letter++;
-		}
-	return i;
-	}
-
-
-void ObeyFileReader::ProcessTime(TInt64& aTime)
-//
-// Process the timestamp
-//
-	{
-	char timebuf[256];
-	if (iNumWords>2)
-		sprintf(timebuf, "%s_%s", iWord[1], iWord[2]);
-	else
-		strcpy(timebuf, (char*)iWord[1]);
-
-	TInt r=StringToTime(aTime, timebuf);
-	if (r==KErrGeneral)
-		{
-		Print(EError, "incorrect format for time keyword on line %d\n", iCurrentLine);
-		exit(0x670);
-		}
-	if (r==KErrArgument)
-		{
-		Print(EError, "Time out of range on line %d\n", iCurrentLine);
-		exit(0x670);
-		}
-	}
-
-TInt64 ObeyFileReader::iTimeNow=0;
-void ObeyFileReader::TimeNow(TInt64& aTime)
-	{
-	if (iTimeNow==0)
-		{
-		TInt sysTime=time(0);					// seconds since midnight Jan 1st, 1970
-		sysTime-=(30*365*24*60*60+7*24*60*60);	// seconds since midnight Jan 1st, 2000
-		TInt64 daysTo2000AD=730497;
-		TInt64 t=daysTo2000AD*24*3600+sysTime;	// seconds since 0000
-		t=t+3600;								// BST (?)
-		iTimeNow=t*1000000;						// milliseconds
-		}
-	aTime=iTimeNow;
-	}
-
-/**
-Funtion to get the current oby file line
-*/
-TText* ObeyFileReader::GetCurrentObeyStatement() const
-{ 
-	return iCurrentObeyStatement;
-}
-
-// File attributes.
-
-
-const FileAttributeKeyword ObeyFileReader::iAttributeKeywords[] =
-{
-	{"attrib",3			,0,1,EAttributeAtt, "File attributes in ROM file system"},
-	{"exattrib",3		,0,1,EAttributeAttExtra, "File extra attributes in ROM file system"},
-//	{_K("compress")		,1,1,EAttributeCompress, "Compress file"},
-	{"stack",3			,1,1,EAttributeStack, "?"},
-	{"fixed",3			,1,0,EAttributeFixed, "Relocate to a fixed address space"},
-	{"priority",3		,1,1,EAttributePriority, "Override process priority"},
-	{_K("uid1")			,1,1,EAttributeUid1, "Override first UID"},
-	{_K("uid2")			,1,1,EAttributeUid2, "Override second UID"},
-	{_K("uid3")			,1,1,EAttributeUid3, "Override third UID"},
-	{_K("heapmin")		,1,1,EAttributeHeapMin, "Override initial heap size"},
-	{_K("heapmax")		,1,1,EAttributeHeapMax, "Override maximum heap size"},
-	{_K("capability")	,1,1,EAttributeCapability, "Override capabilities"},
-	{_K("unpaged")		,1,0,EAttributeUnpaged, "Don't page code or data for this file"},
-	{_K("paged")		,1,0,EAttributePaged, "Page code and data for this file"},
-	{_K("unpagedcode")	,1,0,EAttributeUnpagedCode, "Don't page code for this file"},
-	{_K("pagedcode")	,1,0,EAttributePagedCode, "Page code for this file"},
-	{_K("unpageddata")	,1,0,EAttributeUnpagedData, "Don't page data for this file"},
-	{_K("pageddata")	,1,0,EAttributePagedData, "Page data for this file"},
-	{0,0,0,0,EAttributeAtt,0}
-};
-
-TInt ObeyFileReader::NextAttribute(TInt& aIndex, TInt aHasFile, enum EFileAttribute& aKeyword, TText*& aArg)
-	{
-NextAttribute:
-	if (aIndex >= iNumWords)
-		return KErrEof;
-	TText* word=iWord[aIndex++];
-	const FileAttributeKeyword* k;
-	for (k=iAttributeKeywords; k->iKeyword!=0; k++)
-		{
-		if (k->iKeywordLength == 0)
-			{
-			// Exact match on keyword
-			if (stricmp((const char*)word, k->iKeyword) != 0)
-				continue;
-			}
-		else
-			{
-			// Prefix match
-			if (strnicmp((const char*)word, k->iKeyword, k->iKeywordLength) != 0)
-				continue;
-			}
-		// found a match
-		if (k->iNumArgs>0)
-			{
-			TInt argIndex = aIndex;
-			aIndex += k->iNumArgs;		// interface only really supports 1 argument
-			if (aIndex>iNumWords)
-				{
-				Print(EError, "Missing argument for attribute %s on line %d\n", word, iCurrentLine);
-				return KErrArgument;
-				}
-			aArg=iWord[argIndex];
-			}
-		if (k->iIsFileAttribute && !aHasFile)
-			{
-			Print(EError, "File attribute %s applied to non-file on line %d\n", word, iCurrentLine);
-			return KErrNotSupported;
-			}
-		aKeyword=k->iAttributeEnum;
-		return KErrNone;
-		}
-	Print(EWarning, "Unknown attribute '%s' skipped on line %d\n", word, iCurrentLine);
-	goto NextAttribute;
-	}
-
-
-
-/**
-Constructor:
-1.Obey file instance.
-2.used by both rofs and datadrive image.
-
-@param aReader - obey file reader object.
-*/
-CObeyFile::CObeyFile(ObeyFileReader& aReader):
-	iRomFileName(NULL),
-	iExtensionRofsName(0),
-	iKernelRofsName(0),
-	iRomSize(0),
-	iVersion(0,0,0),
-	iCheckSum(0),
-	iNumberOfFiles(0),
-	iTime(0),
-	iRootDirectory(0),
-	iNumberOfDataFiles(0),
-	iDriveFileName(0),
-	iDataSize(0),
-	iDriveFileFormat(0),
-	iConfigurableFatAttributes(new ConfigurableFatAttributes),
-	iReader(aReader), 
-	iMissingFiles(0), 
-	iLastExecutable(0),
-	iFirstFile(0), 	
-	iCurrentFile(0),
-	iAutoSize(EFalse),
-	iAutoPageSize(4096),
-	iPagingOverrideParsed(0),
-	iCodePagingOverrideParsed(0),
-	iDataPagingOverrideParsed(0),
-	iPatchData(new CPatchDataProcessor)
-	{
-		iNextFilePtrPtr = &iFirstFile ;
-	}
-
-/**
-Obey file Destructor.
-1.Release the tree memory.
-2.Release all allocated memory if any.
-*/
-CObeyFile::~CObeyFile()
-//
-// Destructor
-//
-	{
-	if(iDriveFileName)
-		delete[] iDriveFileName;					
-	if(iDriveFileFormat)
-		delete[] iDriveFileFormat;
-	iRootDirectory->deleteTheFirstNode();                
-	iRootDirectory->InitializeCount();
-
-	Release();
-	delete [] iRomFileName;
-	if (iRootDirectory)
-		iRootDirectory->Destroy();
-
-	delete iConfigurableFatAttributes;
-	delete iPatchData;
-	}
-
-TBool CObeyFile::AutoSize()
-{
-	return iAutoSize;
-}
-
-TUint32 CObeyFile::AutoPageSize()
-{
-	return iAutoPageSize;
-}
-
-void CObeyFile::Release()
-//
-// Free resources not needed after building a ROM
-//
-	{
-	iFirstFile = 0;
-	iNextFilePtrPtr = &iFirstFile;
-	}
-
-TRomBuilderEntry *CObeyFile::FirstFile()
-	{
-	iCurrentFile = iFirstFile;
-	return iCurrentFile;
-	}
-
-TRomBuilderEntry *CObeyFile::NextFile()
-	{
-	iCurrentFile = iCurrentFile ? iCurrentFile->iNext : 0;
-	return iCurrentFile;
-	}
-
-TText* CObeyFile::ProcessCoreImage()
-	{
-	// check for coreimage keyword and return filename
-	iReader.Rewind();
-	enum EKeyword keyword;
-	TText* coreImageFileName = 0;
-	while (iReader.NextLine(1,keyword) != KErrEof)
-		{
-		  if (keyword == EKeywordCoreImage)
-			  {
-  			  #if defined(__TOOLS2__) && defined (_STLP_THREADS)
-  			  istringstream val(iReader.Word(1),(ios_base::in+ios_base::out));	  
-  			  #elif __TOOLS2__
-  			  istringstream val(iReader.Word(1),(std::_Ios_Openmode)(ios_base::in+ios_base::out));
-			  #else
-			  istrstream val(iReader.Word(1),strlen(iReader.Word(1)));
-			  #endif
-			  iReader.CopyWord(1, coreImageFileName);
-			  iReader.MarkNext(); // ready for processing extension
-			  break;
-			  }
-		}
-	return coreImageFileName;
-	}
-
-void CObeyFile::SkipToExtension()
-	{
-	iReader.Rewind();
-	enum EKeyword keyword;
-	while (iReader.NextLine(1,keyword) != KErrEof)
-		{
-		  if (keyword == EKeywordExtensionRofs)
-			  {
-			  iReader.Mark(); // ready for processing extension
-			  break;
-			  }
-		}
-	}
-TInt CObeyFile::ProcessRofs()
-	{
-	//
-	// First pass through the obey file to set up key variables
-	//
-
-	iReader.Rewind();
-
-	TInt count=0;
-	enum EKeyword keyword;
-	while (iReader.NextLine(1,keyword) != KErrEof)
-		{
-		  if (keyword == EKeywordExtensionRofs)
-		    {
-		      if (count==0)
-			return KErrNotFound;		// no core ROFS, just extension ROFSs.
-		      break;
-		    }
-
-		count++;
-		if (! ProcessKeyword(keyword))
-			return KErrGeneral;
-		}
-
-	if (!GotKeyVariables())
-		return KErrGeneral;
-
-	//
-	// second pass to process the file specifications in the obey file building
-	// up the TRomNode directory structure and the TRomBuilderEntry list
-	//
-	iReader.Rewind();
-
-	iRootDirectory = new TRomNode((TText*)"");
-	iLastExecutable = iRootDirectory;
-
-	TInt align=0;
-	while (iReader.NextLine(2,keyword)!=KErrEof)
-		{
-		if (keyword == EKeywordExtensionRofs)
-			break;
-
-		if (keyword == EKeywordHide)
-			keyword = EKeywordHideV2;
-
-		switch (keyword)
-			{
-			  
-		case EKeywordHide:
-		case EKeywordAlias:
-		case EKeywordRename:
-			if (!ProcessRenaming(keyword))
-				return KErrGeneral;
-			break;
-		case EKeywordPatchDllData:
-		{
-			// Collect patchdata statements to process at the end
-			StringVector patchDataTokens;
-			SplitPatchDataStatement(patchDataTokens); 
-			iPatchData->AddPatchDataStatement(patchDataTokens);									
-			break;
-		}
-		default:
-		        if (!ProcessFile(align, keyword))
-		        return KErrGeneral;
-		        align=0;
-		        break;
-			}
-		}
-
-	if(!ParsePatchDllData())
-		return KErrGeneral;
-	iReader.Mark();			// ready for processing the extension rom(s)
-
-	if (iMissingFiles!=0)
-		{
-		return KErrGeneral;
-		}
-	if ( 0 == iNumberOfFiles )
-		{
-		Print(EError, "No files specified.\n");
-		return KErrGeneral;
-		}
-
-	return KErrNone;
-	}
-
-TBool CObeyFile::Process()
-{
-	TBool result = ETrue;
-	iReader.Rewind();
-	enum EKeyword keyword;
-	while(iReader.NextLine(1, keyword) != KErrEof)
-	{
-		String key = iReader.Word(0);
-		String value = iReader.Word(1);
-		if(iKeyValues.find(key) != iKeyValues.end())
-		{
-			iKeyValues[key].push_back(value);
-		}
-		else
-		{
-			StringVector values;
-			values.push_back(value);
-			iKeyValues[key]=values;
-		}
-
-
-	}
-	return result;
-}
-StringVector CObeyFile::getValues(const String& aKey)
-{
-	StringVector values;
-	if(iKeyValues.find(aKey) != iKeyValues.end())
-	{
-		values = iKeyValues[aKey];
-	}
-	return values;
-}
-
-/**
-Process drive obey file and construct the tree.
-
-@return - Return the status,
-          'KErrnone' for Success,
-          'KErrGeneral' for failure (required keywords not there in obey file or failed
-									 to construct the tree).
-*/
-TInt CObeyFile::ProcessDataDrive()
-	{
-
-	iReader.Rewind();
-	enum EKeyword keyword;
-
-	// First pass through the obey file to set up key variables
-	while (iReader.NextLine(1,keyword) != KErrEof)	
-		{
-		if (!ProcessDriveKeyword(keyword))			
-			return KErrGeneral;
-		}
-
-	if (!GotKeyDriveVariables())
-		return KErrGeneral;
-
-	// Second pass to process the file specifications in the obey file.
-	// Build the TRomNode directory structure and the TRomBuilderEntry list
-	iReader.Rewind();
-	iRootDirectory = new TRomNode((TText*)"//");					
-	iLastExecutable = iRootDirectory;
-
-	while(iReader.NextLine(2,keyword)!=KErrEof)
-		{
-		switch (keyword)
-			{
-			case EKeywordPatchDllData:
-			{	// Collect patchdata statements to process at the end
-				StringVector patchDataTokens;
-				SplitPatchDataStatement(patchDataTokens); 				
-				iPatchData->AddPatchDataStatement(patchDataTokens);									
-				break;
-			}
-	
-			case EKeywordHide:						
-			case EKeywordFile:
-			case EKeywordData:
-			case EKeywordFileCompress:
-			case EKeywordFileUncompress:
-		        if (!ProcessDriveFile(keyword))
-				  return KErrGeneral;
-		        break;
-	
-			default:							
-		        break;
-			}
-		}
-
-	if(!ParsePatchDllData())
-		return KErrGeneral;
-    if (iMissingFiles)   
-		{
-		Print(EError, "Source Files Missing.\n");
-		return KErrGeneral;
-		}
-	if (!iNumberOfFiles)
-		Print(EWarning,"No files specified.\n");
-	
-	return KErrNone;
-	}
-
-
-/**
-Process and stores the keyword information.
-
-@param aKeyword - keyword to update its value to variables.
-@return - Return the status i.e Success,
-*/
-TBool CObeyFile::ProcessDriveKeyword(enum EKeyword aKeyword)
-	{
-
-	TBool success = ETrue;
-	switch (aKeyword)
-		{
-		case EKeywordDataImageName:
-			iReader.CopyWord(1, iDriveFileName);
-			break;
-		case EKeywordDataImageFileSystem:
-			iReader.CopyWord(1, iDriveFileFormat);
-			break;
-		case EKeywordDataImageSize:
-			{
-			char* bigString = iReader.Word(1);
-			if(*bigString == '\0')
-				{
-				Print(EWarning,"Not a valid Image Size. Default size is considered\n");		
-				break;
-				}
-#ifdef __LINUX__
-			errno = 0;
-			iDataSize = strtoll(bigString,NULL,10);
-			if((iDataSize == LONG_MAX) || (iDataSize == LONG_MIN) ||(errno == ERANGE))
-				{
-				Print(EWarning,"Invalid Range. Default size is considered\n");		
-				}
-#else
-			iDataSize = _atoi64(bigString);
-#endif
-			}
-			break;
-		case EKeywordDataImageVolume:
-			{				
-				// Get the volume label provided by using "volume" keyword.
-				// e.g. vlolume = NO NAME
-				String volumeLabel = (char*)iReader.GetCurrentObeyStatement();
-				String volumeLabelKeyword = "volume";
-
-				TUint position = volumeLabel.find(volumeLabelKeyword.c_str(),0,volumeLabelKeyword.size());
-				position += volumeLabelKeyword.size();
-				if (volumeLabel.find('=',position) != std::string::npos)
-				{
-					position=volumeLabel.find('=',position);
-					++position;
-				}								
-
-				position = volumeLabel.find_first_not_of(' ',position);
-				if (position != std::string::npos)
-				{
-					volumeLabel = volumeLabel.substr(position);
-
-					// Remove the new line character from the end
-					position = volumeLabel.find_first_of("\r\n");
-					if (position != std::string::npos)
-						volumeLabel = volumeLabel.substr(0,position);
-
-					iConfigurableFatAttributes->iDriveVolumeLabel = volumeLabel.data(); 								
-				}
-				else
-				{
-					Print(EWarning,"Value for Volume Label is not provided. Default value is considered.\n");
-				}
-				break;
-			}
-		case EKeywordDataImageSectorSize:
-			{
-				char* bigString = iReader.Word(1);
-				TInt sectorSize = atoi(bigString);
-				if(sectorSize <= 0)
-				{
-					Print(EWarning,"Invalid Sector Size value. Default value is considered.\n");
-				}
-				else
-				{
-					iConfigurableFatAttributes->iDriveSectorSize = atoi(bigString);
-				}
-			}			
-			break;
-		case EKeywordDataImageNoOfFats:
-			{
-				char* bigString = iReader.Word(1);
-				TInt noOfFats = atoi(bigString);
-				if (noOfFats <=0)
-				{
-					Print(EWarning,"Invalid No of FATs specified. Default value is considered.\n");
-				}
-				else
-				{
-					iConfigurableFatAttributes->iDriveNoOfFATs = atoi(bigString);			
-				}
-			}			
-			break;			
-		default:
-			// unexpected keyword iReader.Word(0), keep going.
-			break;
-		}
-	return success;
-	}
-
-
-/**
-Checks whether obeyfile has supplied enough variables to continue.
-
-@return - Return the status 
-		  ETrue - Supplied valid values,
-		  EFalse- Not valied values.
-*/
-TBool CObeyFile::GotKeyDriveVariables()
-   	{
-
-	TBool retVal=ETrue;
-
-	// Mandatory keywords
-	if (iDriveFileName==0)                             
-		{                                                  
-		Print(EError,"The name of the image file has not been supplied.\n");
-		Print(EError,"Use the keyword \"dataimagename\".\n");
-		retVal = EFalse;
-		}
-		
-	// Check for '-'ve entered value.
-	if(iDataSize <= 0)
-		{
-		Print(EWarning,"Image Size should be positive. Default size is Considered.\n");
-		}
-
-	// File system format.
-	if(iDriveFileFormat==0)
-		{
-		Print(EError,"The name of the file system not been supplied.\n");
-		Print(EError,"Use the keyword \"dataimagefilesystem\".\n");
-		retVal = EFalse;
-		}
-
-	// Checking the validity of file system format.
-	if(iDriveFileFormat)
-		{
-		strupr((char *)iDriveFileFormat);
-		enum TFileSystem check = (TFileSystem)0;
-		if(!(CDriveImage::FormatTranslation(iDriveFileFormat,check)))
-			{
-			Print(EError,"The name of the file system not supported : %s\n",iDriveFileFormat);
-			retVal = EFalse;
-			}
-		}
-	
-	if(retVal)
-		Print(ELog,"\nCreating Data Drive image : %s\n", iDriveFileName);
-
-  	return retVal;
-	}
-
-/**
-Process a parsed line to set up one or more new TRomBuilder entry objects.
-
-@param  - obey file keyword.
-// iWord[0] = the keyword (file,)      
-// iWord[1] = the PC pathname
-// iWord[2] = the EPOC pathname
-// iWord[3] = start of the file attributes
-
-@return - Return the status 
-		  ETrue - Successful generation of tree.
-		  EFalse- Fail to generate the tree.
-*/
-TBool CObeyFile::ProcessDriveFile(enum EKeyword aKeyword)               
-	{
-
-	TBool isPeFile = ETrue;
-	TBool aFileCompressOption, aFileUncompressOption;
-
-	TInt epocPathStart=2;
-	aFileCompressOption = aFileUncompressOption = EFalse;
-	// do some validation of the keyword
-	TInt currentLine = iReader.CurrentLine();
-
-	switch (aKeyword)
-		{
-		case EKeywordData:
-		case EKeywordHide:
-			isPeFile = EFalse;
-			break;
-
-		case EKeywordFile:
-			break;
-
-		case EKeywordFileCompress:
-			aFileCompressOption = ETrue;
-			break;
-
-		case EKeywordFileUncompress:
-			aFileUncompressOption = ETrue;
-			break;
-
-		default:
-			return EFalse;
-		}
-
-	if (aKeyword!=EKeywordHide)
-		{
-		// check the PC file exists
-		char* nname = NormaliseFileName(iReader.Word(1));                 
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)																		  
-		ifstream test(nname);
-#else //!__MSVCDOTNET__
-		ifstream test(nname, ios::nocreate);
-#endif //__MSVCDOTNET__
-
-		if (!test)
-			{
-			Print(EError,"Cannot open file %s for input.\n",iReader.Word(1));
-			iMissingFiles++;
-			}
-
-		test.close();
-		if(nname)
-			free(nname);												
-		nname = 0;
-		}
-	else
-		epocPathStart=1;   
-
-	iNumberOfFiles++;
-
-	TBool endOfName=EFalse;
-	TText *epocStartPtr=IsValidFilePath(iReader.Text(epocPathStart));
-	TText *epocEndPtr=epocStartPtr;
-
-	if (epocStartPtr==NULL)
-		{
-		Print(EError, "Invalid destination path on line %d\n",currentLine);
-		return EFalse;
-		}
-
-	TRomNode* dir=iRootDirectory;
-	TRomNode* subDir=0;
-	TRomBuilderEntry *file=0;      
-
-	while (!endOfName)
-		{
-		endOfName = GetNextBitOfFileName(&epocEndPtr);      
-		if (endOfName) // file
-			{
-			TRomNode* alreadyExists=dir->FindInDirectory(epocStartPtr);
-
-			if ((aKeyword != EKeywordHide) && alreadyExists) // duplicate file
-				{
-				Print(EError, "Duplicate file for %s on line %d\n",iReader.Word(1),iReader.CurrentLine());
-				return EFalse;
-				}
-			else if((aKeyword == EKeywordHide) && (alreadyExists))
-				{ 
-				alreadyExists->iEntry->iHidden = ETrue;
-				alreadyExists->iHidden = ETrue;
-				return ETrue;
-				}
-			else if((aKeyword == EKeywordHide) && (!alreadyExists))
-				{
-				Print(EWarning, "Hiding non-existent file %s on line %d\n",iReader.Word(1),iReader.CurrentLine());
-				return ETrue;
-				}
-				
-			file = new TRomBuilderEntry(iReader.Word(1), epocStartPtr);                   
-			file->iExecutable=isPeFile;
-			if( aFileCompressOption )
-			{
-			file->iCompressEnabled = ECompressionCompress;
-			}
-			else if(aFileUncompressOption )
-			{
-			file->iCompressEnabled = ECompressionUncompress;
-			}
-			
-			TRomNode* node=new TRomNode(epocStartPtr, file);
-			if (node==0)
-				return EFalse;
-
-			TInt r=ParseFileAttributes(node, file, aKeyword);         
-			if (r!=KErrNone)
-				return EFalse;
-
-			if(gCompress != ECompressionUnknown)
-			{
-			node->iFileUpdate = ETrue;
-			}
-
-			if((node->iOverride) || (aFileCompressOption) || (aFileUncompressOption))
-			{
-			node->iFileUpdate = ETrue;
-			}
-
-			dir->AddFile(node);	// to drive directory structure.
-			}		 
-		else	
-		{
-		// directory
-		subDir = dir->FindInDirectory(epocStartPtr);      
-		if (!subDir) // sub directory does not exist
-			{
-			if(aKeyword==EKeywordHide)
-			{
-			Print(EWarning, "Hiding non-existent file %s on line %d\n",iReader.Word(1),iReader.CurrentLine());
-			return ETrue;
-			}
-			subDir = dir->NewSubDir(epocStartPtr);
-			if (!subDir)
-				return EFalse;
-			}
-			dir=subDir;
-
-			epocStartPtr = epocEndPtr;
-			}  // end of else.
-		}
-	return ETrue;
-	}
-
-
-TInt CObeyFile::SetStackSize(TRomNode *aNode, TText *aStr)
-	{
-	if (isNumber(aStr)==0)
-		return Print(EError, "Number required as argument for keyword 'stack'.\n");
-	aNode->SetStackSize( getNumber(aStr) );
-	return KErrNone;
-	}
-
-TInt CObeyFile::SetHeapSizeMin(TRomNode *aNode, TText *aStr)
-	{
-	if (isNumber(aStr)==0)
-		return Print(EError, "Number required as argument for keyword 'heapmin'.\n");
-	aNode->SetHeapSizeMin( getNumber(aStr) );
-	return KErrNone;
-	}
-
-TInt CObeyFile::SetHeapSizeMax(TRomNode *aNode, TText *aStr)
-	{
-	if (isNumber(aStr)==0)
-		return Print(EError, "Number required as argument for keyword 'heapmax'.\n");
-	aNode->SetHeapSizeMax( getNumber(aStr) );
-	return KErrNone;
-	}
-
-TInt CObeyFile::SetCapability(TRomNode *aNode, TText *aStr)
-	{
-	if (isNumber(aStr))
-		{
-		Print(EDiagnostic,"Old style numeric CAPABILTY specification ignored.\n");
-		return KErrNone;
-		}
-	SCapabilitySet cap;
-	TInt r = ParseCapabilitiesArg(cap, (char*)aStr);
-	if( KErrNone == r )
-		{
-		aNode->SetCapability( cap );
-		}
-	return r;
-	}
-
-TInt CObeyFile::SetPriority(TRomNode *aNode, TText *aStr)
-	{
-	TProcessPriority priority;
-	if (isNumber(aStr))
-		{
-		priority = (TProcessPriority)getNumber(aStr);
-		}
-	else
-		{
-		char *str=(char *)aStr;
-		if (stricmp(str, "low")==0)
-			priority=EPriorityLow;
-		else if (strnicmp(str, "background", 4)==0)
-			priority=EPriorityBackground;
-		else if (strnicmp(str, "foreground", 4)==0)
-			priority=EPriorityForeground;
-		else if (stricmp(str, "high")==0)
-			priority=EPriorityHigh;
-		else if (strnicmp(str, "windowserver",3)==0)
-			priority=EPriorityWindowServer;
-		else if (strnicmp(str, "fileserver",4)==0)
-			priority=EPriorityFileServer;
-		else if (strnicmp(str, "realtimeserver",4)==0)
-			priority=EPriorityRealTimeServer;
-		else if (strnicmp(str, "supervisor",3)==0)
-			priority=EPrioritySupervisor;
-		else
-			return Print(EError, "Unrecognised priority keyword.\n");
-		}
-	if (priority<EPriorityLow || priority>EPrioritySupervisor)
-		return Print(EError, "Priority out of range.\n");
-
-	aNode->SetPriority( priority );
-	return KErrNone;
-	}
-
-TInt CObeyFile::SetUid1(TRomNode *aNode, TText *aStr)
-	{
-	if (isNumber(aStr)==0)
-		return Print(EError, "Number required as argument for keyword 'uid1'.\n");
-	aNode->SetUid1( getNumber(aStr) );
-	return KErrNone;
-	}
-TInt CObeyFile::SetUid2(TRomNode *aNode, TText *aStr)
-	{
-	if (isNumber(aStr)==0)
-		return Print(EError, "Number required as argument for keyword 'uid2'.\n");
-	aNode->SetUid2( getNumber(aStr) );
-	return KErrNone;
-	}
-TInt CObeyFile::SetUid3(TRomNode *aNode, TText *aStr)
-	{
-	if (isNumber(aStr)==0)
-		return Print(EError, "Number required as argument for keyword 'uid3'.\n");
-	aNode->SetUid3( getNumber(aStr) );
-	return KErrNone;
-	}
-
-
-TInt CObeyFile::ParseFileAttributes(TRomNode *aNode, TRomBuilderEntry* aFile, enum EKeyword aKeyword)
-//
-// Process any inline keywords
-//
-	{
-	TInt currentLine = iReader.CurrentLine();
-	enum EFileAttribute attribute;
-	TInt r=KErrNone;
-	TInt index=3;
-	TText* arg=0;
-
-	while(r==KErrNone)
-		{
-		r=iReader.NextAttribute(index,(aFile!=0),attribute,arg);
-		if (r!=KErrNone)
-			break;
-		switch(attribute)
-			{
-		case EAttributeAtt:
-			r=aNode->SetAtt(arg);
-			break;
-		case EAttributeAttExtra:
-			r=aNode->SetAttExtra(arg, aFile, aKeyword);
-			break;
-		case EAttributeStack:
-			r=SetStackSize(aNode, arg);
-			break;
-		case EAttributeFixed:
-			aNode->SetFixed();
-			r = KErrNone;
-			break;
-		case EAttributeUid1:
-			r=SetUid1(aNode, arg);
-			break;
-		case EAttributeUid2:
-			r=SetUid2(aNode, arg);
-			break;
-		case EAttributeUid3:
-			r=SetUid3(aNode, arg);
-			break;
-		case EAttributeHeapMin:
-			r=SetHeapSizeMin(aNode, arg);
-			break;
-		case EAttributeHeapMax:
-			r=SetHeapSizeMax(aNode, arg);
-			break;
-		case EAttributePriority:
-			r=SetPriority(aNode, arg);
-			break;
-		case EAttributeCapability:
-			r=SetCapability(aNode, arg);
-			break;
-		case EAttributeUnpaged:
-			aNode->iOverride |= KOverrideCodeUnpaged|KOverrideDataUnpaged;
-			aNode->iOverride &= ~(KOverrideCodePaged|KOverrideDataPaged);
-			break;
-		case EAttributePaged:
-			aNode->iOverride |= KOverrideCodePaged|KOverrideDataPaged;
-			aNode->iOverride &= ~(KOverrideCodeUnpaged|KOverrideDataUnpaged);
-			break;
-		case EAttributeUnpagedCode:
-			aNode->iOverride |= KOverrideCodeUnpaged;
-			aNode->iOverride &= ~KOverrideCodePaged;
-			break;
-		case EAttributePagedCode:
-			aNode->iOverride |= KOverrideCodePaged;
-			aNode->iOverride &= ~KOverrideCodeUnpaged;
-			break;
-		case EAttributeUnpagedData:
-			aNode->iOverride |= KOverrideDataUnpaged;
-			aNode->iOverride &= ~KOverrideDataPaged;
-			break;
-		case EAttributePagedData:
-			aNode->iOverride |= KOverrideDataPaged;
-			aNode->iOverride &= ~KOverrideDataUnpaged;
-			break;
-
-		default:
-			return Print(EError, "Unrecognised keyword in file attributes on line %d.\n",currentLine);
-			}
-		}
-
-	if (r==KErrEof)
-		return KErrNone;
-	return r;
-	}
-
-
-TBool CObeyFile::ProcessFile(TInt /*aAlign*/, enum EKeyword aKeyword)
-//
-// Process a parsed line to set up one or more new TRomBuilder entry objects.
-// iWord[0] = the keyword (file, primary or secondary)
-// iWord[1] = the PC pathname
-// iWord[2] = the EPOC pathname
-// iWord[3] = start of the file attributes
-//
-	{
-	TBool isPeFile = ETrue;
-	TBool aFileCompressOption, aFileUncompressOption;
-	TInt epocPathStart=2;
-	aFileCompressOption = aFileUncompressOption = EFalse;
- 	TBool warnFlag = EFalse;
- 	static const char aStdPath[] = "SYS\\BIN\\";
- 	static const int sysBinLength = sizeof(aStdPath)-1;
-
-	// do some validation of the keyword
-	TInt currentLine = iReader.CurrentLine();
-
-	switch (aKeyword)
-		{
-	case EKeywordData:
-	case EKeywordHideV2:
-		iNumberOfDataFiles++;
-		isPeFile = EFalse;
-		break;
-
-	case EKeywordFile:
-		warnFlag = gEnableStdPathWarning;
-		break;
-	case EKeywordFileCompress:
-		aFileCompressOption = ETrue;
-		warnFlag = gEnableStdPathWarning;
-		break;
-	case EKeywordFileUncompress:
-		aFileUncompressOption = ETrue;
-		warnFlag = gEnableStdPathWarning;
-		break;
-
-	default:
-		Print(EError,"Unexpected keyword '%s' on line %d.\n",iReader.Word(0),currentLine);
-		return EFalse;
-		}
-
-	if (aKeyword!=EKeywordHideV2)
-		{
-
-		// check the PC file exists
-		char* nname = NormaliseFileName(iReader.Word(1));
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-		ifstream test(nname);
-#else //!__MSVCDOTNET__
-		ifstream test(nname, ios::nocreate);
-#endif //__MSVCDOTNET__
-
-		if (!test)
-			{
-			Print(EError,"Cannot open file %s for input.\n",iReader.Word(1));
-			iMissingFiles++;
-			}
-		test.close();
-		free(nname);
-		}
-	else
-		epocPathStart=1;
-
-	iNumberOfFiles++;
-
-
- 	TBool endOfName=EFalse;
-	TText *epocStartPtr=IsValidFilePath(iReader.Text(epocPathStart));
-	TText *epocEndPtr=epocStartPtr;
-	if (epocStartPtr==NULL)
-		{
-		Print(EError, "Invalid destination path on line %d\n",currentLine);
-		return EFalse;
-		}
- 	if(warnFlag)	// Check for the std destination path(for executables) as per platsec.
- 		{
- 		if(strnicmp(aStdPath,(const char*)epocStartPtr,sysBinLength) != 0)
- 			{
- 			Print(EWarning,"Invalid destination path on line %d. \"%s\" \n",currentLine,epocStartPtr);
- 			}
-		}
-	
-	TRomNode* dir=iRootDirectory;
-	TRomNode* subDir=0;
-	TRomBuilderEntry *file=0;
-	while (!endOfName)
-		{
-		endOfName = GetNextBitOfFileName(&epocEndPtr);
-		if (endOfName) // file
-			{
-			TRomNode* alreadyExists=dir->FindInDirectory(epocStartPtr);
-			/*
-			 * The EKeywordHideV2 keyword is used to indicate that:
-			 *	1. if the file exists in the same image and then hidden, mark it hidden
-			 *	2. if the file exists in another image, but in this (ROFS) image, it is
-			 *		required to hide that file, create a 0 length file entry setting the 'hide'
-			 *		flag so that at runtime, file gets hidden in the composite filesystem.
-			 */
-			if ((aKeyword != EKeywordHideV2) && alreadyExists) // duplicate file
-				{
-				Print(EError, "Duplicate file for %s on line %d\n",iReader.Word(1),iReader.CurrentLine());
-				return EFalse;
-				}
-
-			TBool aHidden = aKeyword==EKeywordHideV2;
-			/* The file is only marked hidden and hence the source file name isn't known 
-			 * here as hide statement says :
-			 *	hide <filename as in ROM>
-			 * Therefore, create TRomBuilderEntry with iFileName as 0 for hidden file when
-			 * the file doesn't exist in the same ROM image. Otherwise, the src file name
-			 * is known because of alreadyExists (which comes from the 'file'/'data' statement).
-			 */
-			if(aHidden)
-				file = new TRomBuilderEntry(0, epocStartPtr);
-			else
-				file = new TRomBuilderEntry(iReader.Word(1), epocStartPtr);
-			file->iExecutable=isPeFile;
-			file->iHidden= aHidden;
-			if( aFileCompressOption )
-			{
-				file->iCompressEnabled = ECompressionCompress;
-			}
-			else if(aFileUncompressOption )
-			{
-				file->iCompressEnabled = ECompressionUncompress;
-			}
-			TRomNode* node=new TRomNode(epocStartPtr, file);
-			if (node==0)
-				return EFalse;
-			TInt r=ParseFileAttributes(node, file, aKeyword);
-			if (r!=KErrNone)
-				return EFalse;
-
-			dir->AddFile(node);	// to ROFS directory structure
-			AddFile(file);		// to our list of files
-			}		 
-		else // directory
-			{
-			subDir = dir->FindInDirectory(epocStartPtr);
-			if (!subDir) // sub directory does not exist
-				{
-				subDir = dir->NewSubDir(epocStartPtr);
-				if (!subDir)
-					return EFalse;
-				}
-			dir=subDir;
-			epocStartPtr = epocEndPtr;
-			}
-		}
-	return ETrue;
-	}
-
-
-TBool CObeyFile::ProcessRenaming(enum EKeyword aKeyword)
-	{
-
-	// find existing file
-	TBool endOfName=EFalse;
-	TText *epocStartPtr=IsValidFilePath(iReader.Text(1));
-	
-	// Store the current name and new name to maintain renamed file map
-	String currentName=iReader.Word(1);
-	String newName=iReader.Word(2);
-
-	TText *epocEndPtr=epocStartPtr;
-	if (epocStartPtr==NULL)
-		{
-		Print(EError, "Invalid source path on line %d\n",iReader.CurrentLine());
-		return EFalse;
-		}
-
-	char saved_srcname[257];
-	strcpy(saved_srcname, iReader.Word(1));
-
-	TRomNode* dir=iRootDirectory;
-	TRomNode* existingFile=0;
-	while (!endOfName)
-		{
-		endOfName = GetNextBitOfFileName(&epocEndPtr);
-		if (endOfName) // file
-			{
-			existingFile=dir->FindInDirectory(epocStartPtr);
-			if (existingFile)
-				{
-				TInt fileCount=0;
-				TInt dirCount=0;
-				existingFile->CountDirectory(fileCount, dirCount);
-				if (dirCount != 0 || fileCount != 0)
-					{
-					Print(EError, "Keyword %s not applicable to directories - line %d\n",iReader.Word(0),iReader.CurrentLine());
-					return EFalse;
-					}
-				}
-			}
-		else // directory
-			{
-			TRomNode* subDir = dir->FindInDirectory(epocStartPtr);
-			if (!subDir) // sub directory does not exist
-				break;
-			dir=subDir;
-			epocStartPtr = epocEndPtr;
-			}
-		}
-	if (aKeyword == EKeywordHide)
-		{
-			/*
-			 * The EKeywordHide keyword is used to indicate that if the file exists in 
-			 * the primary ROFS image and then hidden in extension ROFS, mark it hidden.
-			 */
-		if (!existingFile)
-			{
-			Print(EWarning, "Hiding non-existent file %s on line %d\n", 
-				saved_srcname, iReader.CurrentLine());
-			// Just a warning, as we've achieved the right overall effect.
-			}
-		else if (existingFile->iFileStartOffset==(TUint)KFileHidden)
-			{
-			Print(EWarning, "Hiding already hidden file %s on line %d\n", 
-				saved_srcname, iReader.CurrentLine());
-			// We will igrore this request, otherwise it will "undelete" it.
-			}
-		else
-			{
-			  //hidden files will not be placed to the image
-			  existingFile->iHidden = ETrue;
-			}
-		return ETrue;
-		}
-
-	if (!existingFile)
-		{
-		Print(EError, "Can't %s non-existent source file %s on line %d\n",
-			iReader.Word(0), saved_srcname, iReader.CurrentLine());
-		return EFalse;
-		}
-
-	epocStartPtr=IsValidFilePath(iReader.Text(2));
-	epocEndPtr=epocStartPtr;
-	endOfName=EFalse;
-	if (epocStartPtr==NULL)
-		{
-		Print(EError, "Invalid destination path on line %d\n",iReader.CurrentLine());
-		return EFalse;
-		}
-
-	TRomNode* newdir=iRootDirectory;
-	while (!endOfName)
-		{
-		endOfName = GetNextBitOfFileName(&epocEndPtr);
-		if (endOfName) // file
-			{
-			TRomNode* alreadyExists=newdir->FindInDirectory(epocStartPtr);
-			if (alreadyExists && !(alreadyExists->iHidden)) // duplicate file
-				{
-				Print(EError, "Duplicate file for %s on line %d\n",saved_srcname,iReader.CurrentLine());
-				return EFalse;
-				}
-			}
-		else // directory
-			{
-			TRomNode* subDir = newdir->FindInDirectory(epocStartPtr);
-			if (!subDir) // sub directory does not exist
-				{
-				subDir = newdir->NewSubDir(epocStartPtr);
-				if (!subDir)
-					return EFalse;
-				}
-			newdir=subDir;
-			epocStartPtr = epocEndPtr;
-			}
-		}
-
-	if (aKeyword == EKeywordRename)
-		{
-		// rename => remove existingFile and insert into tree at new place
-		// has no effect on the iNextExecutable or iNextNodeForSameFile links
-
-		TInt r=ParseFileAttributes(existingFile, existingFile->iEntry, aKeyword);
-		if (r!=KErrNone)
-			return EFalse;
-		existingFile->Rename(dir, newdir, epocStartPtr);
-		// Store the current and new name of file in the renamed file map.
-		iPatchData->AddToRenamedFileMap(currentName, newName);
-		return ETrue;
-		}
-	
-	// alias => create new TRomNode entry and insert into tree
-
-	TRomNode* node = new TRomNode(epocStartPtr, 0);
-	if (node == 0)
-		{
-		Print(EError, "Out of memory\n");
-		return EFalse;
-		}
-	node->Alias(existingFile);
-	TInt r=ParseFileAttributes(node, 0, aKeyword);
-	if (r!=KErrNone)
-		return EFalse;
-
-	newdir->AddFile(node);	// to ROFS directory structure, though possibly hidden
-
-	return ETrue;
-	}
-
-TInt ParsePagingPolicy(const char* policy)
-	{
-	if(stricmp(policy,"NOPAGING")==0)
-		return EKernelConfigPagingPolicyNoPaging;
-	else if (stricmp(policy,"ALWAYSPAGE")==0)
-		return EKernelConfigPagingPolicyAlwaysPage;
-	else if(stricmp(policy,"DEFAULTUNPAGED")==0)
-		return EKernelConfigPagingPolicyDefaultUnpaged;
-	else if(stricmp(policy,"DEFAULTPAGED")==0)
-		return EKernelConfigPagingPolicyDefaultPaged;
-	return KErrArgument;
-	}
-
-TBool CObeyFile::ProcessKeyword(enum EKeyword aKeyword)
-	{
-	#ifdef __TOOLS2__
-	istringstream val(iReader.Word(1));
-	#else
-	istrstream val(iReader.Word(1),strlen(iReader.Word(1)));
-	#endif
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-	val >> setbase(0);
-#endif //__MSVCDOTNET__
-
-	TBool success = ETrue;
-
-	switch (aKeyword)
-		{
-	case EKeywordRofsName:
-		iReader.CopyWord(1, iRomFileName);
-		break;
-	case EKeywordRofsSize:
-		val >> iRomSize;
-		break;
-	case EKeywordVersion:
-		val >> iVersion;
-		break;
-	case EKeywordRofsChecksum:
-		val >> iCheckSum;
-		break;
-	case EKeywordTime:
-		iReader.ProcessTime(iTime);
-		break;
-	case EKeywordPagingOverride:
-		{
-		if(iPagingOverrideParsed)
-			Print(EWarning, "PagingOverride redefined - previous PagingOverride values lost\n");
-		if(iCodePagingOverrideParsed)
-			Print(EWarning, "PagingOverride defined - previous CodePagingOverride values lost\n");
-		if(iDataPagingOverrideParsed)
-			Print(EWarning, "PagingOverride defined - previous DataPagingOverride values lost\n");
-		iPagingOverrideParsed = true;
-		TInt policy = ParsePagingPolicy(iReader.Word(1));
-		if(policy<0)
-			{
-			Print(EError,"Unrecognised option for PAGINGOVERRIDE keyword\n");
-			success = false;
-			}
-		else
-			{
-			gCodePagingOverride = policy;
-			gDataPagingOverride = policy;
-			}
-		}
-		break;
-	case EKeywordCodePagingOverride:
-		{
-		if(iCodePagingOverrideParsed)
-			Print(EWarning, "CodePagingOverride redefined - previous CodePagingOverride values lost\n");
-		if(iPagingOverrideParsed)
-			Print(EWarning, "CodePagingOverride defined - previous PagingOverride values lost\n");
-		iCodePagingOverrideParsed = true;
-		TInt policy = ParsePagingPolicy(iReader.Word(1));
-		if(policy<0)
-			{
-			Print(EError,"Unrecognised option for CODEPAGINGOVERRIDE keyword\n");
-			success = false;
-			}
-		else
-			gCodePagingOverride = policy;
-		}
-		break;
-	case EKeywordDataPagingOverride:
-		{
-		if(iDataPagingOverrideParsed)
-			Print(EWarning, "DataPagingOverride redefined - previous DataPagingOverride values lost\n");
-		if(iPagingOverrideParsed)
-			{
-			Print(EError, "DataPagingOverride defined - previous PagingOverride values lost\n");
-			success = false;
-			break;
-			}
-		iDataPagingOverrideParsed = true;
-		TInt policy = ParsePagingPolicy(iReader.Word(1));
-		if(policy<0)
-			{
-			Print(EError,"Unrecognised option for DATAPAGINGOVERRIDE keyword\n");
-			success = false;
-			}
-		else
-			gDataPagingOverride = policy;
-		}
-		break;
-	case EKeywordRofsAutoSize:
-		iAutoSize = ETrue;
-		val >> iAutoPageSize;
-		break;
-	default:
-		// unexpected keyword iReader.Word(0)
-		break;
-		}
-
-	return success;
-	}
-
-TBool CObeyFile::GotKeyVariables()
-//
-// Checks that the obeyfile has supplied enough variables to continue
-//
-   	{
-
-	TBool retVal=ETrue;
-
-	// Mandatory keywords
-
-	if (iRomFileName==0)
-		{
-		Print(EAlways,"The name of the image file has not been supplied.\n");
-		Print(EAlways,"Use the keyword \"rofsname\".\n");
-		retVal = EFalse;
-		}
-	if (iRomSize==0)
-		{
-		Print(EAlways,"The size of the image has not been supplied.\n");
-		Print(EAlways,"Use the keyword \"rofssize\".\n");
-		retVal = EFalse;
-		}
-
-	// Apply defaults as necessary
-	if (iTime==0)
-		{
-		Print(ELog, "No timestamp specified. Using current time...\n");
-		ObeyFileReader::TimeNow(iTime);
-		}
-
-	Print(ELog, "\nCreating Rofs image %s\n", iRomFileName);
-	return retVal;
-	}
-
-
-TText *CObeyFile::IsValidFilePath(TText *aPath)
-//
-// Check the path is valid
-//
-	{
-	// skip leading "\"
-	if (*aPath=='\\')
-		aPath++;
-	if (*aPath==0)
-		return NULL; // file ends in a backslash
-
-	TText *p=aPath;
-	TInt len=0;
-	FOREVER
-		{
-		if (*p==0)
-			return (len ? aPath : NULL);
-		if (*p=='\\')
-			{
-			if (len==0)
-				return NULL;
-			len=0;
-			}
-		len++;
-		p++;
-		}
-	}
-
-TBool CObeyFile::GetNextBitOfFileName(TText **epocEndPtr)
-//
-// Move the end pointer past the next directory separator, replacing it with 0
-//
-	{
-	while (**epocEndPtr != '\\') // until reach the directory separator
-		{
-		if (**epocEndPtr==0) // if reach end of string, return TRUE, it's the filename
-			return ETrue;
-		(*epocEndPtr)++;
-		}
-	**epocEndPtr=0; // overwrite the directory separator with a 0
-	(*epocEndPtr)++; // point past the 0 ready for the next one
-	return EFalse;
-	}
-
-
-void CObeyFile::AddFile(TRomBuilderEntry* aFile)
-	{
-	*iNextFilePtrPtr = aFile;
-	iNextFilePtrPtr = &(aFile->iNext);
-	}
-
-
-
-TInt CObeyFile::ProcessExtensionRofs(MRofsImage* aKernelRom)
-	{
-	//
-	// First pass through the obey file to set up key variables
-	//
-
-
-        iReader.Rewind();
-
-	enum EKeyword keyword;
-
-	// Deal with the "extensionrofs" keyword, which should be first
-		
-	if (iReader.NextLine(1,keyword) != KErrNone)
-		return KErrEof;
-	if (keyword != EKeywordExtensionRofs)
-		return Print(EError, "Unexpected keyword '%s' at start of extension rom - line %d\n",
-			iReader.Word(0), iReader.CurrentLine());
-	
-	iReader.CopyWord(1, iRomFileName);
-	Print(ELog, "\n========================================================\n");
-	Print(ELog, "Extension ROFS %s starting at line %d\n\n", iRomFileName, iReader.CurrentLine());
-
-
-	iReader.MarkNext();		// so that we rewind to the line after the extensionrom keyword
-
-	while (iReader.NextLine(1,keyword) != KErrEof)
-		{
-		if (keyword == EKeywordExtensionRofs)
-			break;
-			ProcessExtensionKeyword(keyword);
-		}
-
-	if (!GotExtensionVariables(aKernelRom))
-		return KErrGeneral;
-
-	// second pass to process the file specifications in the obey file building
-	// up the TRomNode directory structure and the TRomBuilderEntry list
-	//
-	iReader.Rewind();
-
-	//
-	if (aKernelRom==0)
-		return Print(EError, "Option to extend a kernel ROFS image not yet implemented\n");
-
-
-	
-	iRootDirectory = new TRomNode((TText*)"");
-	
-	iLastExecutable = 0;
-
-	(aKernelRom->RootDirectory())->deleteTheFirstNode();
-
-
-	iRootDirectory = aKernelRom->CopyDirectory(iLastExecutable);
-	aKernelRom->SetRootDirectory(iRootDirectory);
-
-
-	TInt align=0;
-	while (iReader.NextLine(2,keyword)!=KErrEof)
-		{
-		if (keyword == EKeywordExtensionRofs)
-			break;
-
-		switch (keyword)
-			{
-		case EKeywordHide:
-		case EKeywordAlias:
-		case EKeywordRename:
-			if (!ProcessRenaming(keyword))
-				return KErrGeneral;
-			break;
-
-		case EKeywordPatchDllData:
-		{	
-			// Collect patchdata statements to process at the end
-			StringVector patchDataTokens;
-			SplitPatchDataStatement(patchDataTokens); 
-			iPatchData->AddPatchDataStatement(patchDataTokens);									
-			break;
-		}
-		default:
-			if (!ProcessFile(align, keyword))
-				return KErrGeneral;
-			align=0;
-			break;
-			}
-		}
-
-	if(!ParsePatchDllData() )
-		return KErrGeneral;
-	
-	iReader.Mark();			// ready for processing the next extension rom(s)
-
-	if (iMissingFiles!=0)
-		return KErrGeneral;
-	if (iNumberOfFiles==0)
-		{
-		Print(EError, "No files specified.\n");
-		return KErrGeneral;
-		}
-	return KErrNone;
-	}
-
-
-
-
-void CObeyFile::ProcessExtensionKeyword(enum EKeyword aKeyword)
-	{
-	#ifdef __TOOLS2__
-	istringstream val(iReader.Word(1));
-	#else
-	istrstream val(iReader.Word(1),strlen(iReader.Word(1)));
-	#endif
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-	val >> setbase(0);
-#endif //__MSVCDOTNET__
-
-	switch (aKeyword)
-		{
-	case EKeywordCoreRofsName:
- 		iReader.CopyWord(1, iKernelRofsName);
-		return;
-	case EKeywordRofsSize:
-		val >> iRomSize;
-		return;
-	case EKeywordVersion:
-		val >> iVersion;
-		return;
-	case EKeywordRomChecksum:
-		val >> iCheckSum;
-		return;
-	case EKeywordTime:
-		iReader.ProcessTime(iTime);
-		return;
-	case EKeywordRofsAutoSize:
-		iAutoSize = ETrue;
-		val >> iAutoPageSize;
-		return;
-	default:
-		Print(EError,"Keyword '%s' not valid in extension ROFS - line %d\n", iReader.Word(0), iReader.CurrentLine());
-		break;
-		}
-	return;
-	}
-
-TBool CObeyFile::GotExtensionVariables(MRofsImage* aRom)
-//
-// Checks that the obeyfile has supplied enough variables to continue
-//
-   	{
-
-	TBool retVal=ETrue;
-  	TText* kernelRofsName = iKernelRofsName;
-
-	// Mandatory keywords
-
-	if (iRomSize==0)
-		{
-		Print(EAlways,"The size of the extension ROFS has not been supplied.\n");
-		Print(EAlways,"Use the keyword \"rofssize\".\n");
-		retVal = EFalse;
-		}
-
-	// keywords we need if we don't already have a ROFS image to work from
-
-	if (aRom==0)
-		{
-  		if (iKernelRofsName==0)
-			{
-			Print(EAlways,"The name of the core ROFS has not been supplied.\n");
-			Print(EAlways,"Use the keyword \"rofsname\".\n");
-			retVal = EFalse;
-			}
-		}
-	else
-		{
-		if (iKernelRofsName != 0)
-			{
-			Print(EWarning,"Keyword \"rofsname\" ignored.\n");
-			}
-		kernelRofsName = aRom->RomFileName();
-		}
-
-	// validation
-
-	// Apply defaults as necessary
-	if (iTime==0)
-		{
-		Print(ELog, "No timestamp specified. Using current time...\n");
-		ObeyFileReader::TimeNow(iTime);
-		}
-
-	// fix up "*" in rofsname
-	TText newname[256];
-	TText* p=newname;
-	TText* q=iRomFileName;
-	TText c;
-
-	while ((c=*q++)!='\0')
-		{
-		if (c!='*')
-			{
-			*p++=c;
-			continue;
-			}
-		TText *r=kernelRofsName;
-		while ((c=*r++)!='\0')
-			*p++=c;
-		}
-	*p = '\0';
-	free(iRomFileName);
-  	iRomFileName = (TText*)strdup((char*)newname);
-
-	Print(ELog, "\nCreating ROFS image %s\n", iRomFileName);
-
-	return retVal;
-	}
-
-// Fuction to split patchdata statement 
-void CObeyFile::SplitPatchDataStatement(StringVector& aPatchDataTokens)
-{
-	// Get the value of symbol size, address/ordinal and new value 
-	// to be patched from the patchdata statement.
-	// Syntax of patchdata statements is as follows:
-	// 1)	patchdata dll_name  ordinal OrdinalNumber size_in_bytes   new_value 
-	// 2)   patchdata dll_name  addr    Address       size_in_bytes   new_value
-	for(TInt count=1; count<=5; count++)
-	{
-		aPatchDataTokens.push_back(iReader.Word(count));
-	}
-
-	// Store the the value of current line which will be used
-	// when displaying error messages.
-	OutputStringStream outStrStream;
-	outStrStream<<iReader.CurrentLine();
-    aPatchDataTokens.push_back(outStrStream.str());
-}
-
-TBool CObeyFile::ParsePatchDllData()
-{
-	// Get the list of patchdata statements
-	VectorOfStringVector patchDataStatements=iPatchData->GetPatchDataStatements();
-	// Get the list of renamed file map
-	MapOfString RenamedFileMap=iPatchData->GetRenamedFileMap();
-
-	for(TUint count=0; count<patchDataStatements.size(); count++)
-	{
-		StringVector strVector = patchDataStatements.at(count);
-		String filename=strVector.at(0);
-		String lineNoStr = strVector.at(5);
-		TUint lineNo=getNumber(((TText*)lineNoStr.c_str()));
-		TRomNode* existingFile = NULL;
-		
-		do
-		{
-			TRomNode* dir=iRootDirectory;			
-			TBool endOfName=EFalse;
-
-			TText *epocStartPtr=IsValidFilePath((TText*)filename.c_str());
-			if (epocStartPtr==NULL)
-			{
-				Print(EError, "Invalid source path on line %d\n",lineNo);
-				return EFalse;
-			}
-			epocStartPtr = (TText*)NormaliseFileName((const char*)epocStartPtr);
-			TText *epocEndPtr=epocStartPtr;
-
-			while (!endOfName)
-			{
-				endOfName = GetNextBitOfFileName(&epocEndPtr);
-				if (endOfName) // file
-				{
-					existingFile=dir->FindInDirectory(epocStartPtr);
-					if (existingFile)
-					{
-						TInt fileCount=0;
-						TInt dirCount=0;
-						existingFile->CountDirectory(fileCount, dirCount);
-						if (dirCount != 0 || fileCount != 0)
-						{
-							Print(EError, "Keyword %s not applicable to directories - line %d\n","patchdata",lineNo);
-							return EFalse;
-						}
-					}
-				}
-				else // directory
-				{
-					TRomNode* subDir = dir->FindInDirectory(epocStartPtr);
-					if (!subDir) // sub directory does not exist
-						break;
-					dir=subDir;
-					epocStartPtr = epocEndPtr;
-				}
-			}
-
-			if(!existingFile)
-			{
-				// If the E32Image file to be patched is not included then check if the
-				// file was renamed.
-				MapOfStringIterator RenamedFileMapIterator;
-				if ((RenamedFileMapIterator=RenamedFileMap.find(filename)) != RenamedFileMap.end())
-					filename = (*RenamedFileMapIterator).second; 				
-				else
-				{
-					Print(EError, "File %s not found - line %d\n", filename.c_str(), lineNo);
-					return EFalse;
-				}
-			}
-		}while(!existingFile);
-
-		TUint32 aSize, aOrdinal, aNewValue, aOffset;
-		TLinAddr aDataAddr;
-
-		aOrdinal = (TUint32)-1;
-		aDataAddr = (TUint32)-1;
-		aOffset = 0;
-
-		String symbolSize=strVector.at(3);
-		aSize = getNumber((TText*)symbolSize.c_str());
-		String aValue=strVector.at(4);
-		aNewValue = getNumber((TText*)aValue.c_str());		
-
-		DllDataEntry *dataEntry = new DllDataEntry(aSize, aNewValue);
-
-		// Set the address of the data or the ordinal number specified in OBY statement.
-		String keyword=strVector.at(1);
-		String keywordValue=strVector.at(2);
-		
-		/* Check for +OFFSET at the end of the ordinal number or address */
-		TUint plus = keywordValue.find("+",0);
-		if (plus != std::string::npos)
-		{
-			/* Get the offset that we found after the + sign */
-			String offset = keywordValue.substr(plus+1);
-			aOffset = getNumber((TText*)offset.c_str());
-
-			keywordValue.resize(plus);		
-		}
-		if(stricmp (keyword.c_str(), "addr") == 0)
-			aDataAddr = getNumber((TText*)keywordValue.c_str());
-		
-		else 
-			 aOrdinal = getNumber((TText*)keywordValue.c_str());
-		
-		dataEntry->iDataAddress = aDataAddr;
-		dataEntry->iOrdinal = aOrdinal;
-		dataEntry->iOffset = aOffset;
-
-		existingFile->SetDllData();
-
-		DllDataEntry *aDllDataEntry= existingFile->iEntry->GetFirstDllDataEntry();
-		if (aDllDataEntry==NULL)
-		{
-			// Set the first node of the patchdata linked list
-			aDllDataEntry=dataEntry;
-			existingFile->iEntry->SetFirstDllDataEntry(aDllDataEntry);
-		}
-		else
-		{
-			// Goto the last node
-			while((aDllDataEntry->NextDllDataEntry()) != NULL)
-			{
-				aDllDataEntry = aDllDataEntry->NextDllDataEntry();
-			}
-			
-			// Add the new node at the end of linked list
-			aDllDataEntry->AddDllDataEntry(dataEntry);			
-		}
-	}
-	return ETrue;
-}
-
-
-
-
-
-
-
-
-
+/*
+* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent * @released
+* Rofsbuild Obey file class and its reader class.
+*
+*/
+ 
+#include <strstream>
+#include <iomanip>
+ 
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <time.h>
+#include <assert.h>
+#include <errno.h>
+
+#include <e32std.h>
+#include <e32std_private.h>
+#include <e32rom.h>
+#include <u32std.h>
+#include <f32file.h>
+
+#include "h_utl.h"
+#include "r_obey.h"
+#include "r_coreimage.h"
+#include "patchdataprocessor.h"
+#include "fatimagegenerator.h" 
+#include "r_driveimage.h"
+
+extern TInt gCodePagingOverride;
+extern TInt gDataPagingOverride;
+extern ECompression gCompress;
+extern TBool gEnableStdPathWarning; // Default to not warn if destination path provided for a file is not in standard path.
+extern TBool gKeepGoing;
+
+
+#define _P(word)	word, sizeof(word)-1	// match prefix, optionally followed by [HWVD]
+#define _K(word)	word, 0					// match whole word
+static char* const NullString = "" ;
+const ObeyFileKeyword ObeyFileReader::iKeywords[] =
+{
+	{_K("file"),		2,-2, EKeywordFile, "File to be copied into ROFS"},
+	{_K("data"),		2,-2, EKeywordData, "same as file"},
+	{_K("dir"),         2,1, EKeywordDir, "Directory to be created into FAT image"},
+
+	{_K("rofsname"),	1, 1, EKeywordRofsName, "output file for ROFS image"},
+	{_K("romsize"),		1, 1, EKeywordRomSize, "size of ROM image"}, 
+	{_P("hide"),	    2, -1, EKeywordHide, "Exclude named file from ROM directory structure"},
+	{_P("alias"),	    2, -2, EKeywordAlias, "Create alias for existing file in ROM directory structure"},
+	{_P("rename"),	    2, -2, EKeywordRename, "Change the name of a file in the ROM directory structure"},
+	{_K("rofssize"),		1, 1, EKeywordRofsSize, "maximum size of ROFS image"},
+	{_K("romchecksum"),	1, 1, EKeywordRofsChecksum, "desired 32-bit checksum value for the whole image"},
+	{_K("version"),		1, 1, EKeywordVersion, "ROFS image version number"},
+	{_K("time"),	    1,-1, EKeywordTime, "ROFS image timestamp"},
+	{_K("extensionrofs"),1+2, 1, EKeywordExtensionRofs, "Start of definition of optional Extension ROFS"},
+	{_K("extensionrofsname"),1, 1, EKeywordCoreRofsName, "ROFS image on which extension ROFS is based"},
+	{_K("rem"),			0, 0, EKeywordNone, "comment"},
+	{_K("stop"),		0, 0, EKeywordNone, "Terminates OBEY file prematurely"},
+	{_K("romchecksum"),	1, 1, EKeywordRomChecksum, "desired 32-bit checksum value for the whole ROFS image"},
+	{_K("coreimage"),	1, 1, EKeywordCoreImage, "Core image to be used for extension directory structure"},
+	{_K("autosize"),	1, 1, EKeywordRofsAutoSize, "Automatically adjust maximum image size to actual used"},
+	{_K("pagingoverride"),	1, 1, EKeywordPagingOverride, "Overide the demand paging attributes for every file in ROM, NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
+	{_K("codepagingoverride"),	1, 1, EKeywordCodePagingOverride, "Overide the code paging attributes for every file in ROM, NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
+	{_K("datapagingoverride"),	1, 1, EKeywordDataPagingOverride, "Overide the data paging attributes for every file in ROM, NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
+	{_K("dataimagename"),1, 1,EKeywordDataImageName, "Data Drive image file name"},
+	{_K("dataimagefilesystem"),1, 1,EKeywordDataImageFileSystem, "Drive image file system format"},
+	{_K("dataimagesize"),1, 1,EKeywordDataImageSize, "Maximum size of Data Drive image"},
+	{_K("volume"),1, -1,EKeywordDataImageVolume, "Volume Label of Data Drive image"},
+	{_K("sectorsize"),1, 1,EKeywordDataImageSectorSize, "Sector size(in bytes) of Data Drive image"},
+	{_K("fattable"),1, 1,EKeywordDataImageNoOfFats, "Number of FATs in the Data Drive image"},
+	// things we don't normally report in the help information
+	{_K("trace"),		1, 1, EKeywordTrace, "(ROMBUILD activity trace flags)"},
+	{_K("filecompress"),2, -2,EKeywordFileCompress,"Non-XIP Executable to be loaded into the ROM compressed" },
+	{_K("fileuncompress"),2, -2,EKeywordFileUncompress,"Non-XIP Executable to be loaded into the ROM uncompressed" },
+	{_K("patchdata"),2, 5,EKeywordPatchDllData, "Patch exported data"},
+	{_K("imagename"), 1, 1, EKeywordSmrImageName, "output file for SMR image"},
+	{_K("hcrdata"), 1, 1, EKeywordSmrFileData, "file data for HCR SMR image"},
+	{_K("formatversion"), 1, 1, EKeywordSmrFormatVersion, "format version for HCR SMR image"},
+	{_K("payloadflags"), 1, 1, EKeywordSmrFlags, "payload flags for the HCR SMR image"},
+	{_K("payloaduid"), 1, 1, EKeywordSmrUID, "payload UID for the HCR SMR image"},
+	{0,0,0,0,EKeywordNone,""}
+};
+
+void ObeyFileReader::KeywordHelp() { // static
+
+	cout << "Obey file keywords:\n";
+
+	const ObeyFileKeyword* k=0;
+	for (k=iKeywords; k->iKeyword!=0; k++)
+	{
+		if (k->iHelpText == 0)
+			continue;
+		if (k->iHelpText[0]=='(' && !H.iVerbose)
+			continue;	// don't normally report things in (parentheses)
+
+		char buf[32];
+		sprintf(buf, "%-20s", k->iKeyword);
+		if (k->iKeywordLength)
+			memcpy(buf+k->iKeywordLength,"[HWVD]",6);
+		if (H.iVerbose)
+			sprintf(buf+20,"%2d",k->iNumArgs);
+		cout << "    " << buf << " " << k->iHelpText << endl;
+	}
+	cout << endl;
+
+	cout << "File attributes:\n";
+
+	const FileAttributeKeyword* f=0;
+	for (f=iAttributeKeywords; f->iKeyword!=0; f++)
+	{
+		if (f->iHelpText == 0)
+			continue;
+		if (f->iHelpText[0]=='(' && !H.iVerbose)
+			continue;	// don't normally report things in (parentheses)
+
+		char buf[32];
+		sprintf(buf, "%-20s", f->iKeyword);
+		if (H.iVerbose)
+			sprintf(buf+20,"%2d",k->iNumArgs);
+		cout << "    " << buf << " " << f->iHelpText << endl;
+	}
+	cout << endl;
+}
+
+ObeyFileReader::ObeyFileReader(const char* aFileName):iCurrentLine(0),
+iFileName(aFileName),iNumWords(0),iLine(0),iMarkLine(0),iCurrentObeyStatement(0)	{  
+	for(TUint i = 0 ; i < KNumWords ; i++)
+		iWord[i] = NullString;
+	*iSuffix = 0 ; 
+}
+
+ObeyFileReader::~ObeyFileReader() {	  
+	if(iCurrentObeyStatement) {
+		delete []iCurrentObeyStatement;
+		iCurrentObeyStatement = 0 ;
+	}
+	if(iLine) {
+		delete []iLine; 
+		iLine = 0 ;
+	}
+}
+
+//
+// Open the file & return a status
+//
+TBool ObeyFileReader::Open() {     
+	ifstream ifs(iFileName.c_str(),ios_base::in + ios_base::binary);
+	if (!ifs.is_open()) {
+		Print(EError,"Cannot open obey file %s\n",iFileName.c_str());
+		return EFalse;
+	}
+	iLines.clear();
+	if(iLine){
+		delete []iLine;
+		iLine = 0 ;
+	}		
+	ifs.seekg(0,ios_base::end);
+	size_t length = ifs.tellg();
+	char* buffer = new char[length + 2];
+	if (0 == buffer) {
+		Print(EError,"Insufficent Memory to Continue.");	
+		ifs.close();
+		return EFalse;
+	}
+	ifs.seekg(0,ios_base::beg);
+	ifs.read(buffer,length);
+	size_t readcout = ifs.gcount() ;
+	if(readcout != length){ 	
+		Print(EError,"Cannot Read All of File.");	
+		delete []buffer ;
+		ifs.close();
+		return EFalse;
+	}
+	buffer[length] = '\n';
+	buffer[length + 1] = 0 ;
+	ifs.close();
+	char* lineStart = buffer ;
+	char* end = buffer + length ;
+	string line ;
+	size_t maxLengthOfLine = 0 ;
+	while(lineStart < end){
+		while(*lineStart == ' ' || *lineStart == '\t') //trimleft 
+			lineStart ++ ;		
+		char* lineEnd = lineStart ;	 
+		while(*lineEnd != '\r' && *lineEnd != '\n')
+			lineEnd ++ ;
+		if(strnicmp(lineStart,"REM",3) == 0){
+			line = "" ; // REMOVE "REM ... "
+		}
+		else {
+			TInt lastIndex = lineEnd - lineStart - 1;
+			while(lastIndex >= 0 &&  // trimright
+				(lineStart[lastIndex] == ' ' || lineStart[lastIndex] == '\t'))
+				lastIndex -- ;			
+			if(lastIndex >= 0)
+				line.assign(lineStart,lastIndex + 1);
+			else
+				line = "";
+		}
+		if(line.length() > maxLengthOfLine)
+			maxLengthOfLine = line.length();
+		iLines.push_back(line);
+		if(*lineEnd == '\r') {
+			if(lineEnd[1] == '\n')
+				lineStart = lineEnd + 2 ;
+			else
+				lineStart = lineEnd + 1 ;
+		}
+		else // '\n'
+			lineStart = lineEnd + 1 ;
+	}	
+	delete []buffer ;
+	iLine = new char[maxLengthOfLine + 1];
+	iCurrentObeyStatement = new char[maxLengthOfLine + 1];
+	*iCurrentObeyStatement = 0 ;
+	*iLine = 0 ;
+	iCurrentLine = 0 ;
+	iMarkLine = 0 ;
+	return ETrue;
+}
+
+void ObeyFileReader::Mark()	{ 
+	iMarkLine = iCurrentLine - 1;
+}
+
+void ObeyFileReader::MarkNext() { 
+	iMarkLine = iCurrentLine;
+}
+
+void ObeyFileReader::Rewind() {
+	iCurrentLine = iMarkLine;
+}
+
+char* ObeyFileReader::DupWord(TInt aIndex) const {
+	char* retVal = 0 ;
+	if(aIndex >= 0 && aIndex < (TInt)KNumWords){
+		size_t len = strlen(iWord[aIndex]) + 1;
+		retVal = new char[len];
+		if(retVal)
+			memcpy(retVal,iWord[aIndex],len);
+	} 
+	return retVal ;
+}
+
+TInt ObeyFileReader::ReadAndParseLine() {
+	if (iCurrentLine >= (TInt)iLines.size())
+		return KErrEof;
+	iCurrentLine++; 	
+	iNumWords = Parse();
+	return KErrNone;
+}
+
+TInt ObeyFileReader::NextLine(TInt aPass, enum EKeyword& aKeyword) {
+
+NextLine:
+	TInt err = ReadAndParseLine();
+	if (err == KErrEof)
+		return KErrEof;
+	if(iNumWords == 0)
+		goto NextLine;
+	if (stricmp(iWord[0], "stop")==0)
+		return KErrEof;
+
+	const ObeyFileKeyword* k=0;
+	for (k=iKeywords; k->iKeyword!=0; k++) {
+		if (k->iKeywordLength == 0) {
+			// Exact case-insensitive match on keyword
+			if (stricmp(iWord[0], k->iKeyword) != 0)
+				continue;
+			*iSuffix = 0;
+		}
+		else {
+			// Prefix match
+			if (strnicmp(iWord[0], k->iKeyword, k->iKeywordLength) != 0)
+				continue;
+			// Suffix must be empty, or a variant number in []
+			strncpy(iSuffix,iWord[0] + k->iKeywordLength,80);
+			if (*iSuffix != '\0' && *iSuffix != '[')
+				continue;
+		}
+		// found a match
+		if ((k->iPass & aPass) == 0)
+			goto NextLine;
+		if (k->iNumArgs>=0 && (1+k->iNumArgs != iNumWords)) {
+			Print(EError, "Incorrect number of arguments for keyword %s on line %d.\n",
+				iWord[0], iCurrentLine);
+			goto NextLine;
+		}
+		if (k->iNumArgs<0 && (1-k->iNumArgs > iNumWords)) {
+			Print(EError, "Too few arguments for keyword %s on line %d.\n",
+				iWord[0], iCurrentLine);
+			goto NextLine;
+		}
+
+		aKeyword = k->iKeywordEnum;
+		return KErrNone;
+	}
+	if (aPass == 1)
+		Print(EWarning, "Unknown keyword '%s'.  Line %d ignored\n", iWord[0], iCurrentLine);
+	goto NextLine;
+}
+
+//
+// splits a line into words, and returns the number of words found
+// 
+TInt ObeyFileReader::Parse() {
+
+	for (TUint i = 0; i < KNumWords; i++)
+		iWord[i] = NullString;
+
+	enum TState {EInWord, EInQuotedWord, EInGap};
+	TState state = EInGap;
+	const string& line = iLines[iCurrentLine - 1]; 	
+	size_t len = line.length();	
+	memcpy(iLine,line.c_str(),len);
+	memcpy(iCurrentObeyStatement,iLine,len);
+	iLine[len] = 0 ; 
+	iCurrentObeyStatement[len] = 0 ;
+	TUint i = 0;
+	char* linestr = iLine;
+	while (i < KNumWords && *linestr != 0) {	 
+		switch (state)
+		{
+		case EInGap:
+			if (*linestr =='\"') {
+				if (linestr[1] != 0 && linestr[1]!='\"')
+					iWord[i++] = linestr + 1;
+				state = EInQuotedWord;
+			}
+			else if (!IsGap(*linestr)) {
+				iWord[i++] = linestr;
+				state=EInWord;
+			}
+			else
+				*linestr=0;
+			break;
+		case EInWord:
+			if (*linestr == '\"') {
+				*linestr = 0;
+				if (linestr[1] != 0 && linestr[1] != '\"')
+					iWord[i++] = linestr+1;
+				state=EInQuotedWord;
+			}
+			else if (IsGap(*linestr)) {
+				*linestr=0;
+				state=EInGap;
+			}
+			break;
+		case EInQuotedWord:
+			if (*linestr == '\"'){
+				*linestr = 0;
+				state = EInGap;
+			}
+			break;
+		}
+		linestr++;
+	}
+	return i;
+}
+
+//
+// Process the timestamp
+//
+void ObeyFileReader::ProcessTime(TInt64& aTime) {
+	char timebuf[256];
+	if (iNumWords>2)
+		sprintf(timebuf, "%s_%s", iWord[1], iWord[2]);
+	else
+		strncpy(timebuf, iWord[1],256);
+
+	TInt r = StringToTime(aTime, timebuf);
+	if (r==KErrGeneral) {
+		Print(EError, "incorrect format for time keyword on line %d\n", iCurrentLine);
+		exit(0x670);
+	}
+	if (r==KErrArgument){
+		Print(EError, "Time out of range on line %d\n", iCurrentLine);
+		exit(0x670);
+	}
+}
+
+TInt64 ObeyFileReader::iTimeNow = 0;
+void ObeyFileReader::TimeNow(TInt64& aTime) {
+	if (iTimeNow==0) {
+		TInt sysTime = time(0);					// seconds since midnight Jan 1st, 1970
+		sysTime -= (30*365*24*60*60+7*24*60*60);	// seconds since midnight Jan 1st, 2000
+		TInt64 daysTo2000AD=730497;
+		TInt64 t=daysTo2000AD*24*3600+sysTime;	// seconds since 0000
+		t = t+3600;								// BST (?)
+		iTimeNow=t*1000000;						// milliseconds
+	}
+	aTime=iTimeNow;
+}
+
+ 
+
+// File attributes.
+
+
+const FileAttributeKeyword ObeyFileReader::iAttributeKeywords[] =
+{
+	{"attrib",3			,0,1,EAttributeAtt, "File attributes in ROM file system"},
+	{"exattrib",3		,0,1,EAttributeAttExtra, "File extra attributes in ROM file system"}, 
+	{"stack",3			,1,1,EAttributeStack, "?"},
+	{"fixed",3			,1,0,EAttributeFixed, "Relocate to a fixed address space"},
+	{"priority",3		,1,1,EAttributePriority, "Override process priority"},
+	{_K("uid1")			,1,1,EAttributeUid1, "Override first UID"},
+	{_K("uid2")			,1,1,EAttributeUid2, "Override second UID"},
+	{_K("uid3")			,1,1,EAttributeUid3, "Override third UID"},
+	{_K("heapmin")		,1,1,EAttributeHeapMin, "Override initial heap size"},
+	{_K("heapmax")		,1,1,EAttributeHeapMax, "Override maximum heap size"},
+	{_K("capability")	,1,1,EAttributeCapability, "Override capabilities"},
+	{_K("unpaged")		,1,0,EAttributeUnpaged, "Don't page code or data for this file"},
+	{_K("paged")		,1,0,EAttributePaged, "Page code and data for this file"},
+	{_K("unpagedcode")	,1,0,EAttributeUnpagedCode, "Don't page code for this file"},
+	{_K("pagedcode")	,1,0,EAttributePagedCode, "Page code for this file"},
+	{_K("unpageddata")	,1,0,EAttributeUnpagedData, "Don't page data for this file"},
+	{_K("pageddata")	,1,0,EAttributePagedData, "Page data for this file"},
+	{0,0,0,0,EAttributeAtt,0}
+};
+
+TInt ObeyFileReader::NextAttribute(TInt& aIndex, TInt aHasFile, enum EFileAttribute& aKeyword, char*& aArg)
+{
+NextAttribute:
+	if (aIndex >= iNumWords)
+		return KErrEof;
+	char* word=iWord[aIndex++];
+	const FileAttributeKeyword* k;
+	for (k=iAttributeKeywords; k->iKeyword!=0; k++)
+	{
+		if (k->iKeywordLength == 0)
+		{
+			// Exact match on keyword
+			if (stricmp(word, k->iKeyword) != 0)
+				continue;
+		}
+		else
+		{
+			// Prefix match
+			if (strnicmp(word, k->iKeyword, k->iKeywordLength) != 0)
+				continue;
+		}
+		// found a match
+		if (k->iNumArgs>0)
+		{
+			TInt argIndex = aIndex;
+			aIndex += k->iNumArgs;		// interface only really supports 1 argument
+			if (aIndex>iNumWords)
+			{
+				Print(EError, "Missing argument for attribute %s on line %d\n", word, iCurrentLine);
+				return KErrArgument;
+			}
+			aArg=iWord[argIndex];
+		}
+		if (k->iIsFileAttribute && !aHasFile)
+		{
+			Print(EError, "File attribute %s applied to non-file on line %d\n", word, iCurrentLine);
+			return KErrNotSupported;
+		}
+		aKeyword=k->iAttributeEnum;
+		return KErrNone;
+	}
+	Print(EWarning, "Unknown attribute '%s' skipped on line %d\n", word, iCurrentLine);
+	goto NextAttribute;
+}
+
+
+
+/**
+Constructor:
+1.Obey file instance.
+2.used by both rofs and datadrive image.
+
+@param aReader - obey file reader object.
+*/
+CObeyFile::CObeyFile(ObeyFileReader& aReader):
+iRomFileName(NULL),
+iExtensionRofsName(0),
+iKernelRofsName(0),
+iRomSize(0),
+iVersion(0,0,0),
+iCheckSum(0),
+iNumberOfFiles(0),
+iTime(0),
+iRootDirectory(0),
+iNumberOfDataFiles(0),
+iDriveFileName(0), 
+iDriveFileFormat(0), 
+iReader(aReader), 
+iMissingFiles(0), 
+iLastExecutable(0),
+iFirstFile(0), 	
+iCurrentFile(0),
+iAutoSize(EFalse),
+iAutoPageSize(4096),
+iPagingOverrideParsed(0),
+iCodePagingOverrideParsed(0),
+iDataPagingOverrideParsed(0),
+iPatchData(new CPatchDataProcessor)
+{
+	iNextFilePtrPtr = &iFirstFile ;
+}
+
+/**
+Obey file Destructor.
+1.Release the tree memory.
+2.Release all allocated memory if any.
+*/
+CObeyFile::~CObeyFile() {
+	if(iDriveFileName){
+		delete[] iDriveFileName;					
+		iDriveFileName = 0 ;
+	}
+	if(iDriveFileFormat) {
+		delete[] iDriveFileFormat;
+		iDriveFileFormat = 0 ;
+	}
+	iRootDirectory->deleteTheFirstNode();                
+	iRootDirectory->InitializeCount();
+
+	Release();
+	if(iRomFileName){ 
+		delete [] iRomFileName;
+		iRomFileName = 0 ;
+	}
+	if (iRootDirectory)
+		iRootDirectory->Destroy(); 
+	if(iPatchData)
+		delete iPatchData;
+}
+
+//
+// Free resources not needed after building a ROM
+//
+void CObeyFile::Release() {
+	iFirstFile = 0;
+	iNextFilePtrPtr = &iFirstFile;
+}
+
+TRomBuilderEntry *CObeyFile::FirstFile() {
+	iCurrentFile = iFirstFile;
+	return iCurrentFile;
+}
+
+TRomBuilderEntry *CObeyFile::NextFile() {
+	iCurrentFile = iCurrentFile ? iCurrentFile->iNext : 0;
+	return iCurrentFile;
+}
+
+char* CObeyFile::ProcessCoreImage() const {
+	// check for coreimage keyword and return filename	 
+	enum EKeyword keyword;
+	char* coreImageFileName = 0;
+	iReader.Rewind();
+	while (iReader.NextLine(1,keyword) != KErrEof) {
+		if (keyword == EKeywordCoreImage) {  			  
+			coreImageFileName = iReader.DupWord(1);	
+			iReader.MarkNext();
+			break;
+		}
+	}
+	return coreImageFileName;
+}
+
+void CObeyFile::SkipToExtension() {
+	iReader.Rewind();
+	enum EKeyword keyword;
+	while (iReader.NextLine(1,keyword) != KErrEof) {
+		if (keyword == EKeywordExtensionRofs) {
+			iReader.Mark(); // ready for processing extension
+			break;
+		}
+	}
+}
+
+TInt CObeyFile::ProcessRofs() {
+	
+	//
+	// First pass through the obey file to set up key variables
+	//
+
+	iReader.Rewind();
+
+	TInt count=0;
+	enum EKeyword keyword;
+	while (iReader.NextLine(1,keyword) != KErrEof) {
+		if (keyword == EKeywordExtensionRofs){
+			if (count==0)
+				return KErrNotFound;		// no core ROFS, just extension ROFSs.
+			break;
+		}
+
+		count++;
+		if (! ProcessKeyword(keyword))
+			return KErrGeneral;
+	}
+
+	if (!GotKeyVariables())
+		return KErrGeneral;
+
+	//
+	// second pass to process the file specifications in the obey file building
+	// up the TRomNode directory structure and the TRomBuilderEntry list
+	//
+	iReader.Rewind();
+
+	iRootDirectory = new TRomNode("");
+	iLastExecutable = iRootDirectory;
+
+	TInt align=0;
+	while (iReader.NextLine(2,keyword)!=KErrEof) {
+		if (keyword == EKeywordExtensionRofs)
+			break;
+
+		if (keyword == EKeywordHide)
+			keyword = EKeywordHideV2;
+
+		switch (keyword) 
+		{
+		case EKeywordHide:
+		case EKeywordAlias:
+		case EKeywordRename:
+			if (!ProcessRenaming(keyword))
+				return KErrGeneral;
+			break;
+		case EKeywordPatchDllData:
+			{
+				// Collect patchdata statements to process at the end
+				StringVector patchDataTokens;
+				SplitPatchDataStatement(patchDataTokens); 
+				iPatchData->AddPatchDataStatement(patchDataTokens);									
+				break;
+			}
+		default:
+			if (!ProcessFile(align, keyword))
+				return KErrGeneral;
+			align=0;
+			break;
+		}
+	}
+
+	if(!ParsePatchDllData())
+		return KErrGeneral;
+	iReader.Mark();			// ready for processing the extension rom(s)
+
+	if (iMissingFiles!=0) {
+		return KErrGeneral;
+	}
+	if ( 0 == iNumberOfFiles ){
+		Print(EError, "No files specified.\n");
+		return KErrGeneral;
+	}
+
+	return KErrNone;
+}
+
+TBool CObeyFile::Process() {
+	TBool result = ETrue;
+	iReader.Rewind();
+	enum EKeyword keyword;
+	while(iReader.NextLine(1, keyword) != KErrEof){
+		string key = iReader.Word(0);
+		string value = iReader.Word(1);
+		if(iKeyValues.find(key) != iKeyValues.end()){
+			iKeyValues[key].push_back(value);
+		}
+		else {
+			StringVector values;
+			values.push_back(value);
+			iKeyValues[key]=values;
+		}
+
+
+	}
+	return result;
+}
+StringVector CObeyFile::getValues(const string& aKey) {
+	StringVector values;
+	if(iKeyValues.find(aKey) != iKeyValues.end()){
+		values = iKeyValues[aKey];
+	}
+	return values;
+}
+
+/**
+Process drive obey file and construct the tree.
+
+@return - Return the status,
+'KErrnone' for Success,
+'KErrGeneral' for failure (required keywords not there in obey file or failed
+to construct the tree).
+*/
+TInt CObeyFile::ProcessDataDrive() {
+	iReader.Rewind();
+	enum EKeyword keyword;
+
+	// First pass through the obey file to set up key variables
+	while (iReader.NextLine(1,keyword) != KErrEof) {
+		if (!ProcessDriveKeyword(keyword))			
+			return KErrGeneral;
+	}
+
+	if (!GotKeyDriveVariables())
+		return KErrGeneral;
+
+	// Second pass to process the file specifications in the obey file.
+	// Build the TRomNode directory structure and the TRomBuilderEntry list
+	iReader.Rewind();
+	iRootDirectory = new TRomNode("//");					
+	iLastExecutable = iRootDirectory;
+
+	while(iReader.NextLine(2,keyword)!=KErrEof) {
+		switch (keyword) 
+		{
+		case EKeywordPatchDllData:
+			{	// Collect patchdata statements to process at the end
+				StringVector patchDataTokens;
+				SplitPatchDataStatement(patchDataTokens); 				
+				iPatchData->AddPatchDataStatement(patchDataTokens);									
+				break;
+			}
+
+		case EKeywordHide:						
+		case EKeywordFile:
+		case EKeywordDir:
+		case EKeywordData:
+		case EKeywordFileCompress:
+		case EKeywordFileUncompress:
+			if (!ProcessDriveFile(keyword))
+				return KErrGeneral;
+			break;
+
+		default:							
+			break;
+		}
+	}
+
+	if(!ParsePatchDllData())
+		return KErrGeneral;
+	if (iMissingFiles) {
+		Print(EError, "Source Files Missing.\n");
+		return KErrGeneral;
+	}
+	if (!iNumberOfFiles)
+		Print(EWarning,"No files specified.\n");
+
+	return KErrNone;
+}
+
+
+/**
+Process and stores the keyword information.
+
+@param aKeyword - keyword to update its value to variables.
+@return - Return the status i.e Success,
+*/
+TBool CObeyFile::ProcessDriveKeyword(enum EKeyword aKeyword) {
+
+	TBool success = ETrue;
+	switch (aKeyword)
+	{
+	case EKeywordDataImageName:
+		iDriveFileName = iReader.DupWord(1);
+		break;
+	case EKeywordDataImageFileSystem:
+		iDriveFileFormat = iReader.DupWord(1);
+		break;
+	case EKeywordDataImageSize:
+		{
+			const char* bigString = iReader.Word(1);
+			if(*bigString == '\0')
+			{
+				Print(EWarning,"Not a valid Image Size. Default size is considered\n");		
+				break;
+			}
+ 
+			Val(iConfigurableFatAttributes.iImageSize,bigString); 
+		}
+		break;
+	case EKeywordDataImageVolume:
+		{				
+			// Get the volume label provided by using "volume" keyword.
+			// e.g. vlolume = NO NAME
+			string volumeLabel = iReader.GetCurrentObeyStatement();
+			string volumeLabelKeyword = "volume";
+
+			TUint position = volumeLabel.find(volumeLabelKeyword.c_str(),0,volumeLabelKeyword.size());
+			position += volumeLabelKeyword.size();
+			if (volumeLabel.find('=',position) != string::npos) {
+				position=volumeLabel.find('=',position);
+				++position;
+			}								
+
+			position = volumeLabel.find_first_not_of(' ',position);
+			if (position != string::npos) {
+				volumeLabel = volumeLabel.substr(position);
+
+				// Remove the new line character from the end
+				position = volumeLabel.find_first_of("\r\n");
+				if (position != string::npos)
+					volumeLabel = volumeLabel.substr(0,position);
+				size_t length = volumeLabel.length() ;
+				if(length > 11) 
+						length = 11 ;
+				memcpy(iConfigurableFatAttributes.iDriveVolumeLabel,volumeLabel.c_str(),length) ;
+				while(length != 11)
+					iConfigurableFatAttributes.iDriveVolumeLabel[length++] = ' ';
+				iConfigurableFatAttributes.iDriveVolumeLabel[length] = 0;
+			}
+			else {
+				Print(EWarning,"Value for Volume Label is not provided. Default value is considered.\n");
+			}
+			break;
+		}
+	case EKeywordDataImageSectorSize:
+		{
+			const char* bigString = iReader.Word(1);
+			TInt sectorSize = atoi(bigString);
+			if(sectorSize <= 0)	{
+				Print(EWarning,"Invalid Sector Size value. Default value is considered.\n");
+			}
+			else {
+				iConfigurableFatAttributes.iDriveSectorSize = atoi(bigString);
+			}
+		}			
+		break;
+	case EKeywordDataImageNoOfFats:
+		{
+			const char* bigString = iReader.Word(1);
+			TInt noOfFats = atoi(bigString);
+			if (noOfFats <=0)
+				Print(EWarning,"Invalid No of FATs specified. Default value is considered.\n");
+			else
+				iConfigurableFatAttributes.iDriveNoOfFATs = atoi(bigString);			
+		}			
+		break;			
+	default:
+		// unexpected keyword iReader.Word(0), keep going.
+		break;
+	}
+	return success;
+}
+
+
+/**
+Checks whether obeyfile has supplied enough variables to continue.
+
+@return - Return the status 
+ETrue - Supplied valid values,
+EFalse- Not valied values.
+*/
+TBool CObeyFile::GotKeyDriveVariables() {
+
+	TBool retVal=ETrue;
+
+	// Mandatory keywords
+	if (iDriveFileName==0) {                                                  
+		Print(EError,"The name of the image file has not been supplied.\n");
+		Print(EError,"Use the keyword \"dataimagename\".\n");
+		retVal = EFalse;
+	}
+	// Check for '-'ve entered value.
+	if(iConfigurableFatAttributes.iImageSize <= 0){
+		Print(EWarning,"Image Size should be positive. Default size is Considered.\n");
+	}
+
+	// File system format.
+	if(iDriveFileFormat==0) {
+		Print(EError,"The name of the file system not been supplied.\n");
+		Print(EError,"Use the keyword \"dataimagefilesystem\".\n");
+		retVal = EFalse;
+	}
+
+	// Checking the validity of file system format.
+	if(iDriveFileFormat){		 
+		if(stricmp(iDriveFileFormat,"FAT16") && stricmp(iDriveFileFormat,"FAT32")) {
+			Print(EError,"The name of the file system not supported : %s\n",iDriveFileFormat);
+			retVal = EFalse;
+		}
+	}
+	if(retVal)
+		Print(ELog,"\nCreating Data Drive image : %s\n", iDriveFileName);
+
+	return retVal;
+}
+
+/**
+Process a parsed line to set up one or more new TRomBuilder entry objects.
+
+@param  - obey file keyword.
+// iWord[0] = the keyword (file,)      
+// iWord[1] = the PC pathname
+// iWord[2] = the EPOC pathname
+// iWord[3] = start of the file attributes
+
+@return - Return the status 
+ETrue - Successful generation of tree.
+EFalse- Fail to generate the tree.
+*/
+TBool CObeyFile::ProcessDriveFile(enum EKeyword aKeyword) {
+
+	TBool isPeFile = ETrue;
+	TBool aFileCompressOption, aFileUncompressOption;
+
+	TInt epocPathStart=2;
+	aFileCompressOption = aFileUncompressOption = EFalse;
+	// do some validation of the keyword
+	TInt currentLine = iReader.CurrentLine();
+
+	switch (aKeyword)
+	{
+	case EKeywordData:
+	case EKeywordDir:
+	case EKeywordHide:
+		isPeFile = EFalse;
+		break;
+
+	case EKeywordFile:
+		break;
+
+	case EKeywordFileCompress:
+		aFileCompressOption = ETrue;
+		break;
+
+	case EKeywordFileUncompress:
+		aFileUncompressOption = ETrue;
+		break;
+
+	default:
+		return EFalse;
+	}
+
+	if (aKeyword!=EKeywordHide && aKeyword!=EKeywordDir) {
+		// check the PC file exists
+		char* nname = NormaliseFileName(iReader.Word(1));		  
+		ifstream test(nname);
+		if(!test.is_open()){
+			Print(EError,"Cannot open file %s for input.\n",iReader.Word(1));
+			iMissingFiles++;
+		}
+		test.close();
+		delete []nname ;												
+		 
+	}
+	else
+		epocPathStart=1;   
+
+	if(aKeyword != EKeywordDir)
+		iNumberOfFiles++;
+
+	TBool endOfName=EFalse;
+	const char *epocStartPtr;
+	if(aKeyword != EKeywordDir)
+		epocStartPtr = IsValidFilePath(iReader.Word(epocPathStart));
+	else
+		epocStartPtr = IsValidDirPath(iReader.Word(epocPathStart));
+	char *epocEndPtr = const_cast<char*>(epocStartPtr);
+
+	if (epocStartPtr == NULL) {
+		Print(EError, "Invalid destination path on line %d\n",currentLine);
+		return EFalse;
+	}
+
+	TRomNode* dir=iRootDirectory;
+	TRomNode* subDir=0;
+	TRomBuilderEntry *file=0;      
+
+	while (!endOfName) {
+		endOfName = GetNextBitOfFileName(epocEndPtr);      
+		if (endOfName && (aKeyword!=EKeywordDir)) { // file
+			TRomNode* alreadyExists=dir->FindInDirectory(epocStartPtr);
+			if ((aKeyword != EKeywordHide) && alreadyExists) { // duplicate file		
+				if (gKeepGoing) {
+					Print(EWarning, "Duplicate file for %s on line %d, will be ignored\n",iReader.Word(1),iReader.CurrentLine());
+					iNumberOfFiles--;
+					return ETrue;
+				}
+				else {	
+					Print(EError, "Duplicate file for %s on line %d\n",iReader.Word(1),iReader.CurrentLine());
+					return EFalse;
+				}
+			}
+			else if((aKeyword == EKeywordHide) && (alreadyExists)) { 
+				alreadyExists->iEntry->iHidden = ETrue;
+				alreadyExists->iHidden = ETrue;
+				return ETrue;
+			}
+			else if((aKeyword == EKeywordHide) && (!alreadyExists)) {
+				Print(EWarning, "Hiding non-existent file %s on line %d\n",iReader.Word(1),iReader.CurrentLine());
+				return ETrue;
+			}
+
+			file = new TRomBuilderEntry(iReader.Word(1), epocStartPtr);                   
+			file->iExecutable=isPeFile;
+			if( aFileCompressOption ) {
+				file->iCompressEnabled = ECompressionCompress;
+			}
+			else if(aFileUncompressOption )	{
+				file->iCompressEnabled = ECompressionUncompress;
+			}
+
+			TRomNode* node=new TRomNode(epocStartPtr, file);
+			if (node==0)
+				return EFalse;
+
+			TInt r=ParseFileAttributes(node, file, aKeyword);         
+			if (r!=KErrNone)
+				return EFalse;
+
+			if(gCompress != ECompressionUnknown) {
+				node->iFileUpdate = ETrue;
+			}
+
+			if((node->iOverride) || (aFileCompressOption) || (aFileUncompressOption)) {
+				node->iFileUpdate = ETrue;
+			}
+
+			dir->AddFile(node);	// to drive directory structure.
+		}		 
+		else {
+			// directory
+			//for directory creation, given /sys/bin/, it's possible to reach 0 at the end, just ignore that...
+			if(!*epocStartPtr)
+				break;
+
+			subDir = dir->FindInDirectory(epocStartPtr);      
+			if (!subDir){ // sub directory does not exist			
+				if(aKeyword==EKeywordHide) {
+					Print(EWarning, "Hiding non-existent file %s on line %d\n",
+						iReader.Word(1),iReader.CurrentLine());
+					return ETrue;
+				}
+				subDir = dir->NewSubDir(epocStartPtr);
+				if (!subDir)
+					return EFalse;
+			}
+			dir=subDir;
+			epocStartPtr = epocEndPtr;
+		}  // end of else.
+	}
+	return ETrue;
+}
+
+
+TInt CObeyFile::SetStackSize(TRomNode *aNode, const char* aStr) {
+	if (EFalse == IsValidNumber(aStr))
+		return Print(EError, "Number required as argument for keyword 'stack'.\n"); 
+	TInt size ;
+	TInt err = Val(size,aStr);
+	if(KErrNone == err){
+		aNode->SetStackSize(size );
+	}
+	return err;
+}
+
+TInt CObeyFile::SetHeapSizeMin(TRomNode *aNode, const char* aStr) {
+	if (EFalse == IsValidNumber(aStr))
+		return Print(EError, "Number required as argument for keyword 'heapmin'.\n");
+	TInt size ;
+	TInt err = Val(size,aStr);
+	if(KErrNone == err){
+		aNode->SetHeapSizeMin(size );
+	}
+	return err;	 
+}
+
+TInt CObeyFile::SetHeapSizeMax(TRomNode *aNode, const char* aStr) {
+	if (EFalse == IsValidNumber(aStr))
+		return Print(EError, "Number required as argument for keyword 'heapmax'.\n");
+	TInt size ;
+	TInt err = Val(size,aStr);
+	if(KErrNone == err){
+		aNode->SetHeapSizeMax(size );
+	}
+	return err;	
+	 
+}
+
+TInt CObeyFile::SetCapability(TRomNode *aNode, const char* aStr) {
+	if ( IsValidNumber(aStr)){
+		Print(EDiagnostic,"Old style numeric CAPABILTY specification ignored.\n");
+		return KErrNone;
+	}
+	SCapabilitySet cap;
+	TInt r = ParseCapabilitiesArg(cap, (char*)aStr);
+	if( KErrNone == r ) {
+		aNode->SetCapability( cap );
+	}
+	return r;
+}
+
+TInt CObeyFile::SetPriority(TRomNode *aNode, const char* aStr) {
+	TProcessPriority priority;	
+	
+	if ( IsValidNumber(aStr)) {
+		TUint32 temp = 0;
+		Val(temp,aStr) ;
+		priority = (TProcessPriority)temp ; 
+	}
+	else {	 
+		if (stricmp(aStr, "low")==0)
+			priority=EPriorityLow;
+		else if (strnicmp(aStr, "background", 4)==0)
+			priority=EPriorityBackground;
+		else if (strnicmp(aStr, "foreground", 4)==0)
+			priority=EPriorityForeground;
+		else if (stricmp(aStr, "high")==0)
+			priority=EPriorityHigh;
+		else if (strnicmp(aStr, "windowserver",3)==0)
+			priority=EPriorityWindowServer;
+		else if (strnicmp(aStr, "fileserver",4)==0)
+			priority=EPriorityFileServer;
+		else if (strnicmp(aStr, "realtimeserver",4)==0)
+			priority=EPriorityRealTimeServer;
+		else if (strnicmp(aStr, "supervisor",3)==0)
+			priority=EPrioritySupervisor;
+		else
+			return Print(EError, "Unrecognised priority keyword.\n");
+	}
+	if (priority<EPriorityLow || priority>EPrioritySupervisor)
+		return Print(EError, "Priority out of range.\n");
+
+	aNode->SetPriority( priority );
+	return KErrNone;
+}
+
+TInt CObeyFile::SetUid1(TRomNode *aNode, const char* aStr){
+	if (EFalse == IsValidNumber(aStr))
+		return Print(EError, "Number required as argument for keyword 'uid1'.\n");
+	TInt size ;
+	TInt err = Val(size,aStr);
+	if(KErrNone == err){
+		aNode->SetUid1(size );
+	}
+	return err;		 
+}
+TInt CObeyFile::SetUid2(TRomNode *aNode, const char* aStr) {
+	if (EFalse == IsValidNumber(aStr))
+		return Print(EError, "Number required as argument for keyword 'uid2'.\n");
+	TInt size ;
+	TInt err = Val(size,aStr);
+	if(KErrNone == err){
+		aNode->SetUid2(size );
+	}
+	return err;	
+}
+TInt CObeyFile::SetUid3(TRomNode *aNode, const char* aStr) {
+	if (EFalse == IsValidNumber(aStr))
+		return Print(EError, "Number required as argument for keyword 'uid3'.\n");
+	TInt size ;
+	TInt err = Val(size,aStr);
+	if(KErrNone == err){
+		aNode->SetUid3(size );
+	}
+	return err;	
+}
+
+//
+// Process any inline keywords
+//
+TInt CObeyFile::ParseFileAttributes(TRomNode *aNode, TRomBuilderEntry* aFile, enum EKeyword aKeyword) {
+	TInt currentLine = iReader.CurrentLine();
+	enum EFileAttribute attribute;
+	TInt r=KErrNone;
+	TInt index=3;
+	char* arg=0;
+
+	while(r==KErrNone) {
+		r=iReader.NextAttribute(index,(aFile!=0),attribute,arg);
+		if (r!=KErrNone)
+			break;
+		switch(attribute)
+		{
+		case EAttributeAtt:
+			r=aNode->SetAtt(arg);
+			break;
+		case EAttributeAttExtra:
+			r=aNode->SetAttExtra(arg, aFile, aKeyword);
+			break;
+		case EAttributeStack:
+			r=SetStackSize(aNode, arg);
+			break;
+		case EAttributeFixed:
+			aNode->SetFixed();
+			r = KErrNone;
+			break;
+		case EAttributeUid1:
+			r=SetUid1(aNode, arg);
+			break;
+		case EAttributeUid2:
+			r=SetUid2(aNode, arg);
+			break;
+		case EAttributeUid3:
+			r=SetUid3(aNode, arg);
+			break;
+		case EAttributeHeapMin:
+			r=SetHeapSizeMin(aNode, arg);
+			break;
+		case EAttributeHeapMax:
+			r=SetHeapSizeMax(aNode, arg);
+			break;
+		case EAttributePriority:
+			r=SetPriority(aNode, arg);
+			break;
+		case EAttributeCapability:
+			r=SetCapability(aNode, arg);
+			break;
+		case EAttributeUnpaged:
+			aNode->iOverride |= KOverrideCodeUnpaged|KOverrideDataUnpaged;
+			aNode->iOverride &= ~(KOverrideCodePaged|KOverrideDataPaged);
+			break;
+		case EAttributePaged:
+			aNode->iOverride |= KOverrideCodePaged;
+			aNode->iOverride &= ~(KOverrideCodeUnpaged);
+			break;
+		case EAttributeUnpagedCode:
+			aNode->iOverride |= KOverrideCodeUnpaged;
+			aNode->iOverride &= ~KOverrideCodePaged;
+			break;
+		case EAttributePagedCode:
+			aNode->iOverride |= KOverrideCodePaged;
+			aNode->iOverride &= ~KOverrideCodeUnpaged;
+			break;
+		case EAttributeUnpagedData:
+			aNode->iOverride |= KOverrideDataUnpaged;
+			aNode->iOverride &= ~KOverrideDataPaged;
+			break;
+		case EAttributePagedData:
+			aNode->iOverride |= KOverrideDataPaged;
+			aNode->iOverride &= ~KOverrideDataUnpaged;
+			break;
+		default:
+			return Print(EError, "Unrecognised keyword in file attributes on line %d.\n",currentLine);
+		}
+	}
+
+	if (r==KErrEof)
+		return KErrNone;
+	return r;
+}
+
+//
+// Process a parsed line to set up one or more new TRomBuilder entry objects.
+// iWord[0] = the keyword (file, primary or secondary)
+// iWord[1] = the PC pathname
+// iWord[2] = the EPOC pathname
+// iWord[3] = start of the file attributes
+//
+TBool CObeyFile::ProcessFile(TInt /*aAlign*/, enum EKeyword aKeyword){
+
+	TBool isPeFile = ETrue;
+	TBool aFileCompressOption, aFileUncompressOption;
+	TInt epocPathStart=2;
+	aFileCompressOption = aFileUncompressOption = EFalse;
+	TBool warnFlag = EFalse;
+	static const char aStdPath[] = "SYS\\BIN\\";
+	static const int sysBinLength = sizeof(aStdPath)-1;
+
+	// do some validation of the keyword
+	TInt currentLine = iReader.CurrentLine();
+	switch (aKeyword)
+	{
+	case EKeywordData:
+	case EKeywordHideV2:
+		iNumberOfDataFiles++;
+		isPeFile = EFalse;
+		break;
+
+	case EKeywordFile:
+		warnFlag = gEnableStdPathWarning;
+		break;
+	case EKeywordFileCompress:
+		aFileCompressOption = ETrue;
+		warnFlag = gEnableStdPathWarning;
+		break;
+	case EKeywordFileUncompress:
+		aFileUncompressOption = ETrue;
+		warnFlag = gEnableStdPathWarning;
+		break;
+
+	default:
+		Print(EError,"Unexpected keyword '%s' on line %d.\n",iReader.Word(0),currentLine);
+		return EFalse;
+	}
+
+	if (aKeyword!=EKeywordHideV2) {
+
+		// check the PC file exists
+		char* nname = NormaliseFileName(iReader.Word(1)); 
+		ifstream test(nname);
+		if (!test) {
+			Print(EError,"Cannot open file %s for input.\n",iReader.Word(1));
+			iMissingFiles++;
+		}
+		test.close();
+		delete []nname;
+	}
+	else
+		epocPathStart=1;
+
+	iNumberOfFiles++;
+
+
+	TBool endOfName=EFalse;
+	const char *epocStartPtr=IsValidFilePath(iReader.Word(epocPathStart));
+	char *epocEndPtr=const_cast<char*>(epocStartPtr);
+	if (epocStartPtr==NULL) {
+		Print(EError, "Invalid destination path on line %d\n",currentLine);
+		return EFalse;
+	}
+	if(warnFlag){	// Check for the std destination path(for executables) as per platsec.	
+		if(strnicmp(aStdPath,epocStartPtr,sysBinLength) != 0) {
+			Print(EWarning,"Invalid destination path on line %d. \"%s\" \n",currentLine,epocStartPtr);
+		}
+	}
+
+	TRomNode* dir=iRootDirectory;
+	TRomNode* subDir=0;
+	TRomBuilderEntry *file=0;
+	while (!endOfName) {
+		endOfName = GetNextBitOfFileName(epocEndPtr);
+		if (endOfName) {// file		
+			TRomNode* alreadyExists=dir->FindInDirectory(epocStartPtr);
+			/*
+			* The EKeywordHideV2 keyword is used to indicate that:
+			*	1. if the file exists in the same image and then hidden, mark it hidden
+			*	2. if the file exists in another image, but in this (ROFS) image, it is
+			*		required to hide that file, create a 0 length file entry setting the 'hide'
+			*		flag so that at runtime, file gets hidden in the composite filesystem.
+			*/
+			if ((aKeyword != EKeywordHideV2) && alreadyExists){ // duplicate file		
+				if(gKeepGoing){	
+					Print(EWarning, "Duplicate file for %s on line %d, will be ignored\n",iReader.Word(1),iReader.CurrentLine());
+					switch (aKeyword)
+					{
+					case EKeywordData:
+					case EKeywordHideV2:
+						iNumberOfDataFiles--;
+					default:
+						break;
+					}
+					iNumberOfFiles--;	 	
+					return ETrue;
+				}
+				else {					
+					Print(EError, "Duplicate file for %s on line %d\n",iReader.Word(1),iReader.CurrentLine());
+					return EFalse;
+				}
+			}
+
+			TBool aHidden = aKeyword==EKeywordHideV2;
+			/* The file is only marked hidden and hence the source file name isn't known 
+			* here as hide statement says :
+			*	hide <filename as in ROM>
+			* Therefore, create TRomBuilderEntry with iFileName as 0 for hidden file when
+			* the file doesn't exist in the same ROM image. Otherwise, the src file name
+			* is known because of alreadyExists (which comes from the 'file'/'data' statement).
+			*/
+			if(aHidden)
+				file = new TRomBuilderEntry(0, epocStartPtr);
+			else
+				file = new TRomBuilderEntry(iReader.Word(1), epocStartPtr);
+			file->iExecutable=isPeFile;
+			file->iHidden= aHidden;
+			if( aFileCompressOption ){
+				file->iCompressEnabled = ECompressionCompress;
+			}
+			else if(aFileUncompressOption )	{
+				file->iCompressEnabled = ECompressionUncompress;
+			}
+			TRomNode* node=new TRomNode(epocStartPtr, file);
+			if (node==0)
+				return EFalse;
+			TInt r=ParseFileAttributes(node, file, aKeyword);
+			if (r!=KErrNone)
+				return EFalse;
+
+			dir->AddFile(node);	// to ROFS directory structure
+			AddFile(file);		// to our list of files
+		}		 
+		else { // directory		
+			subDir = dir->FindInDirectory(epocStartPtr);
+			if (!subDir) { // sub directory does not exist			
+				subDir = dir->NewSubDir(epocStartPtr);
+				if (!subDir)
+					return EFalse;
+			}
+			dir=subDir;
+			epocStartPtr = epocEndPtr;
+		}
+	}
+	return ETrue;
+}
+
+
+TBool CObeyFile::ProcessRenaming(enum EKeyword aKeyword) {
+
+	// find existing file
+	TBool endOfName=EFalse;
+	const char *epocStartPtr=IsValidFilePath(iReader.Word(1));
+
+	// Store the current name and new name to maintain renamed file map
+	string currentName=iReader.Word(1);
+	string newName=iReader.Word(2);
+
+	char *epocEndPtr= const_cast<char*>(epocStartPtr);
+	if (epocStartPtr == NULL) {
+		Print(EError, "Invalid source path on line %d\n",iReader.CurrentLine());
+		return EFalse;
+	}
+
+	char saved_srcname[257];
+	strncpy(saved_srcname, iReader.Word(1),257);
+
+	TRomNode* dir=iRootDirectory;
+	TRomNode* existingFile=0;
+	while (!endOfName){
+		endOfName = GetNextBitOfFileName(epocEndPtr);
+		if (endOfName) { // file
+			existingFile=dir->FindInDirectory(epocStartPtr);
+			if (existingFile) {
+				TInt fileCount=0;
+				TInt dirCount=0;
+				existingFile->CountDirectory(fileCount, dirCount);
+				if (dirCount != 0 || fileCount != 0) {
+					Print(EError, "Keyword %s not applicable to directories - line %d\n",
+						iReader.Word(0),iReader.CurrentLine());
+					return EFalse;
+				}
+			}
+		}
+		else { // directory		
+			TRomNode* subDir = dir->FindInDirectory(epocStartPtr);
+			if (!subDir) // sub directory does not exist
+				break;
+			dir=subDir;
+			epocStartPtr = epocEndPtr;
+		}
+	}
+	if (aKeyword == EKeywordHide) {
+		/*
+		* The EKeywordHide keyword is used to indicate that if the file exists in 
+		* the primary ROFS image and then hidden in extension ROFS, mark it hidden.
+		*/
+		if (!existingFile) {
+			Print(EWarning, "Hiding non-existent file %s on line %d\n", 
+				saved_srcname, iReader.CurrentLine());
+			// Just a warning, as we've achieved the right overall effect.
+		}
+		else if (existingFile->iFileStartOffset==(TUint)KFileHidden){
+			Print(EWarning, "Hiding already hidden file %s on line %d\n", 
+				saved_srcname, iReader.CurrentLine());
+			// We will igrore this request, otherwise it will "undelete" it.
+		}
+		else {
+			//hidden files will not be placed to the image
+			existingFile->iHidden = ETrue;
+		}
+		return ETrue;
+	}
+
+	if (!existingFile) {
+		Print(EError, "Can't %s non-existent source file %s on line %d\n",
+			iReader.Word(0), saved_srcname, iReader.CurrentLine());
+		return EFalse;
+	}
+
+	epocStartPtr = IsValidFilePath(iReader.Word(2));
+	epocEndPtr = const_cast<char*>(epocStartPtr);
+	endOfName = EFalse;
+	if (epocStartPtr == NULL) {
+		Print(EError, "Invalid destination path on line %d\n",iReader.CurrentLine());
+		return EFalse;
+	}
+
+	TRomNode* newdir=iRootDirectory;
+	while (!endOfName) {
+		endOfName = GetNextBitOfFileName(epocEndPtr);
+		if (endOfName) {// file		
+			TRomNode* alreadyExists=newdir->FindInDirectory(epocStartPtr);
+			if (alreadyExists && !(alreadyExists->iHidden)) {// duplicate file	
+				if(gKeepGoing){
+					Print(EWarning, "Duplicate file for %s on line %d, renaming will be skipped\n",saved_srcname,iReader.CurrentLine());
+					return ETrue;
+				}
+				else {							
+					Print(EError, "Duplicate file for %s on line %d\n",saved_srcname,iReader.CurrentLine());
+					return EFalse;
+				}
+			}
+		}
+		else { // directory		
+			TRomNode* subDir = newdir->FindInDirectory(epocStartPtr);
+			if (!subDir) {// sub directory does not exist			
+				subDir = newdir->NewSubDir(epocStartPtr);
+				if (!subDir)
+					return EFalse;
+			}
+			newdir=subDir;
+			epocStartPtr = epocEndPtr;
+		}
+	}
+
+	if (aKeyword == EKeywordRename) {
+		// rename => remove existingFile and insert into tree at new place
+		// has no effect on the iNextExecutable or iNextNodeForSameFile links
+		TInt r=ParseFileAttributes(existingFile, existingFile->iEntry, aKeyword);
+		if (r!=KErrNone)
+			return EFalse;
+		existingFile->Rename(dir, newdir, epocStartPtr);
+		// Store the current and new name of file in the renamed file map.
+		iPatchData->AddToRenamedFileMap(currentName, newName);
+		return ETrue;
+	}
+
+	// alias => create new TRomNode entry and insert into tree
+	TRomNode* node = new TRomNode(epocStartPtr, 0);
+	if (node == 0) {
+		Print(EError, "Out of memory\n");
+		return EFalse;
+	}
+	node->Alias(existingFile);
+	TInt r=ParseFileAttributes(node, 0, aKeyword);
+	if (r!=KErrNone)
+		return EFalse;
+	newdir->AddFile(node);	// to ROFS directory structure, though possibly hidden
+	return ETrue;
+}
+
+TInt ParsePagingPolicy(const char* policy){
+	if(stricmp(policy,"NOPAGING") == 0)
+		return EKernelConfigPagingPolicyNoPaging;
+	else if (stricmp(policy,"ALWAYSPAGE") == 0)
+		return EKernelConfigPagingPolicyAlwaysPage;
+	else if(stricmp(policy,"DEFAULTUNPAGED") == 0)
+		return EKernelConfigPagingPolicyDefaultUnpaged;
+	else if(stricmp(policy,"DEFAULTPAGED") == 0)
+		return EKernelConfigPagingPolicyDefaultPaged;
+	return KErrArgument;
+}
+
+TBool CObeyFile::ProcessKeyword(enum EKeyword aKeyword) { 
+
+	TBool success = ETrue;
+	switch (aKeyword)
+	{
+	case EKeywordRofsName:
+		iRomFileName = iReader.DupWord(1);
+		break;
+	case EKeywordRofsSize:
+		Val(iRomSize,iReader.Word(1));
+		break;
+	case EKeywordVersion:
+		{
+			istringstream val(iReader.Word(1)); 
+			val >> iVersion;
+		}
+		break;
+	case EKeywordRofsChecksum:
+		Val(iCheckSum,iReader.Word(1));
+		break;
+	case EKeywordTime:
+		iReader.ProcessTime(iTime);
+		break;
+	case EKeywordPagingOverride:
+		{
+			if(iPagingOverrideParsed)
+				Print(EWarning, "PagingOverride redefined - previous PagingOverride values lost\n");
+			if(iCodePagingOverrideParsed)
+				Print(EWarning, "PagingOverride defined - previous CodePagingOverride values lost\n");
+			iPagingOverrideParsed = true;
+			TInt policy = ParsePagingPolicy(iReader.Word(1));
+			if(policy < 0) {
+				Print(EError,"Unrecognized option for PAGINGOVERRIDE keyword\n");
+				success = false;
+			}
+			else {
+				gCodePagingOverride = policy;
+				if((policy == EKernelConfigPagingPolicyNoPaging) || (policy == EKernelConfigPagingPolicyDefaultUnpaged))
+					gDataPagingOverride = policy;
+			}
+		}
+		break;
+	case EKeywordCodePagingOverride:
+		{
+			if(iCodePagingOverrideParsed)
+				Print(EWarning, "CodePagingOverride redefined - previous CodePagingOverride values lost\n");
+			if(iPagingOverrideParsed)
+				Print(EWarning, "CodePagingOverride defined - previous PagingOverride values lost\n");
+			iCodePagingOverrideParsed = true;
+			TInt policy = ParsePagingPolicy(iReader.Word(1));
+			if(policy<0)
+			{
+				Print(EError,"Unrecognized option for CODEPAGINGOVERRIDE keyword\n");
+				success = false;
+			}
+			else
+				gCodePagingOverride = policy;
+		}
+		break;
+	case EKeywordDataPagingOverride:
+		{
+			if(iDataPagingOverrideParsed)
+				Print(EWarning, "DataPagingOverride redefined - previous DataPagingOverride values lost\n");
+/*			if(iPagingOverrideParsed){
+				Print(EError, "DataPagingOverride defined - previous PagingOverride values lost\n");
+				success = false;
+				break;
+			}
+*/
+			iDataPagingOverrideParsed = true;
+			TInt policy = ParsePagingPolicy(iReader.Word(1));
+			if(policy < 0) {
+				Print(EError,"Unrecognized option for DATAPAGINGOVERRIDE keyword\n");
+				success = false;
+			}
+			else
+				gDataPagingOverride = policy;
+		}
+		break;
+	case EKeywordRofsAutoSize:
+		iAutoSize = ETrue;
+		Val(iAutoPageSize,iReader.Word(1));
+		break;
+	default:
+		// unexpected keyword iReader.Word(0)
+		break;
+	}
+
+	return success;
+}
+//
+// Checks that the obeyfile has supplied enough variables to continue
+//
+TBool CObeyFile::GotKeyVariables() {
+
+	TBool retVal=ETrue;
+	// Mandatory keywords
+	if (iRomFileName == 0) {
+		Print(EAlways,"The name of the image file has not been supplied.\n");
+		Print(EAlways,"Use the keyword \"rofsname\".\n");
+		retVal = EFalse;
+	}
+	if (iRomSize == 0) {
+		Print(EAlways,"The size of the image has not been supplied.\n");
+		Print(EAlways,"Use the keyword \"rofssize\".\n");
+		retVal = EFalse;
+	}
+	// Apply defaults as necessary
+	if (iTime == 0)	{
+		Print(ELog, "No timestamp specified. Using current time...\n");
+		ObeyFileReader::TimeNow(iTime);
+	}
+	Print(ELog, "\nCreating Rofs image %s\n", iRomFileName);
+	return retVal;
+}
+
+//
+// Check the path is valid
+//
+const char* CObeyFile::IsValidFilePath(const char* aPath) {
+	// skip leading "\"
+	if (*aPath == '/' || *aPath == '\\')
+		aPath++;
+	if (*aPath == 0)
+		return NULL; // file ends in a backslash
+
+	const char *p = aPath;
+	TInt len=0;
+	while(*p) {			
+		if (*p == '/' || *p == '\\') {
+			if (len == 0)
+				return NULL;
+			len=0;
+			p++;
+			continue;
+
+		}
+		len++;
+		p++;
+	}
+	return (len ? aPath : NULL);
+}
+
+const char* CObeyFile::IsValidDirPath(const char* aPath)
+{
+	const char* walker = aPath;
+
+	//validate path...
+	while(*walker)
+	{
+		if(((*walker=='/') || (*walker=='\\')) && ((*(walker+1)=='/') || (*(walker+1)=='\\')))
+			return (const char*)0;
+		walker++;
+	}
+
+	if((*aPath=='/') || (*aPath=='\\'))
+		aPath++;
+
+	return aPath;
+}
+
+//
+// Move the end pointer past the next directory separator, replacing it with 0
+//
+TBool CObeyFile::GetNextBitOfFileName(char*& epocEndPtr) {
+	while (*epocEndPtr != '/' && *epocEndPtr != '\\'){ // until reach the directory separator		
+		if (*epocEndPtr == 0) // if reach end of string, return TRUE, it's the filename
+			return ETrue;
+		epocEndPtr++;
+	}
+	*epocEndPtr = 0; // overwrite the directory separator with a 0
+	epocEndPtr++; // point past the 0 ready for the next one
+	return EFalse;
+}
+
+void CObeyFile::AddFile(TRomBuilderEntry* aFile) {
+	*iNextFilePtrPtr = aFile;
+	iNextFilePtrPtr = &(aFile->iNext);
+}
+
+//
+// First pass through the obey file to set up key variables
+//
+TInt CObeyFile::ProcessExtensionRofs(MRofsImage* aKernelRom) { 
+	
+	iReader.Rewind();
+	enum EKeyword keyword;
+
+	// Deal with the "extensionrofs" keyword, which should be first
+	// however, you may've found "time" before it.
+	while(iReader.NextLine(1,keyword) != KErrEof) {
+		if(EKeywordExtensionRofs == keyword)
+			break ;		
+	}
+	if(EKeywordExtensionRofs != keyword) return KErrEof;
+	iRomFileName = iReader.DupWord(1);
+	Print(ELog, "\n========================================================\n");
+	Print(ELog, "Extension ROFS %s starting at line %d\n\n", iRomFileName, iReader.CurrentLine());
+
+	iReader.MarkNext();		// so that we rewind to the line after the extensionrom keyword
+
+	while (iReader.NextLine(1,keyword) != KErrEof) {
+		if (keyword == EKeywordExtensionRofs)
+			break;
+		ProcessExtensionKeyword(keyword);
+	}
+
+	if (!GotExtensionVariables(aKernelRom))
+		return KErrGeneral;
+
+	// second pass to process the file specifications in the obey file building
+	// up the TRomNode directory structure and the TRomBuilderEntry list
+	//
+	iReader.Rewind();
+
+	//
+	if (aKernelRom == 0)
+		return Print(EError, "Option to extend a kernel ROFS image not yet implemented\n");
+
+	iRootDirectory = new TRomNode("");
+
+	iLastExecutable = 0;
+
+	(aKernelRom->RootDirectory())->deleteTheFirstNode();
+
+
+	iRootDirectory = aKernelRom->CopyDirectory(iLastExecutable);
+	aKernelRom->SetRootDirectory(iRootDirectory);
+
+
+	TInt align=0;
+	while (iReader.NextLine(2,keyword)!=KErrEof) {
+		if (keyword == EKeywordExtensionRofs)
+			break;
+
+		switch (keyword)
+		{
+		case EKeywordHide:
+		case EKeywordAlias:
+		case EKeywordRename:
+			if (!ProcessRenaming(keyword))
+				return KErrGeneral;
+			break;
+
+		case EKeywordPatchDllData:
+			{	
+				// Collect patchdata statements to process at the end
+				StringVector patchDataTokens;
+				SplitPatchDataStatement(patchDataTokens); 
+				iPatchData->AddPatchDataStatement(patchDataTokens);									
+				break;
+			}
+		default:
+			if (!ProcessFile(align, keyword))
+				return KErrGeneral;			
+			align=0;
+			break;
+		}
+	}
+	
+	if(!ParsePatchDllData() )
+		return KErrGeneral;
+
+	iReader.MarkNext();			// ready for processing the next extension rom(s)
+
+	if (iMissingFiles!=0)
+		return KErrGeneral;
+	if (iNumberOfFiles == 0) {
+		Print(EError, "No files specified.\n");
+		return KErrGeneral;
+	}
+	return KErrNone;
+}
+void CObeyFile::ProcessExtensionKeyword(enum EKeyword aKeyword)	{ 
+
+	switch (aKeyword)
+	{
+	case EKeywordCoreRofsName:
+		iKernelRofsName = iReader.DupWord(1);
+		return;
+	case EKeywordRofsSize:
+		Val(iRomSize,iReader.Word(1));
+		return;
+	case EKeywordVersion:
+		{
+			istringstream val(iReader.Word(1)); 
+			val >> iVersion;
+		}
+		return;
+	case EKeywordRomChecksum:
+		Val(iCheckSum,iReader.Word(1)); //--
+		return;
+	case EKeywordTime:
+		iReader.ProcessTime(iTime);
+		return;
+	case EKeywordRofsAutoSize:
+		iAutoSize = ETrue;
+		Val(iAutoPageSize , iReader.Word(1)); 
+		return;
+	default:
+		Print(EError,"Keyword '%s' not valid in extension ROFS - line %d\n", iReader.Word(0), iReader.CurrentLine());
+		break;
+	}
+	return;
+}
+//
+// Checks that the obeyfile has supplied enough variables to continue
+//
+TBool CObeyFile::GotExtensionVariables(MRofsImage* aRom) {
+
+	TBool retVal=ETrue;
+	const char* kernelRofsName = iKernelRofsName;
+
+	// Mandatory keywords
+
+	if (iRomSize == 0){
+		Print(EAlways,"The size of the extension ROFS has not been supplied.\n");
+		Print(EAlways,"Use the keyword \"rofssize\".\n");
+		retVal = EFalse;
+	}
+
+	// keywords we need if we don't already have a ROFS image to work from
+	if (aRom == 0) {
+		if (iKernelRofsName == 0) {
+			Print(EAlways,"The name of the core ROFS has not been supplied.\n");
+			Print(EAlways,"Use the keyword \"rofsname\".\n");
+			retVal = EFalse;
+		}
+	}
+	else {
+		if (iKernelRofsName != 0){
+			Print(EWarning,"Keyword \"rofsname\" ignored.\n");
+		}
+		kernelRofsName = aRom->RomFileName();
+	}
+
+	// validation
+	// Apply defaults as necessary
+	if (iTime == 0)	{
+		Print(ELog, "No timestamp specified. Using current time...\n");
+		ObeyFileReader::TimeNow(iTime);
+	}
+
+	// fix up "*" in rofsname
+	char newname[256];
+	char* p=newname;
+	char* q=iRomFileName;
+	char c;
+
+	while ((c=*q++)!='\0'){
+		if (c!='*') {
+			*p++=c;
+			continue;
+		}
+		const char *r = kernelRofsName;
+		while ((c=*r++)!='\0')
+			*p++=c;
+	}
+	*p++ = '\0';
+	delete []iRomFileName;
+	size_t len = p - newname ;
+	iRomFileName = new char[len];
+	memcpy(iRomFileName,newname,len);
+	Print(ELog, "\nCreating ROFS image %s\n", iRomFileName);
+	return retVal;
+}
+
+// Fuction to split patchdata statement 
+void CObeyFile::SplitPatchDataStatement(StringVector& aPatchDataTokens) {
+	// Get the value of symbol size, address/ordinal and new value 
+	// to be patched from the patchdata statement.
+	// Syntax of patchdata statements is as follows:
+	// 1)	patchdata dll_name  ordinal OrdinalNumber size_in_bytes   new_value 
+	// 2)   patchdata dll_name  addr    Address       size_in_bytes   new_value
+	for(TInt count=1; count<=5; count++) {
+		aPatchDataTokens.push_back(iReader.Word(count));
+	}
+
+	// Store the the value of current line which will be used
+	// when displaying error messages.
+	ostringstream outStrStream;
+	outStrStream<<iReader.CurrentLine();
+	aPatchDataTokens.push_back(outStrStream.str());
+}
+
+TBool CObeyFile::ParsePatchDllData() {
+	// Get the list of patchdata statements
+	VectorOfStringVector patchDataStatements=iPatchData->GetPatchDataStatements();
+	// Get the list of renamed file map
+	MapOfString RenamedFileMap=iPatchData->GetRenamedFileMap();
+
+	for(TUint count=0; count < patchDataStatements.size(); count++) {
+		
+		StringVector strVector = patchDataStatements.at(count);
+		string filename=strVector.at(0);
+		string lineNoStr = strVector.at(5);
+		TUint lineNo = 0 ;
+		Val(lineNo,lineNoStr.c_str());
+		TRomNode* existingFile = NULL;
+
+		do {
+			TRomNode* dir=iRootDirectory;			
+			TBool endOfName=EFalse; 
+			
+			if (!IsValidFilePath(filename.c_str())) {
+				Print(EError, "Invalid source path on line %d\n",lineNo);
+				return EFalse;
+			}
+			char* epocStartPtr =NormaliseFileName(filename.c_str());
+			char* savedPtr = epocStartPtr;
+			if(*epocStartPtr == '/' ||*epocStartPtr == '\\')
+				epocStartPtr++ ;
+			char* epocEndPtr = epocStartPtr;
+
+			while (!endOfName) {
+				endOfName = GetNextBitOfFileName(epocEndPtr);
+				if (endOfName) {// file				
+					existingFile=dir->FindInDirectory(epocStartPtr);
+					if (existingFile) {
+						TInt fileCount=0;
+						TInt dirCount=0;
+						existingFile->CountDirectory(fileCount, dirCount);
+						if (dirCount != 0 || fileCount != 0) {
+							Print(EError, "Keyword %s not applicable to directories - line %d\n","patchdata",lineNo);
+							return EFalse;
+						}
+					}
+				}
+				else {// directory				
+					TRomNode* subDir = dir->FindInDirectory(epocStartPtr);
+					if (!subDir) // sub directory does not exist
+						break;
+					dir=subDir;
+					epocStartPtr = epocEndPtr;
+				}
+			}
+			delete []savedPtr;
+
+			if(!existingFile) {
+				// If the E32Image file to be patched is not included then check if the
+				// file was renamed.
+				MapOfStringIterator RenamedFileMapIterator;
+				if ((RenamedFileMapIterator=RenamedFileMap.find(filename)) != RenamedFileMap.end())
+					filename = (*RenamedFileMapIterator).second; 				
+				else {
+					Print(EError, "File %s not found - line %d\n", filename.c_str(), lineNo);
+					return EFalse;
+				}
+			}
+		}while(!existingFile);
+
+		TUint32 aSize, aOrdinal, aNewValue, aOffset;
+		TLinAddr aDataAddr;
+
+		aOrdinal = (TUint32)-1;
+		aDataAddr = (TUint32)-1;
+		aOffset = 0;
+
+		string symbolSize=strVector.at(3);
+		Val(aSize,symbolSize.c_str());
+		string aValue=strVector.at(4);
+		Val(aNewValue,aValue.c_str());		
+
+		DllDataEntry *dataEntry = new DllDataEntry(aSize, aNewValue);
+
+		// Set the address of the data or the ordinal number specified in OBY statement.
+		string keyword=strVector.at(1);
+		string keywordValue=strVector.at(2);
+
+		/* Check for +OFFSET at the end of the ordinal number or address */
+		TUint plus = keywordValue.find("+",0);
+		if (plus != string::npos) {
+			/* Get the offset that we found after the + sign */
+			string offset = keywordValue.substr(plus+1);
+			Val(aOffset,offset.c_str());
+
+			keywordValue.resize(plus);		
+		}
+		if(stricmp (keyword.c_str(), "addr") == 0)
+			Val(aDataAddr,keywordValue.c_str());
+
+		else 
+			Val(aOrdinal,keywordValue.c_str());
+
+		dataEntry->iDataAddress = aDataAddr;
+		dataEntry->iOrdinal = aOrdinal;
+		dataEntry->iOffset = aOffset;
+
+		existingFile->SetDllData();
+
+		DllDataEntry *aDllDataEntry= existingFile->iEntry->GetFirstDllDataEntry();
+		if (aDllDataEntry == NULL) {
+			// Set the first node of the patchdata linked list
+			aDllDataEntry=dataEntry;
+			existingFile->iEntry->SetFirstDllDataEntry(aDllDataEntry);
+		}
+		else {
+			// Goto the last node
+			while((aDllDataEntry->NextDllDataEntry()) != NULL) {
+				aDllDataEntry = aDllDataEntry->NextDllDataEntry();
+			}
+			// Add the new node at the end of linked list
+			aDllDataEntry->AddDllDataEntry(dataEntry);			
+		}
+	}
+	return ETrue;
+}
--- a/imgtools/romtools/rofsbuild/r_obey.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rofsbuild/r_obey.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,284 +1,270 @@
-/*
-* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent * @released
-* OBY file reader and processing class Definition.
-*
-*/
-
-
-#ifndef __R_OBEY_H__
-#define __R_OBEY_H__
-
-#define __REFERENCE_CAPABILITY_NAMES__
-
-#ifdef _MSC_VER
-#pragma warning(disable:4503)
-#endif
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-#include <fstream>
-#else
-#include <fstream.h>
-#endif
-
-#include <stdio.h>
-#include <e32capability.h>
-
-#ifdef _L
-#undef _L
-#endif
-
-#include <vector>
-#include <map>
-#include <kernel/kernboot.h>
-
-//
-const TUint32 KNumWords=16;
-//
-const TInt KDefaultRomSize=0x400000;
-const TInt KDefaultRomAlign=0x10;
-//
-
-typedef std::string String;
-typedef std::vector<String> StringVector;
-typedef std::map<String, StringVector> KeywordMap;
-
-enum EKeyword
-{
-	EKeywordNone=0,	// backwards compatibility, but now ignored
-	EKeywordFile,
-	EKeywordData,
-	EKeywordRofsName,
-	EKeywordExtensionRofs, 
-	EKeywordCoreRofsName,
-	EKeywordRomSize,
-	EKeywordAlias,
-	EKeywordHide,
-	EKeywordRename,
-	EKeywordRofsSize,
-	EKeywordRofsChecksum,
-	EKeywordVersion,
-	EKeywordTime,
-	EKeywordRomChecksum,
-	EKeywordTrace,
-	EKeywordCoreImage,
-	EKeywordRofsAutoSize,
-	EKeywordFileCompress,
-	EKeywordFileUncompress,
-	EKeywordHideV2,
-	EKeywordPatchDllData,
-	EKeywordPagingOverride,
-	EKeywordCodePagingOverride,
-	EKeywordDataPagingOverride,
-	// Added to support data drive images.
-	EKeywordDataImageName,    
-	EKeywordDataImageFileSystem, 
-	EKeywordDataImageSize,
-	EKeywordDataImageVolume,
-	EKeywordDataImageSectorSize,
-	EKeywordDataImageNoOfFats,
-	EKeywordSmrImageName,
-	EKeywordSmrFileData,
-	EKeywordSmrFormatVersion,
-	EKeywordSmrFlags,
-	EKeywordSmrUID
-
-};
-
-enum EFileAttribute {
-	EAttributeAtt,
-	EAttributeAttExtra,
-//	EAttributeCompress,
-	EAttributeStack,
-	EAttributeFixed,
-	EAttributePriority,
-	EAttributeUid1,
-	EAttributeUid2,
-	EAttributeUid3,
-	EAttributeHeapMin,
-	EAttributeHeapMax,
-	EAttributeCapability,
-	EAttributeUnpaged,
-	EAttributePaged,
-	EAttributeUnpagedCode,
-	EAttributePagedCode,
-	EAttributeUnpagedData,
-	EAttributePagedData,
-	};
-
-#include "r_romnode.h"
-#include "r_rofs.h"
-
-class MRofsImage;
-
-struct ObeyFileKeyword
-	{
-	const char* iKeyword;
-	size_t iKeywordLength;
-	TInt iPass;
-	TInt iNumArgs;		// -ve means >= number
-	enum EKeyword iKeywordEnum;
-	const char* iHelpText;
-	};
-
-struct FileAttributeKeyword
-	{
-	const char* iKeyword;
-	size_t iKeywordLength;
-	TInt iIsFileAttribute;
-	TInt iNumArgs;
-	enum EFileAttribute iAttributeEnum;
-	const char* iHelpText;
-	};
-
-class ObeyFileReader
-	{
-public:
-	ObeyFileReader(TText *aFileName);
-	~ObeyFileReader();
-
-	static void KeywordHelp();
-
-	TBool Open();
-	void Mark();
-	void MarkNext();
-	void Rewind();
-
-	TInt NextLine(TInt aPass, enum EKeyword& aKeyword);
-	TInt NextAttribute(TInt& aIndex, TInt aHasFile, enum EFileAttribute& aKeyword, TText*& aArg);
-
-	void CopyWord(TInt aIndex, TText*& aString);				// allocate copy of nth word
-	TInt Count() { return iNumWords;}				// number of words on current line
-	char* Word(TInt aIndex) { return (char*)iWord[aIndex]; }	// return nth word as char*
-	TText* Text(TInt aIndex) { return iWord[aIndex]; }			// return nth word as TText*
-	char* Suffix() { return (char*)iSuffix; }			// return unmatched suffix of word[0]
-	TInt CurrentLine() { return iCurrentLine;}				// number of words on current line
-	TText* GetCurrentObeyStatement() const;						// return current obey statement
-
-	void ProcessTime(TInt64& aTime);
-
-	static void TimeNow(TInt64& aTime);
-private:
-	TInt ReadAndParseLine();
-	TInt SetLineLengthBuffer();
-	TInt Parse();
-	inline TBool IsGap(char ch);
-
-	static const ObeyFileKeyword iKeywords[];
-	static const FileAttributeKeyword iAttributeKeywords[];
-	static TInt64 iTimeNow;
-
-private:
-	FILE* iObeyFile;
-	long iMark;
-	TInt iMarkLine;
-	long iCurrentMark;
-	TInt iCurrentLine;
-	TInt imaxLength;
-	TText* iFileName;
-	TInt iNumWords;
-	TText* iWord[KNumWords];
-	TText* iSuffix;
-	TText* iLine;
-	TText* iCurrentObeyStatement;
-	};
-
-class CPatchDataProcessor;
-struct ConfigurableFatAttributes;
-
-class CObeyFile
-	{
-public:
-	TText *iRomFileName;
-	TText *iExtensionRofsName;
-	TText *iKernelRofsName;
-	TInt iRomSize;
-	TVersion iVersion;
-	TUint32 iCheckSum;
-	TInt iNumberOfFiles;
-	TInt64 iTime;
-	TRomNode* iRootDirectory;
-	TInt iNumberOfDataFiles;
-	// Added to support Data Drive Images.
-	TText* iDriveFileName;
-	TInt64 iDataSize;
-	TText* iDriveFileFormat;
-	ConfigurableFatAttributes* iConfigurableFatAttributes;
-
-private:
-	ObeyFileReader& iReader;
-	TInt iMissingFiles;
-	TRomNode* iLastExecutable;
-
-	TRomBuilderEntry* iFirstFile;
-	TRomBuilderEntry** iNextFilePtrPtr;
-	TRomBuilderEntry* iCurrentFile;
-	KeywordMap iKeyValues;
-
-public:
-	CObeyFile(ObeyFileReader& aReader);
-	~CObeyFile();
-	void Release();
-	TInt ProcessRofs();
-	TInt ProcessExtensionRofs(MRofsImage* info);
-	TInt ProcessDataDrive();		//	Process the data drive obey file.
-	TRomBuilderEntry *FirstFile();
-	TRomBuilderEntry *NextFile();
-	TText* ProcessCoreImage();
-	void SkipToExtension();
-	TBool AutoSize();
-	TUint32 AutoPageSize();
-	TBool Process();
-	StringVector getValues(const String& aKey);
-
-private:
-	TBool ProcessFile(TInt aAlign, enum EKeyword aKeyword);
-	TBool ProcessDriveFile(enum EKeyword aKeyword);               
-	TBool ProcessRenaming(enum EKeyword aKeyword);
-	TBool ProcessKeyword(enum EKeyword aKeyword);
-	TBool ProcessDriveKeyword(enum EKeyword aKeyword);
-	void ProcessExtensionKeyword(enum EKeyword aKeyword);
-	TInt ParseFileAttributes(TRomNode* aNode, TRomBuilderEntry* aFile, enum EKeyword aKeyword);
-	TInt ParseSection();
-	TBool ParsePatchDllData();
-	TBool GotKeyVariables();
-	TBool GotKeyDriveVariables();			// To check the data drive mandatory variables. 
-	TBool GotExtensionVariables(MRofsImage* aRom);
-	TBool GetNextBitOfFileName(TText **epocEndPtr);
-	TText *IsValidFilePath(TText *aPath);
-	void AddFile(TRomBuilderEntry* aFile);
-
-	TInt SetStackSize(TRomNode* aNode, TText *aStr);
-	TInt SetHeapSizeMin(TRomNode* aNode, TText *aStr);
-	TInt SetHeapSizeMax(TRomNode* aNode, TText *aStr);
-	TInt SetCapability(TRomNode* aNode, TText *aStr);
-	TInt SetUid1(TRomNode* aNode, TText *aStr);
-	TInt SetUid2(TRomNode* aNode, TText *aStr);
-	TInt SetUid3(TRomNode* aNode, TText *aStr);
-	TInt SetPriority(TRomNode* aNode, TText *aStr);
-
-	TBool iAutoSize;
-	TUint32 iAutoPageSize;
-	TBool iPagingOverrideParsed;
-	TBool iCodePagingOverrideParsed;
-	TBool iDataPagingOverrideParsed;
-
-public:
-	CPatchDataProcessor* iPatchData;	
-	void SplitPatchDataStatement(StringVector& aPatchDataTokens);	
-	};
-
-
-#endif
+/*
+* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* @internalComponent * @released
+* OBY file reader and processing class Definition.
+*
+*/
+
+
+#ifndef __R_OBEY_H__
+#define __R_OBEY_H__
+
+#define __REFERENCE_CAPABILITY_NAMES__
+
+#include <stdio.h>
+#include <e32capability.h>
+#include <kernel/kernboot.h>
+#include "fatdefines.h"
+
+#include <vector>
+#include <map>
+#include <fstream>
+
+using namespace std;
+//
+const TUint32 KNumWords=16;
+//
+const TInt KDefaultRomSize=0x400000;
+const TInt KDefaultRomAlign=0x10;
+//
+typedef vector<string> StringVector ;
+typedef map<string, StringVector> KeywordMap;
+
+enum EKeyword
+{
+	EKeywordNone=0,	// backwards compatibility, but now ignored
+	EKeywordFile,
+	EKeywordData,
+	EKeywordDir,
+	EKeywordRofsName,
+	EKeywordExtensionRofs, 
+	EKeywordCoreRofsName,
+	EKeywordRomSize,
+	EKeywordAlias,
+	EKeywordHide,
+	EKeywordRename,
+	EKeywordRofsSize,
+	EKeywordRofsChecksum,
+	EKeywordVersion,
+	EKeywordTime,
+	EKeywordRomChecksum,
+	EKeywordTrace,
+	EKeywordCoreImage,
+	EKeywordRofsAutoSize,
+	EKeywordFileCompress,
+	EKeywordFileUncompress,
+	EKeywordHideV2,
+	EKeywordPatchDllData,
+	EKeywordPagingOverride,
+	EKeywordCodePagingOverride,
+	EKeywordDataPagingOverride,
+	// Added to support data drive images.
+	EKeywordDataImageName,    
+	EKeywordDataImageFileSystem, 
+	EKeywordDataImageSize,
+	EKeywordDataImageVolume,
+	EKeywordDataImageSectorSize,
+	EKeywordDataImageNoOfFats,
+	EKeywordSmrImageName,
+	EKeywordSmrFileData,
+	EKeywordSmrFormatVersion,
+	EKeywordSmrFlags,
+	EKeywordSmrUID
+
+};
+
+enum EFileAttribute {
+	EAttributeAtt,
+	EAttributeAttExtra,
+//	EAttributeCompress,
+	EAttributeStack,
+	EAttributeFixed,
+	EAttributePriority,
+	EAttributeUid1,
+	EAttributeUid2,
+	EAttributeUid3,
+	EAttributeHeapMin,
+	EAttributeHeapMax,
+	EAttributeCapability,
+	EAttributeUnpaged,
+	EAttributePaged,
+	EAttributeUnpagedCode,
+	EAttributePagedCode,
+	EAttributeUnpagedData,
+	EAttributePagedData,
+	};
+
+#include "r_romnode.h"
+#include "r_rofs.h"
+
+class MRofsImage;
+ 
+struct ObeyFileKeyword
+	{
+	const char* iKeyword;
+	size_t iKeywordLength;
+	TInt iPass;
+	TInt iNumArgs;		// -ve means >= number
+	enum EKeyword iKeywordEnum;
+	const char* iHelpText;
+	};
+
+struct FileAttributeKeyword
+	{
+	const char* iKeyword;
+	size_t iKeywordLength;
+	TInt iIsFileAttribute;
+	TInt iNumArgs;
+	enum EFileAttribute iAttributeEnum;
+	const char* iHelpText;
+	};
+
+class ObeyFileReader
+	{
+public:
+	ObeyFileReader(const char *aFileName);
+	~ObeyFileReader();
+
+	static void KeywordHelp();
+
+	TBool Open();
+	void Mark();
+	void MarkNext();
+	void Rewind();
+
+	TInt NextLine(TInt aPass, enum EKeyword& aKeyword);
+	TInt NextAttribute(TInt& aIndex, TInt aHasFile, enum EFileAttribute& aKeyword, char*& aArg);
+
+	char* DupWord(TInt aIndex) const;				// allocate copy of nth word
+	TInt Count() const { return iNumWords;}				// number of words on current line
+	const char* Word(TInt aIndex) const { return iWord[aIndex]; }	// return nth word as char* 
+	const char* Suffix() const { return iSuffix; } 			// return unmatched suffix of word[0]
+	TInt CurrentLine() const { return iCurrentLine;}				// number of words on current line
+	const char* GetCurrentObeyStatement() const {return iCurrentObeyStatement;}						// return current obey statement
+
+	void ProcessTime(TInt64& aTime);
+	static void TimeNow(TInt64& aTime);
+private:
+	TInt ReadAndParseLine(); 
+	TInt Parse();
+	inline static TBool IsGap(char ch) {
+		return (ch==' ' || ch=='=' || ch=='\t');
+	}
+
+	static const ObeyFileKeyword iKeywords[];
+	static const FileAttributeKeyword iAttributeKeywords[];
+	static TInt64 iTimeNow;
+
+private:
+	TInt iCurrentLine; 
+	StringVector iLines ;
+	string iFileName;
+	TInt iNumWords;	
+	char* iLine;
+	TInt iMarkLine ;
+	char* iCurrentObeyStatement;
+	char iSuffix[80];
+	char* iWord[KNumWords];
+	};
+
+class CPatchDataProcessor;
+// Configurable FAT attributes
+
+
+class CObeyFile
+	{
+public:
+	char* iRomFileName;
+	char* iExtensionRofsName;
+	char* iKernelRofsName;
+	TInt iRomSize;
+	TVersion iVersion;
+	TUint32 iCheckSum;
+	TInt iNumberOfFiles;
+	TInt64 iTime;
+	TRomNode* iRootDirectory;
+	TInt iNumberOfDataFiles;
+	// Added to support Data Drive Images.
+	char* iDriveFileName; 
+	char* iDriveFileFormat;
+	ConfigurableFatAttributes iConfigurableFatAttributes;
+
+private:
+	ObeyFileReader& iReader;
+	TInt iMissingFiles;
+	TRomNode* iLastExecutable;
+
+	TRomBuilderEntry* iFirstFile;
+	TRomBuilderEntry** iNextFilePtrPtr;
+	TRomBuilderEntry* iCurrentFile;
+	KeywordMap iKeyValues;
+
+public:
+	CObeyFile(ObeyFileReader& aReader);
+	~CObeyFile();
+	void Release();
+	TInt ProcessRofs();
+	TInt ProcessExtensionRofs(MRofsImage* info);
+	TInt ProcessDataDrive();		//	Process the data drive obey file.
+	TRomBuilderEntry *FirstFile();
+	TRomBuilderEntry *NextFile();
+	char* ProcessCoreImage() const;
+	void SkipToExtension();
+	TBool AutoSize() const {return iAutoSize ;}
+	TUint32 AutoPageSize() const {return iAutoPageSize;} 
+	TBool Process();
+ 
+	StringVector getValues(const string& aKey);
+
+private:
+	TBool ProcessFile(TInt aAlign, enum EKeyword aKeyword);
+	TBool ProcessDriveFile(enum EKeyword aKeyword);               
+	TBool ProcessRenaming(enum EKeyword aKeyword);
+	TBool ProcessKeyword(enum EKeyword aKeyword);
+	TBool ProcessDriveKeyword(enum EKeyword aKeyword);
+	void ProcessExtensionKeyword(enum EKeyword aKeyword);
+	TInt ParseFileAttributes(TRomNode* aNode, TRomBuilderEntry* aFile, enum EKeyword aKeyword);
+	TInt ParseSection();
+	TBool ParsePatchDllData();
+	TBool GotKeyVariables();
+	TBool GotKeyDriveVariables();			// To check the data drive mandatory variables. 
+	TBool GotExtensionVariables(MRofsImage* aRom);
+	void AddFile(TRomBuilderEntry* aFile);
+
+	TInt SetStackSize(TRomNode* aNode, const char *aStr);
+	TInt SetHeapSizeMin(TRomNode* aNode, const char *aStr);
+	TInt SetHeapSizeMax(TRomNode* aNode, const char *aStr);
+	TInt SetCapability(TRomNode* aNode, const char *aStr);
+	TInt SetUid1(TRomNode* aNode, const char *aStr);
+	TInt SetUid2(TRomNode* aNode, const char *aStr);
+	TInt SetUid3(TRomNode* aNode, const char *aStr);
+	TInt SetPriority(TRomNode* aNode, const char *aStr);
+	
+	static TBool GetNextBitOfFileName(char*& epocEndPtr);
+	static const char *IsValidFilePath(const char *aPath);
+	static const char* IsValidDirPath(const char* aPath);
+
+	TBool iAutoSize;
+	TUint32 iAutoPageSize;
+	TBool iPagingOverrideParsed;
+	TBool iCodePagingOverrideParsed;
+	TBool iDataPagingOverrideParsed;
+public:
+	CPatchDataProcessor* iPatchData;	
+	void SplitPatchDataStatement(StringVector& aPatchDataTokens);	
+	};
+
+
+#endif
--- a/imgtools/romtools/rofsbuild/r_rofs.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rofsbuild/r_rofs.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,617 +1,587 @@
-/*
-* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include <e32std.h>
-#include <e32std_private.h>
-#include <e32uid.h>
-#include <f32file.h>
-#include "h_utl.h"
-#include <string.h>
-#include <stdlib.h>
-#include "r_obey.h"
-#include "r_rofs.h"
-#include "r_coreimage.h"
-#include "memmap.h"
-extern TInt gLogLevel;
-extern TBool gLowMem;
-extern TBool gFastCompress;
-extern TInt gThreadNum;
-////////////////////////////////////////////////////////////////////////
-
-
-
-inline TUint32 AlignData(TUint32 anAddr)
-	{
-	return ((anAddr+0x0f)&~0x0f);
-	}
-
-
-////////////////////////////////////////////////////////////////////////
-
-E32Rofs::E32Rofs(CObeyFile *aObey)
-//
-// Constructor
-//
-	: iObey( aObey ), iOverhead(0)
-	{
-
-	iSize=aObey->iRomSize;
-	if(gLowMem)
-	{
-		iImageMap = new Memmap();
-
-		if(iImageMap == NULL)
-		{
-			iSize = 0;
-			Print(EError, "Out of memory.\n");
-		}
-		else
-		{
-			iImageMap->SetMaxMapSize(iSize);
-			if(iImageMap->CreateMemoryMap(0, 0xff) == EFalse)
-			{
-				iSize = 0;
-				Print(EError, "Failed to create image map object");
-
-				iImageMap->CloseMemoryMap(ETrue);
-				delete iImageMap;
-				iImageMap = NULL;
-			}
-			else
-			{
-				iData = iImageMap->GetMemoryMapPointer();
-			}
-		}
-	}
-	else
-	{
-		iData=new char [iSize];
-		if (iData==NULL)
-			iSize=0;
-		HMem::Set(iData, 0xff, iSize);
-	}
-
-	}
-
-E32Rofs::~E32Rofs()
-//
-// Destructor
-//
-	{
-
-	if(gLowMem)
-	{
-		iImageMap->CloseMemoryMap(ETrue);
-		delete iImageMap;
-	}
-	else
-		delete iData;
-	}
-
-
-TInt E32Rofs::CreateExtension(MRofsImage* aImage) 
-	{
-
-	TUint8* addr=(TUint8*)iData;
-
-	TRomNode* pRootDir = aImage->RootDirectory();
-	
-
-	const TInt extensionRofsheaderSize = KExtensionRofsHeaderSize;
-	
-	// aImage->iSize contains the max size of the core image
-
-	// Layout the directory structure. Does not actually write it
-	// to the image. Returns the number of bytes used for the directory
-	// structure within the image.
-	TInt directoryOffset = extensionRofsheaderSize;
-	const TInt directorySize = LayoutDirectory( pRootDir, aImage->Size()+directoryOffset );
-	if( directorySize <= 0 )
-		{
-		Print(EError, "Failed laying out directories - return code %d\n", directorySize);
-		return KErrGeneral;
-		}
-
-	// get offset to start of file data, rounded up to next word boundary
-	TInt offs = extensionRofsheaderSize + directorySize;
-	const TInt fileDataStartOffset = offs + ( (4 - offs) & 3);
-
-	// Now we traverse the list of entries placing each file
-	// This updates the directory entries to point to the correct offset
-	// to the start of the file
-	const TInt fileDataSize = PlaceFiles( pRootDir, addr + fileDataStartOffset, fileDataStartOffset + aImage->Size(), aImage->Size());
-	if( fileDataSize <= 0 )
-		{
-		Print(EError, "Failed placing files - return code %d\n", fileDataSize);
-		return KErrGeneral;
-		}
-
-	// and then put the directory into the image
-	TInt err = PlaceDirectory( pRootDir, addr - aImage->Size() ); // offset pointer by size of core image
-	if( err != KErrNone )
-		{
-		Print(EError, "Failed placing directory - return code %d\n", err);
-		return err;
-		}
-		
-	directoryOffset+=aImage->Size(); // offset offset by size of core image
-	// Now write the header
-	TExtensionRofsHeader * pHeader = (TExtensionRofsHeader*)iData;
-	pHeader->iIdentifier[0] = 'R';
-	pHeader->iIdentifier[1] = 'O';
-	pHeader->iIdentifier[2] = 'F';
-	pHeader->iIdentifier[3] = 'x';
-	pHeader->iHeaderSize = KExtensionRofsHeaderSize;
-	pHeader->iDirTreeOffset = directoryOffset;
-	pHeader->iDirTreeSize = iTotalDirectoryBlockSize;
-	pHeader->iDirFileEntriesOffset = directoryOffset + iTotalDirectoryBlockSize;
-	pHeader->iDirFileEntriesSize = iTotalFileBlockSize;
-	pHeader->iRofsFormatVersion = KRofsFormatVersion;
-	pHeader->iTime = iObey->iTime;
-	iSizeUsed = fileDataSize + fileDataStartOffset;
-	pHeader->iImageSize = iSizeUsed;
-	if (iObey->AutoSize())
-		MakeAutomaticSize(iObey->AutoPageSize()); // change iSize to nearest page size
-	pHeader->iMaxImageSize = iSize;
-	pHeader->iCheckSum = 0;		// not used yet
-
-	return KErrNone;
-	}
-	
-void E32Rofs::MakeAutomaticSize(TUint32 aPageSize)
-		{
-		TUint32 size = iSizeUsed;
-		if (iSizeUsed % aPageSize > 0)
-			{
-			//used size needs to be rounded up to nearest page size
-			size = (iSizeUsed/aPageSize + 1)*aPageSize;
-			}
-		iSize = size;
-		}
-
-TInt E32Rofs::Create()
-//
-// This is the main entry point to the ROFS image creation
-//
-	{
-	TUint8* addr=(TUint8*)iData;
-
-	TRomNode* pRootDir = iObey->iRootDirectory;
-	const TInt headerSize = KRofsHeaderSize;
-	// Layout the directory structure. Does not actually write it
-	// to the image. Returns the number of bytes used for the directory
-	// structure within the image.
-	const TInt directoryOffset = headerSize;
-	const TInt directorySize = LayoutDirectory( pRootDir, directoryOffset );
-	if( directorySize <= 0 )
-		{
-		Print(EError, "Failed laying out directories - return code %d\n", directorySize);
-		return KErrGeneral;
-		}
-
-	// get offset to start of file data, rounded up to next word boundary
-	TInt offs = headerSize + directorySize;
-	const TInt fileDataStartOffset = offs + ( (4 - offs) & 3);
-
-	// Now we traverse the list of entries placing each file
-	// This updates the directory entries to point to the correct offset
-	// to the start of the file
-	const TInt fileDataSize = PlaceFiles( pRootDir, addr + fileDataStartOffset, fileDataStartOffset );
-	if( fileDataSize < 0 )
-		{
-		Print(EError, "Failed placing files - return code %d\n", fileDataSize);
-		return KErrGeneral;
-		}
-
-	// and then put the directory into the image
-	TInt err = PlaceDirectory( pRootDir, addr );
-	if( err != KErrNone )
-		{
-		Print(EError, "Failed placing directory - return code %d\n", err);
-		return err;
-		}
-		
-	// Now write the header
-	TRofsHeader* pHeader = (TRofsHeader*)iData;
-	pHeader->iIdentifier[0] = 'R';
-	pHeader->iIdentifier[1] = 'O';
-	pHeader->iIdentifier[2] = 'F';
-	pHeader->iIdentifier[3] = 'S';
-	pHeader->iHeaderSize = KExtensionRofsHeaderSize;
-	pHeader->iDirTreeOffset = directoryOffset;
-	pHeader->iDirTreeSize = iTotalDirectoryBlockSize;
-	pHeader->iDirFileEntriesOffset = directoryOffset + iTotalDirectoryBlockSize;
-	pHeader->iDirFileEntriesSize = iTotalFileBlockSize;
-	pHeader->iRofsFormatVersion = KRofsFormatVersion;
-	pHeader->iTime = iObey->iTime;
-	iSizeUsed = fileDataSize + fileDataStartOffset;
-	pHeader->iImageSize = iSizeUsed;
-	pHeader->iImageVersion = iObey->iVersion;
-	if (iObey->AutoSize())
-		MakeAutomaticSize(iObey->AutoPageSize()); // change iSize to nearest page size
-		
-	pHeader->iMaxImageSize = iSize;
-	pHeader->iCheckSum = 0;		// not used yet
-
-	return KErrNone;
-	}
-void E32Rofs::DisplaySizes(TPrintType aWhere)
-{
-	Print(aWhere, "Summary of file sizes in rofs:\n");
-	TRomBuilderEntry *file=iObey->FirstFile();
-	while(file)
-		{
-		file->DisplaySize(aWhere);
-		file=iObey->NextFile();
-		}
-	Print( aWhere, "Directory block size: %d\n"
-					"File block size:      %d\n"
-					"Total directory size: %d\n"
-					"Total image size:     %d\n",
-					iTotalDirectoryBlockSize,
-					iTotalFileBlockSize,
-					iTotalDirectoryBlockSize + iTotalFileBlockSize,
-					iSizeUsed );
-
-}
-
-void E32Rofs::LogExecutableAttributes(E32ImageHeaderV *aHdr)
-{
-	Print(ELog, "Uids:                    %08x %08x %08x %08x\n", aHdr->iUid1, aHdr->iUid2, aHdr->iUid3, aHdr->iUidChecksum);
-	Print(ELog, "Data size:               %08x\n", aHdr->iDataSize);
-	Print(ELog, "Heap min:                %08x\n", aHdr->iHeapSizeMin);
-	Print(ELog, "Heap max:                %08x\n", aHdr->iHeapSizeMax);
-	Print(ELog, "Stack size:              %08x\n", aHdr->iStackSize);
-	Print(ELog, "Secure ID:               %08x\n", aHdr->iS.iSecureId);
-	Print(ELog, "Vendor ID:               %08x\n", aHdr->iS.iVendorId);
-	Print(ELog, "Priority:                %d\n\n", aHdr->iProcessPriority);
-}
-class Worker : public boost::thread {
-    public:
-    static void thrd_func(E32Rofs* rofs){
-        CBytePair bpe(gFastCompress);
-
-        bool deferred = false;
-        TPlacingSection* p = rofs->GetFileNode(deferred);
-        while(p) {
-            if(!deferred) 
-                p->len = p->node->PlaceFile(p->buf, (TUint32)-1, 0, &bpe);
-            p = rofs->GetFileNode(deferred);
-        }
-        rofs->ArriveDeferPoint();
-        p = rofs->GetDeferredJob();
-        while(p) {
-            p->len = p->node->PlaceFile(p->buf, (TUint32)-1, 0, &bpe);
-            p = rofs->GetDeferredJob();
-        }
-    }
-    Worker(E32Rofs* rofs) : boost::thread(thrd_func,rofs) {
-    }
-};
-
-TPlacingSection* E32Rofs::GetFileNode(bool &aDeferred) {
-    //get a node from the node list, the node list is protected by mutex iMuxTree.
-    //The iMuxTree also helps to make sure the order in iVPS is consistent with the node list.
-    //And this is the guarantee of same outputs regardless of how many threads being used.
-    boost::mutex::scoped_lock lock(iMuxTree);
-    aDeferred = false;
-    TRomNode* node = iLastNode;
-    while(node) {
-        if( node->IsFile()) {
-            if(!node->iHidden) {
-                iLastNode = node->NextNode();
-                break;
-            }
-        }
-        node = node->NextNode();
-    }
-
-    if(node && node->IsFile() && !node->iHidden) {
-        TPlacingSection* pps = new TPlacingSection(node);
-        iVPS.push_back(pps);
-        if(node->iAlias) {
-            iQueueAliasNode.push(pps);
-            aDeferred =  true;
-        }
-        return pps;
-    }
-    return NULL;
-}
-TPlacingSection* E32Rofs::GetDeferredJob() {
-    // waiting all the normal node have been placed.
-    while(iWorkerArrived < gThreadNum)
-        boost::this_thread::sleep(boost::posix_time::milliseconds(10));
-
-    // now we can safely handle the alias nodes.
-    boost::mutex::scoped_lock lock(iMuxTree);
-    TPlacingSection* p = NULL;
-    if(!iQueueAliasNode.empty()) {
-        p = iQueueAliasNode.front();
-        iQueueAliasNode.pop();
-    }
-    return p;
-}
-void E32Rofs::ArriveDeferPoint() {
-    boost::mutex::scoped_lock lock(iMuxTree);
-    ++iWorkerArrived;
-}
-TInt E32Rofs::PlaceFiles( TRomNode* /*aRootDir*/, TUint8* aDestBase, TUint aBaseOffset, TInt aCoreSize ) 
-	//
-	// Traverses all entries placing all files and updating directory entry pointers.
-	// Returns number of bytes placed or -ve error code.
-	//
-	{
-            iLastNode = TRomNode::FirstNode();
-            iWorkerArrived = 0;
-
-            boost::thread_group thrds;
-            Worker** workers = new Worker*[gThreadNum];
-            int i;
-            for (i = 0; i < gThreadNum; ++i) {
-                workers[i] = new Worker(this);
-                thrds.add_thread(workers[i]);
-            }
-
-            thrds.join_all();
-            delete [] workers;
-
-            TUint offset = aBaseOffset;
-            TUint8* dest = aDestBase;
-            TBool aIgnoreHiddenAttrib = ETrue;
-            TInt len = iVPS.size();
-            TInt maxSize;
-            for(i=0;i<len;i++) {
-                maxSize = aCoreSize + iSize - offset;
-                if(maxSize <= 0) {
-                    // Image size is too low to proceed.
-                    return maxSize;
-                }
-                if(iVPS[i]->node->iFileStartOffset != (TUint)KFileHidden) {
-                    memcpy(dest,iVPS[i]->buf,iVPS[i]->len);
-                    if(iVPS[i]->node->iEntry->iFileOffset == -1) {
-                        iVPS[i]->node->iEntry->iFileOffset = offset;
-                        iVPS[i]->node->iFileStartOffset = iVPS[i]->node->iEntry->iFileOffset;
-                    }
-                    else {
-                        TRomBuilderEntry* aEntry = (TRomBuilderEntry*)(iVPS[i]->node->iFileStartOffset);
-                        iVPS[i]->node->iFileStartOffset = aEntry->iFileOffset;
-                    }
-                }
-                iVPS[i]->len += (4-iVPS[i]->len) & 3;// round up to next word boundary
-                dest += iVPS[i]->len;
-                offset += iVPS[i]->len;
-
-                if(gLogLevel > DEFAULT_LOG_LEVEL )
-                {
-                    TRomNode* node = iVPS[i]->node;
-                    TInt aLen = node->FullNameLength(aIgnoreHiddenAttrib);
-                    char *aBuf = new char[aLen+1];
-                    if(gLogLevel & LOG_LEVEL_FILE_DETAILS)
-                    {
-                        node->GetFullName(aBuf, aIgnoreHiddenAttrib);
-                        if(node->iEntry->iFileName)
-                            Print(ELog,"%s\t%d\t%s\t%s\n", node->iEntry->iFileName, node->iEntry->RealFileSize(), (node->iHidden || node->iEntry->iHidden)? "hidden":"", aBuf);
-                        else
-                            Print(ELog,"%s\t%s\n", (node->iHidden || node->iEntry->iHidden) ? "hidden":"", aBuf);
-                    }
-
-                    if(gLogLevel & LOG_LEVEL_FILE_ATTRIBUTES)
-                    {
-                        if(!node->iHidden && !node->iEntry->iHidden)
-                            Print(ELog, "Device file name:        %s\n", aBuf);
-                        if(node->iEntry->iExecutable)
-                            LogExecutableAttributes((E32ImageHeaderV*)(dest-len));
-                    }
-                    delete[] aBuf;
-                }
-            }
-	return offset - aBaseOffset;	// number of bytes used
-	}
-
-
-
-
-
-
-TInt E32Rofs::LayoutDirectory( TRomNode* /*aRootDir*/, TUint aBaseOffset ) 
-	//
-	// Creates the directory layout but does not write it to the image.
-	// All directories are given a location in the image.
-	// Returns the total number of bytes used for the directory (rounded
-	// up to the nearest word) or a -ve error code.
-	//
-	{
-	TRomNode* node = TRomNode::FirstNode();
-
-	TUint offset = aBaseOffset;
-	while( node )
-		{
-		if( node->IsDirectory())
-			{
-			// it is a directory block so we have to give it a location
-			node->SetImagePosition( offset );
-		
-			// work out how much space it requires for the directory block
-			TInt dirLen;
-			TInt fileLen;
-			TInt err = node->CalculateDirectoryEntrySize( dirLen, fileLen );
-			if( err != KErrNone )
-				{
-				return err;
-				}
-			Print( ELog, "Directory '%s' @offs=0x%x, size=%d\n", node->iName, offset, dirLen );
-			dirLen += (4-dirLen) & 3;	// round up to next word boundary
-			offset += dirLen;
-			}
-
-		node = node->NextNode();
-		}
-
-	TInt totalDirectoryBlockSize = offset - aBaseOffset;	// number of bytes used
-	totalDirectoryBlockSize += (4 - totalDirectoryBlockSize) & 3;		// round up
-
-	// Now go round again placing the file blocks
-	offset = aBaseOffset + totalDirectoryBlockSize;
-	const TUint fileBlockStartOffset = offset;
-	node = TRomNode::FirstNode();
-	while( node )
-		{
-		if( node->IsDirectory() )
-			{
-			// work out how much space it requires for the file block
-			TInt dummy;
-			TInt fileLen;
-			TInt err = node->CalculateDirectoryEntrySize( dummy, fileLen );
-
-			if( err != KErrNone )
-				{
-				return fileLen;
-				}
-			if( fileLen )
-				{
-				node->SetFileBlockPosition( offset );
-				Print( ELog, "File block for dir '%s' @offs=0x%x, size=%d\n", node->iName, offset, fileLen );
-				}
-		
-			fileLen += (4-fileLen) & 3;	// round up to next word boundary
-			offset += fileLen;
-			}
-
-		node = node->NextNode();
-		}
-
-	TInt totalFileBlockSize = offset - fileBlockStartOffset;	// number of bytes used
-	totalFileBlockSize += (4 - totalFileBlockSize) & 3;		// round up
-
-	iTotalDirectoryBlockSize = totalDirectoryBlockSize;
-	iTotalFileBlockSize = totalFileBlockSize;
-
-	return totalDirectoryBlockSize + totalFileBlockSize;
-	}
-
-
-TInt E32Rofs::PlaceDirectory( TRomNode* /*aRootDir*/, TUint8* aDestBase ) 
-	//
-	// Writes the directory into the image. 
-	// Returns KErrNone on success, or error code
-	//
-	{
-	TRomNode* node = TRomNode::FirstNode();
-
-	while( node )
-		{
-		if( node->IsDirectory() )
-			{
-			TInt err = node->Place( aDestBase );
-			if( err != KErrNone )
-				{
-				return err;
-				}
-			}
-		node = node->NextNode();
-		}
-	return KErrNone;
-	}
-
-TInt E32Rofs::WriteImage( TInt aHeaderType )
-	{
-	ofstream romFile((const char *)iObey->iRomFileName,ios::binary);
-	if (!romFile)
-		return Print(EError,"Cannot open ROM file %s for output\n",iObey->iRomFileName);
-	Write(romFile, aHeaderType);
-	romFile.close();
-
-	return KErrNone;
-	}
-
-TRomNode* E32Rofs::CopyDirectory(TRomNode*& aLastExecutable)
-	{
-	return iObey->iRootDirectory->CopyDirectory(aLastExecutable);
-	}
-
-
-void E32Rofs::Write(ofstream &os, TInt aHeaderType)
-
-// Output a rom image
-
-	{
-
-	switch (aHeaderType)
-		{
-	default:
-	case 0:
-		Print(EAlways, "\nWriting Rom image without");
-		break;
-	case 2:
-		Print(EAlways, "\nWriting Rom image with PE-COFF");
-			{
-			unsigned char coffhead[0x58] = {0};  // zero all the elements
-
-			// fill in the constant bits
-			// this is supposed to be simple, remember
-			coffhead[1] = 0x0a;
-			coffhead[2] = 0x01;
-			coffhead[0x10] = 0x1c;
-			coffhead[0x12] = 0x0f;
-			coffhead[0x13] = 0xa1;
-			coffhead[0x14] = 0x0b;
-			coffhead[0x15] = 0x01;
-			coffhead[0x26] = 0x40;
-			coffhead[0x2a] = 0x40;
-			coffhead[0x30] = 0x2e;
-			coffhead[0x31] = 0x74;
-			coffhead[0x32] = 0x65;
-			coffhead[0x33] = 0x78;
-			coffhead[0x34] = 0x74;
-			coffhead[0x3a] = 0x40;
-			coffhead[0x3e] = 0x40;
-			coffhead[0x44] = 0x58;
-			coffhead[0x54] = 0x20;
-
-			// now fill in the text segment size
-			*(TUint32 *) (&coffhead[0x18]) = ALIGN4K(iSizeUsed);
-			*(TUint32 *) (&coffhead[0x40]) = ALIGN4K(iSizeUsed);
-
-			os.write(reinterpret_cast<char *>(coffhead), sizeof(coffhead));
-			}
-		break;
-		}
-	Print(EAlways, " header to file %s\n", iObey->iRomFileName);
-	os.write( iData, iSizeUsed );
-	}
-
-
-TRomNode* E32Rofs::RootDirectory()
-	{
-	return iObey->iRootDirectory;
-	}
-void E32Rofs::SetRootDirectory(TRomNode* aDir)
-	{
-	iObey->iRootDirectory = aDir;
-	}
-TText* E32Rofs::RomFileName()
-	{
-	return iObey->iRomFileName;
-	}
-TInt E32Rofs::Size()
-	{
-	return iSize;
-	}
-
-///////////////////
-
+/*
+* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#include <e32std.h>
+#include <e32std_private.h>
+#include <e32uid.h>
+#include <f32file.h>
+#include "h_utl.h"
+#include <string.h>
+#include <stdlib.h>
+#include "r_obey.h"
+#include "r_rofs.h"
+#include "r_coreimage.h"
+#include "memmap.h"
+#include "symbolgenerator.h"
+extern TInt gLogLevel;
+extern TBool gLowMem;
+extern TInt gThreadNum;
+extern TBool gGenSymbols;
+////////////////////////////////////////////////////////////////////////
+
+
+
+inline TUint32 AlignData(TUint32 anAddr) {
+	return ((anAddr+0x0f)&~0x0f);
+}
+
+
+////////////////////////////////////////////////////////////////////////
+
+E32Rofs::E32Rofs(CObeyFile *aObey)
+//
+// Constructor
+//
+	: iObey( aObey ), iOverhead(0)
+	{
+	if(gGenSymbols)
+		iSymGen = SymbolGenerator::GetInstance();
+	else
+		iSymGen = NULL;
+
+	iSize=aObey->iRomSize;
+	if(gLowMem) {
+		iImageMap = new Memmap();
+
+		if(iImageMap == NULL) {
+			iSize = 0;
+			Print(EError, "Out of memory.\n");
+		}
+		else {
+			iImageMap->SetMaxMapSize(iSize);
+			if(iImageMap->CreateMemoryMap(0, 0xff) == EFalse) {
+				iSize = 0;
+				Print(EError, "Failed to create image map object");
+
+				iImageMap->CloseMemoryMap(ETrue);
+				delete iImageMap;
+				iImageMap = NULL;
+			}
+			else {
+				iData = iImageMap->GetMemoryMapPointer();
+			}
+		}
+	}
+	else {
+		iData=new char [iSize];
+		if (iData==NULL)
+			iSize=0;
+		HMem::Set(iData, 0xff, iSize);
+	}
+
+}
+
+E32Rofs::~E32Rofs()  {
+
+	if(gLowMem) {
+		iImageMap->CloseMemoryMap(ETrue);
+		delete iImageMap;
+	}
+	else if(iData)
+		delete []iData;
+}
+
+
+TInt E32Rofs::CreateExtension(MRofsImage* aImage)  {
+
+	TUint8* addr=(TUint8*)iData;
+
+	TRomNode* pRootDir = aImage->RootDirectory();
+
+
+	const TInt extensionRofsheaderSize = KExtensionRofsHeaderSize;
+
+	// aImage->iSize contains the max size of the core image
+
+	// Layout the directory structure. Does not actually write it
+	// to the image. Returns the number of bytes used for the directory
+	// structure within the image.
+	TInt directoryOffset = extensionRofsheaderSize;
+	const TInt directorySize = LayoutDirectory( pRootDir, aImage->Size()+directoryOffset );
+	if( directorySize <= 0 ) {
+		Print(EError, "Failed laying out directories - return code %d\n", directorySize);
+		return KErrGeneral;
+	}
+
+	// get offset to start of file data, rounded up to next word boundary
+	TInt offs = extensionRofsheaderSize + directorySize;
+	const TInt fileDataStartOffset = offs + ( (4 - offs) & 3);
+
+	// Now we traverse the list of entries placing each file
+	// This updates the directory entries to point to the correct offset
+	// to the start of the file
+	const TInt fileDataSize = PlaceFiles( pRootDir, addr + fileDataStartOffset, fileDataStartOffset + aImage->Size(), aImage->Size());
+	if( fileDataSize <= 0 ) {
+		Print(EError, "Failed placing files - return code %d\n", fileDataSize);
+		return KErrGeneral;
+	}
+
+	// and then put the directory into the image
+	TInt err = PlaceDirectory( pRootDir, addr - aImage->Size() ); // offset pointer by size of core image
+	if( err != KErrNone ) {
+		Print(EError, "Failed placing directory - return code %d\n", err);
+		return err;
+	}
+
+	directoryOffset+=aImage->Size(); // offset offset by size of core image
+	// Now write the header
+	TExtensionRofsHeader * pHeader = (TExtensionRofsHeader*)iData;
+	pHeader->iIdentifier[0] = 'R';
+	pHeader->iIdentifier[1] = 'O';
+	pHeader->iIdentifier[2] = 'F';
+	pHeader->iIdentifier[3] = 'x';
+	pHeader->iHeaderSize = KExtensionRofsHeaderSize;
+	pHeader->iDirTreeOffset = directoryOffset;
+	pHeader->iDirTreeSize = iTotalDirectoryBlockSize;
+	pHeader->iDirFileEntriesOffset = directoryOffset + iTotalDirectoryBlockSize;
+	pHeader->iDirFileEntriesSize = iTotalFileBlockSize;
+	pHeader->iRofsFormatVersion = KRofsFormatVersion;
+	pHeader->iTime = iObey->iTime;
+	iSizeUsed = fileDataSize + fileDataStartOffset;
+	pHeader->iImageSize = iSizeUsed;
+	if (iObey->AutoSize())
+		MakeAutomaticSize(iObey->AutoPageSize()); // change iSize to nearest page size
+	pHeader->iMaxImageSize = iSize;
+	pHeader->iCheckSum = 0;		// not used yet
+
+	return KErrNone;
+}
+
+void E32Rofs::MakeAutomaticSize(TUint32 aPageSize) {
+	TUint32 size = iSizeUsed;
+	if (iSizeUsed % aPageSize > 0) {
+		//used size needs to be rounded up to nearest page size
+		size = (iSizeUsed/aPageSize + 1)*aPageSize;
+	}
+	iSize = size;
+}
+
+//
+// This is the main entry point to the ROFS image creation
+//
+TInt E32Rofs::Create() {
+	TUint8* addr=(TUint8*)iData;
+
+	TRomNode* pRootDir = iObey->iRootDirectory;
+	const TInt headerSize = KRofsHeaderSize;
+	// Layout the directory structure. Does not actually write it
+	// to the image. Returns the number of bytes used for the directory
+	// structure within the image.
+	const TInt directoryOffset = headerSize;
+	const TInt directorySize = LayoutDirectory( pRootDir, directoryOffset );
+	if( directorySize <= 0 ) {
+		Print(EError, "Failed laying out directories - return code %d\n", directorySize);
+		return KErrGeneral;
+	}
+
+	// get offset to start of file data, rounded up to next word boundary
+	TInt offs = headerSize + directorySize;
+	const TInt fileDataStartOffset = offs + ( (4 - offs) & 3);
+
+	// Now we traverse the list of entries placing each file
+	// This updates the directory entries to point to the correct offset
+	// to the start of the file
+	const TInt fileDataSize = PlaceFiles( pRootDir, addr + fileDataStartOffset, fileDataStartOffset );
+	if( fileDataSize < 0 ) {
+		Print(EError, "Failed placing files - rofssize is too small\n", fileDataSize);
+		return KErrGeneral;
+	}
+
+	// and then put the directory into the image
+	TInt err = PlaceDirectory( pRootDir, addr );
+	if( err != KErrNone ) {
+		Print(EError, "Failed placing directory - return code %d\n", err);
+		return err;
+	}
+
+	// Now write the header
+	TRofsHeader* pHeader = (TRofsHeader*)iData;
+	pHeader->iIdentifier[0] = 'R';
+	pHeader->iIdentifier[1] = 'O';
+	pHeader->iIdentifier[2] = 'F';
+	pHeader->iIdentifier[3] = 'S';
+	pHeader->iHeaderSize = KExtensionRofsHeaderSize;
+	pHeader->iDirTreeOffset = directoryOffset;
+	pHeader->iDirTreeSize = iTotalDirectoryBlockSize;
+	pHeader->iDirFileEntriesOffset = directoryOffset + iTotalDirectoryBlockSize;
+	pHeader->iDirFileEntriesSize = iTotalFileBlockSize;
+	pHeader->iRofsFormatVersion = KRofsFormatVersion;
+	pHeader->iTime = iObey->iTime;
+	iSizeUsed = fileDataSize + fileDataStartOffset;
+	pHeader->iImageSize = iSizeUsed;
+	pHeader->iImageVersion = iObey->iVersion;
+	if (iObey->AutoSize())
+		MakeAutomaticSize(iObey->AutoPageSize()); // change iSize to nearest page size
+
+	pHeader->iMaxImageSize = iSize;
+	pHeader->iCheckSum = 0;		// not used yet
+
+	return KErrNone;
+}
+void E32Rofs::DisplaySizes(TPrintType aWhere) {
+	Print(aWhere, "Summary of file sizes in rofs:\n");
+	TRomBuilderEntry *file=iObey->FirstFile();
+	while(file) {
+		file->DisplaySize(aWhere);
+		file=iObey->NextFile();
+	}
+	Print( aWhere, "Directory block size: %d\n"
+		"File block size:      %d\n"
+		"Total directory size: %d\n"
+		"Total image size:     %d\n",
+		iTotalDirectoryBlockSize,
+		iTotalFileBlockSize,
+		iTotalDirectoryBlockSize + iTotalFileBlockSize,
+		iSizeUsed );
+
+}
+
+void E32Rofs::LogExecutableAttributes(E32ImageHeaderV *aHdr) {
+	Print(ELog, "Uids:                    %08x %08x %08x %08x\n", aHdr->iUid1, aHdr->iUid2, aHdr->iUid3, aHdr->iUidChecksum);
+	Print(ELog, "Data size:               %08x\n", aHdr->iDataSize);
+	Print(ELog, "Heap min:                %08x\n", aHdr->iHeapSizeMin);
+	Print(ELog, "Heap max:                %08x\n", aHdr->iHeapSizeMax);
+	Print(ELog, "Stack size:              %08x\n", aHdr->iStackSize);
+	Print(ELog, "Secure ID:               %08x\n", aHdr->iS.iSecureId);
+	Print(ELog, "Vendor ID:               %08x\n", aHdr->iS.iVendorId);
+	Print(ELog, "Priority:                %d\n\n", aHdr->iProcessPriority);
+}
+class Worker : public boost::thread {
+    public:
+    static void thrd_func(E32Rofs* rofs){
+        CBytePair bpe;
+
+        bool deferred = false;
+        TPlacingSection* p = rofs->GetFileNode(deferred);
+        while(p) {
+            if(!deferred) {
+                p->len = p->node->PlaceFile(p->buf, (TUint32)-1, 0, &bpe);
+                //no symbol for hidden file
+                if(rofs->iSymGen && !p->node->iEntry->iHidden)
+                    rofs->iSymGen->AddFile(p->node->iEntry->iFileName,(p->node->iEntry->iCompressEnabled|| p->node->iEntry->iExecutable));
+            }
+            p = rofs->GetFileNode(deferred);
+        }
+        rofs->ArriveDeferPoint();
+        p = rofs->GetDeferredJob();
+        while(p) {
+            p->len = p->node->PlaceFile(p->buf, (TUint32)-1, 0, &bpe);
+            p = rofs->GetDeferredJob();
+        }
+    }
+    Worker(E32Rofs* rofs) : boost::thread(thrd_func,rofs) {
+    }
+};
+
+TPlacingSection* E32Rofs::GetFileNode(bool &aDeferred) {
+	//get a node from the node list, the node list is protected by mutex iMuxTree.
+	//The iMuxTree also helps to make sure the order in iVPS is consistent with the node list.
+	//And this is the guarantee of same outputs regardless of how many threads being used.
+	boost::mutex::scoped_lock lock(iMuxTree);
+	aDeferred = false;
+	TRomNode* node = iLastNode;
+	while(node) {
+		if( node->IsFile()) {
+			if(!node->iHidden) {
+				iLastNode = node->NextNode();
+				break;
+			}
+		}
+		node = node->NextNode();
+	}
+
+	if(node && node->IsFile() && !node->iHidden) {
+		TPlacingSection* pps = new TPlacingSection(node);
+		iVPS.push_back(pps);
+		if(node->iAlias) {
+			iQueueAliasNode.push(pps);
+			aDeferred =  true;
+		}
+		return pps;
+	}
+	return NULL;
+}
+TPlacingSection* E32Rofs::GetDeferredJob() {
+	// waiting all the normal node have been placed.
+	while(iWorkerArrived < gThreadNum)
+		boost::this_thread::sleep(boost::posix_time::milliseconds(10));
+
+	// now we can safely handle the alias nodes.
+	boost::mutex::scoped_lock lock(iMuxTree);
+	TPlacingSection* p = NULL;
+	if(!iQueueAliasNode.empty()) {
+		p = iQueueAliasNode.front();
+		iQueueAliasNode.pop();
+	}
+	return p;
+}
+void E32Rofs::ArriveDeferPoint() {
+	boost::mutex::scoped_lock lock(iMuxTree);
+	++iWorkerArrived;
+}
+TInt E32Rofs::PlaceFiles( TRomNode* /*aRootDir*/, TUint8* aDestBase, TUint aBaseOffset, TInt aCoreSize ) 
+	//
+	// Traverses all entries placing all files and updating directory entry pointers.
+	// Returns number of bytes placed or -ve error code.
+	//
+	{
+            if(iSymGen)
+                iSymGen->SetSymbolFileName((const char *)iObey->iRomFileName);
+            iLastNode = TRomNode::FirstNode();
+            iWorkerArrived = 0;
+
+            boost::thread_group thrds;
+            Worker** workers = new Worker*[gThreadNum];
+            int i;
+            for (i = 0; i < gThreadNum; ++i) {
+                workers[i] = new Worker(this);
+                thrds.add_thread(workers[i]);
+            }
+
+            thrds.join_all();
+            delete [] workers;
+            if(iSymGen)
+                iSymGen->AddFile("",false);
+
+            TUint offset = aBaseOffset;
+            TUint8* dest = aDestBase;
+            TBool aIgnoreHiddenAttrib = ETrue;
+            TInt len = iVPS.size();
+            TInt maxSize;
+            for(i=0;i<len;i++) {
+                maxSize = aCoreSize + iSize - offset;
+                if(maxSize <= 0) {
+                    // Image size is too low to proceed.
+                    return maxSize;
+                }
+                if(iVPS[i]->node->iFileStartOffset != (TUint)KFileHidden) {
+                    if (iVPS[i]->len > maxSize) {
+                       // Image size is too low to proceed.
+                       return maxSize - iVPS[i]->len;
+                    }
+                    memcpy(dest,iVPS[i]->buf,iVPS[i]->len);
+                    if(iVPS[i]->node->iEntry->iFileOffset == -1) {
+                        iVPS[i]->node->iEntry->iFileOffset = offset;
+                        iVPS[i]->node->iFileStartOffset = iVPS[i]->node->iEntry->iFileOffset;
+                    }
+                    else {
+                        TRomBuilderEntry* aEntry = (TRomBuilderEntry*)(iVPS[i]->node->iFileStartOffset);
+                        iVPS[i]->node->iFileStartOffset = aEntry->iFileOffset;
+                    }
+                }
+                iVPS[i]->len += (4-iVPS[i]->len) & 3;// round up to next word boundary
+                dest += iVPS[i]->len;
+                offset += iVPS[i]->len;
+
+                if(gLogLevel > DEFAULT_LOG_LEVEL )
+                {
+                    TRomNode* node = iVPS[i]->node;
+                    TInt aLen = node->FullNameLength(aIgnoreHiddenAttrib);
+                    char *aBuf = new char[aLen+1];
+                    if(gLogLevel & LOG_LEVEL_FILE_DETAILS)
+                    {
+                        node->GetFullName(aBuf, aIgnoreHiddenAttrib);
+                        if(node->iEntry->iFileName)
+                            Print(ELog,"%s\t%d\t%s\t%s\n", node->iEntry->iFileName, node->iEntry->RealFileSize(), (node->iHidden || node->iEntry->iHidden)? "hidden":"", aBuf);
+                        else
+                            Print(ELog,"%s\t%s\n", (node->iHidden || node->iEntry->iHidden) ? "hidden":"", aBuf);
+                    }
+
+                    if(gLogLevel & LOG_LEVEL_FILE_ATTRIBUTES)
+                    {
+                        if(!node->iHidden && !node->iEntry->iHidden)
+                            Print(ELog, "Device file name:        %s\n", aBuf);
+                        if(node->iEntry->iExecutable)
+                            LogExecutableAttributes((E32ImageHeaderV*)(dest-len));
+                    }
+                    delete[] aBuf;
+                }
+            }
+	return offset - aBaseOffset;	// number of bytes used
+	}
+
+
+
+
+
+
+//
+// Creates the directory layout but does not write it to the image.
+// All directories are given a location in the image.
+// Returns the total number of bytes used for the directory (rounded
+// up to the nearest word) or a -ve error code.
+//
+TInt E32Rofs::LayoutDirectory( TRomNode* /*aRootDir*/, TUint aBaseOffset )  {
+	TRomNode* node = TRomNode::FirstNode();
+
+	TUint offset = aBaseOffset;
+	while( node ) {
+		if( node->IsDirectory()) {
+			// it is a directory block so we have to give it a location
+			node->SetImagePosition( offset );
+
+			// work out how much space it requires for the directory block
+			TInt dirLen;
+			TInt fileLen;
+			TInt err = node->CalculateDirectoryEntrySize( dirLen, fileLen );
+			if( err != KErrNone ) {
+				return err;
+			}
+			Print( ELog, "Directory '%s' @offs=0x%x, size=%d\n", node->iName, offset, dirLen );
+			dirLen += (4-dirLen) & 3;	// round up to next word boundary
+			offset += dirLen;
+		}
+
+		node = node->NextNode();
+	}
+
+	TInt totalDirectoryBlockSize = offset - aBaseOffset;	// number of bytes used
+	totalDirectoryBlockSize += (4 - totalDirectoryBlockSize) & 3;		// round up
+
+	// Now go round again placing the file blocks
+	offset = aBaseOffset + totalDirectoryBlockSize;
+	const TUint fileBlockStartOffset = offset;
+	node = TRomNode::FirstNode();
+	while( node ) {
+		if( node->IsDirectory() ) {
+			// work out how much space it requires for the file block
+			TInt dummy;
+			TInt fileLen;
+			TInt err = node->CalculateDirectoryEntrySize( dummy, fileLen );
+
+			if( err != KErrNone ) {
+				return fileLen;
+			}
+			if( fileLen ) {
+				node->SetFileBlockPosition( offset );
+				Print( ELog, "File block for dir '%s' @offs=0x%x, size=%d\n", node->iName, offset, fileLen );
+			}
+
+			fileLen += (4-fileLen) & 3;	// round up to next word boundary
+			offset += fileLen;
+		}
+
+		node = node->NextNode();
+	}
+
+	TInt totalFileBlockSize = offset - fileBlockStartOffset;	// number of bytes used
+	totalFileBlockSize += (4 - totalFileBlockSize) & 3;		// round up
+
+	iTotalDirectoryBlockSize = totalDirectoryBlockSize;
+	iTotalFileBlockSize = totalFileBlockSize;
+
+	return totalDirectoryBlockSize + totalFileBlockSize;
+}
+//
+// Writes the directory into the image. 
+// Returns KErrNone on success, or error code
+//
+
+TInt E32Rofs::PlaceDirectory( TRomNode* /*aRootDir*/, TUint8* aDestBase )  {
+	TRomNode* node = TRomNode::FirstNode();
+
+	while( node ) {
+		if( node->IsDirectory() ) {
+			TInt err = node->Place( aDestBase );
+			if( err != KErrNone ) {
+				return err;
+			}
+		}
+		node = node->NextNode();
+	}
+	return KErrNone;
+}
+
+TInt E32Rofs::WriteImage( TInt aHeaderType ) {
+	ofstream romFile((const char *)iObey->iRomFileName,ios_base::binary);
+	if (!romFile)
+		return Print(EError,"Cannot open ROM file %s for output\n",iObey->iRomFileName);
+	Write(romFile, aHeaderType);
+	romFile.close();
+        if(iSymGen)
+            SymbolGenerator::Release();
+
+	return KErrNone;
+}
+
+TRomNode* E32Rofs::CopyDirectory(TRomNode*& aLastExecutable) {
+	return iObey->iRootDirectory->CopyDirectory(aLastExecutable);
+}
+
+
+// Output a rom image
+void E32Rofs::Write(ofstream &os, TInt aHeaderType) {
+
+	switch (aHeaderType) {
+	default:
+	case 0:
+		Print(EAlways, "\nWriting Rom image without");
+		break;
+	case 2:
+		Print(EAlways, "\nWriting Rom image with PE-COFF"); {
+			unsigned char coffhead[0x58] = {0};  // zero all the elements
+
+			// fill in the constant bits
+			// this is supposed to be simple, remember
+			coffhead[1] = 0x0a;
+			coffhead[2] = 0x01;
+			coffhead[0x10] = 0x1c;
+			coffhead[0x12] = 0x0f;
+			coffhead[0x13] = 0xa1;
+			coffhead[0x14] = 0x0b;
+			coffhead[0x15] = 0x01;
+			coffhead[0x26] = 0x40;
+			coffhead[0x2a] = 0x40;
+			coffhead[0x30] = 0x2e;
+			coffhead[0x31] = 0x74;
+			coffhead[0x32] = 0x65;
+			coffhead[0x33] = 0x78;
+			coffhead[0x34] = 0x74;
+			coffhead[0x3a] = 0x40;
+			coffhead[0x3e] = 0x40;
+			coffhead[0x44] = 0x58;
+			coffhead[0x54] = 0x20;
+
+			// now fill in the text segment size
+			*(TUint32 *) (&coffhead[0x18]) = ALIGN4K(iSizeUsed);
+			*(TUint32 *) (&coffhead[0x40]) = ALIGN4K(iSizeUsed);
+
+			os.write(reinterpret_cast<char *>(coffhead), sizeof(coffhead));
+		}
+		break;
+	}
+	Print(EAlways, " header to file %s\n", iObey->iRomFileName);
+	os.write( iData, iSizeUsed );
+}
+
+
+TRomNode* E32Rofs::RootDirectory() {
+	return iObey->iRootDirectory;
+}
+void E32Rofs::SetRootDirectory(TRomNode* aDir) {
+	iObey->iRootDirectory = aDir;
+}
+const char* E32Rofs::RomFileName() const  {
+	return iObey->iRomFileName;
+}
+TInt E32Rofs::Size() const  {
+	return iSize;
+}
+
+///////////////////
+
--- a/imgtools/romtools/rofsbuild/r_rofs.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rofsbuild/r_rofs.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,125 +1,123 @@
-/*
-* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifndef __R_ROFS_H__
-#define __R_ROFS_H__
-
-#include <e32rom.h>
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-#include <fstream>
-#else //!__MSVCDOTNET__
-#include <fstream.h>
-#endif //__MSVCDOTNET__
-
-#include "h_utl.h"
-#include "r_coreimage.h"
-#include <boost/thread/thread.hpp>
-#include <boost/thread/condition.hpp>
-#include <queue>
-
-#define DEFAULT_LOG_LEVEL 0x0
-#define LOG_LEVEL_FILE_DETAILS	0x00000001       // Destination file name (loglevel1)
-#define LOG_LEVEL_FILE_ATTRIBUTES 0x00000002     // File attributes (loglevel2)
-
-
-class CObeyFile;
-class MRofsImage;
-class Memmap;
-
-struct TPlacingSection {
-    TUint8* buf;
-    TInt len;
-    TRomNode* node;
-    TPlacingSection(TRomNode* anode){
-        node = anode;
-        buf = NULL;
-        len = 0;
-    }
-};
-class E32Rofs : public MRofsImage
-	{
-public:
-	E32Rofs(CObeyFile *aObey);
-	virtual ~E32Rofs();
-	TInt Create();
-
-	TInt CreateExtension(MRofsImage* info);
-	TInt WriteImage( TInt aHeaderType );
-
-	TRomNode* CopyDirectory(TRomNode*& aLastExecutable);
-	TRomNode* RootDirectory();
-	void SetRootDirectory(TRomNode* aDir);
-	TText* RomFileName();
-	TInt Size();
-	void MakeAutomaticSize(TUint32 aSize);
-
-        //Get a node to handle, if there is no more, NULL returns.
-        //For alias node, it will be deferred to later phase to handle.
-	TPlacingSection* GetFileNode(bool &aDeferred);
-        TPlacingSection* GetDeferredJob();
-        void ArriveDeferPoint();
-	void DisplaySizes(TPrintType aWhere);
-private:
-	TInt PlaceFiles( TRomNode* aRootDir, TUint8* aDestBase, TUint aBaseOffset, TInt aCoreSize = 0 );
-	TInt LayoutDirectory( TRomNode* aRootDir, TUint aBaseOffset );
-	TInt PlaceDirectory( TRomNode* aRootDir, TUint8* aDest );
-	void LogExecutableAttributes(E32ImageHeaderV *aHdr);
-
-
-	void Write(ofstream &of, TInt aHeaderType);		// main ROM image
-	Memmap* iImageMap;
-
-public:
-	char *iData;
-	TInt iSize;
-
-	TRofsHeader *iHeader;
-	TExtensionRofsHeader *iExtensionRofsHeader;	
-	//
-	CObeyFile *iObey;
-
-	//
-	TInt iSizeUsed;
-	TInt iOverhead;
-	TInt iDirectorySize;
-
-	TInt iTotalDirectoryBlockSize;
-	TInt iTotalFileBlockSize;
-	//
-
-private:
-	TRomNode *iLastNode;
-        int iWorkerArrived;
-        boost::mutex iMuxTree;
-        std::vector<TPlacingSection*> iVPS;
-        std::queue<TPlacingSection*> iQueueAliasNode;
-};
-
-
-class TRofsDirStructure
-	{
-	public:
-		TRofsDirStructure( TRomEntry* aRootDirectory );
-
-		TInt CalculateDirectorySize();
-
-	private:
-		TRomEntry* iRootDirectory;
-	};
-#endif
+/*
+* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifndef __R_ROFS_H__
+#define __R_ROFS_H__
+
+#include <e32rom.h>
+
+#include <fstream>
+
+#include "h_utl.h"
+#include "r_coreimage.h"
+#include <boost/thread/thread.hpp>
+#include <boost/thread/condition.hpp>
+#include <queue>
+
+#define DEFAULT_LOG_LEVEL 0x0
+#define LOG_LEVEL_FILE_DETAILS	0x00000001       // Destination file name (loglevel1)
+#define LOG_LEVEL_FILE_ATTRIBUTES 0x00000002     // File attributes (loglevel2)
+
+
+class CObeyFile;
+class MRofsImage;
+class Memmap;
+class SymbolGenerator;
+
+struct TPlacingSection {
+	TUint8* buf;
+	TInt len;
+	TRomNode* node;
+	TPlacingSection(TRomNode* anode){
+		node = anode;
+		buf = NULL;
+		len = 0;
+	}
+};
+class E32Rofs : public MRofsImage
+{
+public:
+	E32Rofs(CObeyFile *aObey);
+	virtual ~E32Rofs();
+	TInt Create();
+
+	TInt CreateExtension(MRofsImage* info);
+	TInt WriteImage( TInt aHeaderType );
+
+	TRomNode* CopyDirectory(TRomNode*& aLastExecutable);
+	TRomNode* RootDirectory();
+	void SetRootDirectory(TRomNode* aDir);
+	const char* RomFileName() const ;
+	TInt Size() const;
+	void MakeAutomaticSize(TUint32 aSize);
+
+	//Get a node to handle, if there is no more, NULL returns.
+	//For alias node, it will be deferred to later phase to handle.
+	TPlacingSection* GetFileNode(bool &aDeferred);
+	TPlacingSection* GetDeferredJob();
+	void ArriveDeferPoint();
+	void DisplaySizes(TPrintType aWhere);
+private:
+	TInt PlaceFiles( TRomNode* aRootDir, TUint8* aDestBase, TUint aBaseOffset, TInt aCoreSize = 0 );
+	TInt LayoutDirectory( TRomNode* aRootDir, TUint aBaseOffset );
+	TInt PlaceDirectory( TRomNode* aRootDir, TUint8* aDest );
+	void LogExecutableAttributes(E32ImageHeaderV *aHdr);
+
+
+	void Write(ofstream &of, TInt aHeaderType);		// main ROM image
+	Memmap* iImageMap;
+
+public:
+	char *iData;
+	TInt iSize;
+
+	TRofsHeader *iHeader;
+	TExtensionRofsHeader *iExtensionRofsHeader;	
+	//
+	CObeyFile *iObey;
+
+	//
+	TInt iSizeUsed;
+	TInt iOverhead;
+	TInt iDirectorySize;
+
+	TInt iTotalDirectoryBlockSize;
+	TInt iTotalFileBlockSize;
+	//
+        SymbolGenerator* iSymGen;
+
+private:
+	TRomNode *iLastNode;
+	int iWorkerArrived;
+	boost::mutex iMuxTree;
+	vector<TPlacingSection*> iVPS;
+	queue<TPlacingSection*> iQueueAliasNode;
+};
+
+
+class TRofsDirStructure
+{
+public:
+	TRofsDirStructure( TRomEntry* aRootDirectory );
+
+	TInt CalculateDirectorySize();
+
+private:
+	TRomEntry* iRootDirectory;
+};
+#endif
--- a/imgtools/romtools/rofsbuild/r_romnode.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rofsbuild/r_romnode.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,291 +1,286 @@
-/*
-* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifndef __R_ROMNODE_H__
-#define __R_ROMNODE_H__
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-#include <fstream>
-#else //!__MSVCDOTNET__
-#include <fstream.h>
-#endif //__MSVCDOTNET__
-
-#include <e32std.h>
-#include "rofs.h"
-#include "e32image.h"
-#include "h_utl.h"
-
-const TUint KOverrideStack = 0x01;
-const TUint KOverrideHeapMin = 0x02;
-const TUint KOverrideHeapMax = 0x04;
-const TUint KOverrideRelocationAddress = 0x08;
-const TUint KOverrideUid1 = 0x10;
-const TUint KOverrideUid2 = 0x20;
-const TUint KOverrideUid3 = 0x40;
-const TUint KOverrideCallEntryPoint = 0x80;
-const TUint KOverrideNoCallEntryPoint = 0x100;
-const TUint KOverridePriority = 0x200;
-const TUint KOverrideStackReserve = 0x400;
-const TUint KOverrideKeepIAT = 0x800;
-const TUint KOverrideCapability = 0x1000;
-const TUint KOverrideFixed = 0x2000;
-const TUint KOverrideDllData  = 0x4000;
-const TUint KOverrideCodeUnpaged = 0x8000;
-const TUint KOverrideCodePaged = 0x10000;
-const TUint KOverrideDataUnpaged = 0x20000;
-const TUint KOverrideDataPaged = 0x40000;
-
-enum ECompression{
-	ECompressionUnknown=0,
-	ECompressionCompress=1,
-	ECompressionUncompress=2
-};
-
-const TInt KFileHidden = 0xFFFFFFFF;
-
-
-
-class TRomBuilderEntry;
-class RomFileStructure;
-class TRomNode
-	{
-public:
-	TRomNode(TText* aName, TRomBuilderEntry* aEntry=0);
-	~TRomNode();
-	void Destroy();
-
-	static inline TRomNode* FirstNode() { return TheFirstNode; };
-	inline TRomNode* NextNode() { return iNextNode; };
-	inline void SetNextNode(TRomNode* aNode) { iNextNode = aNode; };
-	inline TRomNode* Currentchild() const { return iChild; };
-	inline TRomNode* Currentsibling() const { return iSibling; };
-
-	void DisplayStructure(ostream* aOut);
-	TRomNode* FindInDirectory(TText *aName);
-	void AddFile(TRomNode *aChild);
-	TRomNode* NewSubDir(TText *aName);
-	TInt SetAtt(TText *anAttWord);
-	TInt SetAttExtra(TText *anAttWord, TRomBuilderEntry* aFile, enum EKeyword aKeyword);
-	inline void SetStackSize(TInt aValue);
-	inline void SetHeapSizeMin(TInt aValue);
-	inline void SetHeapSizeMax(TInt aValue);
-	inline void SetCapability(SCapabilitySet& aCapability);
-	inline void SetUid1(TInt aValue);
-	inline void SetUid2(TInt aValue);
-	inline void SetUid3(TInt aValue);
-	inline void SetPriority(TProcessPriority aValue);
-	inline void SetFixed();
-	inline void SetDllData();
-
-
-	TBool IsDirectory() const { return 0==iEntry; };
-	TBool IsFile() const { return 0!=iEntry; };
-
-	TInt CalculateDirectoryEntrySize( TInt& aDirectoryBlockSize,
-										    TInt& aFileBlockSize );
-
-	TInt CountFileAndDir(TInt& aFileCount, TInt& aDirCount);
-
-	TInt PlaceFile( TUint8* &aDest, TUint aOffset, TUint aMaxSize, CBytePair *aBPE );
-	TInt Place( TUint8* aDestBase );
-
-	TInt NameCpy(char* aDest, TUint8& aUnicodeLength );
-	TInt NameLengthUnicode() const;
-
-	void Rename(TRomNode *aOldParent, TRomNode* aNewParent, TText* aNewName);
-
-	TRofsEntry* RofsEntry() const { return iRofsEntry; };
-	void SetRofsEntry(TRofsEntry* aEntry);
-	inline void SetImagePosition( TInt aPosition ) { iImagePosition = aPosition; };
-	inline void SetFileBlockPosition( TInt aPosition ) { iFileBlockPosition = aPosition; };
-	
-	void AddNodeForSameFile(TRomNode* aPreviousNode, TRomBuilderEntry* aFile);
-
-	void CountDirectory(TInt& aFileCount, TInt& aDirCount);
-	TInt ProcessDirectory(RomFileStructure* aRFS);
-
-	TRomNode* CopyDirectory(TRomNode*& aLastExecutable);
-	void Alias(TRomNode* aNode);
-	
-	static void deleteTheFirstNode();
-	static void displayFlatList();
-	TInt FullNameLength(TBool aIgnoreHiddenAttrib = EFalse) const;
-	TInt GetFullName(char* aBuf, TBool aIgnoreHiddenAttrib = EFalse) const;
-	static void InitializeCount();
-	// Accessor Function.
-    inline TRomNode* GetParent() const { return iParent; }
-
-private:
-	void Remove(TRomNode* aChild);
-	void Add(TRomNode* aChild);
-	void Clone(TRomNode* aOriginal);
-
-	TInt CalculateEntrySize() const;
-
-private:	
-	static TInt Count;			// seed for unique identifiers
-
-	// Flat linked list of TRomNode structures
-	static TRomNode*	TheFirstNode;
-	static TRomNode*	TheLastNode;
-	TRomNode* iNextNode;
-
-	TRomNode* iParent;
-	TRomNode* iSibling;
-	TRomNode* iChild;
-	TRomNode* iNextNodeForSameFile;
-
-protected:
-	TInt iIdentifier;
-	TRofsEntry* iRofsEntry;		// in ROM image buffer
-
-	TInt	iTotalDirectoryBlockSize;	// calculated size of directory block
-	TInt	iTotalFileBlockSize;		// calculated size of file block
-
-
-	TInt iImagePosition;		// position of directory entry in image
-	TInt iFileBlockPosition;	// position of directory file block in image
-
-	friend class FileEntry;
-
-public:
-	TText* iName;
-	TUint8 iAtt;
-	TUint8 iAttExtra;
-	TBool iHidden;
-	TRomBuilderEntry* iEntry;		// represents file data
-	TUint	iFileStartOffset;		// position in image of start of file
-	TInt iSize;			        // size of associated file
-
-	// Override values
-	TInt iStackSize;
-	TInt iHeapSizeMin;
-	TInt iHeapSizeMax;
-	SCapabilitySet iCapability;
-	TInt iUid1;
-	TInt iUid2;
-	TInt iUid3;
-	TProcessPriority iPriority;
-
-	TInt iOverride;
-	TBool iFileUpdate;
-  bool iAlias;
-  // for a ROM image, all the files have a default read-only attribute, but in data drive, files's default attribute should be 0 
-	static TUint8 sDefaultInitialAttr ;
-	};
-
-
-
-class DllDataEntry;
-class TRomBuilderEntry
-	{
-public:
-	TRomBuilderEntry(const char *aFileName, TText *aName);
-	~TRomBuilderEntry();
-	void SetRomNode(TRomNode* aNode);
-	TRofsEntry* RofsEntry() const {return iRomNode->RofsEntry(); };
-	TInt PlaceFile( TUint8* &aDest, TUint aMaxSize, CBytePair *aBPE );
-
-	inline TInt RealFileSize() const { return iRealFileSize; };
-	inline void SetRealFileSize(TInt aFileSize) { iRealFileSize=aFileSize;};
-	void DisplaySize(TPrintType aWhere);
-	
-private:
-	TRomBuilderEntry();
-	TRomBuilderEntry(const TRomBuilderEntry&);
-	const TRomBuilderEntry& operator==(const TRomBuilderEntry &);
-	DllDataEntry* iFirstDllDataEntry;
-
-public:
-	TText *iName;
-	char *iFileName;
-
-	TRomBuilderEntry* iNext;
-	TRomBuilderEntry* iNextInArea;
-	TBool iExecutable;
-	TBool iFileOffset; // offset of the file in ROM
-	TUint iCompressEnabled;
-	TUint8 iUids[sizeof(TCheckedUid)];
-	TBool iHidden;
-  	DllDataEntry* GetFirstDllDataEntry() const;
-	void SetFirstDllDataEntry(DllDataEntry *aDllDataEntry);
-
-private:
-	TRomNode *iRomNode;
-	TInt	iRealFileSize;	
-	};
-
-
-inline void TRomNode::SetStackSize(TInt aValue)
-	{
-	iStackSize = aValue;
-	iOverride |= KOverrideStack;
-	}
-
-inline void TRomNode::SetHeapSizeMin(TInt aValue)
-	{
-	iHeapSizeMin = aValue;
-	iOverride |= KOverrideHeapMin;
-	}
-
-inline void TRomNode::SetHeapSizeMax(TInt aValue)
-	{
-	iHeapSizeMax = aValue;
-	iOverride |= KOverrideHeapMax;
-	}
-
-inline void TRomNode::SetCapability(SCapabilitySet& aCapability)
-	{
-	iCapability = aCapability;
-	iOverride |= KOverrideCapability;
-	}
-
-inline void TRomNode::SetUid1(TInt aValue)
-	{
-	iUid1 = aValue;
-	iOverride |= KOverrideUid1;
-	}
-
-inline void TRomNode::SetUid2(TInt aValue)
-	{
-	iUid2 = aValue;
-	iOverride |= KOverrideUid2;
-	}
-
-inline void TRomNode::SetUid3(TInt aValue)
-	{
-	iUid3 = aValue;
-	iOverride |= KOverrideUid3;
-	}
-
-inline void TRomNode::SetPriority(TProcessPriority aValue)
-	{
-	iPriority = aValue;
-	iOverride |= KOverridePriority;
-	}
-
-inline void TRomNode::SetFixed()
-	{
-	iOverride |= KOverrideFixed;
-	}
-inline void TRomNode::SetDllData()
-{
-	iOverride |= KOverrideDllData;
-}
-
-#endif
+/*
+* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifndef __R_ROMNODE_H__
+#define __R_ROMNODE_H__
+
+#include <fstream>
+#include <e32std.h>
+#include "rofs.h"
+#include "e32image.h"
+#include "h_utl.h"
+
+const TUint KOverrideStack = 0x01;
+const TUint KOverrideHeapMin = 0x02;
+const TUint KOverrideHeapMax = 0x04;
+const TUint KOverrideRelocationAddress = 0x08;
+const TUint KOverrideUid1 = 0x10;
+const TUint KOverrideUid2 = 0x20;
+const TUint KOverrideUid3 = 0x40;
+const TUint KOverrideCallEntryPoint = 0x80;
+const TUint KOverrideNoCallEntryPoint = 0x100;
+const TUint KOverridePriority = 0x200;
+const TUint KOverrideStackReserve = 0x400;
+const TUint KOverrideKeepIAT = 0x800;
+const TUint KOverrideCapability = 0x1000;
+const TUint KOverrideFixed = 0x2000;
+const TUint KOverrideDllData  = 0x4000;
+const TUint KOverrideCodeUnpaged = 0x8000;
+const TUint KOverrideCodePaged = 0x10000;
+const TUint KOverrideDataUnpaged = 0x20000;
+const TUint KOverrideDataPaged = 0x40000;
+
+enum ECompression{
+	ECompressionUnknown=0,
+	ECompressionCompress=1,
+	ECompressionUncompress=2
+};
+
+const TInt KFileHidden = 0xFFFFFFFF;
+
+
+
+class TRomBuilderEntry;
+class RomFileStructure;
+class TRomNode
+	{
+public:
+	TRomNode(const char* aName, TRomBuilderEntry* aEntry = 0);
+	~TRomNode();
+	void Destroy();
+
+	static inline TRomNode* FirstNode() { return TheFirstNode; };
+	inline TRomNode* NextNode() { return iNextNode; };
+	inline void SetNextNode(TRomNode* aNode) { iNextNode = aNode; };
+	inline TRomNode* Currentchild() const { return iChild; };
+	inline TRomNode* Currentsibling() const { return iSibling; };
+
+	void DisplayStructure(ostream* aOut);
+	TRomNode* FindInDirectory(const char *aName) const;
+	void AddFile(TRomNode *aChild);
+	TRomNode* NewSubDir(const char *aName);
+	TInt SetAtt(char *anAttWord);
+	TInt SetAttExtra(char *anAttWord, TRomBuilderEntry* aFile, enum EKeyword aKeyword);
+	inline void SetStackSize(TInt aValue);
+	inline void SetHeapSizeMin(TInt aValue);
+	inline void SetHeapSizeMax(TInt aValue);
+	inline void SetCapability(SCapabilitySet& aCapability);
+	inline void SetUid1(TInt aValue);
+	inline void SetUid2(TInt aValue);
+	inline void SetUid3(TInt aValue);
+	inline void SetPriority(TProcessPriority aValue);
+	inline void SetFixed();
+	inline void SetDllData();
+
+
+	TBool IsDirectory() const { return 0 == iEntry; };
+	TBool IsFile() const { return 0!=iEntry; };
+
+	TInt CalculateDirectoryEntrySize( TInt& aDirectoryBlockSize,
+										    TInt& aFileBlockSize );
+
+	TInt CountFileAndDir(TInt& aFileCount, TInt& aDirCount);
+
+	TInt PlaceFile( TUint8* &aDest, TUint aOffset, TUint aMaxSize, CBytePair *aBPE );
+	TInt Place( TUint8* aDestBase ); 
+	
+	TInt NameCpy(char* aDest, TUint8& aUnicodeLength );
+	TInt NameLengthUnicode() const;
+
+	void Rename(TRomNode *aOldParent, TRomNode* aNewParent, const char* aNewName);
+
+	TRofsEntry* RofsEntry() const { return iRofsEntry; };
+	void SetRofsEntry(TRofsEntry* aEntry);
+	inline void SetImagePosition( TInt aPosition ) { iImagePosition = aPosition; };
+	inline void SetFileBlockPosition( TInt aPosition ) { iFileBlockPosition = aPosition; };
+	
+	void AddNodeForSameFile(TRomNode* aPreviousNode, TRomBuilderEntry* aFile);
+
+	void CountDirectory(TInt& aFileCount, TInt& aDirCount);
+	TInt ProcessDirectory(RomFileStructure* aRFS);
+
+	TRomNode* CopyDirectory(TRomNode*& aLastExecutable);
+	void Alias(TRomNode* aNode);
+	
+	static void deleteTheFirstNode();
+	static void displayFlatList();
+	TInt FullNameLength(TBool aIgnoreHiddenAttrib = EFalse) const;
+	TInt GetFullName(char* aBuf, TBool aIgnoreHiddenAttrib = EFalse) const;
+	static void InitializeCount();
+	// Accessor Function.
+    inline TRomNode* GetParent() const { return iParent; }
+
+private:
+	void Remove(TRomNode* aChild);
+	void Add(TRomNode* aChild);
+	void Clone(TRomNode* aOriginal);
+
+	TInt CalculateEntrySize() const;
+
+private:	
+	static TInt Count;			// seed for unique identifiers
+
+	// Flat linked list of TRomNode structures
+	static TRomNode*	TheFirstNode;
+	static TRomNode*	TheLastNode;
+	TRomNode* iNextNode;
+
+	TRomNode* iParent;
+	TRomNode* iSibling;
+	TRomNode* iChild;
+	TRomNode* iNextNodeForSameFile;
+
+protected:
+	TInt iIdentifier;
+	TRofsEntry* iRofsEntry;		// in ROM image buffer
+
+	TInt	iTotalDirectoryBlockSize;	// calculated size of directory block
+	TInt	iTotalFileBlockSize;		// calculated size of file block
+
+
+	TInt iImagePosition;		// position of directory entry in image
+	TInt iFileBlockPosition;	// position of directory file block in image
+
+	friend class FileEntry;
+
+public:
+	char* iName;
+	TUint8 iAtt;
+	TUint8 iAttExtra;
+	TBool iHidden;
+	TRomBuilderEntry* iEntry;		// represents file data
+	TUint	iFileStartOffset;		// position in image of start of file
+	TInt iSize;			        // size of associated file
+
+	// Override values
+	TInt iStackSize;
+	TInt iHeapSizeMin;
+	TInt iHeapSizeMax;
+	SCapabilitySet iCapability;
+	TInt iUid1;
+	TInt iUid2;
+	TInt iUid3;
+	TProcessPriority iPriority;
+
+	TInt iOverride;
+	TBool iFileUpdate;
+  bool iAlias;
+  // for a ROM image, all the files have a default read-only attribute, but in data drive, files's default attribute should be 0 
+	static TUint8 sDefaultInitialAttr ;
+	};
+
+
+
+class DllDataEntry;
+class TRomBuilderEntry
+	{
+public:
+	TRomBuilderEntry(const char *aFileName, const char *aName);
+	~TRomBuilderEntry();
+	void SetRomNode(TRomNode* aNode);
+	TRofsEntry* RofsEntry() const {return iRomNode->RofsEntry(); };
+	TInt PlaceFile( TUint8* &aDest, TUint aMaxSize, CBytePair *aBPE );
+
+	inline TInt RealFileSize() const { return iRealFileSize; };
+	inline void SetRealFileSize(TInt aFileSize) { iRealFileSize=aFileSize;};
+	void DisplaySize(TPrintType aWhere);
+	
+private:
+	TRomBuilderEntry();
+	TRomBuilderEntry(const TRomBuilderEntry&);
+	const TRomBuilderEntry& operator==(const TRomBuilderEntry &);
+	DllDataEntry* iFirstDllDataEntry;
+
+public:
+	char *iName;
+	char *iFileName;
+
+	TRomBuilderEntry* iNext;
+	TRomBuilderEntry* iNextInArea;
+	TBool iExecutable;
+	TBool iFileOffset; // offset of the file in ROM
+	TUint iCompressEnabled;
+	TUint8 iUids[sizeof(TCheckedUid)];
+	TBool iHidden;
+  	DllDataEntry* GetFirstDllDataEntry() const;
+	void SetFirstDllDataEntry(DllDataEntry *aDllDataEntry);
+
+private:
+	TRomNode *iRomNode;
+	TInt	iRealFileSize;	
+	};
+
+
+inline void TRomNode::SetStackSize(TInt aValue)
+	{
+	iStackSize = aValue;
+	iOverride |= KOverrideStack;
+	}
+
+inline void TRomNode::SetHeapSizeMin(TInt aValue)
+	{
+	iHeapSizeMin = aValue;
+	iOverride |= KOverrideHeapMin;
+	}
+
+inline void TRomNode::SetHeapSizeMax(TInt aValue)
+	{
+	iHeapSizeMax = aValue;
+	iOverride |= KOverrideHeapMax;
+	}
+
+inline void TRomNode::SetCapability(SCapabilitySet& aCapability)
+	{
+	iCapability = aCapability;
+	iOverride |= KOverrideCapability;
+	}
+
+inline void TRomNode::SetUid1(TInt aValue)
+	{
+	iUid1 = aValue;
+	iOverride |= KOverrideUid1;
+	}
+
+inline void TRomNode::SetUid2(TInt aValue)
+	{
+	iUid2 = aValue;
+	iOverride |= KOverrideUid2;
+	}
+
+inline void TRomNode::SetUid3(TInt aValue)
+	{
+	iUid3 = aValue;
+	iOverride |= KOverrideUid3;
+	}
+
+inline void TRomNode::SetPriority(TProcessPriority aValue)
+	{
+	iPriority = aValue;
+	iOverride |= KOverridePriority;
+	}
+
+inline void TRomNode::SetFixed()
+	{
+	iOverride |= KOverrideFixed;
+	}
+inline void TRomNode::SetDllData()
+{
+	iOverride |= KOverrideDllData;
+}
+
+#endif
--- a/imgtools/romtools/rofsbuild/r_smrimage.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rofsbuild/r_smrimage.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,227 +1,191 @@
-/*
-* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-
-#ifdef __VC32__
- #ifdef __MSVCDOTNET__
-  #include <strstream>
-  #include <iomanip>
- #else //__MSVCDOTNET__
-  #include <strstrea.h>
-  #include <iomanip.h>
- #endif  //__MSVCDOTNET__
-#else // !__VC32__
-#ifdef __TOOLS2__
-	#include <sstream>
-	#include <iomanip>
-	#include <sys/stat.h>
-	#include <new>
-	using namespace std;
-#else
-	#include <strstrea.h>
-	#include <iomanip.h>
-#endif
- 
-#endif //__VC32__
-#include <e32std.h>
-#include "h_utl.h"
-#include "r_smrimage.h"
-
-CSmrImage::CSmrImage(CObeyFile* aObeyFile)
-	:iObeyFile(aObeyFile)
-{	
-	HMem::Set(&iSmrRomHeader, 0, sizeof(SSmrRomHeader));
-}
-CSmrImage::~CSmrImage()
-{
-}
-TBool CSmrImage::SetImageName(const StringVector& aValues)
-{
-	if(aValues.size() == 0)
-	{
-		Print(EError, "Keyword Imageanme has not been set!");
-		return EFalse;
-
-	}
-	if(aValues.size() > 1)
-	{
-		Print(EError, "Keyword Imagename has been set more than one time!");
-		return EFalse;
-	}
-	iImageName = aValues.at(0);
-	if(iImageName.find(".img") == std::string::npos)
-	{
-		iImageName += ".img";
-	}
-	return ETrue;
-}
-TBool CSmrImage::SetFormatVersion(const StringVector& aValues)
-{
-	if(aValues.size() == 0)
-	{
-		Print(EError, "keyword formatversion has not been set!");
-		return EFalse;
-	}
-	if(aValues.size() > 1)
-	{
-		Print(EError, "Keyword Formatversion has been set more than one time!");
-		return EFalse;
-	}
-	iSmrRomHeader.iImageVersion = StrToInt(aValues.at(0).c_str());
-	return ETrue;
-}
-TBool CSmrImage::SetHcrData(const StringVector& aValues)
-{
-	
-	if(aValues.size() == 0)
-	{
-		Print(EError, "keyword hcrdata has not been set!");
-		return EFalse;
-	}
-	if(aValues.size() > 1)
-	{
-		Print(EError, "Keyword hcrdata has been set more than one time!");
-		return EFalse;
-	}
-	iHcrData = aValues.at(0);
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-	ifstream is(iHcrData.c_str(), ios_base::binary );
-#else //!__MSVCDOTNET__
-	ifstream is(iHcrData.c_str(), ios::nocreate | ios::binary ); 
-#endif //__MSVCDOTNET__
-	if(!is)
-	{
-		Print(EError, "HCR data file: %s dose not exist!", iHcrData.c_str());
-		return EFalse;
-	}
-	TUint32 magicWord = 0;
-	is.read(reinterpret_cast<char*>(&magicWord),sizeof(TUint32));
-	if(0x66524348 != magicWord){
-		Print(EError, "HCR data file: %s is an invalid HCR data file!", iHcrData.c_str());
-		return EFalse;
-	}
-	is.close();
-	return ETrue;
-}
-TBool CSmrImage::SetPayloadUID(const StringVector& aValues)
-{
-
-	if(aValues.size() == 0)
-	{
-		Print(EError, "keyword PayloadUID has not been set!");
-		return EFalse;
-	}
-	if(aValues.size() > 1)
-	{
-		Print(EError, "Keyword PayloadUID has been set more than one time!");
-		return EFalse;
-	}
-	iSmrRomHeader.iPayloadUID = StrToInt(aValues.at(0).c_str());
-	return ETrue;
-}
-TBool CSmrImage::SetPayloadFlags(const StringVector& aValues)
-{
-
-	if(aValues.size() == 0)
-	{
-		Print(EError, "keyword Payloadflags has not been set!");
-		return EFalse;
-	}
-	if(aValues.size() > 1)
-	{
-		Print(EError, "Keyword Payloadfalgs has been set more than one time!");
-		return EFalse;
-	}
-	iSmrRomHeader.iPayloadFlags = StrToInt(aValues.at(0).c_str());
-	return ETrue;
-}
-TUint32 CSmrImage::StrToInt(const char* aStr)
-{
-
-	TUint32 value;
-#ifdef __TOOLS2__
-	istringstream val(aStr);
-#else
-	istrstream val(aStr, strlen(aStr));
-#endif
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-	val >> setbase(0);
-#endif //__MSVCDOTNET
-	val >> value;
-	return value;
-}
-TInt CSmrImage::Initialise()
-{
-	TInt result = KErrGeneral;
-	if(! SetImageName(iObeyFile->getValues("imagename")))
-		return result;
-	if(! SetFormatVersion(iObeyFile->getValues("formatversion")))
-		return result;
-	if(! SetHcrData(iObeyFile->getValues("hcrdata")))
-		return result;
-	if(! SetPayloadUID(iObeyFile->getValues("payloaduid")))
-		return result;
-	if(! SetPayloadFlags(iObeyFile->getValues("payloadflags")))
-		return result;
-	result = KErrNone;
-	return result;
-}
-TInt CSmrImage::CreateImage()
-{
-	TInt imageSize = 0;
-	ifstream is;
-	is.open(iHcrData.c_str(), ios::binary);
-	if(!is)
-	{
-		Print(EError, "Open HCR data file: %s error!\n", iHcrData.c_str());
-		return KErrGeneral;
-	}
-	is.seekg(0, ios::end);
-	TInt fsize = is.tellg();
-	imageSize = sizeof(SSmrRomHeader) + fsize;
-	imageSize += (4 - imageSize) & 3;
-	char* vImage = new (std::nothrow) char[imageSize];
-	if(vImage == NULL)
-	{
-		Print(EError, "Not enough system memory generate SMR partition!\n");
-		return KErrNoMemory;
-	}
-	HMem::Set(vImage, 0, imageSize);
-	HMem::Copy(vImage, &iSmrRomHeader, sizeof(SSmrRomHeader));
-	SSmrRomHeader* pSmrHeader = (SSmrRomHeader *) vImage;
-	pSmrHeader->iFingerPrint[0] = 0x5F524D53;
-	pSmrHeader->iFingerPrint[1] = 0x54524150;
-	is.seekg(0, ios::beg);
-	is.read(vImage + sizeof(SSmrRomHeader), fsize);
-	pSmrHeader->iPayloadChecksum = HMem::CheckSum((TUint *)(vImage + sizeof(SSmrRomHeader)), imageSize - sizeof(SSmrRomHeader));
-	pSmrHeader->iImageSize = imageSize;
-	pSmrHeader->iImageTimestamp = time(0);
-	ofstream os(iImageName.c_str(), ios::binary);
-	os.write(vImage, imageSize);
-	os.close();
-	is.close();
-	delete[] vImage;
-	
-	
-	return KErrNone;
-
-
-}
+/*
+* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+ 
+#include <strstream>
+#include <iomanip> 
+ 
+#include <e32std.h>
+#include "h_utl.h"
+#include "r_smrimage.h"
+using namespace std; 
+CSmrImage::CSmrImage(CObeyFile* aObeyFile)
+	:iObeyFile(aObeyFile)
+{	
+	HMem::Set(&iSmrRomHeader, 0, sizeof(SSmrRomHeader));
+}
+CSmrImage::~CSmrImage()
+{
+}
+TBool CSmrImage::SetImageName(const StringVector& aValues)
+{
+	if(aValues.size() == 0)
+	{
+		Print(EError, "Keyword Imageanme has not been set!");
+		return EFalse;
+
+	}
+	if(aValues.size() > 1)
+	{
+		Print(EError, "Keyword Imagename has been set more than one time!");
+		return EFalse;
+	}
+	iImageName = aValues.at(0);
+	if(iImageName.find(".img") == string::npos)
+	{
+		iImageName += ".img";
+	}
+	return ETrue;
+}
+TBool CSmrImage::SetFormatVersion(const StringVector& aValues)
+{
+	if(aValues.size() == 0)
+	{
+		Print(EError, "keyword formatversion has not been set!");
+		return EFalse;
+	}
+	if(aValues.size() > 1)
+	{
+		Print(EError, "Keyword Formatversion has been set more than one time!");
+		return EFalse;
+	}
+	Val(iSmrRomHeader.iImageVersion,aValues.at(0).c_str()); 
+	return ETrue;
+}
+TBool CSmrImage::SetHcrData(const StringVector& aValues)
+{
+	
+	if(aValues.size() == 0)
+	{
+		Print(EError, "keyword hcrdata has not been set!");
+		return EFalse;
+	}
+	if(aValues.size() > 1)
+	{
+		Print(EError, "Keyword hcrdata has been set more than one time!");
+		return EFalse;
+	}
+	iHcrData = aValues.at(0);
+
+	ifstream is(iHcrData.c_str(), ios_base::binary );
+	if(!is)
+	{
+		Print(EError, "HCR data file: %s dose not exist!", iHcrData.c_str());
+		return EFalse;
+	}
+	TUint32 magicWord = 0;
+	is.read(reinterpret_cast<char*>(&magicWord),sizeof(TUint32));
+	if(0x66524348 != magicWord){
+		Print(EError, "HCR data file: %s is an invalid HCR data file!", iHcrData.c_str());
+		return EFalse;
+	}
+	is.close();
+	return ETrue;
+}
+TBool CSmrImage::SetPayloadUID(const StringVector& aValues)
+{
+
+	if(aValues.size() == 0)
+	{
+		Print(EError, "keyword PayloadUID has not been set!");
+		return EFalse;
+	}
+	if(aValues.size() > 1)
+	{
+		Print(EError, "Keyword PayloadUID has been set more than one time!");
+		return EFalse;
+	}
+	Val(iSmrRomHeader.iPayloadUID,aValues.at(0).c_str()); 
+	return ETrue;
+}
+TBool CSmrImage::SetPayloadFlags(const StringVector& aValues)
+{
+
+	if(aValues.size() == 0)
+	{
+		Print(EError, "keyword Payloadflags has not been set!");
+		return EFalse;
+	}
+	if(aValues.size() > 1)
+	{
+		Print(EError, "Keyword Payloadfalgs has been set more than one time!");
+		return EFalse;
+	}
+	Val(iSmrRomHeader.iPayloadFlags , aValues.at(0).c_str());
+	return ETrue;
+}
+
+TInt CSmrImage::Initialise()
+{
+	TInt result = KErrGeneral;
+	if(! SetImageName(iObeyFile->getValues("imagename")))
+		return result;
+	if(! SetFormatVersion(iObeyFile->getValues("formatversion")))
+		return result;
+	if(! SetHcrData(iObeyFile->getValues("hcrdata")))
+		return result;
+	if(! SetPayloadUID(iObeyFile->getValues("payloaduid")))
+		return result;
+	if(! SetPayloadFlags(iObeyFile->getValues("payloadflags")))
+		return result;
+	result = KErrNone;
+	return result;
+}
+TInt CSmrImage::CreateImage()
+{
+	TInt imageSize = 0;
+	ifstream is;
+	is.open(iHcrData.c_str(), ios_base::binary);
+	if(!is)
+	{
+		Print(EError, "Open HCR data file: %s error!\n", iHcrData.c_str());
+		return KErrGeneral;
+	}
+	is.seekg(0, ios_base::end);
+	TInt fsize = is.tellg();
+	imageSize = sizeof(SSmrRomHeader) + fsize;
+	imageSize += (4 - imageSize) & 3;
+	char* vImage = new (nothrow) char[imageSize];
+	if(vImage == NULL)
+	{
+		Print(EError, "Not enough system memory generate SMR partition!\n");
+		return KErrNoMemory;
+	}
+	HMem::Set(vImage, 0, imageSize);
+	HMem::Copy(vImage, &iSmrRomHeader, sizeof(SSmrRomHeader));
+	SSmrRomHeader* pSmrHeader = (SSmrRomHeader *) vImage;
+	pSmrHeader->iFingerPrint[0] = 0x5F524D53;
+	pSmrHeader->iFingerPrint[1] = 0x54524150;
+	is.seekg(0, ios_base::beg);
+	is.read(vImage + sizeof(SSmrRomHeader), fsize);
+	pSmrHeader->iPayloadChecksum = HMem::CheckSum((TUint *)(vImage + sizeof(SSmrRomHeader)), imageSize - sizeof(SSmrRomHeader));
+	pSmrHeader->iImageSize = imageSize;
+	pSmrHeader->iImageTimestamp = time(0);
+	ofstream os(iImageName.c_str(), ios_base::binary);
+	os.write(vImage, imageSize);
+	os.close();
+	is.close();
+	delete[] vImage;	
+	
+	return KErrNone;
+
+
+}
--- a/imgtools/romtools/rofsbuild/r_smrimage.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rofsbuild/r_smrimage.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,46 +1,44 @@
-/*
-* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifndef __R_SMRIAMGE_H__
-#define __R_SMRIAMGE_H__
-#include "r_obey.h"
-
-class CSmrImage
-{
-public:
-	CSmrImage(CObeyFile* aObeyFile);
-	~CSmrImage();
-	TInt CreateImage();
-	TBool SetImageName(const StringVector& aValues);
-	TBool SetFormatVersion(const StringVector& aValues);
-	TBool SetHcrData(const StringVector& aValues);
-	TBool SetPayloadUID(const StringVector& aValues);
-	TBool SetPayloadFlags(const StringVector& aValues);
-	TInt Initialise();
-	String GetImageName(){ return iImageName; };
-private:
-	CObeyFile* iObeyFile;
-	SSmrRomHeader iSmrRomHeader;
-	String iImageName;
-	String iHcrData;
-private:
-	TUint32 StrToInt(const char* aStr);
-
-};
-
-#endif
+/*
+* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifndef __R_SMRIAMGE_H__
+#define __R_SMRIAMGE_H__
+#include "r_obey.h"
+
+class CSmrImage
+{
+public:
+	CSmrImage(CObeyFile* aObeyFile);
+	~CSmrImage();
+	TInt CreateImage();
+	TBool SetImageName(const StringVector& aValues);
+	TBool SetFormatVersion(const StringVector& aValues);
+	TBool SetHcrData(const StringVector& aValues);
+	TBool SetPayloadUID(const StringVector& aValues);
+	TBool SetPayloadFlags(const StringVector& aValues);
+	TInt Initialise();
+	string GetImageName() const { return iImageName; };
+private:
+	CObeyFile* iObeyFile;
+	SSmrRomHeader iSmrRomHeader;
+	string iImageName;
+	string iHcrData; 
+
+};
+
+#endif
--- a/imgtools/romtools/rofsbuild/rofsbuild.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rofsbuild/rofsbuild.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,728 +1,672 @@
-/*
-* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* @internalComponent * @released
-* Rofsbuild mainfile to generate both rofs and data drive image.
-*
-*/
-
-
-#include <string.h>
-#include <stdlib.h>
-#include <f32file.h>
-#include "e32image.h"
-#include "h_utl.h"
-#include "h_ver.h"
-#include "r_obey.h"
-#include "r_driveimage.h"
-#include "r_driveutl.h"
-#include "r_coreimage.h"
-#include "parameterfileprocessor.h"
-#include "r_smrimage.h"
-
-static const TInt RofsbuildMajorVersion=2;
-static const TInt RofsbuildMinorVersion=6;
-static const TInt RofsbuildPatchVersion=5;
-static TBool SizeSummary=EFalse;
-static TPrintType SizeWhere=EAlways;
-
-static TInt gHeaderType=1;			// EPOC header
-static TInt MAXIMUM_THREADS = 128;
-static TInt DEFAULT_THREADS = 8;
-ECompression gCompress=ECompressionUnknown;
-TUint  gCompressionMethod=0;
-TBool gFastCompress = EFalse;
-TInt gThreadNum = 0;
-TInt gCPUNum = 0;
-char* g_pCharCPUNum = NULL;
-TInt gCodePagingOverride = -1;
-TInt gDataPagingOverride = -1;
-TInt gLogLevel = 0;	// Information is logged based on logging level.
-					// The default is 0. So all the existing logs are generated as if gLogLevel = 0.
-					// If any extra information required, the log level must be appropriately supplied.
-					// Currrently, file details in ROM (like, file name in ROM & host, file size, whether 
-					// the file is hidden etc) are logged when gLogLevel >= LOG_LEVEL_FILE_DETAILS.
-
-TBool gUseCoreImage=EFalse; // command line option for using core image file
-char* gImageFilename=NULL;	// instead of obey file
-TBool gEnableStdPathWarning=EFalse;// for in-correct destination path warning(executables).
-TBool gLowMem=EFalse;
-
-extern TBool gDriveImage;		// to Support data drive image.
-TText* gDriveFilename=NULL;		// input drive oby filename.
-
-string filename;				// to store oby filename passed to Rofsbuild.
-TBool reallyHelp=EFalse;	
-
-TBool gSmrImage = EFalse;
-TText* gSmrFileName = NULL;
-
-void PrintVersion()
-	{
-		Print(EAlways,"\nROFSBUILD - Rofs/Datadrive image builder");
-		Print(EAlways, " V%d.%d.%d\n", RofsbuildMajorVersion, RofsbuildMinorVersion, RofsbuildPatchVersion);
-		Print(EAlways,Copyright);
-	}
-
-char HelpText[] = 
-	"Syntax: ROFSBUILD [options] obeyfilename(Rofs)\n"
-	"Option: -v verbose,  -?,  -s[log|screen|both] size summary\n"
-	"        -d<bitmask> set trace mask (DEB build only)\n"
-	"        -compress   compress executable files where possible\n"
-	"        -fastcompress  compress files with faster bytepair and tradeoff of compress ratio\n"
-	"        -j<digit> do the main job with <digit> threads\n"
-	"        -compressionmethod none|inflate|bytepair to set the compression\n"
-	"              none     uncompress the image.\n"
-	"              inflate  compress the image.\n"
-	"              bytepair compress the image.\n"
-	"        -coreimage <core image file>\n"
-	"        -datadrive=<drive obyfile1>,<drive obyfile2>,... for driveimage creation\n"
-	"              user can also input rofs oby file if required to generate both.\n"
-	"        -smr=<SMR obyfile1>,<SMR obyfile2>,... for SMR partition creation\n"
-	"        -loglevel<level>  level of information to log (valid levels are 0,1,2).\n"//Tools like Visual ROM builder need the host/ROM filenames, size & if the file is hidden.
-	"        -wstdpath   warn if destination path provided for a file is not the standard path\n"
-	"        -argfile=<FileName>   specify argument-file name containing list of command-line arguments\n"
-	"        -lowmem     use memory-mapped file for image build to reduce physical memory consumption\n";
-
-char ReallyHelpText[] =
-	"Log Level:\n"
-	"        0  produce the default logs\n"
-	"        1  produce file detail logs in addition to the default logs\n"
-	"        2  logs e32 header attributes in addition to the level 1 details\n";
-
-void processParamfile(string aFileName);
-
-/**
-Process the command line arguments and prints the helpful message if none are supplied.
-@param argc    - No. of argument.
-@param *argv[] - Arguments value.
-*/ 
-void processCommandLine(int argc, char *argv[], TBool paramFileFlag=EFalse)
-{
-	// If "-argfile" option is passed to rofsbuild, then process the parameters
-	// specified in parameter-file first and then the options passed from the 
-	// command-line.
-	string ParamFileArg("-ARGFILE=");	
-	if(paramFileFlag == EFalse)
-	{	
-		for (int count=1; count<argc; count++)
-		{
-			string paramFile;
-			strupr(argv[count]);
-			if(strncmp(argv[count],ParamFileArg.c_str(),ParamFileArg.length())==0)
-			{
-				paramFile.assign(&argv[count][ParamFileArg.length()]);									
-				processParamfile(paramFile);
-			}
-		}
-	}	
-
-	int i=1;
-	while (i<argc)
-		{
-		strupr(argv[i]);
-		if ((argv[i][0] == '-') || (argv[i][0] == '/'))
-			{ // switch
-			if (argv[i][1] == 'V')
-				H.iVerbose = ETrue;
-			else if(strncmp (argv[i], "-SMR=", 5) == 0)
-			{
-				if(argv[i][5])
-				{
-					gSmrImage = ETrue;
-					gSmrFileName = (TText*)strdup(&argv[i][5]);
-				}
-				else
-				{
-					Print (EError, "SMR obey file is missing\n");
-				}
-			}
-			else if (argv[i][1] == 'S')
-				{
-				SizeSummary=ETrue;
-				if (argv[i][2] == 'L')
-					SizeWhere=ELog;
-				if (argv[i][2] == 'S')
-					SizeWhere=EScreen;
-				}
-			else if (strncmp(argv[i],ParamFileArg.c_str(),ParamFileArg.length())==0)
-				{
-					if (paramFileFlag)
-					{
-						String paramFile;
-						paramFile.assign(&argv[i][ParamFileArg.length()]);		
-						processParamfile(paramFile);
-					}
-					else
-					{
-						i++;
-						continue;
-					}
-				}
-			else if (strcmp(argv[i], "-COMPRESS")==0)
-				{
-				gCompress=ECompressionCompress;
-				gCompressionMethod = KUidCompressionDeflate;
-				}
-			else if (strcmp(argv[i], "-FASTCOMPRESS")==0)
-				{
-				gFastCompress=ETrue;
-				}
-			else if (strncmp(argv[i], "-J",2)==0)
-				{
-					if(argv[i][2])
-						gThreadNum = atoi(&argv[i][2]);
-					else
-						{
-						printf("WARNING: The option should be like '-j4'.\n");
-						gThreadNum = 0;
-						}
-					if(gThreadNum <= 0 || gThreadNum > MAXIMUM_THREADS)
-						{
-						if(gCPUNum > 0 && gCPUNum <= MAXIMUM_THREADS)
-							{
-							printf("WARNING: The number of concurrent jobs set by -j should be between 1 and 128. And the number of processors %d will be used as the number of concurrent jobs.\n", gCPUNum);
-							gThreadNum = gCPUNum;
-							}
-						else if(g_pCharCPUNum)
-							{
-							printf("WARNING: The number of concurrent jobs set by -j should be between 1 and 128. And the NUMBER_OF_PROCESSORS is invalid, so the default value %d will be used.\n", DEFAULT_THREADS);
-							gThreadNum = DEFAULT_THREADS;
-							}
-						else
-							{
-							printf("WARNING: The number of concurrent jobs set by -j should be between 1 and 128. And the NUMBER_OF_PROCESSORS is not available, so the default value %d will be used.\n", DEFAULT_THREADS);
-							gThreadNum = DEFAULT_THREADS;
-							}
-						}
-				}
-			else if (strcmp(argv[i], "-UNCOMPRESS")==0)
-				{
-				gCompress=ECompressionUncompress;
-				}
-			else if( strcmp(argv[i], "-COMPRESSIONMETHOD") == 0 )
-				{
-					// next argument should a be method
-					if( (i+1) >= argc || argv[i+1][0] == '-') 
-					{
-					Print (EError, "Missing compression method! Set it to default (no compression)!");
-					gCompressionMethod = 0;
-					}
-					else 
-					{
-					i++;
-					strupr(argv[i]);
-					if( strcmp(argv[i], "NONE") == 0)	
-						{
-						gCompress=ECompressionUncompress;
-						gCompressionMethod = 0;	
-						}
-					else if( strcmp(argv[i], "INFLATE") == 0)
-						{
-						gCompress=ECompressionCompress;
-						gCompressionMethod = KUidCompressionDeflate;	
-						}	
-					else if( strcmp(argv[i], "BYTEPAIR") == 0)
-						{
-						gCompress=ECompressionCompress;
-						gCompressionMethod = KUidCompressionBytePair;	
-						}
-					else
-						{
-						Print (EError, "Unknown compression method! Set it to default (no compression)!");
-						gCompress=ECompressionUnknown;
-						gCompressionMethod = 0;		
-						}
-					}
-					
-				}
-			else if (strcmp(argv[i], "-COREIMAGE") ==0)
-				{
-					gUseCoreImage = ETrue;
-
-					// next argument should be image filename
-					if ((i+1 >= argc) || argv[i+1][0] == '-')
-						Print (EError, "Missing image file name");
-					else
-					{
-						i++;
-						gImageFilename = strdup(argv[i]);
-					}
-				}
-			else if (strncmp(argv[i], "-DATADRIVE=",11) ==0)
-				{  
-				   	if(argv[i][11])	
-						{
-						gDriveImage = ETrue; 
-						gDriveFilename = (TText*)strdup(&argv[i][11]);	
-						}
-					else
-						{
-						Print (EError, "Drive obey file is missing\n"); 
-						}
-				}
-			else if (argv[i][1] == '?')
-				{
-				reallyHelp=ETrue;
-				}
- 			else if (strcmp(argv[i], "-WSTDPATH") ==0)		// Warn if destination path provided for a executables are incorrect as per platsec.		
- 				{
- 				gEnableStdPathWarning=ETrue;						
- 				}
-			
-			else if( strcmp(argv[i], "-LOGLEVEL") == 0)
-				{
-				// next argument should a be loglevel
-				if( (i+1) >= argc || argv[i+1][0] == '-')
-					{
-					Print (EError, "Missing loglevel!");
-					gLogLevel = DEFAULT_LOG_LEVEL;
-					}
-				else
-					{
-					i++;
-					if (strcmp(argv[i], "2") == 0)
-						gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES);
-					if (strcmp(argv[i], "1") == 0)
-						gLogLevel = LOG_LEVEL_FILE_DETAILS;
-					else if (strcmp(argv[i], "0") == 0)
-						gLogLevel = DEFAULT_LOG_LEVEL;
-					else
-						Print(EError, "Only loglevel 0, 1 or 2 is allowed!");
-					}
-				}
-			else if( strcmp(argv[i], "-LOGLEVEL2") == 0)
-				gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES);
-			else if( strcmp(argv[i], "-LOGLEVEL1") == 0)
-				gLogLevel = LOG_LEVEL_FILE_DETAILS;
-			else if( strcmp(argv[i], "-LOGLEVEL0") == 0)
-				gLogLevel = DEFAULT_LOG_LEVEL;
-			else if (strcmp(argv[i], "-LOWMEM") == 0)
-				gLowMem = ETrue;
-			else 
-				cout << "Unrecognised option " << argv[i] << "\n";
-			}
-		else // Must be the obey filename
-			filename=argv[i];
-		i++;
-		}
-	
-		if (paramFileFlag)
-		return;
-
-		if((gDriveImage == EFalse) && (gSmrImage ==  EFalse) && (filename.empty() || (gUseCoreImage && gImageFilename == NULL)))
-		{
-		PrintVersion();
-		cout << HelpText;
-		if (reallyHelp)
-			{
-			ObeyFileReader::KeywordHelp();
-			cout << ReallyHelpText;
-			}
-		else if (filename.empty())
-			{
-			Print(EError, "Obey filename is missing\n");
-			}
-		}	
-	}
-
-/**
-Function to process parameter-file. 
-
-@param aFileName parameter-file name.
-*/
-void processParamfile(string aFileName)
-{
-	CParameterFileProcessor parameterFile(aFileName);
-	
-	// Invoke fuction "ParameterFileProcessor" to process parameter-file.
-	if(parameterFile.ParameterFileProcessor())
-	{
-		TUint noOfParameters = parameterFile.GetNoOfArguments();
-		char** parameters = parameterFile.GetParameters();
-		TBool paramFileFlag=ETrue;
-
-		// Invoke function "processCommandLine" to process parameters read from parameter-file.
-		processCommandLine(noOfParameters,parameters,paramFileFlag);
-	}	
-}
-
-/**
-Main logic for data drive image creation. Called many types depending on no. of drive obey files.
-
-@param aobeyFileName - Drive obey file.
-@param alogfile      - log file name required for file system module.
- 
-@return - returns the status, after processing the drive obey file.
-*/ 
-TInt ProcessDataDriveMain(TText* aobeyFileName,TText* alogfile)
-	{
-
-	ObeyFileReader *reader=new ObeyFileReader(aobeyFileName);
-
-	if(!reader)
-		return KErrNoMemory;
-
-	if(!reader->Open())
-    {
-        if (reader)
-        {
-            delete reader;
-        }
-		return KErrGeneral;
-    }
-
-	TInt retstatus =0;		
-	CObeyFile* mainObeyFile=new CObeyFile(*reader);   
-	CDriveImage* userImage = 0; 
-
-	if(!mainObeyFile)
-    {
-        if (reader)
-        {
-            delete reader;
-        }
-		return KErrNoMemory;
-    }
-
-	// Process data drive image.
-	// let's clear the TRomNode::sDefaultInitialAttr first, 'cause data drive is different from rom image
-	TRomNode::sDefaultInitialAttr = 0; 
-	retstatus = mainObeyFile->ProcessDataDrive();
-	if (retstatus == KErrNone)
-		{
-		// Build a Data drive image using the description compiled into the CObeyFile object
-		userImage = new CDriveImage(mainObeyFile);
-		if(userImage)
-			{	
-			// Drive image creation.
-			retstatus = userImage->CreateImage(alogfile);
-			if(retstatus == KErrNone)
-				{
-				cout << "\nSuccessfully generated the Drive image : " << mainObeyFile->iDriveFileName << "\n";
-				}
-			else
-				{
-				cout << "\nFailed to generate the Image : " << mainObeyFile->iDriveFileName << "\n";
-				}
-
-			delete userImage;
-			userImage = 0;
-			}
-		else
-			{
-			retstatus = KErrNoMemory;
-			}
-		}
-	// restore
-	TRomNode::sDefaultInitialAttr = (TUint8)KEntryAttReadOnly;
-	cout << "\n-----------------------------------------------------------\n";
-	
-	delete mainObeyFile;
-	delete reader;
-	return retstatus;
-	}
-
-TInt ProcessSmrImageMain(TText* aObeyFileName, TText* /* alogfile */)
-{
-	ObeyFileReader *reader = new ObeyFileReader(aObeyFileName);
-	if(!reader)
-		return KErrNoMemory;
-	if(!reader->Open())
-    {
-        if (reader)
-        {
-            delete reader;
-        }
-		return KErrGeneral;
-    }
-	TInt retstatus = 0;
-	CObeyFile* mainObeyFile = new CObeyFile(*reader);
-	CSmrImage* smrImage = 0;
-	if(!mainObeyFile)
-    {
-        if (reader)
-        {
-            delete reader;
-        }
-		return KErrNoMemory;
-    }
-
-	if(mainObeyFile->Process())
-	{
-		smrImage = new CSmrImage(mainObeyFile);
-		if(smrImage)
-		{
-			if((retstatus=smrImage->Initialise()) == KErrNone)
-			{
-				retstatus = smrImage->CreateImage();
-			}
-			if(retstatus == KErrNone)
-			{
-				cout << "\nSuccessfully generated the SMR image : " << smrImage->GetImageName().c_str() << "\n";
-			}
-			else
-			{
-				cout << "\nFailed to generate the Image : " << smrImage->GetImageName().c_str() << "\n";
-			}
-			delete smrImage;
-		}
-		else
-		{
-			retstatus = KErrNoMemory;
-		}
-	}
-	delete mainObeyFile;
-	delete reader;
-	return retstatus;
-}
-
-/**
-Rofsbuild Main function, which creates both Rofs and Data drive image.
-
-@param argc    - No. of argument.
-@param *argv[] - Arguments value.
-  
-@return - returns the status to caller.
-*/ 
-TInt main(int argc, char *argv[])
-{
-	TInt r =0;	
-
-	g_pCharCPUNum = getenv("NUMBER_OF_PROCESSORS");
-	if(g_pCharCPUNum != NULL)
-		gCPUNum = atoi(g_pCharCPUNum);
-
- 	processCommandLine(argc, argv);
-
- 	TText *obeyFileName = NULL;	
- 	if(!filename.empty())
- 		obeyFileName=(TText*)filename.c_str();	
-
-	if ((obeyFileName==NULL) && (gDriveFilename==NULL) && (gSmrFileName == NULL))                   
-		return KErrGeneral;
-	
-	if(gThreadNum == 0)
-	{
-		if(gCPUNum > 0 && gCPUNum <= MAXIMUM_THREADS)
-		{
-			printf("The number of processors (%d) is used as the number of concurrent jobs.\n", gCPUNum);
-			gThreadNum = gCPUNum;
-		}
-		else if(g_pCharCPUNum)
-		{
-			printf("WARNING: The NUMBER_OF_PROCESSORS is invalid, and the default value %d will be used.\n", DEFAULT_THREADS);
-			gThreadNum = DEFAULT_THREADS;
-		}
-		else
-		{
-			printf("WARNING: The NUMBER_OF_PROCESSORS is not available, and the default value %d will be used.\n", DEFAULT_THREADS);
-			gThreadNum = DEFAULT_THREADS;
-		}
-	}
-
-	// Process drive obey files.
-	if(gDriveImage)
-	{  
-		TText temp = 0;
-		TText *driveobeyFileName = gDriveFilename;
-		
-		do
-		{
-			while(((temp = *gDriveFilename++) != ',') && (temp != 0));
-			*(--gDriveFilename)++ = 0;
-			
-			if(*driveobeyFileName)
-			{	
-				TText* logfile = 0;
-				if(Getlogfile(driveobeyFileName,logfile)== KErrNone)
-				{
-					H.SetLogFile(logfile);	
-					PrintVersion();
-					GetLocalTime();
-					r = ProcessDataDriveMain(driveobeyFileName,logfile);   
-					H.CloseLogFile();
-					delete[] logfile;
-					if(r == KErrNoMemory)
-						return KErrNoMemory;
-				}
-				else
-				{
-					cout << "Error : Invalid obey file name : " << driveobeyFileName << "\n" ;   
-				}
-			}
-			driveobeyFileName = gDriveFilename;
-		}
-		while(temp != 0);   
-		
-		gDriveImage=EFalse;
-	} 
-	if(gSmrImage)
-	{
-		TText temp = 0;
-		TText *smrImageObeyFileName = gSmrFileName;
-		do
-		{
-			while(((temp = *gSmrFileName++) != ',') && (temp != 0));
-			*(--gSmrFileName)++ = 0;
-			if(*smrImageObeyFileName)
-			{	
-				TText * logfile = 0;
-				if(Getlogfile(smrImageObeyFileName,logfile) == KErrNone)
-				{
-					H.SetLogFile(logfile);
-					PrintVersion();
-					GetLocalTime();
-					r = ProcessSmrImageMain(smrImageObeyFileName, logfile);
-					H.CloseLogFile();
-					delete[] logfile;
-					if(r == KErrNoMemory)
-						return KErrNoMemory;
-				}
-				else
-				{
-					cout << "Error: Invalid obey file name: " << smrImageObeyFileName << "\n";
-				}
-			}
-			smrImageObeyFileName = gSmrFileName;
-		}
-		while(temp != 0);
-		gSmrImage = EFalse;
-	}
-	// Process Rofs Obey files.
-	if(obeyFileName)
-	{
-		
-		H.SetLogFile((unsigned char *)"ROFSBUILD.LOG");	
-		PrintVersion();
-		
-		ObeyFileReader *reader=new ObeyFileReader(obeyFileName);
-		if (!reader->Open())
-			return KErrGeneral;
-		
-		E32Rofs* RofsImage = 0;		// for image from obey file
-		CCoreImage *core= 0;		// for image from core image file
-		MRofsImage* imageInfo=0;
-		CObeyFile *mainObeyFile=new CObeyFile(*reader);
-		
-		// need check if obey file has coreimage keyword
-		TText *file = mainObeyFile->ProcessCoreImage();
-		if (file)
-		{
-			// hase coreimage keyword but only use if command line option
-			// for coreimage not already selected
-			if (!gUseCoreImage)
-			{
-				gUseCoreImage = ETrue;
-				gImageFilename = (char *)file;
-			}
-		}
-		
-		if (!gUseCoreImage)
-		{
-			
-			r=mainObeyFile->ProcessRofs();
-			if (r==KErrNone)
-			{
-				// Build a ROFS image using the description compiled into the
-				// CObeyFile object
-				
-				RofsImage = new E32Rofs( mainObeyFile );
-				if( !RofsImage )
-				{
-					return KErrNoMemory;
-				}
-				
-				r = RofsImage->Create();
-				if( KErrNone == r )
-				{
-					if(SizeSummary)
-						RofsImage->DisplaySizes(SizeWhere);
-					RofsImage->WriteImage( gHeaderType );
-				}
-				imageInfo = RofsImage;
-				mainObeyFile->Release();
-			}
-			else if (r!=KErrNotFound)
-				return r;
-		}
-		else
-		{
-			
-			// need to use core image
-			RCoreImageReader *reader = new RCoreImageReader(gImageFilename);
-			if (!reader)
-			{
-				return KErrNoMemory;
-			}
-			core= new CCoreImage(reader);
-			if (!core)
-			{
-				return KErrNoMemory;
-			}
-			r = core->ProcessImage();
-			if (r != KErrNone)
-				return r;
-			imageInfo = core;
-			mainObeyFile->SkipToExtension();
-			
-		}
-		
-		do 
-		{
-			CObeyFile* extensionObeyFile = 0;
-			E32Rofs* extensionRofs = 0;
-			
-			extensionObeyFile = new CObeyFile(*reader);
-			r = extensionObeyFile->ProcessExtensionRofs(imageInfo);
-			if (r==KErrEof)
-			{
-				if(RofsImage)
-					delete RofsImage;
-				if(core)
-					delete core;
-				delete extensionObeyFile;
-				return KErrNone;
-			}
-			if (r!=KErrNone)
-				break;
-			
-			extensionRofs = new E32Rofs(extensionObeyFile);
-			r=extensionRofs->CreateExtension(imageInfo);
-			if (r!=KErrNone)
-			{
-				delete extensionRofs;
-				delete extensionObeyFile;
-				break;
-			}
-			if(SizeSummary)
-				RofsImage->DisplaySizes(SizeWhere);
-			r=extensionRofs->WriteImage(0);		
-			delete extensionRofs;
-			delete extensionObeyFile;
-			extensionRofs = 0;
-			extensionObeyFile = 0;
-			
-		}
-		while (r==KErrNone);
-		
-		if(RofsImage) 
-			delete RofsImage;									
-		if(core)
-			delete core;
-		delete mainObeyFile;
-		
-	}
-	return r;
-}//end of main.
+/*
+* Copyright (c) 2007-2010 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+#include <string.h>
+#include <stdlib.h>
+#include <f32file.h>
+#include "e32image.h"
+#include "h_utl.h"
+#include "h_ver.h"
+#include "r_obey.h"
+#include "r_driveimage.h"
+#include "r_driveutl.h"
+#include "r_coreimage.h"
+#include "parameterfileprocessor.h"
+#include "r_smrimage.h"
+//cache headers
+#include "cache/cacheexception.hpp"
+#include "cache/cacheentry.hpp"
+#include "cache/cache.hpp"
+#include "cache/cachegenerator.hpp"
+#include "cache/cachevalidator.hpp"
+#include "cache/cacheablelist.hpp"
+#include "cache/cachemanager.hpp"
+#include <malloc.h>
+ 
+#ifndef WIN32
+#include <unistd.h>
+#include <strings.h>
+#include <fstream>
+#define strnicmp strncasecmp
+#define stricmp strcasecmp
+#define _alloca alloca
+#endif
+
+static const TInt RofsbuildMajorVersion=2;
+static const TInt RofsbuildMinorVersion=12;
+static const TInt RofsbuildPatchVersion=0;
+static TBool SizeSummary=EFalse;
+static TPrintType SizeWhere=EAlways;
+
+static TInt gHeaderType=1;			// EPOC header
+static TInt MAXIMUM_THREADS = 128;
+static TInt DEFAULT_THREADS = 8;
+ECompression gCompress=ECompressionUnknown;
+TUint  gCompressionMethod=0;
+TInt gThreadNum = 0;
+TInt gCPUNum = 0;
+TBool gGenSymbols = EFalse;
+TInt gCodePagingOverride = -1;
+TInt gDataPagingOverride = -1;
+TInt gLogLevel = 0;	// Information is logged based on logging level.
+// The default is 0. So all the existing logs are generated as if gLogLevel = 0.
+// If any extra information required, the log level must be appropriately supplied.
+// Currrently, file details in ROM (like, file name in ROM & host, file size, whether
+// the file is hidden etc) are logged when gLogLevel >= LOG_LEVEL_FILE_DETAILS.
+
+TBool gUseCoreImage = EFalse; // command line option for using core image file
+string gImageFilename = "";	// instead of obey file
+TBool gEnableStdPathWarning = EFalse;// for in-correct destination path warning(executables).
+TBool gLowMem = EFalse;
+extern TBool gDriveImage;		// to Support data drive image.
+string gDriveFilename = "";		// input drive oby filename.
+string filename;				// to store oby filename passed to Rofsbuild.
+TBool reallyHelp = EFalse;	
+TBool gSmrImage = EFalse;
+string gSmrFileName = "";
+
+//Cache global variables
+bool gCache = false;
+bool gCleanCache = false;
+bool gNoCache = false;
+TBool gKeepGoing = EFalse;
+void PrintVersion() {
+	Print(EAlways,"\nROFSBUILD - Rofs/Datadrive image builder");
+	Print(EAlways, " V%d.%d.%d\n", RofsbuildMajorVersion, RofsbuildMinorVersion, RofsbuildPatchVersion);
+	Print(EAlways,Copyright);
+}
+
+char HelpText[] = 
+	"Syntax: ROFSBUILD [options] obeyfilename(Rofs)\n"
+	"Option: -v verbose,  -?,  -s[log|screen|both] size summary\n"
+	"        -d<bitmask> set trace mask (DEB build only)\n"
+	"        -compress   compress executable files where possible\n"
+	"        -j<digit> do the main job with <digit> threads\n"
+	"        -symbols generate symbol file\n"
+	"        -compressionmethod none|inflate|bytepair to set the compression\n"
+	"              none     uncompress the image.\n"
+	"              inflate  compress the image.\n"
+	"              bytepair compress the image.\n"
+	"        -coreimage <core image file>\n"
+	"        -cache allow the ROFSBUILD to reuse/generate cached executable files\n"
+	"        -nocache force the ROFSBUILD not to reuse/generate cached executable files\n"
+	"        -cleancache permanently remove all cached executable files\n"
+	"        -datadrive=<drive obyfile1>,<drive obyfile2>,... for driveimage creation\n"
+	"              user can also input rofs oby file if required to generate both.\n"
+	"        -smr=<SMR obyfile1>,<SMR obyfile2>,... for SMR partition creation\n"
+	"        -loglevel<level>  level of information to log (valid levels are 0,1,2).\n"//Tools like Visual ROM builder need the host/ROM filenames, size & if the file is hidden.
+	"        -wstdpath   warn if destination path provided for a file is not the standard path\n"
+	"        -argfile=<FileName>   specify argument-file name containing list of command-line arguments\n"
+"        -lowmem     use memory-mapped file for image build to reduce physical memory consumption\n"
+"        -k     to enable keepgoing when duplicate files exist in oby\n";
+
+char ReallyHelpText[] =
+"Log Level:\n"
+"        0  produce the default logs\n"
+"        1  produce file detail logs in addition to the default logs\n"
+"        2  logs e32 header attributes in addition to the level 1 details\n";
+void processParamfile(const string& aFileName);
+/**
+Process the command line arguments and prints the helpful message if none are supplied.
+@param argc    - No. of argument.
+@param *argv[] - Arguments value.
+*/ 
+void processCommandLine(int argc, char *argv[], TBool paramFileFlag = EFalse) {
+	// If "-argfile" option is passed to rofsbuild, then process the parameters
+	// specified in parameter-file first and then the options passed from the command-line.
+	
+	string ParamFileArg("-ARGFILE=");	
+	if(paramFileFlag == EFalse) {
+		for (int count = 1; count<argc; count++) {
+			string paramFile;
+			//strupr(argv[count]);
+			if(strnicmp(argv[count],ParamFileArg.c_str(),ParamFileArg.length()) == 0) {
+				paramFile.assign(&argv[count][ParamFileArg.length()]);									
+				processParamfile(paramFile);
+			}
+		}
+	}	
+
+	int i = 1;
+	while (i<argc) {		 
+#ifdef __LINUX__	
+		if (argv[i][0] == '-') 
+#else
+		if ((argv[i][0] == '-') || (argv[i][0] == '/'))
+#endif
+		{ 
+			// switch
+			if ((argv[i][1] & 0x20) == 'v')
+				H.iVerbose = ETrue;
+			else if(strnicmp (argv[i], "-SMR=", 5) == 0) {
+				if(argv[i][5]) {
+					gSmrImage = ETrue;
+					gSmrFileName.assign(&argv[i][5]);
+				}
+				else {
+					Print (EError, "SMR obey file is missing\n");
+				}
+			} else if (stricmp(argv[i], "-K") == 0) {
+				gKeepGoing = ETrue;
+			}else if (stricmp(argv[i], "-SYMBOLS") == 0) {
+				gGenSymbols = ETrue;
+			}
+			else if (((argv[i][1] | 0x20) == 's') &&  
+				(((argv[i][2]| 0x20) == 'l')||((argv[i][2] | 0x20) == 's'))) {
+					SizeSummary = ETrue;
+					if ((argv[i][2]| 0x20) == 'l')
+						SizeWhere = ELog;
+					else
+						SizeWhere = EScreen;
+			}
+			else if (strnicmp(argv[i],ParamFileArg.c_str(),ParamFileArg.length()) == 0) {
+				if (paramFileFlag){
+					string paramFile;
+					paramFile.assign(&argv[i][ParamFileArg.length()]);		
+					processParamfile(paramFile);
+				}
+				else {
+					i++;
+					continue;
+				}
+			}
+			else if (stricmp(argv[i], "-COMPRESS") == 0) {
+				gCompress = ECompressionCompress;
+				gCompressionMethod = KUidCompressionDeflate;
+			}
+			else if(stricmp(argv[i], "-CACHE") == 0) {
+				gCache = true;
+				if(gCleanCache || gNoCache) {
+					printf("Cache command line options are mutually exclusive, only one option can be used at a time\n");
+					exit(1);
+				}
+			}
+			else if(stricmp(argv[i], "-NOCACHE") == 0) {
+				gNoCache = true;
+				if(gCleanCache || gCache) {
+					printf("Cache command line options are mutually exclusive, only one option can be used at a time\n");
+					exit(1);
+				}
+			}
+			else if(stricmp(argv[i], "-CLEANCACHE") == 0) {
+				gCleanCache = true;
+				if(gCache || gNoCache)
+				{
+					printf("Cache command line options are mutually exclusive, only one option can be used at a time\n");
+					exit(1);
+				}
+			}
+			else if (strnicmp(argv[i], "-J",2) == 0) {
+				if(argv[i][2])
+					gThreadNum = atoi(&argv[i][2]);
+				else {
+					printf("WARNING: The option should be like '-j4'.\n");
+					gThreadNum = 0;
+				}
+				if(gThreadNum <= 0 || gThreadNum > MAXIMUM_THREADS) {
+					printf("WARNING: The number of concurrent jobs set by -j should be between 1 and 128. ");
+					if(gCPUNum > 0) {
+						printf("WARNING: The number of processors %d is used as the number of concurrent jobs.\n", gCPUNum);
+						gThreadNum = gCPUNum;
+					}
+					else {
+						printf("WARNING: Can't automatically get the valid number of concurrent jobs and %d is used.\n", DEFAULT_THREADS);
+						gThreadNum = DEFAULT_THREADS;
+					}
+				}
+			}
+			else if (stricmp(argv[i], "-UNCOMPRESS") == 0) {
+				gCompress = ECompressionUncompress;
+			}
+			else if( stricmp(argv[i], "-COMPRESSIONMETHOD") == 0 ) {
+				// next argument should a be method
+				if( (i+1) >= argc || argv[i+1][0] == '-') {
+					Print (EError, "Missing compression method! Set it to default (no compression)!");
+					gCompressionMethod = 0;
+				}
+				else {
+					i++;					
+					if( stricmp(argv[i], "NONE") == 0) {
+						gCompress = ECompressionUncompress;
+						gCompressionMethod = 0;	
+					}
+					else if( stricmp(argv[i], "INFLATE") == 0) {
+						gCompress = ECompressionCompress;
+						gCompressionMethod = KUidCompressionDeflate;	
+					}	
+					else if( stricmp(argv[i], "BYTEPAIR") == 0) {
+						gCompress = ECompressionCompress;
+						gCompressionMethod = KUidCompressionBytePair;	
+					}
+					else {
+						Print (EError, "Unknown compression method! Set it to default (no compression)!");
+						gCompress = ECompressionUnknown;
+						gCompressionMethod = 0;		
+					}
+				}
+
+			}
+			else if (stricmp(argv[i], "-COREIMAGE") == 0) {
+				
+				gUseCoreImage = ETrue;
+				// next argument should be image filename
+				if ((i+1 >= argc) || argv[i+1][0] == '-')
+					Print (EError, "Missing image file name");
+				else {
+					i++;
+					gImageFilename.assign(argv[i]);
+				}
+			}
+			else if (strnicmp(argv[i], "-DATADRIVE=",11) == 0){  
+				if(argv[i][11])	{
+					gDriveImage = ETrue; 
+					gDriveFilename.assign(&argv[i][11]);	
+				}
+				else {
+					Print (EError, "Drive obey file is missing\n"); 
+				}
+			}
+			else if (argv[i][1] == '?') {
+				reallyHelp = ETrue;
+			}
+			else if (stricmp(argv[i], "-WSTDPATH") == 0)	{	// Warn if destination path provided for a executables are incorrect as per platsec.		
+				gEnableStdPathWarning = ETrue;						
+			}
+			else if( stricmp(argv[i], "-LOGLEVEL") == 0) {
+				// next argument should a be loglevel
+				if( (i+1) >= argc || argv[i+1][0] == '-') {
+					Print (EError, "Missing loglevel!");
+					gLogLevel = DEFAULT_LOG_LEVEL;
+				}
+				else {
+					i++;
+					if (strcmp(argv[i], "2") == 0)
+						gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES);
+					if (strcmp(argv[i], "1") == 0)
+						gLogLevel = LOG_LEVEL_FILE_DETAILS;
+					else if (strcmp(argv[i], "0") == 0)
+						gLogLevel = DEFAULT_LOG_LEVEL;
+					else
+						Print(EError, "Only loglevel 0, 1 or 2 is allowed!");
+				}
+			}
+			else if( stricmp(argv[i], "-LOGLEVEL2") == 0)
+				gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES);
+			else if( stricmp(argv[i], "-LOGLEVEL1") == 0)
+				gLogLevel = LOG_LEVEL_FILE_DETAILS;
+			else if( stricmp(argv[i], "-LOGLEVEL0") == 0)
+				gLogLevel = DEFAULT_LOG_LEVEL;
+			else if (stricmp(argv[i], "-LOWMEM") == 0)
+				gLowMem = ETrue;
+			else {
+#ifdef WIN32
+				Print (EWarning, "Unrecognised option %s\n",argv[i]);
+#else
+				if(0 == access(argv[i],R_OK)){
+					filename.assign(argv[i]);
+				}
+				else {
+					Print (EWarning, "Unrecognised option %s\n",argv[i]);
+				}
+#endif				
+
+			}
+		}
+		else // Must be the obey filename
+			filename.assign(argv[i]);
+		i++;
+	}
+
+	if (paramFileFlag)
+		return;
+
+	if((gDriveImage == EFalse) && (gSmrImage ==  EFalse) && 
+		(filename.empty() || (gUseCoreImage && gImageFilename.length() == 0))){
+			Print (EAlways, HelpText);
+			if (reallyHelp) {
+				ObeyFileReader::KeywordHelp();
+				Print (EAlways, ReallyHelpText);
+			}
+			else if (filename.empty()){
+				Print(EAlways, "Obey filename is missing\n");
+			}
+	}	
+}
+
+/**
+Function to process parameter-file.
+@param aFileName parameter-file name.
+*/
+void processParamfile(const string& aFileName) {
+
+	CParameterFileProcessor parameterFile(aFileName);
+	// Invoke fuction "ParameterFileProcessor" to process parameter-file.
+	if(parameterFile.ParameterFileProcessor()) {
+		TUint noOfParameters = parameterFile.GetNoOfArguments();
+		char** parameters = parameterFile.GetParameters();
+		TBool paramFileFlag = ETrue;
+
+		// Invoke function "processCommandLine" to process parameters read from parameter-file.
+		processCommandLine(noOfParameters,parameters,paramFileFlag);
+	}	
+}
+
+/**
+Main logic for data drive image creation. Called many types depending on no. of drive obey files.
+
+@param aobeyFileName - Drive obey file.
+@param alogfile      - log file name required for file system module.
+
+@return - returns the status, after processing the drive obey file.
+*/ 
+TInt ProcessDataDriveMain(char* aobeyFileName,char* alogfile) {
+
+	ObeyFileReader *reader = new ObeyFileReader(aobeyFileName);
+
+	if(!reader)
+		return KErrNoMemory;
+
+	if(!reader->Open())
+		return KErrGeneral; 
+		
+	CObeyFile* mainObeyFile = new CObeyFile(*reader);    
+	
+	if(!mainObeyFile)
+		return KErrNoMemory;
+
+	// Process data drive image.
+	// let's clear the TRomNode::sDefaultInitialAttr first, 'cause data drive is different from rom image
+	TRomNode::sDefaultInitialAttr = 0; 
+	TInt retstatus = mainObeyFile->ProcessDataDrive();
+	if (retstatus == KErrNone) {
+		// Build a Data drive image using the description compiled into the CObeyFile object
+		CDriveImage* userImage = new CDriveImage(mainObeyFile);
+		if(userImage) {	
+			// Drive image creation.
+			retstatus = userImage->CreateImage(alogfile);
+			if(retstatus == KErrNone) {
+				Print (EAlways, "\nSuccessfully generated the Drive image : %s \n",mainObeyFile->iDriveFileName);
+			}
+			else {
+				Print (EError, "Failed to generate the Image : %s\n",mainObeyFile->iDriveFileName);
+			}
+			delete userImage; 
+		}
+		else {
+			retstatus = KErrNoMemory;
+		}
+	}
+	// restore
+	TRomNode::sDefaultInitialAttr = (TUint8)KEntryAttReadOnly;
+	cout << "\n-----------------------------------------------------------\n";
+
+	delete mainObeyFile;
+	delete reader;
+	return retstatus;
+}
+
+TInt ProcessSmrImageMain(char* aObeyFileName, char* /* alogfile */) {
+	ObeyFileReader *reader = new ObeyFileReader(aObeyFileName);
+	if(!reader)
+		return KErrNoMemory;
+	if(!reader->Open())
+		return KErrGeneral;
+	TInt retstatus = 0;
+	CObeyFile* mainObeyFile = new CObeyFile(*reader);
+	CSmrImage* smrImage = 0;
+	if(!mainObeyFile)
+		return KErrNoMemory;
+	if(mainObeyFile->Process()) {
+		smrImage = new CSmrImage(mainObeyFile);
+		if(smrImage) {
+			if((retstatus = smrImage->Initialise()) == KErrNone) {
+				retstatus = smrImage->CreateImage();
+			}
+			if(retstatus == KErrNone) {
+				Print (EAlways,  "\nSuccessfully generated the SMR image : %s\n" ,smrImage->GetImageName().c_str());
+			}
+			else {
+				Print (EError, "\nFailed to generate the Image : %s\n" ,smrImage->GetImageName().c_str());
+			}
+			delete smrImage;
+		}
+		else {
+			retstatus = KErrNoMemory;
+		}
+	}
+	delete mainObeyFile;
+	delete reader;
+	return retstatus;
+}
+
+/**
+Rofsbuild Main function, which creates both Rofs and Data drive image.
+
+@param argc    - No. of argument.
+@param *argv[] - Arguments value.
+
+@return - returns the status to caller.
+*/ 
+TInt main(int argc, char *argv[]){
+	TInt r =0;
+#ifdef __LINUX__
+	gCPUNum = sysconf(_SC_NPROCESSORS_CONF);
+#else	
+	char* pCPUNum = getenv ("NUMBER_OF_PROCESSORS");
+	if (pCPUNum != NULL)
+		gCPUNum = atoi(pCPUNum);
+#endif		
+	if(gCPUNum > MAXIMUM_THREADS)
+		gCPUNum = MAXIMUM_THREADS;
+	PrintVersion();
+	processCommandLine(argc, argv);
+	//if the user wants to clean up the cache, do it only.
+	if(gCleanCache){
+		try {
+			CacheManager::GetInstance()->CleanCache();
+			Print (EAlways, "Cache has been deleted successfully.\n");
+		}
+		catch(CacheException& ce){
+			Print (EError, "%s\n", ce.GetErrorMessage());
+			return (TInt)1;
+		}
+		return r;
+	}
+	//initialize cache if the user switches on.
+	if(gCache) {
+		try {
+			CacheManager::GetInstance();
+		}
+		catch(CacheException ce){
+			Print (EError, "%s\n", ce.GetErrorMessage());
+			return (TInt)1;
+		}
+	}
+	const char *obeyFileName = 0;	
+	if(!filename.empty())
+		obeyFileName = filename.c_str(); 
+	if ((!obeyFileName) && (!gDriveFilename.empty()) && (!gSmrFileName.empty())){
+		return KErrGeneral;
+	}
+	if(gThreadNum == 0) {
+		if(gCPUNum > 0) {
+			Print (EWarning, "The number of processors (%d) is used as the number of concurrent jobs.\n", gCPUNum);
+			gThreadNum = gCPUNum;
+		}
+		else {
+			Print (EWarning, "Can't automatically get the valid number of concurrent jobs and %d is used.\n", DEFAULT_THREADS);
+			gThreadNum = DEFAULT_THREADS;
+		}
+	}
+	// Process drive obey files.
+	if(gDriveImage) {  
+		char temp = 0;
+		char *driveobeyFileName = (char*)_alloca(gDriveFilename.length() + 1);
+		memcpy(driveobeyFileName,gDriveFilename.c_str(),gDriveFilename.length() + 1);
+		char* ptr = driveobeyFileName;
+		do {
+			while(((temp = *ptr++) != ',') && (temp != 0));
+			*(--ptr)++ = 0; 
+
+			if(*driveobeyFileName) {
+				char* logfile = 0;
+				if(Getlogfile(driveobeyFileName,logfile) == KErrNone) {
+					H.SetLogFile(logfile);
+					GetLocalTime();
+					r = ProcessDataDriveMain(driveobeyFileName,logfile);   
+					H.CloseLogFile();
+					delete[] logfile;
+					if(r == KErrNoMemory)
+						return KErrNoMemory;
+				}
+				else {
+					Print(EError,"Invalid obey file name : %s\n", driveobeyFileName);   
+				}
+			}
+			driveobeyFileName = ptr;
+		} while(temp != 0); 
+		gDriveImage = EFalse;
+	} 
+	if(gSmrImage){
+		char temp = 0;
+		char *smrImageObeyFileName = (char*)_alloca(gSmrFileName.length() + 1);
+		memcpy(smrImageObeyFileName,gSmrFileName.c_str(),gSmrFileName.length() + 1);
+		char* ptr = smrImageObeyFileName;
+		do {
+			while(((temp = *ptr++) != ',') && (temp != 0));
+			*(--ptr)++ = 0;
+
+			if(*smrImageObeyFileName){	
+				char * logfile = 0;
+				if(Getlogfile(smrImageObeyFileName,logfile) == KErrNone){
+					H.SetLogFile(logfile);
+					GetLocalTime();
+					r = ProcessSmrImageMain(smrImageObeyFileName, logfile);
+					H.CloseLogFile();
+					delete[] logfile;
+					if(r == KErrNoMemory)
+						return KErrNoMemory;
+				}
+				else {
+					Print(EError,"Invalid obey file name: %s", smrImageObeyFileName);
+				}
+			}
+			smrImageObeyFileName = ptr;
+		} while(temp != 0);
+		gSmrImage = EFalse;
+	}
+	// Process Rofs Obey files.
+	if(obeyFileName) {
+		H.SetLogFile("ROFSBUILD.LOG");		
+		ObeyFileReader *reader = new ObeyFileReader(obeyFileName); 
+		if (!reader->Open())
+			return KErrGeneral;
+
+		E32Rofs* RofsImage = 0;		// for image from obey file
+		CCoreImage *core = 0;		// for image from core image file
+		MRofsImage* imageInfo = 0;
+		CObeyFile *mainObeyFile = new CObeyFile(*reader);
+		// need check if obey file has coreimage keyword
+		char *file = mainObeyFile->ProcessCoreImage();
+		if (file) {
+			// hase coreimage keyword but only use if command line option
+			// for coreimage not already selected
+			if (!gUseCoreImage){
+				gUseCoreImage = ETrue;
+				gImageFilename = file;
+			}
+			delete []file ;
+		}
+		if (!gUseCoreImage) {
+			r = mainObeyFile->ProcessRofs();
+			if (r == KErrNone) {
+				// Build a ROFS image using the description compiled into the CObeyFile object
+				RofsImage = new E32Rofs( mainObeyFile );
+				if( !RofsImage ) {
+					if(gCache || gCleanCache)
+						delete CacheManager::GetInstance();
+					return KErrNoMemory;
+				}
+				r = RofsImage->Create();
+
+				if( KErrNone == r )	{
+					RofsImage->WriteImage( gHeaderType );
+				}
+				imageInfo = RofsImage;
+				mainObeyFile->Release();
+				if(gCache || gCleanCache)
+					delete CacheManager::GetInstance();
+			}
+			else if (r != KErrNotFound){
+				return r;
+			}
+		}
+		else {
+			// need to use core image
+			RCoreImageReader *reader = new RCoreImageReader(gImageFilename.c_str());
+			if (!reader) {
+				return KErrNoMemory;
+			}
+			core = new CCoreImage(reader);
+			if (!core) {
+				return KErrNoMemory;
+			}
+			r = core->ProcessImage();
+			if (r != KErrNone) {
+				return r;
+			}
+			imageInfo = core;
+			mainObeyFile->SkipToExtension();
+		}
+
+		do {
+			CObeyFile* extensionObeyFile = new CObeyFile(*reader);
+			r = extensionObeyFile->ProcessExtensionRofs(imageInfo);
+			if (r == KErrEof){
+				if(RofsImage){
+					delete RofsImage;
+				}
+				if(core){
+					delete core;
+				}
+				delete extensionObeyFile;
+				return KErrNone;
+			}
+			if (r != KErrNone){
+				break;
+			}
+			E32Rofs* extensionRofs = new E32Rofs(extensionObeyFile);
+			r = extensionRofs->CreateExtension(imageInfo);
+			if (r!= KErrNone){
+				delete extensionRofs;
+				delete extensionObeyFile;
+				break;
+			}
+			r = extensionRofs->WriteImage(0);	
+
+			delete extensionRofs;
+			extensionRofs = 0;
+		} while (r == KErrNone);
+		if(RofsImage) {
+			delete RofsImage;									
+		}
+		if(core){
+			delete core;
+		}
+		delete mainObeyFile;
+	}
+	return r;
+}//end of main.
--- a/imgtools/romtools/rofsbuild/rofsbuild.mmp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rofsbuild/rofsbuild.mmp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,61 +1,62 @@
-/*
-* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-
-TARGET			rofsbuild.exe
-TARGETTYPE		exe
-
-// rofsbuild
-SOURCEPATH	../rofsbuild
-SOURCE			 r_obey.cpp r_build.cpp r_rofs.cpp r_driveimage.cpp r_driveutl.cpp
-SOURCE			 rofsbuild.cpp r_coreimage.cpp r_smrimage.cpp
-SOURCEPATH	../../imglib/host
-SOURCE			h_utl.cpp h_file.cpp h_mem.cpp
-
-// executable compression
-SOURCEPATH	../../imglib/e32uid
-SOURCE			e32uid.cpp
-sourcepath      ../../imglib/e32image
-source                  e32image.cpp
-sourcepath      ../../imglib/e32image/deflate
-source                  decode.cpp encode.cpp deflate.cpp inflate.cpp panic.cpp
-source                  compress.cpp
-sourcepath  	../../imglib/compress
-source					byte_pair.cpp pagedcompress.cpp
-
-OS_LAYER_SYSTEMINCLUDE_SYMBIAN
-
-USERINCLUDE   ../../imglib/inc ../../imglib/compress ../../imglib/filesystem/include 
-USERINCLUDE   ../../imglib/patchdataprocessor/include ../../imglib/parameterfileprocessor/include
-USERINCLUDE	  ../../imglib/memmap/include
-USERINCLUDE   ../../imglib/boostlibrary/
-
-STATICLIBRARY 	filesystem 
-STATICLIBRARY   patchdataprocessor
-STATICLIBRARY   parameterfileprocessor
-STATICLIBRARY	memmap
-#ifdef TOOLS2_LINUX
-STATICLIBRARY   boost_thread-mgw34-mt-1_39_linux
-OPTION    GCC -pthread -O2 -Wno-uninitialized
-#else
-STATICLIBRARY   boost_thread-mgw34-mt-1_39_win32
-OPTION    GCC -mthreads -O2 -Wno-uninitialized
-#endif
-
-
-VENDORID 0x70000001
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+
+TARGET			rofsbuild.exe
+TARGETTYPE		exe
+
+// rofsbuild
+SOURCEPATH	../rofsbuild
+SOURCE			 r_obey.cpp r_build.cpp r_rofs.cpp r_driveimage.cpp r_driveutl.cpp
+SOURCE			 rofsbuild.cpp r_coreimage.cpp r_smrimage.cpp symbolgenerator.cpp
+SOURCE			 fatcluster.cpp fsnode.cpp fatimagegenerator.cpp
+SOURCEPATH	../../imglib/host
+SOURCE			h_utl.cpp h_file.cpp h_mem.cpp utf16string.cpp
+SOURCEPATH ../rofsbuild/src/cache
+SOURCE cachemanager.cpp cacheexception.cpp cache.cpp cacheablelist.cpp cachevalidator.cpp cachegenerator.cpp cacheentry.cpp
+
+// executable compression
+SOURCEPATH	../../imglib/e32uid
+SOURCE			e32uid.cpp
+sourcepath      ../../imglib/e32image
+source                  e32image.cpp
+sourcepath      ../../imglib/e32image/deflate
+source                  decode.cpp encode.cpp deflate.cpp inflate.cpp panic.cpp
+source                  compress.cpp
+sourcepath  	../../imglib/compress
+source					byte_pair.cpp pagedcompress.cpp
+
+OS_LAYER_SYSTEMINCLUDE_SYMBIAN
+
+USERINCLUDE   ../../imglib/inc ../../imglib/compress
+USERINCLUDE   ../../imglib/patchdataprocessor/include ../../imglib/parameterfileprocessor/include
+USERINCLUDE	  ../../imglib/memmap/include
+USERINCLUDE   ../rofsbuild/inc
+USERINCLUDE   ../../imglib/boostlibrary/
+USERINCLUDE   ../../imglib/boostlibrary/boost
+
+STATICLIBRARY 	patchdataprocessor parameterfileprocessor memmap
+STATICLIBRARY   boost_thread-1.39 boost_filesystem-1.39 boost_regex-1.39 boost_system-1.39
+#ifdef TOOLS2_LINUX
+OPTION    GCC -pthread -O2 -Wno-uninitialized
+#else
+OPTION    GCC -mthreads -O2 -Wno-uninitialized
+#endif
+
+
+VENDORID 0x70000001
--- a/imgtools/romtools/rombuild/r_areaset.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_areaset.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,554 +1,504 @@
-/*
-* Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Area-related classes implementation
-*
-*/
-
-
-#include "r_areaset.h"
-#include "r_global.h"
-#include "r_rom.h"
-
-extern TBool gGenDepGraph;
-extern char* gDepInfoFile;
-
-using namespace std;
-
-////////////////////////////////////////////////////////////////////////
-
-Area::Area(const char* aName, TLinAddr aDestBaseAddr, TUint aMaxSize, Area* aNext)
-	: iFirstPagedCode(0),
-	  iName(strdup(aName)),
-	  iDestBaseAddr(aDestBaseAddr),
-	  iSrcBaseAddr(0),
-	  iSrcLimitAddr(0),
-	  iMaxSize(aMaxSize),
-	  iIsDefault(strcmp(aName, AreaSet::KDefaultAreaName) == 0),
-	  iFiles(0),
-	  iNextFilePtrPtr(&iFiles),
-	  iNextArea(aNext)
-	  
-	{
-	}
-
-
-Area::~Area()
-	{
-	ReleaseAllFiles();
-	free(const_cast<char*>(iName));	// allocated with strdup()
-	}
-
-
-/**
- Increase the size of the area.
-
- The reallocation must not exceed the area maximum size.
-
- @param aSrcLimitAddr New source top address
-
- @param aOverflow Number of overflow bytes if failure.
-
- @return success indication
-*/
-
-TBool Area::ExtendSrcLimitAddr(TLinAddr aSrcLimitAddr, TUint& aOverflow)
-	{
-	// must have been set before
-	assert(iSrcBaseAddr != 0);
-	// can only allocate more
-	assert(aSrcLimitAddr > iSrcBaseAddr);
-
-	if (aSrcLimitAddr-iSrcBaseAddr > iMaxSize)
-		{
-		aOverflow = aSrcLimitAddr-iSrcBaseAddr-iMaxSize;
-		return EFalse;
-		}
-
-	iSrcLimitAddr = aSrcLimitAddr;
-	return ETrue;
-	}
-
-
-/**
- Add a file at end of the list of files contained in this area.
-
- @param aFile File to add.  Must be allocated on the heap.  Ownership
- is transfered from the caller to the callee.
-*/
-
-void Area::AddFile(TRomBuilderEntry* aFile)
-	{
-	assert(aFile != 0);
-
-	*iNextFilePtrPtr = aFile;
-	iNextFilePtrPtr = &(aFile->iNextInArea);
-	}
-
-
-void Area::ReleaseAllFiles()
-	{
-	for (TRomBuilderEntry *next = 0, *current = iFiles;
-		 current != 0;
-		 current = next)
-		{
-		next = current->iNextInArea;
-		delete current;
-		}
-
-	iFiles = 0;
-	iNextFilePtrPtr = &iFiles;
-	}
-
-////////////////////////////////////////////////////////////////////////
-
-void FilesInAreaIterator::GoToNext()
-	{
-	assert(iCurrentFile!=0);
-	iCurrentFile = iCurrentFile->iNextInArea;
-	}
-
-////////////////////////////////////////////////////////////////////////
-
-const char AreaSet::KDefaultAreaName[] = "DEFAULT AREA";
-
-AreaSet::AreaSet()
-	: iNonDefaultAreas(0),
-	  iDefaultArea(0),
-	  iAreaCount(0)
-	{
-	}
-
-
-AreaSet::~AreaSet()
-	{
-	ReleaseAllAreas();
-	}
-
-
-inline TBool IsInRange(TLinAddr aAddr, TLinAddr aDestBaseAddr, TLinAddr aEndAddr)
-	{
-	return aDestBaseAddr <= aAddr && aAddr <= aEndAddr;
-	}
-
-
-/**
- Add a new area.
-
- Areas must have unique name, not overlap one another and not overflow
- the 32-bit address range.  
-
- @param aOverlappingArea On return ptr to name of overlapping area if
- any, 0 otherwise.
-
- @return EAdded if success, an error code otherwise.  
-*/
-
-AreaSet::TAddResult AreaSet::AddArea(const char* aNewName,
-									 TLinAddr aNewDestBaseAddr,
-									 TUint aNewMaxSize,
-									 const char*& aOverlappingArea)
-	{
-	assert(aNewName != 0 && strlen(aNewName) > 0);
-	assert(aNewMaxSize > 0);
-
-	aOverlappingArea = 0;
-
-	//
-	// Checking new area validity
-	//
-
-	if (aNewDestBaseAddr+aNewMaxSize <= aNewDestBaseAddr)
-		return EOverflow;
-
-	TLinAddr newEndAddr = aNewDestBaseAddr+aNewMaxSize-1;
-
-	// iterate non default areas first, then the default one if any
-	Area* area=iNonDefaultAreas; 
-	while (area != 0)
-		{
-		if (strcmp(area->Name(), aNewName) == 0)
-			return EDuplicateName;
-
-		TLinAddr curDestBaseAddr = area->DestBaseAddr();
-		TLinAddr curEndAddr = area->DestBaseAddr()+area->MaxSize()-1;
-
-		if (IsInRange(newEndAddr, curDestBaseAddr, curEndAddr) ||
-			IsInRange(aNewDestBaseAddr, curDestBaseAddr, curEndAddr) ||
-			IsInRange(curDestBaseAddr, aNewDestBaseAddr, newEndAddr))
-			{
-			aOverlappingArea = area->Name();
-			return EOverlap;
-			}
-
-		if (area->iNextArea == 0 && area != iDefaultArea)
-			area = iDefaultArea;
-		else
-			area = area->iNextArea;
-		}
-	
-	//
-	// Adding new area
-	//
-
-	if (strcmp(KDefaultAreaName, aNewName) == 0)
-		iDefaultArea = new Area(aNewName, aNewDestBaseAddr, aNewMaxSize);
-	else
-		iNonDefaultAreas = new Area(aNewName, aNewDestBaseAddr, aNewMaxSize, iNonDefaultAreas);
-	++iAreaCount;
-
-	return EAdded;
-	}
-
-
-/**
- Remove every area added to the set.
-
- As a side-effect every file added to the areas is deleted.
-*/
-
-void AreaSet::ReleaseAllAreas()
-	{
-	for (Area *next = 0, *current = iNonDefaultAreas; current != 0; current = next)
-		{
-		next = current->iNextArea;
-		delete current;
-		}
-
-	iNonDefaultAreas = 0;
-
-	delete iDefaultArea;
-	iDefaultArea = 0;
-	}
-
-
-/**
- Find an area from its name.
-
- @return A pointer to the area or 0 if the name is unknown.  The
- returned pointer becomes invalid when "this" is destructed.
-*/
-
-Area* AreaSet::FindByName(const char* aName) const
-	{
-	assert(aName != 0 && strlen(aName) > 0);
-
-	if (iDefaultArea && strcmp(iDefaultArea->Name(), aName) == 0)
-		return iDefaultArea;
-
-	for (Area* area=iNonDefaultAreas; area != 0; area = area->iNextArea)
-		{
-		if (strcmp(area->Name(), aName) == 0)
-			return area;
-		}
-
-	return 0;
-	}
-
-
-////////////////////////////////////////////////////////////////////////
-
-void NonDefaultAreasIterator::GoToNext()
-	{
-	assert(iCurrentArea!=0);
-	iCurrentArea = iCurrentArea->iNextArea;
-	}
-
-TInt Area::SortFilesForPagedRom()
-	{
-	Print(ELog,"Sorting files to paged/unpaged.\n");
-	TRomBuilderEntry* extention[2] = {0,0};
-	TRomBuilderEntry* unpaged[2] = {0,0};
-	TRomBuilderEntry* normal[2] = {0,0};
-	TRomBuilderEntry* current = iFiles;
-	while(current)
-		{
-		TRomBuilderEntry** list;
-		if((current->iRomImageFlags & (KRomImageFlagPrimary|KRomImageFlagVariant|KRomImageFlagExtension|KRomImageFlagDevice)) ||
-			current->HCRDataFile())
-			list = extention;
-		else if(current->iRomImageFlags&(KRomImageFlagCodeUnpaged))
-			list = unpaged;
-		else if(current->iResource && (current->iOverrideFlags&KOverrideCodeUnpaged) && gPagedRom)
-			list = unpaged;
-		else
-			list = normal;
-
-		if(list!=normal)
-			{
-			Print(ELog, "Unpaged file %s\n",current->iRomNode->BareName());
-			}
-
-		if(!list[0])
-			list[0] = current;
-		else
-			list[1]->iNextInArea = current;
-		list[1] = current;
-
-		current = current->iNext;
-		}
-
-	if(extention[1])
-		{
-		if(unpaged[0])
-			{
-			extention[1]->iNextInArea = unpaged[0];
-			unpaged[1]->iNextInArea = normal[0];
-			}
-		else
-			extention[1]->iNextInArea = normal[0];
-
-		if (normal[1])
-			normal[1]->iNextInArea = 0;
-
-		iFiles = extention[0];
-		}
-	else{
-		Print(EError,"No primary files.\n");
-		return KErrGeneral;
-	}
-
-	iFirstPagedCode = normal[0];
-	Print(ELog,"\n");
-	if(gGenDepGraph)
-		WriteDependenceGraph();
-	return KErrNone;
-	}
-
-
-void Area::WriteDependenceGraph()
-{
-	TDepInfoList::iterator infoIt;
-	TStringList::iterator strIt;
-	TDepInfoList myDepInfoList;
-	TRomBuilderEntry* e = iFirstPagedCode;
-	char buffer[255];
-	TInt count = 0;
-	TStringList nameList;
-	while(e)
-	{
-		DepInfo tmpDepInfo;
-		TRomNode* rn = e->iRomNode;
-		TInt ll = rn->FullNameLength();
-		char* mm = (char*) malloc(ll+1);
-		rn->GetFullName(mm);
-		sprintf(buffer, "f%d", count);
-		tmpDepInfo.portName = buffer;
-		tmpDepInfo.index = count;
-		myDepInfoList[mm] = tmpDepInfo;
-		nameList.push_back(mm);
-		free(mm);
-		e = e->iNextInArea;
-		count++;
-	}
-	e = iFirstPagedCode;
-	count = 0;
-	while(e)
-	{
-		TRomNode* rn = e->iRomNode;
-		TRomFile* rf = rn->iRomFile;
-		TInt j;
-		TStringList depFiles;
-		for(j=0; j < rf->iNumDeps; ++j)
-		{
-			TRomFile* f=rf->iDeps[j];
-			TRomBuilderEntry* start = iFiles;
-			while(start && start->iRomNode->iRomFile != f)
-				start = start->iNextInArea;
-			if(start && (start->iRomNode->iRomFile == f))
-			{
-				TRomNode* target = start->iRomNode;
-				TInt l = target->FullNameLength();
-				char* fname = (char *) malloc(l+1);
-				target->GetFullName(fname);
-				if(myDepInfoList.find(fname) != myDepInfoList.end())
-				{
-					depFiles.push_back(fname);
-					myDepInfoList[fname].beenDepended = ETrue;
-				}
-				free(fname);
-			}
-		}
-		if(depFiles.size() > 0)
-		{
-			myDepInfoList[nameList[count]].depFilesList=depFiles;
-			myDepInfoList[nameList[count]].dependOthers = ETrue;
-		}
-		count++;
-		e=e->iNextInArea;
-	}
-	ofstream os;
-	string filename(gDepInfoFile, strlen(gDepInfoFile) - 3);
-	filename = filename + "dot";
-	os.open(filename.c_str());
-	os << "digraph ROM {\n";
-	os << "rankdir = LR;\n";
-	os << "fontsize = 10;\n";
-	os << "fontname = \"Courier New\";\n";
-	os << "label = \"ROM DEPENDENCE GRAPH DOT FILE\";\n";
-	os << "node[shape = plaintext];\n";
-	os << "dependence[label=<<FONT FACE=\"Courier new\" POINT-SIZE=\"10pt\">\n";
-	os << "<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\">\n";
-	//for(infoIt = myDepInfoList.begin(); infoIt != myDepInfoList.end(); infoIt++)
-	for(strIt = nameList.begin(); strIt != nameList.end(); strIt++)
-	{
-		string tmp = *strIt;
-		string::iterator charIt;
-		for(charIt=tmp.begin(); charIt != tmp.end(); charIt++)
-		{
-			if(*charIt == '\\')
-				*charIt = '/';
-		}
-		if(myDepInfoList[*strIt].beenDepended && myDepInfoList[*strIt].dependOthers)
-		{
-			os << "\t<TR><TD PORT=\"" << myDepInfoList[*strIt].portName << "\" ALIGN=\"LEFT\" BGCOLOR=\"yellow\">\n";
-			os << "\t<FONT COLOR=\"red\">" << tmp << "</FONT>\n";
-			os << "\t</TD></TR>\n";
-		}
-		else if(myDepInfoList[*strIt].beenDepended)
-		{
-			os << "\t<TR><TD PORT=\"" << myDepInfoList[*strIt].portName << "\" ALIGN=\"LEFT\" BGCOLOR=\"gray\">\n";
-			os << "\t<FONT COLOR=\"red\">" << tmp << "</FONT>\n";
-			os << "\t</TD></TR>\n";
-		}
-		else if(myDepInfoList[*strIt].dependOthers)
-		{
-			os << "\t<TR><TD PORT=\"" << myDepInfoList[*strIt].portName << "\" ALIGN=\"LEFT\" BGCOLOR=\"cyan\">\n";
-			os << "\t<FONT COLOR=\"blue\">" << tmp << "</FONT>\n";
-			os << "\t</TD></TR>\n";
-		}
-		else
-		{
-			os << "\t<TR><TD PORT=\"" << myDepInfoList[*strIt].portName << "\" ALIGN=\"LEFT\">";
-			os << tmp;
-			os << "</TD></TR>\n";
-		}
-	}
-	os << "</TABLE>\n";
-	os << "</FONT>>]\n";
-	TBool lastEdge = ETrue;
-	TBool first = ETrue;
-	for(infoIt = myDepInfoList.begin(); infoIt != myDepInfoList.end(); infoIt++)
-	{
-		if(!infoIt->second.dependOthers)
-		{
-			continue;
-		}
-		for(strIt = infoIt->second.depFilesList.begin(); strIt != infoIt->second.depFilesList.end(); strIt++)
-		{
-			TBool tmpEdge = ETrue;
-			if(infoIt->second.index < myDepInfoList[*strIt].index)
-			{	
-				tmpEdge = EFalse;
-			}
-			if(first)
-			{
-				lastEdge = tmpEdge;
-				first = EFalse;
-				if(lastEdge)
-				{
-					os << "edge[color=forestgreen];\n";
-				}
-				else
-				{
-					os << "edge[color=red];\n";
-				}
-			}
-			else
-			{
-				if(lastEdge != tmpEdge)
-				{
-					lastEdge = tmpEdge;
-					if(lastEdge)
-					{
-						os << "edge[color=forestgreen];\n";
-					}
-					else
-					{
-						os << "edge[color=red];\n";
-					}
-				}
-			}
-			os << "dependence: " << infoIt->second.portName << " -> dependence: " << myDepInfoList[*strIt].portName << ";\n";
-		}
-	}
-	os << "}\n";
-	os.close();
-	filename = filename.substr(0, filename.size()-4);
-	filename = filename + ".backwarddep.dot";
-	os.open(filename.c_str());
-	os << "digraph ROM {\n";
-	os << "rankdir = LR;\n";
-	os << "fontsize = 10;\n";
-	os << "fontname = \"Courier New\";\n";
-	os << "label = \"ROM FORWARD DEPENDENCE GRAPH DOT FILE\";\n";
-	os << "node[shape = plaintext];\n";
-	os << "dependence[label=<<FONT FACE=\"Courier new\" POINT-SIZE=\"10pt\">\n";
-	os << "<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\">\n";
-	//for(infoIt = myDepInfoList.begin(); infoIt != myDepInfoList.end(); infoIt++)
-	for(strIt = nameList.begin(); strIt != nameList.end(); strIt++)
-	{
-		string tmp = *strIt;
-		string::iterator charIt;
-		for(charIt=tmp.begin(); charIt != tmp.end(); charIt++)
-		{
-			if(*charIt == '\\')
-				*charIt = '/';
-		}
-		if(myDepInfoList[*strIt].beenDepended && myDepInfoList[*strIt].dependOthers)
-		{
-			os << "\t<TR><TD PORT=\"" << myDepInfoList[*strIt].portName << "\" ALIGN=\"LEFT\" BGCOLOR=\"yellow\">\n";
-			os << "\t<FONT COLOR=\"red\">" << tmp << "</FONT>\n";
-			os << "\t</TD></TR>\n";
-		}
-		else if(myDepInfoList[*strIt].beenDepended)
-		{
-			os << "\t<TR><TD PORT=\"" << myDepInfoList[*strIt].portName << "\" ALIGN=\"LEFT\" BGCOLOR=\"gray\">\n";
-			os << "\t<FONT COLOR=\"red\">" << tmp << "</FONT>\n";
-			os << "\t</TD></TR>\n";
-		}
-		else if(myDepInfoList[*strIt].dependOthers)
-		{
-			os << "\t<TR><TD PORT=\"" << myDepInfoList[*strIt].portName << "\" ALIGN=\"LEFT\" BGCOLOR=\"cyan\">\n";
-			os << "\t<FONT COLOR=\"blue\">" << tmp << "</FONT>\n";
-			os << "\t</TD></TR>\n";
-		}
-		else
-		{
-			os << "\t<TR><TD PORT=\"" << myDepInfoList[*strIt].portName << "\" ALIGN=\"LEFT\">";
-			os << tmp;
-			os << "</TD></TR>\n";
-		}
-	}
-	os << "</TABLE>\n";
-	os << "</FONT>>]\n";
-	os << "edge[color=red];\n";
-	for(infoIt = myDepInfoList.begin(); infoIt != myDepInfoList.end(); infoIt++)
-	{
-		if(!infoIt->second.dependOthers)
-		{
-			continue;
-		}
-		for(strIt = infoIt->second.depFilesList.begin(); strIt != infoIt->second.depFilesList.end(); strIt++)
-		{
-			if(infoIt->second.index < myDepInfoList[*strIt].index)
-			{	
-				os << "dependence: " << infoIt->second.portName << " -> dependence: " << myDepInfoList[*strIt].portName << ";\n";
-			}
-		}
-	}
-	os << "}\n";
-	os.close();
-}
-
+/*
+* Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Area-related classes implementation
+*
+*/
+
+
+#include "r_areaset.h"
+#include "r_global.h"
+#include "r_rom.h"
+
+extern TBool gGenDepGraph;
+extern string gDepInfoFile;
+
+using namespace std;
+
+////////////////////////////////////////////////////////////////////////
+
+Area::Area(const char* aName, TLinAddr aDestBaseAddr, TUint aMaxSize, Area* aNext)
+: iFirstPagedCode(0),
+iName(0),
+iDestBaseAddr(aDestBaseAddr),
+iSrcBaseAddr(0),
+iSrcLimitAddr(0),
+iMaxSize(aMaxSize),
+iIsDefault(strcmp(aName, AreaSet::KDefaultAreaName) == 0),
+iFiles(0),
+iNextFilePtrPtr(&iFiles),
+iNextArea(aNext)	   
+{
+	size_t len = strlen(aName) + 1;
+	iName = new char[len];
+	memcpy(iName,aName,len);
+
+}
+
+
+Area::~Area() {
+	ReleaseAllFiles();
+	if(iName)
+		delete []iName;
+}
+
+
+/**
+Increase the size of the area.
+
+The reallocation must not exceed the area maximum size.
+
+@param aSrcLimitAddr New source top address
+
+@param aOverflow Number of overflow bytes if failure.
+
+@return success indication
+*/
+
+TBool Area::ExtendSrcLimitAddr(TLinAddr aSrcLimitAddr, TUint& aOverflow) {
+	// must have been set before
+	assert(iSrcBaseAddr != 0);
+	// can only allocate more
+	assert(aSrcLimitAddr > iSrcBaseAddr);
+
+	if (aSrcLimitAddr-iSrcBaseAddr > iMaxSize) {
+		aOverflow = aSrcLimitAddr-iSrcBaseAddr-iMaxSize;
+		return EFalse;
+	}
+
+	iSrcLimitAddr = aSrcLimitAddr;
+	return ETrue;
+}
+
+
+/**
+Add a file at end of the list of files contained in this area.
+
+@param aFile File to add.  Must be allocated on the heap.  Ownership
+is transfered from the caller to the callee.
+*/
+
+void Area::AddFile(TRomBuilderEntry* aFile) {
+	assert(aFile != 0);
+
+	*iNextFilePtrPtr = aFile; 
+	iNextFilePtrPtr = &(aFile->iNextInArea);
+}
+
+
+void Area::ReleaseAllFiles() {
+	for (TRomBuilderEntry *next = 0, *current = iFiles;
+		current != 0;
+		current = next) {
+		next = current->iNextInArea; 
+		delete current;
+	}
+
+	iFiles = 0;
+	iNextFilePtrPtr = &iFiles;
+}
+
+////////////////////////////////////////////////////////////////////////
+
+void FilesInAreaIterator::GoToNext() {
+	assert(iCurrentFile!=0);
+	iCurrentFile = iCurrentFile->iNextInArea;
+}
+
+////////////////////////////////////////////////////////////////////////
+
+const char AreaSet::KDefaultAreaName[] = "DEFAULT AREA";
+
+AreaSet::AreaSet()
+: iNonDefaultAreas(0),
+iDefaultArea(0),
+iAreaCount(0) {
+}
+
+
+AreaSet::~AreaSet() {
+	ReleaseAllAreas();
+}
+
+
+inline TBool IsInRange(TLinAddr aAddr, TLinAddr aDestBaseAddr, TLinAddr aEndAddr) {
+	return aDestBaseAddr <= aAddr && aAddr <= aEndAddr;
+}
+
+
+/**
+Add a new area.
+
+Areas must have unique name, not overlap one another and not overflow
+the 32-bit address range.  
+
+@param aOverlappingArea On return ptr to name of overlapping area if
+any, 0 otherwise.
+
+@return EAdded if success, an error code otherwise.  
+*/
+
+AreaSet::TAddResult AreaSet::AddArea(const char* aNewName,
+									 TLinAddr aNewDestBaseAddr,
+									 TUint aNewMaxSize,
+									 const char*& aOverlappingArea) {
+	assert(aNewName != 0 && strlen(aNewName) > 0);
+	assert(aNewMaxSize > 0);
+
+	aOverlappingArea = 0;
+
+	//
+	// Checking new area validity
+	//
+
+	if (aNewDestBaseAddr+aNewMaxSize <= aNewDestBaseAddr)
+		return EOverflow;
+
+	TLinAddr newEndAddr = aNewDestBaseAddr+aNewMaxSize-1;
+
+	// iterate non default areas first, then the default one if any
+	Area* area=iNonDefaultAreas; 
+	while (area != 0) {
+		if (strcmp(area->Name(), aNewName) == 0)
+			return EDuplicateName;
+
+		TLinAddr curDestBaseAddr = area->DestBaseAddr();
+		TLinAddr curEndAddr = area->DestBaseAddr()+area->MaxSize()-1;
+
+		if (IsInRange(newEndAddr, curDestBaseAddr, curEndAddr) ||
+			IsInRange(aNewDestBaseAddr, curDestBaseAddr, curEndAddr) ||
+			IsInRange(curDestBaseAddr, aNewDestBaseAddr, newEndAddr)) {
+			aOverlappingArea = area->Name();
+			return EOverlap;
+		}
+
+		if (area->iNextArea == 0 && area != iDefaultArea)
+			area = iDefaultArea;
+		else
+			area = area->iNextArea;
+	}
+
+	//
+	// Adding new area
+	//
+
+	if (strcmp(KDefaultAreaName, aNewName) == 0)
+		iDefaultArea = new Area(aNewName, aNewDestBaseAddr, aNewMaxSize);
+	else
+		iNonDefaultAreas = new Area(aNewName, aNewDestBaseAddr, aNewMaxSize, iNonDefaultAreas);
+	++iAreaCount;
+
+	return EAdded;
+}
+
+
+/**
+Remove every area added to the set.
+
+As a side-effect every file added to the areas is deleted.
+*/
+
+void AreaSet::ReleaseAllAreas() {
+	for (Area *next = 0, *current = iNonDefaultAreas; current != 0; current = next) {
+		next = current->iNextArea;
+		delete current;
+	}
+
+	iNonDefaultAreas = 0;
+	if(iDefaultArea){
+		delete iDefaultArea;
+		iDefaultArea = 0;
+	}
+}
+
+
+/**
+Find an area from its name.
+
+@return A pointer to the area or 0 if the name is unknown.  The
+returned pointer becomes invalid when "this" is destructed.
+*/
+
+Area* AreaSet::FindByName(const char* aName) const {
+	assert(aName != 0 && strlen(aName) > 0);
+
+	if (iDefaultArea && strcmp(iDefaultArea->Name(), aName) == 0)
+		return iDefaultArea;
+
+	for (Area* area=iNonDefaultAreas; area != 0; area = area->iNextArea) {
+		if (strcmp(area->Name(), aName) == 0)
+			return area;
+	}
+
+	return 0;
+}
+
+
+////////////////////////////////////////////////////////////////////////
+
+void NonDefaultAreasIterator::GoToNext() {
+	assert(iCurrentArea!=0);
+	iCurrentArea = iCurrentArea->iNextArea;
+}
+
+TInt Area::SortFilesForPagedRom() {
+	Print(ELog,"Sorting files to paged/unpaged.\n");
+	TRomBuilderEntry* extention[2] = {0,0};
+	TRomBuilderEntry* unpaged[2] = {0,0};
+	TRomBuilderEntry* normal[2] = {0,0};
+	TRomBuilderEntry* current = iFiles;
+	while(current) {
+		TRomBuilderEntry** list;
+		if((current->iRomImageFlags & (KRomImageFlagPrimary|KRomImageFlagVariant|KRomImageFlagExtension|KRomImageFlagDevice)) ||
+			current->HCRDataFile())
+			list = extention;
+		else if(current->iRomImageFlags&(KRomImageFlagCodeUnpaged))
+			list = unpaged;
+		else if(current->iResource && (current->iOverrideFlags&KOverrideCodeUnpaged) && gPagedRom)
+			list = unpaged;
+		else
+			list = normal;
+
+		if(list!=normal) {
+			Print(ELog, "Unpaged file %s\n",current->iRomNode->BareName());
+		}
+
+		if(!list[0])
+			list[0] = current;
+		else
+			list[1]->iNextInArea = current;
+		list[1] = current;
+
+		current = current->iNext;
+	}
+
+	if(extention[1]) {
+		if(unpaged[0]) {
+			extention[1]->iNextInArea = unpaged[0];
+			unpaged[1]->iNextInArea = normal[0];
+		}
+		else
+			extention[1]->iNextInArea = normal[0];
+
+		if (normal[1])
+			normal[1]->iNextInArea = 0;
+
+		iFiles = extention[0];
+	}
+	else{
+		Print(EError,"No primary files.\n");
+		return KErrGeneral;
+	}
+
+	iFirstPagedCode = normal[0];
+	Print(ELog,"\n");
+	if(gGenDepGraph)
+		WriteDependenceGraph();
+	return KErrNone;
+}
+
+
+void Area::WriteDependenceGraph() {
+	TDepInfoList::iterator infoIt;
+	TStringList::iterator strIt;
+	TDepInfoList myDepInfoList;
+	TRomBuilderEntry* e = iFirstPagedCode;
+	char buffer[255];
+	TInt count = 0;
+	TStringList nameList;
+	while(e) {
+		DepInfo tmpDepInfo;
+		TRomNode* rn = e->iRomNode;
+		TInt ll = rn->FullNameLength();
+		char* mm = new char[ll+1];
+		rn->GetFullName(mm);
+		sprintf(buffer, "f%d", count);
+		tmpDepInfo.portName = buffer;
+		tmpDepInfo.index = count;
+		myDepInfoList[mm] = tmpDepInfo;
+		nameList.push_back(mm);
+		delete []mm;
+		e = e->iNextInArea;
+		count++;
+	}
+	e = iFirstPagedCode;
+	count = 0;
+	while(e) {
+		TRomNode* rn = e->iRomNode;
+		TRomFile* rf = rn->iRomFile;
+		TInt j;
+		TStringList depFiles;
+		for(j=0; j < rf->iNumDeps; ++j) {
+			TRomFile* f=rf->iDeps[j];
+			TRomBuilderEntry* start = iFiles;
+			while(start && start->iRomNode->iRomFile != f)
+				start = start->iNextInArea;
+			if(start && (start->iRomNode->iRomFile == f)) {
+				TRomNode* target = start->iRomNode;
+				TInt l = target->FullNameLength();
+				char* fname = new char[l+1];
+				target->GetFullName(fname);
+				if(myDepInfoList.find(fname) != myDepInfoList.end()) {
+					depFiles.push_back(fname);
+					myDepInfoList[fname].beenDepended = ETrue;
+				}
+				delete []fname;
+			}
+		}
+		if(depFiles.size() > 0) {
+			myDepInfoList[nameList[count]].depFilesList=depFiles;
+			myDepInfoList[nameList[count]].dependOthers = ETrue;
+		}
+		count++;
+		e=e->iNextInArea;
+	}
+	ofstream os;
+	string filename(gDepInfoFile.c_str(), gDepInfoFile.length() - 3);
+	filename = filename + "dot";
+	os.open(filename.c_str());
+	os << "digraph ROM {\n";
+	os << "rankdir = LR;\n";
+	os << "fontsize = 10;\n";
+	os << "fontname = \"Courier New\";\n";
+	os << "label = \"ROM DEPENDENCE GRAPH DOT FILE\";\n";
+	os << "node[shape = plaintext];\n";
+	os << "dependence[label=<<FONT FACE=\"Courier new\" POINT-SIZE=\"10pt\">\n";
+	os << "<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\">\n";
+	//for(infoIt = myDepInfoList.begin(); infoIt != myDepInfoList.end(); infoIt++)
+	for(strIt = nameList.begin(); strIt != nameList.end(); strIt++) {
+		string tmp = *strIt;
+		string::iterator charIt;
+		for(charIt=tmp.begin(); charIt != tmp.end(); charIt++) {
+			if(*charIt == '\\')
+				*charIt = '/';
+		}
+		if(myDepInfoList[*strIt].beenDepended && myDepInfoList[*strIt].dependOthers) {
+			os << "\t<TR><TD PORT=\"" << myDepInfoList[*strIt].portName << "\" ALIGN=\"LEFT\" BGCOLOR=\"yellow\">\n";
+			os << "\t<FONT COLOR=\"red\">" << tmp << "</FONT>\n";
+			os << "\t</TD></TR>\n";
+		}
+		else if(myDepInfoList[*strIt].beenDepended) {
+			os << "\t<TR><TD PORT=\"" << myDepInfoList[*strIt].portName << "\" ALIGN=\"LEFT\" BGCOLOR=\"gray\">\n";
+			os << "\t<FONT COLOR=\"red\">" << tmp << "</FONT>\n";
+			os << "\t</TD></TR>\n";
+		}
+		else if(myDepInfoList[*strIt].dependOthers) {
+			os << "\t<TR><TD PORT=\"" << myDepInfoList[*strIt].portName << "\" ALIGN=\"LEFT\" BGCOLOR=\"cyan\">\n";
+			os << "\t<FONT COLOR=\"blue\">" << tmp << "</FONT>\n";
+			os << "\t</TD></TR>\n";
+		}
+		else {
+			os << "\t<TR><TD PORT=\"" << myDepInfoList[*strIt].portName << "\" ALIGN=\"LEFT\">";
+			os << tmp;
+			os << "</TD></TR>\n";
+		}
+	}
+	os << "</TABLE>\n";
+	os << "</FONT>>]\n";
+	TBool lastEdge = ETrue;
+	TBool first = ETrue;
+	for(infoIt = myDepInfoList.begin(); infoIt != myDepInfoList.end(); infoIt++) {
+		if(!infoIt->second.dependOthers) {
+			continue;
+		}
+		for(strIt = infoIt->second.depFilesList.begin(); strIt != infoIt->second.depFilesList.end(); strIt++) {
+			TBool tmpEdge = ETrue;
+			if(infoIt->second.index < myDepInfoList[*strIt].index)
+			{	
+				tmpEdge = EFalse;
+			}
+			if(first) {
+				lastEdge = tmpEdge;
+				first = EFalse;
+				if(lastEdge) {
+					os << "edge[color=forestgreen];\n";
+				}
+				else {
+					os << "edge[color=red];\n";
+				}
+			}
+			else {
+				if(lastEdge != tmpEdge) {
+					lastEdge = tmpEdge;
+					if(lastEdge) {
+						os << "edge[color=forestgreen];\n";
+					}
+					else {
+						os << "edge[color=red];\n";
+					}
+				}
+			}
+			os << "dependence: " << infoIt->second.portName << " -> dependence: " << myDepInfoList[*strIt].portName << ";\n";
+		}
+	}
+	os << "}\n";
+	os.close();
+	filename = filename.substr(0, filename.size()-4);
+	filename = filename + ".backwarddep.dot";
+	os.open(filename.c_str());
+	os << "digraph ROM {\n";
+	os << "rankdir = LR;\n";
+	os << "fontsize = 10;\n";
+	os << "fontname = \"Courier New\";\n";
+	os << "label = \"ROM FORWARD DEPENDENCE GRAPH DOT FILE\";\n";
+	os << "node[shape = plaintext];\n";
+	os << "dependence[label=<<FONT FACE=\"Courier new\" POINT-SIZE=\"10pt\">\n";
+	os << "<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\">\n";
+	//for(infoIt = myDepInfoList.begin(); infoIt != myDepInfoList.end(); infoIt++)
+	for(strIt = nameList.begin(); strIt != nameList.end(); strIt++) {
+		string tmp = *strIt;
+		string::iterator charIt;
+		for(charIt=tmp.begin(); charIt != tmp.end(); charIt++) {
+			if(*charIt == '\\')
+				*charIt = '/';
+		}
+		if(myDepInfoList[*strIt].beenDepended && myDepInfoList[*strIt].dependOthers) {
+			os << "\t<TR><TD PORT=\"" << myDepInfoList[*strIt].portName << "\" ALIGN=\"LEFT\" BGCOLOR=\"yellow\">\n";
+			os << "\t<FONT COLOR=\"red\">" << tmp << "</FONT>\n";
+			os << "\t</TD></TR>\n";
+		}
+		else if(myDepInfoList[*strIt].beenDepended) {
+			os << "\t<TR><TD PORT=\"" << myDepInfoList[*strIt].portName << "\" ALIGN=\"LEFT\" BGCOLOR=\"gray\">\n";
+			os << "\t<FONT COLOR=\"red\">" << tmp << "</FONT>\n";
+			os << "\t</TD></TR>\n";
+		}
+		else if(myDepInfoList[*strIt].dependOthers) {
+			os << "\t<TR><TD PORT=\"" << myDepInfoList[*strIt].portName << "\" ALIGN=\"LEFT\" BGCOLOR=\"cyan\">\n";
+			os << "\t<FONT COLOR=\"blue\">" << tmp << "</FONT>\n";
+			os << "\t</TD></TR>\n";
+		}
+		else {
+			os << "\t<TR><TD PORT=\"" << myDepInfoList[*strIt].portName << "\" ALIGN=\"LEFT\">";
+			os << tmp;
+			os << "</TD></TR>\n";
+		}
+	}
+	os << "</TABLE>\n";
+	os << "</FONT>>]\n";
+	os << "edge[color=red];\n";
+	for(infoIt = myDepInfoList.begin(); infoIt != myDepInfoList.end(); infoIt++) {
+		if(!infoIt->second.dependOthers) {
+			continue;
+		}
+		for(strIt = infoIt->second.depFilesList.begin(); strIt != infoIt->second.depFilesList.end(); strIt++) {
+			if(infoIt->second.index < myDepInfoList[*strIt].index)
+			{	
+				os << "dependence: " << infoIt->second.portName << " -> dependence: " << myDepInfoList[*strIt].portName << ";\n";
+			}
+		}
+	}
+	os << "}\n";
+	os.close();
+}
+
--- a/imgtools/romtools/rombuild/r_areaset.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_areaset.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,320 +1,321 @@
-/*
-* Copyright (c) 2000-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Area-related API
-*
-*/
-
-
-#ifndef __R_AREASET_H__
-#define __R_AREASET_H__
-
-#include <assert.h>
-#include <string.h>
-#include <stdlib.h>
-#include <assert.h>
-#include <iostream>
-#include <string>
-#include <vector>
-#include <map>
-#include <fstream>
-
-#include <e32std.h>
-#include <e32rom.h>				// TLinAddr
-
-typedef std::vector<std::string> TStringList;
-struct DepInfo
-{
-public:
-	TBool dependOthers;
-	TBool beenDepended;
-	int index;
-	std::string portName;
-	TStringList depFilesList;
-	DepInfo()
-	{
-		dependOthers = EFalse;
-		beenDepended = EFalse;
-		index = -1;
-	}
-};
-typedef std::map<std::string, DepInfo> TDepInfoList;
-
-class TRomBuilderEntry;
-
-/**
- A zone of memory in which files are stored.
-
- Areas (except the default one - see below) are relocated from ROM to
- RAM at boot time.
-
- When created an area is given a "destination base address" (the start
- of the area in RAM) and a maximum size.
-
- During processing the "source base address" (the start of the area in
- ROM) is set once and the area is extended each time a file is
- processed by setting repeatedly the "source limit address" (the top
- of the area in ROM).
-
- The default area contains files that don't need relocation.  So its
- "source base address" and "destination base address" are the same.
-
- @private 
-*/
-
-class Area
-	{
-public:
-	~Area();
-
-	const char* Name() const;
-
-	void SetSrcBaseAddr(TLinAddr aSrcBaseAddr);
-	TLinAddr SrcBaseAddr() const;
-
-	TBool ExtendSrcLimitAddr(TLinAddr aSrcLimitAddr, TUint& aOverflow);
-	TLinAddr SrcLimitAddr() const;
-	
-	TLinAddr DestBaseAddr() const;
-
-	TUint MaxSize() const;
-	TUint UsedSize() const;
-
-	TBool IsDefault() const;
-
-	void AddFile(TRomBuilderEntry* aFile);
-
-	TInt SortFilesForPagedRom();
-private:
-	// only AreaSet can create areas
-	Area(const char* aName, TLinAddr aDestBaseAddr, TUint aMaxSize, Area* aNext=0);
-	void ReleaseAllFiles();
-	void WriteDependenceGraph();
-public:
-	TRomBuilderEntry* iFirstPagedCode; // For PagedRom only
-private:
-	const char* iName;
-	TLinAddr iDestBaseAddr;
-	TLinAddr iSrcBaseAddr;
-	TLinAddr iSrcLimitAddr;
-	TUint iMaxSize;
-
-	TBool iIsDefault;
-
-	TRomBuilderEntry* iFiles;
-	TRomBuilderEntry** iNextFilePtrPtr;
-
-	Area* iNextArea;
-
-	friend class AreaSet;
-	friend class FilesInAreaIterator;
-	friend class NonDefaultAreasIterator;
-	};
-
-
-inline  const char* Area::Name() const
-	{
-	return iName;
-	}
-
-
-inline void Area::SetSrcBaseAddr(TLinAddr aSrcBaseAddr)
-	{
-	// setting allowed only once
-	assert(iSrcBaseAddr == 0);	
-	assert(aSrcBaseAddr != 0);
-
-	iSrcLimitAddr = iSrcBaseAddr = aSrcBaseAddr;
-	}
-
-
-inline TLinAddr Area::SrcBaseAddr() const
-	{
-	// must have been set before
-	assert(iSrcBaseAddr != 0);
-	return iSrcBaseAddr;
-	}
-
-
-inline TLinAddr Area::SrcLimitAddr() const
-	{
-	// must have been set before
-	assert(iSrcBaseAddr != 0);
-	return iSrcLimitAddr;
-	}
-
-
-inline TLinAddr Area::DestBaseAddr() const
-	{
-	return iDestBaseAddr;
-	}
-
-
-inline TUint Area::MaxSize() const
-	{
-	return iMaxSize;
-	}
-
-
-inline TUint Area::UsedSize() const
-	{
-	return iSrcLimitAddr-iSrcBaseAddr;
-	}
-
-
-inline TBool Area::IsDefault() const
-	{
-	return iIsDefault;
-	}
-
-
-////////////////////////////////////////////////////////////////////////
-
-class TRomBuilderEntry;
-
-/**
- Iterate over every file in a given area.
-
- Files are iterated in the order in which they have been appended to
- the area.  
- 
- @private
-*/
-
-class FilesInAreaIterator
-	{
-public:
-	FilesInAreaIterator(const Area& aArea);
-
-	TBool IsDone() const;
-	TRomBuilderEntry* Current() const;
-	void GoToNext();
-
-private:
-	TRomBuilderEntry* iCurrentFile;
-	};
-
-
-inline FilesInAreaIterator::FilesInAreaIterator(const Area& aArea)
-	: iCurrentFile(aArea.iFiles)
-	{
-	}
-
-inline TBool FilesInAreaIterator::IsDone() const
-	{
-	return iCurrentFile == 0;
-	}
-
-inline TRomBuilderEntry* FilesInAreaIterator::Current() const
-	{
-	return iCurrentFile;
-	}
-
-////////////////////////////////////////////////////////////////////////
-
-/**
- Set of areas indexed by name.
-
- There can be only one default area identified by its name
- (KDefaultAreaName).
-
- @private 
-*/
-
-class AreaSet
-	{
-public:
-	enum TAddResult
-		{ 
-		EAdded,
-		EOverlap,
-		EDuplicateName,
-		EOverflow,
-		};
-
-public:
-	AreaSet();
-	~AreaSet();
-
-	TAddResult AddArea(const char* aName, TLinAddr aDestBaseAddr, TUint aMaxSize, const char*& aOverlappingArea);
-	void ReleaseAllAreas();
-
-	Area* FindByName(const char* aName) const;
-	TInt Count() const;
-	Area* DefaultArea() const;
-
-private:
-	Area* iNonDefaultAreas;
-	Area* iDefaultArea;
-	TInt iAreaCount;
-
-public:
-	static const char KDefaultAreaName[];
-
-	friend class NonDefaultAreasIterator;
-	};
-
-
-inline TInt AreaSet::Count() const
-	{
-	return iAreaCount;
-	}
-
-
-inline Area* AreaSet::DefaultArea() const
-	{
-	return iDefaultArea;
-	}
-
-
-////////////////////////////////////////////////////////////////////////
-
-
-/**
-
- Iterate over every non-default area of a given area set.
-
- @private
-*/
-
-class NonDefaultAreasIterator
-	{
-public:
-	NonDefaultAreasIterator(const AreaSet& aAreaSet);
-
-	TBool IsDone() const;
-	Area& Current() const;
-	void GoToNext();
-
-private:
-	Area* iCurrentArea;
-	};
-
-inline NonDefaultAreasIterator::NonDefaultAreasIterator(const AreaSet& aAreaSet)
-	: iCurrentArea(aAreaSet.iNonDefaultAreas)
-	{
-	}
-
-inline TBool NonDefaultAreasIterator::IsDone() const
-	{
-	return iCurrentArea == 0;
-	}
-
-inline Area& NonDefaultAreasIterator::Current() const
-	{
-	assert(iCurrentArea != 0);
-	return *iCurrentArea;
-	}
-
-#endif // __R_AREASET_H__
+/*
+* Copyright (c) 2000-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Area-related API
+*
+*/
+
+
+#ifndef __R_AREASET_H__
+#define __R_AREASET_H__
+
+#include <assert.h>
+#include <string.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <iostream>
+#include <string>
+#include <vector>
+#include <map>
+#include <fstream>
+
+#include <e32std.h>
+#include <e32rom.h>				// TLinAddr
+using namespace std;
+
+typedef vector<string> TStringList;
+struct DepInfo
+{
+public:
+	TBool dependOthers;
+	TBool beenDepended;
+	int index;
+	string portName;
+	TStringList depFilesList;
+	DepInfo()
+	{
+		dependOthers = EFalse;
+		beenDepended = EFalse;
+		index = -1;
+	}
+};
+typedef map<string, DepInfo> TDepInfoList;
+
+class TRomBuilderEntry;
+
+/**
+ A zone of memory in which files are stored.
+
+ Areas (except the default one - see below) are relocated from ROM to
+ RAM at boot time.
+
+ When created an area is given a "destination base address" (the start
+ of the area in RAM) and a maximum size.
+
+ During processing the "source base address" (the start of the area in
+ ROM) is set once and the area is extended each time a file is
+ processed by setting repeatedly the "source limit address" (the top
+ of the area in ROM).
+
+ The default area contains files that don't need relocation.  So its
+ "source base address" and "destination base address" are the same.
+
+ @private 
+*/
+
+class Area
+	{
+public:
+	~Area();
+
+	const char* Name() const;
+
+	void SetSrcBaseAddr(TLinAddr aSrcBaseAddr);
+	TLinAddr SrcBaseAddr() const;
+
+	TBool ExtendSrcLimitAddr(TLinAddr aSrcLimitAddr, TUint& aOverflow);
+	TLinAddr SrcLimitAddr() const;
+	
+	TLinAddr DestBaseAddr() const;
+
+	TUint MaxSize() const;
+	TUint UsedSize() const;
+
+	TBool IsDefault() const;
+
+	void AddFile(TRomBuilderEntry* aFile);
+
+	TInt SortFilesForPagedRom();
+private:
+	// only AreaSet can create areas
+	Area(const char* aName, TLinAddr aDestBaseAddr, TUint aMaxSize, Area* aNext=0);
+	void ReleaseAllFiles();
+	void WriteDependenceGraph();
+public:
+	TRomBuilderEntry* iFirstPagedCode; // For PagedRom only
+private:
+	char* iName;
+	TLinAddr iDestBaseAddr;
+	TLinAddr iSrcBaseAddr;
+	TLinAddr iSrcLimitAddr;
+	TUint iMaxSize;
+
+	TBool iIsDefault;
+
+	TRomBuilderEntry* iFiles;
+	TRomBuilderEntry** iNextFilePtrPtr;
+
+	Area* iNextArea;
+
+	friend class AreaSet;
+	friend class FilesInAreaIterator;
+	friend class NonDefaultAreasIterator;
+	};
+
+
+inline  const char* Area::Name() const
+	{
+	return iName;
+	}
+
+
+inline void Area::SetSrcBaseAddr(TLinAddr aSrcBaseAddr)
+	{
+	// setting allowed only once
+	assert(iSrcBaseAddr == 0);	
+	assert(aSrcBaseAddr != 0);
+
+	iSrcLimitAddr = iSrcBaseAddr = aSrcBaseAddr;
+	}
+
+
+inline TLinAddr Area::SrcBaseAddr() const
+	{
+	// must have been set before
+	assert(iSrcBaseAddr != 0);
+	return iSrcBaseAddr;
+	}
+
+
+inline TLinAddr Area::SrcLimitAddr() const
+	{
+	// must have been set before
+	assert(iSrcBaseAddr != 0);
+	return iSrcLimitAddr;
+	}
+
+
+inline TLinAddr Area::DestBaseAddr() const
+	{
+	return iDestBaseAddr;
+	}
+
+
+inline TUint Area::MaxSize() const
+	{
+	return iMaxSize;
+	}
+
+
+inline TUint Area::UsedSize() const
+	{
+	return iSrcLimitAddr-iSrcBaseAddr;
+	}
+
+
+inline TBool Area::IsDefault() const
+	{
+	return iIsDefault;
+	}
+
+
+////////////////////////////////////////////////////////////////////////
+
+class TRomBuilderEntry;
+
+/**
+ Iterate over every file in a given area.
+
+ Files are iterated in the order in which they have been appended to
+ the area.  
+ 
+ @private
+*/
+
+class FilesInAreaIterator
+	{
+public:
+	FilesInAreaIterator(const Area& aArea);
+
+	TBool IsDone() const;
+	TRomBuilderEntry* Current() const;
+	void GoToNext();
+
+private:
+	TRomBuilderEntry* iCurrentFile;
+	};
+
+
+inline FilesInAreaIterator::FilesInAreaIterator(const Area& aArea)
+	: iCurrentFile(aArea.iFiles)
+	{
+	}
+
+inline TBool FilesInAreaIterator::IsDone() const
+	{
+	return iCurrentFile == 0;
+	}
+
+inline TRomBuilderEntry* FilesInAreaIterator::Current() const
+	{
+	return iCurrentFile;
+	}
+
+////////////////////////////////////////////////////////////////////////
+
+/**
+ Set of areas indexed by name.
+
+ There can be only one default area identified by its name
+ (KDefaultAreaName).
+
+ @private 
+*/
+
+class AreaSet
+	{
+public:
+	enum TAddResult
+		{ 
+		EAdded,
+		EOverlap,
+		EDuplicateName,
+		EOverflow,
+		};
+
+public:
+	AreaSet();
+	~AreaSet();
+
+	TAddResult AddArea(const char* aName, TLinAddr aDestBaseAddr, TUint aMaxSize, const char*& aOverlappingArea);
+	void ReleaseAllAreas();
+
+	Area* FindByName(const char* aName) const;
+	TInt Count() const;
+	Area* DefaultArea() const;
+
+private:
+	Area* iNonDefaultAreas;
+	Area* iDefaultArea;
+	TInt iAreaCount;
+
+public:
+	static const char KDefaultAreaName[];
+
+	friend class NonDefaultAreasIterator;
+	};
+
+
+inline TInt AreaSet::Count() const
+	{
+	return iAreaCount;
+	}
+
+
+inline Area* AreaSet::DefaultArea() const
+	{
+	return iDefaultArea;
+	}
+
+
+////////////////////////////////////////////////////////////////////////
+
+
+/**
+
+ Iterate over every non-default area of a given area set.
+
+ @private
+*/
+
+class NonDefaultAreasIterator
+	{
+public:
+	NonDefaultAreasIterator(const AreaSet& aAreaSet);
+
+	TBool IsDone() const;
+	Area& Current() const;
+	void GoToNext();
+
+private:
+	Area* iCurrentArea;
+	};
+
+inline NonDefaultAreasIterator::NonDefaultAreasIterator(const AreaSet& aAreaSet)
+	: iCurrentArea(aAreaSet.iNonDefaultAreas)
+	{
+	}
+
+inline TBool NonDefaultAreasIterator::IsDone() const
+	{
+	return iCurrentArea == 0;
+	}
+
+inline Area& NonDefaultAreasIterator::Current() const
+	{
+	assert(iCurrentArea != 0);
+	return *iCurrentArea;
+	}
+
+#endif // __R_AREASET_H__
--- a/imgtools/romtools/rombuild/r_build.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_build.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,2101 +1,1809 @@
-/*
-* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#define __REFERENCE_CAPABILITY_NAMES__
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-#include <e32std.h>
-#include <e32std_private.h>
-#include <e32rom.h>
-#include "u32std.h"
-#include <e32uid.h>
-#include <f32file.h>
-#include "h_utl.h"
-
-#define USE_IAT_FOR_IMPORTS (iOverrideFlags&KOverrideKeepIAT || (iHdr->iCpuIdentifier & 0x1000))
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-#include <iomanip>
-#else //!__MSVCDOTNET__
-#include <iomanip.h>
-#endif
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-#include <iomanip>
-#else //!__MSVCDOTNET__
-#include <iomanip.h>
-#endif
-
-#include "r_obey.h"
-#include "r_global.h"
-#include "r_dir.h"
-
-TInt NumRootDirs;
-
-inline TLinAddr ActualToRomAddress(TAny* anAddr)
-	{ return TLinAddr(anAddr)-TheRomMem+TheRomLinearAddress; }
-
-TBool THardwareVariant::MutuallyExclusive(THardwareVariant a) const
-	{
-	if (Layer()<=3 || a.Layer()<=3)
-		return EFalse;
-	if (Parent()==3 && a.Parent()==3)
-		return(Layer()!=a.Layer());
-	if (Parent()==3 && a.Parent()!=Layer())
-		return ETrue;
-	if (a.Parent()==3 && Parent()!=a.Layer())
-		return ETrue;
-	if (Layer()!=a.Layer())
-		return ETrue;
-	return((VMask()&a.VMask())==0);
-	}
-
-TBool THardwareVariant::IsVariant() const
-	{
-	if (Layer()<=3 || Parent()==3)
-		return EFalse;
-	TUint v=VMask();
-	TInt i;
-	for (i=0; i<16; i++)
-		{
-		if (v==TUint(1<<i))
-			return ETrue;
-		}
-	return EFalse;
-	}
-
-TInt THardwareVariant::Compare(THardwareVariant a) const
-	{
-	TUint l1=Layer();
-	TUint p1=Parent();
-	TUint v1=VMask();
-	TUint l2=a.Layer();
-	TUint p2=a.Parent();
-	TUint v2=a.VMask();
-
-	if (l1<=3)
-		{
-		if (l2<=3)
-			{
-			return EEqual;
-			}
-		return EGreater;
-		}
-	if (l2<=3)
-		return ELess;
-	if (p1==3)
-		{
-		if (p2==3)
-			{
-			if (l1==l2)
-				return EEqual;
-			return EUnordered;
-			}
-		if (p2==l1)
-			return EGreater;
-		return EUnordered;
-		}
-	if (p2==3)
-		{
-		if (p1==l2)
-			return ELess;
-		return EUnordered;
-		}
-	if (l1!=l2)
-		return EUnordered;
-	if ((v1&v2)==v1)
-		return ELess;
-	if ((v1&v2)==v2)
-		return EGreater;
-	return EUnordered;
-	}
-//
-TInt TRomNode::Count=0;
-TRomNode::TRomNode(const TText* aName, TRomBuilderEntry* aEntry)
-//
-// Constructor from TRomBuilderEntry, i.e. for new file or directory
-//
-	{
-	memset(this, 0, sizeof(TRomNode));
-	iAtt = (TUint8)KEntryAttReadOnly;
-	iName = (TText*)NormaliseFileName((const char*)aName);
-	iIdentifier=TRomNode::Count++;
-	iRomFile = new TRomFile;
-	if (aEntry)
-		{
-		iRomFile->iRbEntry = aEntry;
-		aEntry->SetRomNode(this);
-		iBareName = strdup(aEntry->iBareName);
-		iRomFile->iHwvd = aEntry->iHardwareVariant;
-		}
-	else
-		{
-		iRomFile->iDir = ETrue;
-		iAtt |= (TUint8)KEntryAttDir;
-		iBareName = strdup((const char*)iName);
-		iRomFile->iHwvd = KVariantIndependent;
-		}
-	TRACE(TROMNODE,Print(ELog, "TRomNode %d name %s bare %s att %02x romfile %08x\n", iIdentifier,
-			iName, iBareName, iAtt, iRomFile));
-	}
-
-TRomNode::TRomNode(const TText* aName, TRomNode* aNode)
-//
-// Constructor from TRomNode, i.e. for aliased file
-//
-	{
-	memset(this, 0, sizeof(TRomNode));
-	iAtt = aNode->iAtt;
-	iIdentifier=TRomNode::Count++;
-	iName = (TText*)NormaliseFileName((const char*)aName);
-	iHidden = aNode->iHidden;
-	iRomFile = aNode->iRomFile;
-	if (iRomFile)
-		{
-		iRomFile->Open();
-		}
-	TRACE(TROMNODE,Print(ELog, "TRomNode %d DUP name %s romfile %08x\n", iIdentifier, iName, iRomFile));
-	}
-
-TRomNode::TRomNode(const TRomNode& aNode)
-//
-// Copy constructor - only used in deep copy function
-//
-	{
-	memset(this, 0, sizeof(TRomNode));
-	iAtt = aNode.iAtt;
-	iIdentifier=TRomNode::Count++;
-	iName = (TText*)strdup((const char*)aNode.iName);
-	iBareName = strdup(aNode.iBareName);
-	iHidden = aNode.iHidden;
-	iRomFile = aNode.iRomFile;
-	if (iRomFile)
-		{
-		iRomFile->Open();
-		}
-	TRACE(TROMNODE,Print(ELog, "TRomNode %d COPY name %s bare %s att %02x romfile %08x\n", iIdentifier,
-			iName, iBareName, iAtt, iRomFile));
-	}
-
-TRomNode::~TRomNode()
-	{
-	free(iName);
-	free(iBareName);
-	if (iRomFile)
-		iRomFile->Close();
-	}
-
-TRomNode* TRomNode::FindInDirectory(const TText* aName)
-//
-// Check if the TRomNode for aName exists in aDir, and if so, return it.
-//
-	{
-
-	TRomNode *entry=iChild; // first subdirectory or file
-	while (entry)
-		{
-		if (!entry->iHidden && (stricmp((const char *)aName, (const char *)entry->iName))==0) 
-			return entry;
-		else
-			entry=entry->iSibling;
-		}
-	return 0;
-	}
-
-TRomNode* TRomNode::FindInDirectory(const TText* aName, THardwareVariant aVariant, TBool aPatchDataFlag)
-//
-// Check for a file with same name and a compatible hardware variant
-//
-	{
-
-	TRomNode *entry=iChild; // first subdirectory or file
-	while (entry)
-		{
-		if (((!entry->iHidden)||aPatchDataFlag) && entry->iRomFile && (stricmp((const char *)aName, (const char *)entry->iName))==0) 
-			{
-			if (!aVariant.MutuallyExclusive(entry->HardwareVariant()))
-				return entry;
-			}
-		entry=entry->iSibling;
-		}
-	return 0;
-	}
-
-void TRomNode::AddFile(TRomNode* aChild)
-	{
-	if (!(iAtt & KEntryAttDir))
-		{
-		Print(EError, "Adding subdirectory to a file!!!\n");
-		return;
-		}
-	Add(aChild);
-	}
-
-TRomNode* TRomNode::NewSubDir(const TText* aName)
-	{
-	if (!(iAtt & KEntryAttDir))
-		{
-		Print(EError, "Adding subdirectory to a file!!!\n");
-		return 0;
-		}
-
-	TRomNode* node = new TRomNode(aName);
-	if (node==0)
-		{
-		Print(EError, "TRomNode::NewNode: Out of memory\n");
-		return 0;
-		}
-	Add(node);
-	return node;
-	}
-
-void TRomNode::Add(TRomNode* aChild)
-	{
-	if (iChild) // this node is a non-empty directory
-		{
-		TRomNode* dir = iChild; // find where to link in the new node
-		while (dir->iSibling)
-			dir = dir->iSibling;
-		dir->iSibling = aChild;
-		}
-	else
-		iChild = aChild; // else just set it up as the child of the dir
-	aChild->iSibling = 0;
-	aChild->iParent = this;
-	}
-
-void TRomNode::Remove(TRomNode* aChild)
-	{
-	if (iChild==0)
-		{
-		Print(EError, "Removing file from a file!!!\n");
-		return;
-		}
-	if (iChild==aChild) // first child in this directory
-		{
-		iChild = aChild->iSibling;
-		aChild->iSibling = 0;
-		aChild->iParent = 0;
-		return;
-		}
-	TRomNode* prev = iChild;
-	while (prev->iSibling && prev->iSibling != aChild)
-		prev = prev->iSibling;
-	if (prev==0)
-		{
-		Print(EError, "Attempting to remove file not in this directory!!!\n");
-		return;
-		}
-	prev->iSibling = aChild->iSibling;
-	aChild->iSibling = 0;
-	aChild->iParent = 0;
-	}
-
-void TRomNode::CountDirectory(TInt& aFileCount, TInt& aDirCount)
-	{
-	TRomNode *current=iChild;
-	while(current)
-		{
-		if (current->iChild)
-			aDirCount++;
-		else if (!current->iHidden)
-			aFileCount++;
-		current=current->iSibling;
-		}
-	}
-
-/**
- * Walk the contents of the directory, accumulating the
- * files as FileEntry objects in the specified RomFileStructure
- * and recursively handling the sub-directories
- *
- * TRomNode::ProcessDirectory is a pair with
- * RomFileStructure::ProcessDirectory
- */
-int TRomNode::ProcessDirectory(RomFileStructure* aRFS)
-	{
-	TInt r=KErrNone;
-	TRomNode *current=iChild;
-	while(current)
-		{
-		if (current->iAtt & (TUint8)KEntryAttDir)
-			{
-			r=aRFS->ProcessDirectory(current);
-			if (r!=KErrNone)
-				return r;
-			}
-		else if (!current->iHidden)
-			{
-			FileEntry *pE=FileEntry::New(current);
-			if (!pE)
-				return KErrNoMemory;
-			r=aRFS->Add(*pE);
-			if (r==KErrOverflow)
-				return r;
-			}
-		current=current->iSibling;
-		}
-	return r;
-	}
-
-void TRomNode::AddExecutableFile(TRomNode*& aLast, TRomNode* aNode)
-	{
-	aLast->iNextExecutable = aNode;
-	aLast = aNode;
-	aNode->iAtt |= KEntryAttXIP;
-	}
-
-char* TRomNode::BareName() const
-	{
-	return iBareName;
-	}
-
-TUint32 TRomNode::Uid3() const
-	{
-	return iRomFile->Uid3();
-	}
-
-TUint32 TRomNode::ModuleVersion() const
-	{
-	return iRomFile->ModuleVersion();
-	}
-
-THardwareVariant TRomNode::HardwareVariant() const
-	{
-	return iRomFile->HardwareVariant();
-	}
-
-TUint32 TRomNode::ABI() const
-	{
-	return iRomFile->ABI();
-	}
-
-TUint32 TRomFile::Uid3() const
-	{
-	assert(!iDir);
-	if (iRbEntry)
-	{
-		if(iRbEntry->iHdr)
-			return iRbEntry->iHdr->iUid3;
-	}
-	return RomImgHdr()->iUid3;
-	}
-
-TUint32 TRomFile::ModuleVersion() const
-	{
-	assert(!iDir);
-	if (iRbEntry)
-	{
-		if(iRbEntry->iHdr)
-			return iRbEntry->iHdr->ModuleVersion();
-	}
-	return RomImgHdr()->iModuleVersion;
-	}
-
-THardwareVariant TRomFile::HardwareVariant() const
-	{
-	return iHwvd;
-	}
-
-TUint32 TRomFile::ABI() const
-	{
-	assert(!iDir);
-	if (iRbEntry)
-	{
-		if(iRbEntry->iHdr)
-			return iRbEntry->iHdr->ABI();
-	}
-	return RomImgHdr()->iFlags & KRomImageABIMask;
-	}
-
-TInt TRomFile::ExportDirCount() const
-	{
-	assert(!iDir);
-	if (iRbEntry)
-	{
-		if(iRbEntry->iHdr)
-			return iRbEntry->iHdr->iExportDirCount;
-	}
-	return RomImgHdr()->iExportDirCount;
-	}
-
-TUint32 TRomFile::RomImageFlags() const
-	{
-	assert(!iDir);
-	if (iRbEntry)
-		{
-		if(iRbEntry->iHdr)
-		{
-		const TUint KRomFlagMask = KImageDll | KImageNoCallEntryPoint | KImageFixedAddressExe | KImageNmdExpData;
-		TUint romflags = iRbEntry->iHdr->iFlags & KRomFlagMask;
-		return iRbEntry->iRomImageFlags | romflags;
-		}
-		}
-	return RomImgHdr()->iFlags;
-	}
-
-TLinAddr TRomFile::DataBssLinearBase() const
-	{
-	assert(!iDir);
-	if (iRbEntry)
-		return iRbEntry->iDataBssLinearBase;
-	return RomImgHdr()->iDataBssLinearBase;
-	}
-
-const SSecurityInfo& TRomFile::SecurityInfo() const
-	{
-	assert(!iDir);
-	if (iRbEntry)
-		return iRbEntry->iS;
-	return RomImgHdr()->iS;
-	}
-
-TInt TRomNode::FullNameLength(TBool aIgnoreHiddenAttrib) const
-	{
-	TInt l = 0;
-	// aIgnoreHiddenAttrib is used to find the complete file name length as
-	// in ROM of a hidden file.
-	if (iParent && ( !iHidden || aIgnoreHiddenAttrib))
-		l = iParent->FullNameLength() + 1;
-	l += strlen((const char*)iName);
-	return l;
-	}
-
-TInt TRomNode::GetFullName(char* aBuf, TBool aIgnoreHiddenAttrib) const
-	{
-	TInt l = 0;
-	TInt nl = strlen((const char*)iName);
-	// aIgnoreHiddenAttrib is used to find the complete file name as in ROM of a hidden file.
-	if (iParent && ( !iHidden || aIgnoreHiddenAttrib))
-		l = iParent->GetFullName(aBuf);
-	char* b = aBuf + l;
-	if (l)
-		*b++ = '\\', ++l;
-	memcpy(b, iName, nl);
-	b += nl;
-	*b = 0;
-	l += nl;
-	return l;
-	}
-
-TInt CompareCapabilities(const SCapabilitySet& aSubCaps, const SCapabilitySet& aSuperCaps, const char* aSubName, const char* aSuperName)
-//
-//	Check that a aSubCaps are a subset of aSuperCaps
-//
-	{
-	if ((!gPlatSecEnforcement)&&(!gPlatSecDiagnostics))
-		return KErrNone;
-	TInt i;
-	TUint32 c = 0;
-	for (i=0; i<SCapabilitySet::ENCapW; ++i)
-		c |= (aSubCaps[i] &~ aSuperCaps[i]);
-	TInt r = c ? KErrPermissionDenied : KErrNone;
-	if (r && aSubName && aSuperName)
-		{
-		TPrintType printType;
-		if(gPlatSecEnforcement)
-			printType = EError;
-		else
-			{
-			printType = EWarning;
-			r = KErrNone;
-			}
-		char* buf = (char*)malloc(2);
-		if(!buf)
-			return KErrNoMemory;
-		TInt len = 0;
-		for(i=0; i<ECapability_Limit; i++)
-			{
-			if( (aSubCaps[i>>5] &~ aSuperCaps[i>>5]) & (1<<(i&31)) )
-				{
-				// append capability name to buf
-				const char* name = CapabilityNames[i];
-				if(!name)
-					continue;
-				if(len)
-					{
-					buf[len++] = ' ';
-					}
-				int nameLen=strlen(name);
-				buf = (char*)realloc(buf,len+nameLen+2);
-				if(!buf)
-					return KErrNoMemory;
-				memcpy(buf+len,CapabilityNames[i],nameLen);
-				len += nameLen;
-				}
-			}
-		buf[len]=0;
-		Print(printType, "*PlatSec* %s - Capability check failed. Can't load %s because it links to %s which has the following capabilities missing: %s\n",gPlatSecEnforcement?"ERROR":"WARNING",aSubName, aSuperName, buf);
-		free(buf);
-		}
-	return r;
-	}
-
-TDllFindInfo::TDllFindInfo(const char* aImportName, const TRomBuilderEntry* aEntry)
-	{
-	TUint32 flags;
-	iBareName = SplitFileName(aImportName, iUid3, iModuleVersion, flags);
-	assert(iBareName != 0);
-	iHwVariant = aEntry->iHardwareVariant.ReturnVariant(); 
-	}
-
-TDllFindInfo::~TDllFindInfo()
-	{
-	free((void*)iBareName);
-	}
-
-// Generate name as follows:
-// PC filename (UID3:xxxxxxxx HWVD:xxxxxxxx VER:M.m)
-TModuleName::TModuleName(const TRomBuilderEntry* a)
-	{
-	TInt l = strlen(a->iFileName) + strlen(" (UID3:xxxxxxxx HWVD:xxxxxxxx VER:MMMMM.mmmmm)");
-	iName = (char*)malloc(l + 1);
-	assert(iName != 0);
-	sprintf(iName, "%s (UID3:%08lx HWVD:%08lx VER:%ld.%ld)", a->iFileName, a->iHdr->iUid3,
-		a->iHardwareVariant.ReturnVariant(), a->iHdr->ModuleVersion()>>16, a->iHdr->ModuleVersion()&0x0000ffffu);
-	}
-
-// Generate name as follows:
-// Bare name (UID3:xxxxxxxx HWVD:xxxxxxxx VER:M.m)
-TModuleName::TModuleName(const TDllFindInfo& a)
-	{
-	TInt l = strlen(a.iBareName) + strlen(" (UID3:xxxxxxxx HWVD:xxxxxxxx VER:MMMMM.mmmmm)");
-	iName = (char*)malloc(l + 1);
-	assert(iName != 0);
-	sprintf(iName, "%s (UID3:%08lx HWVD:%08lx VER:%ld.%ld)", a.iBareName, a.iUid3,
-		a.iHwVariant, a.iModuleVersion>>16, a.iModuleVersion&0x0000ffffu);
-	}
-
-// Generate name as follows:
-// Name (UID3:xxxxxxxx HWVD:xxxxxxxx VER:M.m)
-TModuleName::TModuleName(const TRomNode& a)
-	{
-	TBool xip = (a.iAtt & KEntryAttXIP);
-	TUint32 uid3 = xip ? a.Uid3() : 0;
-	TUint32 hwvd = (TUint)a.HardwareVariant();
-	TUint32 ver = xip ? a.ModuleVersion() : 0;
-	TInt l = a.FullNameLength() + strlen(" (UID3:xxxxxxxx HWVD:xxxxxxxx VER:MMMMM.mmmmm)");
-	iName = (char*)malloc(l + 1);
-	assert(iName != 0);
-	char* b = iName + a.GetFullName(iName);
-	sprintf(b, " (UID3:%08lx HWVD:%08lx VER:%ld.%ld)", uid3, hwvd, ver>>16, ver&0x0000ffffu);
-	}
-
-TModuleName::TModuleName(const TRomFile& a, const TRomNode* aRootDir)
-	{
-	iName = 0;
-	if (a.iRbEntry)
-		{
-		new (this) TModuleName(a.iRbEntry);
-		return;
-		}
-	TRomNode* x = aRootDir->iNextExecutable;
-	for(; x; x=x->iNextExecutable)
-		{
-		if (x->iRomFile == &a)
-			{
-			new (this) TModuleName(*x);
-			return;
-			}
-		}
-	}
-
-TModuleName::~TModuleName()
-	{
-	free(iName);
-	}
-
-
-/**
- * TRomNode::FindImageFileByName is always called on the root TRomNode, so
- * it doesn't consider the current TRomNode, just the linked items in the
- * iNextExecutable list.
- */
-TRomNode* TRomNode::FindImageFileByName(const TDllFindInfo& aInfo, TBool aPrintDiag, TBool& aFallBack)
-	{
-	TUint r_major = aInfo.iModuleVersion >> 16;
-	TUint r_minor = aInfo.iModuleVersion & 0x0000ffffu;
-	TRomNode* fallback = NULL;
-	aFallBack = EFalse;
-	for (TRomNode* x=iNextExecutable; x!=0; x=x->iNextExecutable)
-		{
-		if (stricmp(x->BareName(), aInfo.iBareName))
-			continue;	// name doesn't match
-		if (aPrintDiag)
-			Print(ELog, "Candidate: %s ", (const char*)TModuleName(*x) );
-		if ( !(THardwareVariant(aInfo.iHwVariant) <= x->HardwareVariant()) )
-			{
-			if (aPrintDiag)
-				Print(ELog, "HWVD mismatch - requested %08x\n", aInfo.iHwVariant);
-			continue;
-			}
-		if (aInfo.iUid3 && (aInfo.iUid3 != x->Uid3()))
-			{
-			if (aPrintDiag)
-				Print(ELog, "UID3 mismatch - requested %08x\n", aInfo.iUid3);
-			continue;
-			}
-		TUint x_major = x->ModuleVersion() >> 16;
-		TUint x_minor = x->ModuleVersion() & 0x0000ffffu;
-		if ( x->ModuleVersion() == 0x00010000 && aInfo.iModuleVersion == 0 )
-			{
-			// allow requested version 0.0 to link to 1.0 with a warning
-			fallback = x;
-			}
-		if ( x_major != r_major )
-			{
-			if (aPrintDiag)
-				Print(ELog, "Major version mismatch - requested %d\n", r_major);
-			continue;
-			}
-		if ( x_minor < r_minor )
-			{
-			if (aPrintDiag)
-				Print(ELog, "??? Minor version mismatch - requested %d\n", r_minor);
-			continue;
-			}
-		if (aPrintDiag)
-			Print(ELog, "OK\n");
-		return x;
-		}
-	if (fallback)
-		{
-		aFallBack = ETrue;
-		return fallback;
-		}
-	return 0;
-	}
-
-TInt TRomNode::CheckForVersionConflicts(const TRomBuilderEntry* a)
-	{
-	TUint r_major = a->iHdr->ModuleVersion() >> 16;
-	TUint r_minor = a->iHdr->ModuleVersion() & 0x0000ffffu;
-	TInt errors = 0;
-	for (TRomNode* x=iNextExecutable; x!=0; x=x->iNextExecutable)
-		{
-		if (x->iRomFile->iRbEntry == a)
-			continue;	// don't compare a with itself
-		if (stricmp(x->BareName(), a->iBareName))
-			continue;	// name doesn't match
-		if ( a->iHardwareVariant.MutuallyExclusive(x->HardwareVariant()) )
-			continue;	// HWVDs are mutually exclusive
-		if ( a->iHdr->iUid3 && x->Uid3() && (a->iHdr->iUid3 != x->Uid3()) )
-			continue;	// UID3's don't match
-		TUint x_major = x->ModuleVersion() >> 16;
-		TUint x_minor = x->ModuleVersion() & 0x0000ffffu;
-		if (x_major == r_major && x_minor != r_minor)	// allow two copies of same file
-			{
-			Print(EError, "Version Conflict %s with %s\n", (const char*)TModuleName(a), (const char*)TModuleName(*x) );
-			++errors;
-			}
-		}
-	return errors;
-	}
-
-TInt E32Rom::WriteHeadersToRom(char *anAddr)
-//
-// Follow the TRomBuilderEntry tree, writing TRomEntry headers to the rom.
-//
-	{
-	TRACE(TTIMING,Print(EAlways,"0\n"));
-	TRACE(TDIR,Print(EAlways,"WriteHeadersToRom()\n"));
-	char* start=anAddr;
-	TRomRootDirectoryList* dirPointers=(TRomRootDirectoryList*)anAddr;
-	anAddr+=NumberOfVariants*sizeof(TRootDirInfo)+sizeof(TInt);
-	RomFileStructure* pS=RomFileStructure::New(NumberOfVariants);
-	if (!pS)
-		Print(EError,"Error creating RomFileStructure\n");
-	TInt r=pS->ProcessDirectory(iObey->iRootDirectory);
-	if (r!=KErrNone)
-		Print(EError,"Error %d processing directory tree\n",r);
-	TInt c=pS->Count();
-	NumRootDirs=c;
-	if (c!=NumberOfVariants)
-		Print(EError,"Error processing directory tree NR=%d NV=%d\n",c,NumberOfVariants);
-	dirPointers->iNumRootDirs=c;
-	TInt i;
-	TRACE(TDIR,Print(EAlways,"Count=%d\n",c));
-	TRACE(TDIR,pS->DebugPrint());
-	for(i=0; i<c; i++)
-		{
-		DirEntry* pD=(DirEntry*)&(*pS)[i];
-		TRomDir* pR=pD->CreateRomEntries(anAddr);
-		dirPointers->iRootDir[i].iHardwareVariant=TUint(pD->Variants().Lookup());
-		dirPointers->iRootDir[i].iAddressLin=ActualToRomAddress(pR);
-		}
-	TRACE(TDIR,Print(EAlways,"Beginning final cleanup\n"));
-	delete pS;
-	TRACE(TTIMING,Print(EAlways,"1\n"));
-	return anAddr-start;
-	}
-
- void TRomNode::Destroy()
-//
-// Follow the TRomNode tree, destroying it
-//
-	{
-
- 	TRomNode *current = this; // root has no siblings
-	while (current)
-		{
-		if (current->iChild)
-			current->iChild->Destroy();
-		TRomNode* prev=current;
-		current=current->iSibling;
-		delete prev;
-		}
- 	}
-
-
-TInt TRomNode::SetAtt(TText *anAttWord)
-//
-// Set the file attribute byte from the letters passed
-//
-	{
-	iAtt=0;
-	if (anAttWord==0 || anAttWord[0]=='\0')
-		return Print(EError, "Missing argument for keyword 'attrib'.\n");
-	for (TText *letter=anAttWord;*letter!=0;letter++)
-		{
-		switch (*letter)
-			{
-		case 'R':
-		case 'w':
-			iAtt |= KEntryAttReadOnly;
-			break;
-		case 'r':
-		case 'W':
-			iAtt &= ~KEntryAttReadOnly;
-			break;
-		case 'H':
-			iAtt |= KEntryAttHidden;
-			break;
-		case 'h':
-			iAtt &= ~KEntryAttHidden;
-			break;
-		case 'S':
-			iAtt |= KEntryAttSystem;
-			break;
-		case 's':
-			iAtt &= ~KEntryAttSystem;
-			break;
-		default:
-			return Print(EError, "Unrecognised attrib - '%c'.\n", *letter);
-			break;
-			}
-		}
-	return KErrNone;
-	}
-
-TRomBuilderEntry::TRomBuilderEntry(const char *aFileName,TText *aName)
-//
-// Constructor
-//
-	:
-	E32ImageFile(),
-	iName(0),
-	iResource(EFalse), iNonXIP(EFalse), iPreferred(EFalse), iCompression(0), iPatched(EFalse),iArea(0),
-	iOverrideFlags(0),iCodeAlignment(0),iDataAlignment(0),iUid1(0), iUid2(0), iUid3(0),iBareName(0), 
-	iHardwareVariant(KVariantIndependent),iDataBssOffset(0xffffffff), 
-	iStackReserve(0),iIATRefs(0), iNext(0), iNextInArea(0), 
-	iRomImageFlags(0),iProcessName(0), iRomNode(NULL)
-	{
-	if (aFileName)
-   		iFileName = NormaliseFileName((const char*)aFileName);
-	if (aName)
-		iName = (TText*)NormaliseFileName((const char*)aName);
-	}
-
-TRomBuilderEntry::~TRomBuilderEntry()
-//
-// Destructor
-//
-	{
-
-	free(iFileName);
-	iFileName = 0;
-	free(iName);
-	iName = 0;
-	delete[] iProcessName;
-	free(iBareName);
-	iBareName = 0;
-	delete[] iIATRefs;
-	}
-
-TInt isNumber(TText *aString)
-	{
-	if (aString==NULL)
-		return 0;
-	if (strlen((char *)aString)==0)
-		return 0;
-	return isdigit(aString[0]);
-	}
-
-TInt getNumber(TText *aStr)
-	{
-	TUint a;
-	#ifdef __TOOLS2__
-	istringstream val((char *)aStr);
-	#else
-	istrstream val((char *)aStr,strlen((char *)aStr));
-	#endif
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-	val >> setbase(0);
-#endif //__MSVCDOTNET__
-
-	val >> a;
-	return a;
-	}
-
-TInt TRomBuilderEntry::SetCodeAlignment(TText* aStr)
-	{
-    if (!aStr || (aStr && isNumber(aStr)==0))
-		return Print(EError, "Number required as argument for keyword 'code-align'.\n");
-    iCodeAlignment=getNumber(aStr);
-    return KErrNone;
-	}
-
-TInt TRomBuilderEntry::SetDataAlignment(TText* aStr)
-	{
-    if (!isNumber(aStr))
-		return Print(EError, "Number required as argument for keyword 'data-align'.\n");
-    TInt align=getNumber(aStr);
-	if (align<0 || (align&0x0F) != 0)
-		return Print(EError, "Positive multiple of 16 required for 'data-align'.\n");
-	iDataAlignment=align;
-    return KErrNone;
-	}
-
-TInt TRomBuilderEntry::SetRelocationAddress(TText *aStr)
-	{
-	if (aStr && isNumber(aStr)==0)
-		return Print(EError, "Number required as argument for keyword 'reloc'.\n");
-	iOverrideFlags |= KOverrideAddress;
-	iRelocationAddress=aStr ? getNumber(aStr) : 0xFFFFFFFF;
-	return KErrNone;
-	}
-
-TInt TRomBuilderEntry::SetStackReserve(TText *aStr)
-	{
-	if (isNumber(aStr)==0)
-		return Print(EError, "Number required as argument for keyword 'stackreserve'.\n");
-	iOverrideFlags |= KOverrideStackReserve;
-	iStackReserve=getNumber(aStr);
-	return KErrNone;
-	}
-
-TInt TRomBuilderEntry::SetStackSize(TText *aStr)
-	{
-	if (isNumber(aStr)==0)
-		return Print(EError, "Number required as argument for keyword 'stack'.\n");
-	iOverrideFlags |= KOverrideStack;
-	iStackSize=getNumber(aStr);
-	return KErrNone;
-	}
-
-TInt TRomBuilderEntry::SetHeapSizeMin(TText *aStr)
-	{
-	if (isNumber(aStr)==0)
-		return Print(EError, "Number required as argument for keyword 'heapmin'.\n");
-	iOverrideFlags |= KOverrideHeapMin;
-	iHeapSizeMin=getNumber(aStr);
-	return KErrNone;
-	}
-
-TInt TRomBuilderEntry::SetHeapSizeMax(TText *aStr)
-	{
-	if (isNumber(aStr)==0)
-		return Print(EError, "Number required as argument for keyword 'heapmax'.\n");
-	iOverrideFlags |= KOverrideHeapMax;
-	iHeapSizeMax=getNumber(aStr);
-	return KErrNone;
-	}
-
-TInt TRomBuilderEntry::SetCapability(TText *aStr)
-	{
-	iOverrideFlags |= KOverrideCapability;
-	if (isNumber(aStr))
-		{
-		Print(EDiagnostic,"Old style numeric CAPABILTY specification ignored.\n");
-		return KErrNone;
-		}
-	return ParseCapabilitiesArg(iS.iCaps, (char*)aStr);
-	}
-
-TInt TRomBuilderEntry::SetPriority(TText *aStr)
-	{
-	if (isNumber(aStr))
-		iPriority=(TProcessPriority)getNumber(aStr);
-	else
-		{
-		char *str=(char *)aStr;
-		if (stricmp(str, "low")==0)
-			iPriority=EPriorityLow;
-		else if (strnicmp(str, "background", 4)==0)
-			iPriority=EPriorityBackground;
-		else if (strnicmp(str, "foreground", 4)==0)
-			iPriority=EPriorityForeground;
-		else if (stricmp(str, "high")==0)
-			iPriority=EPriorityHigh;
-		else if (strnicmp(str, "windowserver",3)==0)
-			iPriority=EPriorityWindowServer;
-		else if (strnicmp(str, "fileserver",4)==0)
-			iPriority=EPriorityFileServer;
-		else if (strnicmp(str, "realtimeserver",4)==0)
-			iPriority=EPriorityRealTimeServer;
-		else if (strnicmp(str, "supervisor",3)==0)
-			iPriority=EPrioritySupervisor;
-		else
-			return Print(EError, "Unrecognised priority keyword.\n");
-		}
-	if (iPriority<EPriorityLow || iPriority>EPrioritySupervisor)
-		return Print(EError, "Priority out of range.\n");
-	iOverrideFlags |= KOverridePriority;
-	return KErrNone;
-	}
-
-TInt TRomBuilderEntry::SetUid1(TText *aStr)
-	{
-	if (isNumber(aStr)==0)
-		return Print(EError, "Number required as argument for keyword 'uid1'.\n");
-	iOverrideFlags |= KOverrideUid1;
-	iUid1=getNumber(aStr);
-	return KErrNone;
-	}
-TInt TRomBuilderEntry::SetUid2(TText *aStr)
-	{
-	if (isNumber(aStr)==0)
-		return Print(EError, "Number required as argument for keyword 'uid2'.\n");
-	iOverrideFlags |= KOverrideUid2;
-	iUid2=getNumber(aStr);
-	return KErrNone;
-	}
-TInt TRomBuilderEntry::SetUid3(TText *aStr)
-	{
-	if (isNumber(aStr)==0)
-		return Print(EError, "Number required as argument for keyword 'uid3'.\n");
-	iOverrideFlags |= KOverrideUid3;
-	iUid3=getNumber(aStr);
-	return KErrNone;
-	}
-TInt TRomBuilderEntry::SetCallEntryPoint(TBool aState)
-	{
-	if (aState)
-		iOverrideFlags|=KOverrideCallEntryPoint;
-	else
-		iOverrideFlags|=KOverrideNoCallEntryPoint;
-	return KErrNone;
-	}
-
-TInt TRomBuilderEntry::SetAttachProcess(TText *aStr)
-	{
-	const char* s=(const char*)aStr;
-	TInt nd=0;
-	if (*s=='\\')
-		{
-		++s;
-		++nd;
-		}
-	TInt l=strlen(s);
-	if (l==0)
-		return KErrGeneral;
-	const char* ss=s;
-	while(*ss!=0 && *ss!='.') ++ss;
-	int ext=*ss;	// 0 if no extension
-	iProcessName=new TText[l+2+(ext?0:4)];
-	char* d=(char *)iProcessName;
-	strcpy(d+1, s);
-	if (!ext)
-		{
-		char* t=d+1+l;
-		*t++='.';
-		*t++='e';
-		*t++='x';
-		*t++='e';
-		*t++=0;
-		}
-	char* dd=d;
-	int ind=nd;
-	while(*dd)
-		{
-		while(*dd && *dd!='\\') ++dd;
-		if (*dd=='\\')
-			{
-			*dd++=0;	// change \ to NUL
-			++nd;		// count path elements
-			}
-		}
-	if (!ind && nd)
-		++nd;			// add initial \ if not present
-	*d=(char)nd;
-	return 0;
-	}
-
-TInt TRomBuilderEntry::OpenImageFile()
-	{
-	Print(ELog,"Loading E32Image file %s \n", iFileName);
-	TInt err = Open(iFileName);
-	if (err != KErrNone)
-		{
-		Print(EError,"File %s is not a valid E32Image file (error %d)\n", iFileName, err);
-		return err;
-		}
-	TUint hdrfmt = iHdr->HeaderFormat();
-	if (hdrfmt != KImageHdrFmt_V)
-		{
-		Print(EError,"%s: Can't load old format binary\n", iFileName);
-		return KErrNotSupported;
-		}
-	E32ImageHeaderV* h = iHdr;
-	
-	// Overide any settings in the image file with those in the obey file
-	if (iOverrideFlags & (KOverrideUid1|KOverrideUid2|KOverrideUid3))
-		{
-		TUint uid1 = h->iUid1;
-		TUint uid2 = h->iUid2;
-		TUint uid3 = h->iUid3;
-		if (iOverrideFlags & KOverrideUid1)
-			uid1 = iUid1;
-		if (iOverrideFlags & KOverrideUid2)
-			uid2 = iUid2;
-		if (iOverrideFlags & KOverrideUid3)
-			uid3 = iUid3;
-		SetUids(TUid::Uid(uid1), TUid::Uid(uid2), TUid::Uid(uid3));
-		}
-	if (iOverrideFlags & KOverrideStack)
-		h->iStackSize = iStackSize;
-	if (iOverrideFlags & KOverrideHeapMax)
-		h->iHeapSizeMax = iHeapSizeMax;
-	if (iOverrideFlags & KOverrideHeapMin)
-		h->iHeapSizeMin = iHeapSizeMin;
-	if (iOverrideFlags & KOverridePriority)
-		h->iProcessPriority = (TUint16)iPriority;
-	if (iOverrideFlags & KOverrideCapability)
-		h->iS.iCaps = iS.iCaps;
-	for (TInt i=0; i<SCapabilitySet::ENCapW; ++i)
-		{
-		h->iS.iCaps[i] |= gPlatSecDisabledCaps[i];
-		h->iS.iCaps[i] &= gPlatSecAllCaps[i];
-		}
-
-	if (iOverrideFlags & KOverrideCodePaged)
-		{
-		h->iFlags &= ~KImageCodeUnpaged;
-		h->iFlags |= KImageCodePaged;
-		}
-	if (iOverrideFlags & KOverrideCodeUnpaged)
-		{
-		h->iFlags |= KImageCodeUnpaged;
-		h->iFlags &= ~KImageCodePaged;
-		}
-
-	if ((TInt)h->iUid1 == KExecutableImageUidValue)
-		{
-		if (iOverrideFlags & KOverrideDataPaged)
-			{
-			h->iFlags &= ~KImageDataUnpaged;
-			h->iFlags |= KImageDataPaged;
-			}
-		if (iOverrideFlags & KOverrideDataUnpaged)
-			{
-			h->iFlags |= KImageDataUnpaged;
-			h->iFlags &= ~KImageDataPaged;
-			}
-		}
-
-	switch(gCodePagingOverride)
-		{
-	case EKernelConfigPagingPolicyNoPaging:
-		h->iFlags |= KImageCodeUnpaged;
-		h->iFlags &= ~KImageCodePaged;
-		break;
-	case EKernelConfigPagingPolicyAlwaysPage:
-		h->iFlags |= KImageCodePaged;
-		h->iFlags &= ~KImageCodeUnpaged;
-		break;
-	case EKernelConfigPagingPolicyDefaultUnpaged:
-		if(!(h->iFlags&(KImageCodeUnpaged|KImageCodePaged)))
-			h->iFlags |= KImageCodeUnpaged;
-		break;
-	case EKernelConfigPagingPolicyDefaultPaged:
-		if(!(h->iFlags&(KImageCodeUnpaged|KImageCodePaged)))
-			h->iFlags |= KImageCodePaged;
-		break;
-		}
-	switch(gDataPagingOverride)
-		{
-	case EKernelConfigPagingPolicyNoPaging:
-		h->iFlags |= KImageDataUnpaged;
-		h->iFlags &= ~KImageDataPaged;
-		break;
-	case EKernelConfigPagingPolicyAlwaysPage:
-		h->iFlags |= KImageDataPaged;
-		h->iFlags &= ~KImageDataUnpaged;
-		break;
-	case EKernelConfigPagingPolicyDefaultUnpaged:
-		if(!(h->iFlags&(KImageDataUnpaged|KImageDataPaged)))
-			h->iFlags |= KImageDataUnpaged;
-		break;
-	case EKernelConfigPagingPolicyDefaultPaged:
-		if(!(h->iFlags&(KImageDataUnpaged|KImageDataPaged)))
-			h->iFlags |= KImageDataPaged;
-		break;
-		}
-	
-	h->iCompressionType=KUidCompressionDeflate; // XIP images are always uncompressed
-	
-	Print(ELog,"\t\tcompression format:0x%08x \n", h->iCompressionType);
-	if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
-		Print(ELog,"\t\tgCompress:%d, gCompressionMethod: 0x%08x \n", gEnableCompress , gCompressionMethod);
-
-
-	// Check the uids
-
-	if ((TInt)h->iUid1 != KExecutableImageUidValue && (TInt)h->iUid1 != KDynamicLibraryUidValue) 
-		return Print(EError, "First Uid for %s is not KExecutableImageUid or KDynamicLibraryUid\n", iFileName);
-
-	// Set up the sizes and location of the distinct areas
-
-	iHeaderRange.iSize = sizeof(TRomImageHeader);
-
-	iCodeSection.iSize    = h->iTextSize;
-	iCodeSection.iFilePtr = iData + iOrigHdr->iCodeOffset;
-
-	TUint impfmt = h->ImportFormat();
-
-	if (impfmt==KImageImpFmt_PE || impfmt==KImageImpFmt_PE2)
-		{
-		TInt nimports = NumberOfImports();
-		if (nimports)
-			{
-			iImportAddressTableSection.iSize    = (nimports+1)*4;
-			iImportAddressTableSection.iFilePtr = iData + iOrigHdr->iCodeOffset + iOrigHdr->iTextSize;
-			iIATRefs = new TLinAddr*[nimports+1];
-			memcpy(iIATRefs, iImportAddressTableSection.iFilePtr, (nimports+1)*sizeof(TLinAddr*));
-			}
-
-		if (h->iExportDirCount)
-			{
-			iExportDirSection.iSize    = h->iExportDirCount*4;
-			iExportDirSection.iFilePtr = iData + iOrigHdr->iExportDirOffset;
-			}
-
-		// assertion - there's no rdata between IAT and Export Directory
-		TInt rdatasize = h->iCodeSize;		// overall "readonly" size
-		rdatasize -= iCodeSection.iSize;				// text
-		rdatasize -= iImportAddressTableSection.iSize;	// IAT plus trailing 0
-		rdatasize -= iExportDirSection.iSize;			// export data
-
-		if (rdatasize != 0)
-			{
-			Print(EWarning, "Unexpected code in %s: %d bytes unexplained\n", iFileName, rdatasize);
-			// expand the code to cover text+IAT+rdata
-			iCodeSection.iSize = h->iCodeSize - iExportDirSection.iSize;
-			}
-		else
-			{
-			if (USE_IAT_FOR_IMPORTS)
-				iCodeSection.iSize += iImportAddressTableSection.iSize;	// include IAT
-			}
-		}
-	else
-		{
-		// ELF-derived images have no IAT and the export directory is included in the code section
-		iImportAddressTableSection.iSize    = 0;
-		iImportAddressTableSection.iFilePtr = NULL;
-		iExportDirSection.iSize    = 0;
-		iExportDirSection.iFilePtr = NULL;
-		}
-
-	if (h->iDataSize)
-		{
-		iDataSection.iSize    = h->iDataSize;
-		iDataSection.iFilePtr = iData + iOrigHdr->iDataOffset;
-		}
-
-	iRomNode->iRomFile->iTotalDataBss = h->iDataSize + h->iBssSize;
-	iS = h->iS;
-	if (iVersionPresentInName && iVersionInName != h->ModuleVersion())
-		{
-		Print(EError,"%s: Version in name (%d.%d) does not match version in header (%d.%d)\n", iFileName,
-			iVersionInName>>16, iVersionInName&0x0000ffffu, h->ModuleVersion()>>16, h->ModuleVersion()&0x0000ffffu);
-		return KErrGeneral;
-		}
-	return KErrNone;
-	}
-
-TInt TRomNode::NameCpy(char* aDest)
-//
-// Safely copy a file name in the rom entry
-//
-	{
-
-	if ((aDest==NULL) || (iName==NULL))
-		return 0;
-	if (Unicode)
-		{
-		const unsigned char* pSourceByte=iName;
-		unsigned char* pTargetByte=(unsigned char*)aDest;
-		for (;;)
-			{
-			const TUint sourceByte=*pSourceByte;
-			if (sourceByte==0)
-				{
-				*pTargetByte=0;
-				*(pTargetByte+1)=0;
-				break;
-				}
-			if ((sourceByte&0x80)==0)
-				{
-				*pTargetByte=(unsigned char)sourceByte;
-				++pTargetByte;
-				*pTargetByte=0;
-				++pTargetByte;
-				++pSourceByte;
-				}
-			else if ((sourceByte&0xe0)==0xc0)
-				{
-				++pSourceByte;
-				const TUint secondSourceByte=*pSourceByte;
-				if ((secondSourceByte&0xc0)!=0x80)
-					{
-					Print(EError, "Bad UTF-8 '%s'", iName);
-					exit(671);
-					}
-				*pTargetByte=(unsigned char)((secondSourceByte&0x3f)|((sourceByte&0x03)<<6));
-				++pTargetByte;
-				*pTargetByte=(unsigned char)((sourceByte>>2)&0x07);
-				++pTargetByte;
-				++pSourceByte;
-				}
-			else if ((sourceByte&0xf0)==0xe0)
-				{
-				++pSourceByte;
-				const TUint secondSourceByte=*pSourceByte;
-				if ((secondSourceByte&0xc0)!=0x80)
-					{
-					Print(EError, "Bad UTF-8 '%s'", iName);
-					exit(672);
-					}
-				++pSourceByte;
-				const TUint thirdSourceByte=*pSourceByte;
-				if ((thirdSourceByte&0xc0)!=0x80)
-					{
-					Print(EError, "Bad UTF-8 '%s'", iName);
-					exit(673);
-					}
-				*pTargetByte=(unsigned char)((thirdSourceByte&0x3f)|((secondSourceByte&0x03)<<6));
-				++pTargetByte;
-				*pTargetByte=(unsigned char)(((secondSourceByte>>2)&0x0f)|((sourceByte&0x0f)<<4));
-				++pTargetByte;
-				++pSourceByte;
-				}
-			else
-				{
-				Print(EError, "Bad UTF-8 '%s'", iName);
-				exit(674);
-				}
-			}
-		const TInt numberOfBytesInTarget=(pTargetByte-(unsigned char*)aDest); // this number excludes the trailing null-terminator
-		if (numberOfBytesInTarget%2!=0)
-			{
-			Print(EError, "Internal error");
-			exit(675);
-			}
-		return numberOfBytesInTarget/2; // returns the length of aDest (in UTF-16 characters for Unicode, not bytes)
-		}
-	strcpy(aDest,(const char*)iName);
-	return strlen((const char*)iName);
-	}
-
-TInt TRomBuilderEntry::SizeInRom()
-//
-// Approximate the required size of the file when rommed
-//
-	{
-
-	TInt size1, size2;
-	SizeInSections(size1,size2);
-	return size1+size2;
-	}
-
-void TRomBuilderEntry::LoadToRom()
-//
-//
-//
-	{
-	// Copy fixed stuff into iRomImageHeader
-	E32ImageHeaderV* h = iHdr;
-	const TUint KRomFlagMask = KImageDll | KImageNoCallEntryPoint | KImageFixedAddressExe | KImageNmdExpData | KImageDataPagingMask;
-	TUint romflags = h->iFlags & KRomFlagMask;
-	TUint abi = h->ABI();
-	TUint ept = h->EntryPointFormat();
-	TUint impfmt = h->ImportFormat();
-	romflags |= (abi | ept);
-
-	iRomImageHeader = (TRomImageHeader*)iHeaderRange.iImagePtr;
-
-	iRomImageHeader->iUid1              = h->iUid1;
-	iRomImageHeader->iUid2              = h->iUid2;
-	iRomImageHeader->iUid3              = h->iUid3;
-	iRomImageHeader->iUidChecksum       = h->iUidChecksum;
-	iRomImageHeader->iEntryPoint        = iCodeSection.iRunAddr + h->iEntryPoint;
-	iRomImageHeader->iCodeAddress       = iCodeSection.iRunAddr;
-	iRomImageHeader->iDataAddress       = iDataSection.iRunAddr;
-	iRomImageHeader->iCodeSize          = iCodeSection.iSize+iExportDirSection.iSize;
-	iRomImageHeader->iTextSize          = iCodeSection.iSize;
-	iRomImageHeader->iDataSize          = iDataSection.iSize;
-	iRomImageHeader->iBssSize           = h->iBssSize;
-	iRomImageHeader->iTotalDataSize		= iRomNode->iRomFile->iTotalDataBss;
-	iRomImageHeader->iHeapSizeMin       = h->iHeapSizeMin;
-	iRomImageHeader->iHeapSizeMax       = h->iHeapSizeMax;
-	iRomImageHeader->iStackSize         = h->iStackSize;
-	iRomImageHeader->iDllRefTable       = (TDllRefTable*)(iDllRefTableRange.iImageAddr);
-	iRomImageHeader->iExportDirCount    = h->iExportDirCount;
-	iRomImageHeader->iExportDir         = (impfmt==KImageImpFmt_ELF) ?
-											iCodeSection.iRunAddr + (h->iExportDirOffset - h->iCodeOffset)
-											: iExportDirSection.iRunAddr;
-	iRomImageHeader->iS					= h->iS;
-	iRomImageHeader->iToolsVersion		= h->iToolsVersion;
-	iRomImageHeader->iModuleVersion		= h->ModuleVersion();
-	iRomImageHeader->iFlags             = romflags | iRomImageFlags;
-	iRomImageHeader->iPriority          = h->ProcessPriority();
-	iRomImageHeader->iDataBssLinearBase = iDataBssLinearBase;
-	iRomImageHeader->iNextExtension     = 0;
-	iRomImageHeader->iHardwareVariant   = iHardwareVariant;
-	iRomImageHeader->iExceptionDescriptor = 0;
-	TUint32 xd = h->iExceptionDescriptor;
-	if ((xd & 1) && (xd != 0xffffffffu))
-		iRomImageHeader->iExceptionDescriptor = (xd & ~1) + iRomImageHeader->iCodeAddress;
-
-	if (iPreferred)
-		{
-		iRomImageHeader->iModuleVersion	&= ~0xffffu;
-		iRomImageHeader->iModuleVersion	|= 0x8000u;
-		}
-
-	// Relocate the file to reflect the new addresses
-	Relocate();
-
-	// Copy the sections
-	iCodeSection.Load();
-	iExportDirSection.Load();
-	iDataSection.Load();
-	}
-
-void TRomBuilderEntry::Relocate()
-//
-// Relocates the iData to new Code and Data addresses
-//	
-	{
-	TUint codeDelta=iRomImageHeader->iCodeAddress       - iHdr->iCodeBase;
-	TUint dataDelta=iRomImageHeader->iDataBssLinearBase - iHdr->iDataBase;
-
-	// code section (text, IAT, export directory)
-
-	if (iOrigHdr->iCodeRelocOffset)
-		RelocateSection(iData + iOrigHdr->iCodeOffset, iData + iOrigHdr->iCodeRelocOffset,
-			codeDelta, dataDelta, (char*)iCodeSection.iImagePtr, iIATRefs);
-
-	// data section 
-
-	if (iOrigHdr->iDataRelocOffset)
-		RelocateSection(iData + iOrigHdr->iDataOffset, iData + iOrigHdr->iDataRelocOffset, 
-			codeDelta, dataDelta, (char*)iDataSection.iImagePtr, iIATRefs);
-
-	// export directory (only for PE-derived files)
-	if (iExportDirSection.iSize)
-		{
-		TLinAddr* ptr=(TLinAddr*)(iData + iOrigHdr->iExportDirOffset);
-
-		TLinAddr textStart = iHdr->iCodeBase;
-		TLinAddr textFinish = textStart + iHdr->iTextSize;
-		TLinAddr dataStart = textStart + iHdr->iCodeSize;
-		TLinAddr dataFinish = dataStart + iHdr->iDataSize + iHdr->iBssSize;
-	 
-		TInt i;
-		for (i=0; i<iHdr->iExportDirCount; i++, ptr++)
-			{
-			TLinAddr data=*ptr+textStart;
-			if ((data>=textStart) && (data<textFinish))
-				*ptr=data+codeDelta; // export something from the text/rdata section
-			else if ((data>=dataStart) && (data<dataFinish))
-				*ptr=data+dataDelta; // export some data or bss item
-			else
-				{
-				Print(EWarning, "Export directory in %s: item %d -> %08x, which is not text or data!\n", iFileName, i, data);
-				*ptr=0x13;	// unlucky for some
-				}
-			}
-		}
-
-	// Replace absent exports with 0
-	TLinAddr* ptr = (TLinAddr*)(iData + iOrigHdr->iExportDirOffset);
-	TInt i;
-	for (i=0; i<iHdr->iExportDirCount; i++, ptr++)
-		{
-		if ( !( iExportBitMap[i>>3] & (1u << (i&7)) ) )
-			*ptr = 0;
-		}
-
-	// Update E32ImageHeader, in case we want to do this process again later
-
-	iHdr->iCodeBase += codeDelta;
-	iHdr->iDataBase += dataDelta;
-	}
-
-
-
-
-TInt TRomBuilderEntry::FixupImports(E32Rom& aRom)
-//
-// Modify the import stubs to point directly into the export directory of the corresponding DLLs
-// using the back pointers captured by detecting relocations referring to the Import Address Table
-// The old-style Import Address Table behaviour can be retained by specifying the "keepIAT" attribute.
-//
-	{
-	if (iHdr->iImportOffset == 0)
-		return KErrNone;	// nothing to do
-
-	
-
-	TUint impfmt = iHdr->ImportFormat();
-	TUint my_abi = iHdr->ABI();
-	TRACE(TIMPORT,Print(ELog,"%40s[%08x] flags %08x\n",iFileName,(TUint)iHardwareVariant,iHdr->iFlags));
-	const E32ImportSection* importsection = (const E32ImportSection*)(iData + iOrigHdr->iImportOffset);
-	TLinAddr **iatRef=iIATRefs;
-	TAddressRange iatRange = iCodeSection;
-	iatRange.Move(iHdr->iTextSize);
-	if (USE_IAT_FOR_IMPORTS)
-		{
-		if (impfmt == KImageImpFmt_ELF)
-			return Print(EError, "Can't retain IAT for %s since it never existed\n", iFileName);
-		if (iRomSectionNumber==0 && aRom.iObey->iSectionPosition!=-1)
-			return Print(EError, "Can't retain IAT for %s in first section - not yet implemented\n", iFileName);
-		Print(ELog, "%s has IAT at %08x\n", iFileName, iatRange.iRunAddr);
-		}
-	const E32ImportBlock* b = (const E32ImportBlock*)(importsection + 1);
-	TInt i = iHdr->iDllRefTableCount;
-	TInt numberOfImports=0;
-	TUint *impOrdinalP = (TUint*)iImportAddressTableSection.iFilePtr;	// points to original IAT in file
-	while (i-->0)
-		{
-		char* dllname = (char*)importsection + b->iOffsetOfDllName;
-		TDllFindInfo find_info(dllname, this);
-		TBool fallback;
-		TRomNode* romnode = aRom.FindImageFileByName(find_info, EFalse, fallback);
-		if (!romnode)
-			{
-			Print(EError, "Can't fixup imports for\n\t%s\nbecause\n\t%s\nis not in rom.\n",
-						 (const char*)TModuleName(this), (const char*)TModuleName(find_info));
-			aRom.FindImageFileByName(find_info, ETrue, fallback);
-			return KErrGeneral;
-			}
-		TRomFile* dll=romnode->iRomFile;
-		TRACE(TIMPORT,Print(ELog,"%s importing from %s\n", (const char*)TModuleName(this), (const char*)TModuleName(find_info)));
-		if (romnode->ABI() != my_abi)
-			{
-			Print(EWarning, "File %s links to %s with different ABI\n", (const char*)TModuleName(this), (const char*)TModuleName(find_info));
-			}
-		TInt j;
-		numberOfImports += b->iNumberOfImports;
-		if (impfmt==KImageImpFmt_ELF)
-			impOrdinalP = (TUint*)(b->Imports());	// for ELF must look in import block
-		char* codeBase = (char*)iCodeSection.iImagePtr;
-		for (j=0; j<b->iNumberOfImports; j++)
-			{
-			TLinAddr exportAddr = 0xdeadbeef;
-			TLinAddr exporter = 0xdeadbeef;
-			TUint impOrdinal = *impOrdinalP;
-			TUint impOffset = 0;
-			if (impfmt==KImageImpFmt_ELF)
-				{
-				TUint impd = *(TUint*)(codeBase + impOrdinal);
-				impOrdinal = impd & 0xffff;
-				impOffset = impd >> 16;
-				}
-			TRACE(TIMPORT,Print(ELog,"Ordinal %d\n", impOrdinal));
-			TInt ret=dll->AddressFromOrdinal(exporter, exportAddr, impOrdinal);
-			TRACE(TIMPORT,Print(ELog,"export %08x exporter %08x\n",exportAddr,exporter));
-			if (ret!=KErrNone)
-				{
-				Print(EError, "%s wants ordinal %d from %s which only exports %d functions\n",
-					iFileName, impOrdinal, 	(const char*)TModuleName(find_info), dll->ExportDirCount());
-				exporter=0x13;	// unlucky for some...
-				exportAddr=0x13;
-				}
-			else if (exportAddr == 0 && impOrdinal != 0)
-				{
-				Print(EError, "%s wants ordinal %d from %s which is absent\n",
-					iFileName, impOrdinal, 	(const char*)TModuleName(find_info));
-				exporter=0x13;	// unlucky for some...
-				exportAddr=0x13;
-				}
-			if (USE_IAT_FOR_IMPORTS)
-				{
-				// must be PE-derived
-				*iatRef=(unsigned long*)exportAddr; //iatRange.iRunAddr;					// point into IAT ...
-				*(TLinAddr*)(iatRange.iImagePtr)=exportAddr;	// ... which has a copy of the export
-				iatRange.Move(sizeof(TLinAddr));
-				iatRef++;
-				}
-			else if (impfmt==KImageImpFmt_PE || impfmt==KImageImpFmt_PE2)
-				{
-				**iatRef=exporter;	// point directly into export directory
-				iatRef++;
-				}
-			else
-				{
-				// ELF-derived
-				*(TUint*)(codeBase + *impOrdinalP) = exportAddr + impOffset;
-				}
-			impOrdinalP++;
-			}
-		b = b->NextBlock(impfmt);
-		}
-	iImportCount=numberOfImports;
-	return KErrNone;
-	}
-
-const char* KF32ProcessName="efile.exe";
-const char* KWservProcessName="ewsrv.exe";
-const char* KFbservProcessName="fbserv.exe";
-const char* KMdaSvrProcessName="mediaserverstub.exe";
-const char* KC32ProcessName="c32exe.exe";
-
-const char* TRomBuilderEntry::GetDefaultAttachProcess()
-//
-// Work out the attach process from the file extension
-//
-// Only need to handle DLLs which run in F32, WSERV, FBSERV, MEDIASVR, C32
-// F32:		FSY FXT
-// WSERV:	ANI
-// FBSERV:
-// MDASVR:	MDA
-// C32:		CSY, PRT, TSY, AGT, AGX
-//
-	{
-	const char* s=(const char*)iName;
-	TInt l=strlen(s);
-	if (l<4 || s[l-4]!='.')
-		return NULL;
-	s+=(l-3);
-	if (stricmp(s,"fsy")==0)
-		return KF32ProcessName;
-	if (stricmp(s,"fxt")==0)
-		return KF32ProcessName;
-	if (stricmp(s,"ani")==0)
-		return KWservProcessName;
-	if (stricmp(s,"mda")==0)
-		return KMdaSvrProcessName;
-	if (stricmp(s,"csy")==0)
-		return KC32ProcessName;
-	if (stricmp(s,"prt")==0)
-		return KC32ProcessName;
-	if (stricmp(s,"tsy")==0)
-		return KC32ProcessName;
-	if (stricmp(s,"agt")==0)
-		return KC32ProcessName;
-	if (stricmp(s,"agx")==0)
-		return KC32ProcessName;
-	return NULL;
-	}
-
-TInt TRomBuilderEntry::FindAttachProcess(E32Rom& aRom)
-	{
-	if (iRomImageFlags & (KRomImageFlagVariant|KRomImageFlagExtension|KRomImageFlagDevice))
-		return KErrNone;
-	const char* attp_name=(const char*)iProcessName;
-	int nd=0;
-	if (attp_name)
-		nd=*attp_name++;
-	else
-		attp_name=GetDefaultAttachProcess();
-	if (!attp_name)
-		return KErrNone;
-	TInt i;
-	TUint my_abi = iHdr->ABI();
-	TUint abi = 0;
-	if (nd)
-		{
-		// path search
-		TRomNode* rn=aRom.iObey->iRootDirectory;
-		for (; nd; --nd)
-			{
-			rn=rn->FindInDirectory((TText*)attp_name);
-			if (!rn)
-				{
-				Print(EError, "Invalid attach process name element %s\n", attp_name);
-				return KErrGeneral;
-				}
-			attp_name+=(strlen(attp_name)+1);
-			}
-		iRomNode->iRomFile->iAttachProcess=rn->iRomFile;
-		abi = iRomNode->iRomFile->iAttachProcess->ABI();
-		}
-	else
-		{
-		// filename only search
-		for (i=0; i<aRom.iObey->iNumberOfPeFiles; i++)
-			{
-			TRomBuilderEntry* e=aRom.iPeFiles[i];
-			abi = e->iHdr->ABI();
-			if (stricmp((const char*)e->iName, attp_name)==0)
-				{
-				if (iRomNode->iRomFile->iAttachProcess)
-					{
-					Print(EError, "Ambiguous attach process name %s\n", attp_name);
-					return KErrGeneral;
-					}
-				iRomNode->iRomFile->iAttachProcess=e->iRomNode->iRomFile;
-				}
-			}
-		}
-	if (abi != my_abi)
-		{
-		Print(EWarning, "File %s: Attach process has different ABI\n", (const char*)TModuleName(this));
-		}
-	return KErrNone;
-	}
-
-TInt TRomBuilderEntry::BuildDependenceGraph(E32Rom& aRom)
-//
-// Fill in the iDeps
-//
-	{
-	TBool is_kernel = ((iRomImageFlags & KRomImageFlagsKernelMask) != 0);
-	TRomNode* rn = iRomNode;
-	TRomFile* rf = rn->iRomFile;
-	TUint my_abi = iHdr->ABI();
-	TUint impfmt = iHdr->ImportFormat();
-	rf->iNumDeps = iHdr->iDllRefTableCount;
-	if (IsDll() && aRom.iObey->iMemModel!=E_MM_Flexible && aRom.iObey->iMemModel!=E_MM_Multiple && (iHdr->iDataSize!=0 || iHdr->iBssSize!=0))
-		{
-		TInt r=FindAttachProcess(aRom);
-		if (r!=KErrNone)
-			return r;
-		if (aRom.iObey->iMemModel==E_MM_Moving)
-			{
-			if (rf->iAttachProcess && !(rf->iAttachProcess->RomImageFlags() & KRomImageFlagFixedAddressExe))
-				rf->iAttachProcess=NULL;	// ignore attach process if not fixed
-			}
-		}
-	TRomFile* attp=rf->iAttachProcess;
-	if (attp)
-		++rf->iNumDeps;		// extra implicit dependence on process
-	if (rf->iNumDeps)
-		{
-		rf->iDeps=new TRomFile* [rf->iNumDeps];
-		memset(rf->iDeps, 0, rf->iNumDeps*sizeof(TRomFile*));
-		}
-
-	TInt err = KErrNone;
-	const E32ImportSection* importSection = (const E32ImportSection*)(iData + iOrigHdr->iImportOffset);
-	const E32ImportBlock* block = (const E32ImportBlock*)(importSection + 1);
-	TInt i;
-	for (i=0; i<iHdr->iDllRefTableCount; i++, block = block->NextBlock(impfmt), TRACE(TIMPORT,Print(ELog,"DllRef/dll done\n")) )
-		{
-		char* dllname = (char*)importSection + block->iOffsetOfDllName;
-		TDllFindInfo find_info(dllname, this);
-		TBool fallback;
-		TRomNode* romnode = aRom.FindImageFileByName(find_info, EFalse, fallback);
-		if (!romnode)
-			{
-			Print(EError, "Can't build dependence graph for\n\t%s\nbecause\n\t%s\nis not in rom.\n",
-						 (const char*)TModuleName(this), (const char*)TModuleName(find_info));
-			aRom.FindImageFileByName(find_info, ETrue, fallback);
-			err = KErrNotFound;
-			continue;
-			}
-		if (fallback)
-			{
-			Print(EWarning, "File %s links to %s\n\twhich is not in ROM. Version 1.0 of latter used instead.\n",
-					 (const char*)TModuleName(this), (const char*)TModuleName(find_info));
-			}
-		TRACE(TIMPORT,Print(ELog,"%s links to %s\n", (const char*)TModuleName(this), (const char*)TModuleName(find_info)));
-		TRACE(TIMPORT,Print(ELog,"Resolves to %s\n", (const char*)TModuleName(*romnode)));
-		TBool dep_is_kernel = ((romnode->iRomFile->RomImageFlags() & KRomImageFlagsKernelMask) != 0);
-		if (dep_is_kernel != is_kernel)
-			{
-			if (is_kernel)
-				{
-				Print(EError, "Kernel side executable\n\t%s\nlinks to user side executable\n\t%s\n",
-									 (const char*)TModuleName(this), (const char*)TModuleName(find_info));
-				}
-			else
-				{
-				Print(EError, "User side executable\n\t%s\nlinks to kernel side executable\n\t%s\n",
-									 (const char*)TModuleName(this), (const char*)TModuleName(find_info));
-				}
-			err = KErrGeneral;
-			continue;
-			}
-		// prevent the situiation which importer is primary, variant or extension, exporter is device
-		if (is_kernel && !Device() && romnode->iRomFile->iRbEntry->Device())	
-			{
-			Print(EWarning, "Kernel/variant/extension\n\t%s\nlinks to non-extension LDD/PDD\n\t%s\n",
-							(const char*)TModuleName(this), (const char*)TModuleName(find_info));
-			}
-		if (romnode->ABI() != my_abi)
-			{
-			Print(EWarning, "File %s links to %s with different ABI\n", (const char*)TModuleName(this), (const char*)TModuleName(find_info));
-			}
-
-		rf->iDeps[i]=romnode->iRomFile;
-		const SSecurityInfo& s1 = iHdr->iS;
-		const SSecurityInfo& s2 = romnode->iRomFile->SecurityInfo();
-		TInt r = CompareCapabilities(s1.iCaps, s2.iCaps, iFileName, dllname);
-		if (r != KErrNone)
-			err = r;
-		if (romnode->iRomFile==attp)
-			attp=NULL;
-		}
-
-	if (attp)
-		rf->iDeps[rf->iNumDeps-1]=attp;
-	TRACE(TIMPORT,Print(ELog,"BuildDep done all\n"));
-	return err;
-	}
-
-TInt TRomBuilderEntry::ResolveDllRefTable(E32Rom& aRom)
-//
-// Fill in the DLLRefTable
-//
-	{
-	TRomNode* rn = iRomNode;
-	TRomFile* rf = rn->iRomFile;
-	(void)aRom;
-	if (rf->iNumPDeps==0)
-		return KErrNone;	// nothing to do
-
-	TDllRefTable* dllRefTable=(TDllRefTable*)(iDllRefTableRange.iImagePtr);
-
-	TUint16 flags=0;
-
-	dllRefTable->iFlags=flags;
-	dllRefTable->iNumberOfEntries=(TUint16)rf->iNumPDeps;
-
-	TInt err = KErrNone;
-	TInt i;
-	for (i=0; i<rf->iNumPDeps; i++)
-		{
-		dllRefTable->iEntry[i]=(TRomImageHeader*)rf->iPDeps[i]->iAddresses.iRunAddr;
-		}
-	TRACE(TIMPORT,Print(ELog,"DllRef done all\n"));
-	return err;
-	}
-
-void TRomBuilderEntry::DisplaySize(TPrintType aWhere)
-	{
-	if(gLogLevel > DEFAULT_LOG_LEVEL){
-
-		if(gLogLevel & LOG_LEVEL_FILE_DETAILS)
-		{
-			// More detailed information about file name in .
-			TBool aIgnoreHiddenAttrib = ETrue;
-			TInt aLen = iRomNode->FullNameLength(aIgnoreHiddenAttrib);
-			char * aBuf = new char[aLen+1];
-			iRomNode->GetFullName(aBuf, aIgnoreHiddenAttrib);
-			if (iPatched|iRomNode->iHidden)
-				Print(aWhere, "%s\t%d\t%s\t%s\n", iFileName, SizeInRom(), iPatched?"patched":"hidden", aBuf);
-			else
-				Print(aWhere, "%s\t%d\t%s\n", iFileName, SizeInRom(), aBuf);
-			delete[] aBuf;
-		}
-	}
-	else{
-		if (iPatched|iRomNode->iHidden)
-			Print(aWhere, "%s\t%d\t%s\n", iFileName, SizeInRom(), iPatched?"patched":"hidden");
-		else
-			Print(aWhere, "%s\t%d\n", iFileName, SizeInRom());
-	}
-	}
-
-/**
- * TRomFile iRomEntry is a linked list through the various
- * distinct TRomEntry objects which may exist for the associated file
- * due to variant processing / aliasing
- */
-
-void TRomFile::SetRomEntry(TRomEntry* aEntry)
-	{
-	// Need to add to the tail of the list, for backwards compatibility
-	// Adding to the front of the list changes the iPrimary and iSecondary
-	// values in the TRomHeader when multiple variants are present
-
-	if (iFinal)
-		return;			// address already established so no fixup required
-	if (iRomEntry==0)
-		{
-		iRomEntry = aEntry;
-		return;
-		}
-	TRomEntry* entry = iRomEntry;
-	while (entry->iAddressLin != 0)
-		entry = (TRomEntry*)entry->iAddressLin;
-	entry->iAddressLin = (TLinAddr)aEntry;
-	}
-
-void TRomBuilderEntry::FixupRomEntries(TInt aSize)
-	{
-	if (iPatched)
-		return;		// patched files don't appear in the ROM file system
-
-	iRomNode->Finalise(aSize);
-	}
-
-/**
- * TRomNode::Finalise updates the associated TRomEntry objects with the final size and
- * linear address information supplied by the TRomBuilderEntry. It also stores the
- * summary information for resolving static linkages to this executable (if appropriate)
- * and adjusts the TRomNodes so that they are identical to the ones which would be 
- * obtained by walking the directory structure in an existing ROM.
- */
-void TRomNode::Finalise(TInt aSize)
-	{
-	TRACE(TIMPORT,Print(ELog,"TRomNode %s Finalise %08x %d\n", (const char*)TModuleName(*this), iRomFile->iFinal));
-	iRomFile->Finalise(aSize);
-	}
-
-/**
- * TRomFile::Finalise updates the associated TRomEntry objects with the final size and
- * linear address information supplied by the TRomBuilderEntry. It also stores the
- * summary information for resolving static linkages to this executable (if appropriate)
- * and adjusts the TRomFiles so that they are identical to the ones which would be 
- * obtained by walking the directory structure in an existing ROM.
- */
-void TRomFile::Finalise(TInt aSize)
-	{
-	if (iFinal)
-		return;
-	TLinAddr ra = iRbEntry->iHeaderRange.iImageAddr;
-	TRomEntry* entry = iRomEntry;
-	while (entry)
-		{
-		TRomEntry* next = (TRomEntry*)entry->iAddressLin;
-		entry->iSize = aSize;
-		entry->iAddressLin = ra;
-		entry = next;
-		}
-	iAddresses = iRbEntry->iHeaderRange;
-	iAddresses.iSize = aSize;
-	if ((!iRbEntry->iResource) && (!iRbEntry->HCRDataFile()))
-		{
-		iExportDir = iAddresses;
-		iExportDir.iSize = iRbEntry->iHdr->iExportDirCount * sizeof(TLinAddr);
-		iExportDir.Move(RomImgHdr()->iExportDir - iAddresses.iRunAddr);
-		}
-	iRbEntry = 0;
-	iFinal = ETrue;
-	}
-
-void TRomBuilderEntry::SetRomNode(TRomNode* aNode)
-	{
-	iRomNode = aNode;
-	}
-
-
-void TImageSection::Load() const
-	{ 
-	if (iSize && iImagePtr && iFilePtr) 
-		memcpy(iImagePtr,iFilePtr,iSize); 
-	}
-
-/**
- * TDllExportInfo is the information about a DLL which is necessary to
- * resolve a static link to that DLL. It all comes from the TRomImageHeader,
- * as it would with a static linkage resolved at runtime.
- */
-TRomFile::TRomFile()
-	{
-	memset(this, 0, sizeof(TRomFile));
-	iRefCount = 1;
-	iHwvd = KVariantIndependent;
-	iDataBssOffsetInExe = -1;
-	}
-
-TRomFile::~TRomFile()
-	{
-	delete[] iDeps;
-	delete[] iPDeps;
-	}
-
-TInt TRomFile::AddressFromOrdinal(TLinAddr& aEDataAddr, TLinAddr& aExport, TUint aOrdinal)
-//
-// Get the export address of symbol aOrdinal
-//
-	{
-	if(aOrdinal == 0)
-	{
-		aEDataAddr = iExportDir.iRunAddr -1 ;
-		aExport = *(TLinAddr*)((TLinAddr*)iExportDir.iImagePtr - 1);
-		if((TInt)aExport == ExportDirCount()) {
-			aEDataAddr = 0;
-			aExport = 0;
-		}
-		return KErrNone;
-	}
-	
-	TUint index = aOrdinal - KOrdinalBase;
-	if (index >= (TUint)ExportDirCount())
-		return KErrNotFound;
-	aEDataAddr = iExportDir.iRunAddr + index * sizeof(TLinAddr);
-	aExport = ((TLinAddr*)iExportDir.iImagePtr)[index];
-	return KErrNone;
-	}
-
-
-bool TRomFile::ComputeSmpSafe(const TRomBuilderEntry* aRbEntry)
-	{
-	// A component is SMP safe if:
-	//
-	// 1. It's E32 image file is marked as SMP safe (MMP keyword SMPSAFE).
-	// 2. All components it links to are SMP safe.
-	//
-	// This implies a recursive dependency structure.
-
-	if (iSmpInfo.isInit)
-		{
-		// We have already visited this node.
-		return iSmpInfo.isSafe;
-		}
-
-	// Mark this node as "active," meaning that we are currently evaluating it. We
-	// use this to detect cycles in the dependency graph.
-	iSmpInfo.isActive = 1;
-
-	iSmpInfo.isSafe = 1;
-
-	// Have we found any cycle in the graph?
-	bool is_cycle = 0;
-
-	if ( aRbEntry->iOrigHdr->iFlags & KImageSMPSafe )
-		{
-		// OK, the E32 file for this node is marked as SMPSAFE. Now we need to check
-		// that all nodes we depend on are SMP safe.
-
-		for (int i = 0; i < iNumDeps; i++)
-			{
-			TRomFile* e = iDeps[i];
-
-			assert(this != e);
-
-			if (e->iSmpInfo.isActive)
-				{
-				is_cycle = 1;
-				}
-			else if ( ! e->ComputeSmpSafe(e->iRbEntry) )
-				{
-				if (gLogLevel & LOG_LEVEL_SMP_INFO)
-					{
-					Print(ELog,"SMP-unsafe: %s: links to unsafe component %s.\n",
-							aRbEntry->iBareName , e->iRbEntry->iBareName);
-					}
-
-				iSmpInfo.isSafe = 0;
-				break;
-				}
-			}
-		}
-	else
-		{
-		if (gLogLevel & LOG_LEVEL_SMP_INFO)
-			{
-			Print(ELog,"SMP-unsafe: %s: MMP keyword SMPSAFE not used.\n", aRbEntry->iBareName);
-			}
-
-		iSmpInfo.isSafe = 0;
-		}
-
-	iSmpInfo.isActive = 0;
-
-	if (!iSmpInfo.isSafe || !is_cycle)
-		{
-		iSmpInfo.isInit = 1;
-		}
-
-	return iSmpInfo.isSafe;
-	}
-
-/**
- * TRomNode::CopyDirectory performs a deep copy of the TRomNode structure
- */
-TRomNode* TRomNode::CopyDirectory(TRomNode*& aLastExecutable, TRomNode* aParent)
-	{
-	if (iHidden && iChild==0)
-		{
-		// Hidden file - do not copy (as it wouldn't be visible in the ROM filestructure)
-		if (iSibling)
-			return iSibling->CopyDirectory(aLastExecutable, aParent);
-		else
-			return 0;
-		}
-
-	TRomNode* copy = new TRomNode(*this);
-	copy->iParent = aParent;
-	if(aLastExecutable==0)
-		aLastExecutable = copy;		// this must be the root of the structure
-
-	// recursively copy the sub-structures
-	if (iChild)
-		copy->iChild = iChild->CopyDirectory(aLastExecutable, copy);
-	if (iSibling)
-		copy->iSibling = iSibling->CopyDirectory(aLastExecutable, aParent);
-
-	if (copy->iAtt & KEntryAttXIP)
-		AddExecutableFile(aLastExecutable,copy);
-	return copy;
-	}
-
-TInt TRomNode::Alias(TRomNode* aNode, TRomNode*& aLastExecutable)
-	{
-	if (aNode->iAtt & KEntryAttXIP)
-		AddExecutableFile(aLastExecutable,this);
-	return SetBareName();
-	}
-
-TInt TRomNode::Rename(TRomNode *aOldParent, TRomNode* aNewParent, TText* aNewName)
-	{
-	aOldParent->Remove(this);
-	aNewParent->Add(this);
-	free(iName);
-	iName = (TText*)NormaliseFileName((const char*)aNewName);
-	return SetBareName();
-	}
-
-TInt TRomNode::SetBareName()
-	{
-	free(iBareName);
-	TUint32 uid;
-	TUint32 vin;
-	TUint32 flg;
-	iBareName = SplitFileName((const char*)iName, uid, vin, flg);
-	if (uid || (flg & EUidPresent))
-		return KErrBadName;
-	if (strchr(iBareName, '{') || strchr(iBareName, '}'))
-		return KErrBadName;
-	if ((iAtt & KEntryAttXIP) && (flg & EVerPresent))
-		{
-		TUint32 ver = iRomFile->ModuleVersion();
-		if (ver != vin)
-			return KErrArgument;
-		}
-	return KErrNone;
-	}
+/*
+* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#define __REFERENCE_CAPABILITY_NAMES__
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <e32std.h>
+#include <e32std_private.h>
+#include <e32rom.h>
+#include "u32std.h"
+#include <e32uid.h>
+#include <f32file.h>
+#include "h_utl.h"
+
+#define USE_IAT_FOR_IMPORTS (iOverrideFlags&KOverrideKeepIAT || (iHdr->iCpuIdentifier & 0x1000))
+
+#include <iomanip> 
+#include "r_obey.h"
+#include "r_global.h"
+#include "r_dir.h"
+
+TInt NumRootDirs;
+
+inline TLinAddr ActualToRomAddress(TAny* anAddr) { 
+	return TLinAddr(anAddr)-TheRomMem+TheRomLinearAddress; 
+}
+
+TBool THardwareVariant::MutuallyExclusive(THardwareVariant a) const {
+	if (Layer()<=3 || a.Layer()<=3)
+		return EFalse;
+	if (Parent()==3 && a.Parent()==3)
+		return(Layer()!=a.Layer());
+	if (Parent()==3 && a.Parent()!=Layer())
+		return ETrue;
+	if (a.Parent()==3 && Parent()!=a.Layer())
+		return ETrue;
+	if (Layer()!=a.Layer())
+		return ETrue;
+	return((VMask()&a.VMask())==0);
+}
+
+TBool THardwareVariant::IsVariant() const {
+	if (Layer()<=3 || Parent()==3)
+		return EFalse;
+	TUint v=VMask();
+	TInt i;
+	for (i=0; i<16; i++) {
+		if (v==TUint(1<<i))
+			return ETrue;
+	}
+	return EFalse;
+}
+
+TInt THardwareVariant::Compare(THardwareVariant a) const {
+	TUint l1=Layer();
+	TUint p1=Parent();
+	TUint v1=VMask();
+	TUint l2=a.Layer();
+	TUint p2=a.Parent();
+	TUint v2=a.VMask();
+
+	if (l1<=3) {
+		if (l2<=3) {
+			return EEqual;
+		}
+		return EGreater;
+	}
+	if (l2<=3)
+		return ELess;
+	if (p1==3) {
+		if (p2==3) {
+			if (l1==l2)
+				return EEqual;
+			return EUnordered;
+		}
+		if (p2==l1)
+			return EGreater;
+		return EUnordered;
+	}
+	if (p2==3) {
+		if (p1==l2)
+			return ELess;
+		return EUnordered;
+	}
+	if (l1!=l2)
+		return EUnordered;
+	if ((v1&v2)==v1)
+		return ELess;
+	if ((v1&v2)==v2)
+		return EGreater;
+	return EUnordered;
+}
+//
+TInt TRomNode::Count=0;
+
+//
+// Constructor from TRomBuilderEntry, i.e. for new file or directory
+//
+TRomNode::TRomNode(const char* aName, TRomBuilderEntry* aEntry) {
+	memset(this, 0, sizeof(TRomNode));
+	iAtt = (TUint8)KEntryAttReadOnly;
+	iName = NormaliseFileName(aName);
+	iIdentifier=TRomNode::Count++;
+	iRomFile = new TRomFile;
+
+	if (aEntry) {
+		iRomFile->iRbEntry = aEntry;
+		aEntry->SetRomNode(this);
+		size_t len = strlen(aEntry->iBareName) + 1;
+		iBareName = new char[len];
+		memcpy(iBareName,aEntry->iBareName,len);
+		iRomFile->iHwvd = aEntry->iHardwareVariant;
+	}
+	else {
+		iRomFile->iDir = ETrue;
+		iAtt |= (TUint8)KEntryAttDir;
+		size_t len = strlen(iName) + 1;
+		iBareName = new char[len];
+		memcpy(iBareName,iName,len);
+		iRomFile->iHwvd = KVariantIndependent;
+	}
+	TRACE(TROMNODE,Print(ELog, "TRomNode %d name %s bare %s att %02x romfile %08x\n", iIdentifier,
+		iName, iBareName, iAtt, iRomFile));
+}
+
+//
+// Constructor from TRomNode, i.e. for aliased file
+//	
+TRomNode::TRomNode(const char* aName, TRomNode* aNode){
+	memset(this, 0, sizeof(TRomNode));
+	iAtt = aNode->iAtt;
+	iIdentifier=TRomNode::Count++;
+	iName = NormaliseFileName(aName);
+	iHidden = aNode->iHidden;
+	iRomFile = aNode->iRomFile;
+	if (iRomFile) {
+		iRomFile->Open();
+	}
+	TRACE(TROMNODE,Print(ELog, "TRomNode %d DUP name %s romfile %08x\n", iIdentifier, iName, iRomFile));
+}
+//
+// Copy constructor - only used in deep copy function
+//
+TRomNode::TRomNode(const TRomNode& aNode) {
+	memset(this, 0, sizeof(TRomNode));
+	iAtt = aNode.iAtt;
+	iIdentifier=TRomNode::Count++;
+	size_t len = strlen(aNode.iName) + 1;
+	iName = new char[len];
+	memcpy(iName,aNode.iName,len);
+	len = strlen(aNode.iBareName) + 1;
+	iBareName = new char[len];
+	memcpy(iBareName,aNode.iBareName,len);
+	iHidden = aNode.iHidden;
+	iRomFile = aNode.iRomFile;
+	if (iRomFile) {
+		iRomFile->Open();
+	}
+	TRACE(TROMNODE,Print(ELog, "TRomNode %d COPY name %s bare %s att %02x romfile %08x\n", iIdentifier,
+		iName, iBareName, iAtt, iRomFile));
+}
+
+TRomNode::~TRomNode() {
+	if(iName) {
+		delete []iName;
+		iName = 0 ;
+	}
+	if(iBareName){
+		delete []iBareName;
+		iBareName = 0 ;
+	}
+	if (iRomFile)
+		iRomFile->Close();
+}
+//
+// Check if the TRomNode for aName exists in aDir, and if so, return it.
+//
+TRomNode* TRomNode::FindInDirectory(const char* aName) {
+
+	TRomNode *entry=iChild; // first subdirectory or file
+	while (entry){
+		if (!entry->iHidden && (stricmp(aName, entry->iName))==0) 
+			return entry;
+		else
+			entry=entry->iSibling;
+	}
+	return 0;
+}
+//
+// Check for a file with same name and a compatible hardware variant
+//
+TRomNode* TRomNode::FindInDirectory(const char* aName, THardwareVariant aVariant, TBool aPatchDataFlag) {
+	TRomNode *entry=iChild; // first subdirectory or file
+	while (entry) {
+		if (((!entry->iHidden)||aPatchDataFlag) && entry->iRomFile && 
+			(stricmp(aName, entry->iName))==0) 	{
+				if (!aVariant.MutuallyExclusive(entry->HardwareVariant()))
+					return entry;
+		}
+		entry=entry->iSibling;
+	}
+	return 0;
+}
+
+void TRomNode::AddFile(TRomNode* aChild) {
+	if (!(iAtt & KEntryAttDir)) {
+		Print(EError, "Adding subdirectory to a file!!!\n");
+		return;
+	}
+	Add(aChild);
+}
+
+TRomNode* TRomNode::NewSubDir(const char* aName) {
+	if (!(iAtt & KEntryAttDir)) {
+		Print(EError, "Adding subdirectory to a file!!!\n");
+		return 0;
+	}
+
+	TRomNode* node = new TRomNode(aName);
+	if (node==0) {
+		Print(EError, "TRomNode::NewNode: Out of memory\n");
+		return 0;
+	}
+	Add(node);
+	return node;
+}
+
+void TRomNode::Add(TRomNode* aChild) {
+	if (iChild) {// this node is a non-empty directory 
+		TRomNode* dir = iChild; // find where to link in the new node
+		while (dir->iSibling) 
+			dir = dir->iSibling;
+		dir->iSibling = aChild;
+	}
+	else
+		iChild = aChild; // else just set it up as the child of the dir
+	aChild->iSibling = 0;
+	aChild->iParent = this;
+}
+
+void TRomNode::Remove(TRomNode* aChild) {
+	if (iChild==0) {
+		Print(EError, "Removing file from a file!!!\n");
+		return;
+	}
+	if (iChild==aChild) { // first child in this directory 
+		iChild = aChild->iSibling;
+		aChild->iSibling = 0;
+		aChild->iParent = 0;
+		return;
+	}
+	TRomNode* prev = iChild;
+	while (prev->iSibling && prev->iSibling != aChild)
+		prev = prev->iSibling;
+	if (prev==0) {
+		Print(EError, "Attempting to remove file not in this directory!!!\n");
+		return;
+	}
+	prev->iSibling = aChild->iSibling;
+	aChild->iSibling = 0;
+	aChild->iParent = 0;
+}
+
+void TRomNode::CountDirectory(TInt& aFileCount, TInt& aDirCount) {
+	TRomNode *current=iChild;
+	while(current) {
+		if (current->iChild)
+			aDirCount++;
+		else if (!current->iHidden)
+			aFileCount++;
+		current=current->iSibling;
+	}
+}
+
+/**
+* Walk the contents of the directory, accumulating the
+* files as FileEntry objects in the specified RomFileStructure
+* and recursively handling the sub-directories
+*
+* TRomNode::ProcessDirectory is a pair with
+* RomFileStructure::ProcessDirectory
+*/
+int TRomNode::ProcessDirectory(RomFileStructure* aRFS) {
+	TInt r=KErrNone;
+	TRomNode *current=iChild;
+	while(current) {
+		if (current->iAtt & (TUint8)KEntryAttDir) {
+			r=aRFS->ProcessDirectory(current);
+			if (r!=KErrNone)
+				return r;
+		}
+		else if (!current->iHidden) {
+			FileEntry *pE=FileEntry::New(current);
+			if (!pE)
+				return KErrNoMemory;
+			r=aRFS->Add(*pE);
+			if (r==KErrOverflow)
+				return r;
+		}
+		current=current->iSibling;
+	}
+	return r;
+}
+
+void TRomNode::AddExecutableFile(TRomNode*& aLast, TRomNode* aNode) {
+	aLast->iNextExecutable = aNode;
+	aLast = aNode;
+	aNode->iAtt |= KEntryAttXIP;
+}
+
+const char* TRomNode::BareName() const {
+	return iBareName  ;
+}
+
+TUint32 TRomNode::Uid3() const {
+	return iRomFile->Uid3();
+}
+
+TUint32 TRomNode::ModuleVersion() const {
+	return iRomFile->ModuleVersion();
+}
+
+THardwareVariant TRomNode::HardwareVariant() const {
+	return iRomFile->HardwareVariant();
+}
+
+TUint32 TRomNode::ABI() const {
+	return iRomFile->ABI();
+}
+
+TUint32 TRomFile::Uid3() const {
+	assert(!iDir);
+	if (iRbEntry) {
+		if(iRbEntry->iHdr)
+			return iRbEntry->iHdr->iUid3;
+	}
+	return RomImgHdr()->iUid3;
+}
+
+TUint32 TRomFile::ModuleVersion() const {
+	assert(!iDir);
+	if (iRbEntry) {
+		if(iRbEntry->iHdr)
+			return iRbEntry->iHdr->ModuleVersion();
+	}
+	return RomImgHdr()->iModuleVersion;
+}
+
+THardwareVariant TRomFile::HardwareVariant() const {
+	return iHwvd;
+}
+
+TUint32 TRomFile::ABI() const {
+	assert(!iDir);
+	if (iRbEntry) {
+		if(iRbEntry->iHdr)
+			return iRbEntry->iHdr->ABI();
+	}
+	return RomImgHdr()->iFlags & KRomImageABIMask;
+}
+
+TInt TRomFile::ExportDirCount() const {
+	assert(!iDir);
+	if (iRbEntry) {
+		if(iRbEntry->iHdr)
+			return iRbEntry->iHdr->iExportDirCount;
+	}
+	return RomImgHdr()->iExportDirCount;
+}
+
+TUint32 TRomFile::RomImageFlags() const {
+	assert(!iDir);
+	if (iRbEntry) {
+		if(iRbEntry->iHdr) {
+			const TUint KRomFlagMask = KImageDll | KImageNoCallEntryPoint | KImageFixedAddressExe | KImageNmdExpData;
+			TUint romflags = iRbEntry->iHdr->iFlags & KRomFlagMask;
+			return iRbEntry->iRomImageFlags | romflags;
+		}
+	}
+	return RomImgHdr()->iFlags;
+}
+
+TLinAddr TRomFile::DataBssLinearBase() const {
+	assert(!iDir);
+	if (iRbEntry)
+		return iRbEntry->iDataBssLinearBase;
+	return RomImgHdr()->iDataBssLinearBase;
+}
+
+const SSecurityInfo& TRomFile::SecurityInfo() const {
+	assert(!iDir);
+	if (iRbEntry)
+		return iRbEntry->iS;
+	return RomImgHdr()->iS;
+}
+
+TInt TRomNode::FullNameLength(TBool aIgnoreHiddenAttrib) const {
+	TInt l = 0;
+	// aIgnoreHiddenAttrib is used to find the complete file name length as
+	// in ROM of a hidden file.
+	if (iParent && ( !iHidden || aIgnoreHiddenAttrib))
+		l = iParent->FullNameLength() + 1;
+	l += strlen((const char*)iName);
+	return l;
+}
+
+TInt TRomNode::GetFullName(char* aBuf, TBool aIgnoreHiddenAttrib) const {
+	TInt l = 0;
+	TInt nl = strlen(iName);
+	// aIgnoreHiddenAttrib is used to find the complete file name as in ROM of a hidden file.
+	if (iParent && ( !iHidden || aIgnoreHiddenAttrib))
+		l = iParent->GetFullName(aBuf);
+	char* b = aBuf + l;
+	if (l){
+		*b++ = SLASH_CHAR; 
+		++l;
+	}
+	memcpy(b, iName, nl);
+	b += nl;
+	*b = 0;
+	l += nl;
+	return l;
+}
+
+//
+//	Check that a aSubCaps are a subset of aSuperCaps
+//
+TInt CompareCapabilities(const SCapabilitySet& aSubCaps, const SCapabilitySet& aSuperCaps, const char* aSubName, const char* aSuperName) {
+	if ((!gPlatSecEnforcement)&&(!gPlatSecDiagnostics))
+		return KErrNone;
+	TInt i;
+	TUint32 c = 0;
+	for (i=0; i<SCapabilitySet::ENCapW; ++i)
+		c |= (aSubCaps[i] &~ aSuperCaps[i]);
+	TInt r = c ? KErrPermissionDenied : KErrNone;
+	if (r && aSubName && aSuperName) {
+		TPrintType printType;
+		if(gPlatSecEnforcement)
+			printType = EError;
+		else {
+			printType = EWarning;
+			r = KErrNone;
+		}
+		char* buf = (char*)malloc(2);
+		if(!buf)
+			return KErrNoMemory;
+		TInt len = 0;
+		for(i=0; i<ECapability_Limit; i++) {
+			if( (aSubCaps[i>>5] &~ aSuperCaps[i>>5]) & (1<<(i&31)) ) {
+				// append capability name to buf
+				const char* name = CapabilityNames[i];
+				if(!name)
+					continue;
+				if(len) {
+					buf[len++] = ' ';
+				}
+				int nameLen=strlen(name);
+				buf = (char*)realloc(buf,len+nameLen+2);
+				if(!buf)
+					return KErrNoMemory;
+				memcpy(buf+len,CapabilityNames[i],nameLen);
+				len += nameLen;
+			}
+		}
+		buf[len]=0;
+		Print(printType, "*PlatSec* %s - Capability check failed. Can't load %s because it links to %s which has the following capabilities missing: %s\n",gPlatSecEnforcement?"ERROR":"WARNING",aSubName, aSuperName, buf);
+		free(buf);
+	}
+	return r;
+}
+
+TDllFindInfo::TDllFindInfo(const char* aImportName, const TRomBuilderEntry* aEntry) {
+	TUint32 flags;
+	iBareName = SplitFileName(aImportName, iUid3, iModuleVersion, flags);
+	assert(iBareName != 0);
+	iHwVariant = aEntry->iHardwareVariant.ReturnVariant(); 
+}
+
+TDllFindInfo::~TDllFindInfo() {
+	delete []iBareName;
+}
+
+// Generate name as follows:
+// PC filename (UID3:xxxxxxxx HWVD:xxxxxxxx VER:M.m)
+TModuleName::TModuleName(const TRomBuilderEntry* a) {
+	TInt l = strlen(a->iFileName) + strlen(" (UID3:xxxxxxxx HWVD:xxxxxxxx VER:MMMMM.mmmmm)");
+	iName = new char[l + 1];
+	assert(iName != 0);
+	sprintf(iName, "%s (UID3:%08lx HWVD:%08lx VER:%ld.%ld)", a->iFileName, a->iHdr->iUid3,
+		a->iHardwareVariant.ReturnVariant(), a->iHdr->ModuleVersion()>>16, a->iHdr->ModuleVersion()&0x0000ffffu);
+}
+
+// Generate name as follows:
+// Bare name (UID3:xxxxxxxx HWVD:xxxxxxxx VER:M.m)
+TModuleName::TModuleName(const TDllFindInfo& a) {
+	TInt l = strlen(a.iBareName) + strlen(" (UID3:xxxxxxxx HWVD:xxxxxxxx VER:MMMMM.mmmmm)");
+	iName = new char [l + 1];
+	assert(iName != 0);
+	sprintf(iName, "%s (UID3:%08lx HWVD:%08lx VER:%ld.%ld)", a.iBareName, a.iUid3,
+		a.iHwVariant, a.iModuleVersion>>16, a.iModuleVersion&0x0000ffffu);
+}
+
+// Generate name as follows:
+// Name (UID3:xxxxxxxx HWVD:xxxxxxxx VER:M.m)
+TModuleName::TModuleName(const TRomNode& a) {
+	TBool xip = (a.iAtt & KEntryAttXIP);
+	TUint32 uid3 = xip ? a.Uid3() : 0;
+	TUint32 hwvd = (TUint)a.HardwareVariant();
+	TUint32 ver = xip ? a.ModuleVersion() : 0;
+	TInt l = a.FullNameLength() + strlen(" (UID3:xxxxxxxx HWVD:xxxxxxxx VER:MMMMM.mmmmm)");
+	iName = new char[l + 1];
+	assert(iName != 0);
+	char* b = iName + a.GetFullName(iName);
+	sprintf(b, " (UID3:%08lx HWVD:%08lx VER:%ld.%ld)", uid3, hwvd, ver>>16, ver&0x0000ffffu);
+}
+
+TModuleName::TModuleName(const TRomFile& a, const TRomNode* aRootDir) {
+	iName = 0;
+	if (a.iRbEntry) {
+		new (this) TModuleName(a.iRbEntry);
+		return;
+	}
+	TRomNode* x = aRootDir->iNextExecutable;
+	for(; x; x=x->iNextExecutable) {
+		if (x->iRomFile == &a) {
+			new (this) TModuleName(*x);
+			return;
+		}
+	}
+}
+
+TModuleName::~TModuleName() {
+	if(iName)
+		delete []iName;
+}
+
+
+/**
+* TRomNode::FindImageFileByName is always called on the root TRomNode, so
+* it doesn't consider the current TRomNode, just the linked items in the
+* iNextExecutable list.
+*/
+TRomNode* TRomNode::FindImageFileByName(const TDllFindInfo& aInfo, TBool aPrintDiag, TBool& aFallBack) {
+	TUint r_major = aInfo.iModuleVersion >> 16;
+	TUint r_minor = aInfo.iModuleVersion & 0x0000ffffu;
+	TRomNode* fallback = NULL;
+	aFallBack = EFalse;
+	for (TRomNode* x=iNextExecutable; x!=0; x=x->iNextExecutable) {
+		if (stricmp(x->BareName(), aInfo.iBareName))
+			continue;	// name doesn't match
+		if (aPrintDiag)
+			Print(ELog, "Candidate: %s ", (const char*)TModuleName(*x) );
+		if ( !(THardwareVariant(aInfo.iHwVariant) <= x->HardwareVariant()) ) {
+			if (aPrintDiag)
+				Print(ELog, "HWVD mismatch - requested %08x\n", aInfo.iHwVariant);
+			continue;
+		}
+		if (aInfo.iUid3 && (aInfo.iUid3 != x->Uid3())) {
+			if (aPrintDiag)
+				Print(ELog, "UID3 mismatch - requested %08x\n", aInfo.iUid3);
+			continue;
+		}
+		TUint x_major = x->ModuleVersion() >> 16;
+		TUint x_minor = x->ModuleVersion() & 0x0000ffffu;
+		if ( x->ModuleVersion() == 0x00010000 && aInfo.iModuleVersion == 0 ) {
+			// allow requested version 0.0 to link to 1.0 with a warning
+			fallback = x;
+		}
+		if ( x_major != r_major ) {
+			if (aPrintDiag)
+				Print(ELog, "Major version mismatch - requested %d\n", r_major);
+			continue;
+		}
+		if ( x_minor < r_minor ) {
+			if (aPrintDiag)
+				Print(ELog, "??? Minor version mismatch - requested %d\n", r_minor);
+			continue;
+		}
+		if (aPrintDiag)
+			Print(ELog, "OK\n");
+		return x;
+	}
+	if (fallback) {
+		aFallBack = ETrue;
+		return fallback;
+	}
+	return 0;
+}
+
+TInt TRomNode::CheckForVersionConflicts(const TRomBuilderEntry* a) {
+	TUint r_major = a->iHdr->ModuleVersion() >> 16;
+	TUint r_minor = a->iHdr->ModuleVersion() & 0x0000ffffu;
+	TInt errors = 0;
+	for (TRomNode* x=iNextExecutable; x!=0; x=x->iNextExecutable) {
+		if (x->iRomFile->iRbEntry == a)
+			continue;	// don't compare a with itself
+		if (stricmp(x->BareName(), a->iBareName))
+			continue;	// name doesn't match
+		if ( a->iHardwareVariant.MutuallyExclusive(x->HardwareVariant()) )
+			continue;	// HWVDs are mutually exclusive
+		if ( a->iHdr->iUid3 && x->Uid3() && (a->iHdr->iUid3 != x->Uid3()) )
+			continue;	// UID3's don't match
+		TUint x_major = x->ModuleVersion() >> 16;
+		TUint x_minor = x->ModuleVersion() & 0x0000ffffu;
+		if (x_major == r_major && x_minor != r_minor)  {	// allow two copies of same file
+			Print(EError, "Version Conflict %s with %s\n", (const char*)TModuleName(a), (const char*)TModuleName(*x) );
+			++errors;
+		}
+	}
+	return errors;
+}
+
+//
+// Follow the TRomBuilderEntry tree, writing TRomEntry headers to the rom.
+//
+TInt E32Rom::WriteHeadersToRom(char *anAddr) {
+	TRACE(TTIMING,Print(EAlways,"0\n"));
+	TRACE(TDIR,Print(EAlways,"WriteHeadersToRom()\n"));
+	char* start=anAddr;
+	TRomRootDirectoryList* dirPointers=(TRomRootDirectoryList*)anAddr;
+	anAddr+=NumberOfVariants*sizeof(TRootDirInfo)+sizeof(TInt);
+	RomFileStructure* pS=RomFileStructure::New(NumberOfVariants);
+	if (!pS)
+		Print(EError,"Error creating RomFileStructure\n");
+	TInt r=pS->ProcessDirectory(iObey->iRootDirectory);
+	if (r!=KErrNone)
+		Print(EError,"Error %d processing directory tree\n",r);
+	TInt c=pS->Count();
+	NumRootDirs=c;
+	if (c!=NumberOfVariants)
+		Print(EError,"Error processing directory tree NR=%d NV=%d\n",c,NumberOfVariants);
+	dirPointers->iNumRootDirs=c;
+	TInt i;
+	TRACE(TDIR,Print(EAlways,"Count=%d\n",c));
+	TRACE(TDIR,pS->DebugPrint());
+	for(i=0; i<c; i++) {
+		DirEntry* pD=(DirEntry*)&(*pS)[i];
+		TRomDir* pR=pD->CreateRomEntries(anAddr);
+		dirPointers->iRootDir[i].iHardwareVariant=TUint(pD->Variants().Lookup());
+		dirPointers->iRootDir[i].iAddressLin=ActualToRomAddress(pR);
+	}
+	TRACE(TDIR,Print(EAlways,"Beginning final cleanup\n"));
+	delete pS;
+	TRACE(TTIMING,Print(EAlways,"1\n"));
+	return anAddr-start;
+}
+
+//
+// Follow the TRomNode tree, destroying it
+//
+void TRomNode::Destroy() {
+
+	TRomNode *current = this; // root has no siblings
+	while (current) {
+		if (current->iChild)
+			current->iChild->Destroy();
+		TRomNode* prev=current;
+		current=current->iSibling;
+		delete prev;
+	}
+}
+
+//
+// Set the file attribute byte from the letters passed
+//
+TInt TRomNode::SetAtt(const char* anAttWord) {
+	iAtt=0;
+	if (anAttWord==0 || anAttWord[0]=='\0')
+		return Print(EError, "Missing argument for keyword 'attrib'.\n");
+	for (const char* letter = anAttWord; *letter != 0; letter ++) {
+		switch (*letter) {
+		case 'R':
+		case 'w':
+			iAtt |= KEntryAttReadOnly;
+			break;
+		case 'r':
+		case 'W':
+			iAtt &= ~KEntryAttReadOnly;
+			break;
+		case 'H':
+			iAtt |= KEntryAttHidden;
+			break;
+		case 'h':
+			iAtt &= ~KEntryAttHidden;
+			break;
+		case 'S':
+			iAtt |= KEntryAttSystem;
+			break;
+		case 's':
+			iAtt &= ~KEntryAttSystem;
+			break;
+		default:
+			return Print(EError, "Unrecognised attrib - '%c'.\n", *letter);
+			break;
+		}
+	}
+	return KErrNone;
+}
+//
+// Constructor
+//
+TRomBuilderEntry::TRomBuilderEntry(const char *aFileName,const char* aName) :
+E32ImageFile(),
+iName(0),
+iResource(EFalse), iNonXIP(EFalse), iPreferred(EFalse), iCompression(0), iPatched(EFalse),iArea(0),
+iOverrideFlags(0),iCodeAlignment(0),iDataAlignment(0),iUid1(0), iUid2(0), iUid3(0),iBareName(0), 
+iHardwareVariant(KVariantIndependent),iDataBssOffset(0xffffffff), 
+iStackReserve(0),iIATRefs(0), iNext(0), iNextInArea(0), 
+iRomImageFlags(0),iProcessName(0), iRomNode(NULL) {
+	if (aFileName){
+		if(iFileName)
+			delete []iFileName;
+		iFileName = NormaliseFileName(aFileName);	 
+	}
+	if (aName)
+		iName = NormaliseFileName(aName);
+}
+//
+// Destructor
+//
+TRomBuilderEntry::~TRomBuilderEntry() {
+	 
+	if(iName){
+		delete []iName; 
+		iName = 0 ;
+	}
+	if(iProcessName){	
+		delete []iProcessName;
+		iProcessName = 0 ;
+	}
+	if(iBareName) {
+		delete []iBareName;
+		iBareName = 0 ;
+	}
+
+	if(iIATRefs){
+		char* tmp = reinterpret_cast<char*>(iIATRefs);
+		delete []tmp;
+		iIATRefs = 0 ;
+	}
+}
+
+TInt TRomBuilderEntry::SetCodeAlignment(const char* aStr) {
+	if (!IsValidNumber(aStr))
+		return Print(EError, "Number required as argument for keyword 'code-align'.\n"); 
+	TInt err = Val(iCodeAlignment,aStr);	 
+	return err;
+}
+
+TInt TRomBuilderEntry::SetDataAlignment(const char* aStr) {
+	if (!IsValidNumber(aStr))
+		return Print(EError, "Number required as argument for keyword 'data-align'.\n"); 
+	TInt align = 0;
+	Val(align,aStr);
+	if (align < 0 || (align & 0x0F) != 0) 
+		return Print(EError, "Positive multiple of 16 required for 'data-align'.\n");
+	iDataAlignment = align;
+	return KErrNone;
+}
+
+TInt TRomBuilderEntry::SetRelocationAddress(const char* aStr) {
+	if (aStr && !IsValidNumber(aStr))
+		return Print(EError, "Number required as argument for keyword 'reloc'.\n");
+	iOverrideFlags |= KOverrideAddress;
+	iRelocationAddress =  0xFFFFFFFF; 
+	if(aStr){
+		Val(iRelocationAddress,aStr);
+	}
+	return KErrNone;
+}
+
+TInt TRomBuilderEntry::SetStackReserve(const char* aStr) {
+	if (!IsValidNumber(aStr))
+		return Print(EError, "Number required as argument for keyword 'stackreserve'.\n");	
+	TInt err = Val(iStackReserve,aStr);
+	if(err == KErrNone)
+		iOverrideFlags |= KOverrideStackReserve;
+	return err;
+}
+
+TInt TRomBuilderEntry::SetStackSize(const char* aStr) {
+	if (!IsValidNumber(aStr))
+		return Print(EError, "Number required as argument for keyword 'stack'.\n");	
+	TInt err = Val(iStackSize,aStr);
+	if(err == KErrNone)
+		iOverrideFlags |= KOverrideStack;
+	return err;
+}
+
+TInt TRomBuilderEntry::SetHeapSizeMin(const char* aStr) {
+	if (!IsValidNumber(aStr))
+		return Print(EError, "Number required as argument for keyword 'heapmin'.\n");	
+	TInt err = Val(iHeapSizeMin,aStr); 
+	if(err == KErrNone)
+		iOverrideFlags |= KOverrideHeapMin;
+	return KErrNone;
+}
+
+TInt TRomBuilderEntry::SetHeapSizeMax(const char* aStr) {
+	if (!IsValidNumber(aStr))
+		return Print(EError, "Number required as argument for keyword 'heapmax'.\n");
+	TInt err = Val(iHeapSizeMax,aStr); 
+	if(err == KErrNone)
+		iOverrideFlags |= KOverrideHeapMax;
+	return err;
+}
+
+TInt TRomBuilderEntry::SetCapability(const char* aStr) {
+	iOverrideFlags |= KOverrideCapability;
+	if (IsValidNumber(aStr)) {
+		Print(EDiagnostic,"Old style numeric CAPABILTY specification ignored.\n");
+		return KErrNone;
+	}
+	return ParseCapabilitiesArg(iS.iCaps, aStr);
+}
+
+TInt TRomBuilderEntry::SetPriority(const char* aStr) {
+	if (IsValidNumber(aStr)){
+		TUint32 temp = 0 ;
+		Val(temp,aStr);
+		iPriority=(TProcessPriority)temp;
+	}
+	else {		 
+		if (stricmp(aStr, "low")==0)
+			iPriority=EPriorityLow;
+		else if (strnicmp(aStr, "background", 4)==0)
+			iPriority=EPriorityBackground;
+		else if (strnicmp(aStr, "foreground", 4)==0)
+			iPriority=EPriorityForeground;
+		else if (stricmp(aStr, "high")==0)
+			iPriority=EPriorityHigh;
+		else if (strnicmp(aStr, "windowserver",3)==0)
+			iPriority=EPriorityWindowServer;
+		else if (strnicmp(aStr, "fileserver",4)==0)
+			iPriority=EPriorityFileServer;
+		else if (strnicmp(aStr, "realtimeserver",4)==0)
+			iPriority=EPriorityRealTimeServer;
+		else if (strnicmp(aStr, "supervisor",3)==0)
+			iPriority=EPrioritySupervisor;
+		else
+			return Print(EError, "Unrecognised priority keyword.\n");
+	}
+	if (iPriority<EPriorityLow || iPriority>EPrioritySupervisor)
+		return Print(EError, "Priority out of range.\n");
+	iOverrideFlags |= KOverridePriority;
+	return KErrNone;
+}
+
+TInt TRomBuilderEntry::SetUid1(const char* aStr) {
+	if (!IsValidNumber(aStr))
+		return Print(EError, "Number required as argument for keyword 'uid1'.\n");
+	iOverrideFlags |= KOverrideUid1;
+	Val(iUid1,aStr);
+	return KErrNone;
+}
+TInt TRomBuilderEntry::SetUid2(const char* aStr) {
+	if (!IsValidNumber(aStr))
+		return Print(EError, "Number required as argument for keyword 'uid2'.\n");
+	iOverrideFlags |= KOverrideUid2;
+	Val(iUid2,aStr);
+	return KErrNone;
+}
+TInt TRomBuilderEntry::SetUid3(const char* aStr) {
+	if (!IsValidNumber(aStr))
+		return Print(EError, "Number required as argument for keyword 'uid3'.\n");
+	iOverrideFlags |= KOverrideUid3;
+	Val(iUid3,aStr);
+	return KErrNone;
+}
+TInt TRomBuilderEntry::SetCallEntryPoint(TBool aState) {
+	if (aState)
+		iOverrideFlags|=KOverrideCallEntryPoint;
+	else
+		iOverrideFlags|=KOverrideNoCallEntryPoint;
+	return KErrNone;
+}
+
+TInt TRomBuilderEntry::SetAttachProcess(const char* aStr) {
+
+	TInt nd=0;
+	if (*aStr==SLASH_CHAR) {
+		++aStr;
+		++nd;
+	}
+	size_t l = strlen(aStr);
+	if (l == 0)
+		return KErrGeneral;
+	const char* ss=aStr;
+	while(*ss != 0 && *ss!='.') ++ss;
+	int ext = *ss;	// 0 if no extension
+	iProcessName=new char[l+2+(ext?0:4)];
+	char* d=(char *)iProcessName;
+	strcpy(d+1, aStr);
+	if (!ext) {
+		char* t=d+1+l;
+		*t++='.';
+		*t++='e';
+		*t++='x';
+		*t++='e';
+		*t++=0;
+	}
+	char* dd=d;
+	int ind=nd;
+	while(*dd) {
+		while(*dd && *dd!=SLASH_CHAR) ++dd;
+		if (*dd==SLASH_CHAR) {
+			*dd++=0;	// change \ to NUL
+			++nd;		// count path elements
+		}
+	}
+	if (!ind && nd)
+		++nd;			// add initial \ if not present
+	*d=(char)nd;
+	return 0;
+}
+
+TInt TRomBuilderEntry::OpenImageFile()
+	{
+	TInt err = Open(iFileName);
+	return err;
+	}
+TInt TRomBuilderEntry::GetImageFileInfo(TInt aResult)
+{
+	TInt err = aResult;
+	Print(ELog,"Loading E32Image file %s \n", iFileName);
+	if (err != KErrNone) {
+		Print(EError,"File %s is not a valid E32Image file (error %d)\n", iFileName, err);
+		return err;
+	}
+	TUint hdrfmt = iHdr->HeaderFormat();
+	if (hdrfmt != KImageHdrFmt_V) {
+		Print(EError,"%s: Can't load old format binary\n", iFileName);
+		return KErrNotSupported;
+	}
+	E32ImageHeaderV* h = iHdr;
+
+	// Overide any settings in the image file with those in the obey file
+	if (iOverrideFlags & (KOverrideUid1|KOverrideUid2|KOverrideUid3)) {
+		TUint uid1 = h->iUid1;
+		TUint uid2 = h->iUid2;
+		TUint uid3 = h->iUid3;
+		if (iOverrideFlags & KOverrideUid1)
+			uid1 = iUid1;
+		if (iOverrideFlags & KOverrideUid2)
+			uid2 = iUid2;
+		if (iOverrideFlags & KOverrideUid3)
+			uid3 = iUid3;
+		SetUids(TUid::Uid(uid1), TUid::Uid(uid2), TUid::Uid(uid3));
+	}
+	if (iOverrideFlags & KOverrideStack)
+		h->iStackSize = iStackSize;
+	if (iOverrideFlags & KOverrideHeapMax)
+		h->iHeapSizeMax = iHeapSizeMax;
+	if (iOverrideFlags & KOverrideHeapMin)
+		h->iHeapSizeMin = iHeapSizeMin;
+	if (iOverrideFlags & KOverridePriority)
+		h->iProcessPriority = (TUint16)iPriority;
+	if (iOverrideFlags & KOverrideCapability)
+		h->iS.iCaps = iS.iCaps;
+	for (TInt i=0; i<SCapabilitySet::ENCapW; ++i) {
+		h->iS.iCaps[i] |= gPlatSecDisabledCaps[i];
+		h->iS.iCaps[i] &= gPlatSecAllCaps[i];
+	}
+
+	if (iOverrideFlags & KOverrideCodePaged) {
+		h->iFlags &= ~KImageCodeUnpaged;
+		h->iFlags |= KImageCodePaged;
+	}
+	if (iOverrideFlags & KOverrideCodeUnpaged) {
+		h->iFlags |= KImageCodeUnpaged;
+		h->iFlags &= ~KImageCodePaged;
+	}
+
+	if ((TInt)h->iUid1 == KExecutableImageUidValue) {
+		if (iOverrideFlags & KOverrideDataPaged) {
+			h->iFlags &= ~KImageDataUnpaged;
+			h->iFlags |= KImageDataPaged;
+		}
+		if (iOverrideFlags & KOverrideDataUnpaged) {
+			h->iFlags |= KImageDataUnpaged;
+			h->iFlags &= ~KImageDataPaged;
+		}
+	}
+
+	switch(gCodePagingOverride) {
+	case EKernelConfigPagingPolicyNoPaging:
+		h->iFlags |= KImageCodeUnpaged;
+		h->iFlags &= ~KImageCodePaged;
+		break;
+	case EKernelConfigPagingPolicyAlwaysPage:
+		h->iFlags |= KImageCodePaged;
+		h->iFlags &= ~KImageCodeUnpaged;
+		break;
+	case EKernelConfigPagingPolicyDefaultUnpaged:
+		if(!(h->iFlags&(KImageCodeUnpaged|KImageCodePaged)))
+			h->iFlags |= KImageCodeUnpaged;
+		break;
+	case EKernelConfigPagingPolicyDefaultPaged:
+		if(!(h->iFlags&(KImageCodeUnpaged|KImageCodePaged)))
+			h->iFlags |= KImageCodePaged;
+		break;
+	}
+	switch(gDataPagingOverride) {
+	case EKernelConfigPagingPolicyNoPaging:
+		h->iFlags |= KImageDataUnpaged;
+		h->iFlags &= ~KImageDataPaged;
+		break;
+	case EKernelConfigPagingPolicyAlwaysPage:
+		h->iFlags |= KImageDataPaged;
+		h->iFlags &= ~KImageDataUnpaged;
+		break;
+	case EKernelConfigPagingPolicyDefaultUnpaged:
+		if(!(h->iFlags&(KImageDataUnpaged|KImageDataPaged)))
+			h->iFlags |= KImageDataUnpaged;
+		break;
+	case EKernelConfigPagingPolicyDefaultPaged:
+		if(!(h->iFlags&(KImageDataUnpaged|KImageDataPaged)))
+			h->iFlags |= KImageDataPaged;
+		break;
+	}
+
+	h->iCompressionType=KUidCompressionDeflate; // XIP images are always uncompressed
+
+	Print(ELog,"\t\tcompression format:0x%08x \n", h->iCompressionType);
+	if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
+		Print(ELog,"\t\tgCompress:%d, gCompressionMethod: 0x%08x \n", gEnableCompress , gCompressionMethod);
+
+
+	// Check the uids
+
+	if ((TInt)h->iUid1 != KExecutableImageUidValue && (TInt)h->iUid1 != KDynamicLibraryUidValue) 
+		return Print(EError, "First Uid for %s is not KExecutableImageUid or KDynamicLibraryUid\n", iFileName);
+
+	// Set up the sizes and location of the distinct areas
+
+	iHeaderRange.iSize = sizeof(TRomImageHeader);
+
+	iCodeSection.iSize    = h->iTextSize;
+	iCodeSection.iFilePtr = iData + iOrigHdr->iCodeOffset;
+
+	TUint impfmt = h->ImportFormat();
+
+	if (impfmt==KImageImpFmt_PE || impfmt==KImageImpFmt_PE2) {
+		TInt nimports = NumberOfImports();
+		if (nimports) {
+			iImportAddressTableSection.iSize    = (nimports+1)* sizeof(TLinAddr*);
+			iImportAddressTableSection.iFilePtr = iData + iOrigHdr->iCodeOffset + iOrigHdr->iTextSize;
+			iIATRefs = reinterpret_cast<TLinAddr **>(new char[iImportAddressTableSection.iSize ]);
+			memcpy(iIATRefs, iImportAddressTableSection.iFilePtr, iImportAddressTableSection.iSize);
+		}
+
+		if (h->iExportDirCount) {
+			iExportDirSection.iSize    = h->iExportDirCount*4;
+			iExportDirSection.iFilePtr = iData + iOrigHdr->iExportDirOffset;
+		}
+
+		// assertion - there's no rdata between IAT and Export Directory
+		TInt rdatasize = h->iCodeSize;		// overall "readonly" size
+		rdatasize -= iCodeSection.iSize;				// text
+		rdatasize -= iImportAddressTableSection.iSize;	// IAT plus trailing 0
+		rdatasize -= iExportDirSection.iSize;			// export data
+
+		if (rdatasize != 0) {
+			Print(EWarning, "Unexpected code in %s: %d bytes unexplained\n", iFileName, rdatasize);
+			// expand the code to cover text+IAT+rdata
+			iCodeSection.iSize = h->iCodeSize - iExportDirSection.iSize;
+		}
+		else {
+			if (USE_IAT_FOR_IMPORTS)
+				iCodeSection.iSize += iImportAddressTableSection.iSize;	// include IAT
+		}
+	}
+	else {
+		// ELF-derived images have no IAT and the export directory is included in the code section
+		iImportAddressTableSection.iSize    = 0;
+		iImportAddressTableSection.iFilePtr = NULL;
+		iExportDirSection.iSize    = 0;
+		iExportDirSection.iFilePtr = NULL;
+	}
+
+	if (h->iDataSize) {
+		iDataSection.iSize    = h->iDataSize;
+		iDataSection.iFilePtr = iData + iOrigHdr->iDataOffset;
+	}
+
+	iRomNode->iRomFile->iTotalDataBss = h->iDataSize + h->iBssSize;
+	iS = h->iS;
+	if (iVersionPresentInName && iVersionInName != h->ModuleVersion()) {
+		Print(EError,"%s: Version in name (%d.%d) does not match version in header (%d.%d)\n", iFileName,
+			iVersionInName>>16, iVersionInName&0x0000ffffu, h->ModuleVersion()>>16, h->ModuleVersion()&0x0000ffffu);
+		return KErrGeneral;
+	}
+	return KErrNone;
+}
+
+//
+// Approximate the required size of the file when rommed
+//
+TInt TRomBuilderEntry::SizeInRom() {
+	TInt size1, size2;
+	SizeInSections(size1,size2);
+	return size1+size2;
+}
+//
+//
+//
+void TRomBuilderEntry::LoadToRom() {
+	// Copy fixed stuff into iRomImageHeader
+	E32ImageHeaderV* h = iHdr;
+	const TUint KRomFlagMask = KImageDll | KImageNoCallEntryPoint | KImageFixedAddressExe | KImageNmdExpData | KImageDataPagingMask;
+	TUint romflags = h->iFlags & KRomFlagMask;
+	TUint abi = h->ABI();
+	TUint ept = h->EntryPointFormat();
+	TUint impfmt = h->ImportFormat();
+	romflags |= (abi | ept);
+
+	iRomImageHeader = (TRomImageHeader*)iHeaderRange.iImagePtr;
+
+	iRomImageHeader->iUid1              = h->iUid1;
+	iRomImageHeader->iUid2              = h->iUid2;
+	iRomImageHeader->iUid3              = h->iUid3;
+	iRomImageHeader->iUidChecksum       = h->iUidChecksum;
+	iRomImageHeader->iEntryPoint        = iCodeSection.iRunAddr + h->iEntryPoint;
+	iRomImageHeader->iCodeAddress       = iCodeSection.iRunAddr;
+	iRomImageHeader->iDataAddress       = iDataSection.iRunAddr;
+	iRomImageHeader->iCodeSize          = iCodeSection.iSize+iExportDirSection.iSize;
+	iRomImageHeader->iTextSize          = iCodeSection.iSize;
+	iRomImageHeader->iDataSize          = iDataSection.iSize;
+	iRomImageHeader->iBssSize           = h->iBssSize;
+	iRomImageHeader->iTotalDataSize		= iRomNode->iRomFile->iTotalDataBss;
+	iRomImageHeader->iHeapSizeMin       = h->iHeapSizeMin;
+	iRomImageHeader->iHeapSizeMax       = h->iHeapSizeMax;
+	iRomImageHeader->iStackSize         = h->iStackSize;
+	iRomImageHeader->iDllRefTable       = (TDllRefTable*)(iDllRefTableRange.iImageAddr);
+	iRomImageHeader->iExportDirCount    = h->iExportDirCount;
+	iRomImageHeader->iExportDir         = (impfmt==KImageImpFmt_ELF) ?
+		iCodeSection.iRunAddr + (h->iExportDirOffset - h->iCodeOffset)
+		: iExportDirSection.iRunAddr;
+	iRomImageHeader->iS					= h->iS;
+	iRomImageHeader->iToolsVersion		= h->iToolsVersion;
+	iRomImageHeader->iModuleVersion		= h->ModuleVersion();
+	iRomImageHeader->iFlags             = romflags | iRomImageFlags;
+	iRomImageHeader->iPriority          = h->ProcessPriority();
+	iRomImageHeader->iDataBssLinearBase = iDataBssLinearBase;
+	iRomImageHeader->iNextExtension     = 0;
+	iRomImageHeader->iHardwareVariant   = iHardwareVariant;
+	iRomImageHeader->iExceptionDescriptor = 0;
+	TUint32 xd = h->iExceptionDescriptor;
+	if ((xd & 1) && (xd != 0xffffffffu))
+		iRomImageHeader->iExceptionDescriptor = (xd & ~1) + iRomImageHeader->iCodeAddress;
+
+	if (iPreferred) {
+		iRomImageHeader->iModuleVersion	&= ~0xffffu;
+		iRomImageHeader->iModuleVersion	|= 0x8000u;
+	}
+
+	// Relocate the file to reflect the new addresses
+	Relocate();
+
+	// Copy the sections
+	iCodeSection.Load();
+	iExportDirSection.Load();
+	iDataSection.Load();
+}
+//
+// Relocates the iData to new Code and Data addresses
+//
+void TRomBuilderEntry::Relocate() {
+	TUint codeDelta=iRomImageHeader->iCodeAddress       - iHdr->iCodeBase;
+	TUint dataDelta=iRomImageHeader->iDataBssLinearBase - iHdr->iDataBase;
+
+	// code section (text, IAT, export directory)
+
+	if (iOrigHdr->iCodeRelocOffset)
+		RelocateSection(iData + iOrigHdr->iCodeOffset, iData + iOrigHdr->iCodeRelocOffset,
+		codeDelta, dataDelta, (char*)iCodeSection.iImagePtr, iIATRefs);
+
+	// data section 
+
+	if (iOrigHdr->iDataRelocOffset)
+		RelocateSection(iData + iOrigHdr->iDataOffset, iData + iOrigHdr->iDataRelocOffset, 
+		codeDelta, dataDelta, (char*)iDataSection.iImagePtr, iIATRefs);
+
+	// export directory (only for PE-derived files)
+	if (iExportDirSection.iSize) {
+		TLinAddr* ptr=(TLinAddr*)(iData + iOrigHdr->iExportDirOffset);
+
+		TLinAddr textStart = iHdr->iCodeBase;
+		TLinAddr textFinish = textStart + iHdr->iTextSize;
+		TLinAddr dataStart = textStart + iHdr->iCodeSize;
+		TLinAddr dataFinish = dataStart + iHdr->iDataSize + iHdr->iBssSize;
+
+		TInt i;
+		for (i=0; i<iHdr->iExportDirCount; i++, ptr++) {
+			TLinAddr data=*ptr+textStart;
+			if ((data>=textStart) && (data<textFinish))
+				*ptr=data+codeDelta; // export something from the text/rdata section
+			else if ((data>=dataStart) && (data<dataFinish))
+				*ptr=data+dataDelta; // export some data or bss item
+			else {
+				Print(EWarning, "Export directory in %s: item %d -> %08x, which is not text or data!\n", iFileName, i, data);
+				*ptr=0x13;	// unlucky for some
+			}
+		}
+	}
+
+	// Replace absent exports with 0
+	TLinAddr* ptr = (TLinAddr*)(iData + iOrigHdr->iExportDirOffset);
+	TInt i;
+	for (i=0; i<iHdr->iExportDirCount; i++, ptr++) {
+		if ( !( iExportBitMap[i>>3] & (1u << (i&7)) ) )
+			*ptr = 0;
+	}
+
+	// Update E32ImageHeader, in case we want to do this process again later
+
+	iHdr->iCodeBase += codeDelta;
+	iHdr->iDataBase += dataDelta;
+}
+
+
+//
+// Modify the import stubs to point directly into the export directory of the corresponding DLLs
+// using the back pointers captured by detecting relocations referring to the Import Address Table
+// The old-style Import Address Table behaviour can be retained by specifying the "keepIAT" attribute.
+//
+
+TInt TRomBuilderEntry::FixupImports(E32Rom& aRom) {
+	if (iHdr->iImportOffset == 0)
+		return KErrNone;	// nothing to do
+
+
+
+	TUint impfmt = iHdr->ImportFormat();
+	TUint my_abi = iHdr->ABI();
+	TRACE(TIMPORT,Print(ELog,"%40s[%08x] flags %08x\n",iFileName,(TUint)iHardwareVariant,iHdr->iFlags));
+	const E32ImportSection* importsection = (const E32ImportSection*)(iData + iOrigHdr->iImportOffset);
+	TLinAddr **iatRef=iIATRefs;
+	TAddressRange iatRange = iCodeSection;
+	iatRange.Move(iHdr->iTextSize);
+	if (USE_IAT_FOR_IMPORTS) {
+		if (impfmt == KImageImpFmt_ELF)
+			return Print(EError, "Can't retain IAT for %s since it never existed\n", iFileName);
+		if (iRomSectionNumber==0 && aRom.iObey->iSectionPosition!=-1)
+			return Print(EError, "Can't retain IAT for %s in first section - not yet implemented\n", iFileName);
+		Print(ELog, "%s has IAT at %08x\n", iFileName, iatRange.iRunAddr);
+	}
+	const E32ImportBlock* b = (const E32ImportBlock*)(importsection + 1);
+	TInt i = iHdr->iDllRefTableCount;
+	TInt numberOfImports=0;
+	TUint *impOrdinalP = (TUint*)iImportAddressTableSection.iFilePtr;	// points to original IAT in file
+	while (i-->0) {
+		char* dllname = (char*)importsection + b->iOffsetOfDllName;
+		TDllFindInfo find_info(dllname, this);
+		TBool fallback;
+		TRomNode* romnode = aRom.FindImageFileByName(find_info, EFalse, fallback);
+		if (!romnode) {
+			Print(EError, "Can't fixup imports for\n\t%s\nbecause\n\t%s\nis not in rom.\n",
+				(const char*)TModuleName(this), (const char*)TModuleName(find_info));
+			aRom.FindImageFileByName(find_info, ETrue, fallback);
+			return KErrGeneral;
+		}
+		TRomFile* dll=romnode->iRomFile;
+		TRACE(TIMPORT,Print(ELog,"%s importing from %s\n", (const char*)TModuleName(this), (const char*)TModuleName(find_info)));
+		if (romnode->ABI() != my_abi) {
+			Print(EWarning, "File %s links to %s with different ABI\n", (const char*)TModuleName(this), (const char*)TModuleName(find_info));
+		}
+		TInt j;
+		numberOfImports += b->iNumberOfImports;
+		if (impfmt==KImageImpFmt_ELF)
+			impOrdinalP = (TUint*)(b->Imports());	// for ELF must look in import block
+		char* codeBase = (char*)iCodeSection.iImagePtr;
+		for (j=0; j<b->iNumberOfImports; j++) {
+			TLinAddr exportAddr = 0xdeadbeef;
+			TLinAddr exporter = 0xdeadbeef;
+			TUint impOrdinal = *impOrdinalP;
+			TUint impOffset = 0;
+			if (impfmt==KImageImpFmt_ELF) {
+				TUint impd = *(TUint*)(codeBase + impOrdinal);
+				impOrdinal = impd & 0xffff;
+				impOffset = impd >> 16;
+			}
+			TRACE(TIMPORT,Print(ELog,"Ordinal %d\n", impOrdinal));
+			TInt ret=dll->AddressFromOrdinal(exporter, exportAddr, impOrdinal);
+			TRACE(TIMPORT,Print(ELog,"export %08x exporter %08x\n",exportAddr,exporter));
+			if (ret!=KErrNone) {
+				Print(EError, "%s wants ordinal %d from %s which only exports %d functions\n",
+					iFileName, impOrdinal, 	(const char*)TModuleName(find_info), dll->ExportDirCount());
+				exporter=0x13;	// unlucky for some...
+				exportAddr=0x13;
+			}
+			else if (exportAddr == 0 && impOrdinal != 0) {
+				Print(EError, "%s wants ordinal %d from %s which is absent\n",
+					iFileName, impOrdinal, 	(const char*)TModuleName(find_info));
+				exporter=0x13;	// unlucky for some...
+				exportAddr=0x13;
+			}
+			if (USE_IAT_FOR_IMPORTS) {
+				// must be PE-derived
+				*iatRef=(unsigned long*)exportAddr; //iatRange.iRunAddr;					// point into IAT ...
+				*(TLinAddr*)(iatRange.iImagePtr)=exportAddr;	// ... which has a copy of the export
+				iatRange.Move(sizeof(TLinAddr));
+				iatRef++;
+			}
+			else if (impfmt==KImageImpFmt_PE || impfmt==KImageImpFmt_PE2) {
+				**iatRef=exporter;	// point directly into export directory
+				iatRef++;
+			}
+			else {
+				// ELF-derived
+				*(TUint*)(codeBase + *impOrdinalP) = exportAddr + impOffset;
+			}
+			impOrdinalP++;
+		}
+		b = b->NextBlock(impfmt);
+	}
+	iImportCount=numberOfImports;
+	return KErrNone;
+}
+
+const char* KF32ProcessName="efile.exe";
+const char* KWservProcessName="ewsrv.exe";
+const char* KFbservProcessName="fbserv.exe";
+const char* KMdaSvrProcessName="mediaserverstub.exe";
+const char* KC32ProcessName="c32exe.exe";
+
+//
+// Work out the attach process from the file extension
+//
+// Only need to handle DLLs which run in F32, WSERV, FBSERV, MEDIASVR, C32
+// F32:		FSY FXT
+// WSERV:	ANI
+// FBSERV:
+// MDASVR:	MDA
+// C32:		CSY, PRT, TSY, AGT, AGX
+//
+const char* TRomBuilderEntry::GetDefaultAttachProcess() {
+	const char* s=(const char*)iName;
+	TInt l=strlen(s);
+	if (l<4 || s[l-4]!='.')
+		return NULL;
+	s+=(l-3);
+	if (stricmp(s,"fsy")==0)
+		return KF32ProcessName;
+	if (stricmp(s,"fxt")==0)
+		return KF32ProcessName;
+	if (stricmp(s,"ani")==0)
+		return KWservProcessName;
+	if (stricmp(s,"mda")==0)
+		return KMdaSvrProcessName;
+	if (stricmp(s,"csy")==0)
+		return KC32ProcessName;
+	if (stricmp(s,"prt")==0)
+		return KC32ProcessName;
+	if (stricmp(s,"tsy")==0)
+		return KC32ProcessName;
+	if (stricmp(s,"agt")==0)
+		return KC32ProcessName;
+	if (stricmp(s,"agx")==0)
+		return KC32ProcessName;
+	return NULL;
+}
+
+TInt TRomBuilderEntry::FindAttachProcess(E32Rom& aRom) {
+	if (iRomImageFlags & (KRomImageFlagVariant|KRomImageFlagExtension|KRomImageFlagDevice))
+		return KErrNone;
+	const char* attp_name=(const char*)iProcessName;
+	int nd=0;
+	if (attp_name)
+		nd=*attp_name++;
+	else
+		attp_name=GetDefaultAttachProcess();
+	if (!attp_name)
+		return KErrNone;
+	TInt i;
+	TUint my_abi = iHdr->ABI();
+	TUint abi = 0;
+	if (nd) {
+		// path search
+		TRomNode* rn=aRom.iObey->iRootDirectory;
+		for (; nd; --nd) {
+			rn=rn->FindInDirectory(attp_name);
+			if (!rn) {
+				Print(EError, "Invalid attach process name element %s\n", attp_name);
+				return KErrGeneral;
+			}
+			attp_name+=(strlen(attp_name)+1);
+		}
+		iRomNode->iRomFile->iAttachProcess=rn->iRomFile;
+		abi = iRomNode->iRomFile->iAttachProcess->ABI();
+	}
+	else {
+		// filename only search
+		for (i=0; i<aRom.iObey->iNumberOfPeFiles; i++) {
+			TRomBuilderEntry* e=aRom.iPeFiles[i];
+			abi = e->iHdr->ABI();
+			if (stricmp((const char*)e->iName, attp_name)==0) {
+				if (iRomNode->iRomFile->iAttachProcess) {
+					Print(EError, "Ambiguous attach process name %s\n", attp_name);
+					return KErrGeneral;
+				}
+				iRomNode->iRomFile->iAttachProcess=e->iRomNode->iRomFile;
+			}
+		}
+	}
+	if (abi != my_abi) {
+		Print(EWarning, "File %s: Attach process has different ABI\n", (const char*)TModuleName(this));
+	}
+	return KErrNone;
+}
+//
+// Fill in the iDeps
+//
+TInt TRomBuilderEntry::BuildDependenceGraph(E32Rom& aRom) {
+	TBool is_kernel = ((iRomImageFlags & KRomImageFlagsKernelMask) != 0);
+	TRomNode* rn = iRomNode;
+	TRomFile* rf = rn->iRomFile;
+	TUint my_abi = iHdr->ABI();
+	TUint impfmt = iHdr->ImportFormat();
+	rf->iNumDeps = iHdr->iDllRefTableCount;
+	if (IsDll() && aRom.iObey->iMemModel!=E_MM_Flexible && aRom.iObey->iMemModel!=E_MM_Multiple && (iHdr->iDataSize!=0 || iHdr->iBssSize!=0)) {
+		TInt r=FindAttachProcess(aRom);
+		if (r!=KErrNone)
+			return r;
+		if (aRom.iObey->iMemModel==E_MM_Moving) {
+			if (rf->iAttachProcess && !(rf->iAttachProcess->RomImageFlags() & KRomImageFlagFixedAddressExe))
+				rf->iAttachProcess=NULL;	// ignore attach process if not fixed
+		}
+	}
+	TRomFile* attp=rf->iAttachProcess;
+	if (attp)
+		++rf->iNumDeps;		// extra implicit dependence on process
+	if (rf->iNumDeps) {
+		rf->iDeps=new TRomFile* [rf->iNumDeps];
+		memset(rf->iDeps, 0, rf->iNumDeps*sizeof(TRomFile*));
+	}
+
+	TInt err = KErrNone;
+	const E32ImportSection* importSection = (const E32ImportSection*)(iData + iOrigHdr->iImportOffset);
+	const E32ImportBlock* block = (const E32ImportBlock*)(importSection + 1);
+	TInt i;
+	for (i=0; i<iHdr->iDllRefTableCount; i++, block = block->NextBlock(impfmt), TRACE(TIMPORT,Print(ELog,"DllRef/dll done\n")) ) {
+		char* dllname = (char*)importSection + block->iOffsetOfDllName;
+		TDllFindInfo find_info(dllname, this);
+		TBool fallback;
+		TRomNode* romnode = aRom.FindImageFileByName(find_info, EFalse, fallback);
+		if (!romnode) {
+			Print(EError, "Can't build dependence graph for\n\t%s\nbecause\n\t%s\nis not in rom.\n",
+				(const char*)TModuleName(this), (const char*)TModuleName(find_info));
+			aRom.FindImageFileByName(find_info, ETrue, fallback);
+			err = KErrNotFound;
+			continue;
+		}
+		if (fallback) {
+			Print(EWarning, "File %s links to %s\n\twhich is not in ROM. Version 1.0 of latter used instead.\n",
+				(const char*)TModuleName(this), (const char*)TModuleName(find_info));
+		}
+		TRACE(TIMPORT,Print(ELog,"%s links to %s\n", (const char*)TModuleName(this), (const char*)TModuleName(find_info)));
+		TRACE(TIMPORT,Print(ELog,"Resolves to %s\n", (const char*)TModuleName(*romnode)));
+		TBool dep_is_kernel = ((romnode->iRomFile->RomImageFlags() & KRomImageFlagsKernelMask) != 0);
+		if (dep_is_kernel != is_kernel) {
+			if (is_kernel) {
+				Print(EError, "Kernel side executable\n\t%s\nlinks to user side executable\n\t%s\n",
+					(const char*)TModuleName(this), (const char*)TModuleName(find_info));
+			}
+			else {
+				Print(EError, "User side executable\n\t%s\nlinks to kernel side executable\n\t%s\n",
+					(const char*)TModuleName(this), (const char*)TModuleName(find_info));
+			}
+			err = KErrGeneral;
+			continue;
+		}
+		// prevent the situiation which importer is primary, variant or extension, exporter is device
+		if (is_kernel && !Device() && romnode->iRomFile->iRbEntry->Device())	 {
+			Print(EWarning, "Kernel/variant/extension\n\t%s\nlinks to non-extension LDD/PDD\n\t%s\n",
+				(const char*)TModuleName(this), (const char*)TModuleName(find_info));
+		}
+		if (romnode->ABI() != my_abi) {
+			Print(EWarning, "File %s links to %s with different ABI\n", (const char*)TModuleName(this), (const char*)TModuleName(find_info));
+		}
+
+		rf->iDeps[i]=romnode->iRomFile;
+		const SSecurityInfo& s1 = iHdr->iS;
+		const SSecurityInfo& s2 = romnode->iRomFile->SecurityInfo();
+		TInt r = CompareCapabilities(s1.iCaps, s2.iCaps, iFileName, dllname);
+		if (r != KErrNone)
+			err = r;
+		if (romnode->iRomFile==attp)
+			attp=NULL;
+	}
+
+	if (attp)
+		rf->iDeps[rf->iNumDeps-1]=attp;
+	TRACE(TIMPORT,Print(ELog,"BuildDep done all\n"));
+	return err;
+}
+//
+// Fill in the DLLRefTable
+//
+TInt TRomBuilderEntry::ResolveDllRefTable(E32Rom& aRom) {
+	TRomNode* rn = iRomNode;
+	TRomFile* rf = rn->iRomFile;
+	(void)aRom;
+	if (rf->iNumPDeps==0)
+		return KErrNone;	// nothing to do
+
+	TDllRefTable* dllRefTable=(TDllRefTable*)(iDllRefTableRange.iImagePtr);
+
+	TUint16 flags=0;
+
+	dllRefTable->iFlags=flags;
+	dllRefTable->iNumberOfEntries=(TUint16)rf->iNumPDeps;
+
+	TInt err = KErrNone;
+	TInt i;
+	for (i=0; i<rf->iNumPDeps; i++) {
+		dllRefTable->iEntry[i]=(TRomImageHeader*)rf->iPDeps[i]->iAddresses.iRunAddr;
+	}
+	TRACE(TIMPORT,Print(ELog,"DllRef done all\n"));
+	return err;
+}
+
+void TRomBuilderEntry::DisplaySize(TPrintType aWhere) {
+	if(gLogLevel > DEFAULT_LOG_LEVEL){
+
+		if(gLogLevel & LOG_LEVEL_FILE_DETAILS) {
+			// More detailed information about file name in .
+			TBool aIgnoreHiddenAttrib = ETrue;
+			TInt aLen = iRomNode->FullNameLength(aIgnoreHiddenAttrib);
+			char * aBuf = new char[aLen+1];
+			iRomNode->GetFullName(aBuf, aIgnoreHiddenAttrib);
+			if (iPatched|iRomNode->iHidden)
+				Print(aWhere, "%s\t%d\t%s\t%s\n", iFileName, SizeInRom(), iPatched?"patched":"hidden", aBuf);
+			else
+				Print(aWhere, "%s\t%d\t%s\n", iFileName, SizeInRom(), aBuf);
+			delete[] aBuf;
+		}
+	}
+	else{
+		if (iPatched|iRomNode->iHidden)
+			Print(aWhere, "%s\t%d\t%s\n", iFileName, SizeInRom(), iPatched?"patched":"hidden");
+		else
+			Print(aWhere, "%s\t%d\n", iFileName, SizeInRom());
+	}
+}
+
+/**
+* TRomFile iRomEntry is a linked list through the various
+* distinct TRomEntry objects which may exist for the associated file
+* due to variant processing / aliasing
+*/
+
+void TRomFile::SetRomEntry(TRomEntry* aEntry) {
+	// Need to add to the tail of the list, for backwards compatibility
+	// Adding to the front of the list changes the iPrimary and iSecondary
+	// values in the TRomHeader when multiple variants are present
+
+	if (iFinal)
+		return;			// address already established so no fixup required
+	if (iRomEntry==0) {
+		iRomEntry = aEntry;
+		return;
+	}
+	TRomEntry* entry = iRomEntry;
+	while (entry->iAddressLin != 0)
+		entry = (TRomEntry*)entry->iAddressLin;
+	entry->iAddressLin = (TLinAddr)aEntry;
+}
+
+void TRomBuilderEntry::FixupRomEntries(TInt aSize) {
+	if (iPatched)
+		return;		// patched files don't appear in the ROM file system
+
+	iRomNode->Finalise(aSize);
+}
+
+/**
+* TRomNode::Finalise updates the associated TRomEntry objects with the final size and
+* linear address information supplied by the TRomBuilderEntry. It also stores the
+* summary information for resolving static linkages to this executable (if appropriate)
+* and adjusts the TRomNodes so that they are identical to the ones which would be 
+* obtained by walking the directory structure in an existing ROM.
+*/
+void TRomNode::Finalise(TInt aSize) {
+	TRACE(TIMPORT,Print(ELog,"TRomNode %s Finalise %08x %d\n", (const char*)TModuleName(*this), iRomFile->iFinal));
+	iRomFile->Finalise(aSize);
+}
+
+/**
+* TRomFile::Finalise updates the associated TRomEntry objects with the final size and
+* linear address information supplied by the TRomBuilderEntry. It also stores the
+* summary information for resolving static linkages to this executable (if appropriate)
+* and adjusts the TRomFiles so that they are identical to the ones which would be 
+* obtained by walking the directory structure in an existing ROM.
+*/
+void TRomFile::Finalise(TInt aSize) {
+	if (iFinal)
+		return;
+	TLinAddr ra = iRbEntry->iHeaderRange.iImageAddr;
+	TRomEntry* entry = iRomEntry;
+	while (entry) {
+		TRomEntry* next = (TRomEntry*)entry->iAddressLin;
+		entry->iSize = aSize;
+		entry->iAddressLin = ra;
+		entry = next;
+	}
+	iAddresses = iRbEntry->iHeaderRange;
+	iAddresses.iSize = aSize;
+	if ((!iRbEntry->iResource) && (!iRbEntry->HCRDataFile())) {
+		iExportDir = iAddresses;
+		iExportDir.iSize = iRbEntry->iHdr->iExportDirCount * sizeof(TLinAddr);
+		iExportDir.Move(RomImgHdr()->iExportDir - iAddresses.iRunAddr);
+	}
+	iRbEntry = 0;
+	iFinal = ETrue;
+}
+
+void TRomBuilderEntry::SetRomNode(TRomNode* aNode) {
+	iRomNode = aNode;
+}
+
+
+void TImageSection::Load() const
+{ 
+	if (iSize && iImagePtr && iFilePtr) 
+		memcpy(iImagePtr,iFilePtr,iSize); 
+}
+
+/**
+* TDllExportInfo is the information about a DLL which is necessary to
+* resolve a static link to that DLL. It all comes from the TRomImageHeader,
+* as it would with a static linkage resolved at runtime.
+*/
+TRomFile::TRomFile() {
+	memset(this, 0, sizeof(TRomFile));
+	iRefCount = 1;
+	iHwvd = KVariantIndependent;
+	iDataBssOffsetInExe = -1;
+}
+
+TRomFile::~TRomFile() {
+	if(iDeps) delete[] iDeps;
+	if(iPDeps) delete[] iPDeps;
+}
+//
+// Get the export address of symbol aOrdinal
+//
+
+TInt TRomFile::AddressFromOrdinal(TLinAddr& aEDataAddr, TLinAddr& aExport, TUint aOrdinal) {
+	if(aOrdinal == 0) {
+		aEDataAddr = iExportDir.iRunAddr -1 ;
+		aExport = *(TLinAddr*)((TLinAddr*)iExportDir.iImagePtr - 1);
+		if((TInt)aExport == ExportDirCount()) {
+			aEDataAddr = 0;
+			aExport = 0;
+		}
+		return KErrNone;
+	}
+
+	TUint index = aOrdinal - KOrdinalBase;
+	if (index >= (TUint)ExportDirCount())
+		return KErrNotFound;
+	aEDataAddr = iExportDir.iRunAddr + index * sizeof(TLinAddr);
+	aExport = ((TLinAddr*)iExportDir.iImagePtr)[index];
+	return KErrNone;
+}
+
+
+bool TRomFile::ComputeSmpSafe(const TRomBuilderEntry* aRbEntry) {
+	// A component is SMP safe if:
+	//
+	// 1. It's E32 image file is marked as SMP safe (MMP keyword SMPSAFE).
+	// 2. All components it links to are SMP safe.
+	//
+	// This implies a recursive dependency structure.
+
+	if (iSmpInfo.isInit) {
+		// We have already visited this node.
+		return iSmpInfo.isSafe;
+	}
+
+	// Mark this node as "active," meaning that we are currently evaluating it. We
+	// use this to detect cycles in the dependency graph.
+	iSmpInfo.isActive = 1;
+
+	iSmpInfo.isSafe = 1;
+
+	// Have we found any cycle in the graph?
+	bool is_cycle = 0;
+
+	if ( aRbEntry->iOrigHdr->iFlags & KImageSMPSafe ) {
+		// OK, the E32 file for this node is marked as SMPSAFE. Now we need to check
+		// that all nodes we depend on are SMP safe.
+
+		for (int i = 0; i < iNumDeps; i++) {
+			TRomFile* e = iDeps[i];
+
+			assert(this != e);
+
+			if (e->iSmpInfo.isActive) {
+				is_cycle = 1;
+			}
+			else if ( ! e->ComputeSmpSafe(e->iRbEntry) ) {
+				if (gLogLevel & LOG_LEVEL_SMP_INFO) {
+					Print(ELog,"SMP-unsafe: %s: links to unsafe component %s.\n",
+						aRbEntry->iBareName , e->iRbEntry->iBareName);
+				}
+
+				iSmpInfo.isSafe = 0;
+				break;
+			}
+		}
+	}
+	else {
+		if (gLogLevel & LOG_LEVEL_SMP_INFO) {
+			Print(ELog,"SMP-unsafe: %s: MMP keyword SMPSAFE not used.\n", aRbEntry->iBareName);
+		}
+
+		iSmpInfo.isSafe = 0;
+	}
+
+	iSmpInfo.isActive = 0;
+
+	if (!iSmpInfo.isSafe || !is_cycle) {
+		iSmpInfo.isInit = 1;
+	}
+
+	return iSmpInfo.isSafe;
+}
+
+/**
+* TRomNode::CopyDirectory performs a deep copy of the TRomNode structure
+*/
+TRomNode* TRomNode::CopyDirectory(TRomNode*& aLastExecutable, TRomNode* aParent) {
+	if (iHidden && iChild==0) {
+		// Hidden file - do not copy (as it wouldn't be visible in the ROM filestructure)
+		if (iSibling)
+			return iSibling->CopyDirectory(aLastExecutable, aParent);
+		else
+			return 0;
+	}
+
+	TRomNode* copy = new TRomNode(*this);
+	copy->iParent = aParent;
+	if(aLastExecutable==0)
+		aLastExecutable = copy;		// this must be the root of the structure
+
+	// recursively copy the sub-structures
+	if (iChild)
+		copy->iChild = iChild->CopyDirectory(aLastExecutable, copy);
+	if (iSibling)
+		copy->iSibling = iSibling->CopyDirectory(aLastExecutable, aParent);
+
+	if (copy->iAtt & KEntryAttXIP)
+		AddExecutableFile(aLastExecutable,copy);
+	return copy;
+}
+
+TInt TRomNode::Alias(TRomNode* aNode, TRomNode*& aLastExecutable) {
+	if (aNode->iAtt & KEntryAttXIP)
+		AddExecutableFile(aLastExecutable,this);
+	return SetBareName();
+}
+
+TInt TRomNode::Rename(TRomNode *aOldParent, TRomNode* aNewParent, const char* aNewName) {
+	aOldParent->Remove(this);
+	aNewParent->Add(this);
+	if(iName)
+		delete []iName;
+	iName = NormaliseFileName(aNewName);
+	return SetBareName();
+}
+
+TInt TRomNode::SetBareName() {
+	if(iBareName) {
+		delete []iBareName;
+		iBareName = 0 ;
+	}
+	TUint32 uid;
+	TUint32 vin;
+	TUint32 flg;
+	iBareName = SplitFileName(iName, uid, vin, flg);
+	if (uid || (flg & EUidPresent))
+		return KErrBadName;
+	if (strchr(iBareName, '{') || strchr(iBareName, '}'))
+		return KErrBadName;
+	if ((iAtt & KEntryAttXIP) && (flg & EVerPresent)) {
+		TUint32 ver = iRomFile->ModuleVersion();
+		if (ver != vin)
+			return KErrArgument;
+	}
+	return KErrNone;
+}
--- a/imgtools/romtools/rombuild/r_coreimage.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_coreimage.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,189 +1,175 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include <e32def.h>
-#include <e32def_private.h>
-#include <e32rom.h>
-
-#include "h_utl.h"
-#include "r_rom.h"
-
-#include "r_coreimage.h"
-
-// CoreRomImage
-//
-CoreRomImage::CoreRomImage(char* aFileName) : 
-iReader(0),
-iFileName(aFileName),
-iRomHdr(0),
-iRootDirectory(0),
-iNumVariants(0),
-iVariants(0),
-iRomAlign(0),
-iDataRunAddress(0) 
-{	 
-}
-
-CoreRomImage::~CoreRomImage()
-{
-	if(iReader)
-		delete iReader;
-
-	if(iVariants)
-		delete[] iVariants;
-}
-
-TBool CoreRomImage::ProcessImage(const TBool aUseMemMap)
-{
-	TBool Status = EFalse;
-	TRomRootDirectoryList *rootDirInfo = 0;
-	TInt dirCount = 0;
-
-	iReader = new CoreRomImageReader(iFileName, aUseMemMap);
-
-	if(!iReader)
-	{
-		return EFalse;
-	}
-
-	if(iReader->OpenImage())
-	{
-		Status = iReader->ProcessImage();
-	}
-
-	if(Status)
-	{
-		// CoreRomHeader Info
-		iRomHdr = iReader->GetCoreRomHeader();
-
-		if(iRomHdr)
-		{
-			// Root Directory Info
-			rootDirInfo = iReader->GetRootDirList();
-			dirCount = rootDirInfo->iNumRootDirs;
-			if(dirCount)
-			{
-				iNumVariants = dirCount;
-				iVariants = new THardwareVariant[dirCount];
-
-				if(iVariants)
-				{
-					while(dirCount--)
-					{
-						iVariants[dirCount] = rootDirInfo->iRootDir[dirCount].iHardwareVariant;
-					}
-				}
-
-				// RootDirectory Info
-				iRootDirectory = iReader->GetRootDirectory();
-			}
-			else
-			{
-				Status = EFalse;
-			}
-		}
-		else
-		{
-			Status = EFalse;
-		}
-	}
-
-	return Status;
-}
-
-TRomNode* CoreRomImage::CopyDirectory(TRomNode*& aSourceDirectory)
-{
-	return iRootDirectory->CopyDirectory(aSourceDirectory,0); 
-}
-
-TUint32 CoreRomImage::RomBase()
-{
-	return (iRomHdr->iRomBase);
-}
-
-TUint32 CoreRomImage::RomSize()
-{
-	return (iRomHdr->iRomSize);
-}
-
-TVersion CoreRomImage::Version()
-{
-	return (iRomHdr->iVersion);
-}
-
-TInt64 CoreRomImage::Time()
-{
-	return (iRomHdr->iTime);
-}
-
-TUint32 CoreRomImage::CheckSum()
-{
-	return (iRomHdr->iCheckSum);
-}
-
-TUint32 CoreRomImage::CompressionType()
-{
-	return (iRomHdr->iCompressionType);
-}
-
-TRomNode* CoreRomImage::RootDirectory()
-{ 
-	return iRootDirectory; 
-}
-
-TText* CoreRomImage::RomFileName()
-{ 
-	return (TText*)iFileName.data();
-}
-
-TUint32 CoreRomImage::RomAlign()
-{
-	return iRomAlign;
-}
-
-TUint32 CoreRomImage::DataRunAddress()
-{
-	return iDataRunAddress;
-}
-
-TInt32 CoreRomImage::VariantCount()
-{ 
-	return iNumVariants; 
-}
-
-THardwareVariant* CoreRomImage::VariantList()
-{ 
-	return iVariants;
-}
-
-void CoreRomImage::SetRomAlign(const TUint32 aAlign)
-{
-	iRomAlign = aAlign;
-}
-
-void CoreRomImage::SetDataRunAddress(const TUint32 aRunAddress)
-{
-	iDataRunAddress = aRunAddress;
-}
-
-void CoreRomImage::DisplayNodes()
-{ 
-	iReader->Display(iRootDirectory);
-	return;
-}
-
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#include <e32def.h>
+#include <e32def_private.h>
+#include <e32rom.h>
+
+#include "h_utl.h"
+#include "r_rom.h"
+
+#include "r_coreimage.h"
+
+// CoreRomImage
+//
+CoreRomImage::CoreRomImage(const char* aFileName) : 
+iReader(0),
+iFileName(aFileName),
+iRomHdr(0),
+iRootDirectory(0),
+iNumVariants(0),
+iVariants(0),
+iRomAlign(0),
+iDataRunAddress(0) 
+{	 
+}
+
+CoreRomImage::~CoreRomImage()
+{
+	if(iReader)
+		delete iReader;
+
+	if(iVariants)
+		delete[] iVariants;
+}
+
+TBool CoreRomImage::ProcessImage(const TBool aUseMemMap)
+{
+	TBool Status = EFalse;
+	TRomRootDirectoryList *rootDirInfo = 0;
+	TInt dirCount = 0;
+
+	iReader = new CoreRomImageReader(iFileName.c_str(), aUseMemMap);
+
+	if(!iReader)
+	{
+		return EFalse;
+	}
+
+	if(iReader->OpenImage())
+	{
+		Status = iReader->ProcessImage();
+	}
+
+	if(Status)
+	{
+		// CoreRomHeader Info
+		iRomHdr = iReader->GetCoreRomHeader();
+
+		if(iRomHdr)
+		{
+			// Root Directory Info
+			rootDirInfo = iReader->GetRootDirList();
+			dirCount = rootDirInfo->iNumRootDirs;
+			if(dirCount)
+			{
+				iNumVariants = dirCount;
+				iVariants = new THardwareVariant[dirCount];
+
+				if(iVariants)
+				{
+					while(dirCount--)
+					{
+						iVariants[dirCount] = rootDirInfo->iRootDir[dirCount].iHardwareVariant;
+					}
+				}
+
+				// RootDirectory Info
+				iRootDirectory = iReader->GetRootDirectory();
+			}
+			else
+			{
+				Status = EFalse;
+			}
+		}
+		else
+		{
+			Status = EFalse;
+		}
+	}
+
+	return Status;
+}
+
+TRomNode* CoreRomImage::CopyDirectory(TRomNode*& aSourceDirectory) {
+	return iRootDirectory->CopyDirectory(aSourceDirectory,0); 
+}
+
+TUint32 CoreRomImage::RomBase() const {
+	return (iRomHdr->iRomBase);
+}
+
+TUint32 CoreRomImage::RomSize() const {
+	return (iRomHdr->iRomSize);
+}
+
+TVersion CoreRomImage::Version() const {
+	return (iRomHdr->iVersion);
+}
+
+TInt64 CoreRomImage::Time() const {
+	return (iRomHdr->iTime);
+}
+
+TUint32 CoreRomImage::CheckSum() const {
+	return (iRomHdr->iCheckSum);
+}
+
+TUint32 CoreRomImage::CompressionType() const {
+	return (iRomHdr->iCompressionType);
+}
+
+TRomNode* CoreRomImage::RootDirectory() const {
+	return iRootDirectory; 
+}
+
+const char* CoreRomImage::RomFileName() const {
+	return iFileName.data();
+}
+
+TUint32 CoreRomImage::RomAlign() const {
+	return iRomAlign;
+}
+
+TUint32 CoreRomImage::DataRunAddress() const {
+	return iDataRunAddress;
+}
+
+TInt32 CoreRomImage::VariantCount() const {
+	return iNumVariants; 
+}
+
+THardwareVariant* CoreRomImage::VariantList() const {
+	return iVariants;
+}
+
+void CoreRomImage::SetRomAlign(const TUint32 aAlign)  {
+	iRomAlign = aAlign;
+}
+
+void CoreRomImage::SetDataRunAddress(const TUint32 aRunAddress)
+{
+	iDataRunAddress = aRunAddress;
+}
+
+void CoreRomImage::DisplayNodes()
+{ 
+	iReader->Display(iRootDirectory);
+	return;
+}
+
--- a/imgtools/romtools/rombuild/r_coreimage.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_coreimage.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,80 +1,76 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifndef __R_COREIMAGE_H__
-#define __R_COREIMAGE_H__
-
-#include <string>
-
-typedef std::string String;
-typedef std::ifstream Ifstream;
-
-#include "r_mromimage.h"
-#include "r_coreimagereader.h"
-
-class THardwareVariant;
-
-
-/** 
-class CoreRomImage
-
-@internalComponent
-@released
-*/
-class CoreRomImage : public MRomImage
-{
-private:
-	CoreRomImageReader* iReader;
-	String iFileName;
-
-	TRomHeader *iRomHdr;
-	// Directory Structure
-	TRomNode* iRootDirectory;
-
-	TInt32 iNumVariants;
-	THardwareVariant *iVariants;
-
-	TUint32 iRomAlign;
-	TUint32 iDataRunAddress;
-
-public:
-	CoreRomImage(char* aFileName);
-	~CoreRomImage();
-
-	TBool ProcessImage(TBool aUseMemMap = EFalse);
-	TRomNode* CopyDirectory(TRomNode*& aSourceDirectory);
-
-	TRomNode* RootDirectory();
-	TText* RomFileName();
-	TUint32 RomBase();
-	TUint32 RomSize();
-	TVersion Version();
-	TInt64 Time();
-	TUint32 CheckSum();
-	TUint32 RomAlign();
-	TUint32 DataRunAddress();
-	TUint32 CompressionType();
-	TInt32 VariantCount();
-	THardwareVariant* VariantList();
-	void SetRomAlign(const TUint32 aAlign);
-	void SetDataRunAddress(const TUint32 aRunAddress);
-
-	void DisplayNodes();
-};
-
-#endif //__R_COREIMAGE_H__
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifndef __R_COREIMAGE_H__
+#define __R_COREIMAGE_H__
+
+
+#include "r_mromimage.h"
+#include "r_coreimagereader.h"
+
+class THardwareVariant;
+
+
+/** 
+class CoreRomImage
+
+@internalComponent
+@released
+*/
+class CoreRomImage : public MRomImage
+{
+private:
+	CoreRomImageReader* iReader;
+	string iFileName;
+
+	TRomHeader *iRomHdr;
+	// Directory Structure
+	TRomNode* iRootDirectory;
+
+	TInt32 iNumVariants;
+	THardwareVariant *iVariants;
+
+	TUint32 iRomAlign;
+	TUint32 iDataRunAddress;
+
+public:
+	CoreRomImage(const char* aFileName);
+	virtual ~CoreRomImage();
+
+	TBool ProcessImage(TBool aUseMemMap = EFalse);
+	TRomNode* CopyDirectory(TRomNode*& aSourceDirectory);
+
+	TRomNode* RootDirectory() const ;
+	const char* RomFileName() const ;
+	TUint32 RomBase() const ;
+	TUint32 RomSize() const ;
+	TVersion Version() const ;
+	TInt64 Time() const ;
+	TUint32 CheckSum() const ;
+	TUint32 RomAlign() const ;
+	TUint32 DataRunAddress() const ;
+	TUint32 CompressionType() const ;
+	TInt32 VariantCount() const ;
+	THardwareVariant* VariantList() const ;
+	void SetRomAlign(const TUint32 aAlign);
+	void SetDataRunAddress(const TUint32 aRunAddress);
+
+	void DisplayNodes();
+};
+
+#endif //__R_COREIMAGE_H__
--- a/imgtools/romtools/rombuild/r_coreimagereader.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_coreimagereader.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,615 +1,606 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include <e32def.h>
-#include <e32def_private.h>
-#include <e32rom.h>
-
-#include "h_utl.h"
-#include "r_rom.h"
-
-#include "memmap.h"
-
-#include "r_coreimage.h"
-#include "r_global.h"
-
-
-#define ROM_PTR(base_ptr) ((TInt8*)iRomHdr + (base_ptr - iRomHdr->iRomBase))
-
-void InflateUnCompress(unsigned char* source, int sourcesize, unsigned char* dest, int destsize);
-
-const TUint KEntryAttDir=0x0010;
-const TUint KEntryAttXIP=0x0080;
-const TUint KEntryAttHidden=0x0002;
-
-// CoreRomImageReader
-// 
-CoreRomImageReader::CoreRomImageReader(String aFileName, TBool aUseMemMap) : iImgFileName(aFileName), 
-iData(0), iLoaderHdr(0), iRomHdr(0), iRootDirList(0), iRootDirectory(0), iUseMemMap(aUseMemMap), iImageMap(0)
-{
-}
-
-CoreRomImageReader::~CoreRomImageReader() 
-{
-	if(iData)
-	{
-		if(iUseMemMap)
-		{
-			iImageMap->CloseMemoryMap(ETrue);
-			delete iImageMap;
-		}
-		else
-			delete iData;
-	}
-
-	if(iRootDirectory)
-	{
-		DeleteAll(iRootDirectory);
-	}
-}
-
-TBool CoreRomImageReader::IsCoreROM()
-{
-	if(iData)
-	{
-		if(iData[0] == 'E' && iData[1] == 'P' && iData[2] == 'O' && iData[3] == 'C' &&
-			iData[8]  == 'R' && iData[9]  == 'O' && iData[10] == 'M')
-		{
-			return ETrue;
-		}
-	}
-
-	return EFalse;
-}
-
-TUint CoreRomImageReader::GetHdrSize()
-{ 
-	return (sizeof(TRomLoaderHeader) + sizeof(TRomHeader)); 
-}
-
-TBool CoreRomImageReader::AllocateImageMap(Memmap*& aImageMap, TUint8*& aData, TUint aLen)
-{
-	aImageMap = new Memmap(EFalse);
-
-	if(aImageMap == NULL)
-	{
-		return EFalse;
-	}
-	else
-	{
-		aImageMap->SetMaxMapSize(aLen);
-		if(aImageMap->CreateMemoryMap() == EFalse)
-		{
-			aImageMap->CloseMemoryMap(ETrue);
-			delete aImageMap;
-			aImageMap = NULL;
-			return EFalse;
-		}
-		else
-		{
-			aData = (TUint8*)aImageMap->GetMemoryMapPointer();
-		}
-	}
-
-	return ETrue;
-}
-
-TBool CoreRomImageReader::OpenImage()
-{
-	TUint aLen = 0;
-
-	Ifstream aIf(iImgFileName.data(), std::ios::binary | std::ios::in);
-	if( !aIf.is_open() )
-	{
-		Print(EError, "Cannot open file %s", (char*)iImgFileName.data());
-		return EFalse;
-	}
-
-	aIf.seekg(0, std::ios::end);
-	aLen = aIf.tellg();
-
-	if(iUseMemMap)
-	{
-		if(!AllocateImageMap(iImageMap, iData, aLen))
-		{
-			aLen = 0;
-			Print(EError, "Failed to create image map object");
-			return EFalse;
-		}
-	}
-	else
-	{
-		iData = new unsigned char[aLen];
-		if(iData == NULL)
-		{
-			aLen = 0;
-			Print(EError, "Out of memory.\n");
-			return EFalse;
-		}
-		memset(iData, 0, aLen);
-	}
-	aIf.seekg(0, std::ios::beg);
-	aIf.read((char*)iData, aLen);
-
-	if(!IsCoreROM() || !StoreImageHeader())
-	{
-		Print(EError, "Invalid Core ROM image %s", (char*)iImgFileName.data());
-		aIf.close();
-		return EFalse;
-	}
-
-	aIf.close();
-
-	return ETrue;
-}
-
-TBool CoreRomImageReader::StoreImageHeader()
-{
-	iLoaderHdr = (TRomLoaderHeader*)iData;
-	iRomHdr = (TRomHeader*)(iData + sizeof(TRomLoaderHeader));
-
-	if(!iLoaderHdr || !iRomHdr)
-		return EFalse;
-
-	return ETrue;
-}
-
-TInt CoreRomImageReader::CreateRootDirectory()
-{
-	iRootDirectory = new TRomNode((TText*)"", (TRomBuilderEntry*)0);
-	if (iRootDirectory == 0 )
-		return KErrNoMemory;
-	return KErrNone;
-}
-
-TBool CoreRomImageReader::ProcessImage()
-{
-	Memmap *aImageMap = 0;
-
-	if(iRomHdr->iCompressionType == KUidCompressionDeflate)
-	{
-		TUint aDataStart = GetHdrSize();
-		TUint8* aData = 0;
-		if(iUseMemMap)
-		{
-			if(!AllocateImageMap(aImageMap, aData, (iRomHdr->iUncompressedSize + aDataStart)))
-			{
-				Print(EError, "Failed to create image map object");
-				return EFalse;
-			}
-		}
-		else
-		{
-			aData = new unsigned char[iRomHdr->iUncompressedSize + aDataStart];
-		}
-
-		InflateUnCompress((unsigned char*)(iData + aDataStart), iRomHdr->iCompressedSize, (unsigned char*)(aData + aDataStart), iRomHdr->iUncompressedSize);
-		memcpy(aData, iData, aDataStart);
-
-		if(iUseMemMap)
-		{
-			iImageMap->CloseMemoryMap(ETrue);
-			delete iImageMap;
-			iImageMap = aImageMap;
-		}
-		else
-		{
-			delete [] iData;
-		}
-		
-		iData = aData;
-		
-		//update the header fields...
-		if(!StoreImageHeader())
-		{
-			return EFalse;
-		}
-	}
-	else if (iRomHdr && iRomHdr->iRomPageIndex) // paged ROM
-	{
-		const TInt KPageSize = 0x1000;
-		TUint8* aData = 0;
-		
-		TRomHeader *pRomHdr = iRomHdr;
-		
-		TUint headerSize = GetHdrSize();
-		
-		TInt numPages = (pRomHdr->iPageableRomStart + pRomHdr->iPageableRomSize+KPageSize-1)/KPageSize;
-		if(iUseMemMap)
-		{
-			if(!AllocateImageMap(aImageMap, aData, (pRomHdr->iUncompressedSize + headerSize)))
-			{
-				Print(EError, "Failed to create image map object");
-				return EFalse;
-			}
-		}
-		else
-		{
-			aData = new TUint8[pRomHdr->iUncompressedSize + headerSize];
-		}
-		TUint8* dest = (aData + sizeof(TRomLoaderHeader) + pRomHdr->iPageableRomStart);
-		SRomPageInfo* pi = (SRomPageInfo*)((TUint8*)pRomHdr + pRomHdr->iRomPageIndex);
-		
-                CBytePair bpe(gFastCompress);
-		for(TInt i=0; i<numPages; i++,pi++)
-		{
-			if (pi->iPagingAttributes != SRomPageInfo::EPageable) // skip uncompressed part at the beginning of ROM image
-				continue;
-			
-			switch(pi->iCompressionType)
-			{
-			case SRomPageInfo::ENoCompression:
-				{
-					memcpy(dest, (TUint8*)pRomHdr + pi->iDataStart, pi->iDataSize);
-					dest += pi->iDataSize;
-				}
-				break;
-				
-			case SRomPageInfo::EBytePair:
-				{
-					TUint8* srcNext=0;
-					TInt unpacked = bpe.Decompress((unsigned char*)dest, KPageSize, (TUint8*)pRomHdr + pi->iDataStart, pi->iDataSize, srcNext);
-					if (unpacked < 0)
-					{
-						if(iUseMemMap)
-						{
-							aImageMap->CloseMemoryMap(ETrue);
-							delete aImageMap;
-						}
-						else
-						{
-							delete [] aData;
-						}
-						Print(EError, "Corrupted BytePair compressed ROM image %s", (char*)iImgFileName.data());
-						return EFalse;
-					}
-					
-					dest += unpacked;
-				}
-				break;
-
-			default:
-				{
-					if(iUseMemMap)
-					{
-						aImageMap->CloseMemoryMap(ETrue);
-						delete aImageMap;
-					}
-					else
-					{
-						delete [] aData;
-					}
-					Print(EError, "Undefined compression type in %s", (char*)iImgFileName.data());
-					return EFalse;
-				}
-			}
-		}
-		
-		memcpy(aData, iData, sizeof(TRomLoaderHeader) + pRomHdr->iPageableRomStart);
-		if(iUseMemMap)
-		{
-			iImageMap->CloseMemoryMap(ETrue);
-			delete iImageMap;
-			iImageMap = aImageMap;
-		}
-		else
-		{
-			delete [] iData;
-		}
-		
-		iData = aData;
-		
-		//update the header fields...
-		if(!StoreImageHeader())
-		{
-			return EFalse;
-		}
-	}
-
-	if(CreateRootDirectory() != KErrNone)
-	{
-		return EFalse;
-	}
-
-	if(GetDirectoryStructures() != KErrNone)
-	{
-		return EFalse;
-	}
-
-	return ETrue;
-}
-
-TInt CoreRomImageReader::GetDirectoryStructures()
-{
-	int aDirs = 0;
-	TRomDir	*aRomDir = 0;
-
-	iRootDirList = (TRomRootDirectoryList*)ROM_PTR(iRomHdr->iRomRootDirectoryList);
-
-	while( aDirs < iRootDirList->iNumRootDirs )
-	{
-		aRomDir = (TRomDir*)ROM_PTR(iRootDirList->iRootDir[aDirs].iAddressLin);
-
-		if(BuildDir(aRomDir, iRootDirectory) != KErrNone)
-		{
-			return KErrNoMemory;
-		}
-		aDirs++;
-	}
-
-	return KErrNone;
-}
-
-
-TInt OffsetCompare(const void *a, const void *b)
-{
-	return ( *(TInt16*)a - *(TInt16*)b );
-}
-
-TInt CoreRomImageReader::BuildDir(TRomDir* aDir, TRomNode* aPaFSEntry)
-{
-	TInt16			*aFileCnt = 0;
-	TInt16			*aBase, aCount;
-	TInt16			*aSubDirCnt = 0;
-
-	//Sub directories in this directories
-	aSubDirCnt = (TInt16*)((char*)aDir + aDir->iSize + sizeof(aDir->iSize));
-
-	//Files within this directory
-	aFileCnt = aSubDirCnt+1;
-
-	aCount = (*aFileCnt + *aSubDirCnt);
-
-	aBase = aFileCnt+1;
-
-	qsort((void*)aBase, aCount, sizeof(TInt16), &OffsetCompare);
-
-	return BuildDir(aBase, aCount, aDir, aPaFSEntry);
-}
-
-TInt CoreRomImageReader::BuildDir(TInt16 *aOffsetTbl, TInt16 aOffsetTblCount, 
-								  TRomDir *aPaRomDir, TRomNode* aPaFSEntry)
-{
-	TRomNode		*aNewFSEntry;
-	TRomDir			*aNewDir;
-	TRomEntry		*aRomEntry;
-	TUint32			aOffsetFromBase;
-
-	String	aName;
-	char	*aPtr;
-
-	while( aOffsetTblCount )
-	{
-		aOffsetFromBase = *aOffsetTbl;
-
-		aOffsetFromBase <<= 2;
-
-		aRomEntry = (TRomEntry*)((char*)aPaRomDir + sizeof(int) + aOffsetFromBase);
-
-		aPtr = (char*)aRomEntry->iName;
-		Name(aName, aPtr, aRomEntry->iNameLength);
-
-		if( aRomEntry->iAtt & KEntryAttDir )
-		{
-			// add directory
-			aNewFSEntry = aPaFSEntry->NewSubDir((unsigned char*)aName.data());
-			if(aRomEntry->iAtt & KEntryAttHidden)
-				aNewFSEntry->iHidden = ETrue;
-			else
-				aNewFSEntry->iHidden = EFalse;
-
-			aNewDir = (TRomDir*)ROM_PTR(aRomEntry->iAddressLin);
-			if(BuildDir(aNewDir, aNewFSEntry) != KErrNone)
-			{
-				return KErrNoMemory;
-			}
-		}
-		else
-		{
-			// add file
-			if(AddFile(aPaFSEntry, (char*)aName.data(), aRomEntry) != KErrNone)
-			{
-				return KErrNoMemory;
-			}
-		}
-
-		aOffsetTblCount--;
-		aOffsetTbl++;
-	}
-
-	return KErrNone;
-}
-
-TInt CoreRomImageReader::AddFile(TRomNode *aPa, char *entryName, TRomEntry* aRomEntry)
-{
-	TRomImageHeader*	aImgHdr = 0;
-	TRomBuilderEntry*	aFile = 0;
-	TRomNode*			aNewFSEntry = 0;
-	static TRomNode*	aLastExecutable = GetRootDirectory();
-	TUint8				aUid1[4];
-
-	aImgHdr = (TRomImageHeader*)ROM_PTR(aRomEntry->iAddressLin);
-
-	aFile = new TRomBuilderEntry(0, (TUint8*)entryName);
-
-	if(!aFile)
-	{
-		return KErrNoMemory;
-	}
-
-	aFile->iBareName = strdup((char*)aFile->iName);
-	aFile->iUid1 = aImgHdr->iUid1;
-	aFile->iUid2 = aImgHdr->iUid2;
-	aFile->iUid3 = aImgHdr->iUid3;
-	aFile->iRomImageFlags = aImgHdr->iFlags;
-	aFile->iHardwareVariant = aImgHdr->iHardwareVariant;
-
-	memcpy(aUid1, &(aImgHdr->iUid1), 4);
-
-	aFile->iResource = !IsExecutable(aUid1);
-
-	aNewFSEntry = new TRomNode((TUint8*)entryName, aFile);
-	if(!aNewFSEntry)
-	{
-		return KErrNoMemory;
-	}
-
-	if(aRomEntry->iAtt & KEntryAttHidden)
-		aNewFSEntry->iHidden = ETrue;
-	else
-		aNewFSEntry->iHidden = EFalse;
-
-	// RomEntry Update
-	aNewFSEntry->iRomFile->SetRomEntry(aRomEntry);
-	aNewFSEntry->iRomFile->iFinal = ETrue;
-	
-	// E32 Image Pointer Update
-	aNewFSEntry->iRomFile->iAddresses.iImageAddr = aRomEntry->iAddressLin;
-	aNewFSEntry->iRomFile->iAddresses.iRunAddr = aRomEntry->iAddressLin;
-	aNewFSEntry->iRomFile->iAddresses.iSize = aRomEntry->iSize;
-	aNewFSEntry->iRomFile->iAddresses.iImagePtr = 0;
-	aNewFSEntry->iRomFile->iExportDir.iImagePtr = 0;
-
-	if(!aFile->iResource  && !aFile->HCRDataFile())
-	{
-		// Hardware Variant Update
-		aNewFSEntry->iRomFile->iHwvd = aImgHdr->iHardwareVariant;
-		// Security Info Update
-		aNewFSEntry->iRomFile->iRbEntry->iS = aImgHdr->iS;
-
-		// Export Table Update
-		aNewFSEntry->iRomFile->iExportDir.iSize = aImgHdr->iExportDirCount*4;
-		aNewFSEntry->iRomFile->iExportDir.iImageAddr = aImgHdr->iExportDir;
-		aNewFSEntry->iRomFile->iExportDir.iRunAddr = aImgHdr->iExportDir;
-
-		if(aImgHdr->iExportDirCount)
-		{
-			aNewFSEntry->iRomFile->iExportDir.iImagePtr = new char[aNewFSEntry->iRomFile->iExportDir.iSize];
-			memcpy(aNewFSEntry->iRomFile->iExportDir.iImagePtr,
-				   (TInt8*)ROM_PTR(aImgHdr->iExportDir), 
-				   aNewFSEntry->iRomFile->iExportDir.iSize);
-		}
-
-		// E32 Image pointer Update
-		aNewFSEntry->iRomFile->iAddresses.iImagePtr = new char[sizeof(TRomImageHeader)];
-		memcpy(aNewFSEntry->iRomFile->iAddresses.iImagePtr, aImgHdr, sizeof(TRomImageHeader));
-	}
-	else
-	{
-		aNewFSEntry->iRomFile->iHwvd = KVariantIndependent;
-	}
-
-	aPa->AddFile(aNewFSEntry);
-
-	if(aRomEntry->iAtt & KEntryAttXIP)
-	{
-		TRomNode::AddExecutableFile(aLastExecutable, aNewFSEntry);
-	}
-
-	return KErrNone;
-}
-
-void CoreRomImageReader::Name(String& aName, char * aUnicodeName, int aLen)
-{
-	int aPos = 0;
-	int uncodeLen = aLen << 1;
-	aName=("");
-	while( aPos < uncodeLen)
-	{
-		if( aUnicodeName[aPos] )
-			aName += aUnicodeName[aPos];
-		aPos++;
-	}
-}
-
-TBool CoreRomImageReader::IsExecutable(TUint8* Uids1)
-{
-	//In the little-endian world
-	if( Uids1[3] == 0x10 &&
-		Uids1[2] == 0x0 &&
-		Uids1[1] == 0x0 )
-	{
-		if(Uids1[0] == 0x79 || Uids1[0] == 0x7a)
-			return ETrue;
-	}
-	return EFalse;
-}
-
-void CoreRomImageReader::DeleteAll(TRomNode *node)
-{
-	if(!node)
-		return;
-
-	if(node->iChild)
-	{
-		DeleteAll(node->iChild);
-	}
-
-	if(node->iSibling)
-	{
-		DeleteAll(node->iSibling);
-	}
-
-	if(node->iRomFile)
-	{
-		if(!node->iRomFile->iDir)
-		{
-			if(node->iRomFile->iExportDir.iImagePtr)
-			{
-				delete[] (char*)node->iRomFile->iExportDir.iImagePtr;
-				node->iRomFile->iExportDir.iImagePtr = 0;
-			}
-			if(node->iRomFile->iAddresses.iImagePtr)
-			{
-				delete[] (char*)node->iRomFile->iAddresses.iImagePtr;
-				node->iRomFile->iAddresses.iImagePtr = 0;
-			}
-
-			if(node->iRomFile->iRbEntry)
-			{
-				delete node->iRomFile->iRbEntry;
-				node->iRomFile->iRbEntry = 0;
-			}
-		}
-		delete node->iRomFile;
-		node->iRomFile = 0;
-	}
-	delete node;
-	node = 0;
-}
-
-
-void CoreRomImageReader::Display(TRomNode *node, TInt pad)
-{
-	if(!node)
-		return;
-
-	Print(ELog, "\n%*s%s", pad, " ", node->iBareName);
-
-	if(node->iChild)
-	{
-		pad += 2;
-		Display(node->iChild, pad);
-		pad -= 2;
-	}
-
-	if(node->iSibling)
-	{
-		Display(node->iSibling, pad);
-	}
-}
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#include <e32def.h>
+#include <e32def_private.h>
+#include <e32rom.h>
+
+#include "h_utl.h"
+#include "r_rom.h"
+
+#include "memmap.h"
+
+#include "r_coreimage.h"
+#include "r_global.h"
+#include "utf16string.h"
+ 
+
+#define ROM_PTR(base_ptr) ((TInt8*)iRomHdr + (base_ptr - iRomHdr->iRomBase))
+
+void InflateUnCompress(unsigned char* source, int sourcesize, unsigned char* dest, int destsize);
+
+const TUint KEntryAttDir=0x0010;
+const TUint KEntryAttXIP=0x0080;
+const TUint KEntryAttHidden=0x0002;
+
+// CoreRomImageReader
+// 
+CoreRomImageReader::CoreRomImageReader(const char* aFileName, TBool aUseMemMap) : iImgFileName(aFileName), 
+iData(0), iLoaderHdr(0), iRomHdr(0), iRootDirList(0), iRootDirectory(0), iUseMemMap(aUseMemMap), iImageMap(0)
+{
+}
+
+CoreRomImageReader::~CoreRomImageReader() 
+{
+	if(iData)
+	{
+		if(iUseMemMap)
+		{
+			iImageMap->CloseMemoryMap(ETrue);
+			delete iImageMap;
+		}
+		else
+			delete iData;
+	}
+
+	if(iRootDirectory)
+	{
+		DeleteAll(iRootDirectory);
+	}
+}
+
+TBool CoreRomImageReader::IsCoreROM()
+{
+	if(iData)
+	{
+		if(iData[0] == 'E' && iData[1] == 'P' && iData[2] == 'O' && iData[3] == 'C' &&
+			iData[8]  == 'R' && iData[9]  == 'O' && iData[10] == 'M')
+		{
+			return ETrue;
+		}
+	}
+
+	return EFalse;
+}
+
+TUint CoreRomImageReader::GetHdrSize()
+{ 
+	return (sizeof(TRomLoaderHeader) + sizeof(TRomHeader)); 
+}
+
+TBool CoreRomImageReader::AllocateImageMap(Memmap*& aImageMap, TUint8*& aData, TUint aLen)
+{
+	aImageMap = new Memmap(EFalse);
+
+	if(aImageMap == NULL)
+	{
+		return EFalse;
+	}
+	else
+	{
+		aImageMap->SetMaxMapSize(aLen);
+		if(aImageMap->CreateMemoryMap() == EFalse)
+		{
+			aImageMap->CloseMemoryMap(ETrue);
+			delete aImageMap;
+			aImageMap = NULL;
+			return EFalse;
+		}
+		else
+		{
+			aData = (TUint8*)aImageMap->GetMemoryMapPointer();
+		}
+	}
+
+	return ETrue;
+}
+
+TBool CoreRomImageReader::OpenImage()
+{
+	TUint aLen = 0;
+
+	ifstream aIf(iImgFileName.c_str(), ios_base::binary | ios_base::in);
+	if( !aIf.is_open() )
+	{
+		Print(EError, "Cannot open file %s", iImgFileName.c_str());
+		return EFalse;
+	}
+
+	aIf.seekg(0, ios_base::end);
+	aLen = aIf.tellg();
+
+	if(iUseMemMap)
+	{
+		if(!AllocateImageMap(iImageMap, iData, aLen))
+		{
+			aLen = 0;
+			Print(EError, "Failed to create image map object");
+			return EFalse;
+		}
+	}
+	else
+	{
+		iData = new unsigned char[aLen];
+		if(iData == NULL)
+		{
+			aLen = 0;
+			Print(EError, "Out of memory.\n");
+			return EFalse;
+		}
+		memset(iData, 0, aLen);
+	}
+	aIf.seekg(0, ios_base::beg);
+	aIf.read((char*)iData, aLen);
+
+	if(!IsCoreROM() || !StoreImageHeader())
+	{
+		Print(EError, "Invalid Core ROM image %s", iImgFileName.c_str());
+		aIf.close();
+		return EFalse;
+	}
+
+	aIf.close();
+
+	return ETrue;
+}
+
+TBool CoreRomImageReader::StoreImageHeader()
+{
+	iLoaderHdr = (TRomLoaderHeader*)iData;
+	iRomHdr = (TRomHeader*)(iData + sizeof(TRomLoaderHeader));
+
+	if(!iLoaderHdr || !iRomHdr)
+		return EFalse;
+
+	return ETrue;
+}
+
+TInt CoreRomImageReader::CreateRootDirectory()
+{
+	iRootDirectory = new TRomNode("", (TRomBuilderEntry*)0);
+	if (iRootDirectory == 0 )
+		return KErrNoMemory;
+	return KErrNone;
+}
+
+TBool CoreRomImageReader::ProcessImage()
+{
+	Memmap *aImageMap = 0;
+
+	if(iRomHdr->iCompressionType == KUidCompressionDeflate)
+	{
+		TUint aDataStart = GetHdrSize();
+		TUint8* aData = 0;
+		if(iUseMemMap)
+		{
+			if(!AllocateImageMap(aImageMap, aData, (iRomHdr->iUncompressedSize + aDataStart)))
+			{
+				Print(EError, "Failed to create image map object");
+				return EFalse;
+			}
+		}
+		else
+		{
+			aData = new unsigned char[iRomHdr->iUncompressedSize + aDataStart];
+		}
+
+		InflateUnCompress((unsigned char*)(iData + aDataStart), iRomHdr->iCompressedSize, (unsigned char*)(aData + aDataStart), iRomHdr->iUncompressedSize);
+		memcpy(aData, iData, aDataStart);
+
+		if(iUseMemMap)
+		{
+			iImageMap->CloseMemoryMap(ETrue);
+			delete iImageMap;
+			iImageMap = aImageMap;
+		}
+		else
+		{
+			delete [] iData;
+		}
+		
+		iData = aData;
+		
+		//update the header fields...
+		if(!StoreImageHeader())
+		{
+			return EFalse;
+		}
+	}
+	else if (iRomHdr && iRomHdr->iRomPageIndex) // paged ROM
+	{
+		const TInt KPageSize = 0x1000;
+		TUint8* aData = 0;
+		
+		TRomHeader *pRomHdr = iRomHdr;
+		
+		TUint headerSize = GetHdrSize();
+		
+		TInt numPages = (pRomHdr->iPageableRomStart + pRomHdr->iPageableRomSize+KPageSize-1)/KPageSize;
+		if(iUseMemMap)
+		{
+			if(!AllocateImageMap(aImageMap, aData, (pRomHdr->iUncompressedSize + headerSize)))
+			{
+				Print(EError, "Failed to create image map object");
+				return EFalse;
+			}
+		}
+		else
+		{
+			aData = new TUint8[pRomHdr->iUncompressedSize + headerSize];
+		}
+		TUint8* dest = (aData + sizeof(TRomLoaderHeader) + pRomHdr->iPageableRomStart);
+		SRomPageInfo* pi = (SRomPageInfo*)((TUint8*)pRomHdr + pRomHdr->iRomPageIndex);
+		
+                CBytePair bpe;
+		for(TInt i=0; i<numPages; i++,pi++)
+		{
+			if (pi->iPagingAttributes != SRomPageInfo::EPageable) // skip uncompressed part at the beginning of ROM image
+				continue;
+			
+			switch(pi->iCompressionType)
+			{
+			case SRomPageInfo::ENoCompression:
+				{
+					memcpy(dest, (TUint8*)pRomHdr + pi->iDataStart, pi->iDataSize);
+					dest += pi->iDataSize;
+				}
+				break;
+				
+			case SRomPageInfo::EBytePair:
+				{
+					TUint8* srcNext=0;
+					TInt unpacked = bpe.Decompress((unsigned char*)dest, KPageSize, (TUint8*)pRomHdr + pi->iDataStart, pi->iDataSize, srcNext);
+					if (unpacked < 0)
+					{
+						if(iUseMemMap)
+						{
+							aImageMap->CloseMemoryMap(ETrue);
+							delete aImageMap;
+						}
+						else
+						{
+							delete [] aData;
+						}
+						Print(EError, "Corrupted BytePair compressed ROM image %s", iImgFileName.c_str());
+						return EFalse;
+					}
+					
+					dest += unpacked;
+				}
+				break;
+
+			default:
+				{
+					if(iUseMemMap)
+					{
+						aImageMap->CloseMemoryMap(ETrue);
+						delete aImageMap;
+					}
+					else
+					{
+						delete [] aData;
+					}
+					Print(EError, "Undefined compression type in %s", iImgFileName.c_str());
+					return EFalse;
+				}
+			}
+		}
+		
+		memcpy(aData, iData, sizeof(TRomLoaderHeader) + pRomHdr->iPageableRomStart);
+		if(iUseMemMap)
+		{
+			iImageMap->CloseMemoryMap(ETrue);
+			delete iImageMap;
+			iImageMap = aImageMap;
+		}
+		else
+		{
+			delete [] iData;
+		}
+		
+		iData = aData;
+		
+		//update the header fields...
+		if(!StoreImageHeader())
+		{
+			return EFalse;
+		}
+	}
+
+	if(CreateRootDirectory() != KErrNone)
+	{
+		return EFalse;
+	}
+
+	if(GetDirectoryStructures() != KErrNone)
+	{
+		return EFalse;
+	}
+
+	return ETrue;
+}
+
+TInt CoreRomImageReader::GetDirectoryStructures()
+{
+	int aDirs = 0;
+	TRomDir	*aRomDir = 0;
+
+	iRootDirList = (TRomRootDirectoryList*)ROM_PTR(iRomHdr->iRomRootDirectoryList);
+
+	while( aDirs < iRootDirList->iNumRootDirs )
+	{
+		aRomDir = (TRomDir*)ROM_PTR(iRootDirList->iRootDir[aDirs].iAddressLin);
+
+		if(BuildDir(aRomDir, iRootDirectory) != KErrNone)
+		{
+			return KErrNoMemory;
+		}
+		aDirs++;
+	}
+
+	return KErrNone;
+}
+
+
+TInt OffsetCompare(const void *a, const void *b)
+{
+	return ( *(TInt16*)a - *(TInt16*)b );
+}
+
+TInt CoreRomImageReader::BuildDir(TRomDir* aDir, TRomNode* aPaFSEntry)
+{
+	TInt16			*aFileCnt = 0;
+	TInt16			*aBase, aCount;
+	TInt16			*aSubDirCnt = 0;
+
+	//Sub directories in this directories
+	aSubDirCnt = (TInt16*)((char*)aDir + aDir->iSize + sizeof(aDir->iSize));
+
+	//Files within this directory
+	aFileCnt = aSubDirCnt+1;
+
+	aCount = (*aFileCnt + *aSubDirCnt);
+
+	aBase = aFileCnt+1;
+
+	qsort((void*)aBase, aCount, sizeof(TInt16), &OffsetCompare);
+
+	return BuildDir(aBase, aCount, aDir, aPaFSEntry);
+}
+
+TInt CoreRomImageReader::BuildDir(TInt16 *aOffsetTbl, TInt16 aOffsetTblCount, 
+								  TRomDir *aPaRomDir, TRomNode* aPaFSEntry)
+{
+	TRomNode		*aNewFSEntry;
+	TRomDir			*aNewDir;
+	TRomEntry		*aRomEntry;
+	TUint32			aOffsetFromBase;
+
+	string		aName;
+	//char	*aPtr;
+
+	while( aOffsetTblCount )
+	{
+		aOffsetFromBase = *aOffsetTbl;
+
+		aOffsetFromBase <<= 2;
+
+		aRomEntry = (TRomEntry*)((char*)aPaRomDir + sizeof(int) + aOffsetFromBase);
+		UTF16String unistr(reinterpret_cast<const TUint16*>(aRomEntry->iName),aRomEntry->iNameLength);
+		if(!unistr.ToUTF8(aName))
+			aName.assign(reinterpret_cast<const char*>(aRomEntry->iName),aRomEntry->iNameLength);
+
+		if( aRomEntry->iAtt & KEntryAttDir )
+		{
+			// add directory
+			aNewFSEntry = aPaFSEntry->NewSubDir(aName.c_str());
+			if(aRomEntry->iAtt & KEntryAttHidden)
+				aNewFSEntry->iHidden = ETrue;
+			else
+				aNewFSEntry->iHidden = EFalse;
+
+			aNewDir = (TRomDir*)ROM_PTR(aRomEntry->iAddressLin);
+			if(BuildDir(aNewDir, aNewFSEntry) != KErrNone)
+			{
+				return KErrNoMemory;
+			}
+		}
+		else
+		{
+			// add file
+			if(AddFile(aPaFSEntry, aName.c_str(), aRomEntry) != KErrNone)
+			{
+				return KErrNoMemory;
+			}
+		}
+
+		aOffsetTblCount--;
+		aOffsetTbl++;
+	}
+
+	return KErrNone;
+}
+
+TInt CoreRomImageReader::AddFile(TRomNode *aPa, const char* entryName, TRomEntry* aRomEntry)
+{
+	TRomImageHeader*	aImgHdr = 0;
+	TRomBuilderEntry*	aFile = 0;
+	TRomNode*			aNewFSEntry = 0;
+	static TRomNode*	aLastExecutable = GetRootDirectory();
+	TUint8				aUid1[4];
+
+	aImgHdr = (TRomImageHeader*)ROM_PTR(aRomEntry->iAddressLin);
+
+	aFile = new TRomBuilderEntry(0, entryName);
+
+	if(!aFile)
+	{
+		return KErrNoMemory;
+	}
+	size_t len = strlen(aFile->iName) + 1;	
+	aFile->iBareName = new char[len];
+	memcpy(aFile->iBareName,aFile->iName,len);
+	aFile->iUid1 = aImgHdr->iUid1;
+	aFile->iUid2 = aImgHdr->iUid2;
+	aFile->iUid3 = aImgHdr->iUid3;
+	aFile->iRomImageFlags = aImgHdr->iFlags;
+	aFile->iHardwareVariant = aImgHdr->iHardwareVariant;
+
+	memcpy(aUid1, &(aImgHdr->iUid1), 4);
+
+	aFile->iResource = !IsExecutable(aUid1);
+
+	aNewFSEntry = new TRomNode(entryName, aFile);
+	if(!aNewFSEntry)
+	{
+		return KErrNoMemory;
+	}
+
+	if(aRomEntry->iAtt & KEntryAttHidden)
+		aNewFSEntry->iHidden = ETrue;
+	else
+		aNewFSEntry->iHidden = EFalse;
+
+	// RomEntry Update
+	aNewFSEntry->iRomFile->SetRomEntry(aRomEntry);
+	aNewFSEntry->iRomFile->iFinal = ETrue;
+	
+	// E32 Image Pointer Update
+	aNewFSEntry->iRomFile->iAddresses.iImageAddr = aRomEntry->iAddressLin;
+	aNewFSEntry->iRomFile->iAddresses.iRunAddr = aRomEntry->iAddressLin;
+	aNewFSEntry->iRomFile->iAddresses.iSize = aRomEntry->iSize;
+	aNewFSEntry->iRomFile->iAddresses.iImagePtr = 0;
+	aNewFSEntry->iRomFile->iExportDir.iImagePtr = 0;
+
+	if(!aFile->iResource  && !aFile->HCRDataFile())
+	{
+		// Hardware Variant Update
+		aNewFSEntry->iRomFile->iHwvd = aImgHdr->iHardwareVariant;
+		// Security Info Update
+		aNewFSEntry->iRomFile->iRbEntry->iS = aImgHdr->iS;
+
+		// Export Table Update
+		aNewFSEntry->iRomFile->iExportDir.iSize = aImgHdr->iExportDirCount*4;
+		aNewFSEntry->iRomFile->iExportDir.iImageAddr = aImgHdr->iExportDir;
+		aNewFSEntry->iRomFile->iExportDir.iRunAddr = aImgHdr->iExportDir;
+
+		if(aImgHdr->iExportDirCount)
+		{
+			aNewFSEntry->iRomFile->iExportDir.iImagePtr = new char[aNewFSEntry->iRomFile->iExportDir.iSize];
+			memcpy(aNewFSEntry->iRomFile->iExportDir.iImagePtr,
+				   (TInt8*)ROM_PTR(aImgHdr->iExportDir), 
+				   aNewFSEntry->iRomFile->iExportDir.iSize);
+		}
+
+		// E32 Image pointer Update
+		aNewFSEntry->iRomFile->iAddresses.iImagePtr = new char[sizeof(TRomImageHeader)];
+		memcpy(aNewFSEntry->iRomFile->iAddresses.iImagePtr, aImgHdr, sizeof(TRomImageHeader));
+	}
+	else
+	{
+		aNewFSEntry->iRomFile->iHwvd = KVariantIndependent;
+	}
+
+	aPa->AddFile(aNewFSEntry);
+
+	if(aRomEntry->iAtt & KEntryAttXIP)
+	{
+		TRomNode::AddExecutableFile(aLastExecutable, aNewFSEntry);
+	}
+
+	return KErrNone;
+}
+
+ 
+
+TBool CoreRomImageReader::IsExecutable(TUint8* Uids1)
+{
+	//In the little-endian world
+	if( Uids1[3] == 0x10 &&
+		Uids1[2] == 0x0 &&
+		Uids1[1] == 0x0 )
+	{
+		if(Uids1[0] == 0x79 || Uids1[0] == 0x7a)
+			return ETrue;
+	}
+	return EFalse;
+}
+
+void CoreRomImageReader::DeleteAll(TRomNode *node)
+{
+	if(!node)
+		return;
+
+	if(node->iChild)
+	{
+		DeleteAll(node->iChild);
+	}
+
+	if(node->iSibling)
+	{
+		DeleteAll(node->iSibling);
+	}
+
+	if(node->iRomFile)
+	{
+		if(!node->iRomFile->iDir)
+		{
+			if(node->iRomFile->iExportDir.iImagePtr)
+			{
+				delete[] (char*)node->iRomFile->iExportDir.iImagePtr;
+				node->iRomFile->iExportDir.iImagePtr = 0;
+			}
+			if(node->iRomFile->iAddresses.iImagePtr)
+			{
+				delete[] (char*)node->iRomFile->iAddresses.iImagePtr;
+				node->iRomFile->iAddresses.iImagePtr = 0;
+			}
+
+			if(node->iRomFile->iRbEntry)
+			{
+				delete node->iRomFile->iRbEntry;
+				node->iRomFile->iRbEntry = 0;
+			}
+		}
+		delete node->iRomFile;
+		node->iRomFile = 0;
+	}
+	delete node;
+	node = 0;
+}
+
+
+void CoreRomImageReader::Display(TRomNode *node, TInt pad)
+{
+	if(!node)
+		return;
+
+	Print(ELog, "\n%*s%s", pad, " ", node->iBareName);
+
+	if(node->iChild)
+	{
+		pad += 2;
+		Display(node->iChild, pad);
+		pad -= 2;
+	}
+
+	if(node->iSibling)
+	{
+		Display(node->iSibling, pad);
+	}
+}
--- a/imgtools/romtools/rombuild/r_coreimagereader.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_coreimagereader.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,90 +1,88 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifndef __R_COREIMAGEREADER_H__
-#define __R_COREIMAGEREADER_H__
-
-class TRomNode;
-class TRomLoaderHeader;
-class Memmap;
-
-/** 
-class CoreRomImageReader
-
-@internalComponent
-@released
-*/
-class CoreRomImageReader
-{
-private:
-
-	String iImgFileName;
-
-	TUint8* iData;
-
-	// Core ROM Image Headers
-	TRomLoaderHeader	*iLoaderHdr;
-	TRomHeader			*iRomHdr;
-	TRomRootDirectoryList	*iRootDirList;
-
-	// Directory Structure
-	TRomNode* iRootDirectory;
-
-	TBool IsCoreROM();
-	TBool StoreImageHeader();
-	TInt GetDirectoryStructures();
-	TInt BuildDir(TRomDir* aDir, TRomNode* aPaFSEntry);
-	TInt BuildDir(TInt16 *aOffsetTbl, TInt16 aOffsetTblCount, TRomDir *aPaRomDir, TRomNode* aPaFSEntry);
-	TInt CreateRootDirectory();
-	TInt AddFile(TRomNode *aPa, char *entryName, TRomEntry* aRomEntry);
-	void Name(String& aName, char * aUnicodeName, int aLen);
-	TBool IsExecutable(TUint8* Uids1);
-	TUint GetHdrSize();
-
-	TBool iUseMemMap;
-	Memmap* iImageMap;
-
-	TBool AllocateImageMap(Memmap*& aImageMap, TUint8*& aData, TUint aLen);
-public:
-
-	CoreRomImageReader(String aFileName, TBool aUseMemMap = EFalse);
-	~CoreRomImageReader();
-
-	TBool OpenImage();
-	TBool ProcessImage();
-
-	TRomNode* GetRootDirectory()
-	{ 
-		return iRootDirectory; 
-	}
-
-	TRomHeader* GetCoreRomHeader()
-	{
-		return iRomHdr;
-	}
-	TRomRootDirectoryList* GetRootDirList()
-	{
-		return iRootDirList;
-	}
-
-	void DeleteAll(TRomNode *node);
-	void Display(TRomNode *node, TInt pad = 1);
-	friend TInt OffsetCompare(const void *left, const void *right);
-};
-
-#endif //__R_COREIMAGEREADER_H__
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifndef __R_COREIMAGEREADER_H__
+#define __R_COREIMAGEREADER_H__
+
+class TRomNode;
+class TRomLoaderHeader;
+class Memmap;
+
+/** 
+class CoreRomImageReader
+
+@internalComponent
+@released
+*/
+class CoreRomImageReader
+{
+private:
+
+	string iImgFileName;
+
+	TUint8* iData;
+
+	// Core ROM Image Headers
+	TRomLoaderHeader	*iLoaderHdr;
+	TRomHeader			*iRomHdr;
+	TRomRootDirectoryList	*iRootDirList;
+
+	// Directory Structure
+	TRomNode* iRootDirectory;
+
+	TBool IsCoreROM();
+	TBool StoreImageHeader();
+	TInt GetDirectoryStructures();
+	TInt BuildDir(TRomDir* aDir, TRomNode* aPaFSEntry);
+	TInt BuildDir(TInt16 *aOffsetTbl, TInt16 aOffsetTblCount, TRomDir *aPaRomDir, TRomNode* aPaFSEntry);
+	TInt CreateRootDirectory();
+	TInt AddFile(TRomNode *aPa, const char* entryName, TRomEntry* aRomEntry); 
+	TBool IsExecutable(TUint8* Uids1);
+	TUint GetHdrSize();
+	TBool iUseMemMap;
+	Memmap* iImageMap;
+
+	TBool AllocateImageMap(Memmap*& aImageMap, TUint8*& aData, TUint aLen);
+public:
+
+	CoreRomImageReader(const char* aFileName, TBool aUseMemMap = EFalse);
+	~CoreRomImageReader();
+
+	TBool OpenImage();
+	TBool ProcessImage();
+
+	TRomNode* GetRootDirectory()
+	{ 
+		return iRootDirectory; 
+	}
+
+	TRomHeader* GetCoreRomHeader()
+	{
+		return iRomHdr;
+	}
+	TRomRootDirectoryList* GetRootDirList()
+	{
+		return iRootDirList;
+	}
+
+	void DeleteAll(TRomNode *node);
+	void Display(TRomNode *node, TInt pad = 1);
+	friend TInt OffsetCompare(const void *left, const void *right);
+};
+
+#endif //__R_COREIMAGEREADER_H__
--- a/imgtools/romtools/rombuild/r_dir.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_dir.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,807 +1,818 @@
-/*
-* Copyright (c) 1998-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* e32tools/rombuild/r_dir.cpp
-*
-*/
-
-
-#include <stdlib.h>
-#include <string.h>
-#include "r_dir.h"
-#include "r_obey.h"
-#include "r_rom.h"
-#include "r_global.h"
-
-// Generalised set handling
-
-// class SetMember
-TInt SetMember::TotalInSystem=0;
-
-SetMember::~SetMember()
-	{
-	TotalInSystem--;
-	TRACE(TDIR,Print(EAlways,"SetMember %08x Destruct Remaining=%d\n",this,TotalInSystem));
-	}
-
-void SetMember::Close()
-	{
-	delete this;
-	}
-
-// class FiniteSet
-FiniteSet::FiniteSet(TInt aMaxCount)
-	: SetMember(EFiniteSetType), iMaxCount(aMaxCount), iCount(0), iMembers(NULL)
-	{}
-
-FiniteSet::FiniteSet(const FiniteSet& aSet)
-	: SetMember(aSet), iMaxCount(aSet.iMaxCount), iCount(0), iMembers(NULL)
-	{}
-
-FiniteSet* FiniteSet::New(TInt aMaxCount)
-	{
-	FiniteSet* pS=new FiniteSet(aMaxCount);
-	if (pS)
-		pS=pS->Construct();
-	return pS;
-	}
-
-FiniteSet* FiniteSet::Construct()
-	{
-	SetMember** pM=new SetMember*[iMaxCount];
-	if (!pM)
-		{
-		delete this;
-		return NULL;
-		}
-	iMembers=pM;
-	TInt i;
-	for(i=0; i<iMaxCount; i++)
-		pM[i]=NULL;
-	return this;
-	}
-
-FiniteSet* FiniteSet::Singleton(TInt aMaxCount, const SetMember& aMember)
-	{
-	FiniteSet* pS=New(aMaxCount);
-	if (pS)
-		{
-		pS->iCount=1;
-		pS->iMembers[0]=(SetMember*)&aMember;
-		}
-	return pS;
-	}
-
-FiniteSet::~FiniteSet()
-	{
-	TRACE(TDIR,Print(EAlways,"FiniteSet %08x Destruct, iCount=%d\n",this,iCount));
-	TInt i;
-	for (i=0; i<iCount; i++)
-		iMembers[i]->Close();
-	delete[] iMembers;
-	}
-
-TInt FiniteSet::Find(const SetMember& aMember, TInt& anIndex) const
-	{
-	if (iCount==0)
-		{
-		anIndex=0;
-		return KErrNotFound;
-		}
-	TInt k=aMember.Compare(*iMembers[0]);
-	if (k==0)
-		{
-		anIndex=0;
-		return KErrNone;
-		}
-	if (k<0)
-		{
-		anIndex=0;
-		return KErrNotFound;
-		}
-	if (iCount==1)
-		{
-		anIndex=1;
-		return KErrNotFound;
-		}
-	TInt r=iCount-1;
-	k=aMember.Compare(*iMembers[r]);
-	if (k==0)
-		{
-		anIndex=r;
-		return KErrNone;
-		}
-	if (k>0)
-		{
-		anIndex=iCount;
-		return KErrNotFound;
-		}
-	if (iCount==2)
-		{
-		anIndex=1;
-		return KErrNotFound;
-		}
-	TInt l=0;
-	while(r-l>1)
-		{
-		TInt m=(l+r)>>1;
-		k=aMember.Compare(*iMembers[m]);
-		if (k==0)
-			{
-			anIndex=m;
-			return KErrNone;
-			}
-		if (k>0)
-			l=m;
-		else
-			r=m;
-		}
-	anIndex=r;
-	return KErrNotFound;
-	}
-
-TInt FiniteSet::Compare(const SetMember& aSetMember) const
-	{
-	TInt k=Type()-aSetMember.Type();
-	if (k!=0)
-		return k;
-	const FiniteSet& s=(const FiniteSet&)aSetMember;
-	TInt c=Min(iCount,s.iCount);
-	TInt i;
-	for(i=0; i<c; i++)
-		{
-		k=iMembers[i]->Compare(s[i]);
-		if (k!=0)
-			return k;
-		}
-	return (iCount-s.iCount);
-	}
-
-SetMember* FiniteSet::Copy() const
-	{
-	FiniteSet* pS=new FiniteSet(*this);
-	if (pS)
-		{
-		SetMember** pA=new SetMember*[iMaxCount];
-		if (!pA)
-			{
-			delete pS;
-			return NULL;
-			}
-		pS->iMembers=pA;
-		TInt i;
-		for(i=0; i<iCount; i++)
-			{
-			SetMember* pM=iMembers[i]->Copy();
-			if (!pM)
-				{
-				delete pS;
-				return NULL;
-				}
-			pA[i]=pM;
-			pS->iCount++;
-			}
-		}
-	return pS;
-	}
-
-TInt FiniteSet::Find(const SetMember& aMember) const
-	{
-	TInt i;
-	TInt r=Find(aMember,i);
-	if (r<0)
-		return r;
-	return i;
-	}
-
-TBool FiniteSet::SubsetOf(const FiniteSet& aSet) const
-	{
-	if (iCount>aSet.iCount)
-		return EFalse;
-	TInt i;
-	for(i=0; i<iCount; i++)
-		{
-		TInt j;
-		if (aSet.Find(*iMembers[i],j)!=KErrNone)
-			return EFalse;
-		}
-	return ETrue;
-	}
-
-TInt FiniteSet::Intersection(const FiniteSet& aSet)
-	{
-	if (iCount==0)
-		return KErrNotFound;
-	TInt i;
-	for(i=0; i<iCount; i++)
-		{
-		TInt j;
-		if (aSet.Find(*iMembers[i],j)!=KErrNone)
-			Detach(i)->Close();
-		}
-	return iCount ? KErrNone : KErrNotFound;
-	}
-
-TInt FiniteSet::Union(const FiniteSet& aSet)
-	{
-	TInt i;
-	for(i=0; i<aSet.iCount; i++)
-		{
-		const SetMember& m=*aSet.iMembers[i];
-		TInt j;
-		if (Find(m,j)!=KErrNone)
-			{
-			const SetMember* pC=m.Copy();
-			if (!pC)
-				return KErrNoMemory;
-			TInt r=Insert(*pC,j);
-			if (r!=KErrNone)
-				return r;
-			}
-		}
-	return iCount ? KErrNone : KErrNotFound;
-	}
-
-TInt FiniteSet::Difference(const FiniteSet& aSet)
-	{
-	if (iCount==0)
-		return KErrNotFound;
-	TInt i;
-	for(i=0; i<iCount; i++)
-		{
-		TInt j;
-		if (aSet.Find(*iMembers[i],j)==KErrNone)
-			Detach(i)->Close();
-		}
-	return iCount ? KErrNone : KErrNotFound;
-	}
-
-TInt FiniteSet::Add(const SetMember& aMember)
-	{
-	TInt i;
-	TInt r=Find(aMember,i);
-	if (r==KErrNotFound && Insert(aMember,i)==KErrOverflow)
-		return KErrOverflow;
-	return r;
-	}
-
-TInt FiniteSet::Remove(const SetMember& aMember)
-	{
-	TInt i;
-	TInt r=Find(aMember,i);
-	if (r==KErrNone)
-		Detach(i)->Close();
-	return r;
-	}
-
-SetMember* FiniteSet::Detach(TInt anIndex)
-	{
-	TInt i;
-	SetMember* pM=iMembers[anIndex];
-	for(i=anIndex; i<iCount-1; i++)
-		iMembers[i]=iMembers[i+1];
-	iCount--;
-	return pM;
-	}
-
-TInt FiniteSet::Insert(const SetMember& aMember, TInt anIndex)
-	{
-	if (iCount==iMaxCount)
-		return KErrOverflow;
-	TInt i;
-	for(i=iCount-1; i>=anIndex; i--)
-		iMembers[i+1]=iMembers[i];
-	iMembers[anIndex]=(SetMember*)&aMember;
-	iCount++;
-	return KErrNone;
-	}
-
-// ROMBUILD-specific stuff
-
-inline TLinAddr ActualToRomAddress(TAny* anAddr)
-	{ return TLinAddr(anAddr)-TheRomMem+TheRomLinearAddress; }
-
-// class TVariantList
-TInt TVariantList::NumVariants;
-THardwareVariant TVariantList::Variants[TVariantList::EMaxVariants];
-void TVariantList::Setup(CObeyFile* aObey)
-	{
-	NumVariants=aObey->iNumberOfVariants;
-	if (NumVariants>EMaxVariants)
-		Print(EError,"Too many variants");
-	TInt i;
-	for(i=0; i<NumVariants; i++)
-		{
-		Variants[i]=aObey->iVariants[i]->iHardwareVariant;
-		}
-	}
-
-TVariantList::TVariantList(THardwareVariant a)
-	{
-	iList=0;
-	TInt i;
-	for (i=0; i<NumVariants; i++)
-		{
-		if (Variants[i]<=a)
-			iList|=TUint(1<<i);
-		}
-	}
-
-THardwareVariant TVariantList::Lookup() const
-	{
-	TInt i;
-	for (i=0; i<NumVariants; i++)
-		{
-		if (iList & TUint(1<<i))
-			return Variants[i];
-		}
-	return THardwareVariant(0);
-	}
-
-void TVariantList::SetNumVariants(TInt aNumVariants)
-{
-	NumVariants = aNumVariants;
-	if (NumVariants>EMaxVariants)
-		Print(EError,"Too many variants");
-}
-
-void TVariantList::SetVariants(THardwareVariant* aVariants)
-{
-	TInt Index = NumVariants;
-	while(Index--)
-	{
-		Variants[Index] = aVariants[Index];
-	}
-}
-
-void DumpRomEntry(const TRomEntry& e)
-	{
-	char name[256];
-	char* d = name;
-	const wchar_t* s = (const wchar_t*)e.iName;
-	const wchar_t* sE = s + e.iNameLength;
-	for (; s<sE; *d++ = (char)*s++) {}
-	*d++ = 0;
-	Print(ELog, "RomEntry @ %08x: SZ=%08x A=%08x att=%02x name %s\n", &e, e.iSize, e.iAddressLin, e.iAtt, name);
-	}
-
-// class Entry
-TRomEntry* Entry::CreateRomEntry(char*& anAddr) const
-	{
-
-	TRomEntry *pE=(TRomEntry*)anAddr;
-	pE->iAtt=iRomNode->iAtt;
-	pE->iSize=iRomNode->iRomFile->iAddresses.iSize;
-	pE->iAddressLin=iRomNode->iRomFile->iAddresses.iRunAddr;
-	if (IsFile())
-		iRomNode->iRomFile->SetRomEntry(pE);
-	pE->iName[0]=0;
-	pE->iName[1]=0;
-	TInt nl=iRomNode->NameCpy((char*)pE->iName);
-	pE->iNameLength=(TUint8)nl;
-	if (Unicode)
-		nl<<=1;
-	anAddr+=Align4(KRomEntrySize+nl);
-	TRACE(TDIR,DumpRomEntry(*pE));
-	return pE;
-	}
-
-const TText* Entry::Name() const
-	{
-	return iRomNode->iName;
-	}
-
-// class FileEntry
-FileEntry::FileEntry(const FileEntry& aFileEntry)
-	: Entry(aFileEntry)
-	{
-	iVariants=aFileEntry.iVariants;
-	iRomNode=aFileEntry.iRomNode;
-	}
-
-FileEntry* FileEntry::New(TRomNode* aFile)
-	{
-	FileEntry* pE=new FileEntry();
-	if (pE)
-		{
-		pE->iRomNode=aFile;
-		pE->iVariants=TVariantList(aFile->HardwareVariant());
-		}
-	return pE;
-	}
-
-TInt FileEntry::Compare(const SetMember& aMember) const
-	{
-	TInt k=Type()-aMember.Type();
-	if (k!=0)
-		return k;
-	FileEntry *entry=(FileEntry *)&aMember;
-	return (iRomNode->iIdentifier-entry->iRomNode->iIdentifier);
-	}
-
-SetMember* FileEntry::Copy() const
-	{
-	return new FileEntry(*this);
-	}
-
-FileEntry::~FileEntry()
-	{
-	}
-
-// class DirEntry
-DirEntry::DirEntry(const DirEntry& aDirEntry)
-	: Entry(aDirEntry)
-	{
-	iVariants=aDirEntry.iVariants;
-	iRomNode=aDirEntry.iRomNode;
-	iDir=aDirEntry.iDir;
-	}
-
-DirEntry* DirEntry::New(TRomNode* aFile, Directory* aDir)
-	{
-	DirEntry* pE=new DirEntry();
-	if (pE)
-		{
-		pE->iRomNode=aFile;
-		pE->iVariants=aDir->iVariants;
-		pE->iDir=aDir;
-		if (aDir)
-			aDir->Open();
-		}
-	return pE;
-	}
-
-TInt DirEntry::Compare(const SetMember& aMember) const
-	{
-	TInt k=Type()-aMember.Type();
-	if (k!=0)
-		return k;
-	DirEntry *entry=(DirEntry *)&aMember;
-	return (iDir->iIdentifier - entry->iDir->iIdentifier);
-	}
-
-SetMember* DirEntry::Copy() const
-	{
-	DirEntry* pE=new DirEntry(*this);
-	if (pE && pE->iDir)
-		pE->iDir->Open();
-	return pE;
-	}
-
-DirEntry::~DirEntry()
-	{
-	if (iDir)
-		iDir->Close();
-	}
-
-// data structure and function for qsort
-struct SortableEntry 
-	{
-	unsigned int iOffset;
-	Entry* iEntry;
-	};
-
-int compare(const void* left, const void* right)
-	{
-	const SortableEntry* le  = (const SortableEntry*)left;
-	const SortableEntry* re = (const SortableEntry*)right;
-	if (le->iEntry->IsDir())
-		{
-		if (!re->iEntry->IsDir())
-			return -1;	// dir < file
-		}
-	else
-		{
-		if (re->iEntry->IsDir())
-			return +1;	// file > dir
-		}
-	// Both the same type of entry, sort by name.
-	// Sorting the 8-bit data using ASCII folding matches the sort order in terms of 16 bit
-	// characters provided that 8-bit data is actually CESU-8 rather than UTF-8. The two
-	// formats differ only when using surrogates (ie unicode values >= 0x10000). UTF-8 encodes
-	// an entire 32 bit value as a sequence of up to 6 bytes whereas CESU-8 encodes UTF-16
-	// values independently.
-	const char* l = (const char*)le->iEntry->Name();
-	const char* r = (const char*)re->iEntry->Name();
-	int result, lc, rc;
-	do	{
-		lc = *l++;
-		rc = *r++;
-		if (lc >= 'A' && lc <= 'Z')
-			lc += ('a' - 'A');
-		if (rc >= 'A' && rc <= 'Z')
-			rc += ('a' - 'A');
-		result = lc - rc;
-		} while (lc && result==0);
-	return result;
-	}
-
-
-TRomDir* DirEntry::CreateRomEntries(char*& anAddr) const
-	{
-	TInt i;
-	TInt count=iDir->Count();
-	TInt subdircount=0;
-	for(i=0; i<count; i++)
-		{
-		Entry* pE=(Entry*)&(*iDir)[i];
-		if (pE->IsDir())
-			{
-			subdircount++;
-			// Recursively build & place the subdirectories
-			DirEntry *pD=(DirEntry*)pE;
-			TRomDir *pR=pD->iDir->iRomDir;
-			if (!pR)
-				{
-				pR=pD->CreateRomEntries(anAddr);
-				pD->iDir->iRomDir=pR;
-				}
-			}
-		}
-	// Now place & build the TRomDir for this directory
-	TInt *pS=(TInt*)anAddr;
-	iDir->iRomDir=(TRomDir*)anAddr;
-	*pS=0;
-	anAddr+=sizeof(TInt);
-
-	char* offsetbase=anAddr;
-	SortableEntry* array=new SortableEntry [count];
-	if (array==0)
-		{
-		Print(EError,"Failed to allocate array of SortableEntry\n");
-		exit(-1);
-		}
-
-	for(i=0; i<count; i++)
-		{
-		Entry* pE=(Entry*)&(*iDir)[i];
-		array[i].iOffset=anAddr-offsetbase;
-		array[i].iEntry=pE;
-		TRomEntry *pR=pE->CreateRomEntry(anAddr);
-		if (pE->IsDir())
-			{
-			TRomDir *pD=((DirEntry*)pE)->iDir->iRomDir;
-			if (pD)
-				pR->iAddressLin=ActualToRomAddress(pD);
-			else
-				Print(EError,"Failed to fix up subdirectory address\n");
-			}
-		}
-	*pS=TInt(anAddr-(char*)pS-sizeof(TInt));
-
-	// Emit table of offsets for the subdirs and files in sorted order
-	if (gSortedRomFs)
-		{
-	TInt filecount=count-subdircount;
-	if (filecount>65535 || subdircount>65535)
-		{
-		Print(EError,"Too many files or subdirectories\n");
-		exit(-1);
-		}
-	TUint16* ptr=(TUint16*)anAddr;
-	*ptr++=(TUint16)subdircount;
-	*ptr++=(TUint16)filecount;
-	qsort(array,count,sizeof(SortableEntry),&compare);
-	for (i=0; i<count; i++)
-		{
-		unsigned int scaledOffset = array[i].iOffset>>2;
-		if ((array[i].iOffset & 3) != 0 || scaledOffset > 65535)
-			Print(EError, "Bad offset into directory\n");
-		*ptr++ = (TUint16)scaledOffset;
-		}
-	anAddr=(char*)ALIGN4((int)ptr);
-		}
-	delete [] array;
-	return (TRomDir*)pS;
-	}
-
-// class Directory
-TInt Directory::DirectoryCount=0;
-Directory::Directory(TInt aMaxCount)
-	: FiniteSet(aMaxCount), iRomDir(NULL), iAccessCount(1)
-	{
-	iIdentifier=Directory::DirectoryCount++;
-	}
-
-Directory* Directory::New(TInt aMaxCount, TVariantList aList)
-	{
-	Directory *pD=new Directory(aMaxCount);
-	if (pD)
-		{
-		pD->iVariants=aList;
-		pD=(Directory*)pD->Construct();
-		}
-	return pD;
-	}
-
-Directory::~Directory()
-	{
-	TRACE(TDIR,Print(EAlways,"Directory %08x Destruct\n",this));
-	}
-
-void Directory::Open()
-	{
-	iAccessCount++;
-	TRACE(TDIR,Print(EAlways,"Directory %08x Open() access count=%d\n",this,iAccessCount));
-	}
-
-void Directory::Close()
-	{
-	TRACE(TDIR,Print(EAlways,"Directory %08x Close() access count=%d\n",this,iAccessCount));
-	if (--iAccessCount==0)
-		delete this;
-	}
-
-TInt Directory::Compile(const FiniteSet& aSet)
-	{
-	TInt i;
-	TInt count=aSet.Count();
-	for(i=0; i<count; i++)
-		{
-		Entry *pE=(Entry*)&aSet[i];
-		if (iVariants<=pE->Variants())
-			{
-			Entry *pN=(Entry*)pE->Copy();
-			if (!pN)
-				return KErrNoMemory;
-			pN->Restrict(iVariants);
-			TInt r=Add(*pN);
-			if (r==KErrOverflow)
-				return r;
-			}
-		}
-	return KErrNone;
-	}
-
-TInt Directory::Merge(const Directory& aDir)
-	{
-	TInt i;
-	TInt r=Find(aDir,i);
-	if (r==KErrNone)
-		{
-		((Directory*)iMembers[i])->iVariants.Union(aDir.iVariants);
-		return KErrAlreadyExists;
-		}
-	else if (Insert(aDir,i)==KErrOverflow)
-		return KErrOverflow;
-	return KErrNone;
-	}
-
-// class RomFileStructure
-RomFileStructure::RomFileStructure(TInt aMaxCount)
-	: FiniteSet(aMaxCount)
-	{}
-
-RomFileStructure::~RomFileStructure()
-	{
-	}
-
-RomFileStructure* RomFileStructure::New(TInt aMaxCount)
-	{
-	RomFileStructure* pS=new RomFileStructure(aMaxCount);
-	if (pS)
-		pS=(RomFileStructure*)pS->Construct();
-	return pS;
-	}
-
-void RomFileStructure::Destroy()
-	{
-	}
-
-TInt RomFileStructure::ProcessDirectory(TRomNode* aDir)
-	{
-	TRACE(TSCRATCH, Print(EAlways, "ProcessDirectory (%08x) %s\n",aDir,aDir->iName));
-	TRACE(TDIR,Print(EAlways,"ProcessDirectory %s\nInitial:\n",aDir->iName));
-	TRACE(TDIR,DebugPrint());
-	TInt dirs=0;
-	TInt files=0;
-	aDir->CountDirectory(files,dirs);
-	TInt maxSize=files+dirs*TVariantList::NumVariants;
-	TRACE(TDIR,Print(EAlways,"files=%d dirs=%d maxSize=%d\n",files,dirs,maxSize));
-	RomFileStructure* pS=New(maxSize);
-	if (!pS)
-		return KErrNoMemory;
-	TInt r=aDir->ProcessDirectory(pS);
-	TRACE(TDIR,Print(EAlways,"FileList:\n"));
-	TRACE(TDIR,pS->DebugPrint());
-	Directory* dir[TVariantList::EMaxVariants];
-	TInt v;
-	for(v=0; v<TVariantList::NumVariants; v++)
-		{
-		TVariantList vList(v);
-		Directory *pD=Directory::New(files+dirs,vList);
-		if (!pD)
-			return KErrNoMemory;
-		dir[v]=pD;
-		r=pD->Compile(*pS);
-		if (r!=KErrNone)
-			return r;
-		TRACE(TDIR,Print(EAlways,"Variant %d Directory:\n",v));
-		TRACE(TDIR,pD->DebugPrint());
-		}
-	pS->Close();
-	Directory *pX=Directory::New(TVariantList::NumVariants,TVariantList());
-	if (!pX)
-		return KErrNoMemory;
-	for(v=0; v<TVariantList::NumVariants; v++)
-		{
-		if (dir[v]->Empty())
-			r=KErrAlreadyExists;
-		else
-			r=pX->Merge(*dir[v]);
-		if (r==KErrAlreadyExists)
-			{
-			dir[v]->Close();
-			dir[v]=NULL;
-			}
-		else if (r!=KErrNone)
-			return r;
-		}
-	TRACE(TDIR,Print(EAlways,"Final Directories:\n",v));
-	TRACE(TDIR,pX->DebugPrint());
-	TInt count=pX->Count();
-	TInt i;
-	for(i=0; i<count; i++)
-		{
-		Directory* pD=(Directory*)&(*pX)[i];
-		DirEntry* pE=DirEntry::New(aDir,pD);
-		if (!pE)
-			return KErrNoMemory;
-		r=Add(*pE);	// accumulate into the caller
-		if (r==KErrOverflow)
-			return r;
-		}
-	pX->Close();
-	return KErrNone;
-	}
-
-
-// DEBUG
-
-void FileEntry::DebugPrint() const
-	{
-	Print(EAlways,"FileEntry %08x %08x %s\n",iRomNode,iVariants.Mask(),iRomNode->iName);
-	}
-
-void DirEntry::DebugPrint() const
-	{
-	Print(EAlways,"DirEntry %08x %08x %08x %s\n",iRomNode,iVariants.Mask(),iDir,iRomNode->iName);
-	}
-
-void FiniteSet::DebugPrint() const
-	{
-	if (Count()==0)
-		Print(EAlways,"FiniteSet 0\n");
-	else
-		{
-		Print(EAlways,"FiniteSet %d {\n",Count());
-		TInt i;
-		for (i=0; i<Count(); i++)
-			{
-			iMembers[i]->DebugPrint();
-			}
-		Print(EAlways,"}\n");
-		}
-	}
-
-void Directory::DebugPrint() const
-	{
-	Print(EAlways,"Directory %08x %08x\n",iVariants.Mask(),iRomDir);
-	FiniteSet::DebugPrint();
-	}
-
-
-
-
-
+/*
+* Copyright (c) 1998-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* e32tools/rombuild/r_dir.cpp
+*
+*/
+
+
+#include <stdlib.h>
+#include <string.h>
+#include "r_dir.h"
+#include "r_obey.h"
+#include "r_rom.h"
+#include "r_global.h"
+#include "utf16string.h"
+
+// Generalised set handling
+
+// class SetMember
+TInt SetMember::TotalInSystem=0;
+
+SetMember::~SetMember()
+	{
+	TotalInSystem--;
+	TRACE(TDIR,Print(EAlways,"SetMember %08x Destruct Remaining=%d\n",this,TotalInSystem));
+	}
+
+void SetMember::Close()
+	{
+	delete this;
+	}
+
+// class FiniteSet
+FiniteSet::FiniteSet(TInt aMaxCount)
+	: SetMember(EFiniteSetType), iMaxCount(aMaxCount), iCount(0), iMembers(NULL)
+	{}
+
+FiniteSet::FiniteSet(const FiniteSet& aSet)
+	: SetMember(aSet), iMaxCount(aSet.iMaxCount), iCount(0), iMembers(NULL)
+	{}
+
+FiniteSet* FiniteSet::New(TInt aMaxCount)
+	{
+	FiniteSet* pS=new FiniteSet(aMaxCount);
+	if (pS)
+		pS=pS->Construct();
+	return pS;
+	}
+
+FiniteSet* FiniteSet::Construct()
+	{
+	SetMember** pM=new SetMember*[iMaxCount];
+	if (!pM)
+		{
+		delete this;
+		return NULL;
+		}
+	iMembers=pM;
+	TInt i;
+	for(i=0; i<iMaxCount; i++)
+		pM[i]=NULL;
+	return this;
+	}
+
+FiniteSet* FiniteSet::Singleton(TInt aMaxCount, const SetMember& aMember)
+	{
+	FiniteSet* pS=New(aMaxCount);
+	if (pS)
+		{
+		pS->iCount=1;
+		pS->iMembers[0]=(SetMember*)&aMember;
+		}
+	return pS;
+	}
+
+FiniteSet::~FiniteSet()
+	{
+	TRACE(TDIR,Print(EAlways,"FiniteSet %08x Destruct, iCount=%d\n",this,iCount));
+	TInt i;
+	for (i=0; i<iCount; i++)
+		iMembers[i]->Close();
+	if(iMembers)
+		delete[] iMembers;
+	}
+
+TInt FiniteSet::Find(const SetMember& aMember, TInt& anIndex) const
+	{
+	if (iCount==0)
+		{
+		anIndex=0;
+		return KErrNotFound;
+		}
+	TInt k=aMember.Compare(*iMembers[0]);
+	if (k==0)
+		{
+		anIndex=0;
+		return KErrNone;
+		}
+	if (k<0)
+		{
+		anIndex=0;
+		return KErrNotFound;
+		}
+	if (iCount==1)
+		{
+		anIndex=1;
+		return KErrNotFound;
+		}
+	TInt r=iCount-1;
+	k=aMember.Compare(*iMembers[r]);
+	if (k==0)
+		{
+		anIndex=r;
+		return KErrNone;
+		}
+	if (k>0)
+		{
+		anIndex=iCount;
+		return KErrNotFound;
+		}
+	if (iCount==2)
+		{
+		anIndex=1;
+		return KErrNotFound;
+		}
+	TInt l=0;
+	while(r-l>1)
+		{
+		TInt m=(l+r)>>1;
+		k=aMember.Compare(*iMembers[m]);
+		if (k==0)
+			{
+			anIndex=m;
+			return KErrNone;
+			}
+		if (k>0)
+			l=m;
+		else
+			r=m;
+		}
+	anIndex=r;
+	return KErrNotFound;
+	}
+
+TInt FiniteSet::Compare(const SetMember& aSetMember) const
+	{
+	TInt k=Type()-aSetMember.Type();
+	if (k!=0)
+		return k;
+	const FiniteSet& s=(const FiniteSet&)aSetMember;
+	TInt c=Min(iCount,s.iCount);
+	TInt i;
+	for(i=0; i<c; i++)
+		{
+		k=iMembers[i]->Compare(s[i]);
+		if (k!=0)
+			return k;
+		}
+	return (iCount-s.iCount);
+	}
+
+SetMember* FiniteSet::Copy() const
+	{
+	FiniteSet* pS=new FiniteSet(*this);
+	if (pS)
+		{
+		SetMember** pA=new SetMember*[iMaxCount];
+		if (!pA)
+			{
+			delete pS;
+			return NULL;
+			}
+		pS->iMembers=pA;
+		TInt i;
+		for(i=0; i<iCount; i++)
+			{
+			SetMember* pM=iMembers[i]->Copy();
+			if (!pM)
+				{
+				delete pS;
+				return NULL;
+				}
+			pA[i]=pM;
+			pS->iCount++;
+			}
+		}
+	return pS;
+	}
+
+TInt FiniteSet::Find(const SetMember& aMember) const
+	{
+	TInt i;
+	TInt r=Find(aMember,i);
+	if (r<0)
+		return r;
+	return i;
+	}
+
+TBool FiniteSet::SubsetOf(const FiniteSet& aSet) const
+	{
+	if (iCount>aSet.iCount)
+		return EFalse;
+	TInt i;
+	for(i=0; i<iCount; i++)
+		{
+		TInt j;
+		if (aSet.Find(*iMembers[i],j)!=KErrNone)
+			return EFalse;
+		}
+	return ETrue;
+	}
+
+TInt FiniteSet::Intersection(const FiniteSet& aSet)
+	{
+	if (iCount==0)
+		return KErrNotFound;
+	TInt i;
+	for(i=0; i<iCount; i++)
+		{
+		TInt j;
+		if (aSet.Find(*iMembers[i],j)!=KErrNone)
+			Detach(i)->Close();
+		}
+	return iCount ? KErrNone : KErrNotFound;
+	}
+
+TInt FiniteSet::Union(const FiniteSet& aSet)
+	{
+	TInt i;
+	for(i=0; i<aSet.iCount; i++)
+		{
+		const SetMember& m=*aSet.iMembers[i];
+		TInt j;
+		if (Find(m,j)!=KErrNone)
+			{
+			const SetMember* pC=m.Copy();
+			if (!pC)
+				return KErrNoMemory;
+			TInt r=Insert(*pC,j);
+			if (r!=KErrNone)
+				return r;
+			}
+		}
+	return iCount ? KErrNone : KErrNotFound;
+	}
+
+TInt FiniteSet::Difference(const FiniteSet& aSet)
+	{
+	if (iCount==0)
+		return KErrNotFound;
+	TInt i;
+	for(i=0; i<iCount; i++)
+		{
+		TInt j;
+		if (aSet.Find(*iMembers[i],j)==KErrNone)
+			Detach(i)->Close();
+		}
+	return iCount ? KErrNone : KErrNotFound;
+	}
+
+TInt FiniteSet::Add(const SetMember& aMember)
+	{
+	TInt i;
+	TInt r=Find(aMember,i);
+	if (r==KErrNotFound && Insert(aMember,i)==KErrOverflow)
+		return KErrOverflow;
+	return r;
+	}
+
+TInt FiniteSet::Remove(const SetMember& aMember)
+	{
+	TInt i;
+	TInt r=Find(aMember,i);
+	if (r==KErrNone)
+		Detach(i)->Close();
+	return r;
+	}
+
+SetMember* FiniteSet::Detach(TInt anIndex)
+	{
+	TInt i;
+	SetMember* pM=iMembers[anIndex];
+	for(i=anIndex; i<iCount-1; i++)
+		iMembers[i]=iMembers[i+1];
+	iCount--;
+	return pM;
+	}
+
+TInt FiniteSet::Insert(const SetMember& aMember, TInt anIndex)
+	{
+	if (iCount==iMaxCount)
+		return KErrOverflow;
+	TInt i;
+	for(i=iCount-1; i>=anIndex; i--)
+		iMembers[i+1]=iMembers[i];
+	iMembers[anIndex]=(SetMember*)&aMember;
+	iCount++;
+	return KErrNone;
+	}
+
+// ROMBUILD-specific stuff
+
+inline TLinAddr ActualToRomAddress(TAny* anAddr)
+	{ return TLinAddr(anAddr)-TheRomMem+TheRomLinearAddress; }
+
+// class TVariantList
+TInt TVariantList::NumVariants;
+THardwareVariant TVariantList::Variants[TVariantList::EMaxVariants];
+void TVariantList::Setup(CObeyFile* aObey)
+	{
+	NumVariants=aObey->iNumberOfVariants;
+	if (NumVariants>EMaxVariants)
+		Print(EError,"Too many variants");
+	TInt i;
+	for(i=0; i<NumVariants; i++)
+		{
+		Variants[i]=aObey->iVariants[i]->iHardwareVariant;
+		}
+	}
+
+TVariantList::TVariantList(THardwareVariant a)
+	{
+	iList=0;
+	TInt i;
+	for (i=0; i<NumVariants; i++)
+		{
+		if (Variants[i]<=a)
+			iList|=TUint(1<<i);
+		}
+	}
+
+THardwareVariant TVariantList::Lookup() const
+	{
+	TInt i;
+	for (i=0; i<NumVariants; i++)
+		{
+		if (iList & TUint(1<<i))
+			return Variants[i];
+		}
+	return THardwareVariant(0);
+	}
+
+void TVariantList::SetNumVariants(TInt aNumVariants)
+{
+	NumVariants = aNumVariants;
+	if (NumVariants>EMaxVariants)
+		Print(EError,"Too many variants");
+}
+
+void TVariantList::SetVariants(THardwareVariant* aVariants)
+{
+	TInt Index = NumVariants;
+	while(Index--)
+	{
+		Variants[Index] = aVariants[Index];
+	}
+}
+
+void DumpRomEntry(const TRomEntry& e)
+	{
+	char name[256];
+	char* d = name;
+	const wchar_t* s = (const wchar_t*)e.iName;
+	const wchar_t* sE = s + e.iNameLength;
+	for (; s<sE; *d++ = (char)*s++) {}
+	*d++ = 0;
+	Print(ELog, "RomEntry @ %08x: SZ=%08x A=%08x att=%02x name %s\n", &e, e.iSize, e.iAddressLin, e.iAtt, name);
+	}
+
+// class Entry
+TRomEntry* Entry::CreateRomEntry(char*& anAddr) const
+	{
+
+	TRomEntry *pE=(TRomEntry*)anAddr;
+	pE->iAtt=iRomNode->iAtt;
+	pE->iSize=iRomNode->iRomFile->iAddresses.iSize;
+	pE->iAddressLin=iRomNode->iRomFile->iAddresses.iRunAddr;
+	if (IsFile())
+		iRomNode->iRomFile->SetRomEntry(pE);
+	pE->iName[0]=0;
+	pE->iName[1]=0;
+	int nameLen = strlen(iRomNode->iName);
+	if(Unicode){
+		UTF16String unistr(iRomNode->iName,nameLen);
+		pE->iNameLength = unistr.length();
+		memcpy(pE->iName,unistr.c_str(),unistr.bytes());
+		anAddr+=Align4(KRomEntrySize + unistr.bytes());
+	}
+	else{
+		memcpy(pE->iName,iRomNode->iName,nameLen);
+		anAddr+=Align4(KRomEntrySize + nameLen);
+		pE->iNameLength = nameLen ;
+	}
+ 
+	
+	TRACE(TDIR,DumpRomEntry(*pE));
+	return pE;
+	}
+
+const char* Entry::Name() const
+	{
+	return iRomNode->iName;
+	}
+
+// class FileEntry
+FileEntry::FileEntry(const FileEntry& aFileEntry)
+	: Entry(aFileEntry)
+	{
+	iVariants=aFileEntry.iVariants;
+	iRomNode=aFileEntry.iRomNode;
+	}
+
+FileEntry* FileEntry::New(TRomNode* aFile)
+	{
+	FileEntry* pE=new FileEntry();
+	if (pE)
+		{
+		pE->iRomNode=aFile;
+		pE->iVariants=TVariantList(aFile->HardwareVariant());
+		}
+	return pE;
+	}
+
+TInt FileEntry::Compare(const SetMember& aMember) const
+	{
+	TInt k=Type()-aMember.Type();
+	if (k!=0)
+		return k;
+	FileEntry *entry=(FileEntry *)&aMember;
+	return (iRomNode->iIdentifier-entry->iRomNode->iIdentifier);
+	}
+
+SetMember* FileEntry::Copy() const
+	{
+	return new FileEntry(*this);
+	}
+
+FileEntry::~FileEntry()
+	{
+	}
+
+// class DirEntry
+DirEntry::DirEntry(const DirEntry& aDirEntry)
+	: Entry(aDirEntry)
+	{
+	iVariants=aDirEntry.iVariants;
+	iRomNode=aDirEntry.iRomNode;
+	iDir=aDirEntry.iDir;
+	}
+
+DirEntry* DirEntry::New(TRomNode* aFile, Directory* aDir)
+	{
+	DirEntry* pE=new DirEntry();
+	if (pE)
+		{
+		pE->iRomNode=aFile;
+		pE->iVariants=aDir->iVariants;
+		pE->iDir=aDir;
+		if (aDir)
+			aDir->Open();
+		}
+	return pE;
+	}
+
+TInt DirEntry::Compare(const SetMember& aMember) const
+	{
+	TInt k=Type()-aMember.Type();
+	if (k!=0)
+		return k;
+	DirEntry *entry=(DirEntry *)&aMember;
+	return (iDir->iIdentifier - entry->iDir->iIdentifier);
+	}
+
+SetMember* DirEntry::Copy() const
+	{
+	DirEntry* pE=new DirEntry(*this);
+	if (pE && pE->iDir)
+		pE->iDir->Open();
+	return pE;
+	}
+
+DirEntry::~DirEntry()
+	{
+	if (iDir)
+		iDir->Close();
+	}
+
+// data structure and function for qsort
+struct SortableEntry 
+	{
+	unsigned int iOffset;
+	Entry* iEntry;
+	};
+
+int compare(const void* left, const void* right)
+	{
+	const SortableEntry* le  = (const SortableEntry*)left;
+	const SortableEntry* re = (const SortableEntry*)right;
+	if (le->iEntry->IsDir())
+		{
+		if (!re->iEntry->IsDir())
+			return -1;	// dir < file
+		}
+	else
+		{
+		if (re->iEntry->IsDir())
+			return +1;	// file > dir
+		}
+	// Both the same type of entry, sort by name.
+	// Sorting the 8-bit data using ASCII folding matches the sort order in terms of 16 bit
+	// characters provided that 8-bit data is actually CESU-8 rather than UTF-8. The two
+	// formats differ only when using surrogates (ie unicode values >= 0x10000). UTF-8 encodes
+	// an entire 32 bit value as a sequence of up to 6 bytes whereas CESU-8 encodes UTF-16
+	// values independently.
+	const char* l = (const char*)le->iEntry->Name();
+	const char* r = (const char*)re->iEntry->Name();
+	int result, lc, rc;
+	do	{
+		lc = *l++;
+		rc = *r++;
+		if (lc >= 'A' && lc <= 'Z')
+			lc += ('a' - 'A');
+		if (rc >= 'A' && rc <= 'Z')
+			rc += ('a' - 'A');
+		result = lc - rc;
+		} while (lc && result==0);
+	return result;
+	}
+
+
+TRomDir* DirEntry::CreateRomEntries(char*& anAddr) const
+	{
+	TInt i;
+	TInt count=iDir->Count();
+	TInt subdircount=0;
+	for(i=0; i<count; i++)
+		{
+		Entry* pE=(Entry*)&(*iDir)[i];
+		if (pE->IsDir())
+			{
+			subdircount++;
+			// Recursively build & place the subdirectories
+			DirEntry *pD=(DirEntry*)pE;
+			TRomDir *pR=pD->iDir->iRomDir;
+			if (!pR)
+				{
+				pR=pD->CreateRomEntries(anAddr);
+				pD->iDir->iRomDir=pR;
+				}
+			}
+		}
+	// Now place & build the TRomDir for this directory
+	TInt *pS=(TInt*)anAddr;
+	iDir->iRomDir=(TRomDir*)anAddr;
+	*pS=0;
+	anAddr+=sizeof(TInt);
+
+	char* offsetbase=anAddr;
+	SortableEntry* array=new SortableEntry [count];
+	if (array==0)
+		{
+		Print(EError,"Failed to allocate array of SortableEntry\n");
+		exit(-1);
+		}
+
+	for(i=0; i<count; i++)
+		{
+		Entry* pE=(Entry*)&(*iDir)[i];
+		array[i].iOffset=anAddr-offsetbase;
+		array[i].iEntry=pE;
+		TRomEntry *pR=pE->CreateRomEntry(anAddr);
+		if (pE->IsDir())
+			{
+			TRomDir *pD=((DirEntry*)pE)->iDir->iRomDir;
+			if (pD)
+				pR->iAddressLin=ActualToRomAddress(pD);
+			else
+				Print(EError,"Failed to fix up subdirectory address\n");
+			}
+		}
+	*pS=TInt(anAddr-(char*)pS-sizeof(TInt));
+
+	// Emit table of offsets for the subdirs and files in sorted order
+	if (gSortedRomFs)
+		{
+	TInt filecount=count-subdircount;
+	if (filecount>65535 || subdircount>65535)
+		{
+		Print(EError,"Too many files or subdirectories\n");
+		exit(-1);
+		}
+	TUint16* ptr=(TUint16*)anAddr;
+	*ptr++=(TUint16)subdircount;
+	*ptr++=(TUint16)filecount;
+	qsort(array,count,sizeof(SortableEntry),&compare);
+	for (i=0; i<count; i++)
+		{
+		unsigned int scaledOffset = array[i].iOffset>>2;
+		if ((array[i].iOffset & 3) != 0 || scaledOffset > 65535)
+			Print(EError, "Bad offset into directory\n");
+		*ptr++ = (TUint16)scaledOffset;
+		}
+	anAddr=(char*)ALIGN4((int)ptr);
+		}
+	delete [] array;
+	return (TRomDir*)pS;
+	}
+
+// class Directory
+TInt Directory::DirectoryCount=0;
+Directory::Directory(TInt aMaxCount)
+	: FiniteSet(aMaxCount), iRomDir(NULL), iAccessCount(1)
+	{
+	iIdentifier=Directory::DirectoryCount++;
+	}
+
+Directory* Directory::New(TInt aMaxCount, TVariantList aList)
+	{
+	Directory *pD=new Directory(aMaxCount);
+	if (pD)
+		{
+		pD->iVariants=aList;
+		pD=(Directory*)pD->Construct();
+		}
+	return pD;
+	}
+
+Directory::~Directory()
+	{
+	TRACE(TDIR,Print(EAlways,"Directory %08x Destruct\n",this));
+	}
+
+void Directory::Open()
+	{
+	iAccessCount++;
+	TRACE(TDIR,Print(EAlways,"Directory %08x Open() access count=%d\n",this,iAccessCount));
+	}
+
+void Directory::Close()
+	{
+	TRACE(TDIR,Print(EAlways,"Directory %08x Close() access count=%d\n",this,iAccessCount));
+	if (--iAccessCount==0)
+		delete this;
+	}
+
+TInt Directory::Compile(const FiniteSet& aSet)
+	{
+	TInt i;
+	TInt count=aSet.Count();
+	for(i=0; i<count; i++)
+		{
+		Entry *pE=(Entry*)&aSet[i];
+		if (iVariants<=pE->Variants())
+			{
+			Entry *pN=(Entry*)pE->Copy();
+			if (!pN)
+				return KErrNoMemory;
+			pN->Restrict(iVariants);
+			TInt r=Add(*pN);
+			if (r==KErrOverflow)
+				return r;
+			}
+		}
+	return KErrNone;
+	}
+
+TInt Directory::Merge(const Directory& aDir)
+	{
+	TInt i;
+	TInt r=Find(aDir,i);
+	if (r==KErrNone)
+		{
+		((Directory*)iMembers[i])->iVariants.Union(aDir.iVariants);
+		return KErrAlreadyExists;
+		}
+	else if (Insert(aDir,i)==KErrOverflow)
+		return KErrOverflow;
+	return KErrNone;
+	}
+
+// class RomFileStructure
+RomFileStructure::RomFileStructure(TInt aMaxCount)
+	: FiniteSet(aMaxCount)
+	{}
+
+RomFileStructure::~RomFileStructure()
+	{
+	}
+
+RomFileStructure* RomFileStructure::New(TInt aMaxCount)
+	{
+	RomFileStructure* pS=new RomFileStructure(aMaxCount);
+	if (pS)
+		pS=(RomFileStructure*)pS->Construct();
+	return pS;
+	}
+
+void RomFileStructure::Destroy()
+	{
+	}
+
+TInt RomFileStructure::ProcessDirectory(TRomNode* aDir)
+	{
+	TRACE(TSCRATCH, Print(EAlways, "ProcessDirectory (%08x) %s\n",aDir,aDir->iName));
+	TRACE(TDIR,Print(EAlways,"ProcessDirectory %s\nInitial:\n",aDir->iName));
+	TRACE(TDIR,DebugPrint());
+	TInt dirs=0;
+	TInt files=0;
+	aDir->CountDirectory(files,dirs);
+	TInt maxSize=files+dirs*TVariantList::NumVariants;
+	TRACE(TDIR,Print(EAlways,"files=%d dirs=%d maxSize=%d\n",files,dirs,maxSize));
+	RomFileStructure* pS=New(maxSize);
+	if (!pS)
+		return KErrNoMemory;
+	TInt r=aDir->ProcessDirectory(pS);
+	TRACE(TDIR,Print(EAlways,"FileList:\n"));
+	TRACE(TDIR,pS->DebugPrint());
+	Directory* dir[TVariantList::EMaxVariants];
+	TInt v;
+	for(v=0; v<TVariantList::NumVariants; v++)
+		{
+		TVariantList vList(v);
+		Directory *pD=Directory::New(files+dirs,vList);
+		if (!pD)
+			return KErrNoMemory;
+		dir[v]=pD;
+		r=pD->Compile(*pS);
+		if (r!=KErrNone)
+			return r;
+		TRACE(TDIR,Print(EAlways,"Variant %d Directory:\n",v));
+		TRACE(TDIR,pD->DebugPrint());
+		}
+	pS->Close();
+	Directory *pX=Directory::New(TVariantList::NumVariants,TVariantList());
+	if (!pX)
+		return KErrNoMemory;
+	for(v=0; v<TVariantList::NumVariants; v++)
+		{
+		if (dir[v]->Empty())
+			r=KErrAlreadyExists;
+		else
+			r=pX->Merge(*dir[v]);
+		if (r==KErrAlreadyExists)
+			{
+			dir[v]->Close();
+			dir[v]=NULL;
+			}
+		else if (r!=KErrNone)
+			return r;
+		}
+	TRACE(TDIR,Print(EAlways,"Final Directories:\n",v));
+	TRACE(TDIR,pX->DebugPrint());
+	TInt count=pX->Count();
+	TInt i;
+	for(i=0; i<count; i++)
+		{
+		Directory* pD=(Directory*)&(*pX)[i];
+		DirEntry* pE=DirEntry::New(aDir,pD);
+		if (!pE)
+			return KErrNoMemory;
+		r=Add(*pE);	// accumulate into the caller
+		if (r==KErrOverflow)
+			return r;
+		}
+	pX->Close();
+	return KErrNone;
+	}
+
+
+// DEBUG
+
+void FileEntry::DebugPrint() const
+	{
+	Print(EAlways,"FileEntry %08x %08x %s\n",iRomNode,iVariants.Mask(),iRomNode->iName);
+	}
+
+void DirEntry::DebugPrint() const
+	{
+	Print(EAlways,"DirEntry %08x %08x %08x %s\n",iRomNode,iVariants.Mask(),iDir,iRomNode->iName);
+	}
+
+void FiniteSet::DebugPrint() const
+	{
+	if (Count()==0)
+		Print(EAlways,"FiniteSet 0\n");
+	else
+		{
+		Print(EAlways,"FiniteSet %d {\n",Count());
+		TInt i;
+		for (i=0; i<Count(); i++)
+			{
+			iMembers[i]->DebugPrint();
+			}
+		Print(EAlways,"}\n");
+		}
+	}
+
+void Directory::DebugPrint() const
+	{
+	Print(EAlways,"Directory %08x %08x\n",iVariants.Mask(),iRomDir);
+	FiniteSet::DebugPrint();
+	}
+
+
+
+
+
--- a/imgtools/romtools/rombuild/r_dir.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_dir.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,214 +1,214 @@
-/*
-* Copyright (c) 1998-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifndef __R_DIR_H__
-#define __R_DIR_H__
-
-#include <e32std.h>
-
-// Generalised set handling
-class SetMember
-	{
-public:
-	TBool operator==(const SetMember& aMember) {return(Compare(aMember)==0);}
-	virtual SetMember* Copy() const =0;
-	virtual void Close();
-public:
-	TInt Type() const {return iType;}
-	virtual TInt Compare(const SetMember& aMember) const =0;
-	virtual void DebugPrint() const =0;
-protected:
-	virtual ~SetMember();
-	SetMember(TInt aType) : iType(aType) {TotalInSystem++;}
-	SetMember(const SetMember& aMember) : iType(aMember.iType) {TotalInSystem++;}
-	TBool operator<(const SetMember& aMember) {return(Compare(aMember)<0);}
-	TBool operator>(const SetMember& aMember) {return(Compare(aMember)>0);}
-private:
-	TInt iType;
-	static TInt TotalInSystem;
-	};
-
-class FiniteSet : public SetMember
-	{
-protected:
-	enum TFiniteSetType {EFiniteSetType=100};
-public:
-	static FiniteSet* New(TInt aMaxCount);
-	static FiniteSet* Singleton(TInt aMaxCount, const SetMember& aMember);
-	virtual ~FiniteSet();
-	virtual SetMember* Copy() const;
-	TInt Find(const SetMember& aMember) const;
-	TBool SubsetOf(const FiniteSet& aSet) const;
-	TInt Intersection(const FiniteSet& aSet);
-	TInt Union(const FiniteSet& aSet);
-	TInt Difference(const FiniteSet& aSet);
-	TInt Add(const SetMember& aMember);
-	TInt Remove(const SetMember& aMember);
-	SetMember* Detach(TInt anIndex);
-	TInt Count() const {return iCount;}
-	TBool Empty() const {return !iCount;}
-	SetMember& operator[](TInt anIndex) const {return *iMembers[anIndex];}
-	virtual void DebugPrint() const;
-protected:
-	FiniteSet(TInt aMaxCount);
-	FiniteSet(const FiniteSet& aSet);
-	FiniteSet* Construct();
-	virtual TInt Compare(const SetMember& aMember) const;
-	TInt Find(const SetMember& aMember, TInt& anIndex) const;
-	TInt Insert(const SetMember& aMember, TInt anIndex);
-protected:
-	TInt iMaxCount;
-	TInt iCount;
-	SetMember** iMembers;
-	};
-
-// ROMBUILD-specific stuff
-#include <e32rom.h>
-
-class CObeyFile;
-class TRomNode;
-class THardwareVariant;
-
-class RomFileStructure;
-class TVariantList
-	{
-public:
-	enum {EMaxVariants=32};
-	static void Setup(CObeyFile* aObey);
-	TVariantList() : iList(0)
-		{}
-	TVariantList(TInt aVariant)
-		{iList=TUint(1<<aVariant);}
-	TVariantList(THardwareVariant a);
-	void Add(TInt aVariant)
-		{iList|=TUint(1<<aVariant);}
-	TVariantList& Union(const TVariantList aList)
-		{iList|=aList.iList; return *this;}
-	TVariantList& Intersection(const TVariantList aList)
-		{iList&=aList.iList; return *this;}
-	TBool operator==(const TVariantList aList) const
-		{return(iList==aList.iList);}
-	TBool operator!=(const TVariantList aList) const
-		{return(iList!=aList.iList);}
-	TBool operator<=(const TVariantList aList) const
-		{return(iList==(iList&aList.iList));}
-	TBool operator>=(const TVariantList aList) const
-		{return(iList==(iList|aList.iList));}
-	TBool operator[](TInt aVariant) const
-		{return(iList&TUint(1<<aVariant));}
-	TBool Empty() const
-		{return !iList;}
-	TUint Mask() const
-		{return iList;}
-	THardwareVariant Lookup() const;
-	static void SetNumVariants(TInt aNumVariants);
-	static void SetVariants(THardwareVariant* aVariants);
-private:
-	friend class RomFileStructure;
-	TUint iList;
-	static TInt NumVariants;
-	static THardwareVariant Variants[EMaxVariants];
-	};
-
-class Entry : public SetMember
-	{
-public:
-	Entry(TInt aType) : SetMember(aType), iRomNode(NULL) {}
-	Entry(const Entry& anEntry) : SetMember(anEntry), iRomNode(NULL) {}
-	TBool IsFile() const {return (Type()==EFile);}
-	TBool IsDir() const {return (Type()==EDir);}
-	TVariantList Variants() const {return iVariants;}
-	TRomEntry* CreateRomEntry(char*& anAddr) const;
-	void Restrict(TVariantList aList) {iVariants.Intersection(aList);}
-	const TText* Name() const;
-protected:
-	enum {EFile=0, EDir=1};
-	TVariantList iVariants;
-	TRomNode* iRomNode;
-	};
-
-class FileEntry : public Entry
-	{
-public:
-	static FileEntry* New(TRomNode* aFile);
-	virtual SetMember* Copy() const;
-	virtual ~FileEntry();
-	virtual void DebugPrint() const;
-protected:
-	FileEntry() : Entry(EFile) {}
-	FileEntry(const FileEntry& aFileEntry);
-	virtual TInt Compare(const SetMember& aMember) const;
-	};
-
-class Directory;
-class DirEntry : public Entry
-	{
-public:
-	static DirEntry* New(TRomNode* aFile, Directory* aDir);
-	virtual SetMember* Copy() const;
-	virtual ~DirEntry();
-	Directory* Dir() const {return iDir;}
-	TRomDir* CreateRomEntries(char*& anAddr) const;
-	virtual void DebugPrint() const;
-protected:
-	DirEntry() : Entry(EDir) {}
-	DirEntry(const DirEntry& aDirEntry);
-	virtual TInt Compare(const SetMember& aMember) const;
-protected:
-	Directory* iDir;
-	};
-
-class Directory : public FiniteSet
-	{
-public:
-	static Directory* New(TInt aMaxCount, TVariantList aList);
-	TInt Compile(const FiniteSet& aSet);
-	TInt Merge(const Directory& aDir);
-	TVariantList Variants() const {return iVariants;}
-	virtual void DebugPrint() const;
-	void Open();
-	virtual void Close();
-protected:
-	Directory(TInt aMaxCount);
-private:
-	Directory(const Directory &);
-	~Directory();
-protected:
-	friend class DirEntry;
-	TVariantList iVariants;
-	TRomDir* iRomDir;
-private:
-	static TInt DirectoryCount;
-private:
-	TInt iAccessCount;
-	TInt iIdentifier;
-	};
-
-class RomFileStructure : public FiniteSet
-	{
-public:
-	static RomFileStructure* New(TInt aMaxCount);
-	~RomFileStructure();
-	void Destroy();
-	TInt ProcessDirectory(TRomNode* aDir);
-protected:
-	RomFileStructure(TInt aMaxCount);
-	};
-
-
-#endif
+/*
+* Copyright (c) 1998-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifndef __R_DIR_H__
+#define __R_DIR_H__
+
+#include <e32std.h>
+
+// Generalised set handling
+class SetMember
+	{
+public:
+	TBool operator==(const SetMember& aMember) {return(Compare(aMember)==0);}
+	virtual SetMember* Copy() const =0;
+	virtual void Close();
+public:
+	TInt Type() const {return iType;}
+	virtual TInt Compare(const SetMember& aMember) const =0;
+	virtual void DebugPrint() const =0;
+protected:
+	virtual ~SetMember();
+	SetMember(TInt aType) : iType(aType) {TotalInSystem++;}
+	SetMember(const SetMember& aMember) : iType(aMember.iType) {TotalInSystem++;}
+	TBool operator<(const SetMember& aMember) {return(Compare(aMember)<0);}
+	TBool operator>(const SetMember& aMember) {return(Compare(aMember)>0);}
+private:
+	TInt iType;
+	static TInt TotalInSystem;
+	};
+
+class FiniteSet : public SetMember
+	{
+protected:
+	enum TFiniteSetType {EFiniteSetType=100};
+public:
+	static FiniteSet* New(TInt aMaxCount);
+	static FiniteSet* Singleton(TInt aMaxCount, const SetMember& aMember);
+	virtual ~FiniteSet();
+	virtual SetMember* Copy() const;
+	TInt Find(const SetMember& aMember) const;
+	TBool SubsetOf(const FiniteSet& aSet) const;
+	TInt Intersection(const FiniteSet& aSet);
+	TInt Union(const FiniteSet& aSet);
+	TInt Difference(const FiniteSet& aSet);
+	TInt Add(const SetMember& aMember);
+	TInt Remove(const SetMember& aMember);
+	SetMember* Detach(TInt anIndex);
+	TInt Count() const {return iCount;}
+	TBool Empty() const {return !iCount;}
+	SetMember& operator[](TInt anIndex) const {return *iMembers[anIndex];}
+	virtual void DebugPrint() const;
+protected:
+	FiniteSet(TInt aMaxCount);
+	FiniteSet(const FiniteSet& aSet);
+	FiniteSet* Construct();
+	virtual TInt Compare(const SetMember& aMember) const;
+	TInt Find(const SetMember& aMember, TInt& anIndex) const;
+	TInt Insert(const SetMember& aMember, TInt anIndex);
+protected:
+	TInt iMaxCount;
+	TInt iCount;
+	SetMember** iMembers;
+	};
+
+// ROMBUILD-specific stuff
+#include <e32rom.h>
+
+class CObeyFile;
+class TRomNode;
+class THardwareVariant;
+
+class RomFileStructure;
+class TVariantList
+	{
+public:
+	enum {EMaxVariants=32};
+	static void Setup(CObeyFile* aObey);
+	TVariantList() : iList(0)
+		{}
+	TVariantList(TInt aVariant)
+		{iList=TUint(1<<aVariant);}
+	TVariantList(THardwareVariant a);
+	void Add(TInt aVariant)
+		{iList|=TUint(1<<aVariant);}
+	TVariantList& Union(const TVariantList aList)
+		{iList|=aList.iList; return *this;}
+	TVariantList& Intersection(const TVariantList aList)
+		{iList&=aList.iList; return *this;}
+	TBool operator==(const TVariantList aList) const
+		{return(iList==aList.iList);}
+	TBool operator!=(const TVariantList aList) const
+		{return(iList!=aList.iList);}
+	TBool operator<=(const TVariantList aList) const
+		{return(iList==(iList&aList.iList));}
+	TBool operator>=(const TVariantList aList) const
+		{return(iList==(iList|aList.iList));}
+	TBool operator[](TInt aVariant) const
+		{return(iList&TUint(1<<aVariant));}
+	TBool Empty() const
+		{return !iList;}
+	TUint Mask() const
+		{return iList;}
+	THardwareVariant Lookup() const;
+	static void SetNumVariants(TInt aNumVariants);
+	static void SetVariants(THardwareVariant* aVariants);
+private:
+	friend class RomFileStructure;
+	TUint iList;
+	static TInt NumVariants;
+	static THardwareVariant Variants[EMaxVariants];
+	};
+
+class Entry : public SetMember
+	{
+public:
+	Entry(TInt aType) : SetMember(aType), iRomNode(NULL) {}
+	Entry(const Entry& anEntry) : SetMember(anEntry), iRomNode(NULL) {}
+	TBool IsFile() const {return (Type()==EFile);}
+	TBool IsDir() const {return (Type()==EDir);}
+	TVariantList Variants() const {return iVariants;}
+	TRomEntry* CreateRomEntry(char*& anAddr) const;
+	void Restrict(TVariantList aList) {iVariants.Intersection(aList);}
+	const char* Name() const;
+protected:
+	enum {EFile=0, EDir=1};
+	TVariantList iVariants;
+	TRomNode* iRomNode;
+	};
+
+class FileEntry : public Entry
+	{
+public:
+	static FileEntry* New(TRomNode* aFile);
+	virtual SetMember* Copy() const;
+	virtual ~FileEntry();
+	virtual void DebugPrint() const;
+protected:
+	FileEntry() : Entry(EFile) {}
+	FileEntry(const FileEntry& aFileEntry);
+	virtual TInt Compare(const SetMember& aMember) const;
+	};
+
+class Directory;
+class DirEntry : public Entry
+	{
+public:
+	static DirEntry* New(TRomNode* aFile, Directory* aDir);
+	virtual SetMember* Copy() const;
+	virtual ~DirEntry();
+	Directory* Dir() const {return iDir;}
+	TRomDir* CreateRomEntries(char*& anAddr) const;
+	virtual void DebugPrint() const;
+protected:
+	DirEntry() : Entry(EDir) {}
+	DirEntry(const DirEntry& aDirEntry);
+	virtual TInt Compare(const SetMember& aMember) const;
+protected:
+	Directory* iDir;
+	};
+
+class Directory : public FiniteSet
+	{
+public:
+	static Directory* New(TInt aMaxCount, TVariantList aList);
+	TInt Compile(const FiniteSet& aSet);
+	TInt Merge(const Directory& aDir);
+	TVariantList Variants() const {return iVariants;}
+	virtual void DebugPrint() const;
+	void Open();
+	virtual void Close();
+protected:
+	Directory(TInt aMaxCount);
+private:
+	Directory(const Directory &);
+	~Directory();
+protected:
+	friend class DirEntry;
+	TVariantList iVariants;
+	TRomDir* iRomDir;
+private:
+	static TInt DirectoryCount;
+private:
+	TInt iAccessCount;
+	TInt iIdentifier;
+	};
+
+class RomFileStructure : public FiniteSet
+	{
+public:
+	static RomFileStructure* New(TInt aMaxCount);
+	~RomFileStructure();
+	void Destroy();
+	TInt ProcessDirectory(TRomNode* aDir);
+protected:
+	RomFileStructure(TInt aMaxCount);
+	};
+
+
+#endif
--- a/imgtools/romtools/rombuild/r_global.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_global.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,62 +1,62 @@
-/*
-* Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* Global Variables Definition
-*
-*/
-
-
-#include "r_global.h"
-
-TUint32 TheRomMem=0;
-TUint32 TheRomLinearAddress=0;
-ImpTRomHeader *TheRomHeader=0;
-TCpu CPU=ECpuUnknown;
-TBool Unicode=ETrue;
-TBool gLittleEndian=ETrue;
-TUint TraceMask=0;
-TBool TypeSafeLink=EFalse;
-TInt gHeaderType=-1;
-TInt gPagedRom=0;
-TInt gCodePagingOverride=-1; 
-TInt gDataPagingOverride=-1;
-TBool gPlatSecEnforcement=0;
-TBool gPlatSecDiagnostics=0;
-TBool gPlatSecEnforceSysBin=0;
-TBool gSortedRomFs=ETrue;
-TBool gEnableCompress=EFalse;		// Default to uncompressed ROM image
-TBool gFastCompress = EFalse;   // Default to compress most
-TUint gCompressionMethod=0; // Default compression method
-
-TBool gCompressUnpaged=EFalse; // Default to not compress un-paged part of ROM Image
-TUint gCompressUnpagedMethod=0;// Default compression method for un-paged part of ROM Image
-
-SCapabilitySet gPlatSecDisabledCaps={{0}}; 
-SCapabilitySet gPlatSecAllCaps={{0}};
-SDemandPagingConfig gDemandPagingConfig={0,0,0,{0}}; 
-TBool gGenInc=EFalse;	// Default to no generate INC file.  DEF095619
-TInt gLogLevel=0;  // Information is logged based on logging level.
-					// The default is 0. So all the existing logs are generated as if gLogLevel == 0.
-					// If any extra information is required, the log level must be appropriately supplied.
-					// Currrently, file details in ROM (like, file name in ROM & host, file size, whether 
-					// the file is hidden etc) are logged when gLogLevel >= 1.
-
-TBool gEnableStdPathWarning=EFalse; // To generate warning if the destination path is not a standard path. Default is not to warn.
-
-TBool gLowMem = EFalse;
-TBool gUseCoreImage = EFalse;
-TText* gImageFilename = 0;
-
-TInt gBootstrapSize=0;			// To calculate uncompressed un-paged size CR1258
-TInt gPageIndexTableSize=0;		// To calculate uncompressed un-paged size CR1258
+/*
+* Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* Global Variables Definition
+*
+*/
+
+
+#include "r_global.h"
+
+TUint32 TheRomMem=0;
+TUint32 TheRomLinearAddress=0;
+ImpTRomHeader *TheRomHeader=0;
+TCpu CPU=ECpuUnknown;
+TBool Unicode=ETrue;
+TBool gLittleEndian=ETrue;
+TUint TraceMask=0;
+TBool TypeSafeLink=EFalse;
+TInt gHeaderType=-1;
+TInt gPagedRom=0;
+TInt gCodePagingOverride=-1; 
+TInt gDataPagingOverride=-1;
+TBool gPlatSecEnforcement=0;
+TBool gPlatSecDiagnostics=0;
+TBool gPlatSecEnforceSysBin=0;
+TBool gSortedRomFs=ETrue;
+TBool gEnableCompress=EFalse;		// Default to uncompressed ROM image
+TUint gCompressionMethod=0; // Default compression method
+
+TBool gCompressUnpaged=EFalse; // Default to not compress un-paged part of ROM Image
+TUint gCompressUnpagedMethod=0;// Default compression method for un-paged part of ROM Image
+
+SCapabilitySet gPlatSecDisabledCaps={{0}}; 
+SCapabilitySet gPlatSecAllCaps={{0}};
+SDemandPagingConfig gDemandPagingConfig={0,0,0,{0}}; 
+TBool gGenInc=EFalse;	// Default to no generate INC file.  DEF095619
+TInt gLogLevel=0;  // Information is logged based on logging level.
+					// The default is 0. So all the existing logs are generated as if gLogLevel == 0.
+					// If any extra information is required, the log level must be appropriately supplied.
+					// Currrently, file details in ROM (like, file name in ROM & host, file size, whether 
+					// the file is hidden etc) are logged when gLogLevel >= 1.
+
+TBool gEnableStdPathWarning=EFalse; // To generate warning if the destination path is not a standard path. Default is not to warn.
+
+TBool gLowMem = EFalse;
+TBool gUseCoreImage = EFalse;
+string gImageFilename = "";
+
+TInt gBootstrapSize=0;			// To calculate uncompressed un-paged size CR1258
+TInt gPageIndexTableSize=0;		// To calculate uncompressed un-paged size CR1258
+TBool gKeepGoing = EFalse;
--- a/imgtools/romtools/rombuild/r_global.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_global.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,92 +1,93 @@
-/*
-* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#if !defined(__R_GLOBAL_H__)
-#define __R_GLOBAL_H__
-
-#define DEBUG_TRACE
-#ifdef DEBUG_TRACE
-#define TRACE(m,s)	( (void) ((TraceMask&(m)) && ((s),0)) )
-#define STRACE(m,s) if (TraceMask&(m)) s
-#define TDIR		0x00000001
-#define TTIMING		0x00000002
-#define TIMPORT		0x00000004
-#define TROMNODE	0x00000008
-#define TCOLLAPSE1	0x00000010
-#define TCOLLAPSE2	0x00000020
-#define TCOLLAPSE3	0x00000040
-#define TCOLLAPSE4	0x00000080
-#define TAREA       0x00000200
-#define TSCRATCH	0x100
-#else
-#define TRACE(m,s)
-#endif
-
-#define DEFAULT_LOG_LEVEL 0x0
-
-#define LOG_LEVEL_FILE_DETAILS	    0x00000001 // Destination file name (loglevel1)
-#define LOG_LEVEL_FILE_ATTRIBUTES   0x00000002 // File attributes (loglevel2)
-#define LOG_LEVEL_COMPRESSION_INFO  0x00000004 // Compression information (loglevel3)
-#define LOG_LEVEL_SMP_INFO          0x00000008 // SMP-unsafe components (loglevel4)
-
-#include <e32std.h>
-#include "e32image.h"
-#include "r_obey.h"
-
-// in r_global.cpp
-extern TRomLoaderHeader *TheRomLoaderHeader;
-extern ImpTRomHeader *TheRomHeader;
-extern TRomBuilderEntry *TheRootDirectory;
-extern TUint32 TheRomMem;
-extern TUint32 TheRomRootDir;
-extern TBool Unicode;
-extern TBool gSortedRomFs;
-extern TBool gEnableCompress;
-extern TBool gFastCompress;
-
-extern TUint gCompressionMethod;
-
-extern TBool gCompressUnpaged;
-extern TUint gCompressUnpagedMethod;
-
-extern TUint32 TheRomLinearAddress;
-extern TInt NumberOfVariants;
-extern TInt NumRootDirs;
-extern TUint TraceMask;
-extern TBool TypeSafeLink;
-extern TUint32 LastValidAddress;
-extern TCpu CPU;
-extern TInt gHeaderType;
-extern TInt gPagedRom;
-extern TInt gCodePagingOverride;
-extern TInt gDataPagingOverride;
-extern TBool gPlatSecEnforceSysBin;
-extern TBool gPlatSecEnforcement;
-extern TBool gPlatSecDiagnostics;
-extern SCapabilitySet gPlatSecDisabledCaps;
-extern SCapabilitySet gPlatSecAllCaps;
-extern SDemandPagingConfig gDemandPagingConfig;
-extern TBool gGenInc;						// DEF095619
-extern TBool gEnableStdPathWarning;
-extern TInt gLogLevel;
-extern TBool gLowMem;
-extern TBool gUseCoreImage;
-extern TText *gImageFilename;
-extern TInt gBootstrapSize;			// To calculate uncompressed un-paged size CR1258
-extern TInt gPageIndexTableSize;	// To calculate uncompressed un-paged size CR1258
-#endif
+/*
+* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#if !defined(__R_GLOBAL_H__)
+#define __R_GLOBAL_H__
+
+#define DEBUG_TRACE
+#ifdef DEBUG_TRACE
+#define TRACE(m,s)	( (void) ((TraceMask&(m)) && ((s),0)) )
+#define STRACE(m,s) if (TraceMask&(m)) s
+#define TDIR		0x00000001
+#define TTIMING		0x00000002
+#define TIMPORT		0x00000004
+#define TROMNODE	0x00000008
+#define TCOLLAPSE1	0x00000010
+#define TCOLLAPSE2	0x00000020
+#define TCOLLAPSE3	0x00000040
+#define TCOLLAPSE4	0x00000080
+#define TAREA       0x00000200
+#define TSCRATCH	0x100
+#else
+#define TRACE(m,s)
+#endif
+
+#define DEFAULT_LOG_LEVEL 0x0
+
+#define LOG_LEVEL_FILE_DETAILS	    0x00000001 // Destination file name (loglevel1)
+#define LOG_LEVEL_FILE_ATTRIBUTES   0x00000002 // File attributes (loglevel2)
+#define LOG_LEVEL_COMPRESSION_INFO  0x00000004 // Compression information (loglevel3)
+#define LOG_LEVEL_SMP_INFO          0x00000008 // SMP-unsafe components (loglevel4)
+
+#include <e32std.h>
+#include "e32image.h"
+#include "r_obey.h"
+
+// in r_global.cpp
+extern TRomLoaderHeader *TheRomLoaderHeader;
+extern ImpTRomHeader *TheRomHeader;
+extern TRomBuilderEntry *TheRootDirectory;
+extern TUint32 TheRomMem;
+extern TUint32 TheRomRootDir;
+extern TBool Unicode;
+extern TBool gSortedRomFs;
+extern TBool gEnableCompress;
+
+extern TUint gCompressionMethod;
+
+extern TBool gCompressUnpaged;
+extern TUint gCompressUnpagedMethod;
+
+extern TUint32 TheRomLinearAddress;
+extern TInt NumberOfVariants;
+extern TInt NumRootDirs;
+extern TUint TraceMask;
+extern TBool TypeSafeLink;
+extern TUint32 LastValidAddress;
+extern TCpu CPU;
+extern TInt gHeaderType;
+extern TInt gPagedRom;
+extern TInt gCodePagingOverride;
+extern TInt gDataPagingOverride;
+extern TBool gPlatSecEnforceSysBin;
+extern TBool gPlatSecEnforcement;
+extern TBool gPlatSecDiagnostics;
+extern SCapabilitySet gPlatSecDisabledCaps;
+extern SCapabilitySet gPlatSecAllCaps;
+extern SDemandPagingConfig gDemandPagingConfig;
+extern TBool gGenInc;						// DEF095619
+extern TBool gEnableStdPathWarning;
+extern TInt gLogLevel;
+extern TBool gLowMem;
+extern TBool gUseCoreImage;
+extern string gImageFilename;
+extern TBool gGenSymbols; 
+extern TInt gBootstrapSize;			// To calculate uncompressed un-paged size CR1258
+extern TInt gPageIndexTableSize;	// To calculate uncompressed un-paged size CR1258
+extern TBool gKeepGoing;					// To enable keepgoing
+#endif
--- a/imgtools/romtools/rombuild/r_mromimage.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_mromimage.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,50 +1,52 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifndef __R_MROMIMAGE_H__
-#define __R_MROMIMAGE_H__
-
-class TRomNode;
-
-/**
-class MRomImage
-MRofsImage is the interface used to access information held within an Core ROM image.
-This interface used to remove the dependency between processing of 
-extensions and kernel commands in the obey file
-
-@internalComponent
-@released
-*/
-class MRomImage
-{
-public:
-	virtual TRomNode* RootDirectory() = 0;
-	virtual TRomNode* CopyDirectory(TRomNode*& aSourceDirectory)=0;
-	virtual TText* RomFileName() = 0;
-	virtual TUint32 RomBase() = 0;
-	virtual TUint32 RomSize() = 0;
-	virtual TVersion Version() = 0;
-	virtual TInt64 Time() = 0;
-	virtual TUint32 CheckSum() = 0;
-	virtual TUint32 DataRunAddress() = 0;
-	virtual TUint32 RomAlign() = 0;
-
-	virtual ~MRomImage() { };
-};
-
-#endif //__R_MROMIMAGE_H__
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifndef __R_MROMIMAGE_H__
+#define __R_MROMIMAGE_H__
+
+class TRomNode;
+
+/**
+class MRomImage
+MRofsImage is the interface used to access information held within an Core ROM image.
+This interface used to remove the dependency between processing of 
+extensions and kernel commands in the obey file
+
+@internalComponent
+@released
+*/
+class MRomImage
+{
+public:
+	virtual TRomNode* RootDirectory() const = 0 ;
+	virtual TRomNode* CopyDirectory(TRomNode*& aSourceDirectory)=0;
+	virtual const char* RomFileName() const = 0 ;
+	virtual TUint32 RomBase() const = 0 ;
+	virtual TUint32 RomSize() const = 0 ;
+	virtual TVersion Version() const = 0 ;
+	virtual TInt64 Time() const = 0 ;
+	virtual TUint32 CheckSum() const  = 0 ;
+	virtual TUint32 DataRunAddress() const = 0 ;
+	virtual TUint32 RomAlign() const = 0 ;
+ 
+#ifdef __LINUX__
+	virtual ~MRomImage() { };
+#endif
+};
+
+#endif //__R_MROMIMAGE_H__
--- a/imgtools/romtools/rombuild/r_obey.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_obey.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,3015 +1,2678 @@
-/*
-* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include <string.h>
-
-#ifdef __VC32__
- #ifdef __MSVCDOTNET__
-  #include <strstream>
-  #include <iomanip>
- #else //!__MSVCDOTNET__
-  #include <strstrea.h>
-  #include <iomanip.h>
- #endif //__MSVCDOTNET__
-#else //!__VC32__
-#ifdef __TOOLS2__
- #include <sstream>
-  #include <iomanip>
-#else
- #include <strstream.h>
- #include <iomanip.h>
-#endif 
-#endif //__VC32__
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <time.h>
-#include <assert.h>
-
-#include "e32std.h"
-#include "e32std_private.h"
-#include "e32rom.h"
-#include "u32std.h"
-
-#include "r_rom.h"
-#include "r_obey.h"
-#include "r_global.h"
-#include "h_utl.h"
-#include "patchdataprocessor.h"
-#include "r_coreimage.h"
-
-#define _P(word)	word, sizeof(word)-1	// match prefix, optionally followed by [HWVD]
-#define _K(word)	word, 0					// match whole word
-
-const ObeyFileKeyword ObeyFileReader::iKeywords[] =
-{
-	{_P("file"),		2,-2, EKeywordFile, "Executable file to be loaded into the ROM"},
-	{_P("data"),		2,-2, EKeywordData, "Data file to be copied into the ROM"},
-	{_P("primary"),		1+2,-2, EKeywordPrimary, "An EPOC Kernel"},
-	{_P("secondary"),	2,-2, EKeywordSecondary, "?"},
-	{_P("variant"),		1+2,-2, EKeywordVariant, "?"},
-	{_P("extension"),	1+2,-2, EKeywordExtension, "Kernel extension loaded before the secondary"},
-	{_P("device"),		1+2,-2, EKeywordDevice, "Kernel extension loaded from the ROM file system"},
-	{_P("dll"),			2,-2, EKeywordDll, "Executable file whose entry point must be called"},
-	{_P("filecompress"),	2,-2, EKeywordFileCompress, "Non-XIP Executable to be loaded into the ROM compressed"},
-	{_P("fileuncompress"),	2,-2, EKeywordFileUncompress, "Non-XIP Executable to be loaded into the ROM uncompressed"},
-	{_K("area"),	    1, 3, EKeywordArea, "Declare a relocation area"},
-	{_K("align"),	    2, 1, EKeywordAlign, "Override default alignment for following file"},
-	{_P("hide"),	    2, -1, EKeywordHide, "Exclude named file from ROM directory structure"},
-	{_P("alias"),	    2, -2, EKeywordAlias, "Create alias for existing file in ROM directory structure"},
-	{_P("rename"),	    2, -2, EKeywordRename, "Change the name of a file in the ROM directory structure"},
-	{_K("singlekernel"),1, 0, EKeywordSingleKernel, "Single Kernel"},
-	{_K("multikernel"),	1, 0, EKeywordMultiKernel, "Multiple Kernels"},
-	{_K("bootbinary"),	1, 1, EKeywordBootBinary, "file containing the bootstrap"},
-	{_K("romname"),		1, 1, EKeywordRomName, "output file for ROM image"},
-	{_K("romsize"),		1, 1, EKeywordRomSize, "size of ROM image"},
-	{_K("romlinearbase"),	1, 1, EKeywordRomLinearBase, "linear address of ROM image"},
-	{_K("romalign"),	1, 1, EKeywordRomAlign, "default alignment of files in ROM image"},
-	{_K("romchecksum"),	1, 1, EKeywordRomChecksum, "desired 32-bit checksum value for the whole ROM image"},
-	{_K("kerneldataaddress"),	1, 1, EKeywordKernelDataAddress, "?"},
-	{_K("kernelheapmin"),	1, 1, EKeywordKernelHeapMin, "Inital size of the kernel heap"},
-	{_K("kernelheapmax"),	1, 1, EKeywordKernelHeapMax, "Maximum size of the kernel heap"},
-	{_K("dataaddress"),	1, 1, EKeywordDataAddress, "?"},
-	{_K("defaultstackreserve"),	1, 1, EKeywordDefaultStackReserve, "?"},
-	{_K("version"),		1, 1, EKeywordVersion, "ROM version number"},
-	{_K("romnameodd"),	1, 1, EKeywordRomNameOdd, "output file containing odd halfwords of ROM image"},
-	{_K("romnameeven"),	1, 1, EKeywordRomNameEven, "output file containing even halfwords of ROM image"},
-	{_K("srecordfilename"),	1, 1, EKeywordSRecordFileName, "output file containing ROM image in S-Record format"},
-	{_K("srecordbase"),	1, 1, EKeywordSRecordBase, "Destination address for S-Record download"},
-	{_K("kerneltrace"),	1, -1, EKeywordKernelTrace, "Initial value for Kernel tracing flags"},
-	{_K("btrace"),	1, -1, EKeywordBTrace, "Initial value for fast-trace filter"},
-	{_K("btracemode"),	1, 1, EKeywordBTraceMode, "Initial value for fast-trace mode"},
-	{_K("btracebuffer"),	1, 1, EKeywordBTraceBuffer, "Initial size for fast-trace buffer"},
-	{_K("collapse"),	1, 3, EKeywordCollapse, "Additional ROM optimisations"},
-	{_K("time"),	    1,-1, EKeywordTime, "ROM timestamp"},
-	{_K("section"),	    2, 1, EKeywordSection, "Start of replaceable section in old-style 2 section ROM"},
-	{_K("extensionrom"),1+2, 1, EKeywordExtensionRom, "Start of definition of optional Extension ROM"},
-	{_K("kernelromname"),1, 1, EKeywordKernelRomName, "ROM image on which extension ROM is based"},
-	{_K("files"),		0, 0, EKeywordNone, 0},	// backwards compatibility, but now ignored
-	{_K("rem"),			0, 0, EKeywordNone, "comment"},
-	{_K("stop"),		0, 0, EKeywordNone, "Terminates OBEY file prematurely"},
-	{_K("dlldatatop"),	1, 1, EKeywordDllDataTop, "Specify top of DLL data region"},
-	{_K("memmodel"),	1, -1, EKeywordMemModel, "Specifies the memory model to be used at runtime"},
-	{_K("nowrapper"),	1, 0, EKeywordNoWrapper, "Specifies that no ROM wrapper is required"},
-	{_K("epocwrapper"),	1, 0, EKeywordEpocWrapper, "Specifies that an EPOC ROM wrapper is required"},
-	{_K("coffwrapper"),	1, 0, EKeywordCoffWrapper, "Specifies that a COFF ROM wrapper is required"},
-	{_K("platsecenforcement"),	1, 1, EKeywordPlatSecEnforcement, "Set Platform Security enforment on/off"},
-	{_K("platsecdiagnostics"),	1, 1, EKeywordPlatSecDiagnostics, "Set Platform Security diagnostics on/off"},
-	{_K("platsecprocessisolation"), 1, 1, EKeywordPlatSecProcessIsolation, "Set Platform Security process isolation on/off"},
-	{_K("platsecenforcesysbin"), 1, 1, EKeywordPlatSecEnforceSysBin, "Set Platform Security process isolation on/off"},
-	{_K("platsecdisabledcaps"), 1, 1, EKeywordPlatSecDisabledCaps, "Disable the listed Platform Security capabilities"},
-	{_K("pagingpolicy"),	1, 1, EKeywordPagingPolicy, "Set the demand paging policy NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
-	{_K("codepagingpolicy"),	1, 1, EKeywordCodePagingPolicy, "Set the code paging policy NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
-	{_K("datapagingpolicy"),	1, 1, EKeywordDataPagingPolicy, "Set the data paging policy NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
-	{_K("pagingoverride"),	1, 1, EKeywordPagingOverride, "Overide the demand paging attributes for every file in ROM, NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
-	{_K("codepagingoverride"),	1, 1, EKeywordCodePagingOverride, "Overide the code paging attributes for every file in ROM, NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
-	{_K("datapagingoverride"),	1, 1, EKeywordDataPagingOverride, "Overide the data paging attributes for every file in ROM, NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
-	{_K("patchdata"), 2, 5, EKeywordPatchDllData, "Patch exported data"},
-	{_K("coreimage"),	1, 1, EKeywordCoreImage, "Core image to be used for extension directory structure"},
-
-	// things we don't normally report in the help information
-	{_K("trace"),		1, 1, EKeywordTrace, "(ROMBUILD activity trace flags)"},
-	{_K("unicode"),		1, 0, EKeywordUnicode, "(UNICODE rom - the default)"},
-	{_K("ascii"),		1, 0, EKeywordAscii, "(Narrow rom)"},
-	{_K("languages"),	1,-1, EKeywordLanguages, "(List of supported languages (for test))"},
-	{_K("hardware"),	1, 1, EKeywordHardware, "(32-bit Hardware identifier (for test))"},
-	{_K("debugport"),	1, 1, EKeywordDebugPort, "(Debug trace sink (magic cookie passed to ASSP/variant))"},
-	{_K("compress"),	1, 0, EKeywordCompress, "Compress the ROM image"},
-	{_K("demandpagingconfig"),	1, -1, EKeywordDemandPagingConfig, "Demand Paging Config [minPages] [maxPages] [ageRatio]"},
-	{_K("pagedrom"),	1, 0, EKeywordPagedRom, "Build ROM immage suitable for demand paging"},
-	{_K("filecompressnone"), 		2, -2, EKeywordExecutableCompressionMethodNone, "No compress the individual executable image."},
-	{_K("filecompressinflate"),     2, -2, EKeywordExecutableCompressionMethodInflate,  "Inflate compression method for the individual executable image."},
-	{_K("filecompressbytepair"),  	2, -2, EKeywordExecutableCompressionMethodBytePair, "Byte pair compresion method for the individual executable image."},
-	{_K("kernelconfig"), 1, 2, EKeywordKernelConfig, "Set an arbitrary bit of the kernel config flags to on/off)"},
-	{_K("maxunpagedsize"),	1, 1, EKeywordMaxUnpagedMemSize, "Maxinum unpaged size in ROM image. Default is no limited."},
-	{_K("hcrdata") , 2, 2,EKeywordHardwareConfigRepositoryData,"HCR image data"},
-	{0,0,0,0,EKeywordNone,""} 
-	
-};
-
-void ObeyFileReader::KeywordHelp() // static
-	{
-	cout << "Obey file keywords:\n";
-
-	const ObeyFileKeyword* k=0;
-	for (k=iKeywords; k->iKeyword!=0; k++)
-		{
-		if (k->iHelpText==0)
-			continue;
-		if (k->iHelpText[0]=='(' && !H.iVerbose)
-			continue;	// don't normally report things in (parentheses)
-
-		char buf[32];
-		sprintf(buf, "%-20s", k->iKeyword);
-		if (k->iKeywordLength)
-			memcpy(buf+k->iKeywordLength,"[HWVD]",6);
-		if (H.iVerbose)
-			sprintf(buf+20,"%2d",k->iNumArgs);
-		cout << "    " << buf << " " << k->iHelpText << endl;
-		}
-	cout << endl;
-
-	cout << "File attributes:\n";
-
-	const FileAttributeKeyword* f=0;
-	for (f=iAttributeKeywords; f->iKeyword!=0; f++)
-		{
-		if (f->iHelpText==0)
-			continue;
-		if (f->iHelpText[0]=='(' && !H.iVerbose)
-			continue;	// don't normally report things in (parentheses)
-
-		char buf[32];
-		sprintf(buf, "%-20s", f->iKeyword);
-		if (H.iVerbose)
-			sprintf(buf+20,"%2d",k->iNumArgs);
-		cout << "    " << buf << " " << f->iHelpText << endl;
-		}
-	cout << endl;
-	}
-
-TInt NumberOfVariants=0;
-
-ObeyFileReader::ObeyFileReader(TText* aFileName):
-//
-// Constructor
-//
-	iMark(0), iMarkLine(0), iCurrentMark(0), iCurrentLine(0), imaxLength(0),iSuffix(0),iLine(0)
-	{
-
-	iFileName = new TText[strlen((const char *)aFileName)+1];
-	strcpy((char *)iFileName,(const char *)aFileName);
-	}
-
-ObeyFileReader::~ObeyFileReader()
-	{
-	if (iObeyFile)
-		fclose(iObeyFile);
-	iObeyFile=0;
-	delete [] iFileName;
-	delete [] iLine;
-	}
-
-TBool ObeyFileReader::Open()
-//
-// Open the file & return a status
-//
-	{
-
- 	iObeyFile = fopen((const char *)iFileName,"r");
-	if (!iObeyFile)
-		{
-		Print(EError,"Cannot open obey file %s\n",iFileName);
-		return EFalse;
-		}
-	if (SetLineLengthBuffer() != KErrNone)
-	 	{
-		Print(EError,"Insufficent Memory to Continue.");	
-	 	return EFalse;
-		}
-	return ETrue;
-	}
-
-TInt ObeyFileReader::SetLineLengthBuffer()
-// Get the Max Line length for the given obey file and allocate the buffer.
-	{
-	char ch = '\0';
-	TInt length = 0;
-		
-	Rewind();
-	while ((ch = (char)fgetc(iObeyFile)) != EOF)
-		{
-		length++;
-		if (ch == '\n')
-			{
-			if (length > imaxLength)
-				imaxLength = length;
-			length = 0;				
-			}
-		}
-	
-	if (length > imaxLength)
-		imaxLength = length;
-		
-	if (0 == imaxLength)
-		{
-		Print(EError,"Empty obey file passed as input.");
-		exit(-1);
-		}			
-	else if (imaxLength < 2)
-		{
-		Print(EError,"Invalid obey file passed as input.");
-		exit(-1);
-		}
-		
-	Rewind();
-	iLine = new TText[imaxLength+1];
-	
-	if(!iLine)
-		return KErrNoMemory;
-
-	return KErrNone;
-	}
-
-void ObeyFileReader::Mark()
-	{
-
-	iMark = iCurrentMark;
-	iMarkLine = iCurrentLine-1;
-	}
-
-void ObeyFileReader::MarkNext()
-	{
-
-	iMark = ftell(iObeyFile);
-	iMarkLine = iCurrentLine;
-	}
-
-void ObeyFileReader::Rewind()
-	{
-	
-	fseek(iObeyFile,iMark,SEEK_SET);
-	iCurrentMark = iMark;
-	iCurrentLine = iMarkLine;
-	}
-
-void ObeyFileReader::CopyWord(TInt aIndex, TText*& aString)
-	{
-	aString = new TText[strlen((const char *)iWord[aIndex])+1];
-	strcpy((char *)aString, (const char *)iWord[aIndex]);
-	}
-
-TInt ObeyFileReader::ReadAndParseLine()
-	{
-	if (feof(iObeyFile))
-		return KErrEof;
-	iCurrentLine++;
-	iCurrentMark = ftell(iObeyFile);
-	iLine[0]='\0';
-	fgets((char*)iLine,imaxLength+1,iObeyFile);
-	iNumWords = Parse();
-	return KErrNone;
-	}
-
-TInt ObeyFileReader::NextLine(TInt aPass, enum EKeyword& aKeyword)
-	{
-
-NextLine:
-	TInt err = ReadAndParseLine();
-	if (err == KErrEof)
-		return KErrEof;
-	if (iNumWords == 0 || stricmp((const char*)iWord[0], "rem")==0)
-		goto NextLine;
-	if (stricmp((const char*)iWord[0], "stop")==0)
-		return KErrEof;
-
-	const ObeyFileKeyword* k=0;
-	for (k=iKeywords; k->iKeyword!=0; k++)
-		{
-		if (k->iKeywordLength == 0)
-			{
-			// Exact case-insensitive match on keyword
-			if (stricmp((const char*)iWord[0], k->iKeyword) != 0)
-				continue;
-			iSuffix = 0;
-			}
-		else
-			{
-			// Prefix match
-			if (strnicmp((const char*)iWord[0], k->iKeyword, k->iKeywordLength) != 0)
-				continue;
-			// Suffix must be empty, or a variant number in []
-			iSuffix = iWord[0]+k->iKeywordLength;
-			if (*iSuffix != '\0' && *iSuffix != '[')
-				continue;
-			}
-		// found a match
-		if ((k->iPass & aPass) == 0)
-			goto NextLine;
-		if (k->iNumArgs>=0 && (1+k->iNumArgs != iNumWords))
-			{
-			 
-			if(EKeywordHardwareConfigRepositoryData == k->iKeywordEnum){ // preq2131 specific 
-				Print(EWarning, "Incorrect number of arguments for keyword '%s' on line %d. Extra argument(s) are ignored.\n",
-				iWord[0],iCurrentLine);
-				aKeyword = k->iKeywordEnum;
-				return KErrNone;
-			}else{
-				Print(EError, "Incorrect number of arguments for keyword %s on line %d.\n",
-					iWord[0], iCurrentLine);
-			}
-			goto NextLine;
-			}
-		if (k->iNumArgs<0 && (1-k->iNumArgs > iNumWords))
-			{
-			Print(EError, "Too few arguments for keyword %s on line %d.\n",
-				iWord[0], iCurrentLine);
-			goto NextLine;
-			}
-		
-		aKeyword = k->iKeywordEnum;
-		return KErrNone;
-		}
-	if (aPass == 1)
-		Print(EWarning, "Unknown keyword '%s'.  Line %d ignored\n", iWord[0], iCurrentLine);
-	goto NextLine;
-	}
-
-inline TBool ObeyFileReader::IsGap(char ch)
-	{
-	return (ch==' ' || ch=='=' || ch=='\t');
-	}
-
-TInt ObeyFileReader::Parse()
-//
-// splits a line into words, and returns the number of words found
-//
-
-	{
-
-	TUint i; 
-	TText *letter=iLine;
-	TText *end=iLine+strlen((char *)iLine);
-	for (i=0; i<KNumWords; i++)
-		iWord[i]=end;
-
-	enum TState {EInWord, EInQuotedWord, EInGap};
-	TState state=EInGap;
-
-	i=0;
-	while (i<KNumWords && letter<end)
-		{
-		char ch=*letter;
-		if (ch==0)
-			break;
-		if (ch=='\n')
-			{
-			*letter='\0';	// remove trailing newline left by fgets
-			break;
-			}
-		switch (state)
-			{
-		case EInGap:
-			if (ch=='\"')
-				{
-				if (letter[1]!=0 && letter[1]!='\"')
-					iWord[i++]=letter+1;
-				state=EInQuotedWord;
-				}
-			else if (!IsGap(ch))
-				{
-				iWord[i++]=letter;
-				state=EInWord;
-				}
-			else
-				*letter=0;
-			break;
-		case EInWord:
-			if (ch=='\"')
-				{
-				*letter=0;
-				if (letter[1]!=0 && letter[1]!='\"')
-					iWord[i++]=letter+1;
-				state=EInQuotedWord;
-				}
-			else if (IsGap(ch))
-				{
-				*letter=0;
-				state=EInGap;
-				}
-			break;
-		case EInQuotedWord:
-			if (ch=='\"')
-				{
-				*letter=0;
-				state=EInGap;
-				}
-			break;
-			}
-		letter++;
-		}
-	return i;
-	}
-
-void ObeyFileReader::ProcessLanguages(TInt64& aLanguageMask)
-	{
-	TInt i=1;
-	while (i<iNumWords)
-		{
-		char *aStr=(char *)iWord[i];
-		TLanguage l=ELangTest;
-		if (stricmp(aStr, "test")==0)
-			l=ELangTest;
-		else if (stricmp(aStr, "english")==0)
-			l=ELangEnglish;
-		else if (stricmp(aStr, "french")==0)
-			l=ELangFrench;
-		else if (stricmp(aStr, "german")==0)
-			l=ELangGerman;
-		else if (stricmp(aStr, "spanish")==0)
-			l=ELangSpanish;
-		else if (stricmp(aStr, "italian")==0)
-			l=ELangItalian;
-		else if (stricmp(aStr, "swedish")==0)
-			l=ELangSwedish;
-		else if (stricmp(aStr, "danish")==0)
-			l=ELangDanish;
-		else if (stricmp(aStr, "norwegian")==0)
-			l=ELangNorwegian;
-		else if (stricmp(aStr, "finnish")==0)
-			l=ELangFinnish;
-		else if (stricmp(aStr, "american")==0)
-			l=ELangAmerican;
-		else if (stricmp(aStr, "SwissFrench")==0)
-			l=ELangSwissFrench;
-		else if (stricmp(aStr, "SwissGerman")==0)
-			l=ELangSwissGerman;
-		else if (stricmp(aStr, "Portuguese")==0)
-			l=ELangPortuguese;
-		else if (stricmp(aStr, "Turkish")==0)
-			l=ELangTurkish;
-		else if (stricmp(aStr, "Icelandic")==0)
-			l=ELangIcelandic;
-		else if (stricmp(aStr, "Russian")==0)
-			l=ELangRussian;
-		else if (stricmp(aStr, "Hungarian")==0)
-			l=ELangHungarian;
-		else if (stricmp(aStr, "Dutch")==0)
-			l=ELangDutch;
-		else if (stricmp(aStr, "BelgianFlemish")==0)
-			l=ELangBelgianFlemish;
-		else if (stricmp(aStr, "Australian")==0)
-			l=ELangAustralian;
-		else if (stricmp(aStr, "BelgianFrench")==0)
-			l=ELangBelgianFrench;
-		else
-			{
-			Print(EError, "Unknown language '%s' on line %d", iWord[i], iCurrentLine);
-			exit(666);
-			}
-		aLanguageMask = aLanguageMask+(1<<(TInt)l);
-		i++;
-		}
-	}
-
-void ObeyFileReader::ProcessTime(TInt64& aTime)
-//
-// Process the timestamp
-//
-	{
-	char timebuf[256];
-	if (iNumWords>2)
-		sprintf(timebuf, "%s_%s", iWord[1], iWord[2]);
-	else
-		strcpy(timebuf, (char*)iWord[1]);
-
-	TInt r=StringToTime(aTime, timebuf);
-	if (r==KErrGeneral)
-		{
-		Print(EError, "incorrect format for time keyword on line %d\n", iCurrentLine);
-		exit(0x670);
-		}
-	if (r==KErrArgument)
-		{
-		Print(EError, "Time out of range on line %d\n", iCurrentLine);
-		exit(0x670);
-		}
-	}
-
-TInt64 ObeyFileReader::iTimeNow=0;
-void ObeyFileReader::TimeNow(TInt64& aTime)
-	{
-	if (iTimeNow==0)
-		{
-		TInt sysTime=time(0);					// seconds since midnight Jan 1st, 1970
-		sysTime-=(30*365*24*60*60+7*24*60*60);	// seconds since midnight Jan 1st, 2000
-		TInt64 daysTo2000AD=730497;
-		TInt64 t=daysTo2000AD*24*3600+sysTime;	// seconds since 0000
-		t=t+3600;								// BST (?)
-		iTimeNow=t*1000000;						// milliseconds
-		}
-	aTime=iTimeNow;
-	}
-
-TInt ObeyFileReader::ProcessAlign(TInt &aAlign)
-//
-// Process the align keyword
-//
-	{
-
-	TInt align;
-	if (Val(align, Word(1)))
-		return Print(EError, "Number required for 'align' keyword on line %d\n", iCurrentLine);
-	aAlign=align;
-	TInt i;
-	for (i=4; i!=0x40000000; i<<=1)
-		if (i==aAlign)
-			return KErrNone;
-	return Print(EError, "Alignment must be a power of 2 and bigger than 4.  Line %d\n", iCurrentLine);
-	}
-
-
-const FileAttributeKeyword ObeyFileReader::iAttributeKeywords[] =
-{
-	{"stackreserve",6	,1,1,EAttributeStackReserve, "?"},
-	{"stack",3			,1,1,EAttributeStack, "?"},
-	{"reloc",3			,1,1,EAttributeReloc, "?"},
-	{"code-align",10	,1,1,EAttributeCodeAlign, "Additional code alignment constraint"},
-	{"data-align",10	,1,1,EAttributeDataAlign, "Additional data alignment constraint"},
-	{"fixed",3			,1,0,EAttributeFixed, "Relocate to a fixed address space"},
-	{"attrib",3			,0,1,EAttributeAtt, "File attributes in ROM file system"},
-	{"priority",3		,1,1,EAttributePriority, "Override process priority"},
-	{"patched",5		,1,0,EAttributePatched, "File to be replaced in second section"},
-	{_K("uid1")			,1,1,EAttributeUid1, "Override first UID"},
-	{_K("uid2")			,1,1,EAttributeUid2, "Override second UID"},
-	{_K("uid3")			,1,1,EAttributeUid3, "Override third UID"},
-	{_K("heapmin")		,1,1,EAttributeHeapMin, "Override initial heap size"},
-	{_K("heapmax")		,1,1,EAttributeHeapMax, "Override maximum heap size"},
-	{_K("keepIAT")		,1,0,EAttributeKeepIAT, "(Retain old-style Import Address Table)"},
-	{_K("hide")			,0,0,EAttributeHidden, "Don't record file in the ROM file system"},
-	{_K("area")         ,1,1,EAttributeArea, "Relocate file to given area"},
-	{_K("process")		,1,1,EAttributeProcessSpecific, "Indicate which process a DLL will attach to"},
-	{_K("capability")	,1,1,EAttributeCapability, "Override capabilities"},
-	{_K("preferred")	,1,0,EAttributePreferred, "Prefer this over other minor versions of same major version"},
-	{_K("unpaged")		,1,0,EAttributeUnpaged, "Don't use demand paging for this file"},
-	{_K("paged")		,1,0,EAttributePaged, "Use demand paging for this file"},
-	{_K("unpagedcode")	,1,0,EAttributeUnpagedCode, "Don't use code paging for this file"},
-	{_K("pagedcode")	,1,0,EAttributePagedCode, "Use code paging for this file"},
-	{_K("unpageddata")	,1,0,EAttributeUnpagedData, "Don't use data paging for this file"},
-	{_K("pageddata")	,1,0,EAttributePagedData, "Use data paging for this file"},
-	{0,0,0,0,EAttributeStackReserve,0}
-};
-
-TInt ObeyFileReader::NextAttribute(TInt& aIndex, TInt aHasFile, enum EFileAttribute& aKeyword, TText*& aArg)
-	{
-NextAttribute:
-	if (aIndex >= iNumWords)
-		return KErrEof;
-	TText* word=iWord[aIndex++];
-	const FileAttributeKeyword* k;
-	for (k=iAttributeKeywords; k->iKeyword!=0; k++)
-		{
-		if (k->iKeywordLength == 0)
-			{
-			// Exact match on keyword
-			if (stricmp((const char*)word, k->iKeyword) != 0)
-				continue;
-			}
-		else
-			{
-			// Prefix match
-			if (strnicmp((const char*)word, k->iKeyword, k->iKeywordLength) != 0)
-				continue;
-			}
-		// found a match
-		if (k->iNumArgs>0)
-			{
-			TInt argIndex = aIndex;
-			aIndex += k->iNumArgs;		// interface only really supports 1 argument
-			if (aIndex>iNumWords)
-				{
-				Print(EError, "Missing argument for attribute %s on line %d\n", word, iCurrentLine);
-				return KErrArgument;
-				}
-			aArg=iWord[argIndex];
-			}
-		if (k->iIsFileAttribute && !aHasFile)
-			{
-			Print(EError, "File attribute %s applied to non-file on line %d\n", word, iCurrentLine);
-			return KErrNotSupported;
-			}
-		aKeyword=k->iAttributeEnum;
-		return KErrNone;
-		}
-	Print(EWarning, "Unknown attribute '%s' skipped on line %d\n", word, iCurrentLine);
-	goto NextAttribute;
-	}
-
-
-
-
-CObeyFile::CObeyFile(ObeyFileReader& aReader):
-	iRomFileName(0),iRomOddFileName(0),iRomEvenFileName(0),
-	iSRecordFileName(0),iBootFileName(0),iKernelRomName(0),
-	iRomSize(0),iRomLinearBase(0xffffffff),iRomAlign(0),
-	iKernDataRunAddress(0),iDataRunAddress(0),iKernelLimit(0xffffffff),
-	iKernHeapMin(0),iKernHeapMax(0),iSectionStart(0),iSectionPosition(-1),
-	iVersion(0,0,0),iCheckSum(0),iNumberOfPeFiles(0),iNumberOfDataFiles(0),
-	iNumberOfPrimaries(0),iNumberOfExtensions(0),iNumberOfVariants(0),
-	iNumberOfDevices(0),iNumberOfHCRDataFiles (0),
-	//iAllVariantsMask[256],
-	iPrimaries(0),iVariants(0),iExtensions(0),iDevices(0),
-	iLanguage(0),iHardware(0),iTime(0),iMemModel(E_MM_Moving),iPageSize(0x1000),
-	iChunkSize(0x100000),iVirtualAllocSize(0x1000),iKernelModel(ESingleKernel),
-	iCollapseMode(ECollapseNone),iSRecordBase(0),iCurrentSectionNumber(0),
-	iDefaultStackReserve(0),//iTraceMask[KNumTraceMaskWords];iInitialBTraceFilter[8];
-	iInitialBTraceBuffer(0),iInitialBTraceMode(0),iDebugPort(0),
-	iDebugPortParsed(EFalse),iRootDirectory(0),iDllDataTop(0x40000000),
-	iKernelConfigFlags(0),iPagingPolicyParsed(EFalse),iCodePagingPolicyParsed(EFalse),
-	iDataPagingPolicyParsed(EFalse),iPagingOverrideParsed(EFalse),
-	iCodePagingOverrideParsed(EFalse),iDataPagingOverrideParsed(EFalse),
-	/*iPlatSecDisabledCaps(), */iPlatSecDisabledCapsParsed(EFalse),iMaxUnpagedMemSize(0),
-	iReader(aReader),iMissingFiles(0),iLastExecutable(0),iAreaSet(),iFirstFile(0),
-	iCurrentFile(0),iLastVariantFile(0),iFirstDllDataEntry(0),
-	iUpdatedMaxUnpagedMemSize(EFalse),iPatchData(new CPatchDataProcessor)
-	{
-
-	TUint i; 
-	for (i=0; i<256; i++)
-		iAllVariantsMask[i]=0;
-	for (i=0; i<(TUint)KNumTraceMaskWords; i++) 
-		iTraceMask[i]=0;
-	for (i=0; i<sizeof(iInitialBTraceFilter)/sizeof(TUint32); i++)
-		iInitialBTraceFilter[i]=0;	
-	memset(&iPlatSecDisabledCaps,0,sizeof(SCapabilitySet));
-	iNextFilePtrPtr = &iFirstFile;
-	}
-
-CObeyFile::~CObeyFile()
-//
-// Destructor
-//
-	{
-
-	Release();
-	delete [] iRomFileName;
-	if (iRootDirectory)
-		iRootDirectory->Destroy();
-	delete iPatchData;
-	}
-
-void CObeyFile::Release()
-//
-// Free resources not needed after building a ROM
-//
-	{
-	iAreaSet.ReleaseAllAreas();
-
-	delete [] iBootFileName;
-	delete [] iPrimaries;
-	delete [] iVariants;
-	delete [] iExtensions;
-	delete [] iDevices;
-
-	iBootFileName = 0;
-	iPrimaries = 0;
-	iVariants = 0;
-	iExtensions = 0;
-	iDevices = 0;
-	iFirstFile = 0;
-	iNextFilePtrPtr = &iFirstFile;
-	}
-
-TRomBuilderEntry *CObeyFile::FirstFile()
-	{
-	iCurrentFile = iFirstFile;
-	return iCurrentFile;
-	}
-
-TRomBuilderEntry *CObeyFile::NextFile()
-	{
-	iCurrentFile = iCurrentFile ? iCurrentFile->iNext : 0;
-	return iCurrentFile;
-	}
-
-/*
-*Set first link in patchdata linked list
-**/
-void CObeyFile::SetFirstDllDataEntry(DllDataEntry* aDllDataEntry)
-{
-  	iFirstDllDataEntry = aDllDataEntry;
-}
-
-/*
-*Get first link in patchdata linked list
-**/
-DllDataEntry* CObeyFile::GetFirstDllDataEntry() const
-{
-	return iFirstDllDataEntry;
-}
-
-TInt CObeyFile::ProcessKernelRom()
-	{
-	//
-	// First pass through the obey file to set up key variables
-	//
-
-	iReader.Rewind();
-
-	TInt count=0;
-	enum EKeyword keyword;
-	while (iReader.NextLine(1,keyword) != KErrEof)
-		{
-		if (keyword == EKeywordExtensionRom)
-			{
-			if (count==0)
-				return KErrNotFound;		// no kernel ROM, just extension ROMs.
-			break;
-			}
-
-		count++;
-		if (! ProcessKeyword(keyword))
-			return KErrGeneral;
-		}
-
-	if (!GotKeyVariables())
-		return KErrGeneral;
-
-	if (! CreateDefaultArea())
-		return KErrGeneral;
-
-	//
-	// second pass to process the file specifications in the obey file building
-	// up the TRomNode directory structure and the TRomBuilderEntry list
-	//
-	iReader.Rewind();
-
-	iRootDirectory = new TRomNode((TText*)"");
-	iLastExecutable = iRootDirectory;
-
-	TInt align=0;
-	while (iReader.NextLine(2,keyword)!=KErrEof)
-		{
-		if (keyword == EKeywordExtensionRom)
-			break;
-
-		switch (keyword)
-			{
-		case EKeywordSection:
-			if (ParseSection()!=KErrNone)
-				return KErrGeneral;
-			break;
-		case EKeywordAlign:
-			if (iReader.ProcessAlign(align)!=KErrNone)
-				return KErrGeneral;
-			break;
-		case EKeywordHide:
-		case EKeywordAlias:
-		case EKeywordRename:
-			if (!ProcessRenaming(keyword))
-				return KErrGeneral;
-			break;
-		case EKeywordPatchDllData:
-		{
-			// Collect patchdata statements to process at the end
-			StringVector patchDataTokens;
-			SplitPatchDataStatement(patchDataTokens); 
-			iPatchData->AddPatchDataStatement(patchDataTokens);									
-			break;
-		}
-
-		default:
-			if (!ProcessFile(align, keyword))
-				return KErrGeneral;
-			align=0;
-			break;
-			}
-		}
-
-	if( !ParsePatchDllData())
-		return KErrGeneral;
-
-	iReader.Mark();			// ready for processing the extension rom(s)
-
-	if (iMissingFiles!=0)
-		return KErrGeneral;
-	if (iNumberOfDataFiles+iNumberOfPeFiles==0)
-		{
-		Print(EError, "No files specified.\n");
-		return KErrGeneral;
-		}
-	if (!CheckHardwareVariants())
-		return KErrGeneral;
-
-	return KErrNone;
-	}
-
-
-TInt CObeyFile::ParseSection()
-//
-// Process the section keyword
-//
-	{
-	TInt currentLine = iReader.CurrentLine();
-	if (iSectionPosition!=-1)
-		return Print(EError, "Rom already sectioned.  Line %d\n", currentLine);
-	TInt offset;
-	if (Val(offset, iReader.Word(1)))
-		return Print(EError, "Number required for 'section' keyword on line %d\n", currentLine);
-	iSectionStart=offset+iRomLinearBase;
-	if (offset>=iRomSize)
-		return Print(EError, "Sectioned beyond end of Rom.  Line %d\n", currentLine);
-	if (offset&0x0fff)
-		return Print(EError, "Section must be on a 4K boundry.  Line %d\n", currentLine);
-	iSectionPosition=iNumberOfDataFiles+iNumberOfPeFiles;
-	iCurrentSectionNumber++;	
-	return KErrNone;
-	}
-
-TInt CObeyFile::ParseFileAttributes(TRomNode *aNode, TRomBuilderEntry* aFile)
-//
-// Process any inline keywords
-//
-	{
-	TInt currentLine = iReader.CurrentLine();
-	enum EFileAttribute attribute;
-	TInt r=KErrNone;
-	TInt index=3;
-	TText* arg=0;
-
-	while(r==KErrNone)
-		{
-		r=iReader.NextAttribute(index,(aFile!=0),attribute,arg);
-		if (r!=KErrNone)
-			break;
-		switch(attribute)
-			{
-		case EAttributeStackReserve:
-			r=aFile->SetStackReserve(arg);
-			break;
-		case EAttributeStack:
-			r=aFile->SetStackSize(arg);
-			break;
-		case EAttributeReloc:
-			r=aFile->SetRelocationAddress(arg);
-			break;
-		case EAttributeCodeAlign:
-			r=aFile->SetCodeAlignment(arg);
-			break;
-		case EAttributeDataAlign:
-			r=aFile->SetDataAlignment(arg);
-			break;
-		case EAttributeFixed:
-			r=aFile->SetRelocationAddress(NULL);
-			break;
-		case EAttributeAtt:
-			r=aNode->SetAtt(arg);
-			break;
-		case EAttributeUid1:
-			r=aFile->SetUid1(arg);
-			break;
-		case EAttributeUid2:
-			r=aFile->SetUid2(arg);
-			break;
-		case EAttributeUid3:
-			r=aFile->SetUid3(arg);
-			break;
-		case EAttributeHeapMin:
-			r=aFile->SetHeapSizeMin(arg);
-			break;
-		case EAttributeHeapMax:
-			r=aFile->SetHeapSizeMax(arg);
-			break;
-		case EAttributePriority:
-			r=aFile->SetPriority(arg);
-			break;
-		case EAttributePatched:
-			if (iSectionPosition!=-1)
-				return Print(EError, "Not sensible to patch files in top section.  Line %d.\n", currentLine);
-			aFile->iPatched=ETrue;
-			break;
-		case EAttributeKeepIAT:
-			aFile->iOverrideFlags |= KOverrideKeepIAT;
-			break;
-		case EAttributeHidden:
-			if (aFile->Extension())
- 				return Print(EError, "Cannot hide Extension. Line %d.\n", currentLine);
-			aNode->iHidden=ETrue;
-			break;
-		case EAttributeArea:
-			{
-			TRACE(TAREA, Print(EScreen, "Area Attribute: %s\n", arg));
-			const Area* area = aFile->iArea;
-			if (! ParseAreaAttribute(arg, currentLine, area))
-				return KErrGeneral;
-			}
-			break;
-		case EAttributeProcessSpecific:
-			if (!IsValidFilePath(arg))
-				{
-				Print(EError, "Invalid file path for process attribute on line %d\n", currentLine);
-				return KErrGeneral;
-				}
-			r=aFile->SetAttachProcess(arg);
-			break;
-		case EAttributeCapability:
-			r=aFile->SetCapability(arg);
-			break;
-		case EAttributePreferred:
-			aFile->iPreferred = ETrue;
-			break;
-		case EAttributeUnpaged:
-			aFile->iOverrideFlags |= KOverrideCodeUnpaged | KOverrideDataUnpaged;
-			aFile->iOverrideFlags &= ~(KOverrideCodePaged | KOverrideDataPaged);
-			break;
-		case EAttributePaged:
-			aFile->iOverrideFlags |= KOverrideCodePaged | KOverrideDataPaged;
-			aFile->iOverrideFlags &= ~(KOverrideCodeUnpaged | KOverrideDataUnpaged);
-			break;
-		case EAttributeUnpagedCode:
-			aFile->iOverrideFlags |= KOverrideCodeUnpaged;
-			aFile->iOverrideFlags &= ~KOverrideCodePaged;
-			break;
-		case EAttributePagedCode:
-			aFile->iOverrideFlags |= KOverrideCodePaged;
-			aFile->iOverrideFlags &= ~KOverrideCodeUnpaged;
-			break;
-		case EAttributeUnpagedData:
-			aFile->iOverrideFlags |= KOverrideDataUnpaged;
-			aFile->iOverrideFlags &= ~KOverrideDataPaged;
-			break;
-		case EAttributePagedData:
-			aFile->iOverrideFlags |= KOverrideDataPaged;
-			aFile->iOverrideFlags &= ~KOverrideDataUnpaged;
-			break;
-
-		default:
-			return Print(EError, "Unrecognised keyword in file attributes on line %d.\n",currentLine);
-			}
-		}
-
-	// aFile may be null if processing an extension ROM
-	if (aFile && aFile->iPatched && ! aFile->iArea->IsDefault())
-		{
-		return Print(EError, "Relocation to area at line %d forbidden because file is patched\n", currentLine);
-		}
-
-	if (r==KErrEof)
-		return KErrNone;
-	return r;
-	}
-
-TUint32 CObeyFile::ParseVariant()
-	{
-	char* left=iReader.Suffix();
-	if (left == 0 || *left=='\0')
-		return KVariantIndependent;
-	const char* right=left+strlen(left)-1;
-	if (*left=='[' && *right==']')
-		{
-		TUint variant;
-		#ifdef __TOOLS2__
-		string s(left+1);
-		string s2=s.substr(0,right-(left+1));
-		istringstream val(s2,ios::in);
-		#else
-		istrstream val(left+1, right-(left+1));
-		#endif
-		
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-		val >> setbase(0);
-#endif //__MSVCDOTNET__
-
-		val >> variant;
-		if (val.eof() && !val.fail())
-			return variant;
-		}
-//#endif
-	Print(EError,"Syntax error in variant, %s keyword on line %d\n", iReader.Word(0), iReader.CurrentLine());
-	return KVariantIndependent;
-	}
-
-TBool CObeyFile::ProcessFile(TInt aAlign, enum EKeyword aKeyword)
-//
-// Process a parsed line to set up one or more new TRomBuilder entry objects.
-// iWord[0] = the keyword (file, primary or secondary)
-// iWord[1] = the PC pathname
-// iWord[2] = the EPOC pathname
-// iWord[3] = start of the file attributes
-//
-	{
-
-	TUint imageFlags = 0;
-	TUint overrides = 0;
-	TBool isPeFile = ETrue;
-	TBool isResource = EFalse;
-	TBool isNonXIP = EFalse;
-	TUint compression = 0;
-	TBool callEntryPoint = EFalse;
-	TUint hardwareVariant=KVariantIndependent;
-	TBool mustBeInSysBin = EFalse;
-	TBool tryForSysBin = EFalse;
- 	TBool warnFlag = EFalse;
-
-	// do some validation of the keyword
-	TInt currentLine = iReader.CurrentLine();
-
-	switch (aKeyword)
-		{
-	case EKeywordPrimary:
-		imageFlags |= KRomImageFlagPrimary;
-		overrides |= KOverrideCodeUnpaged | KOverrideDataUnpaged;
-		mustBeInSysBin = gPlatSecEnforceSysBin;
- 		warnFlag = gEnableStdPathWarning;		
-		hardwareVariant=ParseVariant();
-		if (iKernelModel==ESingleKernel && !THardwareVariant(hardwareVariant).IsIndependent())
-			{
-			Print(EError,"Kernel must be independent in single kernel ROMs\n");
-			}
-		break;
-
-	case EKeywordSecondary:
-		imageFlags |= KRomImageFlagSecondary;
-		mustBeInSysBin = gPlatSecEnforceSysBin;
- 		warnFlag = gEnableStdPathWarning;
-		hardwareVariant=ParseVariant();
-		break;
-
-	case EKeywordVariant:
-		imageFlags |= KRomImageFlagVariant;
-		overrides |= KOverrideCodeUnpaged | KOverrideDataUnpaged;
-		mustBeInSysBin = gPlatSecEnforceSysBin;
- 		warnFlag = gEnableStdPathWarning;		
-		hardwareVariant=ParseVariant();
-		break;
-
-	case EKeywordExtension:
-		imageFlags |= KRomImageFlagExtension;
-		overrides |= KOverrideCodeUnpaged | KOverrideDataUnpaged;
-		mustBeInSysBin = gPlatSecEnforceSysBin;
- 		warnFlag = gEnableStdPathWarning;
-		hardwareVariant=ParseVariant();
-		break;
-
-	case EKeywordDevice:
-		imageFlags |= KRomImageFlagDevice;
-		overrides |= KOverrideCodeUnpaged | KOverrideDataUnpaged;
-		mustBeInSysBin = gPlatSecEnforceSysBin;
- 		warnFlag = gEnableStdPathWarning;		
-		hardwareVariant=ParseVariant();
-		break;
-
-	case EKeywordExecutableCompressionMethodBytePair:
-		compression=KUidCompressionBytePair;
-		
-	case EKeywordExecutableCompressionMethodInflate:
-	case EKeywordFileCompress:
-		compression = compression ? compression : KUidCompressionDeflate;
-
-	case EKeywordExecutableCompressionMethodNone:	
-	case EKeywordFileUncompress:
-		isNonXIP = ETrue;
-	case EKeywordData:
-		iNumberOfDataFiles++;
-		isPeFile = EFalse;
-		isResource = ETrue;
-		hardwareVariant=ParseVariant();
-		tryForSysBin = gPlatSecEnforceSysBin;
-		break;	 
-
-	case EKeywordHardwareConfigRepositoryData:
-		if(iNumberOfHCRDataFiles){
-			Print(EError,"Multiple keywords '%s' on line %d.\n",iReader.Word(0),currentLine);
-			return EFalse ;
-		}
-		compression = EFalse ; 
-		overrides |= KOverrideCodeUnpaged | KOverrideDataUnpaged | KOverrideHCRData;
-		warnFlag = gEnableStdPathWarning;	 
-		iNumberOfHCRDataFiles ++ ;
-		isPeFile = EFalse;
-		break;
-
-	case EKeywordDll:
-		callEntryPoint = ETrue;
-		// and fall through to handling for "file"
-	
-	case EKeywordFile:
-		{
-			
-		char* nname = NormaliseFileName(iReader.Word(1));
-		strupr(nname);
-		
-		if( gCompressionMethod == 0 || NULL != strstr(nname, ".DLL") || callEntryPoint )
-		{
-			mustBeInSysBin = gPlatSecEnforceSysBin;
- 			warnFlag = gEnableStdPathWarning;			
-			hardwareVariant=ParseVariant();
-		}
-		else 
-		{
-			compression = gCompressionMethod;
-			hardwareVariant=ParseVariant();
-			tryForSysBin = gPlatSecEnforceSysBin;
-		}
-		}
-		break;
-
-	default:
-		Print(EError,"Unexpected keyword '%s' on line %d.\n",iReader.Word(0),currentLine);
-		return EFalse;
-		}
-
-	if (isPeFile)
-		iNumberOfPeFiles++;
-
-	// check the PC file exists
-	char* nname = NormaliseFileName(iReader.Word(1));
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-	ifstream test(nname,ios_base::binary );
-#else //!__MSVCDOTNET__
-	ifstream test(nname,ios::nocreate | ios::binary); 
-#endif //__MSVCDOTNET__
-
-	if (!test.is_open())
-		{
-		Print(EError,"Cannot open file %s for input.\n",iReader.Word(1));
-		if(EKeywordHardwareConfigRepositoryData == aKeyword)
-			{
-			free(nname);
-			return EFalse ;
-			}
-		iMissingFiles++;
-		}
-		
-	if(EKeywordHardwareConfigRepositoryData == aKeyword)
-		{ // check hcr file 
-
-		TUint32 magicWord = 0;
-		test.read(reinterpret_cast<char*>(&magicWord),sizeof(TUint32));
-		if(0x66524348 != magicWord)
-			{
-			Print(EError,"Invalid hardware configuration repository data file %s .\n",iReader.Word(1));
-			test.close();
-			free(nname);
-			return EFalse;
-			}
-
-		}
-	test.close();
-	free(nname);
- 	
-
- 	TBool endOfName=EFalse;
-	TText *epocStartPtr=IsValidFilePath(iReader.Text(2));
-	if (epocStartPtr==NULL)
-		{
-		Print(EError, "Invalid destination path on line %d\n",currentLine);
-		return EFalse;
-		}
-	epocStartPtr = (TText*)NormaliseFileName((const char*)epocStartPtr);
-
-	if(tryForSysBin)
-		{
-		if(strnicmp((const char*)epocStartPtr, "system\\bin\\", 11)==0)
-			mustBeInSysBin = 1;
-		if(strnicmp((const char*)epocStartPtr, "system\\libs\\", 12)==0)
-			mustBeInSysBin = 1;
-		if(strnicmp((const char*)epocStartPtr, "system\\programs\\", 16)==0)
-			mustBeInSysBin = 1;
-		}
-
-	static const char sysBin[] = "sys\\bin\\";
-	static const int sysBinLength = sizeof(sysBin)-1;
-
- 	if (strnicmp((const char*)epocStartPtr, sysBin, sysBinLength)!=0)
- 	{		
- 		if(mustBeInSysBin)
-		{
- 			TInt len = strlen((char*)epocStartPtr);
- 			TInt i = len;
- 			while(--i>=0) if(epocStartPtr[i]=='\\') break;
- 			++i;
- 			char* old = (char*)epocStartPtr;
- 			epocStartPtr = (TText*)malloc(sysBinLength+(len-i)+1);
- 			strcpy((char*)epocStartPtr,sysBin);
- 			strcat((char*)epocStartPtr,old+i);
-
- 			Print(EDiagnostic, "%s moved to %s\n", old, epocStartPtr);
- 			delete old;
-		}
- 		else if (warnFlag)
- 		{
- 			Print(EWarning, "Outside standard path at %s\n", epocStartPtr);
- 		}		
- 	}	
-
-	TText *epocEndPtr=epocStartPtr;
-	AUTO_FREE(epocStartPtr);	
-		
-	TRomNode* dir=iRootDirectory;
-	TRomNode* subDir=0;
-	TRomBuilderEntry *file=0;
-	while (!endOfName)
-		{
-		endOfName = GetNextBitOfFileName(&epocEndPtr);
-		if (endOfName) // file
-			{
-			TRomNode* alreadyExists=dir->FindInDirectory(epocStartPtr,hardwareVariant);
-			if (alreadyExists) // duplicate file
-				{
-				Print(EError, "Duplicate file for %s on line %d\n",iReader.Word(1),iReader.CurrentLine());
-				return EFalse;
-				}
-			file = new TRomBuilderEntry(iReader.Word(1),epocStartPtr);
-			file->iRomImageFlags = imageFlags;
-			file->iResource = isResource;
-			file->iNonXIP = isNonXIP;
-			file->iCompression = compression;
-			
-			file->iArea = iAreaSet.FindByName(AreaSet::KDefaultAreaName);
-			file->iRomSectionNumber = iCurrentSectionNumber;
-			file->iHardwareVariant = hardwareVariant;
-			file->iOverrideFlags |= overrides;
-			if (callEntryPoint)
-				file->SetCallEntryPoint(callEntryPoint);
-			file->iAlignment=aAlign;
-			TUint32 uid;
-			file->iBareName = SplitFileName((const char*)file->iName, uid, file->iVersionInName, file->iVersionPresentInName);
-			assert(uid==0 && !(file->iVersionPresentInName & EUidPresent));
-			if (strchr(file->iBareName, '{') || strchr(file->iBareName, '}'))
-				{
-				Print(EError, "Illegal character in name %s on line %d\n", file->iName, iReader.CurrentLine());
-				delete file;
-				return EFalse;
-				}
-			TRomNode* node=new TRomNode(epocStartPtr, file);
-			if (node==0){
-				delete file;
-				return EFalse;
-			}
-				
-			TInt r=ParseFileAttributes(node, file);
-			if (r!=KErrNone){
-				delete file;
-				delete node;
-				return EFalse;
-			}
-
-			TRACE(TAREA, Print(EScreen, "File %s area '%s'\n", iReader.Word(1), file->iArea->Name()));
-
-			// Apply some specific overrides to the primary
-			if (imageFlags & KRomImageFlagPrimary)
-				{
-				if (file->iCodeAlignment < iPageSize)
-					file->iCodeAlignment = iPageSize;	// Kernel code is at least page aligned
-				file->iHeapSizeMin = iKernHeapMin;
-				file->iHeapSizeMax = iKernHeapMax;
-				file->iOverrideFlags |= KOverrideHeapMin+KOverrideHeapMax;
-				}
-
-			if (!file->iPatched)
-				dir->AddFile(node);	// to ROM directory structure, though possibly hidden
-			if (isPeFile)
-				TRomNode::AddExecutableFile(iLastExecutable, node);
-			
-			AddFile(file);
-			}		 
-		else // directory
-			{
-			subDir = dir->FindInDirectory(epocStartPtr);
-			if (!subDir) // sub directory does not exist
-				{
-				subDir = dir->NewSubDir(epocStartPtr);
-				if (!subDir)
-					return EFalse;
-				}
-			dir=subDir;
-			epocStartPtr = epocEndPtr;
-			}
-		}
-	return ETrue;
-	}
-
-
-void CObeyFile::AddFile(TRomBuilderEntry* aFile)
-	{
-	aFile->iArea->AddFile(aFile);
-
-	*iNextFilePtrPtr = aFile;
-	iNextFilePtrPtr = &(aFile->iNext);
-	}
-
-
-TBool CObeyFile::ProcessRenaming(enum EKeyword aKeyword)
-	{
-	TUint hardwareVariant=ParseVariant();
-
-	// find existing file
-	TBool endOfName=EFalse;
-
-	// Store the current name and new name to maintain renamed file map
-	String currentName=iReader.Word(1);
-	String newName=iReader.Word(2);
-
-	TText *epocStartPtr=IsValidFilePath(iReader.Text(1));
-	if (epocStartPtr==NULL)
-		{
-		Print(EError, "Invalid source path on line %d\n",iReader.CurrentLine());
-		return EFalse;
-		}
-	epocStartPtr = (TText*)NormaliseFileName((const char*)epocStartPtr);
-	TText *epocEndPtr=epocStartPtr;
-	AUTO_FREE(epocStartPtr);
-
-	char saved_srcname[257];
-	strcpy(saved_srcname, iReader.Word(1));
-
-	TRomNode* dir=iRootDirectory;
-	TRomNode* existingFile=0;
-	while (!endOfName)
-		{
-		endOfName = GetNextBitOfFileName(&epocEndPtr);
-		if (endOfName) // file
-			{
-			existingFile=dir->FindInDirectory(epocStartPtr,hardwareVariant);
-			if (existingFile)
-				{
-				TInt fileCount=0;
-				TInt dirCount=0;
-				existingFile->CountDirectory(fileCount, dirCount);
-				if (dirCount != 0 || fileCount != 0)
-					{
-					Print(EError, "Keyword %s not applicable to directories - line %d\n",iReader.Word(0),iReader.CurrentLine());
-					return EFalse;
-					}
-				}
-			}
-		else // directory
-			{
-			TRomNode* subDir = dir->FindInDirectory(epocStartPtr);
-			if (!subDir) // sub directory does not exist
-				break;
-			dir=subDir;
-			epocStartPtr = epocEndPtr;
-			}
-		}
-	if (aKeyword == EKeywordHide)
-		{
-		if (!existingFile)
-			{
-			Print(EWarning, "Hiding non-existent file %s on line %d\n", 
-				saved_srcname, iReader.CurrentLine());
-			// Just a warning, as we've achieved the right overall effect.
-			}
-		else
-			{
-			existingFile->iHidden = ETrue;
-			}
-		return ETrue;
-		}
-
-	if (!existingFile)
-		{
-		Print(EError, "Can't %s non-existent source file %s on line %d\n",
-			iReader.Word(0), saved_srcname, iReader.CurrentLine());
-		return EFalse;
-		}
-
-	epocStartPtr=IsValidFilePath(iReader.Text(2));
-	epocEndPtr=epocStartPtr;
-	endOfName=EFalse;
-	if (epocStartPtr==NULL)
-		{
-		Print(EError, "Invalid destination path on line %d\n",iReader.CurrentLine());
-		return EFalse;
-		}
-
-	TRomNode* newdir=iRootDirectory;
-	while (!endOfName)
-		{
-		endOfName = GetNextBitOfFileName(&epocEndPtr);
-		if (endOfName) // file
-			{
-			TRomNode* alreadyExists=newdir->FindInDirectory(epocStartPtr,existingFile->HardwareVariant());
-			if (alreadyExists) // duplicate file
-				{
-				Print(EError, "Duplicate file for %s on line %d\n",saved_srcname,iReader.CurrentLine());
-				return EFalse;
-				}
-			}
-		else // directory
-			{
-			TRomNode* subDir = newdir->FindInDirectory(epocStartPtr);
-			if (!subDir) // sub directory does not exist
-				{
-				subDir = newdir->NewSubDir(epocStartPtr);
-				if (!subDir)
-					return EFalse;
-				}
-			newdir=subDir;
-			epocStartPtr = epocEndPtr;
-			}
-		}
-
-	if (aKeyword == EKeywordRename)
-		{
-		// rename => remove existingFile and insert into tree at new place
-		// has no effect on the iNextExecutable or iNextNodeForSameFile links
-
-		TInt r=ParseFileAttributes(existingFile, existingFile->iRomFile->iRbEntry);
-		if (r!=KErrNone)
-			return EFalse;
-		r = existingFile->Rename(dir, newdir, epocStartPtr);
-		if (r==KErrBadName)
-			{
-			Print(EError, "Bad name %s at line %d\n", epocStartPtr, iReader.CurrentLine());
-			return EFalse;
-			}
-		else if (r==KErrArgument)
-			{
-			Print(EError, "Version in name %s does not match version in file header at line %d\n", epocStartPtr, iReader.CurrentLine());
-			return EFalse;
-			}
-		// Store the current and new name of file in the renamed file map.
-		iPatchData->AddToRenamedFileMap(currentName, newName);
-		return ETrue;
-		}
-	
-	// alias => create new TRomNode entry and insert into tree
-
-	TRomNode* node = new TRomNode(epocStartPtr, existingFile);
-	if (node == 0)
-		{
-		Print(EError, "Out of memory\n");
-		return EFalse;
-		}
-
-	TInt r = node->Alias(existingFile, iLastExecutable);
-	if (r==KErrBadName)
-		{
-		Print(EError, "Bad name %s at line %d\n", epocStartPtr, iReader.CurrentLine());
-		return EFalse;
-		}
-	else if (r==KErrArgument)
-		{
-		Print(EError, "Version in name %s does not match version in file header at line %d\n", epocStartPtr, iReader.CurrentLine());
-		return EFalse;
-		}
-	r=ParseFileAttributes(node, 0);
-	if (r!=KErrNone)
-		return EFalse;
-
-	newdir->AddFile(node);	// to ROM directory structure, though possibly hidden
-
-	return ETrue;
-	}
-
-
-TInt ParsePagingPolicy(const char* policy)
-	{
-	if(stricmp(policy,"NOPAGING")==0)
-		return EKernelConfigPagingPolicyNoPaging;
-	else if (stricmp(policy,"ALWAYSPAGE")==0)
-		return EKernelConfigPagingPolicyAlwaysPage;
-	else if(stricmp(policy,"DEFAULTUNPAGED")==0)
-		return EKernelConfigPagingPolicyDefaultUnpaged;
-	else if(stricmp(policy,"DEFAULTPAGED")==0)
-		return EKernelConfigPagingPolicyDefaultPaged;
-	return KErrArgument;
-	}
-
-
-TBool CObeyFile::ProcessKeyword(enum EKeyword aKeyword)
-	{
-	TUint hardwareVariant=KVariantIndependent;
-
-	#ifdef __TOOLS2__
-	istringstream val(iReader.Word(1));
-	#else
-	istrstream val(iReader.Word(1),strlen(iReader.Word(1)));
-	#endif
-
-#if defined(__MSVCDOTNET__) || defined (__TOOLS2__)
-	val >> setbase(0);
-#endif //__MSVCDOTNET__
-
-	TBool success = ETrue;
-
-	switch (aKeyword)
-		{
-	case EKeywordUnicode:
-		Unicode=ETrue;
-		break;
-	case EKeywordAscii:
-		Unicode=EFalse;
-		break;
-
-	case EKeywordSingleKernel:
-		iKernelModel=ESingleKernel;
-		break;
-	case EKeywordMultiKernel:
-		iKernelModel=EMultipleKernels;
-		break;
-
-	case EKeywordBootBinary:
-		iReader.CopyWord(1, iBootFileName);
-		break;
-	case EKeywordRomName:
-		iReader.CopyWord(1, iRomFileName);
-		break;
-	case EKeywordRomNameOdd:
-		iReader.CopyWord(1, iRomOddFileName);
-		break;
-	case EKeywordRomNameEven:
-		iReader.CopyWord(1, iRomEvenFileName);
-		break;
-	case EKeywordSRecordFileName:
-		iReader.CopyWord(1, iSRecordFileName);
-		break;
-
-	case EKeywordRomLinearBase:
-		val >> iRomLinearBase;
-		break;
-	case EKeywordRomSize:
-		val >> iRomSize;
-		break;
-	case EKeywordRomAlign:
-		val >> iRomAlign;
-		break;
-	case EKeywordKernelDataAddress:
-		val >> iKernDataRunAddress;
-		break;
-	case EKeywordKernelHeapMin:
-		val >> iKernHeapMin;
-		break;
-	case EKeywordKernelHeapMax:
-		val >> iKernHeapMax;
-		break;
-	case EKeywordDataAddress:
-		val >> iDataRunAddress;
-		break;
-	case EKeywordDefaultStackReserve:
-		val >> iDefaultStackReserve;
-		break;
-	case EKeywordVersion:
-		val >> iVersion;
-		break;
-	case EKeywordSRecordBase:
-		val >> iSRecordBase;
-		break;
-	case EKeywordRomChecksum:
-		val >> iCheckSum;
-		break;
-	case EKeywordHardware:
-		val >> iHardware;
-		break;
-	case EKeywordLanguages:
-		iReader.ProcessLanguages(iLanguage);
-		break;
-	case EKeywordTime:
-		iReader.ProcessTime(iTime);
-		break;
-	case EKeywordDllDataTop:
-		val >> iDllDataTop;
-		break;
-
-	case EKeywordMemModel:
-		{
-		char* arg1=iReader.Word(1);
-		char* arg2=iReader.Word(2);
-		char* arg3=iReader.Word(3);
-		char* arg4=iReader.Word(4);
-		if (strnicmp(arg1, "moving", 6)==0)
-			iMemModel=E_MM_Moving;
-		else if (strnicmp(arg1, "direct", 6)==0)
-			iMemModel=E_MM_Direct;
-		else if (strnicmp(arg1, "multiple", 8)==0)
-			iMemModel=E_MM_Multiple;
-		else if (strnicmp(arg1, "flexible", 8)==0)
-			iMemModel=E_MM_Flexible;
-		else
-			{
-			Print(EError, "Unknown memory model specified\n");
-			success = EFalse;
-			}
-		if (strlen(arg2))
-			{
-			#ifdef __TOOLS2__
-			istringstream arg2s(arg2);
-			#else
-			istrstream arg2s(arg2,strlen(arg2));
-			#endif
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-			arg2s >> setbase(0);
-#endif //__MSVCDOTNET__
-
-			arg2s >> iChunkSize;
-			}
-		if (iMemModel!=E_MM_Direct && strlen(arg3))
-			{
-				#ifdef __TOOLS2__
-			istringstream arg3s(arg3);
-			#else
-			istrstream arg3s(arg3,strlen(arg3));
-			#endif
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-			arg3s >> setbase(0);
-#endif //__MSVCDOTNET__
-
-			arg3s >> iPageSize;
-			}
-		else if (iMemModel==E_MM_Direct)
-			iPageSize=iChunkSize;
-		if (iMemModel!=E_MM_Direct && strlen(arg4))
-			{
-			#ifdef __TOOLS2__
-			istringstream arg4s(arg4);
-			#else
-			istrstream arg4s(arg4,strlen(arg4));
-			#endif
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-			arg4s >> setbase(0);
-#endif //__MSVCDOTNET__
-
-			arg4s >> iVirtualAllocSize;
-			}
-		else
-			iVirtualAllocSize = iPageSize;
-		
-		break;
-		}
-	case EKeywordNoWrapper:
-		if (gHeaderType<0)
-			gHeaderType=0;
-		break;
-	case EKeywordEpocWrapper:
-		if (gHeaderType<0)
-			gHeaderType=1;
-		break;
-	case EKeywordCoffWrapper:
-		if (gHeaderType<0)
-			gHeaderType=2;
-		break;
-
-	case EKeywordPlatSecEnforcement:
-		ParseBoolArg(gPlatSecEnforcement,iReader.Word(1));
-		if(gPlatSecEnforcement)
-			iKernelConfigFlags |= EKernelConfigPlatSecEnforcement;
-		else
-			iKernelConfigFlags &= ~EKernelConfigPlatSecEnforcement;
-		break;
-	case EKeywordPlatSecDiagnostics:
-		ParseBoolArg(gPlatSecDiagnostics,iReader.Word(1));
-		if(gPlatSecDiagnostics)
-			iKernelConfigFlags |= EKernelConfigPlatSecDiagnostics;
-		else
-			iKernelConfigFlags &= ~EKernelConfigPlatSecDiagnostics;
-		break;
-	case EKeywordPlatSecProcessIsolation:
-		{
-		TInt processIsolation;
-		ParseBoolArg(processIsolation,iReader.Word(1));
-		if(processIsolation)
-			iKernelConfigFlags |= EKernelConfigPlatSecProcessIsolation;
-		else
-			iKernelConfigFlags &= ~EKernelConfigPlatSecProcessIsolation;
-		break;
-		}
-	case EKeywordPlatSecEnforceSysBin:
-		{
-		ParseBoolArg(gPlatSecEnforceSysBin,iReader.Word(1));
-		if(gPlatSecEnforceSysBin)
-			iKernelConfigFlags |= EKernelConfigPlatSecEnforceSysBin;
-		else
-			iKernelConfigFlags &= ~EKernelConfigPlatSecEnforceSysBin;
-		break;
-		}
-	case EKeywordPlatSecDisabledCaps:
-		if(iPlatSecDisabledCapsParsed)
-			Print(EWarning, "PlatSecDisabledCaps redefined - previous values lost\n");
-		{
-		ParseCapabilitiesArg(iPlatSecDisabledCaps, iReader.Word(1));
-		gPlatSecDisabledCaps = iPlatSecDisabledCaps;
-		iPlatSecDisabledCapsParsed=ETrue;
-		}
-		break;
-	case EKeywordPagingPolicy:
-		{
-		if(iPagingPolicyParsed)
-			Print(EWarning, "PagingPolicy redefined - previous PagingPolicy values lost\n");
-		if(iDataPagingPolicyParsed)
-			Print(EWarning, "PagingPolicy defined - previous DataPagingPolicy values lost\n");
-		if(iCodePagingPolicyParsed)
-			Print(EWarning, "PagingPolicy defined - previous DataPagingPolicy values lost\n");
-		iPagingPolicyParsed = true;
-		iKernelConfigFlags &= ~(EKernelConfigCodePagingPolicyMask|EKernelConfigDataPagingPolicyMask);
-		TInt policy = ParsePagingPolicy(iReader.Word(1));
-		if(policy<0)
-			{
-			Print(EError,"Unrecognised option for PAGINGPOLICY keyword\n");
-			success = false;
-			}
-		else 	{
-#ifndef SYMBIAN_WRITABLE_DATA_PAGING
-			if ((policy != EKernelConfigPagingPolicyNoPaging) && (iMemModel == E_MM_Flexible))
-				Print(EWarning, "SYMBIAN_WRITABLE_DATA_PAPING is not defined. Writable data paging is not warranted on this version of Symbian.");
-#endif
-			iKernelConfigFlags |= policy << EKernelConfigCodePagingPolicyShift;
-			iKernelConfigFlags |= policy << EKernelConfigDataPagingPolicyShift;
-			}
-		}
-		break;
-	case EKeywordCodePagingPolicy:
-		{
-		if(iCodePagingPolicyParsed)
-			Print(EWarning, "CodePagingPolicy redefined - previous CodePagingPolicy values lost\n");
-		if(iPagingPolicyParsed)
-			Print(EWarning, "CodePagingPolicy defined - previous PagingPolicy values lost\n");
-		iCodePagingPolicyParsed = true;
-		iKernelConfigFlags &= ~EKernelConfigCodePagingPolicyMask;
-		TInt policy = ParsePagingPolicy(iReader.Word(1));
-		if(policy<0)
-			{
-			Print(EError,"Unrecognised option for CODEPAGINGPOLICY keyword\n");
-			success = false;
-			}
-		else
-			iKernelConfigFlags |= policy << EKernelConfigCodePagingPolicyShift;
-		}
-		break;
-	case EKeywordDataPagingPolicy:
-		{
-		if(iDataPagingPolicyParsed)
-			Print(EWarning, "DataPagingPolicy redefined - previous DataPagingPolicy values lost\n");
-		if(iPagingPolicyParsed)
-			Print(EWarning, "DataPagingPolicy defined - previous PagingPolicy values lost\n");
-		iDataPagingPolicyParsed = true;
-		iKernelConfigFlags &= ~EKernelConfigDataPagingPolicyMask;
-		TInt policy = ParsePagingPolicy(iReader.Word(1));
-		if(policy<0)
-			{
-			Print(EError,"Unrecognised option for DATAPAGINGPOLICY keyword\n");
-			success = false;
-			}
-		else
-#ifndef SYMBIAN_WRITABLE_DATA_PAGING
-			if ((policy != EKernelConfigPagingPolicyNoPaging) && (iMemModel == E_MM_Flexible))
-				Print(EWarning, "SYMBIAN_WRITABLE_DATA_PAPING is not defined. Writable data paging is not warranted on this version of Symbian.");
-#endif
-			iKernelConfigFlags |= policy << EKernelConfigDataPagingPolicyShift;
-		}
-		break;
-	case EKeywordPagingOverride:
-		{
-		if(iPagingOverrideParsed)
-			Print(EWarning, "PagingOverride redefined - previous PagingOverride values lost\n");
-		if(iCodePagingOverrideParsed)
-			Print(EWarning, "PagingOverride defined - previous CodePagingOverride valus lost\n");
-		if(iDataPagingOverrideParsed)
-			Print(EWarning, "PagingOverride defined - previous DataPagingOverride values lostn");
-		iPagingOverrideParsed = true;
-		TInt policy = ParsePagingPolicy(iReader.Word(1));
-		if(policy<0)
-			{
-			Print(EError,"Unrecognised option for PAGINGOVERRIDE keyword\n");
-			success = false;
-			}
-		else
-			{
-			gCodePagingOverride = policy;
-			gDataPagingOverride = policy;
-			}
-		}
-		break;
-	case EKeywordCodePagingOverride:
-		{
-		if(iCodePagingOverrideParsed)
-			Print(EWarning, "CodePagingOverride redefined - previous CodePagingOverride values lost\n");
-		if(iPagingOverrideParsed)
-			Print(EWarning, "CodePagingOverride defined - previous PagingOverride values lost\n");
-		iCodePagingOverrideParsed = true;
-		TInt policy = ParsePagingPolicy(iReader.Word(1));
-		if(policy<0)
-			{
-			Print(EError,"Unrecognised option for CODEPAGINGOVERRIDE keyword\n");
-			success = false;
-			}
-		else
-			gCodePagingOverride = policy;
-		}
-		break;
-	case EKeywordDataPagingOverride:
-		{
-		if(iDataPagingOverrideParsed)
-			Print(EWarning, "DataPagingOverride redefined - previous DataPagingOverride values lost\n");
-		if(iPagingOverrideParsed)
-			Print(EWarning, "DataPagingOverride defined - previous PagingOverride values lost\n");
-		iDataPagingOverrideParsed = true;
-		TInt policy = ParsePagingPolicy(iReader.Word(1));
-		if(policy<0)
-			{
-			Print(EError,"Unrecognised option for DATAPAGINGOVERRIDE keyword\n");
-			success = false;
-			}
-		else
-			gDataPagingOverride = policy;
-		}
-		break;
-	case EKeywordDemandPagingConfig:
-		{
-		memset(&gDemandPagingConfig,0,sizeof(gDemandPagingConfig));
-		val >> gDemandPagingConfig.iMinPages;
-		if(strlen(iReader.Word(2)))
-			{
-			#ifdef __TOOLS2__
-			istringstream val(iReader.Word(2));
-			#else
-			istrstream val(iReader.Word(2),strlen(iReader.Word(2)));
-		    #endif
-			val >> gDemandPagingConfig.iMaxPages;
-			if(strlen(iReader.Word(3)))
-				{
-				#ifdef __TOOLS2__
-				istringstream val(iReader.Word(3));
-				#else
-				istrstream val(iReader.Word(3),strlen(iReader.Word(3)));
-				#endif
-				val >> gDemandPagingConfig.iYoungOldRatio;
-				for(int i=0; i<=2; i++)
-					{
-					if(!strlen(iReader.Word(4+i)))
-						break;
-					#ifdef __TOOLS2__
-					istringstream val(iReader.Word(4+i));
-					#else
-					istrstream val(iReader.Word(4+i),strlen(iReader.Word(4+i)));
-					#endif
-					val >> gDemandPagingConfig.iSpare[i];
-					}
-				}
-			}
-		if(gDemandPagingConfig.iMaxPages && gDemandPagingConfig.iMaxPages<gDemandPagingConfig.iMinPages)
-			{
-			Print(EError,"DemandPagingConfig maxPages must be >= minPages\n");
-			success = EFalse;
-			break;
-			}
-		}
-		break;
-	case EKeywordPagedRom:
-		gPagedRom = ETrue;
-		break;
-
-	case EKeywordTrace:
-		val >> TraceMask;
-		break;
-
-	case EKeywordKernelTrace:
-		{
-		TInt i;
-		val >> iTraceMask[0];
-		i=1;
-		while(strlen(iReader.Word(i+1)) && i<KNumTraceMaskWords)
-			{
-			#ifdef __TOOLS2__
-			istringstream val(iReader.Word(i+1));
-			#else
-			istrstream val(iReader.Word(i+1),strlen(iReader.Word(i+1)));
-			#endif
-			#if defined(__MSVCDOTNET__) || defined (__TOOLS2__)
- 				val >> setbase(0);
-			#endif
-			val >> iTraceMask[i];
-			++i;
-			}
-		}
-		break;
-
-	case EKeywordBTrace:
-		{
-		TUint i; 
-		val >> iInitialBTraceFilter[0];
-		i=1;
-		while(strlen(iReader.Word(i+1)) && i<sizeof(iInitialBTraceFilter)/sizeof(TUint32))
-			{
-			#ifdef __TOOLS2__
-			istringstream val(iReader.Word(i+1));
-			#else
-			istrstream val(iReader.Word(i+1),strlen(iReader.Word(i+1)));
-			#endif
-			#if defined(__MSVCDOTNET__) || defined (__TOOLS2__)
- 				val >> setbase(0);
-			#endif
-			val >> iInitialBTraceFilter[i];
-			++i;
-			}
-		}
-		break;
-
-	case EKeywordBTraceMode:
-		val >> iInitialBTraceMode;
-		break;
-
-	case EKeywordBTraceBuffer:
-		val >> iInitialBTraceBuffer;
-		break;
-
-	case EKeywordDebugPort:
-		if (iDebugPortParsed)
-			Print(EWarning, "DEBUGPORT redefined - previous value lost\n");
-		val >> iDebugPort;
-		iDebugPortParsed = ETrue;
-		break;
-
-	case EKeywordCompress:
-		gEnableCompress=ETrue; // Set ROM Compression on.
-		break;
-
-	case EKeywordCollapse:
-		if (strnicmp(iReader.Word(1), "arm", 3)!=0 || strnicmp(iReader.Word(2), "gcc", 3)!=0)
-			{
-			Print(EWarning, "COLLAPSE only supported for ARM and GCC - keyword ignored\n");
-			}
-		else
-			{
-			TInt cm;
-			#ifdef __TOOLS2__
-			istringstream cmval(iReader.Word(3));
-			#else
-			istrstream cmval(iReader.Word(3),strlen(iReader.Word(3)));
-			#endif
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-			cmval >> setbase(0);
-#endif //__MSVCDOTNET__
-
-			cmval>>cm;
-			if (cm<0 || cm>ECollapseAllChainBranches)
-				{
-				Print(EWarning, "COLLAPSE mode unrecognised - keyword ignored\n");
-				}
-			else
-				iCollapseMode=cm;
-			}
-		break;
-
-	case EKeywordPrimary:
-		iNumberOfPrimaries++;
-		break;
-	case EKeywordVariant:
-		hardwareVariant=ParseVariant();
-		if (THardwareVariant(hardwareVariant).IsVariant())
-			{
-			iNumberOfVariants++;
-			TUint layer=THardwareVariant(hardwareVariant).Layer();
-			TUint vmask=THardwareVariant(hardwareVariant).VMask();
-			iAllVariantsMask[layer] |= vmask;
-			}
-		else
-			{
-			Print(EError,"Variant DLLs must belong to variant layer - line %d\n", iReader.CurrentLine());
-			break;
-			}
-
-		break;
-	case EKeywordExtension:
-		iNumberOfExtensions++;
-		break;
-	case EKeywordDevice:
-		iNumberOfDevices++;
-		break;
-
-	case EKeywordKernelRomName:
-		Print(EError,"Keyword '%s' only valid in extension ROMs - line %d\n", iReader.Word(0), iReader.CurrentLine());
-		break;
-
-	case EKeywordArea:
-		if(! ParseAreaKeyword())
-			success = EFalse;
-		break;
-
-	case EKeywordExecutableCompressionMethodNone:
-		gCompressionMethod = 0;
-		break;
-		
-	case EKeywordExecutableCompressionMethodInflate:
-		gCompressionMethod = KUidCompressionDeflate;
-		break;
-		
-	case EKeywordExecutableCompressionMethodBytePair:
-		gCompressionMethod = KUidCompressionBytePair;
-		break;
-		
-	case EKeywordKernelConfig:
-		{
-		TInt bit, setTo;
-		val >> bit;
-		if(bit<0 || bit>31)
-			{
-			Print(EError,"KernelConfig bit must be between 0 and 31\n");
-			success = EFalse;
-			break;
-			}
-		if(ParseBoolArg(setTo,iReader.Word(2))!=KErrNone)
-			{
-			success = EFalse;
-			break;
-			}
-		if(setTo)
-			iKernelConfigFlags |= 1<<bit;
-		else
-			iKernelConfigFlags &= ~(1<<bit);
-		break;
-		}
-		
-	case EKeywordMaxUnpagedMemSize:
-		{
-		TInt unpagedSize = -1;
-		val >> unpagedSize;
-			
-		if (!val || unpagedSize < 0)
-			{
-			Print(EWarning, "Invalid value of MaxUnpagedSize (0 to 0x7FFFFFFF) - value ignored\n");
-			break;
-			}
-			
-		iMaxUnpagedMemSize = unpagedSize;
-		
-		if(iUpdatedMaxUnpagedMemSize)
-			{
-			Print(EWarning, "MaxUnpagedSize redefined - previous values lost\n");
-			}
-		else
-			{
-			iUpdatedMaxUnpagedMemSize = ETrue;
-			}
-		
-		break;
-		}
-
-	default:
-		// unexpected keyword iReader.Word(0)
-		break;
-		}
-
-	return success;
-	}
-
-TBool CObeyFile::GotKeyVariables()
-//
-// Checks that the obeyfile has supplied enough variables to continue
-//
-   	{
-
-	TBool retVal=ETrue;
-
-	// Mandatory keywords
-
-	if (iRomFileName==0)
-		{
-		Print(EAlways,"The name of the ROM has not been supplied.\n");
-		Print(EAlways,"Use the keyword \"romname\".\n");
-		retVal = EFalse;
-		}
-	if (iBootFileName==0)
-		{
-		Print(EAlways,"The name of the bootstrap binary has not been supplied.\n");
-		Print(EAlways,"Use the keyword \"bootbinary\".\n");
-		retVal = EFalse;
-		}
-	if (iRomLinearBase==0xFFFFFFFF)
-		{
-		Print(EAlways,"The base linear address of the ROM has not been supplied.\n");
-		Print(EAlways,"Use the keyword \"romlinearbase\".\n");
-		retVal = EFalse;
-		}
-	if (iRomSize==0)
-		{
-		Print(EAlways,"The size of the ROM has not been supplied.\n");
-		Print(EAlways,"Use the keyword \"romsize\".\n");
-		retVal = EFalse;
-		}
-	if (iKernDataRunAddress==0)
-		{
-		Print(EAlways,"The address for the kernel's data section has not been supplied.\n");
-		Print(EAlways,"Use the keyword \"kerneldataaddress\".\n");
-		retVal = EFalse;
-		}
-
-	// Validation
-	if (iNumberOfPrimaries>1 && iKernelModel==ESingleKernel)
-		{
-		Print(EError,"More than one primary in single-kernel ROM\n");
-		retVal = EFalse;
-		}
-	if (iNumberOfPrimaries==0)
-		{
-		Print(EError,"No primary file specified\n");
-		retVal = EFalse;
-		}
-	if (iNumberOfVariants==0)
-		{
-		Print(EError,"No variants specified\n");
-		retVal = EFalse;
-		}
-	if(iNumberOfHCRDataFiles > 1)
-		{
-		Print(EError,"More than one hcr data files in ROM.\n");
-		retVal = EFalse ;
-		}
-	// Warn about enabling data paging on OS versions where's it's not officially supported
-#ifndef SYMBIAN_WRITABLE_DATA_PAGING
-	if (iMemModel == E_MM_Flexible &&
-		(iKernelConfigFlags & EKernelConfigDataPagingPolicyMask) != EKernelConfigDataPagingPolicyNoPaging)
-		{
-		Print(EWarning, "Writable data paging is not warranted on this version of Symbian OS.");
-		}
-#endif
-	
-	// Apply defaults as necessary
-	TheRomLinearAddress=iRomLinearBase;
-
-	if (iDataRunAddress==0)
-		{
-		iDataRunAddress=0x400000;
-		Print(EWarning,"The address for a running ROM app's data section (keyword \"dataaddress\") has not been supplied.\n");
-		Print(EWarning,"Will use the default value of 0x%0x.\n", iDataRunAddress);
-		retVal = EFalse;
-		}
-	if (iRomAlign==0)
-		{
-		iRomAlign=0x1000;
-		Print(EWarning,"The ROM section alignment (keyword \"romalign\") has not been supplied.\n");
-		Print(EWarning,"Will use the default value of 0x%0x.\n", iRomAlign);
-		}
-	if (iRomAlign&0x3)
-		{
-		Print(EWarning, "Rounding rom alignment to multiple of 4.\n");
-		iRomAlign=(iRomAlign+0x3)&0xfffffffc;
-		}
-	if (iKernHeapMin==0)
-	 	{
-	 	iKernHeapMin=0x10000;
-		Print(EWarning,"The kernel heap min size (keyword \"kernelheapmin\") has not been supplied.\n");
-		Print(EWarning,"Will use the default value of 0x%0x.\n", iKernHeapMin);
-		}
-	if (iKernHeapMax==0)
-	 	{
-	 	iKernHeapMax=0x100000;
-		Print(EWarning,"The kernel heap max size (keyword \"kernelheapmax\") has not been supplied.\n");
-		Print(EWarning,"Will use the default value of 0x%0x.\n", iKernHeapMax);
-		}
-
-	if (iTime==0)
-		{
-		Print(ELog, "No timestamp specified. Using current time...\n");
-		ObeyFileReader::TimeNow(iTime);
-		}
-
-	Print(ELog, "\nCreating Rom image %s\n", iRomFileName);
-	Print(ELog, "MemModel: %1d\nChunkSize: %08x\nPageSize: %08x\n", iMemModel, iChunkSize, iPageSize);
-	return retVal;
-	}
-
-
-TText *CObeyFile::IsValidFilePath(TText *aPath)
-//
-// Check the path is valid
-//
-	{
-	// skip leading "\"
-	if (*aPath=='\\')
-		aPath++;
-	if (*aPath==0)
-		return NULL; // file ends in a backslash
-
-	TText *p=aPath;
-	TInt len=0;
-	FOREVER
-		{
-		if (*p==0)
-			return (len ? aPath : NULL);
-		if (*p=='\\')
-			{
-			if (len==0)
-				return NULL;
-			len=0;
-			}
-		len++;
-		p++;
-		}
-	}
-
-TBool CObeyFile::GetNextBitOfFileName(TText **epocEndPtr)
-//
-// Move the end pointer past the next directory separator, replacing it with 0
-//
-	{
-	while (**epocEndPtr != '\\') // until reach the directory separator
-		{
-		if (**epocEndPtr==0) // if reach end of string, return TRUE, it's the filename
-			return ETrue;
-		(*epocEndPtr)++;
-		}
-	**epocEndPtr=0; // overwrite the directory separator with a 0
-	(*epocEndPtr)++; // point past the 0 ready for the next one
-	return EFalse;
-	}
-
-
-TBool CObeyFile::CheckHardwareVariants()
-	{
-	iPrimaries=new TRomBuilderEntry*[iNumberOfPrimaries];
-	iVariants=new TRomBuilderEntry*[iNumberOfVariants];
-	THardwareVariant* primaryHwVariants=new THardwareVariant[iNumberOfPrimaries];
-	TInt nVar=0;
-	TRomBuilderEntry* current=FirstFile();
-	THardwareVariant* variantHwVariants=new THardwareVariant[iNumberOfVariants];
-	while(current)
-		{
-		if (current->Variant())
-			{
-			TInt i;
-			for(i=0; i<nVar; i++)
-				{
-				if (!current->iHardwareVariant.MutuallyExclusive(variantHwVariants[i]))
-					{
-					delete[] variantHwVariants;
-					delete[] primaryHwVariants;
-					Print(EError,"Variants not mutually exclusive\n");
-					return EFalse;
-					}
-				}
-			iVariants[nVar]=current;
-			variantHwVariants[nVar++]=current->iHardwareVariant;
-			}
-		current=NextFile();
-		}
-	delete[] variantHwVariants;
-	nVar=0;
-	current=FirstFile();
-	while(current)
-		{
-		TInt i;
-		for (i=0; i<iNumberOfVariants; i++)
-			{
-			if (iVariants[i]->iHardwareVariant<=current->iHardwareVariant)
-				break;
-			}
-		if (i==iNumberOfVariants)
-			{
-			Print(EError,"File %s[%08x] does not correspond to any variant\n",
-									current->iName,TUint(current->iHardwareVariant));
-			delete[] primaryHwVariants;
-			return EFalse;
-			}
-		if (current->Primary())
-			{
-			for(i=0; i<nVar; i++)
-				{
-				if (!current->iHardwareVariant.MutuallyExclusive(primaryHwVariants[i]))
-					{
-					delete[] primaryHwVariants;
-					Print(EError,"Primaries not mutually exclusive\n");
-					return EFalse;
-					}
-				}
-			iPrimaries[nVar]=current;
-			primaryHwVariants[nVar++]=current->iHardwareVariant;
-			}
-		current=NextFile();
-		}
-	delete[] primaryHwVariants;
-	if (iNumberOfExtensions)
-		{
-		nVar=0;
-		iExtensions=new TRomBuilderEntry*[iNumberOfExtensions];
-		TRomBuilderEntry* current=FirstFile();
-		while(current)
-			{
-			if (current->Extension())
-				{
-				if (current->iHardwareVariant.IsVariant())
-					{
-					TUint layer=current->iHardwareVariant.Layer();
-					TUint vmask=current->iHardwareVariant.VMask();
-					if ((iAllVariantsMask[layer]&vmask)==0)
-						{
-						Print(EError,"Variant-layer extension %s has no corresponding variant DLL\n",current->iName);
-						return EFalse;
-						}
-					}
-				iExtensions[nVar++]=current;
-				}
-			current=NextFile();
-			}
-		}
-	if (iNumberOfDevices)
-		{
-		nVar=0;
-		iDevices=new TRomBuilderEntry*[iNumberOfDevices];
-		TRomBuilderEntry* current=FirstFile();
-		while(current)
-			{
-			if (current->Device())
-				{
-				if (current->iHardwareVariant.IsVariant())
-					{
-					TUint layer=current->iHardwareVariant.Layer();
-					TUint vmask=current->iHardwareVariant.VMask();
-					if ((iAllVariantsMask[layer]&vmask)==0)
-						{
-						Print(EError,"Variant-layer device %s has no corresponding variant DLL\n",current->iName);
-						return EFalse;
-						}
-					}
-				iDevices[nVar++]=current;
-				}
-			current=NextFile();
-			}
-		}
-	NumberOfVariants=iNumberOfVariants;
-	return ETrue;
-	}
-
-
-TInt CObeyFile::ProcessExtensionRom(MRomImage*& aKernelRom)
-	{
-	//
-	// First pass through the obey file to set up key variables
-	//
-
-	iReader.Rewind();
-
-	enum EKeyword keyword;
-
-	// Deal with the "extensionrom" keyword, which should be first
-	
-	if (iReader.NextLine(1,keyword) != KErrNone)
-		return KErrEof;
-	if (keyword != EKeywordExtensionRom)
-		return Print(EError, "Unexpected keyword '%s' at start of extension rom - line %d\n",
-			iReader.Word(0), iReader.CurrentLine());
-	
-	iReader.CopyWord(1, iRomFileName);
-	Print(ELog, "\n========================================================\n");
-	Print(ELog, "Extension ROM %s starting at line %d\n\n", iRomFileName, iReader.CurrentLine());
-
-	iReader.MarkNext();		// so that we rewind to the line after the extensionrom keyword
-
-	while (iReader.NextLine(1,keyword) != KErrEof)
-		{
-		if (keyword == EKeywordExtensionRom)
-			break;
-		ProcessExtensionKeyword(keyword);
-		}
-
-	if (!GotExtensionVariables(aKernelRom))
-		return KErrGeneral;
-
-	if (! CreateDefaultArea())
-		return KErrGeneral;
-
-	//
-	// second pass to process the file specifications in the obey file building
-	// up the TRomNode directory structure and the TRomBuilderEntry list
-	//
-	iReader.Rewind();
-
-	if (aKernelRom==0)
-		return Print(EError, "Option to extend a kernel ROM image not yet implemented\n");
-	iLastExecutable = 0;
-	iRootDirectory = aKernelRom->CopyDirectory(iLastExecutable);
-
-
-	TInt align=0;
-	while (iReader.NextLine(2,keyword)!=KErrEof)
-		{
-		if (keyword == EKeywordExtensionRom)
-			break;
-
-		switch (keyword)
-			{
-		case EKeywordSection:
-		case EKeywordArea:
-		case EKeywordPrimary:
-		case EKeywordSecondary:
-		case EKeywordExtension:
-		case EKeywordDevice:
-		case EKeywordVariant:
-		case EKeywordHardwareConfigRepositoryData:
-			Print(EError, "Keyword '%s' not supported in extension ROMs - line %d\n",
-				iReader.Word(0), iReader.CurrentLine());
-			break;
-
-		case EKeywordAlign:
-			if (iReader.ProcessAlign(align)!=KErrNone)
-				return KErrGeneral;
-			break;
-
-		case EKeywordHide:
-		case EKeywordAlias:
-		case EKeywordRename:
-			if (!ProcessRenaming(keyword))
-				return KErrGeneral;
-			break;
-		case EKeywordPatchDllData:
-		{
-			// Collect patchdata statements to process at the end
-			StringVector patchDataTokens;
-			SplitPatchDataStatement(patchDataTokens); 
-			iPatchData->AddPatchDataStatement(patchDataTokens);										
-			break;
-		}
-
-		default:
-			if (!ProcessFile(align, keyword))
-				return KErrGeneral;
-			align=0;
-			break;
-			}
-		}
-
-	if( !ParsePatchDllData())
-		return KErrGeneral;
-
-	iReader.Mark();			// ready for processing the next extension rom(s)
-
-	if (iMissingFiles!=0)
-		return KErrGeneral;
-	if (iNumberOfDataFiles+iNumberOfPeFiles==0)
-		{
-		Print(EError, "No files specified.\n");
-		return KErrGeneral;
-		}
-	return KErrNone;
-	}
-
-void CObeyFile::ProcessExtensionKeyword(enum EKeyword aKeyword)
-	{
-	#ifdef __TOOLS2__
-	istringstream val(iReader.Word(1));
-	#else
-	istrstream val(iReader.Word(1),strlen(iReader.Word(1)));
-	#endif
-	
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-	val >> setbase(0);
-#endif //__MSVCDOTNET__
-
-	switch (aKeyword)
-		{
-	case EKeywordKernelRomName:
-		iReader.CopyWord(1, iKernelRomName);
-		return;
-	case EKeywordRomNameOdd:
-		iReader.CopyWord(1, iRomOddFileName);
-		return;
-	case EKeywordRomNameEven:
-		iReader.CopyWord(1, iRomEvenFileName);
-		return;
-	case EKeywordSRecordFileName:
-		iReader.CopyWord(1, iSRecordFileName);
-		return;
-
-	case EKeywordRomLinearBase:
-		val >> iRomLinearBase;
-		return;
-	case EKeywordRomSize:
-		val >> iRomSize;
-		return;
-	case EKeywordRomAlign:
-		val >> iRomAlign;
-		return;
-
-	case EKeywordDataAddress:
-		val >> iDataRunAddress;
-		return;
-	case EKeywordDefaultStackReserve:
-		val >> iDefaultStackReserve;
-		return;
-	case EKeywordVersion:
-		val >> iVersion;
-		return;
-	case EKeywordSRecordBase:
-		val >> iSRecordBase;
-		return;
-	case EKeywordRomChecksum:
-		val >> iCheckSum;
-		return;
-	case EKeywordTime:
-		iReader.ProcessTime(iTime);
-		return;
-
-	case EKeywordTrace:
-		val >> TraceMask;
-		return;
-
-	case EKeywordCollapse:
-		if (strnicmp(iReader.Word(1), "arm", 3)!=0 || strnicmp(iReader.Word(2), "gcc", 3)!=0)
-			{
-			Print(EWarning, "COLLAPSE only supported for ARM and GCC - keyword ignored\n");
-			}
-		else
-			{
-			TInt cm;
-			#ifdef __TOOLS2__
-			istringstream cmval(iReader.Word(3));
-			#else
-			istrstream cmval(iReader.Word(3),strlen(iReader.Word(3)));
-			#endif
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-			cmval >> setbase(0);
-#endif //__MSVCDOTNET__
-
-			cmval>>cm;
-			if (cm<0 || cm>ECollapseAllChainBranches)
-				{
-				Print(EWarning, "COLLAPSE mode unrecognised - keyword ignored\n");
-				}
-			else
-				{
-				Print(EWarning, "COLLAPSE not currently supported for extension roms\n");
-				}
-			}
-		return;
-
-	case EKeywordCoreImage:
-		//Already handled, skip it
-		return;
-
-	default:
-		Print(EError,"Keyword '%s' not valid in extension ROMs - line %d\n", iReader.Word(0), iReader.CurrentLine());
-		break;
-		}
-	return;
-	}
-
-TBool CObeyFile::GotExtensionVariables(MRomImage*& aRom)
-//
-// Checks that the obeyfile has supplied enough variables to continue
-//
-   	{
-
-	TBool retVal=ETrue;
-	TText* kernelRomName = iKernelRomName;
-
-	// Mandatory keywords
-
-	if (iRomSize==0)
-		{
-		Print(EAlways,"The size of the extension ROM has not been supplied.\n");
-		Print(EAlways,"Use the keyword \"romsize\".\n");
-		retVal = EFalse;
-		}
-
-	// keywords we need if we don't already have a ROM image to work from
-
-	if (aRom==0)
-		{
-		if (iKernelRomName==0)
-			{
-			Print(EAlways,"The name of the kernel ROM has not been supplied.\n");
-			Print(EAlways,"Use the keyword \"kernelromname\".\n");
-			retVal = EFalse;
-			}
-		if (iRomLinearBase==0xFFFFFFFF)
-			{
-			Print(EAlways,"The base linear address of the ROM has not been supplied.\n");
-			Print(EAlways,"Use the keyword \"romlinearbase\".\n");
-			retVal = EFalse;
-			}
-		}
-	else
-		{
-		if (iKernelRomName != 0)
-			{
-			Print(EWarning,"Keyword \"kernelromname\") ignored.\n");
-			}
-		kernelRomName = aRom->RomFileName();
-		}
-
-	// validation
-
-	// Apply defaults as necessary
-
-	if (iRomLinearBase==0xFFFFFFFF && aRom!=0)
-		{
-		iRomLinearBase = aRom->RomBase() + aRom->RomSize();
-		Print(ELog,"Assuming extension ROM is contiguous with kernel ROM\n");
-		Print(ELog,"Setting romlinearbase to 0x%08x\n", iRomLinearBase);
-		}
-	TheRomLinearAddress=iRomLinearBase;
-
-	if (iDataRunAddress==0)
-		{
-		iDataRunAddress= aRom->DataRunAddress();
-		Print(EWarning,"The address for a running ROM app's data section (keyword \"dataaddress\") has not been supplied.\n");
-		Print(EWarning,"Will use the default value of 0x%0x.\n", iDataRunAddress);
-		}
-	if (iRomAlign==0)
-		{
-		iRomAlign = aRom->RomAlign();
-		Print(EWarning,"The ROM section alignment (keyword \"romalign\") has not been supplied.\n");
-		Print(EWarning,"Will use the default value of 0x%0x.\n", iRomAlign);
-		}
-	if (iRomAlign&0x3)
-		{
-		Print(EWarning, "Rounding rom alignment to multiple of 4.\n");
-		iRomAlign=(iRomAlign+0x3)&0xfffffffc;
-		}
-	if (iTime==0)
-		{
-		Print(ELog, "No timestamp specified. Using current time...\n");
-		ObeyFileReader::TimeNow(iTime);
-		}
-
-	// fix up "*" in romname
-	TText newname[256];
-	TText* p=newname;
-	TText* q=iRomFileName;
-	TText c;
-
-	while ((c=*q++)!='\0')
-		{
-		if (c!='*')
-			{
-			*p++=c;
-			continue;
-			}
-		TText *r=kernelRomName;
-		while ((c=*r++)!='\0')
-			*p++=c;
-		}
-	*p = '\0';
-	free(iRomFileName);
-	iRomFileName = (TText*)strdup((char*)newname);
-
-	Print(ELog, "\nCreating Rom image %s\n", iRomFileName);
-	return retVal;
-	}
-
-
-////////////////////////////////////////////////////////////////////////
-// AREA RELATED CODE
-////////////////////////////////////////////////////////////////////////
-
-/**
- Process an area declaration.
- */
-
-TBool CObeyFile::ParseAreaKeyword()
-	{
-	const char* name = iReader.Word(1);
-	TLinAddr start;
-	TUint length;
-	if(Val(start, iReader.Word(2)) != KErrNone || Val(length, iReader.Word(3)) != KErrNone)
-		{
-		Print(EError, "Line %d: Wrong area specification: Should be <name> <start address> <length>\n",
-			  iReader.CurrentLine());
-		return EFalse;
-		}
-
-	if (! AddAreaAndHandleError(name, start, length, iReader.CurrentLine()))
-		return EFalse;
-
-	return ETrue;
-	}
-
-
-/**
- Process an "area=xxx" file attribute.
- */
-
-TBool CObeyFile::ParseAreaAttribute(const TText* aArg, TInt aLineNumber, const Area*& aArea)
-	{
-	if (iSectionPosition != -1)
-		{
-		Print(EError, "Line %d: Relocation to area forbidden in second section\n", aLineNumber);
-		return EFalse;
-		}
-
-	aArea = iAreaSet.FindByName(reinterpret_cast<const char*>(aArg));
-	if (aArea == 0)
-		{
-		Print(EError, "Line %d: Attempt to use an unknown area named '%s'\n", aLineNumber, aArg);
-		return EFalse;
-		}
-
-	return ETrue;
-	}
-
-
-TBool CObeyFile::CreateDefaultArea()
-	{
-	return AddAreaAndHandleError(AreaSet::KDefaultAreaName, iRomLinearBase, iRomSize);
-	}
-
-
-TBool CObeyFile::AddAreaAndHandleError(const char* aName, TLinAddr aDestBaseAddr, TUint aLength, TInt aLineNumber)
-	{
-	TBool added = EFalse;
-	
-	const char lineInfoFmt[] = "Line %d:";
-	char lineInfo[sizeof(lineInfoFmt)+10];
-	if (aLineNumber > 0)
-		sprintf(lineInfo, lineInfoFmt, aLineNumber);
-	else
-		lineInfo[0] = '\0';
-
-	const char* overlappingArea;
-	switch (iAreaSet.AddArea(aName, aDestBaseAddr, aLength, overlappingArea))
-		{
-	case AreaSet::EAdded:
-		TRACE(TAREA, Print(EScreen, "Area '%s' added to AreaSet\n", aName));
-		added = ETrue;
-		break;
-	case AreaSet::EOverlap:
-		Print(EError, "%s Area '%s' collides with area '%s'\n", lineInfo, aName, overlappingArea);
-		break;
-	case AreaSet::EDuplicateName:
-		Print(EError, "%s Name '%s' already reserved for another area\n", lineInfo, aName);
-		break;
-	case AreaSet::EOverflow:
-		Print(EError, "%s Area overflow (0x%X+0x%X > 0x%X)\n", lineInfo, aDestBaseAddr, aLength, -1);
-		break;
-	default:
-		assert(0);				// can't happen
-		}
-
-	return added;
-	}
-
-TInt getNumber(TText*);
-
-
-// Fuction to split patchdata statement 
-void CObeyFile::SplitPatchDataStatement(StringVector& aPatchDataTokens)
-{
-	// Get the value of symbol size, address/ordinal and new value 
-	// to be patched from the patchdata statement.
-	// Syntax of patchdata statements is as follows:
-	// 1)	patchdata dll_name  ordinal OrdinalNumber size_in_bytes   new_value 
-	// 2)   patchdata dll_name  addr    Address       size_in_bytes   new_value
-	for(TInt count=1; count<=5; count++)	
-	{
-		aPatchDataTokens.push_back(iReader.Word(count));
-	}
-
-	// Store the the value of current line which will be used
-	// when displaying error messages.
-	OutputStringStream outStrStream;
-	outStrStream << iReader.CurrentLine();
-    aPatchDataTokens.push_back(outStrStream.str());	
-}
-
-TBool CObeyFile::ParsePatchDllData()
-{
-	// Get the list of patchdata statements
-	VectorOfStringVector patchDataStatements=iPatchData->GetPatchDataStatements();
-	// Get the list of renamed file map
-	MapOfString RenamedFileMap=iPatchData->GetRenamedFileMap();
-	DllDataEntry *aDllDataEntry=NULL;
-
-	for(TUint count=0; count<patchDataStatements.size(); count++)
-	{
-		StringVector strVector = patchDataStatements.at(count);
-		String filename=strVector.at(0);
-		String lineNoStr = strVector.at(5);
-		TUint lineNo=getNumber(((TText*)lineNoStr.c_str()));
-		TRomNode* existingFile = NULL;
-			
-		do
-		{			
-			TUint hardwareVariant=ParseVariant();
-			TRomNode* dir=iRootDirectory;		
-			TBool endOfName=EFalse;
-
-			TText *epocStartPtr=IsValidFilePath((TText*)filename.c_str());
-			if (epocStartPtr==NULL)
-			{
-				Print(EError, "Invalid source path on line %d\n",lineNo);
-				return EFalse;
-			}
-			epocStartPtr = (TText*)NormaliseFileName((const char*)epocStartPtr);
-			TText *epocEndPtr=epocStartPtr;
-
-			while (!endOfName)
-			{
-				endOfName = GetNextBitOfFileName(&epocEndPtr);
-				if (endOfName) // file
-				{
-					existingFile=dir->FindInDirectory(epocStartPtr,hardwareVariant,TRUE);
-					if (existingFile)
-					{
-						TInt fileCount=0;
-						TInt dirCount=0;
-						existingFile->CountDirectory(fileCount, dirCount);
-						if (dirCount != 0 || fileCount != 0)
-						{
-							Print(EError, "Keyword %s not applicable to directories - line %d\n","patchdata",lineNo);
-							return EFalse;
-						}
-					}
-				}
-				else // directory
-				{
-					TRomNode* subDir = dir->FindInDirectory(epocStartPtr);
-					if (!subDir) // sub directory does not exist
-						break;
-					dir=subDir;
-					epocStartPtr = epocEndPtr;
-				}
-			}
-
-			if( !existingFile )
-			{
-				MapOfStringIterator RenamedFileMapIterator;
-
-				// If the E32Image file to be patched is not included then check if the
-				// file was renamed.
-				if ((RenamedFileMapIterator=RenamedFileMap.find(filename)) != RenamedFileMap.end())
-					filename = (*RenamedFileMapIterator).second; 
-				else
-				{
-					Print(EError, "File %s not found - line %d\n", filename.c_str(), lineNo);
-					return EFalse;
-				}
-			}
-		}while(!existingFile);
-
-		TUint32 aSize, aOrdinal, aNewValue, aOffset;
-		TLinAddr aDataAddr;
-
-		aOrdinal = (TUint32)-1;
-		aDataAddr = (TUint32)-1;
-		aOffset = 0;
-
-		String symbolSize = strVector.at(3);
-		aSize = getNumber((TText*)symbolSize.c_str());
-		String aValue = strVector.at(4);
-		aNewValue = getNumber( (TText*)aValue.c_str());
-
-		DllDataEntry *dataEntry = new DllDataEntry(aSize, aNewValue);
-
-		// Set the address of the data or the ordinal number specified in OBY statement.
-		String keyword = strVector.at(1);
-		String keywordValue = strVector.at(2);
-
-		/* Check for +OFFSET at the end of the ordinal number or address */
-		TUint plus = keywordValue.find("+",0);
-		if (plus != std::string::npos)
-		{
-			/* Get the offset that we found after the + sign */
-			String offset = keywordValue.substr(plus+1);
-			aOffset = getNumber((TText*)offset.c_str());
-
-			keywordValue.resize(plus);		
-		}
-		if(stricmp ((char*)keyword.c_str(), "addr") == 0)
-			aDataAddr = getNumber((TText*)keywordValue.c_str());
-		
-		else 
-			 aOrdinal = getNumber((TText*)keywordValue.c_str());
-		
-		dataEntry->iDataAddress = aDataAddr;
-		dataEntry->iOrdinal = aOrdinal;
-		dataEntry->iOffset = aOffset;
-		dataEntry->iRomNode = existingFile;
-
-		if (aDllDataEntry==NULL)
-		{
-			// Set the first node of the patchdata linked list
-			aDllDataEntry = dataEntry;
-			SetFirstDllDataEntry(aDllDataEntry);
-		}
-		else
-		{
-			// Add the new node at the end of linked list
-			aDllDataEntry->AddDllDataEntry(dataEntry);
-			aDllDataEntry = aDllDataEntry->NextDllDataEntry();
-		}
-	}
-	return ETrue;
-}
-
-int CObeyFile::SkipToExtension()
-{
-	int found = 0;
-
-	iReader.Rewind();
-	enum EKeyword keyword;
-	while (iReader.NextLine(1,keyword) != KErrEof)
-	{
-		if (keyword == EKeywordExtensionRom)
-		{
-			found = 1;
-			iReader.Mark(); // ready for processing extension
-			break;
-		}
-	}
-
-	if(!found)
-	{
-		Print(EError, "Coreimage option requires valid \"extensionrom\" keyword\n");
-	}
-
-	return found;
-}
-
-TText* CObeyFile::ProcessCoreImage()
-{
-	// check for coreimage keyword and return filename
-	iReader.Rewind();
-	enum EKeyword keyword;
-	TText* coreImageFileName = 0;
-
-	iRomAlign = KDefaultRomAlign;
-	iDataRunAddress = KDefaultDataRunAddress;
-
-	while (iReader.NextLine(1,keyword) != KErrEof)
-	{
-		if (keyword == EKeywordCoreImage)
-		{
-#if defined(__TOOLS2__) && defined (_STLP_THREADS)
-			istringstream val(iReader.Word(1),(ios_base::in+ios_base::out));	  
-#elif __TOOLS2__
-			istringstream val(iReader.Word(1),(std::_Ios_Openmode)(ios_base::in+ios_base::out));
-#else
-			istrstream val(iReader.Word(1),strlen(iReader.Word(1)));
-#endif
-			iReader.CopyWord(1, coreImageFileName);
-			break;
-		}
-		else if ((keyword == EKeywordRomAlign) || (keyword == EKeywordDataAddress))
-		{
-#ifdef __TOOLS2__
-			istringstream val(iReader.Word(1));
-#else
-			istrstream val(iReader.Word(1),strlen(iReader.Word(1)));
-#endif
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-	val >> setbase(0);
-#endif //__MSVCDOTNET__
-			if(keyword == EKeywordRomAlign)
-			{
-				val >> iRomAlign;
-			}
-			else
-			{
-				val >> iDataRunAddress;
-			}
-		}
-	}
-
-	if (iRomAlign&0x3)
-	{
-		//Rounding rom alignment to multiple of 4
-		iRomAlign=(iRomAlign+0x3)&0xfffffffc;
-	}
-
-	return coreImageFileName;
-}
-
+/*
+* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#include <string.h>
+
+#include <strstream>
+#include <iomanip>
+
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <time.h>
+#include <assert.h>
+#include <errno.h>
+
+#include <e32std.h>
+#include <e32std_private.h>
+#include <e32rom.h>
+#include <u32std.h>
+#include <f32file.h>
+
+#include "r_rom.h"
+#include "r_obey.h"
+#include "r_global.h"
+#include "h_utl.h"
+#include "patchdataprocessor.h"
+#include "r_coreimage.h" 
+
+#define _P(word)	word, sizeof(word)-1	// match prefix, optionally followed by [HWVD]
+#define _K(word)	word, 0					// match whole word
+static char* const NullString = "" ;
+const ObeyFileKeyword ObeyFileReader::iKeywords[] = {
+	{_P("file"),		2,-2, EKeywordFile, "Executable file to be loaded into the ROM"},
+	{_P("data"),		2,-2, EKeywordData, "Data file to be copied into the ROM"},
+	{_P("primary"),		1+2,-2, EKeywordPrimary, "An EPOC Kernel"},
+	{_P("secondary"),	2,-2, EKeywordSecondary, "?"},
+	{_P("variant"),		1+2,-2, EKeywordVariant, "?"},
+	{_P("extension"),	1+2,-2, EKeywordExtension, "Kernel extension loaded before the secondary"},
+	{_P("device"),		1+2,-2, EKeywordDevice, "Kernel extension loaded from the ROM file system"},
+	{_P("dll"),			2,-2, EKeywordDll, "Executable file whose entry point must be called"},
+	{_P("filecompress"),	2,-2, EKeywordFileCompress, "Non-XIP Executable to be loaded into the ROM compressed"},
+	{_P("fileuncompress"),	2,-2, EKeywordFileUncompress, "Non-XIP Executable to be loaded into the ROM uncompressed"},
+	{_K("area"),	    1, 3, EKeywordArea, "Declare a relocation area"},
+	{_K("align"),	    2, 1, EKeywordAlign, "Override default alignment for following file"},
+	{_P("hide"),	    2, -1, EKeywordHide, "Exclude named file from ROM directory structure"},
+	{_P("alias"),	    2, -2, EKeywordAlias, "Create alias for existing file in ROM directory structure"},
+	{_P("rename"),	    2, -2, EKeywordRename, "Change the name of a file in the ROM directory structure"},
+	{_K("singlekernel"),1, 0, EKeywordSingleKernel, "Single Kernel"},
+	{_K("multikernel"),	1, 0, EKeywordMultiKernel, "Multiple Kernels"},
+	{_K("bootbinary"),	1, 1, EKeywordBootBinary, "file containing the bootstrap"},
+	{_K("romname"),		1, 1, EKeywordRomName, "output file for ROM image"},
+	{_K("romsize"),		1, 1, EKeywordRomSize, "size of ROM image"},
+	{_K("romlinearbase"),	1, 1, EKeywordRomLinearBase, "linear address of ROM image"},
+	{_K("romalign"),	1, 1, EKeywordRomAlign, "default alignment of files in ROM image"},
+	{_K("romchecksum"),	1, 1, EKeywordRomChecksum, "desired 32-bit checksum value for the whole ROM image"},
+	{_K("kerneldataaddress"),	1, 1, EKeywordKernelDataAddress, "?"},
+	{_K("kernelheapmin"),	1, 1, EKeywordKernelHeapMin, "Inital size of the kernel heap"},
+	{_K("kernelheapmax"),	1, 1, EKeywordKernelHeapMax, "Maximum size of the kernel heap"},
+	{_K("dataaddress"),	1, 1, EKeywordDataAddress, "?"},
+	{_K("defaultstackreserve"),	1, 1, EKeywordDefaultStackReserve, "?"},
+	{_K("version"),		1, 1, EKeywordVersion, "ROM version number"},
+	{_K("romnameodd"),	1, 1, EKeywordRomNameOdd, "output file containing odd halfwords of ROM image"},
+	{_K("romnameeven"),	1, 1, EKeywordRomNameEven, "output file containing even halfwords of ROM image"},
+	{_K("srecordfilename"),	1, 1, EKeywordSRecordFileName, "output file containing ROM image in S-Record format"},
+	{_K("srecordbase"),	1, 1, EKeywordSRecordBase, "Destination address for S-Record download"},
+	{_K("kerneltrace"),	1, -1, EKeywordKernelTrace, "Initial value for Kernel tracing flags"},
+	{_K("btrace"),	1, -1, EKeywordBTrace, "Initial value for fast-trace filter"},
+	{_K("btracemode"),	1, 1, EKeywordBTraceMode, "Initial value for fast-trace mode"},
+	{_K("btracebuffer"),	1, 1, EKeywordBTraceBuffer, "Initial size for fast-trace buffer"},
+	{_K("collapse"),	1, 3, EKeywordCollapse, "Additional ROM optimisations"},
+	{_K("time"),	    1,-1, EKeywordTime, "ROM timestamp"},
+	{_K("section"),	    2, 1, EKeywordSection, "Start of replaceable section in old-style 2 section ROM"},
+	{_K("extensionrom"),1+2, 1, EKeywordExtensionRom, "Start of definition of optional Extension ROM"},
+	{_K("kernelromname"),1, 1, EKeywordKernelRomName, "ROM image on which extension ROM is based"},
+	{_K("files"),		0, 0, EKeywordNone, 0},	// backwards compatibility, but now ignored
+	{_K("rem"),			0, 0, EKeywordNone, "comment"},
+	{_K("stop"),		0, 0, EKeywordNone, "Terminates OBEY file prematurely"},
+	{_K("dlldatatop"),	1, 1, EKeywordDllDataTop, "Specify top of DLL data region"},
+	{_K("memmodel"),	1, -1, EKeywordMemModel, "Specifies the memory model to be used at runtime"},
+	{_K("nowrapper"),	1, 0, EKeywordNoWrapper, "Specifies that no ROM wrapper is required"},
+	{_K("epocwrapper"),	1, 0, EKeywordEpocWrapper, "Specifies that an EPOC ROM wrapper is required"},
+	{_K("coffwrapper"),	1, 0, EKeywordCoffWrapper, "Specifies that a COFF ROM wrapper is required"},
+	{_K("platsecenforcement"),	1, 1, EKeywordPlatSecEnforcement, "Set Platform Security enforment on/off"},
+	{_K("platsecdiagnostics"),	1, 1, EKeywordPlatSecDiagnostics, "Set Platform Security diagnostics on/off"},
+	{_K("platsecprocessisolation"), 1, 1, EKeywordPlatSecProcessIsolation, "Set Platform Security process isolation on/off"},
+	{_K("platsecenforcesysbin"), 1, 1, EKeywordPlatSecEnforceSysBin, "Set Platform Security process isolation on/off"},
+	{_K("platsecdisabledcaps"), 1, 1, EKeywordPlatSecDisabledCaps, "Disable the listed Platform Security capabilities"},
+	{_K("pagingpolicy"),	1, 1, EKeywordPagingPolicy, "Set the demand paging policy NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
+	{_K("codepagingpolicy"),	1, 1, EKeywordCodePagingPolicy, "Set the code paging policy NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
+	{_K("datapagingpolicy"),	1, 1, EKeywordDataPagingPolicy, "Set the data paging policy NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
+	{_K("pagingoverride"),	1, 1, EKeywordPagingOverride, "Overide the demand paging attributes for every file in ROM, NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
+	{_K("codepagingoverride"),	1, 1, EKeywordCodePagingOverride, "Overide the code paging attributes for every file in ROM, NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
+	{_K("datapagingoverride"),	1, 1, EKeywordDataPagingOverride, "Overide the data paging attributes for every file in ROM, NOPAGING|DEFAULTUNPAGED|DEFAULTPAGED"},
+	{_K("patchdata"), 2, 5, EKeywordPatchDllData, "Patch exported data"},
+	{_K("coreimage"),	1, 1, EKeywordCoreImage, "Core image to be used for extension directory structure"},
+
+	// things we don't normally report in the help information
+	{_K("trace"),		1, 1, EKeywordTrace, "(ROMBUILD activity trace flags)"},
+	{_K("unicode"),		1, 0, EKeywordUnicode, "(UNICODE rom - the default)"},
+	{_K("ascii"),		1, 0, EKeywordAscii, "(Narrow rom)"},
+	{_K("languages"),	1,-1, EKeywordLanguages, "(List of supported languages (for test))"},
+	{_K("hardware"),	1, 1, EKeywordHardware, "(32-bit Hardware identifier (for test))"},
+	{_K("debugport"),	1, 1, EKeywordDebugPort, "(Debug trace sink (magic cookie passed to ASSP/variant))"},
+	{_K("compress"),	1, 0, EKeywordCompress, "Compress the ROM image"},
+	{_K("demandpagingconfig"),	1, -1, EKeywordDemandPagingConfig, "Demand Paging Config [minPages] [maxPages] [ageRatio]"},
+	{_K("pagedrom"),	1, 0, EKeywordPagedRom, "Build ROM immage suitable for demand paging"},
+	{_K("filecompressnone"), 		2, -2, EKeywordExecutableCompressionMethodNone, "No compress the individual executable image."},
+	{_K("filecompressinflate"),     2, -2, EKeywordExecutableCompressionMethodInflate,  "Inflate compression method for the individual executable image."},
+	{_K("filecompressbytepair"),  	2, -2, EKeywordExecutableCompressionMethodBytePair, "Byte pair compresion method for the individual executable image."},
+	{_K("kernelconfig"), 1, 2, EKeywordKernelConfig, "Set an arbitrary bit of the kernel config flags to on/off)"},
+	{_K("maxunpagedsize"),	1, 1, EKeywordMaxUnpagedMemSize, "Maxinum unpaged size in ROM image. Default is no limited."},
+	{_K("hcrdata") , 2, 2,EKeywordHardwareConfigRepositoryData,"HCR image data"},
+	{0,0,0,0,EKeywordNone,""} 
+
+};
+
+void ObeyFileReader::KeywordHelp() { // static
+
+	cout << "Obey file keywords:\n";
+
+	const ObeyFileKeyword* k=0;
+	for (k=iKeywords; k->iKeyword!=0; k++) {
+		if (k->iHelpText==0)
+			continue;
+		if (k->iHelpText[0]=='(' && !H.iVerbose)
+			continue;	// don't normally report things in (parentheses)
+
+		char buf[32];
+		sprintf(buf, "%-20s", k->iKeyword);
+		if (k->iKeywordLength)
+			memcpy(buf+k->iKeywordLength,"[HWVD]",6);
+		if (H.iVerbose)
+			sprintf(buf+20,"%2d",k->iNumArgs);
+		cout << "    " << buf << " " << k->iHelpText << endl;
+	}
+	cout << endl;
+
+	cout << "File attributes:\n";
+
+	const FileAttributeKeyword* f=0;
+	for (f=iAttributeKeywords; f->iKeyword!=0; f++) {
+		if (f->iHelpText==0)
+			continue;
+		if (f->iHelpText[0]=='(' && !H.iVerbose)
+			continue;	// don't normally report things in (parentheses)
+
+		char buf[32];
+		sprintf(buf, "%-20s", f->iKeyword);
+		if (H.iVerbose)
+			sprintf(buf+20,"%2d",k->iNumArgs);
+		cout << "    " << buf << " " << f->iHelpText << endl;
+	}
+	cout << endl;
+}
+
+TInt NumberOfVariants=0;
+//
+// Constructor
+//
+ObeyFileReader::ObeyFileReader(const char* aFileName):iFileName(aFileName),iCurrentLine(0), iNumWords(0),iLine(0),iMarkLine(0)  {
+	for(TUint i = 0 ; i < KNumWords ; i++)
+		iWord[i] = NullString ;	 
+	*iSuffix = 0 ; 
+
+}
+
+ObeyFileReader::~ObeyFileReader() {
+	if(iLine)
+		delete [] iLine;
+}
+//
+// Open the file & return a status
+//
+TBool ObeyFileReader::Open() {
+	ifstream ifs(iFileName.c_str(),ios_base::in + ios_base::binary);
+	if (!ifs.is_open()) {
+		Print(EError,"Cannot open obey file %s\n",iFileName.c_str());
+		return EFalse;
+	}
+	iLines.clear();
+	if(iLine){
+		delete []iLine;
+		iLine = 0 ;
+	}		
+	ifs.seekg(0,ios_base::end);
+	size_t length = ifs.tellg();
+	char* buffer = new char[length + 2];
+	if (0 == buffer) {
+		Print(EError,"Insufficient Memory to Continue.");
+		return EFalse;
+	}
+	ifs.seekg(0,ios_base::beg);
+	ifs.read(buffer,length); 
+	size_t readcout = ifs.gcount() ;
+	if(readcout != length){ 	
+		Print(EError,"Cannot Read All of File.");	
+		delete []buffer ;
+		ifs.close();
+		return EFalse;
+	}
+	buffer[length] = '\n';
+	buffer[length + 1] = 0 ; 
+	ifs.close();
+	char* lineStart = buffer ;
+	char* end = buffer + length ;
+	string line ;
+	size_t maxLengthOfLine = 0 ; 
+	while(lineStart <= end){
+		while(*lineStart == ' ' || *lineStart == '\t') //trimleft 
+			lineStart ++ ;		
+		char* lineEnd = lineStart ;	 
+		while(*lineEnd != '\r' && *lineEnd != '\n')
+			lineEnd ++ ;
+		if(strnicmp(lineStart,"REM",3) == 0){
+			line = "" ; // REMOVE "REM ... "
+		}
+		else {
+			TInt lastIndex = lineEnd - lineStart - 1;
+			while(lastIndex >= 0 &&  // trimright
+				(lineStart[lastIndex] == ' ' || lineStart[lastIndex] == '\t'))
+				lastIndex -- ;
+			if(lastIndex >= 0)
+				line.assign(lineStart,lastIndex + 1);
+			else
+				line = "";
+		}
+	 
+
+		if(line.length() > maxLengthOfLine)
+			maxLengthOfLine = line.length();
+		iLines.push_back(line);
+		if(*lineEnd == '\r') {
+			if(lineEnd[1] == '\n')
+				lineStart = lineEnd + 2 ;
+			else
+				lineStart = lineEnd + 1 ;
+		}
+		else // '\n'
+			lineStart = lineEnd + 1 ; 
+	}	
+	delete []buffer ;
+	iLine = new char[maxLengthOfLine + 1]; 
+	iCurrentLine = 0 ;
+	iMarkLine = 0 ;
+	return ETrue;
+}
+ 
+
+void ObeyFileReader::Mark()	{ 
+	iMarkLine = iCurrentLine - 1;
+}
+
+void ObeyFileReader::MarkNext() { 
+	iMarkLine = iCurrentLine;
+}
+
+void ObeyFileReader::Rewind() {
+	iCurrentLine = iMarkLine;
+}
+
+char* ObeyFileReader::DupWord(TInt aIndex) const {
+	char* retVal = 0 ;
+	if(aIndex >= 0 && aIndex < (TInt)KNumWords){
+		size_t len = strlen(iWord[aIndex]) + 1;
+		retVal = new char[len];
+		if(retVal)
+			memcpy(retVal,iWord[aIndex],len);
+	} 
+	return retVal ;
+}
+
+
+TInt ObeyFileReader::ReadAndParseLine() {
+	if (iCurrentLine >= (TInt)iLines.size())
+		return KErrEof;
+	iCurrentLine++; 
+	iNumWords = Parse();
+	return KErrNone;
+}
+TInt ObeyFileReader::NextLine(TInt aPass, enum EKeyword& aKeyword)
+	{
+
+NextLine:
+	TInt err = ReadAndParseLine();
+	if (err == KErrEof)
+		return KErrEof;
+	if (iNumWords == 0 )
+		goto NextLine;
+	if (stricmp((const char*)iWord[0], "stop")==0)
+		return KErrEof;
+
+	const ObeyFileKeyword* k=0;
+	for (k=iKeywords; k->iKeyword!=0; k++) {
+		if (k->iKeywordLength == 0) {
+			// Exact case-insensitive match on keyword
+			if (stricmp((const char*)iWord[0], k->iKeyword) != 0)
+				continue;
+			*iSuffix = 0;
+		}
+		else {
+			// Prefix match
+			if (strnicmp((const char*)iWord[0], k->iKeyword, k->iKeywordLength) != 0)
+				continue;
+			// Suffix must be empty, or a variant number in []
+			strncpy(iSuffix,iWord[0]+k->iKeywordLength,80);
+			if (*iSuffix != '\0' && *iSuffix != '[')
+				continue;
+		}
+		// found a match
+		if ((k->iPass & aPass) == 0) 
+			goto NextLine;
+		if (k->iNumArgs>=0 && (1+k->iNumArgs != iNumWords))	{			 
+			if(EKeywordHardwareConfigRepositoryData == k->iKeywordEnum){ // preq2131 specific 
+				Print(EWarning, "Incorrect number of arguments for keyword '%s' on line %d. Extra argument(s) are ignored.\n",	iWord[0],iCurrentLine);
+				aKeyword = k->iKeywordEnum;
+				return KErrNone;
+			}else{
+				Print(EError, "Incorrect number of arguments for keyword %s on line %d.\n",
+					iWord[0], iCurrentLine);
+			}
+			goto NextLine;
+		}
+		if (k->iNumArgs<0 && (1-k->iNumArgs > iNumWords)){
+			Print(EError, "Too few arguments for keyword %s on line %d.\n",
+				iWord[0], iCurrentLine);
+			goto NextLine;
+		}
+		
+		aKeyword = k->iKeywordEnum;
+		return KErrNone;
+	}
+	if (aPass == 1)
+		Print(EWarning, "Unknown keyword '%s'.  Line %d ignored\n", iWord[0], iCurrentLine);
+	goto NextLine;
+}
+
+ 
+//
+// splits a line into words, and returns the number of words found
+// 
+TInt ObeyFileReader::Parse() {
+
+	for (TUint i = 0; i < KNumWords; i++)
+		iWord[i] = NullString;
+
+	enum TState {EInWord, EInQuotedWord, EInGap};
+	TState state = EInGap;	 
+	TUint i = 0;
+	const string& line = iLines[iCurrentLine -1];  
+
+	memcpy(iLine,line.c_str(),line.length());
+	iLine[line.length()] = 0 ; 
+	char* linestr = iLine;
+	while (i < KNumWords && *linestr != 0) {
+		switch (state) {
+		case EInGap:
+			if (*linestr =='\"') {
+				if (linestr[1] != 0 && linestr[1]!='\"')
+					iWord[i++] = linestr + 1;
+				state = EInQuotedWord;
+			}
+			else if (!IsGap(*linestr)) {
+				iWord[i++] = linestr;
+				state=EInWord;
+			}
+			else
+				*linestr=0;
+			break;
+		case EInWord:
+			if (*linestr == '\"') {
+				*linestr = 0;
+				if (linestr[1] != 0 && linestr[1] != '\"')
+					iWord[i++] = linestr+1;
+				state=EInQuotedWord;
+			}
+			else if (IsGap(*linestr)) {
+				*linestr=0;
+				state=EInGap;
+			}
+			break;
+		case EInQuotedWord:
+			if (*linestr == '\"'){
+				*linestr = 0;
+				state = EInGap;
+			}
+			break;
+		}
+		linestr++;
+	}
+	return i;
+}
+
+
+void ObeyFileReader::ProcessLanguages(TInt64& aLanguageMask) {
+	TInt i=1;
+	while (i<iNumWords) {
+		char *aStr=(char *)iWord[i];
+		TLanguage l=ELangTest;
+		if (stricmp(aStr, "test")==0)
+			l=ELangTest;
+		else if (stricmp(aStr, "english")==0)
+			l=ELangEnglish;
+		else if (stricmp(aStr, "french")==0)
+			l=ELangFrench;
+		else if (stricmp(aStr, "german")==0)
+			l=ELangGerman;
+		else if (stricmp(aStr, "spanish")==0)
+			l=ELangSpanish;
+		else if (stricmp(aStr, "italian")==0)
+			l=ELangItalian;
+		else if (stricmp(aStr, "swedish")==0)
+			l=ELangSwedish;
+		else if (stricmp(aStr, "danish")==0)
+			l=ELangDanish;
+		else if (stricmp(aStr, "norwegian")==0)
+			l=ELangNorwegian;
+		else if (stricmp(aStr, "finnish")==0)
+			l=ELangFinnish;
+		else if (stricmp(aStr, "american")==0)
+			l=ELangAmerican;
+		else if (stricmp(aStr, "SwissFrench")==0)
+			l=ELangSwissFrench;
+		else if (stricmp(aStr, "SwissGerman")==0)
+			l=ELangSwissGerman;
+		else if (stricmp(aStr, "Portuguese")==0)
+			l=ELangPortuguese;
+		else if (stricmp(aStr, "Turkish")==0)
+			l=ELangTurkish;
+		else if (stricmp(aStr, "Icelandic")==0)
+			l=ELangIcelandic;
+		else if (stricmp(aStr, "Russian")==0)
+			l=ELangRussian;
+		else if (stricmp(aStr, "Hungarian")==0)
+			l=ELangHungarian;
+		else if (stricmp(aStr, "Dutch")==0)
+			l=ELangDutch;
+		else if (stricmp(aStr, "BelgianFlemish")==0)
+			l=ELangBelgianFlemish;
+		else if (stricmp(aStr, "Australian")==0)
+			l=ELangAustralian;
+		else if (stricmp(aStr, "BelgianFrench")==0)
+			l=ELangBelgianFrench;
+		else {
+			Print(EError, "Unknown language '%s' on line %d", iWord[i], iCurrentLine);
+			exit(666);
+		}
+		aLanguageMask = aLanguageMask+(1<<(TInt)l);
+		i++;
+	}
+}
+
+//
+// Process the timestamp
+//
+void ObeyFileReader::ProcessTime(TInt64& aTime) {
+	char timebuf[256];
+	if (iNumWords>2)
+		sprintf(timebuf, "%s_%s", iWord[1], iWord[2]);
+	else
+		strncpy(timebuf, iWord[1],256);
+
+	TInt r = StringToTime(aTime, timebuf);
+	if (r==KErrGeneral) {
+		Print(EError, "incorrect format for time keyword on line %d\n", iCurrentLine);
+		exit(0x670);
+	}
+	if (r==KErrArgument) {
+		Print(EError, "Time out of range on line %d\n", iCurrentLine);
+		exit(0x670);
+	}
+}
+
+TInt64 ObeyFileReader::iTimeNow=0;
+void ObeyFileReader::TimeNow(TInt64& aTime) {
+	if (iTimeNow==0) {
+		TInt sysTime=time(0);					// seconds since midnight Jan 1st, 1970
+		sysTime-=(30*365*24*60*60+7*24*60*60);	// seconds since midnight Jan 1st, 2000
+		TInt64 daysTo2000AD=730497;
+		TInt64 t=daysTo2000AD*24*3600+sysTime;	// seconds since 0000
+		t=t+3600;								// BST (?)
+		iTimeNow=t*1000000;						// milliseconds
+	}
+	aTime=iTimeNow;
+}
+//
+// Process the align keyword
+//
+TInt ObeyFileReader::ProcessAlign(TInt &aAlign) {
+		
+	TInt err = Val(aAlign,Word(1));
+	if(err != KErrNone) 
+		return Print(EError, "Number required for 'align' keyword on line %d\n", iCurrentLine); 
+	TInt i;
+	for (i=4; i!=0x40000000; i<<=1)
+		if (i==aAlign)
+			return KErrNone;
+	return Print(EError, "Alignment must be a power of 2 and bigger than 4.  Line %d\n", iCurrentLine);
+}
+
+
+const FileAttributeKeyword ObeyFileReader::iAttributeKeywords[] = {
+	{"stackreserve",6	,1,1,EAttributeStackReserve, "?"},
+	{"stack",3			,1,1,EAttributeStack, "?"},
+	{"reloc",3			,1,1,EAttributeReloc, "?"},
+	{"code-align",10	,1,1,EAttributeCodeAlign, "Additional code alignment constraint"},
+	{"data-align",10	,1,1,EAttributeDataAlign, "Additional data alignment constraint"},
+	{"fixed",3			,1,0,EAttributeFixed, "Relocate to a fixed address space"},
+	{"attrib",3			,0,1,EAttributeAtt, "File attributes in ROM file system"},
+	{"priority",3		,1,1,EAttributePriority, "Override process priority"},
+	{"patched",5		,1,0,EAttributePatched, "File to be replaced in second section"},
+	{_K("uid1")			,1,1,EAttributeUid1, "Override first UID"},
+	{_K("uid2")			,1,1,EAttributeUid2, "Override second UID"},
+	{_K("uid3")			,1,1,EAttributeUid3, "Override third UID"},
+	{_K("heapmin")		,1,1,EAttributeHeapMin, "Override initial heap size"},
+	{_K("heapmax")		,1,1,EAttributeHeapMax, "Override maximum heap size"},
+	{_K("keepIAT")		,1,0,EAttributeKeepIAT, "(Retain old-style Import Address Table)"},
+	{_K("hide")			,0,0,EAttributeHidden, "Don't record file in the ROM file system"},
+	{_K("area")         ,1,1,EAttributeArea, "Relocate file to given area"},
+	{_K("process")		,1,1,EAttributeProcessSpecific, "Indicate which process a DLL will attach to"},
+	{_K("capability")	,1,1,EAttributeCapability, "Override capabilities"},
+	{_K("preferred")	,1,0,EAttributePreferred, "Prefer this over other minor versions of same major version"},
+	{_K("unpaged")		,1,0,EAttributeUnpaged, "Don't use demand paging for this file"},
+	{_K("paged")		,1,0,EAttributePaged, "Use demand paging for this file"},
+	{_K("unpagedcode")	,1,0,EAttributeUnpagedCode, "Don't use code paging for this file"},
+	{_K("pagedcode")	,1,0,EAttributePagedCode, "Use code paging for this file"},
+	{_K("unpageddata")	,1,0,EAttributeUnpagedData, "Don't use data paging for this file"},
+	{_K("pageddata")	,1,0,EAttributePagedData, "Use data paging for this file"},
+	{0,0,0,0,EAttributeStackReserve,0}
+};
+
+TInt ObeyFileReader::NextAttribute(TInt& aIndex, TInt aHasFile, enum EFileAttribute& aKeyword, char*& aArg) {
+NextAttribute:
+	if (aIndex >= iNumWords)
+		return KErrEof;
+	char* word=iWord[aIndex++];
+	const FileAttributeKeyword* k;
+	for (k=iAttributeKeywords; k->iKeyword!=0; k++) {
+		if (k->iKeywordLength == 0) {
+			// Exact match on keyword
+			if (stricmp(word, k->iKeyword) != 0)
+				continue;
+		}
+		else {
+			// Prefix match
+			if (strnicmp(word, k->iKeyword, k->iKeywordLength) != 0)
+				continue;
+		}
+		// found a match
+		if (k->iNumArgs>0) {
+			TInt argIndex = aIndex;
+			aIndex += k->iNumArgs;		// interface only really supports 1 argument
+			if (aIndex>iNumWords) {
+				Print(EError, "Missing argument for attribute %s on line %d\n", word, iCurrentLine);
+				return KErrArgument;
+			}
+			aArg=iWord[argIndex];
+		}
+		if (k->iIsFileAttribute && !aHasFile) {
+			Print(EError, "File attribute %s applied to non-file on line %d\n", word, iCurrentLine);
+			return KErrNotSupported;
+		}
+		aKeyword=k->iAttributeEnum;
+		return KErrNone;
+	}
+	Print(EWarning, "Unknown attribute '%s' skipped on line %d\n", word, iCurrentLine);
+	goto NextAttribute;
+}
+
+
+
+
+CObeyFile::CObeyFile(ObeyFileReader& aReader):
+iRomFileName(0),iRomOddFileName(0),iRomEvenFileName(0),
+iSRecordFileName(0),iBootFileName(0),iKernelRomName(0),
+iRomSize(0),iRomLinearBase(0xffffffff),iRomAlign(0),
+iKernDataRunAddress(0),iDataRunAddress(0),iKernelLimit(0xffffffff),
+iKernHeapMin(0),iKernHeapMax(0),iSectionStart(0),iSectionPosition(-1),
+iVersion(0,0,0),iCheckSum(0),iNumberOfPeFiles(0),iNumberOfDataFiles(0),
+iNumberOfPrimaries(0),iNumberOfExtensions(0),iNumberOfVariants(0),
+iNumberOfDevices(0),iNumberOfHCRDataFiles (0),
+//iAllVariantsMask[256],
+iPrimaries(0),iVariants(0),iExtensions(0),iDevices(0),
+iLanguage(0),iHardware(0),iTime(0),iMemModel(E_MM_Moving),iPageSize(0x1000),
+iChunkSize(0x100000),iVirtualAllocSize(0x1000),iKernelModel(ESingleKernel),
+iCollapseMode(ECollapseNone),iSRecordBase(0),iCurrentSectionNumber(0),
+iDefaultStackReserve(0),//iTraceMask[KNumTraceMaskWords];iInitialBTraceFilter[8];
+iInitialBTraceBuffer(0),iInitialBTraceMode(0),iDebugPort(0),
+iDebugPortParsed(EFalse),iRootDirectory(0),iDllDataTop(0x40000000),
+iKernelConfigFlags(0),iPagingPolicyParsed(EFalse),iCodePagingPolicyParsed(EFalse),
+iDataPagingPolicyParsed(EFalse),iPagingOverrideParsed(EFalse),
+iCodePagingOverrideParsed(EFalse),iDataPagingOverrideParsed(EFalse),
+/*iPlatSecDisabledCaps(), */iPlatSecDisabledCapsParsed(EFalse),iMaxUnpagedMemSize(0),
+iReader(aReader),iMissingFiles(0),iLastExecutable(0),iAreaSet(),iFirstFile(0),
+iCurrentFile(0),iLastVariantFile(0),iFirstDllDataEntry(0),
+iUpdatedMaxUnpagedMemSize(EFalse),iPatchData(new CPatchDataProcessor) {
+
+	TUint i; 
+	for (i=0; i<256; i++)
+		iAllVariantsMask[i]=0;
+	for (i=0; i<(TUint)KNumTraceMaskWords; i++) 
+		iTraceMask[i]=0;
+	for (i=0; i<sizeof(iInitialBTraceFilter)/sizeof(TUint32); i++)
+		iInitialBTraceFilter[i]=0;	
+	memset(&iPlatSecDisabledCaps,0,sizeof(SCapabilitySet));
+	iNextFilePtrPtr = &iFirstFile;
+}
+
+//
+// Destructor
+// 
+CObeyFile::~CObeyFile(){
+
+	Release();
+	if(iRomFileName){
+		delete [] iRomFileName;
+		iRomFileName = 0 ;
+	}
+	if (iRootDirectory)
+		iRootDirectory->Destroy();
+	if(iPatchData) {
+		delete iPatchData;
+		iPatchData = 0 ;
+	}
+}
+//
+// Free resources not needed after building a ROM
+// 
+void CObeyFile::Release() {
+	iAreaSet.ReleaseAllAreas();
+	
+	if(iBootFileName) delete [] iBootFileName;
+	if(iPrimaries) delete [] iPrimaries;
+	if(iVariants) delete [] iVariants;
+	if(iExtensions) delete [] iExtensions;
+	if(iDevices) delete [] iDevices;
+
+	iBootFileName = 0;
+	iPrimaries = 0;
+	iVariants = 0;
+	iExtensions = 0;
+	iDevices = 0;
+	iFirstFile = 0;
+	iNextFilePtrPtr = &iFirstFile;
+}
+
+TRomBuilderEntry *CObeyFile::FirstFile() {
+	iCurrentFile = iFirstFile;
+	return iCurrentFile;
+}
+
+TRomBuilderEntry *CObeyFile::NextFile() {
+	iCurrentFile = iCurrentFile ? iCurrentFile->iNext : 0;
+	return iCurrentFile;
+}
+
+/*
+*Set first link in patchdata linked list
+**/
+void CObeyFile::SetFirstDllDataEntry(DllDataEntry* aDllDataEntry) {
+	iFirstDllDataEntry = aDllDataEntry;
+}
+
+/*
+*Get first link in patchdata linked list
+**/
+DllDataEntry* CObeyFile::GetFirstDllDataEntry() const {
+	return iFirstDllDataEntry;
+}
+
+TInt CObeyFile::ProcessKernelRom() {
+	//
+	// First pass through the obey file to set up key variables
+	//
+	iReader.Rewind();
+
+	TInt count=0;
+	enum EKeyword keyword;
+	while (iReader.NextLine(1,keyword) != KErrEof) {
+		if (keyword == EKeywordExtensionRom) {
+			if (count==0)
+				return KErrNotFound;		// no kernel ROM, just extension ROMs.
+			break;
+		}
+
+		count++;
+		if (! ProcessKeyword(keyword))
+			return KErrGeneral;
+	}
+
+	if (!GotKeyVariables())
+		return KErrGeneral;
+
+	if (! CreateDefaultArea())
+		return KErrGeneral;
+
+	//
+	// second pass to process the file specifications in the obey file building
+	// up the TRomNode directory structure and the TRomBuilderEntry list
+	//
+	iReader.Rewind();
+
+	iRootDirectory = new TRomNode("");
+	iLastExecutable = iRootDirectory;
+
+	TInt align=0;
+	while (iReader.NextLine(2,keyword)!=KErrEof) {
+		if (keyword == EKeywordExtensionRom)
+			break;
+
+		switch (keyword) {
+		case EKeywordSection:
+			if (ParseSection()!=KErrNone)
+				return KErrGeneral;
+			break;
+		case EKeywordAlign:
+			if (iReader.ProcessAlign(align)!=KErrNone)
+				return KErrGeneral;
+			break;
+		case EKeywordHide:
+		case EKeywordAlias:
+		case EKeywordRename:
+			if (!ProcessRenaming(keyword))
+				return KErrGeneral;
+			break;
+		case EKeywordPatchDllData: {
+				// Collect patchdata statements to process at the end
+				StringVector patchDataTokens;
+				SplitPatchDataStatement(patchDataTokens); 
+				iPatchData->AddPatchDataStatement(patchDataTokens);									
+				break;
+			}
+
+		default:
+			if (!ProcessFile(align, keyword))
+				return KErrGeneral;				
+			align=0;
+			break;
+		}
+	}
+	
+	if( !ParsePatchDllData())
+		return KErrGeneral;
+
+	iReader.Mark();			// ready for processing the extension rom(s)
+
+	if (iMissingFiles!=0)
+		return KErrGeneral;
+	if (iNumberOfDataFiles+iNumberOfPeFiles==0) {
+		Print(EError, "No files specified.\n");
+		return KErrGeneral;
+	}
+	if (!CheckHardwareVariants())
+		return KErrGeneral;
+
+	return KErrNone;
+}
+
+//
+// Process the section keyword
+// 
+TInt CObeyFile::ParseSection(){
+	TInt currentLine = iReader.CurrentLine();
+	if (iSectionPosition!=-1)
+		return Print(EError, "Rom already sectioned.  Line %d\n", currentLine);
+	 
+	if (!IsValidNumber(iReader.Word(1)))
+		return Print(EError, "Number required for 'section' keyword on line %d\n", currentLine);
+	TUint32 offset = 0 ;
+	Val(offset,iReader.Word(1)) ; 
+	iSectionStart = offset + iRomLinearBase;
+	if (offset>=(TUint32)iRomSize)
+		return Print(EError, "Sectioned beyond end of Rom.  Line %d\n", currentLine);
+	if (offset&0x0fff)
+		return Print(EError, "Section must be on a 4K boundry.  Line %d\n", currentLine);
+	iSectionPosition=iNumberOfDataFiles + iNumberOfPeFiles;
+	iCurrentSectionNumber++;	
+	return KErrNone;
+}
+
+
+//
+// Process any inline keywords
+// 
+TInt CObeyFile::ParseFileAttributes(TRomNode *aNode, TRomBuilderEntry* aFile) {
+	TInt currentLine = iReader.CurrentLine();
+	enum EFileAttribute attribute;
+	TInt r=KErrNone;
+	TInt index=3;
+	char* arg=0;
+
+	while(r==KErrNone) {
+		r=iReader.NextAttribute(index,(aFile!=0),attribute,arg);
+		if (r!=KErrNone)
+			break;
+		switch(attribute) {
+		case EAttributeStackReserve:
+			r=aFile->SetStackReserve(arg);
+			break;
+		case EAttributeStack:
+			r=aFile->SetStackSize(arg);
+			break;
+		case EAttributeReloc:
+			r=aFile->SetRelocationAddress(arg);
+			break;
+		case EAttributeCodeAlign:
+			r=aFile->SetCodeAlignment(arg);
+			break;
+		case EAttributeDataAlign:
+			r=aFile->SetDataAlignment(arg);
+			break;
+		case EAttributeFixed:
+			r=aFile->SetRelocationAddress(NULL);
+			break;
+		case EAttributeAtt:
+			r=aNode->SetAtt(arg);
+			break;
+		case EAttributeUid1:
+			r=aFile->SetUid1(arg);
+			break;
+		case EAttributeUid2:
+			r=aFile->SetUid2(arg);
+			break;
+		case EAttributeUid3:
+			r=aFile->SetUid3(arg);
+			break;
+		case EAttributeHeapMin:
+			r=aFile->SetHeapSizeMin(arg);
+			break;
+		case EAttributeHeapMax:
+			r=aFile->SetHeapSizeMax(arg);
+			break;
+		case EAttributePriority:
+			r=aFile->SetPriority(arg);
+			break;
+		case EAttributePatched:
+			if (iSectionPosition!=-1)
+				return Print(EError, "Not sensible to patch files in top section.  Line %d.\n", currentLine);
+			aFile->iPatched=ETrue;
+			break;
+		case EAttributeKeepIAT:
+			aFile->iOverrideFlags |= KOverrideKeepIAT;
+			break;
+		case EAttributeHidden:
+			if (aFile->Extension())
+				return Print(EError, "Cannot hide Extension. Line %d.\n", currentLine);
+			aNode->iHidden=ETrue;
+			break;
+		case EAttributeArea: {
+				TRACE(TAREA, Print(EScreen, "Area Attribute: %s\n", arg));
+				const Area* area = aFile->iArea;
+				if (! ParseAreaAttribute(arg, currentLine, area))
+					return KErrGeneral;
+			}
+			break;
+		case EAttributeProcessSpecific:
+			if (!IsValidFilePath(arg)) {
+				Print(EError, "Invalid file path for process attribute on line %d\n", currentLine);
+				return KErrGeneral;
+			}
+			r=aFile->SetAttachProcess(arg);
+			break;
+		case EAttributeCapability:
+			r=aFile->SetCapability(arg);
+			break;
+		case EAttributePreferred:
+			aFile->iPreferred = ETrue;
+			break;
+		case EAttributeUnpaged:
+			aFile->iOverrideFlags |= KOverrideCodeUnpaged | KOverrideDataUnpaged;
+			aFile->iOverrideFlags &= ~(KOverrideCodePaged | KOverrideDataPaged);
+			break;
+		case EAttributePaged:
+			aFile->iOverrideFlags |= KOverrideCodePaged;
+			aFile->iOverrideFlags &= ~(KOverrideCodeUnpaged);
+			break;
+		case EAttributeUnpagedCode:
+			aFile->iOverrideFlags |= KOverrideCodeUnpaged;
+			aFile->iOverrideFlags &= ~KOverrideCodePaged;
+			break;
+		case EAttributePagedCode:
+			aFile->iOverrideFlags |= KOverrideCodePaged;
+			aFile->iOverrideFlags &= ~KOverrideCodeUnpaged;
+			break;
+		case EAttributeUnpagedData:
+			aFile->iOverrideFlags |= KOverrideDataUnpaged;
+			aFile->iOverrideFlags &= ~KOverrideDataPaged;
+			break;
+		case EAttributePagedData:
+			aFile->iOverrideFlags |= KOverrideDataPaged;
+			aFile->iOverrideFlags &= ~KOverrideDataUnpaged;
+			break;
+
+		default:
+			return Print(EError, "Unrecognised keyword in file attributes on line %d.\n",currentLine);
+		}
+	}
+
+	// aFile may be null if processing an extension ROM
+	if (aFile && aFile->iPatched && ! aFile->iArea->IsDefault()) {
+		return Print(EError, "Relocation to area at line %d forbidden because file is patched\n", currentLine);
+	}
+
+	if (r==KErrEof)
+		return KErrNone;
+	return r;
+}
+
+TUint32 CObeyFile::ParseVariant() {
+	if (iReader.Count() == 0 || stricmp(iReader.Word(0), "rem")==0)
+		return KVariantIndependent;
+	const char* left=iReader.Suffix();
+	if (left == 0 || *left=='\0')
+		return KVariantIndependent;
+	const char* right=left+strlen(left)-1;
+	if (*left=='[' && *right==']') { 
+		string s(left+1);
+		string s2=s.substr(0,right-(left+1));
+		if(IsValidNumber(s2.c_str())){
+			TUint32 temp = 0 ;
+			Val(temp,s2.c_str());
+			return temp;
+		}
+	}
+	//#endif
+	Print(EError,"Syntax error in variant, %s keyword on line %d\n", iReader.Word(0), iReader.CurrentLine());
+	return KVariantIndependent;
+}
+
+//
+// Process a parsed line to set up one or more new TRomBuilder entry objects.
+// iWord[0] = the keyword (file, primary or secondary)
+// iWord[1] = the PC pathname
+// iWord[2] = the EPOC pathname
+// iWord[3] = start of the file attributes
+// 
+TBool CObeyFile::ProcessFile(TInt aAlign, enum EKeyword aKeyword){
+
+	TUint imageFlags = 0;
+	TUint overrides = 0;
+	TBool isPeFile = ETrue;
+	TBool isResource = EFalse;
+	TBool isNonXIP = EFalse;
+	TUint compression = 0;
+	TBool callEntryPoint = EFalse;
+	TUint hardwareVariant=KVariantIndependent;
+	TBool mustBeInSysBin = EFalse;
+	TBool tryForSysBin = EFalse;
+	TBool warnFlag = EFalse;
+
+	// do some validation of the keyword
+	TInt currentLine = iReader.CurrentLine();
+
+	switch (aKeyword) {
+	case EKeywordPrimary:
+		imageFlags |= KRomImageFlagPrimary;
+		overrides |= KOverrideCodeUnpaged | KOverrideDataUnpaged;
+		mustBeInSysBin = gPlatSecEnforceSysBin;
+		warnFlag = gEnableStdPathWarning;		
+		hardwareVariant=ParseVariant();
+		if (iKernelModel==ESingleKernel && !THardwareVariant(hardwareVariant).IsIndependent()) {
+			Print(EError,"Kernel must be independent in single kernel ROMs\n");
+		}
+		break;
+
+	case EKeywordSecondary:
+		imageFlags |= KRomImageFlagSecondary;
+		mustBeInSysBin = gPlatSecEnforceSysBin;
+		warnFlag = gEnableStdPathWarning;
+		hardwareVariant=ParseVariant();
+		break;
+
+	case EKeywordVariant:
+		imageFlags |= KRomImageFlagVariant;
+		overrides |= KOverrideCodeUnpaged | KOverrideDataUnpaged;
+		mustBeInSysBin = gPlatSecEnforceSysBin;
+		warnFlag = gEnableStdPathWarning;		
+		hardwareVariant=ParseVariant();
+		break;
+
+	case EKeywordExtension:
+		imageFlags |= KRomImageFlagExtension;
+		overrides |= KOverrideCodeUnpaged | KOverrideDataUnpaged;
+		mustBeInSysBin = gPlatSecEnforceSysBin;
+		warnFlag = gEnableStdPathWarning;
+		hardwareVariant=ParseVariant();
+		break;
+
+	case EKeywordDevice:
+		imageFlags |= KRomImageFlagDevice;
+		overrides |= KOverrideCodeUnpaged | KOverrideDataUnpaged;
+		mustBeInSysBin = gPlatSecEnforceSysBin;
+		warnFlag = gEnableStdPathWarning;		
+		hardwareVariant=ParseVariant();
+		break;
+
+	case EKeywordExecutableCompressionMethodBytePair:
+		compression=KUidCompressionBytePair;
+
+	case EKeywordExecutableCompressionMethodInflate:
+	case EKeywordFileCompress:
+		compression = compression ? compression : KUidCompressionDeflate;
+
+	case EKeywordExecutableCompressionMethodNone:	
+	case EKeywordFileUncompress:
+		isNonXIP = ETrue;
+	case EKeywordData:
+		iNumberOfDataFiles++;
+		isPeFile = EFalse;
+		isResource = ETrue;
+		hardwareVariant=ParseVariant();
+		tryForSysBin = gPlatSecEnforceSysBin;
+		break;	 
+
+	case EKeywordHardwareConfigRepositoryData:
+		if(iNumberOfHCRDataFiles){
+			Print(EError,"Multiple keywords '%s' on line %d.\n",iReader.Word(0),currentLine);
+			return EFalse ;
+		}
+		compression = EFalse ; 
+		overrides |= KOverrideCodeUnpaged | KOverrideDataUnpaged | KOverrideHCRData;
+		warnFlag = gEnableStdPathWarning;	 
+		iNumberOfHCRDataFiles ++ ;
+		isPeFile = EFalse;
+		break;
+
+	case EKeywordDll:
+		callEntryPoint = ETrue;
+		// and fall through to handling for "file"
+
+	case EKeywordFile: {
+
+		char* nname = NormaliseFileName(iReader.Word(1)); 
+		strupr(nname);
+		if( gCompressionMethod == 0 || NULL != strstr(nname, ".DLL") || callEntryPoint ) {
+			mustBeInSysBin = gPlatSecEnforceSysBin;
+			warnFlag = gEnableStdPathWarning;			
+			hardwareVariant=ParseVariant();
+		}
+		else  {
+			compression = gCompressionMethod;
+			hardwareVariant=ParseVariant();
+			tryForSysBin = gPlatSecEnforceSysBin;
+		}
+		delete []nname ;
+	}
+	break;
+
+	default:
+		Print(EError,"Unexpected keyword '%s' on line %d.\n",iReader.Word(0),currentLine);
+		return EFalse;
+	}
+
+	if (isPeFile)
+		iNumberOfPeFiles++;
+
+	// check the PC file exists
+	char* nname = NormaliseFileName(iReader.Word(1)); 
+	ifstream test(nname,ios_base::binary | ios_base::in); 
+
+	if (!test.is_open()) {
+		Print(EError,"Cannot open file %s for input.\n",iReader.Word(1));
+		if(EKeywordHardwareConfigRepositoryData == aKeyword) {
+			delete []nname;
+			return EFalse ;
+		}
+		iMissingFiles++;
+	}
+	if(EKeywordHardwareConfigRepositoryData == aKeyword) { // check hcr file 
+
+		TUint32 magicWord = 0;
+		test.read(reinterpret_cast<char*>(&magicWord),sizeof(TUint32));
+		if(0x66524348 != magicWord) {
+			Print(EError,"Invalid hardware configuration repository data file %s .\n",iReader.Word(1));
+			test.close();
+			delete []nname;
+			return EFalse;
+		}
+
+	}
+	test.close();
+	delete []nname;
+
+
+	TBool endOfName=EFalse; 
+	if (IsValidFilePath(iReader.Word(2)) == NULL) {
+		Print(EError, "Invalid destination path on line %d\n",currentLine);
+		return EFalse;
+	}
+	char* epocStartPtr = NormaliseFileName(iReader.Word(2));
+	char* savedPtr = epocStartPtr;
+	if(*epocStartPtr == '/' ||*epocStartPtr == '\\')
+				epocStartPtr++ ;
+#ifdef __LINUX__
+	if(tryForSysBin) {
+		if(strnicmp(epocStartPtr, "system/bin/", 11)==0)
+			mustBeInSysBin = 1;
+		if(strnicmp(epocStartPtr, "system/libs/", 12)==0)
+			mustBeInSysBin = 1;
+		if(strnicmp(epocStartPtr, "system/programs/", 16)==0)
+			mustBeInSysBin = 1;
+	}
+
+	static const char sysBin[] = "sys/bin/";
+#else
+	if(tryForSysBin) {
+		if(strnicmp(epocStartPtr, "system\\bin\\", 11)==0)
+			mustBeInSysBin = 1;
+		if(strnicmp(epocStartPtr, "system\\libs\\", 12)==0)
+			mustBeInSysBin = 1;
+		if(strnicmp(epocStartPtr, "system\\programs\\", 16)==0)
+			mustBeInSysBin = 1;
+	}
+
+	static const char sysBin[] = "sys\\bin\\";
+#endif
+	static const int sysBinLength = sizeof(sysBin)-1;
+
+	if (strnicmp(epocStartPtr, sysBin, sysBinLength)!=0) {
+		if(mustBeInSysBin) {
+			TInt len = strlen((char*)epocStartPtr);
+			TInt i = len;
+			while(--i>=0) if(epocStartPtr[i] == SLASH_CHAR) break;
+			++i;
+			char* old = (char*)epocStartPtr;
+			epocStartPtr = new char[sysBinLength+(len-i)+1];
+			strcpy((char*)epocStartPtr,sysBin);
+			strcat((char*)epocStartPtr,old+i);
+			delete []old;
+			savedPtr = epocStartPtr;
+			Print(EDiagnostic, "%s moved to %s\n", old, epocStartPtr); 
+		}
+		else if (warnFlag) {
+			Print(EWarning, "Outside standard path at %s\n", epocStartPtr);
+		}		
+	}	
+
+	char *epocEndPtr=epocStartPtr; 
+
+	TRomNode* dir=iRootDirectory;
+	TRomNode* subDir=0;
+	TRomBuilderEntry *file=0;
+	while (!endOfName) {
+		endOfName = GetNextBitOfFileName(epocEndPtr);
+		if (endOfName){ // file 
+			TRomNode* alreadyExists=dir->FindInDirectory(epocStartPtr,hardwareVariant);
+			if (alreadyExists) { // duplicate file 
+				if (gKeepGoing) {
+					Print(EWarning, "Duplicate file for %s on line %d, will be ignored\n",iReader.Word(1),iReader.CurrentLine());
+					delete []savedPtr;
+					switch (aKeyword) {
+						case EKeywordExecutableCompressionMethodBytePair:
+						case EKeywordExecutableCompressionMethodInflate:
+						case EKeywordFileCompress:
+						case EKeywordExecutableCompressionMethodNone:	
+						case EKeywordFileUncompress:
+						case EKeywordData:
+							iNumberOfDataFiles--;
+							break;
+						case EKeywordHardwareConfigRepositoryData:
+							iNumberOfHCRDataFiles -- ;
+							break;	
+						default:	
+							break;
+					}		
+					if (isPeFile)
+						iNumberOfPeFiles--;
+					return ETrue;
+				
+				}
+				else {
+					Print(EError, "Duplicate file for %s on line %d\n",iReader.Word(1),iReader.CurrentLine());
+					delete []savedPtr;
+					return EFalse;
+				}
+			}
+			file = new TRomBuilderEntry(iReader.Word(1),epocStartPtr);
+			file->iRomImageFlags = imageFlags;
+			file->iResource = isResource;
+			file->iNonXIP = isNonXIP;
+			file->iCompression = compression;
+
+			file->iArea = iAreaSet.FindByName(AreaSet::KDefaultAreaName);
+			file->iRomSectionNumber = iCurrentSectionNumber;
+			file->iHardwareVariant = hardwareVariant;
+			file->iOverrideFlags |= overrides;
+			if (callEntryPoint)
+				file->SetCallEntryPoint(callEntryPoint);
+			file->iAlignment=aAlign;
+			TUint32 uid;
+			file->iBareName = SplitFileName(file->iName, uid, file->iVersionInName, file->iVersionPresentInName);
+			assert(uid==0 && !(file->iVersionPresentInName & EUidPresent));
+			if (strchr(file->iBareName, '{') || strchr(file->iBareName, '}')) {
+				Print(EError, "Illegal character in name %s on line %d\n", file->iName, iReader.CurrentLine());
+				delete file;
+				delete []savedPtr;
+				return EFalse;
+			}
+			TRomNode* node=new TRomNode(epocStartPtr, file);
+			if (node==0){
+				delete file;
+				delete []savedPtr;
+				return EFalse;
+			}
+
+			TInt r=ParseFileAttributes(node, file);
+			if (r!=KErrNone){
+				delete file;
+				delete node;
+				delete []savedPtr;
+				return EFalse;
+			}
+
+			TRACE(TAREA, Print(EScreen, "File %s area '%s'\n", iReader.Word(1), file->iArea->Name()));
+
+			// Apply some specific overrides to the primary
+			if (imageFlags & KRomImageFlagPrimary) {
+				if (file->iCodeAlignment < iPageSize)
+					file->iCodeAlignment = iPageSize;	// Kernel code is at least page aligned
+				file->iHeapSizeMin = iKernHeapMin;
+				file->iHeapSizeMax = iKernHeapMax;
+				file->iOverrideFlags |= KOverrideHeapMin+KOverrideHeapMax;
+			}
+
+			if (!file->iPatched)
+				dir->AddFile(node);	// to ROM directory structure, though possibly hidden
+			if (isPeFile)
+				TRomNode::AddExecutableFile(iLastExecutable, node);
+
+			AddFile(file);
+		}		 
+		else // directory {
+			subDir = dir->FindInDirectory(epocStartPtr);
+		if (!subDir) { // sub directory does not exist 
+			subDir = dir->NewSubDir(epocStartPtr);
+			if (!subDir){
+				delete []savedPtr;
+				return EFalse;
+			}
+		}
+		dir=subDir;
+		epocStartPtr = epocEndPtr;
+	}
+ 
+	delete []savedPtr;
+	return ETrue;	
+}
+
+
+void CObeyFile::AddFile(TRomBuilderEntry* aFile) {
+	aFile->iArea->AddFile(aFile);
+
+	*iNextFilePtrPtr = aFile;
+	iNextFilePtrPtr = &(aFile->iNext);
+}
+
+
+TBool CObeyFile::ProcessRenaming(enum EKeyword aKeyword) {
+	TUint hardwareVariant=ParseVariant();
+
+	// find existing file
+	TBool endOfName=EFalse;
+
+	// Store the current name and new name to maintain renamed file map
+	string currentName=iReader.Word(1);
+	string newName=iReader.Word(2);
+
+	 
+	if (IsValidFilePath(iReader.Word(1)) == NULL) {
+		Print(EError, "Invalid source path on line %d\n",iReader.CurrentLine());
+		return EFalse;
+	}
+	char* epocStartPtr = NormaliseFileName(iReader.Word(1));
+	char* savedPtr = epocStartPtr;	
+	if(*epocStartPtr == '/' ||*epocStartPtr == '\\')
+		epocStartPtr++ ;
+	char* epocEndPtr = epocStartPtr; 
+	char saved_srcname[257];
+	strcpy(saved_srcname, iReader.Word(1));
+
+	TRomNode* dir=iRootDirectory;
+	TRomNode* existingFile=0;
+	while (!endOfName) {
+		endOfName = GetNextBitOfFileName(epocEndPtr);
+		if (endOfName) { // file 
+			existingFile=dir->FindInDirectory(epocStartPtr,hardwareVariant);
+			if (existingFile) {
+				TInt fileCount=0;
+				TInt dirCount=0;
+				existingFile->CountDirectory(fileCount, dirCount);
+				if (dirCount != 0 || fileCount != 0) {					
+					Print(EError, "Keyword %s not applicable to directories - line %d\n",
+						iReader.Word(0),iReader.CurrentLine());
+					delete []savedPtr;
+					return EFalse;
+					
+				}
+			}
+		}
+		else {// directory 
+			TRomNode* subDir = dir->FindInDirectory(epocStartPtr);
+			if (!subDir) // sub directory does not exist
+				break;
+			dir=subDir;
+			epocStartPtr = epocEndPtr;
+		}
+	}
+	if (aKeyword == EKeywordHide) {
+		if (!existingFile) {
+			Print(EWarning, "Hiding non-existent file %s on line %d\n", 
+				saved_srcname, iReader.CurrentLine());
+			// Just a warning, as we've achieved the right overall effect.
+		}
+		else {
+			existingFile->iHidden = ETrue;
+		}
+		delete []savedPtr;
+		return ETrue;
+	}
+
+	if (!existingFile) {
+		Print(EError, "Can't %s non-existent source file %s on line %d\n",
+			iReader.Word(0), saved_srcname, iReader.CurrentLine());
+		delete []savedPtr;
+		return EFalse;
+	}
+	delete []savedPtr;
+	epocStartPtr=(char*)IsValidFilePath(iReader.Word(2));
+	epocEndPtr=epocStartPtr;
+	endOfName=EFalse;
+	if (epocStartPtr==NULL) {
+		Print(EError, "Invalid destination path on line %d\n",iReader.CurrentLine());
+		return EFalse;
+	}
+
+	TRomNode* newdir=iRootDirectory;
+	while (!endOfName) {
+		endOfName = GetNextBitOfFileName(epocEndPtr);
+		if (endOfName){ // file 
+			TRomNode* alreadyExists=newdir->FindInDirectory(epocStartPtr,existingFile->HardwareVariant());
+			if (alreadyExists) { // duplicate file 
+				if (gKeepGoing) {
+					Print(EWarning, "Duplicate file for %s on line %d, renaming will be skipped\n",saved_srcname,iReader.CurrentLine());
+					return ETrue;			
+				}
+				else {
+					Print(EError, "Duplicate file for %s on line %d\n",saved_srcname,iReader.CurrentLine());
+					return EFalse;
+				}
+			}
+		}
+		else { // directory 
+			TRomNode* subDir = newdir->FindInDirectory(epocStartPtr);
+			if (!subDir) { // sub directory does not exist 
+				subDir = newdir->NewSubDir(epocStartPtr);
+				if (!subDir)
+					return EFalse;
+			}
+			newdir=subDir;
+			epocStartPtr = epocEndPtr;
+		}
+	}
+
+	if (aKeyword == EKeywordRename) {
+		// rename => remove existingFile and insert into tree at new place
+		// has no effect on the iNextExecutable or iNextNodeForSameFile links
+
+		TInt r=ParseFileAttributes(existingFile, existingFile->iRomFile->iRbEntry);
+		if (r!=KErrNone)
+			return EFalse;
+		r = existingFile->Rename(dir, newdir, epocStartPtr);
+		if (r==KErrBadName) {
+			Print(EError, "Bad name %s at line %d\n", epocStartPtr, iReader.CurrentLine());
+			return EFalse;
+		}
+		else if (r==KErrArgument) {
+			Print(EError, "Version in name %s does not match version in file header at line %d\n", epocStartPtr, iReader.CurrentLine());
+			return EFalse;
+		}
+		// Store the current and new name of file in the renamed file map.
+		iPatchData->AddToRenamedFileMap(currentName, newName);
+		return ETrue;
+	}
+
+	// alias => create new TRomNode entry and insert into tree
+
+	TRomNode* node = new TRomNode(epocStartPtr, existingFile);
+	if (node == 0) {
+		Print(EError, "Out of memory\n");
+		return EFalse;
+	}
+
+	TInt r = node->Alias(existingFile, iLastExecutable);
+	if (r==KErrBadName) {
+		Print(EError, "Bad name %s at line %d\n", epocStartPtr, iReader.CurrentLine());
+		return EFalse;
+	}
+	else if (r==KErrArgument) {
+		Print(EError, "Version in name %s does not match version in file header at line %d\n", epocStartPtr, iReader.CurrentLine());
+		return EFalse;
+	}
+	r=ParseFileAttributes(node, 0);
+	if (r!=KErrNone)
+		return EFalse;
+
+	newdir->AddFile(node);	// to ROM directory structure, though possibly hidden
+
+	return ETrue;
+}
+
+
+TInt ParsePagingPolicy(const char* policy) {
+	if(stricmp(policy,"NOPAGING")==0)
+		return EKernelConfigPagingPolicyNoPaging;
+	else if (stricmp(policy,"ALWAYSPAGE")==0)
+		return EKernelConfigPagingPolicyAlwaysPage;
+	else if(stricmp(policy,"DEFAULTUNPAGED")==0)
+		return EKernelConfigPagingPolicyDefaultUnpaged;
+	else if(stricmp(policy,"DEFAULTPAGED")==0)
+		return EKernelConfigPagingPolicyDefaultPaged;
+	return KErrArgument;
+}
+
+
+TBool CObeyFile::ProcessKeyword(enum EKeyword aKeyword) {
+	TUint hardwareVariant=KVariantIndependent; 
+	TBool success = ETrue;
+	switch (aKeyword) {
+	case EKeywordUnicode:
+		Unicode=ETrue;
+		break;
+	case EKeywordAscii:
+		Unicode=EFalse;
+		break;
+
+	case EKeywordSingleKernel:
+		iKernelModel=ESingleKernel;
+		break;
+	case EKeywordMultiKernel:
+		iKernelModel=EMultipleKernels;
+		break;
+
+	case EKeywordBootBinary:
+		iBootFileName = iReader.DupWord(1);
+		break;
+	case EKeywordRomName:
+		iRomFileName = iReader.DupWord(1);
+		break;
+	case EKeywordRomNameOdd:
+		iRomOddFileName = iReader.DupWord(1);
+		break;
+	case EKeywordRomNameEven:
+		iRomEvenFileName = iReader.DupWord(1);
+		break;
+	case EKeywordSRecordFileName:
+		iSRecordFileName = iReader.DupWord(1);
+		break;
+
+	case EKeywordRomLinearBase:
+		Val(iRomLinearBase,iReader.Word(1));
+		break;
+	case EKeywordRomSize:
+		Val(iRomSize,iReader.Word(1));
+		break;
+	case EKeywordRomAlign:
+		Val(iRomAlign,iReader.Word(1));
+		break;
+	case EKeywordKernelDataAddress:
+		Val(iKernDataRunAddress,iReader.Word(1));
+		break;
+	case EKeywordKernelHeapMin:
+		Val(iKernHeapMin,iReader.Word(1));
+		break;
+	case EKeywordKernelHeapMax:
+		Val(iKernHeapMax,iReader.Word(1));
+		break;
+	case EKeywordDataAddress:
+		Val(iDataRunAddress,iReader.Word(1));
+		break;
+	case EKeywordDefaultStackReserve:
+		Val(iDefaultStackReserve,iReader.Word(1));
+		break;
+	case EKeywordVersion:
+		{
+			istringstream val(iReader.Word(1));
+			val >> iVersion ;
+		}
+		break;
+	case EKeywordSRecordBase:
+		Val(iSRecordBase,iReader.Word(1));
+		break;
+	case EKeywordRomChecksum:
+		Val(iCheckSum,iReader.Word(1));
+		break;
+	case EKeywordHardware:
+		Val(iHardware,iReader.Word(1));
+		break;
+	case EKeywordLanguages:
+		iReader.ProcessLanguages(iLanguage);
+		break;
+	case EKeywordTime:
+		iReader.ProcessTime(iTime);
+		break;
+	case EKeywordDllDataTop:
+		Val(iDllDataTop,iReader.Word(1));
+		break;
+
+	case EKeywordMemModel: {
+			const char* arg1=iReader.Word(1);
+			const char* arg2=iReader.Word(2);
+			const char* arg3=iReader.Word(3);
+			const char* arg4=iReader.Word(4);
+			if (strnicmp(arg1, "moving", 6)==0)
+				iMemModel=E_MM_Moving;
+			else if (strnicmp(arg1, "direct", 6)==0)
+				iMemModel=E_MM_Direct;
+			else if (strnicmp(arg1, "multiple", 8)==0)
+				iMemModel=E_MM_Multiple;
+			else if (strnicmp(arg1, "flexible", 8)==0)
+				iMemModel=E_MM_Flexible;
+			else {
+				Print(EError, "Unknown memory model specified\n");
+				success = EFalse;
+			}
+			if (IsValidNumber(arg2)) { 
+				Val(iChunkSize,arg2); 
+			}
+			if (iMemModel!=E_MM_Direct && IsValidNumber(arg3)) { 
+				 Val(iPageSize,arg3); 
+			}
+			else if (iMemModel==E_MM_Direct)
+				iPageSize=iChunkSize;
+			if (iMemModel!=E_MM_Direct && IsValidNumber(arg4)) { 
+				Val(iVirtualAllocSize,arg4); 
+			}
+			else
+				iVirtualAllocSize = iPageSize;
+
+			break;
+		}
+	case EKeywordNoWrapper:
+		if (gHeaderType<0)
+			gHeaderType=0;
+		break;
+	case EKeywordEpocWrapper:
+		if (gHeaderType<0)
+			gHeaderType=1;
+		break;
+	case EKeywordCoffWrapper:
+		if (gHeaderType<0)
+			gHeaderType=2;
+		break;
+
+	case EKeywordPlatSecEnforcement:
+		ParseBoolArg(gPlatSecEnforcement,iReader.Word(1));
+		if(gPlatSecEnforcement)
+			iKernelConfigFlags |= EKernelConfigPlatSecEnforcement;
+		else
+			iKernelConfigFlags &= ~EKernelConfigPlatSecEnforcement;
+		break;
+	case EKeywordPlatSecDiagnostics:
+		ParseBoolArg(gPlatSecDiagnostics,iReader.Word(1));
+		if(gPlatSecDiagnostics)
+			iKernelConfigFlags |= EKernelConfigPlatSecDiagnostics;
+		else
+			iKernelConfigFlags &= ~EKernelConfigPlatSecDiagnostics;
+		break;
+	case EKeywordPlatSecProcessIsolation: {
+			TInt processIsolation;
+			ParseBoolArg(processIsolation,iReader.Word(1));
+			if(processIsolation)
+				iKernelConfigFlags |= EKernelConfigPlatSecProcessIsolation;
+			else
+				iKernelConfigFlags &= ~EKernelConfigPlatSecProcessIsolation;
+			break;
+		}
+	case EKeywordPlatSecEnforceSysBin: {
+			ParseBoolArg(gPlatSecEnforceSysBin,iReader.Word(1));
+			if(gPlatSecEnforceSysBin)
+				iKernelConfigFlags |= EKernelConfigPlatSecEnforceSysBin;
+			else
+				iKernelConfigFlags &= ~EKernelConfigPlatSecEnforceSysBin;
+			break;
+		}
+	case EKeywordPlatSecDisabledCaps:
+		if(iPlatSecDisabledCapsParsed)
+			Print(EWarning, "PlatSecDisabledCaps redefined - previous values lost\n"); {
+			ParseCapabilitiesArg(iPlatSecDisabledCaps, iReader.Word(1));
+			gPlatSecDisabledCaps = iPlatSecDisabledCaps;
+			iPlatSecDisabledCapsParsed=ETrue;
+		}
+		break;
+	case EKeywordPagingPolicy: {
+			if(iPagingPolicyParsed)
+				Print(EWarning, "PagingPolicy redefined - previous PagingPolicy values lost\n");
+			if(iCodePagingPolicyParsed)
+				Print(EWarning, "PagingPolicy defined - previous CodePagingPolicy values lost\n");
+			iPagingPolicyParsed = true;
+			iKernelConfigFlags &= ~(EKernelConfigCodePagingPolicyMask);
+			TInt policy = ParsePagingPolicy(iReader.Word(1));
+			if(policy<0) {
+				Print(EError,"Unrecognized option for PAGINGPOLICY keyword\n");
+				success = false;
+			}
+			else 	{
+#ifndef SYMBIAN_WRITABLE_DATA_PAGING
+				if ((policy != EKernelConfigPagingPolicyNoPaging) && (iMemModel == E_MM_Flexible))
+					Print(EWarning, "SYMBIAN_WRITABLE_DATA_PAPING is not defined. Writable data paging is not warranted on this version of Symbian.");
+#endif
+				iKernelConfigFlags |= policy << EKernelConfigCodePagingPolicyShift;
+				if((policy==EKernelConfigPagingPolicyNoPaging) || (policy==EKernelConfigPagingPolicyDefaultUnpaged))
+					iKernelConfigFlags |= policy << EKernelConfigDataPagingPolicyShift;
+			}
+		}
+		break;
+	case EKeywordCodePagingPolicy: {
+			if(iCodePagingPolicyParsed)
+				Print(EWarning, "CodePagingPolicy redefined - previous CodePagingPolicy values lost\n");
+			if(iPagingPolicyParsed)
+				Print(EWarning, "CodePagingPolicy defined - previous PagingPolicy values lost\n");
+			iCodePagingPolicyParsed = true;
+			iKernelConfigFlags &= ~EKernelConfigCodePagingPolicyMask;
+			TInt policy = ParsePagingPolicy(iReader.Word(1));
+			if(policy<0) {
+				Print(EError,"Unrecognised option for CODEPAGINGPOLICY keyword\n");
+				success = false;
+			}
+			else
+				iKernelConfigFlags |= policy << EKernelConfigCodePagingPolicyShift;
+		}
+		break;
+	case EKeywordDataPagingPolicy: {
+			if(iDataPagingPolicyParsed)
+				Print(EWarning, "DataPagingPolicy redefined - previous DataPagingPolicy values lost\n");
+			if(iPagingPolicyParsed)
+				Print(EWarning, "DataPagingPolicy defined - previous PagingPolicy values lost\n");
+			iDataPagingPolicyParsed = true;
+			iKernelConfigFlags &= ~EKernelConfigDataPagingPolicyMask;
+			TInt policy = ParsePagingPolicy(iReader.Word(1));
+			if(policy<0) {
+				Print(EError,"Unrecognized option for DATAPAGINGPOLICY keyword\n");
+				success = false;
+			}
+			else
+#ifndef SYMBIAN_WRITABLE_DATA_PAGING
+				if ((policy != EKernelConfigPagingPolicyNoPaging) && (iMemModel == E_MM_Flexible))
+					Print(EWarning, "SYMBIAN_WRITABLE_DATA_PAPING is not defined. Writable data paging is not warranted on this version of Symbian.");
+#endif
+			iKernelConfigFlags |= policy << EKernelConfigDataPagingPolicyShift;
+		}
+		break;
+	case EKeywordPagingOverride: {
+			if(iPagingOverrideParsed)
+				Print(EWarning, "PagingOverride redefined - previous PagingOverride values lost\n");
+			if(iCodePagingOverrideParsed)
+				Print(EWarning, "PagingOverride defined - previous CodePagingOverride values lost\n");
+			iPagingOverrideParsed = true;
+			TInt policy = ParsePagingPolicy(iReader.Word(1));
+			if(policy<0) {
+				Print(EError,"Unrecognized option for PAGINGOVERRIDE keyword\n");
+				success = false;
+			}
+			else {
+				gCodePagingOverride = policy;
+				if((policy==EKernelConfigPagingPolicyNoPaging) || (policy==EKernelConfigPagingPolicyDefaultUnpaged))
+					gDataPagingOverride = policy;
+			}
+		}
+		break;
+	case EKeywordCodePagingOverride: {
+			if(iCodePagingOverrideParsed)
+				Print(EWarning, "CodePagingOverride redefined - previous CodePagingOverride values lost\n");
+			if(iPagingOverrideParsed)
+				Print(EWarning, "CodePagingOverride defined - previous PagingOverride values lost\n");
+			iCodePagingOverrideParsed = true;
+			TInt policy = ParsePagingPolicy(iReader.Word(1));
+			if(policy<0) {
+				Print(EError,"Unrecognised option for CODEPAGINGOVERRIDE keyword\n");
+				success = false;
+			}
+			else
+				gCodePagingOverride = policy;
+		}
+		break;
+	case EKeywordDataPagingOverride: 
+		{
+			if(iDataPagingOverrideParsed)
+				Print(EWarning, "DataPagingOverride redefined - previous DataPagingOverride values lost\n");
+			if(iPagingOverrideParsed)
+				Print(EWarning, "DataPagingOverride defined - previous PagingOverride values lost\n");
+			iDataPagingOverrideParsed = true;
+			TInt policy = ParsePagingPolicy(iReader.Word(1));
+			if(policy<0) {
+				Print(EError,"Unrecognised option for DATAPAGINGOVERRIDE keyword\n");
+				success = false;
+			}
+			else
+				gDataPagingOverride = policy;
+		}
+		break;
+	case EKeywordDemandPagingConfig: 
+		{
+			memset(&gDemandPagingConfig,0,sizeof(gDemandPagingConfig));
+			Val(gDemandPagingConfig.iMinPages,iReader.Word(1));
+			const char* tmp = iReader.Word(2);
+			if(*tmp) {
+				Val(gDemandPagingConfig.iMaxPages,tmp);
+				tmp = iReader.Word(3);
+				if(*tmp){
+					Val(gDemandPagingConfig.iYoungOldRatio,tmp);
+					for(int i = 1 ; i <= 2 ; i++){
+						tmp = iReader.Word(4 + i);
+						if(0 == *tmp) break ;
+							Val(gDemandPagingConfig.iSpare[i],tmp);
+					}
+				}
+			} 
+			if(gDemandPagingConfig.iMaxPages && gDemandPagingConfig.iMaxPages<gDemandPagingConfig.iMinPages) {
+				Print(EError,"DemandPagingConfig maxPages must be >= minPages\n");
+				success = EFalse;
+				break;
+			}
+		}
+		break;
+	case EKeywordPagedRom:
+		gPagedRom = ETrue;
+		break;
+
+	case EKeywordTrace:
+		Val(TraceMask,iReader.Word(1));
+		break;
+
+	case EKeywordKernelTrace: 	
+		iTraceMask[0] = 0;
+		for(int i = 0 ; i < KNumTraceMaskWords ; i++) {
+			const char* tmp = iReader.Word(i+1);
+			if(0 == *tmp) break ;
+			Val(iTraceMask[i],tmp);
+		}	 
+		break;
+
+	case EKeywordBTrace: 
+		iInitialBTraceFilter[0] = 0 ;
+		for(TUint i = 0 ; i < sizeof(iInitialBTraceFilter) / sizeof(iInitialBTraceFilter[0]); i++) {
+			const char* tmp = iReader.Word(i+1);
+			if(0 == *tmp) break ;
+			Val(iInitialBTraceFilter[i],tmp);
+		}
+		break;
+
+	case EKeywordBTraceMode:
+		Val(iInitialBTraceMode,iReader.Word(1));
+		break;
+
+	case EKeywordBTraceBuffer:
+		Val(iInitialBTraceBuffer,iReader.Word(1));
+		break;
+
+	case EKeywordDebugPort:
+		if (iDebugPortParsed)
+			Print(EWarning, "DEBUGPORT redefined - previous value lost\n");
+		Val(iDebugPort,iReader.Word(1));
+		iDebugPortParsed = ETrue;
+		break;
+
+	case EKeywordCompress:
+		gEnableCompress=ETrue; // Set ROM Compression on.
+		break;
+
+	case EKeywordCollapse:
+		if (strnicmp(iReader.Word(1), "arm", 3)!=0 || strnicmp(iReader.Word(2), "gcc", 3)!=0) {
+			Print(EWarning, "COLLAPSE only supported for ARM and GCC - keyword ignored\n");
+		}
+		else {
+
+			TUint32 cm = 0;
+			Val(cm,iReader.Word(3)); 
+			if ((cm & 0x80000000L) != 0 || cm > ECollapseAllChainBranches) {
+				Print(EWarning, "COLLAPSE mode unrecognised - keyword ignored\n");
+			}
+			else
+				iCollapseMode=cm;
+		}
+		break;
+
+	case EKeywordPrimary:
+		iNumberOfPrimaries++;
+		break;
+	case EKeywordVariant:
+		hardwareVariant=ParseVariant();
+		if (THardwareVariant(hardwareVariant).IsVariant()) {
+			iNumberOfVariants++;
+			TUint layer=THardwareVariant(hardwareVariant).Layer();
+			TUint vmask=THardwareVariant(hardwareVariant).VMask();
+			iAllVariantsMask[layer] |= vmask;
+		}
+		else {
+			Print(EError,"Variant DLLs must belong to variant layer - line %d\n", iReader.CurrentLine());
+			break;
+		}
+
+		break;
+	case EKeywordExtension:
+		iNumberOfExtensions++;
+		break;
+	case EKeywordDevice:
+		iNumberOfDevices++;
+		break;
+
+	case EKeywordKernelRomName:
+		Print(EError,"Keyword '%s' only valid in extension ROMs - line %d\n", iReader.Word(0), iReader.CurrentLine());
+		break;
+
+	case EKeywordArea:
+		if(! ParseAreaKeyword())
+			success = EFalse;
+		break;
+
+	case EKeywordExecutableCompressionMethodNone:
+		gCompressionMethod = 0;
+		break;
+
+	case EKeywordExecutableCompressionMethodInflate:
+		gCompressionMethod = KUidCompressionDeflate;
+		break;
+
+	case EKeywordExecutableCompressionMethodBytePair:
+		gCompressionMethod = KUidCompressionBytePair;
+		break;
+
+	case EKeywordKernelConfig: 
+		{
+			TUint32 bit = (TUint32)-1 ;
+			Val(bit,iReader.Word(1)) ; 
+			TInt setTo = 0;
+			 
+			if(bit > 31) {
+				Print(EError,"KernelConfig bit must be between 0 and 31\n");
+				success = EFalse;
+				break;
+			}
+			if(ParseBoolArg(setTo,iReader.Word(2))!=KErrNone) {
+				success = EFalse;
+				break;
+			}
+			if(setTo)
+				iKernelConfigFlags |= 1<<bit;
+			else
+				iKernelConfigFlags &= ~(1<<bit);
+			break;
+		}
+
+	case EKeywordMaxUnpagedMemSize: 
+	{	
+		TUint32 unpagedSize = (TUint32)-1;
+		Val(unpagedSize,iReader.Word(1)); 
+		if (unpagedSize > 0x7FFFFFFF) {
+			Print(EWarning, "Invalid value of MaxUnpagedSize (0 to 0x7FFFFFFF) - value ignored\n");
+			break;
+		}
+
+		iMaxUnpagedMemSize = unpagedSize;
+
+		if(iUpdatedMaxUnpagedMemSize) {
+			Print(EWarning, "MaxUnpagedSize redefined - previous values lost\n");
+		}
+		else {
+			iUpdatedMaxUnpagedMemSize = ETrue;
+		}
+
+		break;
+	}
+
+	default:
+		// unexpected keyword iReader.Word(0)
+		break;
+	}
+
+	return success;
+}
+
+//
+// Checks that the obeyfile has supplied enough variables to continue
+// 
+TBool CObeyFile::GotKeyVariables() {
+
+	TBool retVal=ETrue;
+
+	// Mandatory keywords
+
+	if (iRomFileName==0) {
+		Print(EAlways,"The name of the ROM has not been supplied.\n");
+		Print(EAlways,"Use the keyword \"romname\".\n");
+		retVal = EFalse;
+	}
+	if (iBootFileName==0) {
+		Print(EAlways,"The name of the bootstrap binary has not been supplied.\n");
+		Print(EAlways,"Use the keyword \"bootbinary\".\n");
+		retVal = EFalse;
+	}
+	if (iRomLinearBase==0xFFFFFFFF) {
+		Print(EAlways,"The base linear address of the ROM has not been supplied.\n");
+		Print(EAlways,"Use the keyword \"romlinearbase\".\n");
+		retVal = EFalse;
+	}
+	if (iRomSize==0) {
+		Print(EAlways,"The size of the ROM has not been supplied.\n");
+		Print(EAlways,"Use the keyword \"romsize\".\n");
+		retVal = EFalse;
+	}
+	if (iKernDataRunAddress==0) {
+		Print(EAlways,"The address for the kernel's data section has not been supplied.\n");
+		Print(EAlways,"Use the keyword \"kerneldataaddress\".\n");
+		retVal = EFalse;
+	}
+
+	// Validation
+	if (iNumberOfPrimaries>1 && iKernelModel==ESingleKernel) {
+		Print(EError,"More than one primary in single-kernel ROM\n");
+		retVal = EFalse;
+	}
+	if (iNumberOfPrimaries==0) {
+		Print(EError,"No primary file specified\n");
+		retVal = EFalse;
+	}
+	if (iNumberOfVariants==0) {
+		Print(EError,"No variants specified\n");
+		retVal = EFalse;
+	}
+	if(iNumberOfHCRDataFiles > 1) {
+		Print(EError,"More than one hcr data files in ROM.\n");
+		retVal = EFalse ;
+	}
+	// Warn about enabling data paging on OS versions where's it's not officially supported
+#ifndef SYMBIAN_WRITABLE_DATA_PAGING
+	if (iMemModel == E_MM_Flexible &&
+		(iKernelConfigFlags & EKernelConfigDataPagingPolicyMask) != EKernelConfigDataPagingPolicyNoPaging) {
+		Print(EWarning, "Writable data paging is not warranted on this version of Symbian OS.");
+	}
+#endif
+
+	// Apply defaults as necessary
+	TheRomLinearAddress=iRomLinearBase;
+
+	if (iDataRunAddress==0) {
+		iDataRunAddress=0x400000;
+		Print(EWarning,"The address for a running ROM app's data section (keyword \"dataaddress\") has not been supplied.\n");
+		Print(EWarning,"Will use the default value of 0x%0x.\n", iDataRunAddress);
+		retVal = EFalse;
+	}
+	if (iRomAlign==0) {
+		iRomAlign=0x1000;
+		Print(EWarning,"The ROM section alignment (keyword \"romalign\") has not been supplied.\n");
+		Print(EWarning,"Will use the default value of 0x%0x.\n", iRomAlign);
+	}
+	if (iRomAlign&0x3) {
+		Print(EWarning, "Rounding rom alignment to multiple of 4.\n");
+		iRomAlign=(iRomAlign+0x3)&0xfffffffc;
+	}
+	if (iKernHeapMin==0) {
+		iKernHeapMin=0x10000;
+		Print(EWarning,"The kernel heap min size (keyword \"kernelheapmin\") has not been supplied.\n");
+		Print(EWarning,"Will use the default value of 0x%0x.\n", iKernHeapMin);
+	}
+	if (iKernHeapMax==0) {
+		iKernHeapMax=0x100000;
+		Print(EWarning,"The kernel heap max size (keyword \"kernelheapmax\") has not been supplied.\n");
+		Print(EWarning,"Will use the default value of 0x%0x.\n", iKernHeapMax);
+	}
+
+	if (iTime==0) {
+		Print(ELog, "No timestamp specified. Using current time...\n");
+		ObeyFileReader::TimeNow(iTime);
+	}
+
+	Print(ELog, "\nCreating Rom image %s\n", iRomFileName);
+	Print(ELog, "MemModel: %1d\nChunkSize: %08x\nPageSize: %08x\n", iMemModel, iChunkSize, iPageSize);
+	return retVal;
+}
+
+
+//
+// Check the path is valid
+// 
+const char* CObeyFile::IsValidFilePath(const char* aPath) {
+	// skip leading "\"
+	if (*aPath == '/' || *aPath == '\\')
+		aPath++;
+	if (*aPath == 0)
+		return NULL; // file ends in a backslash
+
+	const char *p = aPath;
+	TInt len=0;
+	while(*p) {			
+		if (*p == '/' || *p == '\\') {
+			if (len == 0)
+				return NULL;
+			len=0;
+		}
+		len++;
+		p++;
+	}
+	return (len ? aPath : NULL);
+}
+
+//
+// Move the end pointer past the next directory separator, replacing it with 0
+//
+TBool CObeyFile::GetNextBitOfFileName(char*& epocEndPtr) {
+	while (*epocEndPtr != '/' && *epocEndPtr != '\\'){ // until reach the directory separator		
+		if (*epocEndPtr == 0) // if reach end of string, return TRUE, it's the filename
+			return ETrue;
+		epocEndPtr++;
+	}
+	*epocEndPtr = 0; // overwrite the directory separator with a 0
+	epocEndPtr++; // point past the 0 ready for the next one
+	return EFalse;
+}
+
+
+TBool CObeyFile::CheckHardwareVariants() {
+	iPrimaries=new TRomBuilderEntry*[iNumberOfPrimaries];
+	iVariants=new TRomBuilderEntry*[iNumberOfVariants];
+	THardwareVariant* primaryHwVariants=new THardwareVariant[iNumberOfPrimaries];
+	TInt nVar=0;
+	TRomBuilderEntry* current=FirstFile();
+	THardwareVariant* variantHwVariants=new THardwareVariant[iNumberOfVariants];
+	while(current) {
+		if (current->Variant()) {
+			TInt i;
+			for(i=0; i<nVar; i++) {
+				if (!current->iHardwareVariant.MutuallyExclusive(variantHwVariants[i])) {
+					delete[] variantHwVariants;
+					delete[] primaryHwVariants;
+					Print(EError,"Variants not mutually exclusive\n");
+					return EFalse;
+				}
+			}
+			iVariants[nVar]=current;
+			variantHwVariants[nVar++]=current->iHardwareVariant;
+		}
+		current=NextFile();
+	}
+	delete[] variantHwVariants;
+	nVar=0;
+	current=FirstFile();
+	while(current) {
+		TInt i;
+		for (i=0; i<iNumberOfVariants; i++) {
+			if (iVariants[i]->iHardwareVariant<=current->iHardwareVariant)
+				break;
+		}
+		if (i==iNumberOfVariants) {
+			Print(EError,"File %s[%08x] does not correspond to any variant\n",
+				current->iName,TUint(current->iHardwareVariant));
+			delete[] primaryHwVariants;
+			return EFalse;
+		}
+		if (current->Primary()) {
+			for(i=0; i<nVar; i++) {
+				if (!current->iHardwareVariant.MutuallyExclusive(primaryHwVariants[i])) {
+					delete[] primaryHwVariants;
+					Print(EError,"Primaries not mutually exclusive\n");
+					return EFalse;
+				}
+			}
+			iPrimaries[nVar]=current;
+			primaryHwVariants[nVar++]=current->iHardwareVariant;
+		}
+		current=NextFile();
+	}
+	delete[] primaryHwVariants;
+	if (iNumberOfExtensions) {
+		nVar=0;
+		iExtensions=new TRomBuilderEntry*[iNumberOfExtensions];
+		TRomBuilderEntry* current=FirstFile();
+		while(current) {
+			if (current->Extension()) {
+				if (current->iHardwareVariant.IsVariant()) {
+					TUint layer=current->iHardwareVariant.Layer();
+					TUint vmask=current->iHardwareVariant.VMask();
+					if ((iAllVariantsMask[layer]&vmask)==0) {
+						Print(EError,"Variant-layer extension %s has no corresponding variant DLL\n",current->iName);
+						return EFalse;
+					}
+				}
+				iExtensions[nVar++]=current;
+			}
+			current=NextFile();
+		}
+	}
+	if (iNumberOfDevices) {
+		nVar=0;
+		iDevices=new TRomBuilderEntry*[iNumberOfDevices];
+		TRomBuilderEntry* current=FirstFile();
+		while(current) {
+			if (current->Device()) {
+				if (current->iHardwareVariant.IsVariant()) {
+					TUint layer=current->iHardwareVariant.Layer();
+					TUint vmask=current->iHardwareVariant.VMask();
+					if ((iAllVariantsMask[layer]&vmask)==0) {
+						Print(EError,"Variant-layer device %s has no corresponding variant DLL\n",current->iName);
+						return EFalse;
+					}
+				}
+				iDevices[nVar++]=current;
+			}
+			current=NextFile();
+		}
+	}
+	NumberOfVariants=iNumberOfVariants;
+	return ETrue;
+}
+
+
+TInt CObeyFile::ProcessExtensionRom(MRomImage*& aKernelRom) {
+	//
+	// First pass through the obey file to set up key variables
+	//
+	iReader.Rewind();
+
+	enum EKeyword keyword;
+
+	// Deal with the "extensionrom" keyword, which should be first
+	// however, you may've found "time" before it.
+	while(iReader.NextLine(1,keyword) != KErrEof) {
+		if(EKeywordExtensionRom == keyword)
+			break ;		
+	}
+	if(EKeywordExtensionRom != keyword) return KErrEof;
+
+	iRomFileName = iReader.DupWord(1);
+	Print(ELog, "\n========================================================\n");
+	Print(ELog, "Extension ROM %s starting at line %d\n\n", iRomFileName, iReader.CurrentLine());
+
+	iReader.MarkNext();		// so that we rewind to the line after the extensionrom keyword
+
+	while (iReader.NextLine(1,keyword) != KErrEof) {
+		if (keyword == EKeywordExtensionRom)
+			break;
+		ProcessExtensionKeyword(keyword);
+	}
+
+	if (!GotExtensionVariables(aKernelRom))
+		return KErrGeneral;
+
+	if (! CreateDefaultArea())
+		return KErrGeneral;
+
+	//
+	// second pass to process the file specifications in the obey file building
+	// up the TRomNode directory structure and the TRomBuilderEntry list
+	//
+	iReader.Rewind();
+
+	if (aKernelRom==0)
+		return Print(EError, "Option to extend a kernel ROM image not yet implemented\n");
+	iLastExecutable = 0;
+	iRootDirectory = aKernelRom->CopyDirectory(iLastExecutable);
+
+
+	TInt align=0;
+	while (iReader.NextLine(2,keyword)!=KErrEof) {
+		if (keyword == EKeywordExtensionRom)
+			break;
+
+		switch (keyword) {
+		case EKeywordSection:
+		case EKeywordArea:
+		case EKeywordPrimary:
+		case EKeywordSecondary:
+		case EKeywordExtension:
+		case EKeywordDevice:
+		case EKeywordVariant:
+		case EKeywordHardwareConfigRepositoryData:
+			Print(EError, "Keyword '%s' not supported in extension ROMs - line %d\n",
+				iReader.Word(0), iReader.CurrentLine());
+			break;
+
+		case EKeywordAlign:
+			if (iReader.ProcessAlign(align)!=KErrNone)
+				return KErrGeneral;
+			break;
+
+		case EKeywordHide:
+		case EKeywordAlias:
+		case EKeywordRename:
+			if (!ProcessRenaming(keyword))
+				return KErrGeneral;
+			break;
+		case EKeywordPatchDllData: {
+				// Collect patchdata statements to process at the end
+				StringVector patchDataTokens;
+				SplitPatchDataStatement(patchDataTokens); 
+				iPatchData->AddPatchDataStatement(patchDataTokens);										
+				break;
+			}
+
+		default:
+			if (!ProcessFile(align, keyword))
+					return KErrGeneral;			
+			align=0;
+			break;
+		}
+	}
+	
+	if( !ParsePatchDllData())
+		return KErrGeneral;
+
+	iReader.Mark();			// ready for processing the next extension rom(s)
+
+	if (iMissingFiles!=0)
+		return KErrGeneral;
+	if (iNumberOfDataFiles+iNumberOfPeFiles==0) {
+		Print(EError, "No files specified.\n");
+		return KErrGeneral;
+	}
+	return KErrNone;
+}
+
+void CObeyFile::ProcessExtensionKeyword(enum EKeyword aKeyword) {
+	
+	switch (aKeyword) {
+	case EKeywordKernelRomName:
+		iKernelRomName = iReader.DupWord(1);
+		return;
+	case EKeywordRomNameOdd:
+		iRomOddFileName = iReader.DupWord(1);
+		return;
+	case EKeywordRomNameEven:
+		iRomEvenFileName = iReader.DupWord(1);
+		return;
+	case EKeywordSRecordFileName:
+		iSRecordFileName = iReader.DupWord(1);
+		return;
+
+	case EKeywordRomLinearBase:
+		Val(iRomLinearBase,iReader.Word(1));
+		return;
+	case EKeywordRomSize:
+		Val(iRomSize,iReader.Word(1));
+		return;
+	case EKeywordRomAlign:
+		Val(iRomAlign,iReader.Word(1));
+		return;
+	case EKeywordDataAddress:
+		Val(iDataRunAddress ,iReader.Word(1));
+		return;
+	case EKeywordDefaultStackReserve:
+		Val(iDefaultStackReserve,iReader.Word(1));
+		return;
+	case EKeywordVersion:
+		{
+			istringstream val(iReader.Word(1));
+			val >> iVersion;
+		}
+		return;
+	case EKeywordSRecordBase:
+		Val(iSRecordBase,iReader.Word(1));
+		return;
+	case EKeywordRomChecksum:
+		Val(iCheckSum,iReader.Word(1)); 
+		return;
+	case EKeywordTime:
+		iReader.ProcessTime(iTime);
+		return;
+
+	case EKeywordTrace:
+		Val(TraceMask,iReader.Word(1));
+		return;
+
+	case EKeywordCollapse:
+		if (strnicmp(iReader.Word(1), "arm", 3)!=0 || strnicmp(iReader.Word(2), "gcc", 3)!=0) {
+			Print(EWarning, "COLLAPSE only supported for ARM and GCC - keyword ignored\n");
+		}
+		else {
+			TUint32 cm = 0;
+			Val(cm,iReader.Word(3)); 
+			if ( cm > ECollapseAllChainBranches) {
+				Print(EWarning, "COLLAPSE mode unrecognised - keyword ignored\n");
+			}
+			else {
+				Print(EWarning, "COLLAPSE not currently supported for extension roms\n");
+			}
+		}
+		return;
+
+	case EKeywordCoreImage:
+		//Already handled, skip it
+		return;
+
+	default:
+		Print(EError,"Keyword '%s' not valid in extension ROMs - line %d\n", iReader.Word(0), iReader.CurrentLine());
+		break;
+	}
+	return;
+}
+
+//
+// Checks that the obeyfile has supplied enough variables to continue
+// 
+TBool CObeyFile::GotExtensionVariables(MRomImage*& aRom){
+
+	TBool retVal=ETrue;
+	const char* kernelRomName = iKernelRomName ;
+
+	// Mandatory keywords
+
+	if (iRomSize==0) {
+		Print(EAlways,"The size of the extension ROM has not been supplied.\n");
+		Print(EAlways,"Use the keyword \"romsize\".\n");
+		retVal = EFalse;
+	}
+
+	// keywords we need if we don't already have a ROM image to work from
+
+	if (aRom==0) {
+		if (iKernelRomName==0) {
+			Print(EAlways,"The name of the kernel ROM has not been supplied.\n");
+			Print(EAlways,"Use the keyword \"kernelromname\".\n");
+			retVal = EFalse;
+		}
+		if (iRomLinearBase==0xFFFFFFFF) {
+			Print(EAlways,"The base linear address of the ROM has not been supplied.\n");
+			Print(EAlways,"Use the keyword \"romlinearbase\".\n");
+			retVal = EFalse;
+		}
+	}
+	else {
+		if (iKernelRomName != 0) {
+			Print(EWarning,"Keyword \"kernelromname\") ignored.\n");
+		}
+		kernelRomName = aRom->RomFileName();
+	}
+
+	// validation
+
+	// Apply defaults as necessary
+
+	if (iRomLinearBase==0xFFFFFFFF && aRom!=0) {
+		iRomLinearBase = aRom->RomBase() + aRom->RomSize();
+		Print(ELog,"Assuming extension ROM is contiguous with kernel ROM\n");
+		Print(ELog,"Setting romlinearbase to 0x%08x\n", iRomLinearBase);
+	}
+	TheRomLinearAddress=iRomLinearBase;
+
+	if (iDataRunAddress==0) {
+		iDataRunAddress= aRom->DataRunAddress();
+		Print(EWarning,"The address for a running ROM app's data section (keyword \"dataaddress\") has not been supplied.\n");
+		Print(EWarning,"Will use the default value of 0x%0x.\n", iDataRunAddress);
+	}
+	if (iRomAlign==0) {
+		iRomAlign = aRom->RomAlign();
+		Print(EWarning,"The ROM section alignment (keyword \"romalign\") has not been supplied.\n");
+		Print(EWarning,"Will use the default value of 0x%0x.\n", iRomAlign);
+	}
+	if (iRomAlign&0x3) {
+		Print(EWarning, "Rounding rom alignment to multiple of 4.\n");
+		iRomAlign=(iRomAlign+0x3)&0xfffffffc;
+	}
+	if (iTime==0) {
+		Print(ELog, "No timestamp specified. Using current time...\n");
+		ObeyFileReader::TimeNow(iTime);
+	}
+
+	// fix up "*" in romname
+	char newname[256];
+	char* p=newname;
+	char* q=iRomFileName;
+	char c;
+
+	while ((c=*q++)!='\0') {
+		if (c!='*') {
+			*p++=c;
+			continue;
+		}
+		const char *r = kernelRomName ? kernelRomName : "";
+		while ((c=*r++)!='\0')
+			*p++=c;
+	}
+	*p++ = '\0';
+	delete []iRomFileName;
+	size_t len = p - newname ;
+	iRomFileName = new char[len];
+	memcpy(iRomFileName,newname,len);
+
+	Print(ELog, "\nCreating Rom image %s\n", iRomFileName);
+	return retVal;
+}
+
+
+////////////////////////////////////////////////////////////////////////
+// AREA RELATED CODE
+////////////////////////////////////////////////////////////////////////
+
+/**
+Process an area declaration.
+*/
+
+TBool CObeyFile::ParseAreaKeyword() {
+		 
+	if(!IsValidNumber(iReader.Word(2)) || !IsValidNumber(iReader.Word(3))) {
+		Print(EError, "Line %d: Wrong area specification: Should be <name> <start address> <length>\n",
+			iReader.CurrentLine());
+		return EFalse;
+	}
+	const char* name = iReader.Word(1);
+	TLinAddr start = 0;
+	Val(start,iReader.Word(2)); 
+	TUint length = 0;
+	Val(length,iReader.Word(3));
+	if (! AddAreaAndHandleError(name, start, length, iReader.CurrentLine()))
+		return EFalse;
+
+	return ETrue;
+}
+
+
+/**
+Process an "area=xxx" file attribute.
+*/
+
+TBool CObeyFile::ParseAreaAttribute(const char* aArg, TInt aLineNumber, const Area*& aArea) {
+	if (iSectionPosition != -1) {
+		Print(EError, "Line %d: Relocation to area forbidden in second section\n", aLineNumber);
+		return EFalse;
+	}
+
+	aArea = iAreaSet.FindByName(reinterpret_cast<const char*>(aArg));
+	if (aArea == 0) {
+		Print(EError, "Line %d: Attempt to use an unknown area named '%s'\n", aLineNumber, aArg);
+		return EFalse;
+	}
+
+	return ETrue;
+}
+
+
+TBool CObeyFile::CreateDefaultArea() {
+	return AddAreaAndHandleError(AreaSet::KDefaultAreaName, iRomLinearBase, iRomSize);
+}
+
+
+TBool CObeyFile::AddAreaAndHandleError(const char* aName, TLinAddr aDestBaseAddr, TUint aLength, TInt aLineNumber) {
+	TBool added = EFalse;
+
+	const char lineInfoFmt[] = "Line %d:";
+	char lineInfo[sizeof(lineInfoFmt)+10];
+	if (aLineNumber > 0)
+		sprintf(lineInfo, lineInfoFmt, aLineNumber);
+	else
+		lineInfo[0] = '\0';
+
+	const char* overlappingArea;
+	switch (iAreaSet.AddArea(aName, aDestBaseAddr, aLength, overlappingArea)) {
+	case AreaSet::EAdded:
+		TRACE(TAREA, Print(EScreen, "Area '%s' added to AreaSet\n", aName));
+		added = ETrue;
+		break;
+	case AreaSet::EOverlap:
+		Print(EError, "%s Area '%s' collides with area '%s'\n", lineInfo, aName, overlappingArea);
+		break;
+	case AreaSet::EDuplicateName:
+		Print(EError, "%s Name '%s' already reserved for another area\n", lineInfo, aName);
+		break;
+	case AreaSet::EOverflow:
+		Print(EError, "%s Area overflow (0x%X+0x%X > 0x%X)\n", lineInfo, aDestBaseAddr, aLength, -1);
+		break;
+	default:
+		assert(0);				// can't happen
+	}
+
+	return added;
+}
+
+// Fuction to split patchdata statement 
+void CObeyFile::SplitPatchDataStatement(StringVector& aPatchDataTokens) {
+	// Get the value of symbol size, address/ordinal and new value 
+	// to be patched from the patchdata statement.
+	// Syntax of patchdata statements is as follows:
+	// 1)	patchdata dll_name  ordinal OrdinalNumber size_in_bytes   new_value 
+	// 2)   patchdata dll_name  addr    Address       size_in_bytes   new_value
+	for(TInt count=1; count<=5; count++)	 {
+		aPatchDataTokens.push_back(iReader.Word(count));
+	}
+
+	// Store the the value of current line which will be used
+	// when displaying error messages.
+	ostringstream outStrStream;
+	outStrStream << iReader.CurrentLine();
+	aPatchDataTokens.push_back(outStrStream.str());	
+}
+
+TBool CObeyFile::ParsePatchDllData() {
+	// Get the list of patchdata statements
+	VectorOfStringVector patchDataStatements=iPatchData->GetPatchDataStatements();
+	// Get the list of renamed file map
+	MapOfString RenamedFileMap=iPatchData->GetRenamedFileMap();
+	DllDataEntry *aDllDataEntry=NULL;
+
+	for(TUint count=0; count<patchDataStatements.size(); count++) {
+		StringVector strVector = patchDataStatements.at(count);
+		string filename=strVector.at(0);
+		string lineNoStr = strVector.at(5);
+		TUint lineNo = 1 ;
+		Val(lineNo,lineNoStr.c_str()); 
+		TRomNode* existingFile = NULL;
+
+		do {
+			TUint hardwareVariant=ParseVariant();
+			TRomNode* dir=iRootDirectory;		
+			TBool endOfName=EFalse;
+
+		 
+			if (IsValidFilePath(filename.c_str()) == NULL) {
+				Print(EError, "Invalid source path on line %d\n",lineNo);
+				return EFalse;
+			}
+			char* epocStartPtr = NormaliseFileName(filename.c_str());
+			char* savedPtr = epocStartPtr;
+			if(*epocStartPtr == '/' ||*epocStartPtr == '\\')
+				epocStartPtr++ ;
+			char* epocEndPtr=epocStartPtr;
+
+			while (!endOfName) {
+				endOfName = GetNextBitOfFileName(epocEndPtr);
+				if (endOfName) { // file 
+					existingFile=dir->FindInDirectory(epocStartPtr,hardwareVariant,TRUE);
+					if (existingFile) {
+						TInt fileCount=0;
+						TInt dirCount=0;
+						existingFile->CountDirectory(fileCount, dirCount);
+						if (dirCount != 0 || fileCount != 0) {
+							Print(EError, "Keyword %s not applicable to directories - line %d\n","patchdata",lineNo);
+							delete []savedPtr;
+							return EFalse;
+						}
+					}
+				}
+				else {// directory 
+					TRomNode* subDir = dir->FindInDirectory(epocStartPtr);
+					if (!subDir) // sub directory does not exist
+						break;
+					dir=subDir;
+					epocStartPtr = epocEndPtr;
+				}
+			}
+			delete []savedPtr;
+			if( !existingFile ) {
+				MapOfStringIterator RenamedFileMapIterator;
+
+				// If the E32Image file to be patched is not included then check if the
+				// file was renamed.
+				if ((RenamedFileMapIterator=RenamedFileMap.find(filename)) != RenamedFileMap.end())
+					filename = (*RenamedFileMapIterator).second; 
+				else {
+					Print(EError, "File %s not found - line %d\n", filename.c_str(), lineNo);
+					return EFalse;
+				}
+			}
+		}while(!existingFile);
+
+		TUint32 aSize, aOrdinal, aNewValue, aOffset;
+		TLinAddr aDataAddr;
+
+		aOrdinal = (TUint32)-1;
+		aDataAddr = (TUint32)-1;
+		aOffset = 0;
+
+		string symbolSize = strVector.at(3);
+		Val(aSize,symbolSize.c_str());
+		string aValue = strVector.at(4);
+		Val(aNewValue,aValue.c_str());
+
+		DllDataEntry *dataEntry = new DllDataEntry(aSize, aNewValue);
+
+		// Set the address of the data or the ordinal number specified in OBY statement.
+		string keyword = strVector.at(1);
+		string keywordValue = strVector.at(2);
+
+		/* Check for +OFFSET at the end of the ordinal number or address */
+		TUint plus = keywordValue.find("+",0);
+		if (plus != string::npos) {
+			/* Get the offset that we found after the + sign */
+			string offset = keywordValue.substr(plus+1);
+			Val(aOffset,offset.c_str());
+			keywordValue.resize(plus);		
+		}
+		if(stricmp (keyword.c_str(), "addr") == 0)
+			Val(aDataAddr,keywordValue.c_str());
+
+		else 
+			Val(aOrdinal,keywordValue.c_str());
+
+		dataEntry->iDataAddress = aDataAddr;
+		dataEntry->iOrdinal = aOrdinal;
+		dataEntry->iOffset = aOffset;
+		dataEntry->iRomNode = existingFile;
+
+		if (aDllDataEntry==NULL) {
+			// Set the first node of the patchdata linked list
+			aDllDataEntry = dataEntry;
+			SetFirstDllDataEntry(aDllDataEntry);
+		}
+		else {
+			// Add the new node at the end of linked list
+			aDllDataEntry->AddDllDataEntry(dataEntry);
+			aDllDataEntry = aDllDataEntry->NextDllDataEntry();
+		}
+	}
+	return ETrue;
+}
+
+int CObeyFile::SkipToExtension() {
+	int found = 0;
+
+	iReader.Rewind();
+	enum EKeyword keyword;
+	while (iReader.NextLine(1,keyword) != KErrEof) {
+		if (keyword == EKeywordExtensionRom) {
+			found = 1;
+			iReader.Mark(); // ready for processing extension
+			break;
+		}
+	}
+
+	if(!found) {
+		Print(EError, "Coreimage option requires valid \"extensionrom\" keyword\n");
+	}
+
+	return found;
+}
+
+char* CObeyFile::ProcessCoreImage() {
+	// check for coreimage keyword and return filename
+	iReader.Rewind();
+	enum EKeyword keyword;
+	char* coreImageFileName = 0;
+
+	iRomAlign = KDefaultRomAlign;
+	iDataRunAddress = KDefaultDataRunAddress;
+
+	while (iReader.NextLine(1,keyword) != KErrEof) {
+		if (keyword == EKeywordCoreImage) {
+			coreImageFileName = iReader.DupWord(1);
+			break;
+		}
+		else if ((keyword == EKeywordRomAlign) || (keyword == EKeywordDataAddress)) {
+			if(keyword == EKeywordRomAlign) {
+				Val(iRomAlign,iReader.Word(1));
+			}
+			else {
+				Val(iDataRunAddress,iReader.Word(1));
+			}
+		}
+	}
+
+	if (iRomAlign&0x3) {
+		//Rounding rom alignment to multiple of 4
+		iRomAlign=(iRomAlign+0x3)&0xfffffffc;
+	}
+
+	return coreImageFileName;
+}
--- a/imgtools/romtools/rombuild/r_obey.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_obey.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,366 +1,361 @@
-/*
-* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifndef __R_OBEY_H__
-#define __R_OBEY_H__
-
-#define __REFERENCE_CAPABILITY_NAMES__
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-#include <fstream>
-#else //!__MSVCDOTNET__
-#include <fstream.h>
-#endif //__MSVCDOTNET__
-
-#include "r_rom.h"
-#include "r_areaset.h"
-#include <e32capability.h>
-
-#ifdef _L
-#undef _L
-#endif
-
-#include <vector>
-
-const TUint32 KNumWords=16;
-//
-const TInt KDefaultRomSize=0x400000;
-const TInt KDefaultRomLinearBase=0x50000000;
-const TInt KDefaultRomAlign=0x1000;
-const TUint32 KDefaultDataRunAddress = 0x400000;
-//
-
-typedef std::string String;
-typedef std::vector<String> StringVector;
-
-enum EFileAttribute
-	{
-	EAttributeStackReserve,
-	EAttributeStack,
-	EAttributeReloc,
-	EAttributeCodeAlign,
-	EAttributeDataAlign,
-	EAttributeFixed,
-	EAttributeAtt,
-	EAttributePriority,
-	EAttributePatched,
-	EAttributeUid1,
-	EAttributeUid2,
-	EAttributeUid3,
-	EAttributeHeapMin,
-	EAttributeHeapMax,
-	EAttributeHidden,
-	EAttributeKeepIAT,
-	EAttributeArea,
-	EAttributeProcessSpecific,
-	EAttributeCapability,
-	EAttributePreferred,
-	EAttributeUnpaged,
-	EAttributePaged,
-	EAttributeUnpagedCode,
-	EAttributePagedCode,
-	EAttributeUnpagedData,
-	EAttributePagedData,
-	};
-enum EKeyword 
-	{
-	EKeywordNone=0,	// backwards compatibility, but now ignored
-	EKeywordFile,
-	EKeywordData,
-	EKeywordPrimary,
-	EKeywordSecondary,
-	EKeywordVariant,
-	EKeywordExtension,
-	EKeywordDevice,
-	EKeywordDll,
-	EKeywordFileCompress,
-	EKeywordFileUncompress,
-	EKeywordArea,
-	EKeywordAlign,
-	EKeywordUnicode,
-	EKeywordAscii,
-	EKeywordSingleKernel,
-	EKeywordMultiKernel,
-	EKeywordBootBinary,
-	EKeywordRomName,
-	EKeywordRomSize,
-	EKeywordRomLinearBase,
-	EKeywordRomAlign,
-	EKeywordRomChecksum,
-	EKeywordKernelDataAddress,
-	EKeywordKernelHeapMin,
-	EKeywordKernelHeapMax,
-	EKeywordDataAddress,
-	EKeywordDllDataTop,
-	EKeywordDefaultStackReserve,
-	EKeywordVersion,
-	EKeywordLanguages,
-	EKeywordHardware,
-	EKeywordRomNameOdd,
-	EKeywordRomNameEven,
-	EKeywordSRecordFileName,
-	EKeywordSRecordBase,
-	EKeywordTrace,
-	EKeywordKernelTrace,
-	EKeywordBTrace,
-	EKeywordBTraceMode,
-	EKeywordBTraceBuffer,
-	EKeywordCollapse,
-	EKeywordTime,
-	EKeywordSection,
-	EKeywordExtensionRom,
-	EKeywordKernelRomName,
-	EKeywordAlias,
-	EKeywordHide,
-	EKeywordRename,
-	EKeywordDebugPort,
-	EKeywordCompress,
-	EKeywordMemModel,
-	EKeywordNoWrapper,
-	EKeywordEpocWrapper,
-	EKeywordCoffWrapper,
-	EKeywordPlatSecEnforcement,
-	EKeywordPlatSecDiagnostics,
-	EKeywordPlatSecProcessIsolation,
-	EKeywordPlatSecEnforceSysBin,
-	EKeywordPlatSecDisabledCaps,
-	EKeywordPagingPolicy,
-	EKeywordCodePagingPolicy,
-	EKeywordDataPagingPolicy,
-	EKeywordPagingOverride,
-	EKeywordCodePagingOverride,
-	EKeywordDataPagingOverride,
-	EKeywordDemandPagingConfig,
-	EKeywordPagedRom,
-	EKeywordPatchDllData,
-	EKeywordExecutableCompressionMethodNone,
-	EKeywordExecutableCompressionMethodInflate,
-	EKeywordExecutableCompressionMethodBytePair,
-	EKeywordCoreImage,
-	EKeywordKernelConfig,
-	EKeywordMaxUnpagedMemSize,
-	EKeywordHardwareConfigRepositoryData ,
-	};
-enum TCollapseMode
-	{
-	ECollapseNone=0,
-	ECollapseImportThunksOnly=1,
-	ECollapseImportThunksAndVtables=2,
-	ECollapseAllChainBranches=3,
-	};
-
-struct ObeyFileKeyword
-	{
-	const char* iKeyword;
-	size_t iKeywordLength;
-	TInt iPass;
-	TInt iNumArgs;		// -ve means >= number
-	enum EKeyword iKeywordEnum;
-	const char* iHelpText;
-	};
-
-struct FileAttributeKeyword
-	{
-	const char* iKeyword;
-	size_t iKeywordLength;
-	TInt iIsFileAttribute;
-	TInt iNumArgs;
-	enum EFileAttribute iAttributeEnum;
-	const char* iHelpText;
-	};
-
-class ObeyFileReader
-	{
-public:
-	ObeyFileReader(TText *aFileName);
-	~ObeyFileReader();
-
-	static void KeywordHelp();
-
-	TBool Open();
-	void Mark();
-	void MarkNext();
-	void Rewind();
-
-	TInt NextLine(TInt aPass, enum EKeyword& aKeyword);
-	TInt NextAttribute(TInt& aIndex, TInt aHasFile, enum EFileAttribute& aKeyword, TText*& aArg);
-
-	void CopyWord(TInt aIndex, TText*& aString);				// allocate copy of nth word
-	TInt Count() { return iNumWords;}				// number of words on current line
-	char* Word(TInt aIndex) { return (char*)iWord[aIndex]; }	// return nth word as char*
-	TText* Text(TInt aIndex) { return iWord[aIndex]; }			// return nth word as TText*
-	char* Suffix() { return (char*)iSuffix; }			// return unmatched suffix of word[0]
-	TInt CurrentLine() { return iCurrentLine;}				// number of words on current line
-
-	TInt ProcessAlign(TInt& aAlign);
-	void ProcessLanguages(TInt64& aLanguageMask);
-	void ProcessTime(TInt64& aTime);
-
-	static void TimeNow(TInt64& aTime);
-private:
-	TInt ReadAndParseLine();
-	TInt SetLineLengthBuffer();
-	TInt Parse();
-	inline TBool IsGap(char ch); 
-
-	static const ObeyFileKeyword iKeywords[];
-	static const FileAttributeKeyword iAttributeKeywords[];
-	static TInt64 iTimeNow;
-
-private:
-	FILE* iObeyFile;
-	long iMark;
-	TInt iMarkLine;
-	long iCurrentMark;
-	TInt iCurrentLine;
-	TInt imaxLength;
-	TText* iFileName;
-	TInt iNumWords;
-	TText* iWord[KNumWords];
-	TText* iSuffix;
-	TText* iLine;
-	};
-
-class CPatchDataProcessor;
-class DllDataEntry;
-
-class CObeyFile
-	{
-public:
-	TText *iRomFileName;
-	TText *iRomOddFileName;
-	TText *iRomEvenFileName;
-	TText *iSRecordFileName;
-	TText *iBootFileName;
-	TText *iKernelRomName;
-	TInt iRomSize;
-	TUint32 iRomLinearBase;
-	TUint32 iRomAlign;
-	TUint32 iKernDataRunAddress;
-	TUint32 iDataRunAddress;
-	TUint32 iKernelLimit;
-	TUint32 iKernHeapMin;
-	TUint32 iKernHeapMax;
-	TUint32 iSectionStart;
-	TInt iSectionPosition;
-	TVersion iVersion;
-	TUint32 iCheckSum;
-	TInt iNumberOfPeFiles;
-	TInt iNumberOfDataFiles;
-	TInt iNumberOfPrimaries;
-	TInt iNumberOfExtensions;
-	TInt iNumberOfVariants;
-	TInt iNumberOfDevices;
-	TInt iNumberOfHCRDataFiles ;
-	TUint iAllVariantsMask[256];
-	TRomBuilderEntry** iPrimaries;
-	TRomBuilderEntry** iVariants;
-	TRomBuilderEntry** iExtensions;
-	TRomBuilderEntry** iDevices;
-	TInt64 iLanguage;
-	TUint32 iHardware;
-	TInt64 iTime;
-	TMemModel iMemModel;
-	TInt iPageSize;
-	TInt iChunkSize;
-	TInt iVirtualAllocSize;
-	TKernelModel iKernelModel;
-	TInt iCollapseMode;
-	TUint32 iSRecordBase;
-	TInt iCurrentSectionNumber;
-	TInt iDefaultStackReserve;
-	TUint32 iTraceMask[KNumTraceMaskWords];			// Pass through to the kernel tracemask
-	TUint32 iInitialBTraceFilter[8];
-	TInt iInitialBTraceBuffer;
-	TInt iInitialBTraceMode;
-	TUint32 iDebugPort;
-	TBool iDebugPortParsed;
-	TRomNode* iRootDirectory;
-	TUint32 iDllDataTop;
-	TUint32 iKernelConfigFlags;
-	TBool iPagingPolicyParsed;
-	TBool iCodePagingPolicyParsed;
-	TBool iDataPagingPolicyParsed;
-	TBool iPagingOverrideParsed;
-	TBool iCodePagingOverrideParsed;
-	TBool iDataPagingOverrideParsed;
-	SCapabilitySet iPlatSecDisabledCaps;
-	TBool iPlatSecDisabledCapsParsed;
-	TInt iMaxUnpagedMemSize;		// Max unpaged memory size, 0 = no limits
-private:
-	ObeyFileReader& iReader;
-	TInt iMissingFiles;
-	TRomNode* iLastExecutable;
-	AreaSet iAreaSet;
-
-	TRomBuilderEntry* iFirstFile;
-	TRomBuilderEntry** iNextFilePtrPtr;
-	TRomBuilderEntry* iCurrentFile;
-	TRomBuilderEntry* iLastVariantFile;
-	DllDataEntry* iFirstDllDataEntry;
-	TBool iUpdatedMaxUnpagedMemSize;		// ETure = iMaxUnpagedMemSize has been set
-
-public:
-	CObeyFile(ObeyFileReader& aReader);
-	~CObeyFile();
-	void Release();
-	TInt ProcessKernelRom();
-	TInt ProcessExtensionRom(MRomImage*& aKernelRom);
-	TRomBuilderEntry *FirstFile();
-	TRomBuilderEntry *NextFile();
-	const AreaSet& SetArea() const ; 
- 	DllDataEntry* GetFirstDllDataEntry() const;
-	void SetFirstDllDataEntry(DllDataEntry* aDllDataEntry);
-
-	int SkipToExtension();
-	TText* ProcessCoreImage();
-
-private:
-	TBool CheckHardwareVariants();
-	TBool ProcessFile(TInt aAlign, enum EKeyword aKeyword);
-	TBool ProcessRenaming(enum EKeyword aKeyword);
-	TBool ProcessKeyword(enum EKeyword aKeyword);
-	TBool ParsePatchDllData();
-	void ProcessExtensionKeyword(enum EKeyword aKeyword);
-	TInt ParseFileAttributes(TRomNode* aNode, TRomBuilderEntry* aFile);
-	TInt ParseSection();
-	TUint32 ParseVariant();
-	TBool GotKeyVariables();
-	TBool GotExtensionVariables(MRomImage*& aRom);
-	TBool GetNextBitOfFileName(TText **epocEndPtr);
-	TText *IsValidFilePath(TText *aPath);
-	void AddFile(TRomBuilderEntry* aFile);
-
-	// Area-related methods
-	TBool CreateDefaultArea();
-	TBool ParseAreaKeyword();
-	TBool ParseAreaAttribute(const TText* aArg, TInt aLineNumber, const Area*& aArea);
-	TBool AddAreaAndHandleError(const char* aName, TLinAddr aDestBaseAddr, TUint aLength, TInt aLineNumber = -1);
-
-public:
-	CPatchDataProcessor* iPatchData;	
-	void SplitPatchDataStatement(StringVector& aPatchDataTokens);	
-	};
-
-
-inline const AreaSet& CObeyFile::SetArea() const
-	{
-	return iAreaSet;
-	}
-
-#endif
+/*
+* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifndef __R_OBEY_H__
+#define __R_OBEY_H__
+
+#define __REFERENCE_CAPABILITY_NAMES__
+ 
+#include <e32capability.h>
+#include <vector>
+#include <map>
+#include <fstream>
+using namespace std;
+
+#include "r_rom.h"
+#include "r_areaset.h"
+ 
+ 
+
+const TUint32 KNumWords=16;
+//
+const TInt KDefaultRomSize=0x400000;
+const TInt KDefaultRomLinearBase=0x50000000;
+const TInt KDefaultRomAlign=0x1000;
+const TUint32 KDefaultDataRunAddress = 0x400000;
+//
+typedef vector<string> StringVector ;
+ 
+
+enum EFileAttribute
+	{
+	EAttributeStackReserve,
+	EAttributeStack,
+	EAttributeReloc,
+	EAttributeCodeAlign,
+	EAttributeDataAlign,
+	EAttributeFixed,
+	EAttributeAtt,
+	EAttributePriority,
+	EAttributePatched,
+	EAttributeUid1,
+	EAttributeUid2,
+	EAttributeUid3,
+	EAttributeHeapMin,
+	EAttributeHeapMax,
+	EAttributeHidden,
+	EAttributeKeepIAT,
+	EAttributeArea,
+	EAttributeProcessSpecific,
+	EAttributeCapability,
+	EAttributePreferred,
+	EAttributeUnpaged,
+	EAttributePaged,
+	EAttributeUnpagedCode,
+	EAttributePagedCode,
+	EAttributeUnpagedData,
+	EAttributePagedData,
+	};
+enum EKeyword 
+	{
+	EKeywordNone=0,	// backwards compatibility, but now ignored
+	EKeywordFile,
+	EKeywordData,
+	EKeywordPrimary,
+	EKeywordSecondary,
+	EKeywordVariant,
+	EKeywordExtension,
+	EKeywordDevice,
+	EKeywordDll,
+	EKeywordFileCompress,
+	EKeywordFileUncompress,
+	EKeywordArea,
+	EKeywordAlign,
+	EKeywordUnicode,
+	EKeywordAscii,
+	EKeywordSingleKernel,
+	EKeywordMultiKernel,
+	EKeywordBootBinary,
+	EKeywordRomName,
+	EKeywordRomSize,
+	EKeywordRomLinearBase,
+	EKeywordRomAlign,
+	EKeywordRomChecksum,
+	EKeywordKernelDataAddress,
+	EKeywordKernelHeapMin,
+	EKeywordKernelHeapMax,
+	EKeywordDataAddress,
+	EKeywordDllDataTop,
+	EKeywordDefaultStackReserve,
+	EKeywordVersion,
+	EKeywordLanguages,
+	EKeywordHardware,
+	EKeywordRomNameOdd,
+	EKeywordRomNameEven,
+	EKeywordSRecordFileName,
+	EKeywordSRecordBase,
+	EKeywordTrace,
+	EKeywordKernelTrace,
+	EKeywordBTrace,
+	EKeywordBTraceMode,
+	EKeywordBTraceBuffer,
+	EKeywordCollapse,
+	EKeywordTime,
+	EKeywordSection,
+	EKeywordExtensionRom,
+	EKeywordKernelRomName,
+	EKeywordAlias,
+	EKeywordHide,
+	EKeywordRename,
+	EKeywordDebugPort,
+	EKeywordCompress,
+	EKeywordMemModel,
+	EKeywordNoWrapper,
+	EKeywordEpocWrapper,
+	EKeywordCoffWrapper,
+	EKeywordPlatSecEnforcement,
+	EKeywordPlatSecDiagnostics,
+	EKeywordPlatSecProcessIsolation,
+	EKeywordPlatSecEnforceSysBin,
+	EKeywordPlatSecDisabledCaps,
+	EKeywordPagingPolicy,
+	EKeywordCodePagingPolicy,
+	EKeywordDataPagingPolicy,
+	EKeywordPagingOverride,
+	EKeywordCodePagingOverride,
+	EKeywordDataPagingOverride,
+	EKeywordDemandPagingConfig,
+	EKeywordPagedRom,
+	EKeywordPatchDllData,
+	EKeywordExecutableCompressionMethodNone,
+	EKeywordExecutableCompressionMethodInflate,
+	EKeywordExecutableCompressionMethodBytePair,
+	EKeywordCoreImage,
+	EKeywordKernelConfig,
+	EKeywordMaxUnpagedMemSize,
+	EKeywordHardwareConfigRepositoryData ,
+	};
+enum TCollapseMode
+	{
+	ECollapseNone=0,
+	ECollapseImportThunksOnly=1,
+	ECollapseImportThunksAndVtables=2,
+	ECollapseAllChainBranches=3,
+	};
+
+struct ObeyFileKeyword
+	{
+	const char* iKeyword;
+	size_t iKeywordLength;
+	TInt iPass;
+	TInt iNumArgs;		// -ve means >= number
+	enum EKeyword iKeywordEnum;
+	const char* iHelpText;
+	};
+
+struct FileAttributeKeyword
+	{
+	const char* iKeyword;
+	size_t iKeywordLength;
+	TInt iIsFileAttribute;
+	TInt iNumArgs;
+	enum EFileAttribute iAttributeEnum;
+	const char* iHelpText;
+	};
+class CObeyFile;
+class ObeyFileReader
+	{
+public:
+	ObeyFileReader(const char* aFileName);
+	~ObeyFileReader();
+
+	static void KeywordHelp();
+
+	TBool Open();
+	void Mark();
+	void MarkNext();
+	void Rewind();
+
+	TInt NextLine(TInt aPass, enum EKeyword& aKeyword);
+	TInt NextAttribute(TInt& aIndex, TInt aHasFile, enum EFileAttribute& aKeyword, char*& aArg);
+
+	char* DupWord(TInt aIndex) const ;				// allocate copy of nth word
+	TInt Count() const { return iNumWords;}				// number of words on current line
+	const char* Word(TInt aIndex) const  { return iWord[aIndex]; }	// return nth word as char* 
+	const char* Suffix() const { return iSuffix; }			// return unmatched suffix of word[0]
+	TInt CurrentLine() const { return iCurrentLine;}				// number of words on current line
+
+	TInt ProcessAlign(TInt& aAlign);
+	void ProcessLanguages(TInt64& aLanguageMask);
+	void ProcessTime(TInt64& aTime);
+
+	static void TimeNow(TInt64& aTime);
+private:
+	TInt ReadAndParseLine(); 
+	TInt Parse();
+	inline static TBool IsGap(char ch) {
+		return (ch==' ' || ch=='=' || ch=='\t');
+	}
+
+	static const ObeyFileKeyword iKeywords[];
+	static const FileAttributeKeyword iAttributeKeywords[];
+	static TInt64 iTimeNow;
+protected:
+	string iFileName;	
+private:
+	TInt iCurrentLine; 
+	StringVector iLines ;
+	TInt iNumWords;	
+	char* iLine;
+	TInt iMarkLine ;
+	 
+	char iSuffix[80];
+	char* iWord[KNumWords];
+friend class CObeyFile;
+	};
+
+class CPatchDataProcessor;
+class DllDataEntry;
+
+class CObeyFile
+	{
+public:
+	char* iRomFileName;
+	char* iRomOddFileName;
+	char* iRomEvenFileName;
+	char* iSRecordFileName;
+	char* iBootFileName;
+	char* iKernelRomName;
+	TInt iRomSize;
+	TUint32 iRomLinearBase;
+	TUint32 iRomAlign;
+	TUint32 iKernDataRunAddress;
+	TUint32 iDataRunAddress;
+	TUint32 iKernelLimit;
+	TUint32 iKernHeapMin;
+	TUint32 iKernHeapMax;
+	TUint32 iSectionStart;
+	TInt iSectionPosition;
+	TVersion iVersion;
+	TUint32 iCheckSum;
+	TInt iNumberOfPeFiles;
+	TInt iNumberOfDataFiles;
+	TInt iNumberOfPrimaries;
+	TInt iNumberOfExtensions;
+	TInt iNumberOfVariants;
+	TInt iNumberOfDevices;
+	TInt iNumberOfHCRDataFiles ;
+	TUint iAllVariantsMask[256];
+	TRomBuilderEntry** iPrimaries;
+	TRomBuilderEntry** iVariants;
+	TRomBuilderEntry** iExtensions;
+	TRomBuilderEntry** iDevices;
+	TInt64 iLanguage;
+	TUint32 iHardware;
+	TInt64 iTime;
+	TMemModel iMemModel;
+	TInt iPageSize;
+	TInt iChunkSize;
+	TInt iVirtualAllocSize;
+	TKernelModel iKernelModel;
+	TInt iCollapseMode;
+	TUint32 iSRecordBase;
+	TInt iCurrentSectionNumber;
+	TInt iDefaultStackReserve;
+	TUint32 iTraceMask[KNumTraceMaskWords];			// Pass through to the kernel tracemask
+	TUint32 iInitialBTraceFilter[8];
+	TInt iInitialBTraceBuffer;
+	TInt iInitialBTraceMode;
+	TUint32 iDebugPort;
+	TBool iDebugPortParsed;
+	TRomNode* iRootDirectory;
+	TUint32 iDllDataTop;
+	TUint32 iKernelConfigFlags;
+	TBool iPagingPolicyParsed;
+	TBool iCodePagingPolicyParsed;
+	TBool iDataPagingPolicyParsed;
+	TBool iPagingOverrideParsed;
+	TBool iCodePagingOverrideParsed;
+	TBool iDataPagingOverrideParsed;
+	SCapabilitySet iPlatSecDisabledCaps;
+	TBool iPlatSecDisabledCapsParsed;
+	TInt iMaxUnpagedMemSize;		// Max unpaged memory size, 0 = no limits
+private:
+	ObeyFileReader& iReader;
+	TInt iMissingFiles;
+	TRomNode* iLastExecutable;
+	AreaSet iAreaSet;
+
+	TRomBuilderEntry* iFirstFile;
+	TRomBuilderEntry** iNextFilePtrPtr;
+	TRomBuilderEntry* iCurrentFile;
+	TRomBuilderEntry* iLastVariantFile;
+	DllDataEntry* iFirstDllDataEntry;
+	TBool iUpdatedMaxUnpagedMemSize;		// ETure = iMaxUnpagedMemSize has been set
+
+public:
+	CObeyFile(ObeyFileReader& aReader);
+	~CObeyFile();
+	void Release();
+	TInt ProcessKernelRom();
+	TInt ProcessExtensionRom(MRomImage*& aKernelRom);
+	TRomBuilderEntry *FirstFile();
+	TRomBuilderEntry *NextFile();
+	const AreaSet& SetArea() const ; 
+ 	DllDataEntry* GetFirstDllDataEntry() const;
+	void SetFirstDllDataEntry(DllDataEntry* aDllDataEntry);
+
+	int SkipToExtension();
+	char* ProcessCoreImage();
+	const char* GetFileName() const ;
+
+private:
+	TBool CheckHardwareVariants();
+	TBool ProcessFile(TInt aAlign, enum EKeyword aKeyword);
+	TBool ProcessRenaming(enum EKeyword aKeyword);
+	TBool ProcessKeyword(enum EKeyword aKeyword);
+	TBool ParsePatchDllData();
+	void ProcessExtensionKeyword(enum EKeyword aKeyword);
+	TInt ParseFileAttributes(TRomNode* aNode, TRomBuilderEntry* aFile);
+	TInt ParseSection();
+	TUint32 ParseVariant();
+	TBool GotKeyVariables();
+	TBool GotExtensionVariables(MRomImage*& aRom);
+	TBool GetNextBitOfFileName(char*& epocEndPtr);
+	const char* IsValidFilePath(const char* aPath);
+	void AddFile(TRomBuilderEntry* aFile);
+
+	// Area-related methods
+	TBool CreateDefaultArea();
+	TBool ParseAreaKeyword();
+	TBool ParseAreaAttribute(const char* aArg, TInt aLineNumber, const Area*& aArea);
+	TBool AddAreaAndHandleError(const char* aName, TLinAddr aDestBaseAddr, TUint aLength, TInt aLineNumber = -1);
+
+public:
+	CPatchDataProcessor* iPatchData;	
+	void SplitPatchDataStatement(StringVector& aPatchDataTokens);	
+	};
+
+
+inline const AreaSet& CObeyFile::SetArea() const {
+	return iAreaSet;
+}
+inline const char* CObeyFile::GetFileName() const {
+	return iReader.iFileName.c_str();
+}
+#endif
--- a/imgtools/romtools/rombuild/r_rom.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_rom.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,2708 +1,2719 @@
-/*
-* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include <e32std.h>
-#include <e32std_private.h>
-#include <e32uid.h>
-#include "h_utl.h"
-#include <string.h>
-#include <stdlib.h>
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-#include <iomanip>
-#else //!__MSVCDOTNET__
-#include <iomanip.h>
-#endif //__MSVCDOTNET__
-
-#include "r_global.h"
-#include "r_obey.h"
-#include "r_rom.h"
-#include "r_dir.h"
-#include "patchdataprocessor.h"
-#include "memmap.h"
-#include "byte_pair.h"
-
-const TInt KSpareExports=16;
-extern TInt gThreadNum;
-extern char* gDepInfoFile;
-extern TBool gGenDepGraph;
-
-TUint32 DeflateCompressCheck(char *bytes,TInt size,ostream &os);
-void DeflateCompress(char *bytes,TInt size,ostream &os);
-void InflateUnCompress(unsigned char* source, int sourcesize,unsigned char* dest, int destsize);
-
-EntryQueue* LoadImageWorker::m_queue = NULL;
-TInt LoadImageWorker::m_errors = 0;
-TMemModel LoadImageWorker::m_memmodel;
-boost::mutex LoadImageWorker::m_mutex;
-LoadImageWorker::LoadImageWorker(EntryQueue* aQueue, TMemModel aMemModel)
-	{
-	m_queue = aQueue;
-	m_memmodel = aMemModel;
-	}
-void LoadImageWorker::operator()()
-	{
-	while(1)
-		{
-		m_mutex.lock();
-		if(m_queue->size() > 0)
-			{
-			TRomBuilderEntry * current = m_queue->front();
-			m_queue->pop();
-			m_mutex.unlock();
-			TInt err = current->OpenImageFile();
-			if(err)
-				{
-				m_mutex.lock();
-				++m_errors;
-				m_mutex.unlock();
-				continue;
-				}
-			if(current->iOverrideFlags&KOverrideAddress || current->iHdr->iFlags & KImageFixedAddressExe)
-				{
-				if(m_memmodel != E_MM_Multiple && m_memmodel != E_MM_Flexible &&  !current->IsDll())
-					current->iRomImageFlags |=KRomImageFlagFixedAddressExe;
-				}
-			if(gPagedRom)
-				{
-				if(current->iHdr->iFlags&KImageCodePaged)
-					{
-					current->iRomImageFlags&=~KRomImageFlagCodeUnpaged;
-					current->iRomImageFlags|=KRomImageFlagCodePaged;
-					}
-				if(current->iHdr->iFlags&KImageCodeUnpaged)
-					{
-					current->iRomImageFlags|=KRomImageFlagCodeUnpaged;
-					current->iRomImageFlags&=~KRomImageFlagCodePaged;
-					}
-				}
-			if(current->iHdr->iFlags&KImageDataPaged)
-				{
-				current->iRomImageFlags&=~KRomImageFlagDataUnpaged;
-				current->iRomImageFlags|=KRomImageFlagDataPaged;
-				}
-			if(current->iHdr->iFlags&KImageDataUnpaged)
-				{
-				current->iRomImageFlags|=KRomImageFlagDataUnpaged;
-				current->iRomImageFlags&=~KRomImageFlagDataPaged;
-				}
-			if(current->iHdr->iFlags&KImageDebuggable)
-				{
-				current->iRomImageFlags|=KRomImageDebuggable;
-				}
-				else
-				{
-				current->iRomImageFlags&=~KRomImageDebuggable;
-				}
-			}
-			else
-			{
-			m_mutex.unlock();
-			break;
-			}
-		}
-	}
-E32Rom* CompressPageWorker::m_rom = NULL;
-TInt CompressPageWorker::m_nextpage = 0;
-TInt CompressPageWorker::m_totalpages = 0;
-TInt CompressPageWorker::m_pagesize = 0;
-boost::mutex CompressPageWorker::m_mutex;
-TInt CompressPageWorker::m_error = 0;
-CompressPageWorker::CompressPageWorker(E32Rom* aRom, TInt aPageSize, TInt aTotalPages, TInt aNextPage)
-	{
-	m_rom = aRom;
-	m_pagesize = aPageSize;
-	m_totalpages = aTotalPages;
-	m_nextpage = aNextPage;
-	}
-void CompressPageWorker::operator()()
-	{
-	SRomPageInfo* pPageBase = (SRomPageInfo*)((TInt)m_rom->iHeader + m_rom->iHeader->iRomPageIndex);
-	CBytePair bpe(gFastCompress);
-	while(1)
-		{
-		m_mutex.lock();
-		TInt currentPageIndex = m_nextpage++;
-		m_mutex.unlock();
-		if(currentPageIndex < m_totalpages)
-			{
-			TInt inOffset = m_pagesize * currentPageIndex;
-			TUint8 attrib = (TUint8)SRomPageInfo::EPageable;
-			SRomPageInfo info ={ (TUint32)inOffset, (TUint16)m_pagesize, (TUint8)SRomPageInfo::EBytePair, attrib };
-			TUint8* in = (TUint8*) m_rom->iHeader + inOffset;
-			TUint8* out = in;
-			TInt outSize = BytePairCompress(out, in, m_pagesize, &bpe);
-			if(outSize == KErrTooBig)
-				{
-				info.iCompressionType = SRomPageInfo::ENoCompression;
-				memcpy(out, in, m_pagesize);
-				outSize = m_pagesize;
-				}
-				if(outSize < 0 )
-					{
-					m_mutex.lock();
-					m_error = outSize;
-					m_mutex.unlock();
-					break;
-					}
-				info.iDataSize = (TUint16) outSize;
-				*(pPageBase + currentPageIndex) = info;
-				if((currentPageIndex & 255) == 255)
-					{
-					m_mutex.lock();
-					Print(EAlways, ".\n");
-					m_mutex.unlock();
-					}
-				}
-			else
-			{
-			break;
-			}
-		}
-	}
-	
-////////////////////////////////////////////////////////////////////////
-
-TAddressRange::TAddressRange() 
-	: iImagePtr(0), iImageAddr(0), iRunAddr(0), iSize(0) 
-	{
-	}
-
-void TAddressRange::Append(TAddressRange& aRange)
-	{ 
-	if(aRange.iSize) 
-		{ 
-		aRange.iImagePtr = iImagePtr;
-		aRange.iImageAddr = iImageAddr;
-		aRange.iRunAddr = iRunAddr;
-		Extend(aRange.iSize); 
-		} 
-	}
-
-void TAddressRange::Move(TInt aOffset) 
-	{ 
-	iImagePtr = static_cast<char*>(iImagePtr) + aOffset; 
-	iImageAddr += aOffset; 
-	iRunAddr += aOffset;
-	}
-
-void TAddressRange::Extend(TInt aOffset) 
-	{ 
-	Move(aOffset);
-	iSize += aOffset; 
-	}
-
-////////////////////////////////////////////////////////////////////////
-
-inline TUint32 AlignData(TUint32 anAddr)
-	{
-	return ((anAddr+0x0f)&~0x0f);
-	}
-
-TUint32 E32Rom::AlignToPage(TUint32 anAddr)
-	{
-	TUint a=(TUint)iObey->iPageSize-1;
-	return ((anAddr+a)&~a);
-	}
-
-/*
-Allocate virtual memory for static data in rom.
-@param aAddr Base address of last allocated memory.
-@param aSize Size of memory to allocate.
-@return Address allocated. This is below aAddr.
-*/
-TUint32 E32Rom::AllocVirtual(TUint32 aAddr,TUint aSize)
-	{
-	TInt align = iObey->iVirtualAllocSize;
-	if(align<0)
-		{
-		align = -align; // get correct sign
-		// -ve align means also align to next power-of-two >= aSize...
-		while(aSize>(TUint)align)
-			align <<=1;
-		}
-
-	TUint mask = (TUint)align-1;
-	aSize = (aSize+mask)&~mask; // round up
-	aAddr &= ~mask; // round down
-	return aAddr-aSize;
-	}
-
-TUint32 E32Rom::AlignToChunk(TUint32 anAddr)
-	{
-	TUint a=(TUint)iObey->iChunkSize-1;
-	return ((anAddr+a)&~a);
-	}
-
-COrderedFileList::COrderedFileList(TInt aMaxFiles)
-	: iCount(0), iMaxFiles(aMaxFiles), iOrderedFiles(NULL)
-	{}
-
-COrderedFileList::~COrderedFileList()
-	{
-	iCount=0;
-	delete[] iOrderedFiles;
-	}
-
-COrderedFileList* COrderedFileList::New(TInt aMaxFiles)
-	{
-	COrderedFileList *pL=new COrderedFileList(aMaxFiles);
-	pL->iOrderedFiles=new TRomBuilderEntry*[aMaxFiles];
-	return pL;
-	}
-
-void COrderedFileList::Add(TRomBuilderEntry* anEntry)
-	{
-	// note: this routine assumes that the set of kernel-mode files
-	// (primary/extension/device) required by a given variant is linearly ordered by <=
-	// e.g. can't have three variants {A,B,V1} {A,B,C,V2} {A,C,V3} because B and C
-	// are unordered with respect to <=, since neither of
-	// {n | Vn requires B} and {n | Vn requires C} is a subset of the other.
-	// In a case like this, ROMBUILD may fail to resolve the addresses of some global data
-	THardwareVariant& v=anEntry->iHardwareVariant;
-	TInt i=0;
-	while(i<iCount && v<=iOrderedFiles[i]->iHardwareVariant) i++;
-	TInt j=iCount;
-	while(j>i)
-		{
-		iOrderedFiles[j]=iOrderedFiles[j-1];
-		j--;
-		}
-	iOrderedFiles[i]=anEntry;
-	iCount++;
-	}
-
-void GetFileNameAndUid(char *aDllName, TUid &aDllUid, char *aExportName)
-	{	
-	strcpy(aDllName, aExportName);
-	aDllUid=KNullUid;
-	TInt start;
-	for (start=0; start<(TInt)strlen(aExportName) && aExportName[start]!='['; start++)
-		;
-	if (start==(TInt)strlen(aExportName))
-		start=KErrNotFound;
-	TInt end=strlen(aExportName)-1;
-	while (end>=0)
-		{
-		if (aExportName[end]==']')
-			break;
-		--end;
-		}
-	if (end<0)
-		end=KErrNotFound;
-
-	if ((start!=KErrNotFound) && (end!=KErrNotFound) && (end>start))
-		{
-		// Importing from DLL with Uid
-		char uidStr[0x100];
-		strcpy(uidStr, "0x");
-		strncat(uidStr, aExportName+start+1, end-start-1);
-		#ifdef __TOOLS2__
-		istringstream val(uidStr);
-		#else
-		istrstream val(uidStr,strlen(uidStr));
-		#endif
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-		val >> setbase(0);
-#endif //__MSVCDOTNET__
-
-		TUint32 u;
-		val >> u;
-		val.peek();
-		if (val.eof())
-			{
-			aDllUid=TUid::Uid(u);
-			char *dot=aExportName+strlen(aExportName)-1;
-			while (dot>=aExportName)
-				{
-				if (*dot=='.')
-					break;
-				dot--;
-				}
-			if (dot<aExportName) // no dot
-				aDllName[start]=0;
-			else
-				{
-				aDllName[start]=0;
-				strcat(aDllName, dot);
-				}
-			}
-		}
-	}
-
-E32Rom::E32Rom(CObeyFile *aObey)
-//
-// Constructor
-//
-	{
-
-	iSize=sizeof(TRomLoaderHeader)+aObey->iRomSize;
-	iObey=aObey;
-	iPeFiles=NULL;
-
-	if(gLowMem)
-	{
-		iImageMap = new Memmap();
-
-		if(iImageMap == NULL)
-		{
-			iSize = 0;
-			Print(EError, "Out of memory.\n");
-		}
-		else
-		{
-			iImageMap->SetMaxMapSize(iSize);
-			if(iImageMap->CreateMemoryMap(0, 0xff) == EFalse)
-			{
-				iSize = 0;
-				Print(EError, "Failed to create image map object");
-
-				iImageMap->CloseMemoryMap(ETrue);
-				delete iImageMap;
-				iImageMap = NULL;
-			}
-			else
-			{
-				iData = iImageMap->GetMemoryMapPointer();
-			}
-		}
-	}
-	else
-	{
-		iData=new char [iSize];
-		if (iData==NULL)
-			{
-			iSize=0;
-			Print(EError, "Out of memory.\n");
-			}
-		HMem::Set(iData, 0xff, iSize);
-	}
-	iHeader=(TRomHeader *)(iData+sizeof(TRomLoaderHeader));
-	iExtensionRomHeader=NULL;
-	iLoaderHeader=(TRomLoaderHeader *)iData;
-	iSectionPtr=(char *)iHeader+aObey->iSectionStart-aObey->iRomLinearBase+sizeof(TRomSectionHeader);
-	TheRomHeader=(ImpTRomHeader *)iHeader;
-	TheRomMem=(TUint32)iHeader;
-	iNextDataChunkBase=aObey->iKernDataRunAddress;
-	iTotalSvDataSize=0;
-	iNextDllDataAddr=aObey->iDllDataTop;
-	iPrevPrimaryAddress=NULL;
-	iPrevVariantAddress=NULL;
-	iVariantFileLists=NULL;
-	iImportsFixedUp=0;
-	iBranchesFixedUp=0;
-	iVtableEntriesFixedUp=0;
-	iOverhead=0;
-	}
-
-E32Rom::~E32Rom()
-//
-// Destructor
-//
-	{
-
-	if(gLowMem)
-	{
-		iImageMap->CloseMemoryMap(ETrue);
-		delete iImageMap;
-	}
-	else
-		delete iData;
-	delete [] iPeFiles;
-	if (iVariantFileLists)
-		{
-		TInt i;
-		for (i=0; i<iObey->iNumberOfVariants; i++)
-			delete iVariantFileLists[i];
-		delete [] iVariantFileLists;
-		}
-	}
-
-TInt E32Rom::Align(TInt aVal)
-//
-// Align to romalign
-//
-	{
- 	
-	return ((aVal+iObey->iRomAlign-1)/iObey->iRomAlign)*iObey->iRomAlign;
-	}
-
-TInt E32Rom::LoadContents(char*& anAddr, TRomHeader* aHeader)
-	{
-	// Load all the PE/E32Image files
-	TInt nfiles=iObey->iNumberOfPeFiles;
-	iPeFiles=new TRomBuilderEntry* [nfiles];
-	if (!iPeFiles)
-		return Print(EError, "Out of memory.\n");
-
-	TInt r=TranslateFiles();
-	if (r!=KErrNone)
-		return r;
-	
-	ProcessDllData();
-
-	EnumerateVariants();
-
-	r=BuildDependenceGraph();
-	if (r!=KErrNone)
-		return r;
-
-	// Update the ROM image headers with SMP information.
-	SetSmpFlags();
-
-	r=ProcessDependencies();
-	if (r!=KErrNone)
-		return r;
-
-	char* addr = anAddr;
-	TRomExceptionSearchTable* exceptionSearchTable = 0;
-
-	if(gPagedRom)
-		{
-		gDepInfoFile = (char* )malloc(strlen((char *)iObey->iRomFileName) + 1);
-		strcpy(gDepInfoFile, (char *)iObey->iRomFileName);
-		iObey->SetArea().DefaultArea()->SortFilesForPagedRom();
-		// exception search table needs to go at start of ROM to make it not demand paged...
-		addr = ReserveRomExceptionSearchTable(addr,exceptionSearchTable);
-		}
-	else if(gGenDepGraph)
-		{
-			Print(EWarning, "Not dependence information in an unpaged ROM.");
-		}
-
-	addr=WriteDirectory(addr, aHeader);
-	// Aligned
-
-	TRACE(TSCRATCH,Print(EAlways,"Directory written\n"));
-
-	// Stick all the files in ROM
-
-	TReloc* relocationTable;
-	addr = AllocateRelocationTable(addr, relocationTable);
-	aHeader->iRelocInfo = relocationTable ? ActualToRomAddress(relocationTable) : 0;
-	// Aligned
-
-	TRACE(TSCRATCH,Print(EAlways,"Done AllocateRelocationTable\n"));
-
-	CalculateDataAddresses();
-	addr = LayoutRom(addr);
-
-	TRACE(TSCRATCH,Print(EAlways,"Done LayoutRom\n"));
-
-	FillInRelocationTable(relocationTable);
-
-	TRACE(TSCRATCH,Print(EAlways,"Done FillInRelocationTable\n"));
-
-	if(!exceptionSearchTable)
-		addr = ReserveRomExceptionSearchTable(addr,exceptionSearchTable);
-	ConstructRomExceptionSearchTable(exceptionSearchTable);
-
-	TRACE(TSCRATCH,Print(EAlways,"Done ConstructRomExceptionSearchTable\n"));
-
-	LinkKernelExtensions(iObey->iExtensions, iObey->iNumberOfExtensions);
-
-	TRACE(TSCRATCH,Print(EAlways,"Done LinkKernelExtensions\n"));
-
-	r=ResolveDllRefTables();
-	if (r!=KErrNone)
-		return r;
-	r=ResolveImports();
-	if (r!=KErrNone)
-		return r;
-	if (iObey->iCollapseMode>ECollapseNone)
-		{
-		r=CollapseImportThunks();
-		if (r!=KErrNone)
-			return r;
-		if (iObey->iCollapseMode>ECollapseImportThunksOnly)
-			{
-			r=CollapseBranches();
-			if (r!=KErrNone)
-				return r;
-			}
-		Print(ELog,"%d imports, %d branches, %d vtable entries fixed up\n",
-			  iImportsFixedUp,iBranchesFixedUp,iVtableEntriesFixedUp);
-		}
-
-	iSizeUsed=(TInt)addr-(TInt)iHeader;
-	Print(ELog, "\n%08x of %08x bytes used.\n", iSizeUsed, iSize-sizeof(TRomLoaderHeader));
-
-	// round the rom size in the header to a multiple of 1 Megabyte
-	TInt rounded = ((iSizeUsed+0xfffff)&0xfff00000);
-	if (rounded < iObey->iRomSize)
-		iObey->iRomSize = rounded;
-	iUncompressedSize = iSizeUsed;
-
-	anAddr = addr;
-
-	return KErrNone;
-	}
-
-
-void E32Rom::CreatePageIndex(char*& aAddr)
-	{
-	iHeader->iRomPageIndex = 0;
-	if(gPagedRom==0 || gEnableCompress==0)
-		return;
-
-	// Insert space for Rom Page Info table...
-	iHeader->iRomPageIndex = (TInt)aAddr-(TInt)iHeader;
-	TInt pageSize = iObey->iPageSize;
-	TInt numPages = iSize/pageSize+1;
-	TInt pageInfoSize = numPages*sizeof(SRomPageInfo);
-	
-	gPageIndexTableSize = pageInfoSize;		// For accumulate uncompressed un-paged size added Page Index Table
-		
-	Print(ELog, "Inserting %d bytes for RomPageInfo at ROM offset 0x%08x\n", pageInfoSize, iHeader->iRomPageIndex);
-	memset(aAddr,0,pageInfoSize);
-	iOverhead += pageInfoSize;
-	aAddr += pageInfoSize;
-	}
-
-TInt E32Rom::SetupPages()
-	{
-	iHeader->iPageableRomStart = 0;
-	iHeader->iPageableRomSize = 0;
-	iHeader->iDemandPagingConfig = gDemandPagingConfig;
-
-	if(!gPagedRom)
-		return KErrNone;
-
-	// Initialise the Rom Page Info for each page which indicates it is uncompressed...
-	TInt pageSize = iObey->iPageSize;
-
-	TInt pagedStartOffset = 0x7fffffff;
-	TRomBuilderEntry* e = iObey->SetArea().DefaultArea()->iFirstPagedCode;
-	if(e)
-		{
-		// we have paged code...
-		pagedStartOffset = e->RomEntry()->iAddressLin-iObey->iRomLinearBase;
-		pagedStartOffset = (pagedStartOffset+pageSize-1)&~(pageSize-1); // round up to next page;
-		iHeader->iPageableRomStart = pagedStartOffset;
-		TInt pageableSize = iSizeUsed-pagedStartOffset;
-		if(pageableSize>0)
-			iHeader->iPageableRomSize = pageableSize;
-		}
-	
-	return KErrNone;
-	}
-
-TInt E32Rom::CompressPages()
-	{
-	
-	if(!gPagedRom || !gEnableCompress)
-		return KErrNone;
-
-	// Initialise the Rom Page Info for each page which indicates it is uncompressed...
-	TInt pageSize = iObey->iPageSize;
-	TInt numPages = (iSizeUsed+pageSize-1)/pageSize;
-
-	TInt pagedStartOffset = iHeader->iPageableRomStart;
-
-	Print(EAlways, "\nCompressing pages...\n");
-	TInt inOffset = 0;
-    SRomPageInfo* pi = (SRomPageInfo*)((TInt)iHeader+iHeader->iRomPageIndex);
-	TInt currentIndex = 0;
-	while(inOffset < pagedStartOffset)
-		{
-		
-		TUint8 attrib = (TUint8)0;
-		SRomPageInfo info = {(TUint32)inOffset,(TUint16)pageSize,(TUint8)SRomPageInfo::EBytePair,(TUint8)attrib};
-		info.iDataSize = (TUint16) pageSize;
-		*pi++ = info;
-		inOffset += pageSize;
-		if((currentIndex & 255) == 255)
-			Print(EAlways, ".\n");
-		currentIndex++;
-		}
-	CompressPageWorker compressworker(this, pageSize, numPages, currentIndex);
-
-	boost::thread_group threads;
-	for(int i = 0; i < gThreadNum; i++)
-		{
-		threads.create_thread(compressworker);
-		}
-	threads.join_all();
-	if(compressworker.m_error < 0)
-	       return compressworker.m_error;
-	for(;currentIndex < numPages - 1; currentIndex++)
-		{
-		pi++;
-		SRomPageInfo* prev = pi - 1;
-		TUint8* dest = (TUint8*) iHeader + prev->iDataStart + prev->iDataSize;
-		TUint8* src = (TUint8*) iHeader + pi->iDataStart;
-		memcpy(dest, src, pi->iDataSize);
-		pi->iDataStart = prev->iDataStart + prev->iDataSize;
-		}
-	TInt relSize = pi->iDataStart + pi->iDataSize;
-
-	memset((TUint8*)iHeader + relSize, 0xff, iSizeUsed - relSize);
-	TInt compression = (iSizeUsed >= 1000) ? (relSize*10)/(iSizeUsed/1000) : (relSize*10000)/iSizeUsed;
-	Print(EAlways, "%d.%02d%%\n", compression/100, compression%100);
-	iSizeUsed = relSize;
-	return KErrNone;
-	}
-
-TInt E32Rom::CompressPage(SRomPageInfo& aPageInfo, TInt aOutOffset, CBytePair * aBPE)
-	{
-	TUint8* in = (TUint8*)iHeader+aPageInfo.iDataStart;
-	TInt inSize = aPageInfo.iDataSize;
-	TUint8* out = (TUint8*)iHeader+aOutOffset;
-	switch(aPageInfo.iCompressionType)
-		{
-	case SRomPageInfo::ENoCompression:
-		memcpy(out,in,inSize);
-		return inSize;
-
-	case SRomPageInfo::EBytePair:
-		{
-		TInt r = BytePairCompress(out, in, inSize, aBPE);
-		if(r!=KErrTooBig)
-			return r;
-		// data can't be compressed...
-		aPageInfo.iCompressionType = SRomPageInfo::ENoCompression;
-		memcpy(out,in,inSize);
-		return inSize;
-		}
-
-	default:
-		Print(EError, "Unsupported page compression type (%d)\n", aPageInfo.iCompressionType);
-		return KErrNotSupported;
-		}
-	}
-
-
-// Avoid "warning" about constant expression
-static void checksize(const char* aTypeName, int aSize, int aCorrectSize)
-	{
-	if (aSize != aCorrectSize)
-		Print(EError, "sizeof(%s) = %d, should be %d\n", aTypeName, aSize, aCorrectSize);
-	}
-
-TInt E32Rom::CreateExtension(MRomImage* aKernelRom) 
-	{
-
-	// sanity check
-	checksize("TExtensionRomHeader", sizeof(TExtensionRomHeader), 128);
-
-	char *addr=(char *)iHeader;
-	iExtensionRomHeader=(TExtensionRomHeader*)addr;
-	addr += sizeof(TExtensionRomHeader);
-	// Aligned
-
-	TRomHeader dummy;
-	TInt r=LoadContents(addr, &dummy);
-	if (r!=KErrNone)
-		{
-		Print(EError, "LoadContents failed - return code %d\n", r);
-		return r;
-		}
-	iExtensionRomHeader->iRomRootDirectoryList = dummy.iRomRootDirectoryList;
-
-	iLoaderHeader->SetUp(iObey);
-	FinaliseExtensionHeader(aKernelRom);
-	DisplayExtensionHeader();
-
-	return KErrNone;
-	}
-	
-TInt E32Rom::Create()
-	{
-
-	TVariantList::Setup(iObey);
-	char *addr=(char *)iHeader;
-	// Aligned
-
-	// Put the bootstrap in rom - it contains a hole at offset 0x80 where the 
-	// TRomHeader information will be placed later
-
-	gBootstrapSize = HFile::Read(iObey->iBootFileName, iHeader);
-	if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
-		Print(ELog, "bootstrapSize: 0x%08x, (%d)\n", gBootstrapSize, gBootstrapSize);	
-	
-	if (gBootstrapSize==0)
-		return Print(EError, "Cannot open the bootstrap file '%s'.\n", iObey->iBootFileName);
-	gBootstrapSize=Align(gBootstrapSize);
-	addr+=gBootstrapSize;
-	iOverhead=gBootstrapSize;
-	// Aligned
-
-	CreatePageIndex(addr);
-
-	TInt r=LoadContents(addr, iHeader);
-	if (r!=KErrNone)
-		{
-		Print(EError, "LoadContents failed - return code %d\n", r);
-		return r;
-		}
-
-	r = SetupPages(); // initialize ROM paging info...
-	if(r!=KErrNone)
-		{
-		Print(EError, "Setup pages information failed - return code %d\n", r);
-		return r;
-		}
-	
-	r = CheckUnpagedMemSize(); // check for unpaged memory overflow
-	if(r!=KErrNone)
-	{
-		return r;
-	}
-	
-	r = CompressPages(); // setup ROM paging info...
-	if(r!=KErrNone)
-		{
-		Print(EError, "CompressPages failed - return code %d\n", r);
-		return r;
-		}
-
-	iLoaderHeader->SetUp(iObey);
-	ImpTRomHeader* header = (ImpTRomHeader *)iHeader;
-	header->SetUp(iObey);
-	header->iTotalSvDataSize=iTotalSvDataSize;
-	if (iObey->iMemModel==E_MM_Direct)
-		{
-		header->iUserDataAddress=iObey->iDataRunAddress;
-		header->iTotalUserDataSize=iNextDataChunkBase-iObey->iDataRunAddress;
-		}
-	else
-		{
-		header->iUserDataAddress=iObey->iDllDataTop;
-		header->iTotalUserDataSize=iObey->iDllDataTop-iNextDllDataAddr;
-		}
-	if (header->iRomSectionHeader)
-		FinaliseSectionHeader();	// sorts out the second section checksum
-
-	header->CheckSum(iObey->iCheckSum);	// finally, sort out the overall checksum
-
-	header->Display();
-
-	TUint testCheckSum = HMem::CheckSum((TUint *)iHeader, iHeader->iRomSize);
-	Print(ELog, "Rom 32bit words sum to   %08x\n", testCheckSum);
-	if (testCheckSum != iObey->iCheckSum)
-		return Print(EError, "Rom checksum is incorrect: %08x should be %08x\n",
-					testCheckSum, iObey->iCheckSum);
-
-	// 8bit checksum = sum of bytes
-	// odd/even checksum = checksum of the odd and even halfwords of the image
-
-	Print(ELog, "Rom 8bit checksum        %08x\n", HMem::CheckSum8((TUint8 *)iHeader, iHeader->iRomSize));
-	Print(ELog, "Rom 8bit odd checksum    %08x\n", HMem::CheckSumOdd8((TUint8 *)iHeader, iHeader->iRomSize));
-	Print(ELog, "Rom 8bit even checksum   %08x\n", HMem::CheckSumEven8((TUint8 *)iHeader, iHeader->iRomSize));
-
-	if (iHeader->iPrimaryFile)
-		{
-		if (iObey->iKernelModel==ESingleKernel)
-			{
-			Print(ELog,"\nPrimary details (Single Kernel):\n");
-			TRomEntry *r = (TRomEntry *)(iHeader->iPrimaryFile-iObey->iRomLinearBase+(char *)iHeader);
-			TRomImageHeader *hdr = (TRomImageHeader *)(r->iAddressLin-iObey->iRomLinearBase+(char *)iHeader);
-			Display(hdr);
-			Print(ELog,"\n");
-			}
-		else if (iObey->iKernelModel==EMultipleKernels)
-			{
-			Print(ELog,"\nPrimary details (Multiple Kernels):\n");
-			TRomEntry *r = (TRomEntry *)(iHeader->iPrimaryFile-iObey->iRomLinearBase+(char *)iHeader);
-			TInt n=1;
-			FOREVER
-					{
-					Print(ELog,"\nKernel %d:\n",n);
-					TRomImageHeader *hdr = (TRomImageHeader *)(r->iAddressLin-iObey->iRomLinearBase+(char *)iHeader);
-					Display(hdr);
-					Print(ELog,"\n");
-					if (!hdr->iNextExtension)
-						break;
-					r=(TRomEntry*)(hdr->iNextExtension-iObey->iRomLinearBase+(char*)iHeader);
-					n++;
-					}
-			}
-		}
-
-	return KErrNone;
-	}
-
-char *E32Rom::WriteDirectory(char *aAddr, TRomHeader* aHeader)
-//
-// Write the directory structure where appropriate
-//
-	{
-
-	TLinAddr dirptr=ActualToRomAddress(aAddr);
-	if (iObey->iSectionPosition==-1)
-		{
-		// Just the one rom.  Put the directory structure at aAddr
-		iDirectorySize=WriteHeadersToRom(aAddr);
-		aAddr+=Align(iDirectorySize);
-		}
-	else
-		{
-		// Put the directory structure in the second ROM, after the SectionHeader
-		// and the second section information for first section files
-		TInt size=0;
-		TInt i;
-		for (i=0; i<iObey->iNumberOfPeFiles; i++)
-			{
-			TRomBuilderEntry *file=iPeFiles[i];
-			if (file->iRomSectionNumber!=0)
-				break;
-			TInt size1, size2;
-			file->SizeInSections(size1,size2);
-			size+=size2;
-			}
-		dirptr=ActualToRomAddress(iSectionPtr)+size;
-		iDirectorySize=WriteHeadersToRom(RomToActualAddress(dirptr));
-		}
-	aHeader->iRomRootDirectoryList=dirptr;
-	return aAddr;
-	}
-
-void E32Rom::Display(TRomImageHeader *aHdr)
-//
-// Print info on a file
-//
-	{
-	TRACE(TAREA, Print(ELog, "+Display header %08x\n", aHdr));
-	Print(ELog, "Uids:                    %08x %08x %08x %08x\n", aHdr->iUid1, aHdr->iUid2, aHdr->iUid3, aHdr->iUidChecksum);
-	Print(ELog, "Entry point:             %08x\n", aHdr->iEntryPoint);
-	Print(ELog, "Code start addr:         %08x\n", aHdr->iCodeAddress);
-	Print(ELog, "Data start addr:         %08x\n", aHdr->iDataAddress);
-	Print(ELog, "DataBssLinearBase:       %08x\n", aHdr->iDataBssLinearBase);
-	Print(ELog, "Text size:               %08x\n", aHdr->iTextSize);
-	Print(ELog, "Code size:               %08x\n", aHdr->iCodeSize);
-	Print(ELog, "Data size:               %08x\n", aHdr->iDataSize);
-	Print(ELog, "BssSize:                 %08x\n", aHdr->iBssSize);
-	Print(ELog, "Total data size:         %08x\n", aHdr->iTotalDataSize);
-	Print(ELog, "Heap min:                %08x\n", aHdr->iHeapSizeMin);
-	Print(ELog, "Heap max:                %08x\n", aHdr->iHeapSizeMax);
-	Print(ELog, "Stack size:              %08x\n", aHdr->iStackSize);
-	Print(ELog, "Dll ref table:           %08x\n", aHdr->iDllRefTable);
-	Print(ELog, "Export directory:        %08x\n", aHdr->iExportDir);
-	Print(ELog, "Export dir count:        %08x\n", aHdr->iExportDirCount);
-	Print(ELog, "Hardware variant:        %08x\n", aHdr->iHardwareVariant);
-	Print(ELog, "Flags:                   %08x\n", aHdr->iFlags);
-	Print(ELog, "Secure ID:               %08x\n", aHdr->iS.iSecureId);
-	Print(ELog, "Vendor ID:               %08x\n", aHdr->iS.iVendorId);
-	Print(ELog, "Capability:              %08x %08x\n", aHdr->iS.iCaps[1], aHdr->iS.iCaps[0]);
-	Print(ELog, "Tools Version:           %d.%02d(%d)\n", aHdr->iToolsVersion.iMajor, aHdr->iToolsVersion.iMinor, aHdr->iToolsVersion.iBuild);
-	Print(ELog, "Module Version:          %d.%d\n", aHdr->iModuleVersion>>16, aHdr->iModuleVersion&0x0000ffffu);
-	Print(ELog, "Exception Descriptor:    %08x\n", aHdr->iExceptionDescriptor);
-	Print(ELog, "Priority:                %d\n", aHdr->iPriority);
-	}
-
-void E32Rom::DisplaySizes(TPrintType aWhere)
-	{
-
-	Print(aWhere, "Summary of file sizes in rom:\n");
-	Print(aWhere, "Overhead (bootstrap+gaps+sectioning)\t%d\n", iOverhead);
-	Print(aWhere, "Overhead (directory size)\t%d\n", iDirectorySize);
-	TRomBuilderEntry *file=iObey->FirstFile();
-	while (file)
-		{
-		file->DisplaySize(aWhere);
-		file=iObey->NextFile();
-		}
-	Print(aWhere, "\nTotal used\t%d\n", iSizeUsed);
-	Print(aWhere, "Free\t%d\n", iObey->iRomSize-iSizeUsed);
-
-	if (iObey->SetArea().Count() > 1)
-		{
-		Print(aWhere, "\nArea summary:\n");
-		for (NonDefaultAreasIterator it(iObey->SetArea());
-			 ! it.IsDone();
-			 it.GoToNext())
-			{
-			const Area& a = it.Current();
-			Print(aWhere, "%s\t used: %d bytes / free: %d bytes\n",
-				  a.Name(), a.UsedSize(), a.MaxSize()-a.UsedSize());
-			}
-		}
-	}
-
-TInt E32Rom::RequiredSize()
-//
-// Get the (approximate) required size of the Rom
-//
-	{
-
-	TInt sum=0;
-	TRomBuilderEntry *current=iObey->FirstFile();
-	while (current)
-		{
-		if (current->iResource || current->HCRDataFile())
-			sum+=Align(HFile::GetLength((TText*)current->iFileName));
-		else
- 			sum+=Align(current->SizeInRom());
-		current=iObey->NextFile();
-		}
-	return sum+iOverhead+Align(iDirectorySize);
-	}
-
-TInt E32Rom::TranslateFiles()
-//
-// Load and translate all PE/E32 image files
-//
-	{
-
-	TInt i=0;
-	TInt total_errors = 0;
-	TRomBuilderEntry* current = 0;
-	EntryQueue imagesQueue;
-	for (current = iObey->FirstFile(); current; current = iObey->NextFile() )
-		{	
-		if ((!current->iResource) && (!current->HCRDataFile()))
-			{
-			iPeFiles[i++]=current;
-			imagesQueue.push(current);
-			}
-		}
-	LoadImageWorker loadworker(&imagesQueue, iObey->iMemModel);
-	boost::thread_group threads;
-	for(int i = 0; i < gThreadNum; i++)
-		{
-		threads.create_thread(loadworker);
-		}
-	threads.join_all();
-
-	total_errors = loadworker.m_errors;
-	if (total_errors)
-		return KErrGeneral;
-	for (current = iObey->FirstFile(); current; current = iObey->NextFile() )
-		{
-		if ((!current->iResource) && (!current->HCRDataFile()))
-			{
-			TInt err = CheckForVersionConflicts(current);
-			total_errors += err;
-			}
-		}
-	return total_errors ? KErrGeneral : KErrNone;
-	}
-
-const TText FileTypeFile[]=		"File     ";
-const TText FileTypePrimary[]=	"Primary  ";
-const TText FileTypeVariant[]=	"Variant  ";
-const TText FileTypeExtension[]="Extension";
-const TText FileTypeDevice[]=	"Device   ";
-
-void E32Rom::EnumerateVariants()
-	{
-	TInt vIndex;
-	TInt nFiles=iObey->iNumberOfExtensions+iObey->iNumberOfDevices+3;
-	iVariantFileLists=new COrderedFileList*[iObey->iNumberOfVariants];
-	for (vIndex=0; vIndex<iObey->iNumberOfVariants; vIndex++)
-		iVariantFileLists[vIndex]=COrderedFileList::New(nFiles);
-	for (vIndex=0; vIndex<iObey->iNumberOfVariants; vIndex++)
-		{
-		TRomBuilderEntry *variant=iObey->iVariants[vIndex];
-		THardwareVariant& v=variant->iHardwareVariant;
-		TInt i;
-		for (i=0; i<iObey->iNumberOfPrimaries; i++)
-			{
-			TRomBuilderEntry *primary=iObey->iPrimaries[i];
-			if (v<=primary->iHardwareVariant)
-				{
-				iVariantFileLists[vIndex]->Add(primary);
-				break;
-				}
-			}
-		iVariantFileLists[vIndex]->Add(variant);
-		for (i=0; i<iObey->iNumberOfExtensions; i++)
-			{
-			TRomBuilderEntry *ext=iObey->iExtensions[i];
-			if (v<=ext->iHardwareVariant)
-				{
-				iVariantFileLists[vIndex]->Add(ext);
-				}
-			}
-		for (i=0; i<iObey->iNumberOfDevices; i++)
-			{
-			TRomBuilderEntry *dev=iObey->iDevices[i];
-			if (v<=dev->iHardwareVariant)
-				{
-				iVariantFileLists[vIndex]->Add(dev);
-				}
-			}
-		}
-	TUint totalDataBss=0;
-	for (vIndex=0; vIndex<iObey->iNumberOfVariants; vIndex++)
-		{
-		TRomBuilderEntry *variant=iObey->iVariants[vIndex];
-		THardwareVariant& v=variant->iHardwareVariant;
-		COrderedFileList& files=*iVariantFileLists[vIndex];
-		TInt count=files.Count();
-		Print(ELog,"\nVariant %08x, %d Files:\n",v.ReturnVariant(),count); 
-		TInt i;
-		TUint dataOffset=0;
-		for (i=0; i<count; i++)
-			{
-			TRomBuilderEntry *pF=files[i];
-			TUint gap=0;
-			if (pF->iDataAlignment>0)
-				{
-				gap=(pF->iDataAlignment-dataOffset)%(pF->iDataAlignment);
-				dataOffset+=gap;
-				}
-			E32ImageHeader *pH=pF->iHdr;
-			if (pF->iDataBssOffset!=0xffffffff && pF->iDataBssOffset!=dataOffset)
-				Print(EError,"Conflicting DataBss addresses\n");
-			pF->iDataBssOffset=dataOffset;
-			TInt dataSize=AlignData(pH->iDataSize+pH->iBssSize);
-			const TText* pT=FileTypeFile;
-			if (pF->Primary())
-				pT=FileTypePrimary;
-			if (pF->Variant())
-				pT=FileTypeVariant;
-			if (pF->Extension())
-				pT=FileTypeExtension;
-			if (pF->Device())
-				pT=FileTypeDevice;
-			Print(ELog,"%s %12s[%08x] DataSize=%6x DataOffset=%6x",pT,pF->iName,pF->iHardwareVariant.ReturnVariant(),dataSize,dataOffset);
-			if (gap)
-				Print(ELog, " (gap %x for %x alignment)\n", gap, pF->iDataAlignment);
-			Print(ELog, "\n");
-			dataOffset+=dataSize;
-			}
-		if (dataOffset>totalDataBss)
-			totalDataBss=dataOffset;
-		}
-	Print(ELog,"\nTotal SvData size=%6x\n",totalDataBss);
-	iTotalSvDataSize=totalDataBss;
-	}
-
-TInt E32Rom::LoadDataToRom(TRomBuilderEntry *aFile, TAddressRange& aAddress, CBytePair* aBPE)
-//
-// Load a data file to rom
-//
-	{
-	const char* tn = "resource";
-	if (aFile->iNonXIP)
-		tn = (aFile->iCompression) ? "compressed executable" : "uncompressed executable";
-	Print(ELog,"Reading %s %s to rom linear address %08x\n", tn, aFile->iFileName, aAddress.iImageAddr);
-
-	TUint32 size=HFile::GetLength((TText*)aFile->iFileName);
-	if (size==0)
-		{
-		Print(EWarning, "File %s does not exist or is 0 bytes in length.\n",aFile->iFileName);
-		return size;
-		}
-
-	aFile->iHeaderRange=aAddress;
-	char* addr = (char*)aFile->iHeaderRange.iImagePtr;
-	const char* src = NULL;
-	#ifdef __TOOLS2__
-	ostringstream os;
-	#else
-	ostrstream os;
-	#endif
-	if (aFile->iNonXIP)
-		{
-		E32ImageFile f(aBPE);
-		TInt r = f.Open(aFile->iFileName);
-		// is it really a valid E32ImageFile?
-		if (r != KErrNone)
-			{
-			Print(EWarning, "File '%s' is not a valid executable.  Loading file as data.\n", aFile->iFileName);
-			aFile->iNonXIP = EFalse;
-			}
-		else
-			{
-			TUint compression = f.iHdr->CompressionType();
-			if (compression != aFile->iCompression || aFile->iPreferred)
-				{
-				if (compression == 0)
-					Print(ELog, "Compressing file %s\n", aFile->iFileName);
-				else if (aFile->iCompression == 0)
-					Print(ELog, "Decompressing file %s\n", aFile->iFileName);
-				f.iHdr->iCompressionType = aFile->iCompression;
-				if (aFile->iPreferred)
-					{
-					f.iHdr->iModuleVersion &= ~0xffffu;
-					f.iHdr->iModuleVersion |= 0x8000u;
-					}
-				f.UpdateHeaderCrc();
-				}
-			Print(ELog, "Compression Method:0x%08x/0x%08x \n", f.iHdr->CompressionType(), aFile->iCompression);
-			os << f;
-			#ifdef __TOOLS2__
-			size = (os.str()).length(); 
-			src = (os.str()).c_str();
-			#else
-			size = os.pcount();
-			src = os.str();
-			#endif
-			}
-		}
-	if (addr+size>iData+iSize)
-		{
-		Print(EError, "Can't fit '%s' in Rom.\n", aFile->iFileName);
-		Print(EError, "Rom overflowed by approximately 0x%x bytes.\n", RequiredSize()-iObey->iRomSize);
-		exit(667);
-		}
-	if (src)
-		memcpy(addr, src, size);
-	else
-		size = HFile::Read((TText*)aFile->iFileName, (TAny *)addr);
-	Print(ELog,"Size:                    %08x\n", size);
-
-	aFile->iHeaderRange.iSize=size;
-	aAddress.Extend(aFile->iHeaderRange.iSize);
-	return size;
-	}
-
-
-void E32Rom::CalculateDataAddresses()
-//
-//
-//
-	{
-
-	TInt i;
-	TUint32 maxkern = 0;
-	Print(ELog, "\nCalculating kernel limit.\n");
-	for (i=0; i<iObey->iNumberOfPeFiles; i++)
-		{
-		TRomBuilderEntry* e = iPeFiles[i];
-		if (e->Primary())
-			{
-			// this is a kernel
-			TUint32 stack = AlignToPage(e->iHdr->iStackSize);
-			TUint32 heap = AlignToPage(e->iHdr->iHeapSizeMax);
-			if (stack + heap > maxkern)
-				maxkern = stack + heap;
-			}
-		}
-	iObey->iKernelLimit = AlignToChunk(maxkern + iTotalSvDataSize) + iObey->iKernDataRunAddress;
-	if (iObey->iMemModel==E_MM_Direct)
-		iNextDataChunkBase=iObey->iDataRunAddress;
-	else
-		iNextDataChunkBase = iObey->iKernelLimit;
-	Print(ELog, "\nCalculating data addresses.\n");
-	for (i=0; i<iObey->iNumberOfPeFiles; i++)
-		{
-		TRACE(TAREA,Print(ELog,"CalculateDataAddresses %d %s\n",i,iPeFiles[i]->iFileName));
-		CalculateDataAddress(iPeFiles[i]);
-		}
-	TRACE(TIMPORT,Print(ELog,"CalculateDataAddresses complete\n"));
-
-	// On moving model, advance kernel limit past fixed process data areas
-	if (iObey->iMemModel==E_MM_Moving)
-		iObey->iKernelLimit = iNextDataChunkBase;
-	}
-
-void E32Rom::CalculateDataAddress(TRomBuilderEntry *aFile)
-//
-// Work out where the .data/.bss will be
-//
-	{
-	TUint32 dataBssSize=aFile->iRomNode->iRomFile->iTotalDataBss;
-	TUint32 dataRunAddr;
-	if (aFile->Primary())
-		{
-		dataRunAddr = iObey->iKernDataRunAddress;
-		CPU = aFile->iHdr->CpuIdentifier();
-		}
-	else
-		{
-		dataRunAddr = iObey->iDataRunAddress;
-		if (iObey->iMemModel!=E_MM_Multiple && iObey->iMemModel!=E_MM_Flexible && (aFile->iHdr->iFlags & KImageFixedAddressExe))	// propagate 'fixed' from PETRAN
-			{
-			dataRunAddr=0xffffffff;
-			}
-		}
-	if (aFile->iOverrideFlags&KOverrideAddress)
-		{
-		if ((iObey->iMemModel!=E_MM_Multiple && iObey->iMemModel!=E_MM_Flexible) || aFile->iRelocationAddress!=0xffffffff)
-			dataRunAddr=aFile->iRelocationAddress;
-		if (aFile->Extension() || aFile->Variant() || aFile->Device())
-			Print(EError, "reloc not permitted with extension/variant/device\n");
-		}
-	if (!aFile->IsDll() && !aFile->Primary() && (dataRunAddr==0xffffffff || iObey->iMemModel==E_MM_Direct))
-		{
-		dataRunAddr=iNextDataChunkBase;
-		TInt stackreserve=iObey->iDefaultStackReserve;
-		if (aFile->iOverrideFlags & KOverrideStackReserve)
-			stackreserve=aFile->iStackReserve;
-		TInt datsize=AlignToChunk(dataBssSize+stackreserve);
-		// Move target data address to next free chunk
-		iNextDataChunkBase+=datsize;
-		}
-	if (aFile->Extension() || aFile->Device() || aFile->Variant())
-		{
-		dataRunAddr=iObey->iKernDataRunAddress+aFile->iDataBssOffset;
-		}
-	else if (aFile->IsDll() && dataBssSize!=0 && aFile->iRomNode->iRomFile->iDataBssOffsetInExe<0)
-		{
-		iNextDllDataAddr = AllocVirtual(iNextDllDataAddr,dataBssSize);
-		dataRunAddr=iNextDllDataAddr;
-		}
-	if (iObey->iMemModel==E_MM_Moving && dataRunAddr==iObey->iDataRunAddress && aFile->Secondary())
-		{
-		Print(EWarning,"Secondary not fixed\n");
-		}
-
-	TRACE(TAREA, Print(ELog, "Data run address %08x\n", dataRunAddr));
-	aFile->iDataBssLinearBase=dataRunAddr;
-	}
-
-void E32Rom::LoadFileToRom(TRomBuilderEntry *aFile)
-//
-// Load an E32Image/PE file to rom
-//
-	{
-
-	char* addr = (char*)aFile->iHeaderRange.iImagePtr;
-	TRACE(TAREA, Print(ELog,"+LoadFileToRom addr %08x %08x %08x\n", addr,
-					   aFile->iHeaderRange.iImageAddr, aFile->iHeaderRange.iRunAddr));
-
-	if (addr+aFile->SizeInRom()>iData+iSize) // check this
-		{
-		Print(EError, "Can't fit '%s' in Rom.\n", aFile->iFileName);
-		Print(EError, "Rom overflowed by approximately 0x%x bytes.\n", RequiredSize()-iObey->iRomSize);
-		exit(666);
-		}
-
-	// check file will not overflow into next ROM
-	if (aFile->Primary())
-		{
-		if (!iPrevPrimaryAddress)
-			iHeader->iPrimaryFile=ActualToRomAddress(aFile->RomEntry());
-		else if (iObey->iKernelModel==EMultipleKernels)
-			{
-			((TRomImageHeader*)iPrevPrimaryAddress)->iNextExtension=ActualToRomAddress(aFile->RomEntry());
-			}
-		iPrevPrimaryAddress=addr;
-		TRACE(TAREA, Print(ELog, "iHeader->iPrimaryFile = %08x\n", iHeader->iPrimaryFile));
-		}
-
-	// Place the file in rom
-	if (aFile->Variant())
-		{
-		if (iPrevVariantAddress)
-			((TRomImageHeader*)iPrevVariantAddress)->iNextExtension=ActualToRomAddress(aFile->RomEntry());
-		else
-			iHeader->iVariantFile=ActualToRomAddress(aFile->RomEntry());
-		iPrevVariantAddress=addr;
-		}
-	if (aFile->IsDll() && aFile->iRomNode->iRomFile->iTotalDataBss!=0 && aFile->iRomNode->iRomFile->iDataBssOffsetInExe>=0)
-		{
-		TRomFile* f=aFile->iRomNode->iRomFile->iPDeps[0];	// attach process
-		aFile->iDataBssLinearBase = f->DataBssLinearBase() + aFile->iRomNode->iRomFile->iDataBssOffsetInExe;
-		}
-
-	aFile->LoadToRom();
-	}
-
-char *E32Rom::LayoutRom(char *romaddr)
-//
-// Layout the files from the obey file starting at romaddr in the image
-// dealing correctly with areas
-// Also deals with two section ROMs
-//
-	{
-
-	TAddressRange main;
-	TAddressRange* mainptr=&main;
-	SetImageAddr(main, romaddr);
-
-	TAddressRange second;
-	TAddressRange* secondptr=0;
-	if (iObey->iSectionStart != 0)
-		{
-		SetImageAddr(second,iSectionPtr);
-		secondptr = &second;
-		}
-
-	TInt fileCount=0;
-
-	//
-	// Process files in non default areas
-	//
-
-        CBytePair bpe(gFastCompress);
-	for (NonDefaultAreasIterator areaIt(iObey->SetArea());
-		 ! areaIt.IsDone();
-		 areaIt.GoToNext())
-		{
-		Area& currentArea = areaIt.Current();
-		currentArea.SetSrcBaseAddr(mainptr->iImageAddr);
-
-		mainptr->iRunAddr = currentArea.DestBaseAddr();
-
-		for (FilesInAreaIterator fileIt(currentArea);
-			 ! fileIt.IsDone();
-			 fileIt.GoToNext())
-			{
-			TRomBuilderEntry* currentFile = fileIt.Current();
-
-			LayoutFile(currentFile, *mainptr, secondptr, &bpe);
-		
-			TUint overflow;
-			if (! currentArea.ExtendSrcLimitAddr(mainptr->iImageAddr, overflow))
-				{
-				Print(EError, "Can't fit '%s' in area '%s'\n", currentFile->iFileName, currentArea.Name());
-				Print(EError, "Area overflowed by 0x%x bytes.\n", overflow);
-				exit(666);
-				}
-
-			++fileCount;
-			assert(iObey->iSectionPosition == -1 || fileCount < iObey->iSectionPosition);
-			}
-
-		TInt offset=(char*)mainptr->iImagePtr-romaddr;
-		mainptr->Extend(Align(offset)-offset);
-		} // for every non default area
-
-
-	//
-	// Process files in default area
-	//
-
-	mainptr->iRunAddr = mainptr->iImageAddr;
-
-	for (FilesInAreaIterator fileIt(*(iObey->SetArea().DefaultArea()));
-		 ! fileIt.IsDone();
-		 fileIt.GoToNext())
-		{
-		if (fileCount==iObey->iSectionPosition)
-			{
-			// skip rest of first section and pick up after the
-			// information already accumulated in the second section
-			NextRom(mainptr, secondptr);
-			mainptr = secondptr;
-			secondptr = 0;
-			}
-
-		LayoutFile(fileIt.Current(), *mainptr, secondptr, &bpe);
-
-		++fileCount;
-		}
-
-	// align to likely position of next file
-	TInt offset=(char*)mainptr->iImagePtr-romaddr;
-	offset = Align(offset)-offset;
-	mainptr->Extend(offset);
-	iOverhead +=offset;
-
-	return (char*)mainptr->iImagePtr;
- 	}
-
-void E32Rom::LayoutFile(TRomBuilderEntry* current, TAddressRange& aMain, TAddressRange* aSecond, CBytePair * aBPE)
-//
-// Work out where to place a file in ROM and set up the 
-// appropriate TAddressRange information
-//
-	{
-	TInt alignment = iObey->iRomAlign;
-	if (current->iAlignment > alignment)
-		alignment = current->iAlignment;
-
-	if (alignment)
-		{
-		// Align this file on a boundary
-		TUint32 romaddr=aMain.iRunAddr;
-		TInt i=romaddr & (alignment-1);
-		TInt gap=0;
-		if (i!=0)
-			gap=alignment-i;
-		if (current->iAlignment)
-			Print(ELog, "\nAlign to %08x.  Skipped %d bytes\n", romaddr+gap, gap);
-		aMain.Extend(gap);
-		iOverhead += gap;
-		}
-
-	if (current->iCodeAlignment != 0)
-		{
-		TUint32 runaddr=aMain.iRunAddr + sizeof(TRomImageHeader);
-		TInt i=runaddr & (current->iCodeAlignment-1);
-		TInt gap=0;
-		if (i!=0)
-			gap=current->iCodeAlignment-i;
-		Print(ELog, "\nCode Align to %08x.  Skipped %d bytes\n", runaddr+gap, gap);
-		aMain.Extend(gap);
-		iOverhead += gap;
-		}
-
-	Print(ELog,"\n********************************************************************\n");
-
-	if (current->iPatched)
-		Print(ELog, "[Patched file]\n");
-
-	if (current->iResource)
-		{
-		TInt size=LoadDataToRom(current, aMain, aBPE);
-		if (aSecond != 0 && aMain.iImageAddr > iObey->iSectionStart)
-			return;		// first section has overflowed
-		current->FixupRomEntries(size);
-		return;
-		}
-	if(current->HCRDataFile()){	
-		TInt size=LoadDataToRom(current, aMain, aBPE);		
-		if (aSecond != 0 && aMain.iImageAddr > iObey->iSectionStart)
-			return;		// first section has overflowed
-		current->FixupRomEntries(size);
-		iHeader->iHcrFileAddress =  current->iHeaderRange.iImageAddr ;
-		TRACE(TAREA, Print(ELog, "iHeader->iHcrFileAddress = %08x\n", iHeader->iHcrFileAddress));		 
-		return ;
-	}
-	Print(ELog,"Processing file %s\n",current->iFileName);
-
-	if (current->Primary())
-		{
-		Print(ELog, "[Primary]\n");
-		}
-
-	if (current->Secondary())
-		{
-		iHeader->iSecondaryFile=ActualToRomAddress(current->RomEntry());
-		Print(ELog, "[Secondary]\n");
-		}
-
-	// Section 1 things
-	//
-	// TRomImageHeader, text, export directory, data
-
-	aMain.Append(current->iHeaderRange);
-	aMain.Append(current->iCodeSection);
-	aMain.Append(current->iDataSection);
-
-	// section 2 things
-	//
-	// dll ref table
-
-	if (aSecond != 0)
-		{
-		// two section ROM - split image between both sections
-		aSecond->Append(current->iExportDirSection);
-		aSecond->Append(current->iDllRefTableRange);
-		}
-	else
-		{
-		// default placement in first section
-		aMain.Append(current->iExportDirSection);
-		aMain.Append(current->iDllRefTableRange);
-		}
-
-	TInt section1size = aMain.iRunAddr-current->iCodeSection.iRunAddr;
-
-	if (aMain.iRunAddr == aMain.iImageAddr)
-		{
-		Print(ELog, "Load Address:            %08x\n", current->iHeaderRange.iImageAddr);
-		}
-	else
-		{
-		Print(ELog, "Rom Address:             %08x\n", current->iHeaderRange.iImageAddr);
-		Print(ELog, "Area Address:            %08x\n", current->iHeaderRange.iRunAddr);
-		}
-	Print(ELog,     "Size:                    %08x\n", section1size);
-
-	if (aSecond != 0 && aMain.iImageAddr > iObey->iSectionStart)
-		return;		// first section has overflowed
-
-	LoadFileToRom(current);
-	Display(current->iRomImageHeader);
-	Print(ELog,     "Dll ref table size:      %08x\n", current->iDllRefTableRange.iSize);
-	Print(ELog,     "Compression:             %08x\n", current->iCompression);
-	Print(ELog,     "\n");
-
-	current->FixupRomEntries(section1size);	
-	}
-
-static int CompareAddresses(const void * arg1, const void * arg2) 
-	{ 
-	return (* (TUint32 *)arg1) < (* (TUint32 *)arg2) ? -1: 1; 
-	}
-
-char *E32Rom::ReserveRomExceptionSearchTable(char *anAddr, TRomExceptionSearchTable*& exceptionSearchTable)
-	{
-	TRomExceptionSearchTable *pT = (TRomExceptionSearchTable *)anAddr;
-	exceptionSearchTable = pT;
-	if (iExtensionRomHeader)
-		{
-		iExtensionRomHeader->iRomExceptionSearchTable = ActualToRomAddress(anAddr);
-		}
-	else
-		{
-		iHeader->iRomExceptionSearchTable = ActualToRomAddress(anAddr);
-		}
-	TLinAddr * addr = &pT->iEntries[0];
-	int numEntries = 0;
-	int errors = 0;
-	// Count number of entries needed
-	for (int i = 0; i < iObey->iNumberOfPeFiles; i++)
-		{
-		TUint32 xd = iPeFiles[i]->iHdr->iExceptionDescriptor;
-		if ((xd & 1) && (xd != 0xffffffffu))
-			{
-			numEntries++;
-			}
-		else if (!iPeFiles[i]->iHdr->iExceptionDescriptor)
-			{
-#ifdef __REJECT_NON_EXCEPTION_AWARE_BINARIES__
-			Print(EError, "Executable not exception aware: %s\n", iPeFiles[i]->iName);
-			errors++;
-#else
-			Print(ELog, "Executable not exception aware: %s\n", iPeFiles[i]->iName);
-#endif
-			}
-		}
-	if (errors > 0) exit(666);
-	// NB we add one to numEntries to allow space for a fencepost value (see below for more)
-	int spaceNeeded = sizeof(pT->iNumEntries) + sizeof(pT->iEntries[0])*(numEntries+1);
-	int delta = (int)(addr+spaceNeeded) - (int)(iData+iSize);
-	// Check we've got enough room
-	if (delta > 0)
-		{
-		Print(EError, "Can't fit Rom Exception Search Table in Rom.\n");
-		Print(EError, "Rom overflowed by approximately 0x%x bytes.\n", delta);
-		exit(666);
-		}
-	pT->iNumEntries = numEntries;
-	return anAddr+spaceNeeded;
-	}
-	
-void E32Rom::ConstructRomExceptionSearchTable(TRomExceptionSearchTable* exceptionSearchTable)
-	{
-	TRomExceptionSearchTable *pT = exceptionSearchTable;
-	TLinAddr * addr = &pT->iEntries[0];
-	// Initialize the table
-	int numEntries = pT->iNumEntries;
-	TLinAddr fencepost = 0xffffffff;
-	if (numEntries)
-		{
-		TLinAddr fp = 0;
-		for (int j = 0; j < iObey->iNumberOfPeFiles; j++)
-			{
-			TUint32 xd = iPeFiles[j]->iHdr->iExceptionDescriptor;
-			if ((xd & 1) && (xd != 0xffffffff))
-				{
-				// mask out bottom bit set by ELFTRAN.
-				xd &= ~1;
-				*addr++ = iPeFiles[j]->iHdr->iCodeBase;
-				TLinAddr aEDAddr = iPeFiles[j]->iHdr->iCodeBase + xd; 
-				// Keep track of greatest code limit so we can use it as the fencepost value
-				TExceptionDescriptor * aEDp = (TExceptionDescriptor *)RomToActualAddress(aEDAddr);
-				TLinAddr codeLimit = aEDp->iROSegmentLimit;
-				if (codeLimit>fp) fp=codeLimit;
-				}
-			}
-		if (fp) fencepost=fp;
-		// now check they're in order (they should be).
-		int inOrder = 1;
-		for (int k=numEntries-1;inOrder && k; k--) 
-			{
-			inOrder = pT->iEntries[k]>pT->iEntries[k-1]?1:0;
-			}
-
-		if (!inOrder)
-			{
-			Print(ELog, "Sorting Rom Exception Table.\n");
-			qsort(&pT->iEntries[0],numEntries,sizeof(pT->iEntries[0]), CompareAddresses);
-			}
-		}
-	/*
-	  Add the fencepost value at the end of the table. This is used to optimize the comparison
-	  function passed to bsearch when retrieving values from the search table. It also allows a certain
-	  amount of error checking on lookup keys.
-	*/
-	*addr++ = fencepost;
-	}
-
-void TRomBuilderEntry::SizeInSections(TInt& aSize1, TInt& aSize2)
-//
-// Exact size of the upper & lower section information
-// lower = text + data
-// upper = export directory + dllref table
-//
-	{
-	aSize1  = iHeaderRange.iSize;
-	aSize1 += iCodeSection.iSize;			// text (including rdata)
-	aSize1 += iDataSection.iSize;			// static data
-
-	aSize2  = iExportDirSection.iSize;		// export directory
-	aSize2 += iDllRefTableRange.iSize;	// DLL ref table
-	}
-
-							
-void E32Rom::NextRom(TAddressRange* aFirst, TAddressRange* aSecond)
-//
-// Move on to the next Rom bank, taking the IATs with us
-//
-	{
-
-	Print(ELog,"\n####################################################################\n");
-	TInt gap=iObey->iSectionStart-aFirst->iImageAddr;
-	if (gap<0)
-		{
-		Print(EError, "First section overflowed by %08x bytes\n", -gap);
-		exit(669);
-		}
-	iOverhead+=gap+sizeof(TRomSectionHeader);
-	Print(ELog, "[Next rom section]\n");
-	Print(ELog, "Skipping %08x bytes\n", gap);
-	Print(ELog, "LinAddr:                 %08x\n", iObey->iSectionStart);
-	Print(ELog, "First section tables:    %08x\n", iObey->iSectionStart+sizeof(TRomSectionHeader));
-	TInt size=aSecond->iImageAddr-iObey->iSectionStart;
-	Print(ELog, "Tables size:             %08x\n", size-sizeof(TRomSectionHeader));
-	Print(ELog, "Rom Directory            %08x\n", iHeader->iRomRootDirectoryList);
-	Print(ELog, "Rom Directory size       %08x\n", iDirectorySize);
-
-	if (aSecond->iImageAddr != iHeader->iRomRootDirectoryList)
-		{
-		Print(EError, "Second section has overwritten the Rom directory\n");
-		exit(669);
-		}
-	aSecond->Extend(iDirectorySize);
-
-	Print(ELog, "\n");
-	}
-
-TInt E32Rom::ResolveDllRefTables()
-//
-//
-//
-	{
-
-	Print(ELog, "\nResolving Dll reference tables.\n");
-	TInt i;
-	TInt err = KErrNone;
-	for (i=0; i<iObey->iNumberOfPeFiles; i++)
-		{
-		TRACE(TIMPORT,Print(ELog,"ResolveDllRefTables %d\n",i));
-		TInt r=iPeFiles[i]->ResolveDllRefTable(*this);
-		if (r!=KErrNone)
-			err=r;
-		}
-	TRACE(TIMPORT,Print(ELog,"ResolveDllRefTables complete\n"));
-	return err;
-	}
-
-
-TInt E32Rom::BuildDependenceGraph()
-	{
-	Print(ELog, "\nBuilding dependence graph.\n");
-	TInt i;
-	TInt err = KErrNone;
-	for (i=0; i<iObey->iNumberOfPeFiles; i++)
-		{
-		TRACE(TIMPORT,Print(ELog,"BuildDep %d\n",i));
-		TRomBuilderEntry* e=iPeFiles[i];
-		TInt r=e->BuildDependenceGraph(*this);
-		if (r!=KErrNone)
-			err=r;
-		if (!e->IsDll())
-			{
-			if (e->iHdr->iDataSize!=0 || e->iHdr->iBssSize!=0)
-				e->iRomImageFlags|=(KRomImageFlagData|KRomImageFlagDataPresent);	// EXE with static data
-			}
-		else if ((e->iHdr->iDataSize!=0 || e->iHdr->iBssSize!=0) && !e->Variant() && !e->Extension())
-			{
-			// requires normal case DLL data initialisation
-			e->iRomImageFlags|=(KRomImageFlagData|KRomImageFlagDataInit|KRomImageFlagDataPresent);
-			}
-		}
-	TRACE(TIMPORT,Print(ELog,"BuildDep complete\n"));
-
-	if(!gPagedRom)
-		return err;
-
-	Print(ELog,"\n");
-
-	return err;
-	}
-
-#define MARK_BEEN_HERE	1
-#define MARK_KEEP		2
-#define	MARK_EXE		4
-#define MARK_CHECKED	8
-void E32Rom::UnmarkGraph(TInt aMark)
-	{
-	TRomNode* x = 0;
-	for (x=iObey->iRootDirectory->iNextExecutable; x; x=x->iNextExecutable)
-		x->iRomFile->iMark &= ~aMark;
-	}
-
-void E32Rom::FindMarked(TInt aMarkMask, TInt aMark, TRomFile**& aList)
-	{
-	UnmarkGraph(MARK_CHECKED);
-	TRomNode* x = 0;
-	aMarkMask |= MARK_CHECKED;
-	aMark &= ~MARK_CHECKED;
-	for (x=iObey->iRootDirectory->iNextExecutable; x; x=x->iNextExecutable)
-		{
-		TRomFile* e = x->iRomFile;
-		if ((e->iMark&aMarkMask)==aMark)
-			{
-			*aList++=e;
-			e->iMark |= MARK_CHECKED;
-			}
-		}
-	}
-
-TInt TRomFile::MarkDeps()
-	{
-	TInt n=0;
-	TInt i;
-	for (i=0; i<iNumDeps; ++i)
-		{
-		TRomFile* e=iDeps[i];
-		if (!(e->iMark & MARK_BEEN_HERE))
-			{
-			e->iMark|=MARK_BEEN_HERE;
-			++n;
-			n+=e->MarkDeps();
-			TUint32 flg = RomImageFlags();
-			TUint32 eflg = e->RomImageFlags();
-			if (eflg & KRomImageFlagDataPresent)
-				iRbEntry->iRomImageFlags |= KRomImageFlagDataPresent;
-			TBool e_is_dll = eflg & KImageDll;
-			if ((flg & KImageDll) && e_is_dll && (eflg & KRomImageFlagDataInit))
-				iRbEntry->iRomImageFlags |= KRomImageFlagDataInit;
-			if (!e_is_dll)
-				e->iMark|=MARK_EXE;
-			if (eflg&KRomImageFlagData)
-				e->iMark|=MARK_KEEP;
-			}
-		}
-	return n;
-	}
-
-TInt TRomFile::FindRouteTo(TRomFile* aDest, TRomFile** aStack, TInt aIndex)
-	{
-	TInt i;
-	for (i=0; i<iNumDeps; ++i)
-		{
-		TRomFile* e=iDeps[i];
-		if (e == aDest)
-			return aIndex;
-		if (!(e->iMark & MARK_BEEN_HERE))
-			{
-			e->iMark|=MARK_BEEN_HERE;
-			aStack[aIndex] = e;
-			TInt r = e->FindRouteTo(aDest, aStack, aIndex+1);
-			if (r >= 0)
-				return r;
-			}
-		}
-	return KErrNotFound;
-	}
-
-void E32Rom::ListRouteTo(TRomFile* aStart, TRomFile* aDest, TInt aNDeps)
-	{
-	TRomNode* rootdir = iObey->iRootDirectory;
-	TRomFile** stack = new TRomFile*[aNDeps];
-	UnmarkGraph();
-	TInt depth = aStart->FindRouteTo(aDest, stack, 0);
-	assert(depth >= 0);
-	Print(EAlways, "\t--->%s\n", (const char*)TModuleName(*aDest, rootdir));
-	while(--depth >= 0)
-		Print(EAlways, "\tvia %s\n", (const char*)TModuleName(*stack[depth], rootdir));
-	delete[] stack;
-	}
-
-TInt E32Rom::ProcessDependencies()
-	{
-	TInt i;
-	TInt errors = 0;
-	for (i=0; i<iObey->iNumberOfPeFiles; i++)
-		{
-		TRomBuilderEntry* e=iPeFiles[i];
-		TRomNode* rn = e->iRomNode;
-		TRomFile* rf = rn->iRomFile;
-		UnmarkGraph();
-		TInt n=rf->MarkDeps();
-		rf->iNumPDeps=n;
-		if (n)
-			{
-			rf->iPDeps=new TRomFile* [n];
-			if (!rf->iPDeps)
-				return KErrNoMemory;
-			TRomFile** l=rf->iPDeps;
-			FindMarked(MARK_EXE, MARK_EXE, l);
-			TInt nx=l-rf->iPDeps;
-			if (!e->IsDll() && (nx>1 || nx==1 && l[-1]!=rf))
-				{
-				Print(EError,"EXE %s links to the following other EXEs:\n", e->iFileName);
-				TInt j;
-				for (j=0; j<nx; ++j)
-					{
-					if (rf->iPDeps[j] != rf)
-						ListRouteTo(rf, rf->iPDeps[j], n);
-					}
-				++errors;
-				continue;
-				}
-			else if (nx>1)
-				{
-				Print(EError,"DLL %s links to more than one EXE:\n",e->iFileName);
-				TInt j;
-				for (j=0; j<nx; ++j)
-					ListRouteTo(rf, rf->iPDeps[j], n);
-				++errors;
-				continue;
-				}
-			if (nx)
-				e->iRomImageFlags|=KRomImageFlagExeInTree;
-			FindMarked(MARK_KEEP|MARK_EXE, MARK_KEEP, l);
-			rf->iNumPDeps=l-rf->iPDeps;
-			if (rf->iNumPDeps)
-				{
-				e->iDllRefTableRange.iSize=(rf->iNumPDeps-1)*sizeof(TRomImageHeader*)+sizeof(TDllRefTable);
-				if (e->IsDll() && rf->iTotalDataBss)
-					{
-					TRomFile* f=rf->iPDeps[0];	// first dependency, EXE if there is one
-					TUint fflg = f->RomImageFlags();
-					TBool f_is_dll = fflg & KImageDll;
-					if (!f_is_dll)
-						{
-						// DLL with data/bss depends on EXE
-						if ((fflg & KRomImageFlagFixedAddressExe) || iObey->iMemModel==E_MM_Direct)
-							{
-							// assign the DLL data address in the EXE bss section
-							rf->iDataBssOffsetInExe=f->iTotalDataBss;
-							f->iTotalDataBss+=rf->iTotalDataBss;
-							}
-						}
-					else if (iObey->iMemModel==E_MM_Direct)
-						{
-						Print(EError, "DLL with data/bss must have attach process specified\n");
-						return KErrGeneral;
-						}
-					}
-				}
-			else
-				{
-				delete[] rf->iPDeps;
-				rf->iPDeps=NULL;
-				}
-			}
-		if (!rf->iNumPDeps)
-			e->iDllRefTableRange.iSize=0;
-		}
-	if (iObey->iMemModel == E_MM_Moving)
-		{
-		// On moving model only, we must verify that no fixed process links to a
-		// DLL with data/bss which is attached to a fixed process.
-		// On multiple model there is no restriction.
-		// On direct model all DLLs with data/bss must specify an attach process
-		// and the error will show up as one EXE depending on another.
-		for (i=0; i<iObey->iNumberOfPeFiles; i++)
-			{
-			TRomBuilderEntry* e=iPeFiles[i];
-			TRomNode* rn = e->iRomNode;
-			TRomFile* rf = rn->iRomFile;
-			TUint rif = rf->RomImageFlags();
-			if (e->IsDll() || e->Primary() || !(rif & KRomImageFlagFixedAddressExe))
-				continue;	// only need to check fixed address user mode EXEs
-			TInt n = rf->iNumPDeps;
-			TInt j;
-			for (j=0; j<n; ++j)
-				{
-				TRomFile* f = rf->iPDeps[j];
-				TUint fflg = f->RomImageFlags();
-				if ((fflg & KImageDll) && (f->iDataBssOffsetInExe < 0))
-					{
-					// fixed user EXE links to DLL with data/bss and no attach process
-					Print(EError,"Fixed EXE %s links to DLL with data/bss and no attach process:\n", e->iFileName);
-					ListRouteTo(rf, rf->iPDeps[j], n);
-					++errors;
-					}
-				}
-			}
-		}
-	if (errors)
-		return KErrGeneral;
-
-	STRACE(TIMPORT, 
-		{
-		for (i=0; i<iObey->iNumberOfPeFiles; i++)
-			{
-			TRomBuilderEntry* e=iPeFiles[i];
-			TRomNode* rn = e->iRomNode;
-			TRomFile* rf = rn->iRomFile;
-			Print(ELog,"File %s: PN=%d\n",e->iFileName,rf->iNumPDeps);
-			TInt j;
-			for (j=0; j<rf->iNumPDeps; ++j)
-				{
-				TRomFile* f=rf->iPDeps[j];
-				Print(ELog,"\t%s\n", (const char*)TModuleName(*f, iObey->iRootDirectory));
-				}
-			}
-		})
-	return KErrNone;
-	}
-
-void E32Rom::SetSmpFlags()
-    {
-	if (gLogLevel & LOG_LEVEL_SMP_INFO)
-		{
-		Print(ELog,"\nComputing SMP properties. The following components are SMP-unsafe:\n");
-		}
-
-	bool is_all_safe = 1;
-
-	for (int i = 0; i < iObey->iNumberOfPeFiles; i++)
-		{
-		TRomBuilderEntry* e = iPeFiles[i];
-
-        if ( e->iRomNode->iRomFile->ComputeSmpSafe(e) )
-			{
-			e->iRomImageFlags |= KRomImageSMPSafe;
-			}
-		else
-			{
-			is_all_safe = 0;
-			e->iRomImageFlags &= ~KRomImageSMPSafe;
-			}
-		}
-
-	if ( (gLogLevel & LOG_LEVEL_SMP_INFO) && is_all_safe)
-		{
-		Print(ELog,"There are no unsafe components.");
-		}
-    }
-
-TInt E32Rom::ResolveImports()
-//
-// Fix the import address table for each of the files in rom
-//	
-	{
-
-	Print(ELog, "Resolving Imports.\n");
-	TInt i;
-	for (i=0; i<iObey->iNumberOfPeFiles; i++)
-		{
-		TInt r=iPeFiles[i]->FixupImports(*this);
-		if (r!=KErrNone)
-			return r;
-		}
-	return KErrNone;
-	}
-
-char *E32Rom::RomToActualAddress(TUint aPtr)
-	{
-	return (char *)(aPtr-iObey->iRomLinearBase+(TUint)iHeader);
-	}
-
-TUint E32Rom::ActualToRomAddress(TAny *aPtr)
-	{
-	return ((TUint)aPtr)-(TUint32)iHeader+iObey->iRomLinearBase;
-	}
-
-void E32Rom::SetImageAddr(TAddressRange& aRange, TAny* aPtr, TUint32 aRunOffset)
-	{
-	aRange.iImagePtr=aPtr;
-	aRange.iImageAddr=ActualToRomAddress(aPtr);
-	aRange.iRunAddr=aRange.iImageAddr+aRunOffset;
-	}
-
-void E32Rom::SetImageAddr(TAddressRange& aRange, TUint aAddr, TUint32 aRunOffset)
-	{
-	aRange.iImagePtr=RomToActualAddress(aAddr);
-	aRange.iImageAddr=aAddr;
-	aRange.iRunAddr=aAddr+aRunOffset;
-	}
-
-TRomNode* E32Rom::FindImageFileByName(const TDllFindInfo& aInfo, TBool aPrintDiag, TBool& aFallBack)
-//
-// return the file with the name aName
-//
-	{
-	return iObey->iRootDirectory->FindImageFileByName(aInfo, aPrintDiag, aFallBack);
-	}
-
-TInt E32Rom::CheckForVersionConflicts(const TRomBuilderEntry* a)
-	{
-	return iObey->iRootDirectory->CheckForVersionConflicts(a);
-	}
-
-TRomNode* E32Rom::CopyDirectory(TRomNode*& aLastExecutable)
-	{
-	return iObey->iRootDirectory->CopyDirectory(aLastExecutable, 0);
-	}
-
-TInt E32Rom::CollapseImportThunks()
-//
-// Collapse 3-word import thunks into a single branch
-//	
-	{
-
-	Print(ELog, "\nCollapsing Import Thunks.\n");
-	TInt i;
-	for (i=0; i<iObey->iNumberOfPeFiles; i++)
-		{
-		if (iPeFiles[i]->iHdr->iImportOffset)
-			{
-			TInt r=CollapseImportThunks(iPeFiles[i]);
-			if (r!=KErrNone)
-				return r;
-			}
-		}
-	return KErrNone;
-	}
-
-TInt E32Rom::WriteImages(TInt aHeaderType)
-	{
-	if (aHeaderType < 0)
-		aHeaderType = 1;
-	ofstream romFile((const char *)iObey->iRomFileName,ios::binary);
-	if (!romFile)
-		return Print(EError,"Cannot open ROM file %s for output\n",iObey->iRomFileName);
-	Write(romFile, aHeaderType);
-	romFile.close();
-
-	// Write out the odd/even 16-bits of the images
-
-	char sname[256];
-	if (iObey->iRomOddFileName)
-		{
-		strcpy(sname, (const char*)iObey->iRomOddFileName);
-		if (strcmp(sname, "*")==0)
-			{
-			// use romname with ".odd" appended.
-			sprintf(sname,"%s.odd",(const char *)iObey->iRomFileName);
-			}
-		ofstream oFile(sname,ios::binary);
-		if (!oFile)
-			return Print(EError,"Cannot open file %s for output\n",sname);
-		Print(EAlways, "Writing odd half words to file %s\n",sname);
-		WriteOdd(oFile);
-		oFile.close();
-		}
-	if (iObey->iRomEvenFileName)
-		{
-		strcpy(sname, (const char*)iObey->iRomEvenFileName);
-		if (strcmp(sname, "*")==0)
-			{
-			// use romname with ".even" appended.
-			sprintf(sname,"%s.even",(const char *)iObey->iRomFileName);
-			}
-		ofstream oFile(sname,ios::binary);
-		if (!oFile)
-			return Print(EError,"Cannot open file %s for output\n",sname);
-		Print(EAlways, "Writing even half words to file %s\n",sname);
-		WriteEven(oFile);
-		oFile.close();
-		}
-
-	// Write out the ROM in the SREC or S19 format
-
-	if (iObey->iSRecordFileName)
-		{
-		strcpy(sname, (const char*)iObey->iSRecordFileName);
-		if (strcmp(sname, "*")==0)
-			{
-			// use romname with ".srec" appended.
-			sprintf(sname,"%s.srec",(const char *)iObey->iRomFileName);
-			}
-		ofstream sFile(sname,ios::binary);
-		if (!romFile)
-			return Print(EError,"Cannot open file %s for output\n",sname);
-		Print(EAlways, "Writing S record format to file %s\n",sname);
-		WriteSRecord(sFile);
-		sFile.close();
-		}
-	return KErrNone;
-	}
-
-void E32Rom::WriteOdd(ofstream &os)
-	{
-	char *ptr=(char *)iHeader+2;
-	TInt i;
-	for (i=2; i<iObey->iRomSize; i+=4, ptr+=4)
-		os.write(ptr, 2);
-	}
-
-void E32Rom::WriteEven(ofstream &os)
-	{
-	char *ptr=(char *)iHeader;
-	TInt i;
-	for (i=0; i<iObey->iRomSize; i+=4, ptr+=4)
-		os.write(ptr, 2);
-	}
-
-void E32Rom::SetCompressionInfo(TUint aCompressionType, TUint aCompressedSize, TUint aUncompressedSize)
-	{
-
-	if (iExtensionRomHeader)
-		{
-		iExtensionRomHeader->iCompressionType=aCompressionType;
-		iExtensionRomHeader->iCompressedSize=aCompressedSize;
-		iExtensionRomHeader->iUncompressedSize=aUncompressedSize;
-		}
-	else
-		{
-		iHeader->iCompressionType=aCompressionType;
-		iHeader->iCompressedSize=aCompressedSize;
-		iHeader->iUncompressedSize=aUncompressedSize;
-		}
-	}
-
-void E32Rom::Write(ofstream &os, TInt aHeaderType)
-//
-// Output a rom image
-//
-	{
-
-	const char *compressed=gEnableCompress ? " compressed" : " uncompressed"; 
-
-	switch (aHeaderType)
-		{
-	case 0:
-		Print(EAlways, "\nWriting%s Rom image without",compressed);
-		break;
-	case 1:
-	default:
-		Print(EAlways, "\nWriting%sRom image with repro",compressed);
-		os.write(iData, sizeof(TRomLoaderHeader));
-		break;
-	case 2:
-		Print(EAlways, "\nWriting%s Rom image with PE-COFF",compressed);
-			{
-			unsigned char coffhead[0x58] = {0};  // zero all the elements
-
-			// fill in the constant bits
-			// this is supposed to be simple, remember
-			coffhead[1] = 0x0a;
-			coffhead[2] = 0x01;
-			coffhead[0x10] = 0x1c;
-			coffhead[0x12] = 0x0f;
-			coffhead[0x13] = 0xa1;
-			coffhead[0x14] = 0x0b;
-			coffhead[0x15] = 0x01;
-			coffhead[0x26] = 0x40;
-			coffhead[0x2a] = 0x40;
-			coffhead[0x30] = 0x2e;
-			coffhead[0x31] = 0x74;
-			coffhead[0x32] = 0x65;
-			coffhead[0x33] = 0x78;
-			coffhead[0x34] = 0x74;
-			coffhead[0x3a] = 0x40;
-			coffhead[0x3e] = 0x40;
-			coffhead[0x44] = 0x58;
-			coffhead[0x54] = 0x20;
-
-			// now fill in the text segment size
-			*(TUint32 *) (&coffhead[0x18]) = ALIGN4K(iSizeUsed);
-			*(TUint32 *) (&coffhead[0x40]) = ALIGN4K(iSizeUsed);
-
-			os.write(reinterpret_cast<char *>(coffhead), sizeof(coffhead));
-			}
-		break;
-		}
-	Print(EAlways, " header to file %s\n", iObey->iRomFileName);
-	
-	iHeader->iUnpagedCompressedSize   = 0;
-	iHeader->iUnpagedUncompressedSize = iHeader->iPageableRomStart;
-	iHeader->iCompressedUnpagedStart =  gBootstrapSize + gPageIndexTableSize;	// AttilaV calculate uncompressed un-paged size 
-	
-	if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
-		{
-		Print(ELog, "iUnpagedCompressedSize  :0x%08x (%d)\n",     iHeader->iUnpagedCompressedSize);
-		Print(ELog, "iUnpagedUncompressedSize:0x%08x (%d)\n\n",   iHeader->iUnpagedUncompressedSize);
-		
-		Print(ELog, "iExtensionRomHeader     :%d\n",     iExtensionRomHeader);
-		Print(ELog, "iCompressionType        :0x%08x\n", (iExtensionRomHeader ? iExtensionRomHeader->iCompressionType : iHeader->iCompressionType ));	
-		Print(ELog, "iCompressedSize         :0x%08x (%d)\n",     (iExtensionRomHeader ? iExtensionRomHeader->iCompressedSize  : iHeader->iCompressedSize ), (iExtensionRomHeader ? iExtensionRomHeader->iCompressedSize  : iHeader->iCompressedSize ));
-		Print(ELog, "iUncompressedSize       :0x%08x (%d)\n\n",   (iExtensionRomHeader ? iExtensionRomHeader->iUncompressedSize: iHeader->iUncompressedSize ), (iExtensionRomHeader ? iExtensionRomHeader->iUncompressedSize: iHeader->iUncompressedSize ));
-	
-		Print(ELog, "iPageableRomStart       :0x%08x (%d)\n",   iHeader->iPageableRomStart, iHeader->iPageableRomStart );
-		Print(ELog, "iPageableRomSize        :0x%08x (%d)\n",   iHeader->iPageableRomSize, iHeader->iPageableRomSize  );
-		Print(ELog, "iRomPageIndex           :0x%08x (%d)\n",   iHeader->iRomPageIndex, iHeader->iRomPageIndex );
-	
-		Print(ELog, "iSizeUsed               :0x%08x (%d)\n",   iSizeUsed, iSizeUsed );
-		Print(ELog, "Linear base address     :0x%08x\n",iHeader->iRomBase); 
-		Print(ELog, "Size:                    0x%08x\n",iHeader->iRomSize);
-		}
-
-	if ( gPagedRom && gCompressUnpaged)
-		{
-		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
-			Print(ELog, "Write out compressed un-paged and paged sections\n\n");
-		ImpTRomHeader* header = (ImpTRomHeader *)iHeader;
-		
-		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
-			{
-			Print(ELog, "Header:\n");
-			header->Display();
-			}
-		
-		streampos headerpos=os.tellp();
-		
-		// Write out uncompressed un-paged part (bootstrap + Page Index Table)
-		os.write((char *)(iHeader), iHeader->iCompressedUnpagedStart);
-		
-		// write out the compressed unpaged part
-		int srcsize=iHeader->iPageableRomStart - iHeader->iCompressedUnpagedStart;		
-		
-		int rawimagelen=DeflateCompressCheck(((char *)iHeader)+iHeader->iCompressedUnpagedStart,srcsize,os);
-		iHeader->iUnpagedCompressedSize = rawimagelen;
-		iHeader->iUnpagedUncompressedSize = srcsize ;
-		
-		// align to 4kbyte boundary if neccessary
-		TUint32 distanceFrom4kBoundary = ((~(iHeader->iCompressedUnpagedStart + rawimagelen /*+ sizeof(TRomLoaderHeader)*/ )) & 0xfff) + 1;
-		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
-			Print(ELog, "distanceFrom4kBoundary  :0x%08x (%d)\n", distanceFrom4kBoundary, distanceFrom4kBoundary);
-		char filer[0x1000];
-		memset( filer, 0, 0x1000);
-		os.write((char *)filer, distanceFrom4kBoundary);
-		
-		
-		// write out the paged part
-		os.write((char *)iHeader + iHeader->iPageableRomStart, ALIGN4K(iSizeUsed - iHeader->iPageableRomStart));
-		
-		// update size and compression information of paged-part
-		SetCompressionInfo(KUidCompressionDeflate, ALIGN4K(iSizeUsed), ALIGN4K(iUncompressedSize));
-		
-		// Calculate starting index of the Pageable Rom Start
-		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
-			{
-			Print(ELog, "iPageableRomStart				: %d (0x%08x)\n", iHeader->iPageableRomStart, iHeader->iPageableRomStart);
-			Print(ELog, "iCompressedUnpagedStart			: %d (0x%08x)\n", iHeader->iCompressedUnpagedStart, iHeader->iCompressedUnpagedStart);
-			Print(ELog, "rawimagelen						: %d (0x%08x)\n", rawimagelen, rawimagelen);
-			}
-		
-		TInt displacement = iHeader->iCompressedUnpagedStart + rawimagelen + distanceFrom4kBoundary; 
-		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
-			Print(ELog, "new iPageableRomStart			: %d (0x%08x)\n", (iHeader->iCompressedUnpagedStart + rawimagelen + distanceFrom4kBoundary), (iHeader->iCompressedUnpagedStart + rawimagelen + distanceFrom4kBoundary));
-		displacement = iHeader->iPageableRomStart-displacement;
-		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
-			Print(ELog, "displacement					: %d (0x%08x)\n", displacement, displacement);
-		
-		SRomPageInfo* pi = (SRomPageInfo*)((TInt)iHeader+iHeader->iRomPageIndex);
-		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
-			Print(ELog, "First Pageable page info[0x%08x]:(iDataStart:0x%08x, iDataSize:0x%08x (%d))\n\n", pi, pi->iDataStart, pi->iDataSize, pi->iDataSize);
-		
-		TInt startPageableIndex = (iHeader->iPageableRomStart) / (iObey->iPageSize);
-		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
-			{
-			Print(ELog, "iObey->iPageSize				: %d (0x%08x)\n", iObey->iPageSize, iObey->iPageSize);
-			Print(ELog, "startPageableIndex				: %d (0x%08x)\n", startPageableIndex, startPageableIndex);
-			}
-		pi += startPageableIndex;
-		
-		
-		while ( 0 != pi->iDataStart)
-			{
-				if (H.iVerbose) Print(ELog, "\t\tinfo[0x%08x]:(iDataStart:0x%08x, iDataSize:0x%08x (%d))\n\n", pi, pi->iDataStart, pi->iDataSize, pi->iDataSize);		
-				
-				pi->iDataStart -= displacement;
-				
-				if (H.iVerbose) Print(ELog, "\t\tinfo[0x%08x]:(iDataStart:0x%08x, iDataSize:0x%08x (%d))\n\n", pi, pi->iDataStart, pi->iDataSize, pi->iDataSize);		
-				
-				++pi;
-			}
-		
-		
-		
-		// Rewrite the header with updated info
-		#ifdef __TOOLS2__
-		os.seekp(headerpos); 
-		#else
-		os.seekp(headerpos,ios::beg);
-		#endif
-		
-		// Rewrite uncompressed un-paged part (bootstrap + Page Index Table)
-		os.write((char *)(iHeader), iHeader->iCompressedUnpagedStart);
-		
-		
-		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
-			{
-			Print(ELog, "iUnpagedCompressedSize  :0x%08x (%d)\n",     iHeader->iUnpagedCompressedSize, iHeader->iUnpagedCompressedSize);
-			Print(ELog, "iUnpagedUncompressedSize:0x%08x (%d)\n\n",   iHeader->iUnpagedUncompressedSize, iHeader->iUnpagedUncompressedSize);
-		
-			Print(ELog, "iCompressionType        :0x%08x\n", (iExtensionRomHeader ? iExtensionRomHeader->iCompressionType : iHeader->iCompressionType ));	
-			Print(ELog, "iCompressedSize         :0x%08x (%d)\n",     (iExtensionRomHeader ? iExtensionRomHeader->iCompressedSize  : iHeader->iCompressedSize ), (iExtensionRomHeader ? iExtensionRomHeader->iCompressedSize  : iHeader->iCompressedSize ));
-			Print(ELog, "iUncompressedSize       :0x%08x (%d)\n\n",   (iExtensionRomHeader ? iExtensionRomHeader->iUncompressedSize: iHeader->iUncompressedSize ), (iExtensionRomHeader ? iExtensionRomHeader->iUncompressedSize: iHeader->iUncompressedSize ));
-		
-			Print(ELog, "iPageableRomStart       :0x%08x (%d)\n",   iHeader->iPageableRomStart, iHeader->iPageableRomStart );
-			Print(ELog, "iPageableRomSize        :0x%08x (%d)\n",   iHeader->iPageableRomSize, iHeader->iPageableRomSize  );
-			Print(ELog, "iRomPageIndex           :0x%08x (%d)\n",   iHeader->iRomPageIndex, iHeader->iRomPageIndex );
-			Print(ELog, "\t\tinfo(iDataStart:0x%08x, iDataSize:0x%08x (%d))\n\n", pi->iDataStart, pi->iDataSize, pi->iDataSize);
-		
-			Print(ELog, "Linear base address:     %08x\n",iHeader->iRomBase); 
-			Print(ELog, "Size:                    %08x\n",iHeader->iRomSize);
-			}
-		
-		return;
-		}
-
-	if (!gEnableCompress || gPagedRom || !gCompressUnpaged)
-		{
-		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
-			Print(ELog, "Writeout uncompressed un-paged and paged sections2\n");
-		SetCompressionInfo(KFormatNotCompressed, ALIGN4K(iSizeUsed), ALIGN4K(iUncompressedSize));
-		iHeader->iUnpagedCompressedSize = ALIGN4K(iSizeUsed);
-		iHeader->iUnpagedUncompressedSize = ALIGN4K(iUncompressedSize);
-		
-		os.write((char *)iHeader, ALIGN4K(iSizeUsed));
-		
-		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
-			{
-			Print(ELog, "iUnpagedCompressedSize  :0x%08x (%d)\n",     iHeader->iUnpagedCompressedSize);
-			Print(ELog, "iUnpagedUncompressedSize:0x%08x (%d)\n\n",   iHeader->iUnpagedUncompressedSize);
-		
-			Print(ELog, "iCompressionType        :0x%08x\n", (iExtensionRomHeader ? iExtensionRomHeader->iCompressionType : iHeader->iCompressionType ));	
-			Print(ELog, "iCompressedSize         :0x%08x (%d)\n",     (iExtensionRomHeader ? iExtensionRomHeader->iCompressedSize  : iHeader->iCompressedSize ), (iExtensionRomHeader ? iExtensionRomHeader->iCompressedSize  : iHeader->iCompressedSize ));
-			Print(ELog, "iUncompressedSize       :0x%08x (%d)\n\n",   (iExtensionRomHeader ? iExtensionRomHeader->iUncompressedSize: iHeader->iUncompressedSize ), (iExtensionRomHeader ? iExtensionRomHeader->iUncompressedSize: iHeader->iUncompressedSize ));
-		
-			Print(ELog, "iPageableRomStart       :0x%08x (%d)\n",   iHeader->iPageableRomStart, iHeader->iPageableRomStart );
-			Print(ELog, "iPageableRomSize        :0x%08x (%d)\n",   iHeader->iPageableRomSize, iHeader->iPageableRomSize  );
-			Print(ELog, "iRomPageIndex           :0x%08x (%d)\n",   iHeader->iRomPageIndex, iHeader->iRomPageIndex );
-			}
-		
-		return;
-		}
-
-	// compressed image without paging section
-	streampos headerpos=os.tellp();
-	int headersize=iExtensionRomHeader ? sizeof(TExtensionRomHeader) : sizeof(TRomHeader);
-
-	os.write(reinterpret_cast<char*>(iHeader), headersize); // write a dummy header
-	// compress the rest of the image
-	int srcsize=iSizeUsed - headersize;
-	int rawimagelen=DeflateCompressCheck(((char *)iHeader)+headersize,srcsize,os);
-	// write the compression info into the header
-	SetCompressionInfo(KUidCompressionDeflate, rawimagelen, iUncompressedSize); // doesn't need to be 4K aligned
-	iHeader->iCompressedUnpagedStart = headersize; 
-	iHeader->iUnpagedCompressedSize = rawimagelen;
-	iHeader->iUnpagedUncompressedSize = srcsize;
-		
-	#ifdef __TOOLS2__
-	os.seekp(headerpos); 
-	#else
-	os.seekp(headerpos,ios::beg);
-	#endif
-	os.write(reinterpret_cast<char*>(iHeader), headersize);	// write header again with (compressed) size info
-	
-	if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
-		Print(ELog, "\tiSizeUsed:%d, iUncompressedSize:%d, headersize:%d, srcsize:%d, rawimagelen:%d \n",iSizeUsed, iUncompressedSize, headersize, srcsize, rawimagelen);
-	}
-
-TInt E32Rom::Compare(char *anImage, TInt aHeaderType)
-	{
-	if (aHeaderType < 0)
-		aHeaderType = 1;
-	ifstream file(anImage, ios::binary);
-	if (!file)
-		return Print(EError, "Cannot open Rom image '%s' for verification\n", anImage);
-	Print(ELog, "\nVerifying ROM against image in %s\n", anImage);
-	switch (aHeaderType)
-		{
-	case 0:
-		break;
-	case 1:
-	default:
-		Print(ELog, "Skipping repro header\n");
-		file.seekg(sizeof(TRomLoaderHeader));
-		break;
-	case 2:
-		Print(ELog, "Skipping coff header\n");
-		file.seekg(0x58);
-		break;
-		}
-	TInt length=ALIGN4K(iSizeUsed);
-	if (iObey->iSectionStart != 0)
-		{
-		length = iObey->iSectionStart-iObey->iRomLinearBase;
-		Print(ELog, "Verifying first section (%08x bytes)... ", length);
-		}
-
-	TRomHeader compareHeader;
-	file.read((char *)&compareHeader, sizeof(TRomHeader));
-	// Arrange different settings for TRomHeader and
-	// TRomSectionHeader in the obey file
-	// For now just copy across the things that'll change
-	compareHeader.iVersion=iHeader->iVersion;
-	compareHeader.iTime=iHeader->iTime;
-	compareHeader.iTimeHi=(TUint32)(iHeader->iTime >> 32);
-	compareHeader.iCheckSum=iHeader->iCheckSum;
-	compareHeader.iLanguage=iHeader->iLanguage;
-
-	if (memcmp(&compareHeader, iHeader, sizeof(TRomHeader))!=0)
-		return Print(EError, "Verify failed.\nRom headers are different\n");
-
-	// Now compare the rest of the image (or first section)
-
-	TUint *ptr=(TUint *)(iHeader+1);
-	TInt i;
-	for (i=sizeof(TRomHeader); i<length; i+=4)
-		{
-		TUint a;
-		file.read((char *)&a, sizeof(TUint));
-		if (file.eof())
-			return Print(EError, "Verify failed.\nDifferent Rom sizes\n");
-		if (a!=*ptr)
-			return Print(EError, "Verify failed.\nContents differ at Rom address %08x\n", i+iObey->iRomLinearBase);
-		ptr++;
-		}
-	file.close();
-	Print(EAlways, "Verify OK\n");
-	return KErrNone;
-	}
-
-
-char* E32Rom::AllocateRelocationTable(char* aAddr, TReloc*& aRelocTable)
-	{
-	if(iObey->SetArea().Count() > 1)
-		{
-		aRelocTable = reinterpret_cast<TReloc*>(aAddr);
-
-		// Allocate one entry per non default area + 1 sentinel
-		// (Count() returns number of non default areas + 1 (the
-		// default area))
-		TInt size = iObey->SetArea().Count() * sizeof(TReloc);	
-		aAddr += Align(size);
-		}
-	else
-		{
-		aRelocTable = 0;
-		}
-
-	return aAddr;
-	}
-
-
-void E32Rom::FillInRelocationTable(TReloc* aRelocTable)
-	{
-	TReloc* p = aRelocTable;
-	TInt wastedBytes = 0;
-
-	for (NonDefaultAreasIterator areaIt(iObey->SetArea());
-		 ! areaIt.IsDone();
-		 areaIt.GoToNext())
-		{
-		Area& currentArea = areaIt.Current();
-
-		if (currentArea.UsedSize() > 0)
-			{
-			p->iLength = currentArea.UsedSize();
-			p->iSrc = currentArea.SrcBaseAddr();
-			p->iDest = currentArea.DestBaseAddr();
-			++p;
-			}
-		else
-			{
-			wastedBytes += sizeof(TReloc);
-			}
-		}
-
-	if (aRelocTable != 0)
-		{
-		// Last entry acts as a sentinel
-		memset(p, 0, sizeof(*p));
-		}
-
-	if (wastedBytes > 0)
-		{
- 		Print(EWarning, "Some areas are declared but not used\n");
- 		Print(EWarning, "%d bytes wasted in relocation table\n", wastedBytes);
-		}
-	}
-
-
-/**
- Link together the kernel extensions.
-
- Must be called only after space has been allocated in the ROM image
- for the kernel extension.
- */
-
-void E32Rom::LinkKernelExtensions(TRomBuilderEntry* aExtArray[], TInt aExtCount)
-	{
-	/**
-	 * The kernel extensions should never be linked together as part of extension ROMs.
-	 */
-	if (!iExtensionRomHeader)
-		{
-		TLinAddr* pLastNextExtAddr = &(iHeader->iExtensionFile);
-
-		for (TInt i=0; i<aExtCount; ++i)
-			{
-			TRomBuilderEntry* curExt = aExtArray[i];
-			*pLastNextExtAddr = ActualToRomAddress(curExt->RomEntry());
-			pLastNextExtAddr = &(curExt->iRomImageHeader->iNextExtension);
-			}
-	
-		*pLastNextExtAddr = 0;
-		}
-	}
-
-void E32Rom::ProcessDllData()
-	{
-		DllDataEntry *entry = iObey->GetFirstDllDataEntry();
-		TRomBuilderEntry	*romEntry;
-		TLinAddr* aExportTbl;
-		void	*aLocation;
-		TUint	aDataAddr;
-		while(entry){
-			// A Dll data may be patched either via the ordinal number (as in ABIv2), or via
-			// the address of the data field (as in ABIv1).
-			romEntry = entry->iRomNode->iRomFile->iRbEntry;
-			if((TInt)entry->iOrdinal != -1) { 
-				
-				// const data symbol may belong in the Code section. Get the address of the data field via the 
-				// export table. If the address lies within the Code or data section limits, 
-				// get the corresponding location and update it.While considering the Data section limits don't 
-				// include the Bss section, as it doesn't exist as yet in the image.
-				if(entry->iOrdinal < 1 || entry->iOrdinal > (TUint32)romEntry->iOrigHdr->iExportDirCount)
-				{
-					Print(EWarning, "Invalid ordinal %d specified for DLL %s\n", entry->iOrdinal, romEntry->iName);
-					entry = entry->NextDllDataEntry();
-					continue;
-				}
-				aExportTbl = (TLinAddr*)((char*)romEntry->iOrigHdr + romEntry->iOrigHdr->iExportDirOffset);
-				aDataAddr = (TInt32)(aExportTbl[entry->iOrdinal - 1] + entry->iOffset);
-				
-				if( (aDataAddr >= romEntry->iOrigHdr->iCodeBase) && 
-					(aDataAddr <= (TUint)(romEntry->iOrigHdr->iCodeBase + \
-										romEntry->iOrigHdr->iCodeSize)) )
-				{
-					char *aCodeSeg = (char*)((char*)romEntry->iOrigHdr + romEntry->iOrigHdr->iCodeOffset);
-					aLocation = (void*)(aCodeSeg + (aDataAddr - romEntry->iOrigHdr->iCodeBase));
-					memcpy(aLocation, &(entry->iNewValue), entry->iSize);
-				}
-				else if( (aDataAddr >= romEntry->iOrigHdr->iDataBase) && 
-					(aDataAddr <= (TUint)(romEntry->iOrigHdr->iDataBase + \
-										romEntry->iOrigHdr->iDataSize )) )
-				{
-					char *aDataSeg = (char*)((char*)romEntry->iOrigHdr + romEntry->iOrigHdr->iDataOffset);
-					aLocation = (void*)(aDataSeg + (aDataAddr - romEntry->iOrigHdr->iDataBase));
-					memcpy(aLocation, &(entry->iNewValue), entry->iSize);
-				}
-				else
-				{
-					Print(EWarning, "Patchdata failed as address pointed by ordinal %d of DLL %s doesn't lie within Code or Data section limits\n", entry->iOrdinal, romEntry->iName);
-				}
-				
-			}
-			else if((TInt)entry->iDataAddress != -1) { 
-				// const data symbol may belong in the Code section. If the address lies within the Code
-				// or data section limits, get the corresponding location and update it.While considering 
-				// the Data section limits don't include the Bss section, as it doesn't exist as yet in the image.
-				aDataAddr = (TUint)(entry->iDataAddress + entry->iOffset);
-				if( (aDataAddr >= romEntry->iOrigHdr->iCodeBase) && 
-					(aDataAddr <= (TUint)(romEntry->iOrigHdr->iCodeBase + \
-											romEntry->iOrigHdr->iCodeSize )) )
-				{
-					char *aCodeSeg = (char*)((char*)romEntry->iOrigHdr + romEntry->iOrigHdr->iCodeOffset);
-					aLocation = (void*)(aCodeSeg + (aDataAddr - romEntry->iOrigHdr->iCodeBase));
-					memcpy(aLocation, &(entry->iNewValue), entry->iSize);
-				}
-				else if( (aDataAddr   >= romEntry->iOrigHdr->iDataBase) && 
-					(aDataAddr <= (TUint)(romEntry->iOrigHdr->iDataBase + \
-											romEntry->iOrigHdr->iDataSize )) )
-				{
-					char *aDataSeg = (char*)((char*)romEntry->iOrigHdr + romEntry->iOrigHdr->iDataOffset);
-					aLocation = (void*)(aDataSeg + (aDataAddr - romEntry->iOrigHdr->iDataBase));
-					memcpy(aLocation, &(entry->iNewValue), entry->iSize);
-				}
-				else
-				{
-					Print(EWarning, "Patchdata failed as address 0x%x specified for DLL %s doesn't lie within Code or Data section limits\n", entry->iOrdinal, romEntry->iName);
-				}
-			}
-			else {
-			}
-			entry = entry->NextDllDataEntry();
-		}
-	}
-
-TInt E32Rom::CheckUnpagedMemSize()
-	{
-
-	if (H.iVerbose && gPagedRom)
-		{
-		Print(EDiagnostic, "iMaxUnpagedMemSize 0x%08x (%d)\n", iObey->iMaxUnpagedMemSize, iObey->iMaxUnpagedMemSize);
-		}
-		
-	// Only check if the iMaxUnpagedMemSize is set
-	if (iObey->iMaxUnpagedMemSize <= 0) return KErrNone;
-	
-	// Only for paged rom
-	if (!gPagedRom) 
-		{
-		Print(EWarning, "The unpaged size overflow check is skipped.\n");
-		return KErrNone;
-		}
-	
-	if (iHeader->iPageableRomStart > 0)
-		{
-		if (iHeader->iPageableRomStart > iObey->iMaxUnpagedMemSize) 
-			{
-			Print(EError, "Unpaged memory size overflow: require 0x%08x (%d) bytes while the maximum size is 0x%08x (%d) bytes\n",
-				iHeader->iPageableRomStart, 
-				iHeader->iPageableRomStart, 
-				iObey->iMaxUnpagedMemSize, 
-				iObey->iMaxUnpagedMemSize);
-			
-			return KErrNoMemory;
-			}
-		}
-	else
-		{
-		Print(EWarning, "The size of unpaged memory is not available. The unpaged memory overflow checking is skipped.\n");
-		}
-		
-	return KErrNone;
-	}
-
-TRomNode* E32Rom::RootDirectory() 
-{ 
-	return iObey->iRootDirectory; 
-}
-
-TText* E32Rom::RomFileName()
-{ 
-	return iObey->iRomFileName; 
-}
-
-TUint32 E32Rom::RomBase()
-{
-	return iHeader->iRomBase;
-}
-
-TUint32 E32Rom::RomSize()
-{
-	return iHeader->iRomSize;
-}
-
-TVersion E32Rom::Version()
-{
-	return iHeader->iVersion;
-}
-
-TInt64 E32Rom::Time()
-{
-	return iHeader->iTime;
-}
-
-TUint32 E32Rom::CheckSum()
-{
-	return iHeader->iCheckSum;
-}
-
-TUint32 E32Rom::DataRunAddress()
-{
-	return iObey->iDataRunAddress;
-}
-
-TUint32 E32Rom::RomAlign()
-{
-	return iObey->iRomAlign;
-}
+/*
+* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#include <e32std.h>
+#include <e32std_private.h>
+#include <e32uid.h>
+#include "h_utl.h"
+#include <string.h>
+#include <stdlib.h>
+#include <iomanip> 
+
+#include "r_global.h"
+#include "r_obey.h"
+#include "r_rom.h"
+#include "r_dir.h"
+#include "patchdataprocessor.h"
+#include "memmap.h"
+#include "byte_pair.h"
+#include "symbolgenerator.h"
+
+const TInt KSpareExports=16;
+extern TInt gThreadNum;
+extern string gDepInfoFile;
+extern TBool gGenDepGraph;
+
+TUint32 DeflateCompressCheck(char *bytes,TInt size,ostream &os);
+void DeflateCompress(char *bytes,TInt size,ostream &os);
+void InflateUnCompress(unsigned char* source, int sourcesize,unsigned char* dest, int destsize);
+
+EntryQueue* LoadImageWorker::m_queue = NULL;
+TInt LoadImageWorker::m_errors = 0;
+TMemModel LoadImageWorker::m_memmodel;
+boost::mutex LoadImageWorker::m_mutex;
+LoadImageWorker::LoadImageWorker(EntryQueue* aQueue, TMemModel aMemModel)
+	{
+	m_queue = aQueue;
+	m_memmodel = aMemModel;
+	}
+void LoadImageWorker::operator()()
+	{
+	while(1)
+		{
+		m_mutex.lock();
+		if(m_queue->size() > 0)
+			{
+			TRomBuilderEntry * current = m_queue->front();
+			m_queue->pop();
+			m_mutex.unlock();
+			TInt err = current->OpenImageFile();
+			m_mutex.lock();
+			err = current->GetImageFileInfo(err);
+			m_mutex.unlock();
+			if(err)
+				{
+				m_mutex.lock();
+				++m_errors;
+				m_mutex.unlock();
+				continue;
+				}
+			if(current->iOverrideFlags&KOverrideAddress || current->iHdr->iFlags & KImageFixedAddressExe)
+				{
+				if(m_memmodel != E_MM_Multiple && m_memmodel != E_MM_Flexible &&  !current->IsDll())
+					current->iRomImageFlags |=KRomImageFlagFixedAddressExe;
+				}
+			if(gPagedRom)
+				{
+				if(current->iHdr->iFlags&KImageCodePaged)
+					{
+					current->iRomImageFlags&=~KRomImageFlagCodeUnpaged;
+					current->iRomImageFlags|=KRomImageFlagCodePaged;
+					}
+				if(current->iHdr->iFlags&KImageCodeUnpaged)
+					{
+					current->iRomImageFlags|=KRomImageFlagCodeUnpaged;
+					current->iRomImageFlags&=~KRomImageFlagCodePaged;
+					}
+				}
+			if(current->iHdr->iFlags&KImageDataPaged)
+				{
+				current->iRomImageFlags&=~KRomImageFlagDataUnpaged;
+				current->iRomImageFlags|=KRomImageFlagDataPaged;
+				}
+			if(current->iHdr->iFlags&KImageDataUnpaged)
+				{
+				current->iRomImageFlags|=KRomImageFlagDataUnpaged;
+				current->iRomImageFlags&=~KRomImageFlagDataPaged;
+				}
+			if(current->iHdr->iFlags&KImageDebuggable)
+				{
+				current->iRomImageFlags|=KRomImageDebuggable;
+				}
+				else
+				{
+				current->iRomImageFlags&=~KRomImageDebuggable;
+				}
+			}
+			else
+			{
+			m_mutex.unlock();
+			break;
+			}
+		}
+	}
+E32Rom* CompressPageWorker::m_rom = NULL;
+TInt CompressPageWorker::m_nextpage = 0;
+TInt CompressPageWorker::m_totalpages = 0;
+TInt CompressPageWorker::m_pagesize = 0;
+boost::mutex CompressPageWorker::m_mutex;
+TInt CompressPageWorker::m_error = 0;
+CompressPageWorker::CompressPageWorker(E32Rom* aRom, TInt aPageSize, TInt aTotalPages, TInt aNextPage)
+	{
+	m_rom = aRom;
+	m_pagesize = aPageSize;
+	m_totalpages = aTotalPages;
+	m_nextpage = aNextPage;
+	}
+void CompressPageWorker::operator()()
+	{
+	SRomPageInfo* pPageBase = (SRomPageInfo*)((TInt)m_rom->iHeader + m_rom->iHeader->iRomPageIndex);
+	CBytePair bpe;
+	while(1)
+		{
+		m_mutex.lock();
+		TInt currentPageIndex = m_nextpage++;
+		m_mutex.unlock();
+		if(currentPageIndex < m_totalpages)
+			{
+			TInt inOffset = m_pagesize * currentPageIndex;
+			TUint8 attrib = (TUint8)SRomPageInfo::EPageable;
+			SRomPageInfo info ={ (TUint32)inOffset, (TUint16)m_pagesize, (TUint8)SRomPageInfo::EBytePair, attrib };
+			TUint8* in = (TUint8*) m_rom->iHeader + inOffset;
+			TUint8* out = in;
+			TInt outSize = BytePairCompress(out, in, m_pagesize, &bpe);
+			if(outSize == KErrTooBig)
+				{
+				info.iCompressionType = SRomPageInfo::ENoCompression;
+				memcpy(out, in, m_pagesize);
+				outSize = m_pagesize;
+				}
+				if(outSize < 0 )
+					{
+					m_mutex.lock();
+					m_error = outSize;
+					m_mutex.unlock();
+					break;
+					}
+				info.iDataSize = (TUint16) outSize;
+				*(pPageBase + currentPageIndex) = info;
+				if((currentPageIndex & 255) == 255)
+					{
+					m_mutex.lock();
+					Print(EAlways, ".\n");
+					m_mutex.unlock();
+					}
+				}
+			else
+			{
+			break;
+			}
+		}
+	}
+	
+////////////////////////////////////////////////////////////////////////
+
+TAddressRange::TAddressRange() 
+	: iImagePtr(0), iImageAddr(0), iRunAddr(0), iSize(0) 
+	{
+	}
+
+void TAddressRange::Append(TAddressRange& aRange)
+	{ 
+	if(aRange.iSize) 
+		{ 
+		aRange.iImagePtr = iImagePtr;
+		aRange.iImageAddr = iImageAddr;
+		aRange.iRunAddr = iRunAddr;
+		Extend(aRange.iSize); 
+		} 
+	}
+
+void TAddressRange::Move(TInt aOffset) 
+	{ 
+	iImagePtr = static_cast<char*>(iImagePtr) + aOffset; 
+	iImageAddr += aOffset; 
+	iRunAddr += aOffset;
+	}
+
+void TAddressRange::Extend(TInt aOffset) 
+	{ 
+	Move(aOffset);
+	iSize += aOffset; 
+	}
+
+////////////////////////////////////////////////////////////////////////
+
+inline TUint32 AlignData(TUint32 anAddr)
+	{
+	return ((anAddr+0x0f)&~0x0f);
+	}
+
+TUint32 E32Rom::AlignToPage(TUint32 anAddr)
+	{
+	TUint a=(TUint)iObey->iPageSize-1;
+	return ((anAddr+a)&~a);
+	}
+
+/*
+Allocate virtual memory for static data in rom.
+@param aAddr Base address of last allocated memory.
+@param aSize Size of memory to allocate.
+@return Address allocated. This is below aAddr.
+*/
+TUint32 E32Rom::AllocVirtual(TUint32 aAddr,TUint aSize)
+	{
+	TInt align = iObey->iVirtualAllocSize;
+	if(align<0)
+		{
+		align = -align; // get correct sign
+		// -ve align means also align to next power-of-two >= aSize...
+		while(aSize>(TUint)align)
+			align <<=1;
+		}
+
+	TUint mask = (TUint)align-1;
+	aSize = (aSize+mask)&~mask; // round up
+	aAddr &= ~mask; // round down
+	return aAddr-aSize;
+	}
+
+TUint32 E32Rom::AlignToChunk(TUint32 anAddr)
+	{
+	TUint a=(TUint)iObey->iChunkSize-1;
+	return ((anAddr+a)&~a);
+	}
+
+COrderedFileList::COrderedFileList(TInt aMaxFiles)
+	: iCount(0), iMaxFiles(aMaxFiles), iOrderedFiles(NULL)
+	{}
+
+COrderedFileList::~COrderedFileList()
+	{
+	iCount=0;
+	if(iOrderedFiles)
+		delete[] iOrderedFiles;
+	}
+
+COrderedFileList* COrderedFileList::New(TInt aMaxFiles)
+	{
+	COrderedFileList *pL=new COrderedFileList(aMaxFiles);
+	pL->iOrderedFiles=new TRomBuilderEntry*[aMaxFiles];
+	return pL;
+	}
+
+void COrderedFileList::Add(TRomBuilderEntry* anEntry)
+	{
+	// note: this routine assumes that the set of kernel-mode files
+	// (primary/extension/device) required by a given variant is linearly ordered by <=
+	// e.g. can't have three variants {A,B,V1} {A,B,C,V2} {A,C,V3} because B and C
+	// are unordered with respect to <=, since neither of
+	// {n | Vn requires B} and {n | Vn requires C} is a subset of the other.
+	// In a case like this, ROMBUILD may fail to resolve the addresses of some global data
+	THardwareVariant& v=anEntry->iHardwareVariant;
+	TInt i=0;
+	while(i<iCount && v<=iOrderedFiles[i]->iHardwareVariant) i++;
+	TInt j=iCount;
+	while(j>i)
+		{
+		iOrderedFiles[j]=iOrderedFiles[j-1];
+		j--;
+		}
+	iOrderedFiles[i]=anEntry;
+	iCount++;
+	}
+
+void GetFileNameAndUid(char *aDllName, TUid &aDllUid, char *aExportName)
+	{	
+	strcpy(aDllName, aExportName);
+	aDllUid=KNullUid;
+	TInt start;
+	for (start=0; start<(TInt)strlen(aExportName) && aExportName[start]!='['; start++)
+		;
+	if (start==(TInt)strlen(aExportName))
+		start=KErrNotFound;
+	TInt end=strlen(aExportName)-1;
+	while (end>=0)
+		{
+		if (aExportName[end]==']')
+			break;
+		--end;
+		}
+	if (end<0)
+		end=KErrNotFound;
+
+	if ((start!=KErrNotFound) && (end!=KErrNotFound) && (end>start))
+		{
+		// Importing from DLL with Uid
+		char uidStr[0x100];
+		strcpy(uidStr, "0x");
+		strncat(uidStr, aExportName+start+1, end-start-1); 
+
+				 
+		if (IsValidNumber(uidStr)){
+			TUint32 u = 0;
+			Val(u,uidStr);
+			aDllUid=TUid::Uid(u);
+			char *dot=aExportName+strlen(aExportName)-1;
+			while (dot>=aExportName)
+				{
+				if (*dot=='.')
+					break;
+				dot--;
+				}
+			if (dot<aExportName) // no dot
+				aDllName[start]=0;
+			else
+				{
+				aDllName[start]=0;
+				strcat(aDllName, dot);
+				}
+			}
+		}
+	}
+
+E32Rom::E32Rom(CObeyFile *aObey) {
+
+	iSize=sizeof(TRomLoaderHeader)+aObey->iRomSize;
+	iObey=aObey;
+	iPeFiles=NULL;
+	iSymGen = NULL ;
+	if(gLowMem)
+	{
+		iImageMap = new Memmap();
+
+		if(iImageMap == NULL)
+		{
+			iSize = 0;
+			Print(EError, "Out of memory.\n");
+		}
+		else
+		{
+			iImageMap->SetMaxMapSize(iSize);
+			if(iImageMap->CreateMemoryMap(0, 0xff) == EFalse)
+			{
+				iSize = 0;
+				Print(EError, "Failed to create image map object");
+
+				iImageMap->CloseMemoryMap(ETrue);
+				delete iImageMap;
+				iImageMap = NULL;
+			}
+			else
+			{
+				iData = iImageMap->GetMemoryMapPointer();
+			}
+		}
+	}
+	else
+	{
+		iData=new char [iSize];
+		if (iData==NULL)
+			{
+			iSize=0;
+			Print(EError, "Out of memory.\n");
+			}
+		HMem::Set(iData, 0xff, iSize);
+	}
+	iHeader=(TRomHeader *)(iData+sizeof(TRomLoaderHeader));
+	iExtensionRomHeader=NULL;
+	iLoaderHeader=(TRomLoaderHeader *)iData;
+	iSectionPtr=(char *)iHeader+aObey->iSectionStart-aObey->iRomLinearBase+sizeof(TRomSectionHeader);
+	TheRomHeader=(ImpTRomHeader *)iHeader;
+	TheRomMem=(TUint32)iHeader;
+	iNextDataChunkBase=aObey->iKernDataRunAddress;
+	iTotalSvDataSize=0;
+	iNextDllDataAddr=aObey->iDllDataTop;
+	iPrevPrimaryAddress=NULL;
+	iPrevVariantAddress=NULL;
+	iVariantFileLists=NULL;
+	iImportsFixedUp=0;
+	iBranchesFixedUp=0;
+	iVtableEntriesFixedUp=0;
+	iOverhead=0;
+	}
+
+E32Rom::~E32Rom() {
+	if(iSymGen){		
+		delete iSymGen;
+		iSymGen = NULL ;
+	}
+	if(gLowMem)
+	{
+		iImageMap->CloseMemoryMap(ETrue);
+		delete iImageMap;
+	}
+	else
+		delete iData;
+	delete [] iPeFiles;
+	if (iVariantFileLists)
+		{
+		TInt i;
+		for (i=0; i<iObey->iNumberOfVariants; i++)
+			delete iVariantFileLists[i];
+		delete [] iVariantFileLists;
+		}
+	}
+
+TInt E32Rom::Align(TInt aVal)
+//
+// Align to romalign
+//
+	{
+ 	
+	return ((aVal+iObey->iRomAlign-1)/iObey->iRomAlign)*iObey->iRomAlign;
+	}
+
+TInt E32Rom::LoadContents(char*& anAddr, TRomHeader* aHeader)
+	{
+	// Load all the PE/E32Image files
+	TInt nfiles=iObey->iNumberOfPeFiles;
+	iPeFiles=new TRomBuilderEntry* [nfiles];
+	if (!iPeFiles)
+		return Print(EError, "Out of memory.\n");
+
+	TInt r=TranslateFiles();
+	if (r!=KErrNone)
+		return r;
+	
+	ProcessDllData();
+
+	EnumerateVariants();
+
+	r=BuildDependenceGraph();
+	if (r!=KErrNone)
+		return r;
+
+	// Update the ROM image headers with SMP information.
+	SetSmpFlags();
+
+	r=ProcessDependencies();
+	if (r!=KErrNone)
+		return r;
+
+	char* addr = anAddr;
+	TRomExceptionSearchTable* exceptionSearchTable = 0;
+
+	if(gPagedRom)
+		{ 
+		gDepInfoFile = iObey->iRomFileName; 
+		iObey->SetArea().DefaultArea()->SortFilesForPagedRom();
+		// exception search table needs to go at start of ROM to make it not demand paged...
+		addr = ReserveRomExceptionSearchTable(addr,exceptionSearchTable);
+		}
+	else if(gGenDepGraph)
+		{
+			Print(EWarning, "Not dependence information in an unpaged ROM.");
+		}
+
+	addr=WriteDirectory(addr, aHeader);
+	// Aligned
+
+	TRACE(TSCRATCH,Print(EAlways,"Directory written\n"));
+
+	// Stick all the files in ROM
+
+	TReloc* relocationTable;
+	addr = AllocateRelocationTable(addr, relocationTable);
+	aHeader->iRelocInfo = relocationTable ? ActualToRomAddress(relocationTable) : 0;
+	// Aligned
+
+	TRACE(TSCRATCH,Print(EAlways,"Done AllocateRelocationTable\n"));
+
+	CalculateDataAddresses();
+	addr = LayoutRom(addr);
+
+	TRACE(TSCRATCH,Print(EAlways,"Done LayoutRom\n"));
+
+	FillInRelocationTable(relocationTable);
+
+	TRACE(TSCRATCH,Print(EAlways,"Done FillInRelocationTable\n"));
+
+	if(!exceptionSearchTable)
+		addr = ReserveRomExceptionSearchTable(addr,exceptionSearchTable);
+	ConstructRomExceptionSearchTable(exceptionSearchTable);
+
+	TRACE(TSCRATCH,Print(EAlways,"Done ConstructRomExceptionSearchTable\n"));
+
+	LinkKernelExtensions(iObey->iExtensions, iObey->iNumberOfExtensions);
+
+	TRACE(TSCRATCH,Print(EAlways,"Done LinkKernelExtensions\n"));
+
+	r=ResolveDllRefTables();
+	if (r!=KErrNone)
+		return r;
+	r=ResolveImports();
+	if (r!=KErrNone)
+		return r;
+	if (iObey->iCollapseMode>ECollapseNone)
+		{
+		r=CollapseImportThunks();
+		if (r!=KErrNone)
+			return r;
+		if (iObey->iCollapseMode>ECollapseImportThunksOnly)
+			{
+			r=CollapseBranches();
+			if (r!=KErrNone)
+				return r;
+			}
+		Print(ELog,"%d imports, %d branches, %d vtable entries fixed up\n",
+			  iImportsFixedUp,iBranchesFixedUp,iVtableEntriesFixedUp);
+		}
+
+	iSizeUsed=(TInt)addr-(TInt)iHeader;
+	Print(ELog, "\n%08x of %08x bytes used.\n", iSizeUsed, iSize-sizeof(TRomLoaderHeader));
+
+	// round the rom size in the header to a multiple of 1 Megabyte
+	TInt rounded = ((iSizeUsed+0xfffff)&0xfff00000);
+	if (rounded < iObey->iRomSize)
+		iObey->iRomSize = rounded;
+	iUncompressedSize = iSizeUsed;
+
+	anAddr = addr;
+
+	return KErrNone;
+	}
+
+
+void E32Rom::CreatePageIndex(char*& aAddr)
+	{
+	iHeader->iRomPageIndex = 0;
+	if(gPagedRom==0 || gEnableCompress==0)
+		return;
+
+	// Insert space for Rom Page Info table...
+	iHeader->iRomPageIndex = (TInt)aAddr-(TInt)iHeader;
+	TInt pageSize = iObey->iPageSize;
+	TInt numPages = iSize/pageSize+1;
+	TInt pageInfoSize = numPages*sizeof(SRomPageInfo);
+	
+	gPageIndexTableSize = pageInfoSize;		// For accumulate uncompressed un-paged size added Page Index Table
+		
+	Print(ELog, "Inserting %d bytes for RomPageInfo at ROM offset 0x%08x\n", pageInfoSize, iHeader->iRomPageIndex);
+	memset(aAddr,0,pageInfoSize);
+	iOverhead += pageInfoSize;
+	aAddr += pageInfoSize;
+	}
+
+TInt E32Rom::SetupPages()
+	{
+	iHeader->iPageableRomStart = 0;
+	iHeader->iPageableRomSize = 0;
+	iHeader->iDemandPagingConfig = gDemandPagingConfig;
+
+	if(!gPagedRom)
+		return KErrNone;
+
+	// Initialise the Rom Page Info for each page which indicates it is uncompressed...
+	TInt pageSize = iObey->iPageSize;
+
+	TInt pagedStartOffset = 0x7fffffff;
+	TRomBuilderEntry* e = iObey->SetArea().DefaultArea()->iFirstPagedCode;
+	if(e)
+		{
+		// we have paged code...
+		pagedStartOffset = e->RomEntry()->iAddressLin-iObey->iRomLinearBase;
+		pagedStartOffset = (pagedStartOffset+pageSize-1)&~(pageSize-1); // round up to next page;
+		iHeader->iPageableRomStart = pagedStartOffset;
+		TInt pageableSize = iSizeUsed-pagedStartOffset;
+		if(pageableSize>0)
+			iHeader->iPageableRomSize = pageableSize;
+		}
+	
+	return KErrNone;
+	}
+
+TInt E32Rom::CompressPages()
+	{
+	
+	if(!gPagedRom || !gEnableCompress)
+		return KErrNone;
+
+	// Initialise the Rom Page Info for each page which indicates it is uncompressed...
+	TInt pageSize = iObey->iPageSize;
+	TInt numPages = (iSizeUsed+pageSize-1)/pageSize;
+
+	TInt pagedStartOffset = iHeader->iPageableRomStart;
+
+	Print(EAlways, "\nCompressing pages...\n");
+	TInt inOffset = 0;
+    SRomPageInfo* pi = (SRomPageInfo*)((TInt)iHeader+iHeader->iRomPageIndex);
+	TInt currentIndex = 0;
+	while(inOffset < pagedStartOffset)
+		{
+		
+		TUint8 attrib = (TUint8)0;
+		SRomPageInfo info = {(TUint32)inOffset,(TUint16)pageSize,(TUint8)SRomPageInfo::EBytePair,(TUint8)attrib};
+		info.iDataSize = (TUint16) pageSize;
+		*pi++ = info;
+		inOffset += pageSize;
+		if((currentIndex & 255) == 255)
+			Print(EAlways, ".\n");
+		currentIndex++;
+		}
+	CompressPageWorker compressworker(this, pageSize, numPages, currentIndex);
+
+	boost::thread_group threads;
+	for(int i = 0; i < gThreadNum; i++)
+		{
+		threads.create_thread(compressworker);
+		}
+	threads.join_all();
+	if(compressworker.m_error < 0)
+	       return compressworker.m_error;
+	for(;currentIndex < numPages - 1; currentIndex++)
+		{
+		pi++;
+		SRomPageInfo* prev = pi - 1;
+		TUint8* dest = (TUint8*) iHeader + prev->iDataStart + prev->iDataSize;
+		TUint8* src = (TUint8*) iHeader + pi->iDataStart;
+		memcpy(dest, src, pi->iDataSize);
+		pi->iDataStart = prev->iDataStart + prev->iDataSize;
+		}
+	TInt relSize = pi->iDataStart + pi->iDataSize;
+
+	memset((TUint8*)iHeader + relSize, 0xff, iSizeUsed - relSize);
+	TInt compression = (iSizeUsed >= 1000) ? (relSize*10)/(iSizeUsed/1000) : (relSize*10000)/iSizeUsed;
+	Print(EAlways, "%d.%02d%%\n", compression/100, compression%100);
+	iSizeUsed = relSize;
+	return KErrNone;
+	}
+
+TInt E32Rom::CompressPage(SRomPageInfo& aPageInfo, TInt aOutOffset, CBytePair * aBPE)
+	{
+	TUint8* in = (TUint8*)iHeader+aPageInfo.iDataStart;
+	TInt inSize = aPageInfo.iDataSize;
+	TUint8* out = (TUint8*)iHeader+aOutOffset;
+	switch(aPageInfo.iCompressionType)
+		{
+	case SRomPageInfo::ENoCompression:
+		memcpy(out,in,inSize);
+		return inSize;
+
+	case SRomPageInfo::EBytePair:
+		{
+		TInt r = BytePairCompress(out, in, inSize, aBPE);
+		if(r!=KErrTooBig)
+			return r;
+		// data can't be compressed...
+		aPageInfo.iCompressionType = SRomPageInfo::ENoCompression;
+		memcpy(out,in,inSize);
+		return inSize;
+		}
+
+	default:
+		Print(EError, "Unsupported page compression type (%d)\n", aPageInfo.iCompressionType);
+		return KErrNotSupported;
+		}
+	}
+
+
+// Avoid "warning" about constant expression
+static void checksize(const char* aTypeName, int aSize, int aCorrectSize)
+	{
+	if (aSize != aCorrectSize)
+		Print(EError, "sizeof(%s) = %d, should be %d\n", aTypeName, aSize, aCorrectSize);
+	}
+
+TInt E32Rom::CreateExtension(MRomImage* aKernelRom) 
+	{
+
+	// sanity check
+	checksize("TExtensionRomHeader", sizeof(TExtensionRomHeader), 128);
+
+	char *addr=(char *)iHeader;
+	iExtensionRomHeader=(TExtensionRomHeader*)addr;
+	addr += sizeof(TExtensionRomHeader);
+	// Aligned
+
+	TRomHeader dummy;
+	TInt r=LoadContents(addr, &dummy);
+	if (r!=KErrNone)
+		{
+		Print(EError, "LoadContents failed - return code %d\n", r);
+		if(iSymGen)
+			iSymGen->WaitThreads();
+		return r;
+		}
+	iExtensionRomHeader->iRomRootDirectoryList = dummy.iRomRootDirectoryList;
+
+	iLoaderHeader->SetUp(iObey);
+	FinaliseExtensionHeader(aKernelRom);
+	DisplayExtensionHeader();
+	if(iSymGen)
+		iSymGen->WaitThreads();
+	return KErrNone;
+	}
+	
+TInt E32Rom::Create()
+	{
+
+	TVariantList::Setup(iObey);
+	char *addr=(char *)iHeader;
+	// Aligned
+
+	// Put the bootstrap in rom - it contains a hole at offset 0x80 where the 
+	// TRomHeader information will be placed later
+
+	gBootstrapSize = HFile::Read(iObey->iBootFileName, iHeader);
+	if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
+		Print(ELog, "bootstrapSize: 0x%08x, (%d)\n", gBootstrapSize, gBootstrapSize);	
+	
+	if (gBootstrapSize==0)
+		return Print(EError, "Cannot open the bootstrap file '%s'.\n", iObey->iBootFileName);
+	gBootstrapSize=Align(gBootstrapSize);
+	addr+=gBootstrapSize;
+	iOverhead=gBootstrapSize;
+	// Aligned
+
+	CreatePageIndex(addr);
+
+	TInt r=LoadContents(addr, iHeader);
+	if (r!=KErrNone)
+		{
+		Print(EError, "LoadContents failed - return code %d\n", r);
+		if(iSymGen)
+			iSymGen->WaitThreads();
+		return r;
+		}
+
+	r = SetupPages(); // initialize ROM paging info...
+	if(r!=KErrNone)
+		{
+		Print(EError, "Setup pages information failed - return code %d\n", r);
+		if(iSymGen)
+			iSymGen->WaitThreads();
+		return r;
+		}
+	
+	r = CheckUnpagedMemSize(); // check for unpaged memory overflow
+	if(r!=KErrNone)
+	{
+		if(iSymGen)
+			iSymGen->WaitThreads();
+		return r;
+	}
+	
+	r = CompressPages(); // setup ROM paging info...
+	if(r!=KErrNone)
+		{
+		Print(EError, "CompressPages failed - return code %d\n", r);
+		if(iSymGen)
+			iSymGen->WaitThreads();
+		return r;
+		}
+
+	iLoaderHeader->SetUp(iObey);
+	ImpTRomHeader* header = (ImpTRomHeader *)iHeader;
+	header->SetUp(iObey);
+	header->iTotalSvDataSize=iTotalSvDataSize;
+	if (iObey->iMemModel==E_MM_Direct)
+		{
+		header->iUserDataAddress=iObey->iDataRunAddress;
+		header->iTotalUserDataSize=iNextDataChunkBase-iObey->iDataRunAddress;
+		}
+	else
+		{
+		header->iUserDataAddress=iObey->iDllDataTop;
+		header->iTotalUserDataSize=iObey->iDllDataTop-iNextDllDataAddr;
+		}
+	if (header->iRomSectionHeader)
+		FinaliseSectionHeader();	// sorts out the second section checksum
+
+	header->CheckSum(iObey->iCheckSum);	// finally, sort out the overall checksum
+
+	header->Display();
+
+	TUint testCheckSum = HMem::CheckSum((TUint *)iHeader, iHeader->iRomSize);
+	Print(ELog, "Rom 32bit words sum to   %08x\n", testCheckSum);
+	if (testCheckSum != iObey->iCheckSum){
+		if(iSymGen)
+			iSymGen->WaitThreads();
+		return Print(EError, "Rom checksum is incorrect: %08x should be %08x\n",
+					testCheckSum, iObey->iCheckSum);
+	}
+
+	// 8bit checksum = sum of bytes
+	// odd/even checksum = checksum of the odd and even halfwords of the image
+
+	Print(ELog, "Rom 8bit checksum        %08x\n", HMem::CheckSum8((TUint8 *)iHeader, iHeader->iRomSize));
+	Print(ELog, "Rom 8bit odd checksum    %08x\n", HMem::CheckSumOdd8((TUint8 *)iHeader, iHeader->iRomSize));
+	Print(ELog, "Rom 8bit even checksum   %08x\n", HMem::CheckSumEven8((TUint8 *)iHeader, iHeader->iRomSize));
+
+	if (iHeader->iPrimaryFile)
+		{
+		if (iObey->iKernelModel==ESingleKernel)
+			{
+			Print(ELog,"\nPrimary details (Single Kernel):\n");
+			TRomEntry *r = (TRomEntry *)(iHeader->iPrimaryFile-iObey->iRomLinearBase+(char *)iHeader);
+			TRomImageHeader *hdr = (TRomImageHeader *)(r->iAddressLin-iObey->iRomLinearBase+(char *)iHeader);
+			Display(hdr);
+			Print(ELog,"\n");
+			}
+		else if (iObey->iKernelModel==EMultipleKernels)
+			{
+			Print(ELog,"\nPrimary details (Multiple Kernels):\n");
+			TRomEntry *r = (TRomEntry *)(iHeader->iPrimaryFile-iObey->iRomLinearBase+(char *)iHeader);
+			TInt n=1;
+			FOREVER
+					{
+					Print(ELog,"\nKernel %d:\n",n);
+					TRomImageHeader *hdr = (TRomImageHeader *)(r->iAddressLin-iObey->iRomLinearBase+(char *)iHeader);
+					Display(hdr);
+					Print(ELog,"\n");
+					if (!hdr->iNextExtension)
+						break;
+					r=(TRomEntry*)(hdr->iNextExtension-iObey->iRomLinearBase+(char*)iHeader);
+					n++;
+					}
+			}
+		}
+	if(iSymGen)
+			iSymGen->WaitThreads();
+	return KErrNone;
+	}
+
+char *E32Rom::WriteDirectory(char *aAddr, TRomHeader* aHeader)
+//
+// Write the directory structure where appropriate
+//
+	{
+
+	TLinAddr dirptr=ActualToRomAddress(aAddr);
+	if (iObey->iSectionPosition==-1)
+		{
+		// Just the one rom.  Put the directory structure at aAddr
+		iDirectorySize=WriteHeadersToRom(aAddr);
+		aAddr+=Align(iDirectorySize);
+		}
+	else
+		{
+		// Put the directory structure in the second ROM, after the SectionHeader
+		// and the second section information for first section files
+		TInt size=0;
+		TInt i;
+		for (i=0; i<iObey->iNumberOfPeFiles; i++)
+			{
+			TRomBuilderEntry *file=iPeFiles[i];
+			if (file->iRomSectionNumber!=0)
+				break;
+			TInt size1, size2;
+			file->SizeInSections(size1,size2);
+			size+=size2;
+			}
+		dirptr=ActualToRomAddress(iSectionPtr)+size;
+		iDirectorySize=WriteHeadersToRom(RomToActualAddress(dirptr));
+		}
+	aHeader->iRomRootDirectoryList=dirptr;
+	return aAddr;
+	}
+
+void E32Rom::Display(TRomImageHeader *aHdr)
+//
+// Print info on a file
+//
+	{
+	TRACE(TAREA, Print(ELog, "+Display header %08x\n", aHdr));
+	Print(ELog, "Uids:                    %08x %08x %08x %08x\n", aHdr->iUid1, aHdr->iUid2, aHdr->iUid3, aHdr->iUidChecksum);
+	Print(ELog, "Entry point:             %08x\n", aHdr->iEntryPoint);
+	Print(ELog, "Code start addr:         %08x\n", aHdr->iCodeAddress);
+	Print(ELog, "Data start addr:         %08x\n", aHdr->iDataAddress);
+	Print(ELog, "DataBssLinearBase:       %08x\n", aHdr->iDataBssLinearBase);
+	Print(ELog, "Text size:               %08x\n", aHdr->iTextSize);
+	Print(ELog, "Code size:               %08x\n", aHdr->iCodeSize);
+	Print(ELog, "Data size:               %08x\n", aHdr->iDataSize);
+	Print(ELog, "BssSize:                 %08x\n", aHdr->iBssSize);
+	Print(ELog, "Total data size:         %08x\n", aHdr->iTotalDataSize);
+	Print(ELog, "Heap min:                %08x\n", aHdr->iHeapSizeMin);
+	Print(ELog, "Heap max:                %08x\n", aHdr->iHeapSizeMax);
+	Print(ELog, "Stack size:              %08x\n", aHdr->iStackSize);
+	Print(ELog, "Dll ref table:           %08x\n", aHdr->iDllRefTable);
+	Print(ELog, "Export directory:        %08x\n", aHdr->iExportDir);
+	Print(ELog, "Export dir count:        %08x\n", aHdr->iExportDirCount);
+	Print(ELog, "Hardware variant:        %08x\n", aHdr->iHardwareVariant);
+	Print(ELog, "Flags:                   %08x\n", aHdr->iFlags);
+	Print(ELog, "Secure ID:               %08x\n", aHdr->iS.iSecureId);
+	Print(ELog, "Vendor ID:               %08x\n", aHdr->iS.iVendorId);
+	Print(ELog, "Capability:              %08x %08x\n", aHdr->iS.iCaps[1], aHdr->iS.iCaps[0]);
+	Print(ELog, "Tools Version:           %d.%02d(%d)\n", aHdr->iToolsVersion.iMajor, aHdr->iToolsVersion.iMinor, aHdr->iToolsVersion.iBuild);
+	Print(ELog, "Module Version:          %d.%d\n", aHdr->iModuleVersion>>16, aHdr->iModuleVersion&0x0000ffffu);
+	Print(ELog, "Exception Descriptor:    %08x\n", aHdr->iExceptionDescriptor);
+	Print(ELog, "Priority:                %d\n", aHdr->iPriority);
+	}
+
+void E32Rom::DisplaySizes(TPrintType aWhere)
+	{
+
+	Print(aWhere, "Summary of file sizes in rom:\n");
+	Print(aWhere, "Overhead (bootstrap+gaps+sectioning)\t%d\n", iOverhead);
+	Print(aWhere, "Overhead (directory size)\t%d\n", iDirectorySize);
+	TRomBuilderEntry *file=iObey->FirstFile();
+	while (file)
+		{
+		file->DisplaySize(aWhere);
+		file=iObey->NextFile();
+		}
+	Print(aWhere, "\nTotal used\t%d\n", iSizeUsed);
+	Print(aWhere, "Free\t%d\n", iObey->iRomSize-iSizeUsed);
+
+	if (iObey->SetArea().Count() > 1)
+		{
+		Print(aWhere, "\nArea summary:\n");
+		for (NonDefaultAreasIterator it(iObey->SetArea());
+			 ! it.IsDone();
+			 it.GoToNext())
+			{
+			const Area& a = it.Current();
+			Print(aWhere, "%s\t used: %d bytes / free: %d bytes\n",
+				  a.Name(), a.UsedSize(), a.MaxSize()-a.UsedSize());
+			}
+		}
+	}
+
+TInt E32Rom::RequiredSize()
+//
+// Get the (approximate) required size of the Rom
+//
+	{
+
+	TInt sum=0;
+	TRomBuilderEntry *current=iObey->FirstFile();
+	while (current)
+		{
+		if (current->iResource || current->HCRDataFile())
+			sum+=Align(HFile::GetLength(current->iFileName));
+		else
+ 			sum+=Align(current->SizeInRom());
+		current=iObey->NextFile();
+		}
+	return sum+iOverhead+Align(iDirectorySize);
+	}
+
+TInt E32Rom::TranslateFiles()
+//
+// Load and translate all PE/E32 image files
+//
+	{
+
+	TInt i=0;
+	TInt total_errors = 0;
+	TRomBuilderEntry* current = 0;
+	EntryQueue imagesQueue;
+	for (current = iObey->FirstFile(); current; current = iObey->NextFile() )
+		{	
+		if ((!current->iResource) && (!current->HCRDataFile()))
+			{
+			iPeFiles[i++]=current;
+			imagesQueue.push(current);
+			}
+		}
+	LoadImageWorker loadworker(&imagesQueue, iObey->iMemModel);
+	boost::thread_group threads;
+	for(int i = 0; i < gThreadNum; i++)
+		{
+		threads.create_thread(loadworker);
+		}
+	threads.join_all();
+
+	total_errors = loadworker.m_errors;
+	if (total_errors)
+		return KErrGeneral;
+	for (current = iObey->FirstFile(); current; current = iObey->NextFile() )
+		{
+		if ((!current->iResource) && (!current->HCRDataFile()))
+			{
+			TInt err = CheckForVersionConflicts(current);
+			total_errors += err;
+			}
+		}
+	return total_errors ? KErrGeneral : KErrNone;
+	}
+
+const char FileTypeFile[]=		"File     ";
+const char FileTypePrimary[]=	"Primary  ";
+const char FileTypeVariant[]=	"Variant  ";
+const char FileTypeExtension[]="Extension";
+const char FileTypeDevice[]=	"Device   ";
+
+void E32Rom::EnumerateVariants()
+	{
+	TInt vIndex;
+	TInt nFiles=iObey->iNumberOfExtensions+iObey->iNumberOfDevices+3;
+	iVariantFileLists=new COrderedFileList*[iObey->iNumberOfVariants];
+	for (vIndex=0; vIndex<iObey->iNumberOfVariants; vIndex++)
+		iVariantFileLists[vIndex]=COrderedFileList::New(nFiles);
+	for (vIndex=0; vIndex<iObey->iNumberOfVariants; vIndex++)
+		{
+		TRomBuilderEntry *variant=iObey->iVariants[vIndex];
+		THardwareVariant& v=variant->iHardwareVariant;
+		TInt i;
+		for (i=0; i<iObey->iNumberOfPrimaries; i++)
+			{
+			TRomBuilderEntry *primary=iObey->iPrimaries[i];
+			if (v<=primary->iHardwareVariant)
+				{
+				iVariantFileLists[vIndex]->Add(primary);
+				break;
+				}
+			}
+		iVariantFileLists[vIndex]->Add(variant);
+		for (i=0; i<iObey->iNumberOfExtensions; i++)
+			{
+			TRomBuilderEntry *ext=iObey->iExtensions[i];
+			if (v<=ext->iHardwareVariant)
+				{
+				iVariantFileLists[vIndex]->Add(ext);
+				}
+			}
+		for (i=0; i<iObey->iNumberOfDevices; i++)
+			{
+			TRomBuilderEntry *dev=iObey->iDevices[i];
+			if (v<=dev->iHardwareVariant)
+				{
+				iVariantFileLists[vIndex]->Add(dev);
+				}
+			}
+		}
+	TUint totalDataBss=0;
+	for (vIndex=0; vIndex<iObey->iNumberOfVariants; vIndex++)
+		{
+		TRomBuilderEntry *variant=iObey->iVariants[vIndex];
+		THardwareVariant& v=variant->iHardwareVariant;
+		COrderedFileList& files=*iVariantFileLists[vIndex];
+		TInt count=files.Count();
+		Print(ELog,"\nVariant %08x, %d Files:\n",v.ReturnVariant(),count); 
+		TInt i;
+		TUint dataOffset=0;
+		for (i=0; i<count; i++)
+			{
+			TRomBuilderEntry *pF=files[i];
+			TUint gap=0;
+			if (pF->iDataAlignment>0)
+				{
+				gap=(pF->iDataAlignment-dataOffset)%(pF->iDataAlignment);
+				dataOffset+=gap;
+				}
+			E32ImageHeader *pH=pF->iHdr;
+			if (pF->iDataBssOffset!=0xffffffff && pF->iDataBssOffset!=dataOffset)
+				Print(EError,"Conflicting DataBss addresses\n");
+			pF->iDataBssOffset=dataOffset;
+			TInt dataSize=AlignData(pH->iDataSize+pH->iBssSize);
+			const char* pT=FileTypeFile;
+			if (pF->Primary())
+				pT=FileTypePrimary;
+			if (pF->Variant())
+				pT=FileTypeVariant;
+			if (pF->Extension())
+				pT=FileTypeExtension;
+			if (pF->Device())
+				pT=FileTypeDevice;
+			Print(ELog,"%s %12s[%08x] DataSize=%6x DataOffset=%6x",pT,pF->iName,pF->iHardwareVariant.ReturnVariant(),dataSize,dataOffset);
+			if (gap)
+				Print(ELog, " (gap %x for %x alignment)\n", gap, pF->iDataAlignment);
+			Print(ELog, "\n");
+			dataOffset+=dataSize;
+			}
+		if (dataOffset>totalDataBss)
+			totalDataBss=dataOffset;
+		}
+	Print(ELog,"\nTotal SvData size=%6x\n",totalDataBss);
+	iTotalSvDataSize=totalDataBss;
+	}
+
+TInt E32Rom::LoadDataToRom(TRomBuilderEntry *aFile, TAddressRange& aAddress, CBytePair* aBPE)
+//
+// Load a data file to rom
+//
+	{
+	const char* tn = "resource";
+	if (aFile->iNonXIP)
+		tn = (aFile->iCompression) ? "compressed executable" : "uncompressed executable";
+	Print(ELog,"Reading %s %s to rom linear address %08x\n", tn, aFile->iFileName, aAddress.iImageAddr);
+
+	TUint32 size=HFile::GetLength(aFile->iFileName);
+	if (size==0)
+		{
+		Print(EWarning, "File %s does not exist or is 0 bytes in length.\n",aFile->iFileName);
+		return size;
+		}
+
+	aFile->iHeaderRange=aAddress;
+	char* addr = (char*)aFile->iHeaderRange.iImagePtr;
+	const char* src = NULL; 
+	ostringstream os; 
+	if (aFile->iNonXIP)
+		{
+		E32ImageFile f(aBPE);
+		TInt r = f.Open(aFile->iFileName);
+		// is it really a valid E32ImageFile?
+		if (r != KErrNone)
+			{
+			Print(EWarning, "File '%s' is not a valid executable.  Loading file as data.\n", aFile->iFileName);
+			aFile->iNonXIP = EFalse;
+			}
+		else
+			{
+			TUint compression = f.iHdr->CompressionType();
+			if (compression != aFile->iCompression || aFile->iPreferred)
+				{
+				if (compression == 0)
+					Print(ELog, "Compressing file %s\n", aFile->iFileName);
+				else if (aFile->iCompression == 0)
+					Print(ELog, "Decompressing file %s\n", aFile->iFileName);
+				f.iHdr->iCompressionType = aFile->iCompression;
+				if (aFile->iPreferred)
+					{
+					f.iHdr->iModuleVersion &= ~0xffffu;
+					f.iHdr->iModuleVersion |= 0x8000u;
+					}
+				f.UpdateHeaderCrc();
+				}
+			Print(ELog, "Compression Method:0x%08x/0x%08x \n", f.iHdr->CompressionType(), aFile->iCompression);
+			os << f; 
+			size = (os.str()).length(); 
+			src = (os.str()).c_str(); 
+			}
+		}
+	if (addr+size>iData+iSize)
+		{
+		Print(EError, "Can't fit '%s' in Rom.\n", aFile->iFileName);
+		Print(EError, "Rom overflowed by approximately 0x%x bytes.\n", RequiredSize()-iObey->iRomSize);
+		exit(667);
+		}
+	if (src)
+		memcpy(addr, src, size);
+	else
+		size = HFile::Read(aFile->iFileName, (TAny *)addr);
+	Print(ELog,"Size:                    %08x\n", size);
+
+	aFile->iHeaderRange.iSize=size;
+	aAddress.Extend(aFile->iHeaderRange.iSize);
+	return size;
+	}
+
+
+void E32Rom::CalculateDataAddresses()
+//
+//
+//
+	{
+
+	TInt i;
+	TUint32 maxkern = 0;
+	Print(ELog, "\nCalculating kernel limit.\n");
+	for (i=0; i<iObey->iNumberOfPeFiles; i++)
+		{
+		TRomBuilderEntry* e = iPeFiles[i];
+		if (e->Primary())
+			{
+			// this is a kernel
+			TUint32 stack = AlignToPage(e->iHdr->iStackSize);
+			TUint32 heap = AlignToPage(e->iHdr->iHeapSizeMax);
+			if (stack + heap > maxkern)
+				maxkern = stack + heap;
+			}
+		}
+	iObey->iKernelLimit = AlignToChunk(maxkern + iTotalSvDataSize) + iObey->iKernDataRunAddress;
+	if (iObey->iMemModel==E_MM_Direct)
+		iNextDataChunkBase=iObey->iDataRunAddress;
+	else
+		iNextDataChunkBase = iObey->iKernelLimit;
+	Print(ELog, "\nCalculating data addresses.\n");
+	for (i=0; i<iObey->iNumberOfPeFiles; i++)
+		{
+		TRACE(TAREA,Print(ELog,"CalculateDataAddresses %d %s\n",i,iPeFiles[i]->iFileName));
+		CalculateDataAddress(iPeFiles[i]);
+		}
+	TRACE(TIMPORT,Print(ELog,"CalculateDataAddresses complete\n"));
+
+	// On moving model, advance kernel limit past fixed process data areas
+	if (iObey->iMemModel==E_MM_Moving)
+		iObey->iKernelLimit = iNextDataChunkBase;
+	}
+
+void E32Rom::CalculateDataAddress(TRomBuilderEntry *aFile)
+//
+// Work out where the .data/.bss will be
+//
+	{
+	TUint32 dataBssSize=aFile->iRomNode->iRomFile->iTotalDataBss;
+	TUint32 dataRunAddr;
+	if (aFile->Primary())
+		{
+		dataRunAddr = iObey->iKernDataRunAddress;
+		CPU = aFile->iHdr->CpuIdentifier();
+		}
+	else
+		{
+		dataRunAddr = iObey->iDataRunAddress;
+		if (iObey->iMemModel!=E_MM_Multiple && iObey->iMemModel!=E_MM_Flexible && (aFile->iHdr->iFlags & KImageFixedAddressExe))	// propagate 'fixed' from PETRAN
+			{
+			dataRunAddr=0xffffffff;
+			}
+		}
+	if (aFile->iOverrideFlags&KOverrideAddress)
+		{
+		if ((iObey->iMemModel!=E_MM_Multiple && iObey->iMemModel!=E_MM_Flexible) || aFile->iRelocationAddress!=0xffffffff)
+			dataRunAddr=aFile->iRelocationAddress;
+		if (aFile->Extension() || aFile->Variant() || aFile->Device())
+			Print(EError, "reloc not permitted with extension/variant/device\n");
+		}
+	if (!aFile->IsDll() && !aFile->Primary() && (dataRunAddr==0xffffffff || iObey->iMemModel==E_MM_Direct))
+		{
+		dataRunAddr=iNextDataChunkBase;
+		TInt stackreserve=iObey->iDefaultStackReserve;
+		if (aFile->iOverrideFlags & KOverrideStackReserve)
+			stackreserve=aFile->iStackReserve;
+		TInt datsize=AlignToChunk(dataBssSize+stackreserve);
+		// Move target data address to next free chunk
+		iNextDataChunkBase+=datsize;
+		}
+	if (aFile->Extension() || aFile->Device() || aFile->Variant())
+		{
+		dataRunAddr=iObey->iKernDataRunAddress+aFile->iDataBssOffset;
+		}
+	else if (aFile->IsDll() && dataBssSize!=0 && aFile->iRomNode->iRomFile->iDataBssOffsetInExe<0)
+		{
+		iNextDllDataAddr = AllocVirtual(iNextDllDataAddr,dataBssSize);
+		dataRunAddr=iNextDllDataAddr;
+		}
+	if (iObey->iMemModel==E_MM_Moving && dataRunAddr==iObey->iDataRunAddress && aFile->Secondary())
+		{
+		Print(EWarning,"Secondary not fixed\n");
+		}
+
+	TRACE(TAREA, Print(ELog, "Data run address %08x\n", dataRunAddr));
+	aFile->iDataBssLinearBase=dataRunAddr;
+	}
+
+void E32Rom::LoadFileToRom(TRomBuilderEntry *aFile)
+//
+// Load an E32Image/PE file to rom
+//
+	{
+
+	char* addr = (char*)aFile->iHeaderRange.iImagePtr;
+	TRACE(TAREA, Print(ELog,"+LoadFileToRom addr %08x %08x %08x\n", addr,
+					   aFile->iHeaderRange.iImageAddr, aFile->iHeaderRange.iRunAddr));
+
+	if (addr+aFile->SizeInRom()>iData+iSize) // check this
+		{
+		Print(EError, "Can't fit '%s' in Rom.\n", aFile->iFileName);
+		Print(EError, "Rom overflowed by approximately 0x%x bytes.\n", RequiredSize()-iObey->iRomSize);
+		exit(666);
+		}
+
+	// check file will not overflow into next ROM
+	if (aFile->Primary())
+		{
+		if (!iPrevPrimaryAddress)
+			iHeader->iPrimaryFile=ActualToRomAddress(aFile->RomEntry());
+		else if (iObey->iKernelModel==EMultipleKernels)
+			{
+			((TRomImageHeader*)iPrevPrimaryAddress)->iNextExtension=ActualToRomAddress(aFile->RomEntry());
+			}
+		iPrevPrimaryAddress=addr;
+		TRACE(TAREA, Print(ELog, "iHeader->iPrimaryFile = %08x\n", iHeader->iPrimaryFile));
+		}
+
+	// Place the file in rom
+	if (aFile->Variant())
+		{
+		if (iPrevVariantAddress)
+			((TRomImageHeader*)iPrevVariantAddress)->iNextExtension=ActualToRomAddress(aFile->RomEntry());
+		else
+			iHeader->iVariantFile=ActualToRomAddress(aFile->RomEntry());
+		iPrevVariantAddress=addr;
+		}
+	if (aFile->IsDll() && aFile->iRomNode->iRomFile->iTotalDataBss!=0 && aFile->iRomNode->iRomFile->iDataBssOffsetInExe>=0)
+		{
+		TRomFile* f=aFile->iRomNode->iRomFile->iPDeps[0];	// attach process
+		aFile->iDataBssLinearBase = f->DataBssLinearBase() + aFile->iRomNode->iRomFile->iDataBssOffsetInExe;
+		}
+
+	aFile->LoadToRom();
+	}
+
+char *E32Rom::LayoutRom(char *romaddr)
+//
+// Layout the files from the obey file starting at romaddr in the image
+// dealing correctly with areas
+// Also deals with two section ROMs
+//
+	{
+
+	TAddressRange main;
+	TAddressRange* mainptr=&main;
+	SetImageAddr(main, romaddr);
+
+	TAddressRange second;
+	TAddressRange* secondptr=0;
+	if (iObey->iSectionStart != 0)
+		{
+		SetImageAddr(second,iSectionPtr);
+		secondptr = &second;
+		}
+
+	TInt fileCount=0;
+	if(gGenSymbols && !iSymGen) {
+		string filename(iObey->GetFileName());
+		filename.erase(filename.length() - 3,3);
+		filename.append("symbol");
+		iSymGen = new SymbolGenerator(filename.c_str(),gThreadNum - 1);		
+	}
+		
+	//
+	// Process files in non default areas
+	//
+
+        CBytePair bpe;
+	for (NonDefaultAreasIterator areaIt(iObey->SetArea());
+		 ! areaIt.IsDone();
+		 areaIt.GoToNext())
+		{
+		Area& currentArea = areaIt.Current();
+		currentArea.SetSrcBaseAddr(mainptr->iImageAddr);
+
+		mainptr->iRunAddr = currentArea.DestBaseAddr();
+
+		for (FilesInAreaIterator fileIt(currentArea);
+			 ! fileIt.IsDone();
+			 fileIt.GoToNext())
+			{
+			TRomBuilderEntry* currentFile = fileIt.Current();
+
+			LayoutFile(currentFile, *mainptr, secondptr, &bpe);
+		
+			TUint overflow;
+			if (! currentArea.ExtendSrcLimitAddr(mainptr->iImageAddr, overflow))
+				{
+				Print(EError, "Can't fit '%s' in area '%s'\n", currentFile->iFileName, currentArea.Name());
+				Print(EError, "Area overflowed by 0x%x bytes.\n", overflow);
+				exit(666);
+				}
+
+			++fileCount;
+			assert(iObey->iSectionPosition == -1 || fileCount < iObey->iSectionPosition);
+			}
+
+		TInt offset=(char*)mainptr->iImagePtr-romaddr;
+		mainptr->Extend(Align(offset)-offset);
+		} // for every non default area
+
+
+	//
+	// Process files in default area
+	//
+
+	mainptr->iRunAddr = mainptr->iImageAddr;
+
+	for (FilesInAreaIterator fileIt(*(iObey->SetArea().DefaultArea()));
+		 ! fileIt.IsDone();
+		 fileIt.GoToNext())
+		{
+		if (fileCount==iObey->iSectionPosition)
+			{
+			// skip rest of first section and pick up after the
+			// information already accumulated in the second section
+			NextRom(mainptr, secondptr);
+			mainptr = secondptr;
+			secondptr = 0;
+			}
+
+		LayoutFile(fileIt.Current(), *mainptr, secondptr, &bpe);
+
+		++fileCount;
+		}
+
+	// align to likely position of next file
+	TInt offset=(char*)mainptr->iImagePtr-romaddr;
+	offset = Align(offset)-offset;
+	mainptr->Extend(offset);
+	iOverhead +=offset;
+	if(iSymGen){
+		SymGenContext context ;
+		memset(&context,0,sizeof(SymGenContext));
+		iSymGen->AddEntry(context);
+	}
+	return (char*)mainptr->iImagePtr;
+ 	}
+
+void E32Rom::LayoutFile(TRomBuilderEntry* current, TAddressRange& aMain, TAddressRange* aSecond, CBytePair * aBPE)
+//
+// Work out where to place a file in ROM and set up the 
+// appropriate TAddressRange information
+//
+	{
+	TInt alignment = iObey->iRomAlign;
+	if (current->iAlignment > alignment)
+		alignment = current->iAlignment;
+
+	if (alignment)
+		{
+		// Align this file on a boundary
+		TUint32 romaddr=aMain.iRunAddr;
+		TInt i=romaddr & (alignment-1);
+		TInt gap=0;
+		if (i!=0)
+			gap=alignment-i;
+		if (current->iAlignment)
+			Print(ELog, "\nAlign to %08x.  Skipped %d bytes\n", romaddr+gap, gap);
+		aMain.Extend(gap);
+		iOverhead += gap;
+		}
+
+	if (current->iCodeAlignment != 0)
+		{
+		TUint32 runaddr=aMain.iRunAddr + sizeof(TRomImageHeader);
+		TInt i=runaddr & (current->iCodeAlignment-1);
+		TInt gap=0;
+		if (i!=0)
+			gap=current->iCodeAlignment-i;
+		Print(ELog, "\nCode Align to %08x.  Skipped %d bytes\n", runaddr+gap, gap);
+		aMain.Extend(gap);
+		iOverhead += gap;
+		}
+
+	Print(ELog,"\n********************************************************************\n");
+
+	if (current->iPatched)
+		Print(ELog, "[Patched file]\n");
+	TLinAddr savedAddr = aMain.iImageAddr;
+	if (current->iResource)
+		{		
+		TInt size=LoadDataToRom(current, aMain, aBPE);
+		if (aSecond != 0 && aMain.iImageAddr > iObey->iSectionStart)
+			return;		// first section has overflowed
+		current->FixupRomEntries(size);
+		if(iSymGen) {
+			SymGenContext context ;
+			memset(&context,0,sizeof(SymGenContext));
+			context.iFileName = current->iFileName ;
+			context.iDataAddress = savedAddr ;
+			iSymGen->AddEntry(context); 
+		}
+		return;
+		}
+	if(current->HCRDataFile()){	
+		TInt size=LoadDataToRom(current, aMain, aBPE);		
+		if (aSecond != 0 && aMain.iImageAddr > iObey->iSectionStart)
+			return;		// first section has overflowed
+		current->FixupRomEntries(size);
+		iHeader->iHcrFileAddress =  current->iHeaderRange.iImageAddr ;
+		TRACE(TAREA, Print(ELog, "iHeader->iHcrFileAddress = %08x\n", iHeader->iHcrFileAddress));	
+		if(iSymGen) {
+			SymGenContext context ;
+			memset(&context,0,sizeof(SymGenContext));
+			context.iFileName = current->iFileName ;
+			context.iDataAddress = savedAddr ;
+			iSymGen->AddEntry(context); 
+		}		
+		return ;
+	}
+	Print(ELog,"Processing file %s\n",current->iFileName);
+
+	if (current->Primary())
+		{
+		Print(ELog, "[Primary]\n");
+		}
+
+	if (current->Secondary())
+		{
+		iHeader->iSecondaryFile=ActualToRomAddress(current->RomEntry());
+		Print(ELog, "[Secondary]\n");
+		}
+
+	// Section 1 things
+	//
+	// TRomImageHeader, text, export directory, data
+
+	aMain.Append(current->iHeaderRange);
+	aMain.Append(current->iCodeSection);
+	aMain.Append(current->iDataSection);
+
+	// section 2 things
+	//
+	// dll ref table
+
+	if (aSecond != 0)
+		{
+		// two section ROM - split image between both sections
+		aSecond->Append(current->iExportDirSection);
+		aSecond->Append(current->iDllRefTableRange);
+		}
+	else
+		{
+		// default placement in first section
+		aMain.Append(current->iExportDirSection);
+		aMain.Append(current->iDllRefTableRange);
+		}
+
+	TInt section1size = aMain.iRunAddr-current->iCodeSection.iRunAddr;
+
+	if (aMain.iRunAddr == aMain.iImageAddr)
+		{
+		Print(ELog, "Load Address:            %08x\n", current->iHeaderRange.iImageAddr);
+		}
+	else
+		{
+		Print(ELog, "Rom Address:             %08x\n", current->iHeaderRange.iImageAddr);
+		Print(ELog, "Area Address:            %08x\n", current->iHeaderRange.iRunAddr);
+		}
+	Print(ELog,     "Size:                    %08x\n", section1size);
+
+	if (aSecond != 0 && aMain.iImageAddr > iObey->iSectionStart)
+		return;		// first section has overflowed
+
+	LoadFileToRom(current);
+	TRomImageHeader *header = current->iRomImageHeader;
+	if(iSymGen){
+		SymGenContext context  ;
+		context.iFileName = current->iFileName ;		
+		context.iTotalSize = section1size;
+		context.iCodeAddress = header->iCodeAddress; 
+		context.iDataAddress = header->iDataAddress; 
+		context.iDataBssLinearBase = header->iDataBssLinearBase;	 
+		context.iTextSize = header->iTextSize; 
+		context.iDataSize = header->iDataSize; 
+		context.iBssSize = header->iBssSize;   	
+		context.iTotalDataSize = header->iTotalDataSize;
+		context.iExecutable = ETrue ;
+		iSymGen->AddEntry(context);		
+	}
+	Display(header);
+	Print(ELog,     "Dll ref table size:      %08x\n", current->iDllRefTableRange.iSize);
+	Print(ELog,     "Compression:             %08x\n", current->iCompression);
+	Print(ELog,     "\n");
+
+	current->FixupRomEntries(section1size);	
+	}
+
+static int CompareAddresses(const void * arg1, const void * arg2) 
+	{ 
+	return (* (TUint32 *)arg1) < (* (TUint32 *)arg2) ? -1: 1; 
+	}
+
+char *E32Rom::ReserveRomExceptionSearchTable(char *anAddr, TRomExceptionSearchTable*& exceptionSearchTable)
+	{
+	TRomExceptionSearchTable *pT = (TRomExceptionSearchTable *)anAddr;
+	exceptionSearchTable = pT;
+	if (iExtensionRomHeader)
+		{
+		iExtensionRomHeader->iRomExceptionSearchTable = ActualToRomAddress(anAddr);
+		}
+	else
+		{
+		iHeader->iRomExceptionSearchTable = ActualToRomAddress(anAddr);
+		}
+	TLinAddr * addr = &pT->iEntries[0];
+	int numEntries = 0;
+	int errors = 0;
+	// Count number of entries needed
+	for (int i = 0; i < iObey->iNumberOfPeFiles; i++)
+		{
+		TUint32 xd = iPeFiles[i]->iHdr->iExceptionDescriptor;
+		if ((xd & 1) && (xd != 0xffffffffu))
+			{
+			numEntries++;
+			}
+		else if (!iPeFiles[i]->iHdr->iExceptionDescriptor)
+			{
+#ifdef __REJECT_NON_EXCEPTION_AWARE_BINARIES__
+			Print(EError, "Executable not exception aware: %s\n", iPeFiles[i]->iName);
+			errors++;
+#else
+			Print(ELog, "Executable not exception aware: %s\n", iPeFiles[i]->iName);
+#endif
+			}
+		}
+	if (errors > 0) exit(666);
+	// NB we add one to numEntries to allow space for a fencepost value (see below for more)
+	int spaceNeeded = sizeof(pT->iNumEntries) + sizeof(pT->iEntries[0])*(numEntries+1);
+	int delta = (int)(addr+spaceNeeded) - (int)(iData+iSize);
+	// Check we've got enough room
+	if (delta > 0)
+		{
+		Print(EError, "Can't fit Rom Exception Search Table in Rom.\n");
+		Print(EError, "Rom overflowed by approximately 0x%x bytes.\n", delta);
+		exit(666);
+		}
+	pT->iNumEntries = numEntries;
+	return anAddr+spaceNeeded;
+	}
+	
+void E32Rom::ConstructRomExceptionSearchTable(TRomExceptionSearchTable* exceptionSearchTable)
+	{
+	TRomExceptionSearchTable *pT = exceptionSearchTable;
+	TLinAddr * addr = &pT->iEntries[0];
+	// Initialize the table
+	int numEntries = pT->iNumEntries;
+	TLinAddr fencepost = 0xffffffff;
+	if (numEntries)
+		{
+		TLinAddr fp = 0;
+		for (int j = 0; j < iObey->iNumberOfPeFiles; j++)
+			{
+			TUint32 xd = iPeFiles[j]->iHdr->iExceptionDescriptor;
+			if ((xd & 1) && (xd != 0xffffffff))
+				{
+				// mask out bottom bit set by ELFTRAN.
+				xd &= ~1;
+				*addr++ = iPeFiles[j]->iHdr->iCodeBase;
+				TLinAddr aEDAddr = iPeFiles[j]->iHdr->iCodeBase + xd; 
+				// Keep track of greatest code limit so we can use it as the fencepost value
+				TExceptionDescriptor * aEDp = (TExceptionDescriptor *)RomToActualAddress(aEDAddr);
+				TLinAddr codeLimit = aEDp->iROSegmentLimit;
+				if (codeLimit>fp) fp=codeLimit;
+				}
+			}
+		if (fp) fencepost=fp;
+		// now check they're in order (they should be).
+		int inOrder = 1;
+		for (int k=numEntries-1;inOrder && k; k--) 
+			{
+			inOrder = pT->iEntries[k]>pT->iEntries[k-1]?1:0;
+			}
+
+		if (!inOrder)
+			{
+			Print(ELog, "Sorting Rom Exception Table.\n");
+			qsort(&pT->iEntries[0],numEntries,sizeof(pT->iEntries[0]), CompareAddresses);
+			}
+		}
+	/*
+	  Add the fencepost value at the end of the table. This is used to optimize the comparison
+	  function passed to bsearch when retrieving values from the search table. It also allows a certain
+	  amount of error checking on lookup keys.
+	*/
+	*addr++ = fencepost;
+	}
+
+void TRomBuilderEntry::SizeInSections(TInt& aSize1, TInt& aSize2)
+//
+// Exact size of the upper & lower section information
+// lower = text + data
+// upper = export directory + dllref table
+//
+	{
+	aSize1  = iHeaderRange.iSize;
+	aSize1 += iCodeSection.iSize;			// text (including rdata)
+	aSize1 += iDataSection.iSize;			// static data
+
+	aSize2  = iExportDirSection.iSize;		// export directory
+	aSize2 += iDllRefTableRange.iSize;	// DLL ref table
+	}
+
+							
+void E32Rom::NextRom(TAddressRange* aFirst, TAddressRange* aSecond)
+//
+// Move on to the next Rom bank, taking the IATs with us
+//
+	{
+
+	Print(ELog,"\n####################################################################\n");
+	TInt gap=iObey->iSectionStart-aFirst->iImageAddr;
+	if (gap<0)
+		{
+		Print(EError, "First section overflowed by %08x bytes\n", -gap);
+		exit(669);
+		}
+	iOverhead+=gap+sizeof(TRomSectionHeader);
+	Print(ELog, "[Next rom section]\n");
+	Print(ELog, "Skipping %08x bytes\n", gap);
+	Print(ELog, "LinAddr:                 %08x\n", iObey->iSectionStart);
+	Print(ELog, "First section tables:    %08x\n", iObey->iSectionStart+sizeof(TRomSectionHeader));
+	TInt size=aSecond->iImageAddr-iObey->iSectionStart;
+	Print(ELog, "Tables size:             %08x\n", size-sizeof(TRomSectionHeader));
+	Print(ELog, "Rom Directory            %08x\n", iHeader->iRomRootDirectoryList);
+	Print(ELog, "Rom Directory size       %08x\n", iDirectorySize);
+
+	if (aSecond->iImageAddr != iHeader->iRomRootDirectoryList)
+		{
+		Print(EError, "Second section has overwritten the Rom directory\n");
+		exit(669);
+		}
+	aSecond->Extend(iDirectorySize);
+
+	Print(ELog, "\n");
+	}
+
+TInt E32Rom::ResolveDllRefTables()
+//
+//
+//
+	{
+
+	Print(ELog, "\nResolving Dll reference tables.\n");
+	TInt i;
+	TInt err = KErrNone;
+	for (i=0; i<iObey->iNumberOfPeFiles; i++)
+		{
+		TRACE(TIMPORT,Print(ELog,"ResolveDllRefTables %d\n",i));
+		TInt r=iPeFiles[i]->ResolveDllRefTable(*this);
+		if (r!=KErrNone)
+			err=r;
+		}
+	TRACE(TIMPORT,Print(ELog,"ResolveDllRefTables complete\n"));
+	return err;
+	}
+
+
+TInt E32Rom::BuildDependenceGraph()
+	{
+	Print(ELog, "\nBuilding dependence graph.\n");
+	TInt i;
+	TInt err = KErrNone;
+	for (i=0; i<iObey->iNumberOfPeFiles; i++)
+		{
+		TRACE(TIMPORT,Print(ELog,"BuildDep %d\n",i));
+		TRomBuilderEntry* e=iPeFiles[i];
+		TInt r=e->BuildDependenceGraph(*this);
+		if (r!=KErrNone)
+			err=r;
+		if (!e->IsDll())
+			{
+			if (e->iHdr->iDataSize!=0 || e->iHdr->iBssSize!=0)
+				e->iRomImageFlags|=(KRomImageFlagData|KRomImageFlagDataPresent);	// EXE with static data
+			}
+		else if ((e->iHdr->iDataSize!=0 || e->iHdr->iBssSize!=0) && !e->Variant() && !e->Extension())
+			{
+			// requires normal case DLL data initialisation
+			e->iRomImageFlags|=(KRomImageFlagData|KRomImageFlagDataInit|KRomImageFlagDataPresent);
+			}
+		}
+	TRACE(TIMPORT,Print(ELog,"BuildDep complete\n"));
+
+	if(!gPagedRom)
+		return err;
+
+	Print(ELog,"\n");
+
+	return err;
+	}
+
+#define MARK_BEEN_HERE	1
+#define MARK_KEEP		2
+#define	MARK_EXE		4
+#define MARK_CHECKED	8
+void E32Rom::UnmarkGraph(TInt aMark)
+	{
+	TRomNode* x = 0;
+	for (x=iObey->iRootDirectory->iNextExecutable; x; x=x->iNextExecutable)
+		x->iRomFile->iMark &= ~aMark;
+	}
+
+void E32Rom::FindMarked(TInt aMarkMask, TInt aMark, TRomFile**& aList)
+	{
+	UnmarkGraph(MARK_CHECKED);
+	TRomNode* x = 0;
+	aMarkMask |= MARK_CHECKED;
+	aMark &= ~MARK_CHECKED;
+	for (x=iObey->iRootDirectory->iNextExecutable; x; x=x->iNextExecutable)
+		{
+		TRomFile* e = x->iRomFile;
+		if ((e->iMark&aMarkMask)==aMark)
+			{
+			*aList++=e;
+			e->iMark |= MARK_CHECKED;
+			}
+		}
+	}
+
+TInt TRomFile::MarkDeps()
+	{
+	TInt n=0;
+	TInt i;
+	for (i=0; i<iNumDeps; ++i)
+		{
+		TRomFile* e=iDeps[i];
+		if (!(e->iMark & MARK_BEEN_HERE))
+			{
+			e->iMark|=MARK_BEEN_HERE;
+			++n;
+			n+=e->MarkDeps();
+			TUint32 flg = RomImageFlags();
+			TUint32 eflg = e->RomImageFlags();
+			if (eflg & KRomImageFlagDataPresent)
+				iRbEntry->iRomImageFlags |= KRomImageFlagDataPresent;
+			TBool e_is_dll = eflg & KImageDll;
+			if ((flg & KImageDll) && e_is_dll && (eflg & KRomImageFlagDataInit))
+				iRbEntry->iRomImageFlags |= KRomImageFlagDataInit;
+			if (!e_is_dll)
+				e->iMark|=MARK_EXE;
+			if (eflg&KRomImageFlagData)
+				e->iMark|=MARK_KEEP;
+			}
+		}
+	return n;
+	}
+
+TInt TRomFile::FindRouteTo(TRomFile* aDest, TRomFile** aStack, TInt aIndex)
+	{
+	TInt i;
+	for (i=0; i<iNumDeps; ++i)
+		{
+		TRomFile* e=iDeps[i];
+		if (e == aDest)
+			return aIndex;
+		if (!(e->iMark & MARK_BEEN_HERE))
+			{
+			e->iMark|=MARK_BEEN_HERE;
+			aStack[aIndex] = e;
+			TInt r = e->FindRouteTo(aDest, aStack, aIndex+1);
+			if (r >= 0)
+				return r;
+			}
+		}
+	return KErrNotFound;
+	}
+
+void E32Rom::ListRouteTo(TRomFile* aStart, TRomFile* aDest, TInt aNDeps)
+	{
+	TRomNode* rootdir = iObey->iRootDirectory;
+	TRomFile** stack = new TRomFile*[aNDeps];
+	UnmarkGraph();
+	TInt depth = aStart->FindRouteTo(aDest, stack, 0);
+	assert(depth >= 0);
+	Print(EAlways, "\t--->%s\n", (const char*)TModuleName(*aDest, rootdir));
+	while(--depth >= 0)
+		Print(EAlways, "\tvia %s\n", (const char*)TModuleName(*stack[depth], rootdir));
+	delete[] stack;
+	}
+
+TInt E32Rom::ProcessDependencies()
+	{
+	TInt i;
+	TInt errors = 0;
+	for (i=0; i<iObey->iNumberOfPeFiles; i++)
+		{
+		TRomBuilderEntry* e=iPeFiles[i];
+		TRomNode* rn = e->iRomNode;
+		TRomFile* rf = rn->iRomFile;
+		UnmarkGraph();
+		TInt n=rf->MarkDeps();
+		rf->iNumPDeps=n;
+		if (n)
+			{
+			rf->iPDeps=new TRomFile* [n];
+			if (!rf->iPDeps)
+				return KErrNoMemory;
+			TRomFile** l=rf->iPDeps;
+			FindMarked(MARK_EXE, MARK_EXE, l);
+			TInt nx=l-rf->iPDeps;
+			if (!e->IsDll() && (nx>1 || nx==1 && l[-1]!=rf))
+				{
+				Print(EError,"EXE %s links to the following other EXEs:\n", e->iFileName);
+				TInt j;
+				for (j=0; j<nx; ++j)
+					{
+					if (rf->iPDeps[j] != rf)
+						ListRouteTo(rf, rf->iPDeps[j], n);
+					}
+				++errors;
+				continue;
+				}
+			else if (nx>1)
+				{
+				Print(EError,"DLL %s links to more than one EXE:\n",e->iFileName);
+				TInt j;
+				for (j=0; j<nx; ++j)
+					ListRouteTo(rf, rf->iPDeps[j], n);
+				++errors;
+				continue;
+				}
+			if (nx)
+				e->iRomImageFlags|=KRomImageFlagExeInTree;
+			FindMarked(MARK_KEEP|MARK_EXE, MARK_KEEP, l);
+			rf->iNumPDeps=l-rf->iPDeps;
+			if (rf->iNumPDeps)
+				{
+				e->iDllRefTableRange.iSize=(rf->iNumPDeps-1)*sizeof(TRomImageHeader*)+sizeof(TDllRefTable);
+				if (e->IsDll() && rf->iTotalDataBss)
+					{
+					TRomFile* f=rf->iPDeps[0];	// first dependency, EXE if there is one
+					TUint fflg = f->RomImageFlags();
+					TBool f_is_dll = fflg & KImageDll;
+					if (!f_is_dll)
+						{
+						// DLL with data/bss depends on EXE
+						if ((fflg & KRomImageFlagFixedAddressExe) || iObey->iMemModel==E_MM_Direct)
+							{
+							// assign the DLL data address in the EXE bss section
+							rf->iDataBssOffsetInExe=f->iTotalDataBss;
+							f->iTotalDataBss+=rf->iTotalDataBss;
+							}
+						}
+					else if (iObey->iMemModel==E_MM_Direct)
+						{
+						Print(EError, "DLL with data/bss must have attach process specified\n");
+						return KErrGeneral;
+						}
+					}
+				}
+			else
+				{
+				delete[] rf->iPDeps;
+				rf->iPDeps=NULL;
+				}
+			}
+		if (!rf->iNumPDeps)
+			e->iDllRefTableRange.iSize=0;
+		}
+	if (iObey->iMemModel == E_MM_Moving)
+		{
+		// On moving model only, we must verify that no fixed process links to a
+		// DLL with data/bss which is attached to a fixed process.
+		// On multiple model there is no restriction.
+		// On direct model all DLLs with data/bss must specify an attach process
+		// and the error will show up as one EXE depending on another.
+		for (i=0; i<iObey->iNumberOfPeFiles; i++)
+			{
+			TRomBuilderEntry* e=iPeFiles[i];
+			TRomNode* rn = e->iRomNode;
+			TRomFile* rf = rn->iRomFile;
+			TUint rif = rf->RomImageFlags();
+			if (e->IsDll() || e->Primary() || !(rif & KRomImageFlagFixedAddressExe))
+				continue;	// only need to check fixed address user mode EXEs
+			TInt n = rf->iNumPDeps;
+			TInt j;
+			for (j=0; j<n; ++j)
+				{
+				TRomFile* f = rf->iPDeps[j];
+				TUint fflg = f->RomImageFlags();
+				if ((fflg & KImageDll) && (f->iDataBssOffsetInExe < 0))
+					{
+					// fixed user EXE links to DLL with data/bss and no attach process
+					Print(EError,"Fixed EXE %s links to DLL with data/bss and no attach process:\n", e->iFileName);
+					ListRouteTo(rf, rf->iPDeps[j], n);
+					++errors;
+					}
+				}
+			}
+		}
+	if (errors)
+		return KErrGeneral;
+
+	STRACE(TIMPORT, 
+		{
+		for (i=0; i<iObey->iNumberOfPeFiles; i++)
+			{
+			TRomBuilderEntry* e=iPeFiles[i];
+			TRomNode* rn = e->iRomNode;
+			TRomFile* rf = rn->iRomFile;
+			Print(ELog,"File %s: PN=%d\n",e->iFileName,rf->iNumPDeps);
+			TInt j;
+			for (j=0; j<rf->iNumPDeps; ++j)
+				{
+				TRomFile* f=rf->iPDeps[j];
+				Print(ELog,"\t%s\n", (const char*)TModuleName(*f, iObey->iRootDirectory));
+				}
+			}
+		})
+	return KErrNone;
+	}
+
+void E32Rom::SetSmpFlags()
+    {
+	if (gLogLevel & LOG_LEVEL_SMP_INFO)
+		{
+		Print(ELog,"\nComputing SMP properties. The following components are SMP-unsafe:\n");
+		}
+
+	bool is_all_safe = 1;
+
+	for (int i = 0; i < iObey->iNumberOfPeFiles; i++)
+		{
+		TRomBuilderEntry* e = iPeFiles[i];
+
+        if ( e->iRomNode->iRomFile->ComputeSmpSafe(e) )
+			{
+			e->iRomImageFlags |= KRomImageSMPSafe;
+			}
+		else
+			{
+			is_all_safe = 0;
+			e->iRomImageFlags &= ~KRomImageSMPSafe;
+			}
+		}
+
+	if ( (gLogLevel & LOG_LEVEL_SMP_INFO) && is_all_safe)
+		{
+		Print(ELog,"There are no unsafe components.");
+		}
+    }
+
+TInt E32Rom::ResolveImports()
+//
+// Fix the import address table for each of the files in rom
+//	
+	{
+
+	Print(ELog, "Resolving Imports.\n");
+	TInt i;
+	for (i=0; i<iObey->iNumberOfPeFiles; i++)
+		{
+		TInt r=iPeFiles[i]->FixupImports(*this);
+		if (r!=KErrNone)
+			return r;
+		}
+	return KErrNone;
+	}
+
+char *E32Rom::RomToActualAddress(TUint aPtr)
+	{
+	return (char *)(aPtr-iObey->iRomLinearBase+(TUint)iHeader);
+	}
+
+TUint E32Rom::ActualToRomAddress(TAny *aPtr)
+	{
+	return ((TUint)aPtr)-(TUint32)iHeader+iObey->iRomLinearBase;
+	}
+
+void E32Rom::SetImageAddr(TAddressRange& aRange, TAny* aPtr, TUint32 aRunOffset)
+	{
+	aRange.iImagePtr=aPtr;
+	aRange.iImageAddr=ActualToRomAddress(aPtr);
+	aRange.iRunAddr=aRange.iImageAddr+aRunOffset;
+	}
+
+void E32Rom::SetImageAddr(TAddressRange& aRange, TUint aAddr, TUint32 aRunOffset)
+	{
+	aRange.iImagePtr=RomToActualAddress(aAddr);
+	aRange.iImageAddr=aAddr;
+	aRange.iRunAddr=aAddr+aRunOffset;
+	}
+
+TRomNode* E32Rom::FindImageFileByName(const TDllFindInfo& aInfo, TBool aPrintDiag, TBool& aFallBack)
+//
+// return the file with the name aName
+//
+	{
+	return iObey->iRootDirectory->FindImageFileByName(aInfo, aPrintDiag, aFallBack);
+	}
+
+TInt E32Rom::CheckForVersionConflicts(const TRomBuilderEntry* a)
+	{
+	return iObey->iRootDirectory->CheckForVersionConflicts(a);
+	}
+
+TRomNode* E32Rom::CopyDirectory(TRomNode*& aLastExecutable)
+	{
+	return iObey->iRootDirectory->CopyDirectory(aLastExecutable, 0);
+	}
+
+TInt E32Rom::CollapseImportThunks()
+//
+// Collapse 3-word import thunks into a single branch
+//	
+	{
+
+	Print(ELog, "\nCollapsing Import Thunks.\n");
+	TInt i;
+	for (i=0; i<iObey->iNumberOfPeFiles; i++)
+		{
+		if (iPeFiles[i]->iHdr->iImportOffset)
+			{
+			TInt r=CollapseImportThunks(iPeFiles[i]);
+			if (r!=KErrNone)
+				return r;
+			}
+		}
+	return KErrNone;
+	}
+
+TInt E32Rom::WriteImages(TInt aHeaderType)
+	{
+	if (aHeaderType < 0)
+		aHeaderType = 1;
+	ofstream romFile((const char *)iObey->iRomFileName,ios_base::binary);
+	if (!romFile)
+		return Print(EError,"Cannot open ROM file %s for output\n",iObey->iRomFileName);
+	Write(romFile, aHeaderType);
+	romFile.close();
+
+	// Write out the odd/even 16-bits of the images
+
+	char sname[256];
+	if (iObey->iRomOddFileName)
+		{
+		strcpy(sname, (const char*)iObey->iRomOddFileName);
+		if (strcmp(sname, "*")==0)
+			{
+			// use romname with ".odd" appended.
+			sprintf(sname,"%s.odd",(const char *)iObey->iRomFileName);
+			}
+		ofstream oFile(sname,ios_base::binary);
+		if (!oFile)
+			return Print(EError,"Cannot open file %s for output\n",sname);
+		Print(EAlways, "Writing odd half words to file %s\n",sname);
+		WriteOdd(oFile);
+		oFile.close();
+		}
+	if (iObey->iRomEvenFileName)
+		{
+		strcpy(sname, (const char*)iObey->iRomEvenFileName);
+		if (strcmp(sname, "*")==0)
+			{
+			// use romname with ".even" appended.
+			sprintf(sname,"%s.even",(const char *)iObey->iRomFileName);
+			}
+		ofstream oFile(sname,ios_base::binary);
+		if (!oFile)
+			return Print(EError,"Cannot open file %s for output\n",sname);
+		Print(EAlways, "Writing even half words to file %s\n",sname);
+		WriteEven(oFile);
+		oFile.close();
+		}
+
+	// Write out the ROM in the SREC or S19 format
+
+	if (iObey->iSRecordFileName)
+		{
+		strcpy(sname, (const char*)iObey->iSRecordFileName);
+		if (strcmp(sname, "*")==0)
+			{
+			// use romname with ".srec" appended.
+			sprintf(sname,"%s.srec",(const char *)iObey->iRomFileName);
+			}
+		ofstream sFile(sname,ios_base::binary);
+		if (!romFile)
+			return Print(EError,"Cannot open file %s for output\n",sname);
+		Print(EAlways, "Writing S record format to file %s\n",sname);
+		WriteSRecord(sFile);
+		sFile.close();
+		}
+	return KErrNone;
+	}
+
+void E32Rom::WriteOdd(ofstream &os)
+	{
+	char *ptr=(char *)iHeader+2;
+	TInt i;
+	for (i=2; i<iObey->iRomSize; i+=4, ptr+=4)
+		os.write(ptr, 2);
+	}
+
+void E32Rom::WriteEven(ofstream &os)
+	{
+	char *ptr=(char *)iHeader;
+	TInt i;
+	for (i=0; i<iObey->iRomSize; i+=4, ptr+=4)
+		os.write(ptr, 2);
+	}
+
+void E32Rom::SetCompressionInfo(TUint aCompressionType, TUint aCompressedSize, TUint aUncompressedSize)
+	{
+
+	if (iExtensionRomHeader)
+		{
+		iExtensionRomHeader->iCompressionType=aCompressionType;
+		iExtensionRomHeader->iCompressedSize=aCompressedSize;
+		iExtensionRomHeader->iUncompressedSize=aUncompressedSize;
+		}
+	else
+		{
+		iHeader->iCompressionType=aCompressionType;
+		iHeader->iCompressedSize=aCompressedSize;
+		iHeader->iUncompressedSize=aUncompressedSize;
+		}
+	}
+
+void E32Rom::Write(ofstream &os, TInt aHeaderType)
+//
+// Output a rom image
+//
+	{
+
+	const char *compressed=gEnableCompress ? " compressed" : " uncompressed"; 
+
+	switch (aHeaderType)
+		{
+	case 0:
+		Print(EAlways, "\nWriting%s Rom image without",compressed);
+		break;
+	case 1:
+	default:
+		Print(EAlways, "\nWriting%sRom image with repro",compressed);
+		os.write(iData, sizeof(TRomLoaderHeader));
+		break;
+	case 2:
+		Print(EAlways, "\nWriting%s Rom image with PE-COFF",compressed);
+			{
+			unsigned char coffhead[0x58] = {0};  // zero all the elements
+
+			// fill in the constant bits
+			// this is supposed to be simple, remember
+			coffhead[1] = 0x0a;
+			coffhead[2] = 0x01;
+			coffhead[0x10] = 0x1c;
+			coffhead[0x12] = 0x0f;
+			coffhead[0x13] = 0xa1;
+			coffhead[0x14] = 0x0b;
+			coffhead[0x15] = 0x01;
+			coffhead[0x26] = 0x40;
+			coffhead[0x2a] = 0x40;
+			coffhead[0x30] = 0x2e;
+			coffhead[0x31] = 0x74;
+			coffhead[0x32] = 0x65;
+			coffhead[0x33] = 0x78;
+			coffhead[0x34] = 0x74;
+			coffhead[0x3a] = 0x40;
+			coffhead[0x3e] = 0x40;
+			coffhead[0x44] = 0x58;
+			coffhead[0x54] = 0x20;
+
+			// now fill in the text segment size
+			*(TUint32 *) (&coffhead[0x18]) = ALIGN4K(iSizeUsed);
+			*(TUint32 *) (&coffhead[0x40]) = ALIGN4K(iSizeUsed);
+
+			os.write(reinterpret_cast<char *>(coffhead), sizeof(coffhead));
+			}
+		break;
+		}
+	Print(EAlways, " header to file %s\n", iObey->iRomFileName);
+	
+	iHeader->iUnpagedCompressedSize   = 0;
+	iHeader->iUnpagedUncompressedSize = iHeader->iPageableRomStart;
+	iHeader->iCompressedUnpagedStart =  gBootstrapSize + gPageIndexTableSize;	// AttilaV calculate uncompressed un-paged size 
+	
+	if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
+		{
+		Print(ELog, "iUnpagedCompressedSize  :0x%08x (%d)\n",     iHeader->iUnpagedCompressedSize);
+		Print(ELog, "iUnpagedUncompressedSize:0x%08x (%d)\n\n",   iHeader->iUnpagedUncompressedSize);
+		
+		Print(ELog, "iExtensionRomHeader     :%d\n",     iExtensionRomHeader);
+		Print(ELog, "iCompressionType        :0x%08x\n", (iExtensionRomHeader ? iExtensionRomHeader->iCompressionType : iHeader->iCompressionType ));	
+		Print(ELog, "iCompressedSize         :0x%08x (%d)\n",     (iExtensionRomHeader ? iExtensionRomHeader->iCompressedSize  : iHeader->iCompressedSize ), (iExtensionRomHeader ? iExtensionRomHeader->iCompressedSize  : iHeader->iCompressedSize ));
+		Print(ELog, "iUncompressedSize       :0x%08x (%d)\n\n",   (iExtensionRomHeader ? iExtensionRomHeader->iUncompressedSize: iHeader->iUncompressedSize ), (iExtensionRomHeader ? iExtensionRomHeader->iUncompressedSize: iHeader->iUncompressedSize ));
+	
+		Print(ELog, "iPageableRomStart       :0x%08x (%d)\n",   iHeader->iPageableRomStart, iHeader->iPageableRomStart );
+		Print(ELog, "iPageableRomSize        :0x%08x (%d)\n",   iHeader->iPageableRomSize, iHeader->iPageableRomSize  );
+		Print(ELog, "iRomPageIndex           :0x%08x (%d)\n",   iHeader->iRomPageIndex, iHeader->iRomPageIndex );
+	
+		Print(ELog, "iSizeUsed               :0x%08x (%d)\n",   iSizeUsed, iSizeUsed );
+		Print(ELog, "Linear base address     :0x%08x\n",iHeader->iRomBase); 
+		Print(ELog, "Size:                    0x%08x\n",iHeader->iRomSize);
+		}
+
+	if ( gPagedRom && gCompressUnpaged)
+		{
+		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
+			Print(ELog, "Write out compressed un-paged and paged sections\n\n");
+		ImpTRomHeader* header = (ImpTRomHeader *)iHeader;
+		
+		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
+			{
+			Print(ELog, "Header:\n");
+			header->Display();
+			}
+		
+		streampos headerpos=os.tellp();
+		
+		// Write out uncompressed un-paged part (bootstrap + Page Index Table)
+		os.write((char *)(iHeader), iHeader->iCompressedUnpagedStart);
+		
+		// write out the compressed unpaged part
+		int srcsize=iHeader->iPageableRomStart - iHeader->iCompressedUnpagedStart;		
+		
+		int rawimagelen=DeflateCompressCheck(((char *)iHeader)+iHeader->iCompressedUnpagedStart,srcsize,os);
+		iHeader->iUnpagedCompressedSize = rawimagelen;
+		iHeader->iUnpagedUncompressedSize = srcsize ;
+		
+		// align to 4kbyte boundary if neccessary
+		TUint32 distanceFrom4kBoundary = ((~(iHeader->iCompressedUnpagedStart + rawimagelen /*+ sizeof(TRomLoaderHeader)*/ )) & 0xfff) + 1;
+		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
+			Print(ELog, "distanceFrom4kBoundary  :0x%08x (%d)\n", distanceFrom4kBoundary, distanceFrom4kBoundary);
+		char filer[0x1000];
+		memset( filer, 0, 0x1000);
+		os.write((char *)filer, distanceFrom4kBoundary);
+		
+		
+		// write out the paged part
+		os.write((char *)iHeader + iHeader->iPageableRomStart, ALIGN4K(iSizeUsed - iHeader->iPageableRomStart));
+		
+		// update size and compression information of paged-part
+		SetCompressionInfo(KUidCompressionDeflate, ALIGN4K(iSizeUsed), ALIGN4K(iUncompressedSize));
+		
+		// Calculate starting index of the Pageable Rom Start
+		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
+			{
+			Print(ELog, "iPageableRomStart				: %d (0x%08x)\n", iHeader->iPageableRomStart, iHeader->iPageableRomStart);
+			Print(ELog, "iCompressedUnpagedStart			: %d (0x%08x)\n", iHeader->iCompressedUnpagedStart, iHeader->iCompressedUnpagedStart);
+			Print(ELog, "rawimagelen						: %d (0x%08x)\n", rawimagelen, rawimagelen);
+			}
+		
+		TInt displacement = iHeader->iCompressedUnpagedStart + rawimagelen + distanceFrom4kBoundary; 
+		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
+			Print(ELog, "new iPageableRomStart			: %d (0x%08x)\n", (iHeader->iCompressedUnpagedStart + rawimagelen + distanceFrom4kBoundary), (iHeader->iCompressedUnpagedStart + rawimagelen + distanceFrom4kBoundary));
+		displacement = iHeader->iPageableRomStart-displacement;
+		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
+			Print(ELog, "displacement					: %d (0x%08x)\n", displacement, displacement);
+		
+		SRomPageInfo* pi = (SRomPageInfo*)((TInt)iHeader+iHeader->iRomPageIndex);
+		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
+			Print(ELog, "First Pageable page info[0x%08x]:(iDataStart:0x%08x, iDataSize:0x%08x (%d))\n\n", pi, pi->iDataStart, pi->iDataSize, pi->iDataSize);
+		
+		TInt startPageableIndex = (iHeader->iPageableRomStart) / (iObey->iPageSize);
+		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
+			{
+			Print(ELog, "iObey->iPageSize				: %d (0x%08x)\n", iObey->iPageSize, iObey->iPageSize);
+			Print(ELog, "startPageableIndex				: %d (0x%08x)\n", startPageableIndex, startPageableIndex);
+			}
+		pi += startPageableIndex;
+		
+		
+		while ( 0 != pi->iDataStart)
+			{
+				if (H.iVerbose) Print(ELog, "\t\tinfo[0x%08x]:(iDataStart:0x%08x, iDataSize:0x%08x (%d))\n\n", pi, pi->iDataStart, pi->iDataSize, pi->iDataSize);		
+				
+				pi->iDataStart -= displacement;
+				
+				if (H.iVerbose) Print(ELog, "\t\tinfo[0x%08x]:(iDataStart:0x%08x, iDataSize:0x%08x (%d))\n\n", pi, pi->iDataStart, pi->iDataSize, pi->iDataSize);		
+				
+				++pi;
+			}
+		
+		
+		
+		// Rewrite the header with updated info
+		#ifdef __TOOLS2__
+		os.seekp(headerpos); 
+		#else
+		os.seekp(headerpos,ios_base::beg);
+		#endif
+		
+		// Rewrite uncompressed un-paged part (bootstrap + Page Index Table)
+		os.write((char *)(iHeader), iHeader->iCompressedUnpagedStart);
+		
+		
+		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
+			{
+			Print(ELog, "iUnpagedCompressedSize  :0x%08x (%d)\n",     iHeader->iUnpagedCompressedSize, iHeader->iUnpagedCompressedSize);
+			Print(ELog, "iUnpagedUncompressedSize:0x%08x (%d)\n\n",   iHeader->iUnpagedUncompressedSize, iHeader->iUnpagedUncompressedSize);
+		
+			Print(ELog, "iCompressionType        :0x%08x\n", (iExtensionRomHeader ? iExtensionRomHeader->iCompressionType : iHeader->iCompressionType ));	
+			Print(ELog, "iCompressedSize         :0x%08x (%d)\n",     (iExtensionRomHeader ? iExtensionRomHeader->iCompressedSize  : iHeader->iCompressedSize ), (iExtensionRomHeader ? iExtensionRomHeader->iCompressedSize  : iHeader->iCompressedSize ));
+			Print(ELog, "iUncompressedSize       :0x%08x (%d)\n\n",   (iExtensionRomHeader ? iExtensionRomHeader->iUncompressedSize: iHeader->iUncompressedSize ), (iExtensionRomHeader ? iExtensionRomHeader->iUncompressedSize: iHeader->iUncompressedSize ));
+		
+			Print(ELog, "iPageableRomStart       :0x%08x (%d)\n",   iHeader->iPageableRomStart, iHeader->iPageableRomStart );
+			Print(ELog, "iPageableRomSize        :0x%08x (%d)\n",   iHeader->iPageableRomSize, iHeader->iPageableRomSize  );
+			Print(ELog, "iRomPageIndex           :0x%08x (%d)\n",   iHeader->iRomPageIndex, iHeader->iRomPageIndex );
+			Print(ELog, "\t\tinfo(iDataStart:0x%08x, iDataSize:0x%08x (%d))\n\n", pi->iDataStart, pi->iDataSize, pi->iDataSize);
+		
+			Print(ELog, "Linear base address:     %08x\n",iHeader->iRomBase); 
+			Print(ELog, "Size:                    %08x\n",iHeader->iRomSize);
+			}
+		
+		return;
+		}
+
+	if (!gEnableCompress || gPagedRom || !gCompressUnpaged)
+		{
+		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
+			Print(ELog, "Writeout uncompressed un-paged and paged sections2\n");
+		SetCompressionInfo(KFormatNotCompressed, ALIGN4K(iSizeUsed), ALIGN4K(iUncompressedSize));
+		iHeader->iUnpagedCompressedSize = ALIGN4K(iSizeUsed);
+		iHeader->iUnpagedUncompressedSize = ALIGN4K(iUncompressedSize);
+		
+		os.write((char *)iHeader, ALIGN4K(iSizeUsed));
+		
+		if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
+			{
+			Print(ELog, "iUnpagedCompressedSize  :0x%08x (%d)\n",     iHeader->iUnpagedCompressedSize);
+			Print(ELog, "iUnpagedUncompressedSize:0x%08x (%d)\n\n",   iHeader->iUnpagedUncompressedSize);
+		
+			Print(ELog, "iCompressionType        :0x%08x\n", (iExtensionRomHeader ? iExtensionRomHeader->iCompressionType : iHeader->iCompressionType ));	
+			Print(ELog, "iCompressedSize         :0x%08x (%d)\n",     (iExtensionRomHeader ? iExtensionRomHeader->iCompressedSize  : iHeader->iCompressedSize ), (iExtensionRomHeader ? iExtensionRomHeader->iCompressedSize  : iHeader->iCompressedSize ));
+			Print(ELog, "iUncompressedSize       :0x%08x (%d)\n\n",   (iExtensionRomHeader ? iExtensionRomHeader->iUncompressedSize: iHeader->iUncompressedSize ), (iExtensionRomHeader ? iExtensionRomHeader->iUncompressedSize: iHeader->iUncompressedSize ));
+		
+			Print(ELog, "iPageableRomStart       :0x%08x (%d)\n",   iHeader->iPageableRomStart, iHeader->iPageableRomStart );
+			Print(ELog, "iPageableRomSize        :0x%08x (%d)\n",   iHeader->iPageableRomSize, iHeader->iPageableRomSize  );
+			Print(ELog, "iRomPageIndex           :0x%08x (%d)\n",   iHeader->iRomPageIndex, iHeader->iRomPageIndex );
+			}
+		
+		return;
+		}
+
+	// compressed image without paging section
+	streampos headerpos=os.tellp();
+	int headersize=iExtensionRomHeader ? sizeof(TExtensionRomHeader) : sizeof(TRomHeader);
+
+	os.write(reinterpret_cast<char*>(iHeader), headersize); // write a dummy header
+	// compress the rest of the image
+	int srcsize=iSizeUsed - headersize;
+	int rawimagelen=DeflateCompressCheck(((char *)iHeader)+headersize,srcsize,os);
+	// write the compression info into the header
+	SetCompressionInfo(KUidCompressionDeflate, rawimagelen, iUncompressedSize); // doesn't need to be 4K aligned
+	iHeader->iCompressedUnpagedStart = headersize; 
+	iHeader->iUnpagedCompressedSize = rawimagelen;
+	iHeader->iUnpagedUncompressedSize = srcsize;
+		
+	#ifdef __TOOLS2__
+	os.seekp(headerpos); 
+	#else
+	os.seekp(headerpos,ios_base::beg);
+	#endif
+	os.write(reinterpret_cast<char*>(iHeader), headersize);	// write header again with (compressed) size info
+	
+	if (gLogLevel & LOG_LEVEL_COMPRESSION_INFO)
+		Print(ELog, "\tiSizeUsed:%d, iUncompressedSize:%d, headersize:%d, srcsize:%d, rawimagelen:%d \n",iSizeUsed, iUncompressedSize, headersize, srcsize, rawimagelen);
+	}
+
+TInt E32Rom::Compare(const char *aImage, TInt aHeaderType)
+	{
+	if (aHeaderType < 0)
+		aHeaderType = 1;
+	ifstream file(aImage, ios_base::binary);
+	if (!file)
+		return Print(EError, "Cannot open Rom image '%s' for verification\n", aImage);
+	Print(ELog, "\nVerifying ROM against image in %s\n", aImage);
+	switch (aHeaderType)
+		{
+	case 0:
+		break;
+	case 1:
+	default:
+		Print(ELog, "Skipping repro header\n");
+		file.seekg(sizeof(TRomLoaderHeader));
+		break;
+	case 2:
+		Print(ELog, "Skipping coff header\n");
+		file.seekg(0x58);
+		break;
+		}
+	TInt length=ALIGN4K(iSizeUsed);
+	if (iObey->iSectionStart != 0)
+		{
+		length = iObey->iSectionStart-iObey->iRomLinearBase;
+		Print(ELog, "Verifying first section (%08x bytes)... ", length);
+		}
+
+	TRomHeader compareHeader;
+	file.read((char *)&compareHeader, sizeof(TRomHeader));
+	// Arrange different settings for TRomHeader and
+	// TRomSectionHeader in the obey file
+	// For now just copy across the things that'll change
+	compareHeader.iVersion=iHeader->iVersion;
+	compareHeader.iTime=iHeader->iTime;
+	compareHeader.iTimeHi=(TUint32)(iHeader->iTime >> 32);
+	compareHeader.iCheckSum=iHeader->iCheckSum;
+	compareHeader.iLanguage=iHeader->iLanguage;
+
+	if (memcmp(&compareHeader, iHeader, sizeof(TRomHeader))!=0)
+		return Print(EError, "Verify failed.\nRom headers are different\n");
+
+	// Now compare the rest of the image (or first section)
+
+	TUint *ptr=(TUint *)(iHeader+1);
+	TInt i;
+	for (i=sizeof(TRomHeader); i<length; i+=4)
+		{
+		TUint a;
+		file.read((char *)&a, sizeof(TUint));
+		if (file.eof())
+			return Print(EError, "Verify failed.\nDifferent Rom sizes\n");
+		if (a!=*ptr)
+			return Print(EError, "Verify failed.\nContents differ at Rom address %08x\n", i+iObey->iRomLinearBase);
+		ptr++;
+		}
+	file.close();
+	Print(EAlways, "Verify OK\n");
+	return KErrNone;
+	}
+
+
+char* E32Rom::AllocateRelocationTable(char* aAddr, TReloc*& aRelocTable)
+	{
+	if(iObey->SetArea().Count() > 1)
+		{
+		aRelocTable = reinterpret_cast<TReloc*>(aAddr);
+
+		// Allocate one entry per non default area + 1 sentinel
+		// (Count() returns number of non default areas + 1 (the
+		// default area))
+		TInt size = iObey->SetArea().Count() * sizeof(TReloc);	
+		aAddr += Align(size);
+		}
+	else
+		{
+		aRelocTable = 0;
+		}
+
+	return aAddr;
+	}
+
+
+void E32Rom::FillInRelocationTable(TReloc* aRelocTable)
+	{
+	TReloc* p = aRelocTable;
+	TInt wastedBytes = 0;
+
+	for (NonDefaultAreasIterator areaIt(iObey->SetArea());
+		 ! areaIt.IsDone();
+		 areaIt.GoToNext())
+		{
+		Area& currentArea = areaIt.Current();
+
+		if (currentArea.UsedSize() > 0)
+			{
+			p->iLength = currentArea.UsedSize();
+			p->iSrc = currentArea.SrcBaseAddr();
+			p->iDest = currentArea.DestBaseAddr();
+			++p;
+			}
+		else
+			{
+			wastedBytes += sizeof(TReloc);
+			}
+		}
+
+	if (aRelocTable != 0)
+		{
+		// Last entry acts as a sentinel
+		memset(p, 0, sizeof(*p));
+		}
+
+	if (wastedBytes > 0)
+		{
+ 		Print(EWarning, "Some areas are declared but not used\n");
+ 		Print(EWarning, "%d bytes wasted in relocation table\n", wastedBytes);
+		}
+	}
+
+
+/**
+ Link together the kernel extensions.
+
+ Must be called only after space has been allocated in the ROM image
+ for the kernel extension.
+ */
+
+void E32Rom::LinkKernelExtensions(TRomBuilderEntry* aExtArray[], TInt aExtCount)
+	{
+	/**
+	 * The kernel extensions should never be linked together as part of extension ROMs.
+	 */
+	if (!iExtensionRomHeader)
+		{
+		TLinAddr* pLastNextExtAddr = &(iHeader->iExtensionFile);
+
+		for (TInt i=0; i<aExtCount; ++i)
+			{
+			TRomBuilderEntry* curExt = aExtArray[i];
+			*pLastNextExtAddr = ActualToRomAddress(curExt->RomEntry());
+			pLastNextExtAddr = &(curExt->iRomImageHeader->iNextExtension);
+			}
+	
+		*pLastNextExtAddr = 0;
+		}
+	}
+
+void E32Rom::ProcessDllData()
+	{
+		DllDataEntry *entry = iObey->GetFirstDllDataEntry();
+		TRomBuilderEntry	*romEntry;
+		TLinAddr* aExportTbl;
+		void	*aLocation;
+		TUint	aDataAddr;
+		while(entry){
+			// A Dll data may be patched either via the ordinal number (as in ABIv2), or via
+			// the address of the data field (as in ABIv1).
+			romEntry = entry->iRomNode->iRomFile->iRbEntry;
+			if((TInt)entry->iOrdinal != -1) { 
+				
+				// const data symbol may belong in the Code section. Get the address of the data field via the 
+				// export table. If the address lies within the Code or data section limits, 
+				// get the corresponding location and update it.While considering the Data section limits don't 
+				// include the Bss section, as it doesn't exist as yet in the image.
+				if(entry->iOrdinal < 1 || entry->iOrdinal > (TUint32)romEntry->iOrigHdr->iExportDirCount)
+				{
+					Print(EWarning, "Invalid ordinal %d specified for DLL %s\n", entry->iOrdinal, romEntry->iName);
+					entry = entry->NextDllDataEntry();
+					continue;
+				}
+				aExportTbl = (TLinAddr*)((char*)romEntry->iOrigHdr + romEntry->iOrigHdr->iExportDirOffset);
+				aDataAddr = (TInt32)(aExportTbl[entry->iOrdinal - 1] + entry->iOffset);
+				
+				if( (aDataAddr >= romEntry->iOrigHdr->iCodeBase) && 
+					(aDataAddr <= (TUint)(romEntry->iOrigHdr->iCodeBase + \
+										romEntry->iOrigHdr->iCodeSize)) )
+				{
+					char *aCodeSeg = (char*)((char*)romEntry->iOrigHdr + romEntry->iOrigHdr->iCodeOffset);
+					aLocation = (void*)(aCodeSeg + (aDataAddr - romEntry->iOrigHdr->iCodeBase));
+					memcpy(aLocation, &(entry->iNewValue), entry->iSize);
+				}
+				else if( (aDataAddr >= romEntry->iOrigHdr->iDataBase) && 
+					(aDataAddr <= (TUint)(romEntry->iOrigHdr->iDataBase + \
+										romEntry->iOrigHdr->iDataSize )) )
+				{
+					char *aDataSeg = (char*)((char*)romEntry->iOrigHdr + romEntry->iOrigHdr->iDataOffset);
+					aLocation = (void*)(aDataSeg + (aDataAddr - romEntry->iOrigHdr->iDataBase));
+					memcpy(aLocation, &(entry->iNewValue), entry->iSize);
+				}
+				else
+				{
+					Print(EWarning, "Patchdata failed as address pointed by ordinal %d of DLL %s doesn't lie within Code or Data section limits\n", entry->iOrdinal, romEntry->iName);
+				}
+				
+			}
+			else if((TInt)entry->iDataAddress != -1) { 
+				// const data symbol may belong in the Code section. If the address lies within the Code
+				// or data section limits, get the corresponding location and update it.While considering 
+				// the Data section limits don't include the Bss section, as it doesn't exist as yet in the image.
+				aDataAddr = (TUint)(entry->iDataAddress + entry->iOffset);
+				if( (aDataAddr >= romEntry->iOrigHdr->iCodeBase) && 
+					(aDataAddr <= (TUint)(romEntry->iOrigHdr->iCodeBase + \
+											romEntry->iOrigHdr->iCodeSize )) )
+				{
+					char *aCodeSeg = (char*)((char*)romEntry->iOrigHdr + romEntry->iOrigHdr->iCodeOffset);
+					aLocation = (void*)(aCodeSeg + (aDataAddr - romEntry->iOrigHdr->iCodeBase));
+					memcpy(aLocation, &(entry->iNewValue), entry->iSize);
+				}
+				else if( (aDataAddr   >= romEntry->iOrigHdr->iDataBase) && 
+					(aDataAddr <= (TUint)(romEntry->iOrigHdr->iDataBase + \
+											romEntry->iOrigHdr->iDataSize )) )
+				{
+					char *aDataSeg = (char*)((char*)romEntry->iOrigHdr + romEntry->iOrigHdr->iDataOffset);
+					aLocation = (void*)(aDataSeg + (aDataAddr - romEntry->iOrigHdr->iDataBase));
+					memcpy(aLocation, &(entry->iNewValue), entry->iSize);
+				}
+				else
+				{
+					Print(EWarning, "Patchdata failed as address 0x%x specified for DLL %s doesn't lie within Code or Data section limits\n", entry->iOrdinal, romEntry->iName);
+				}
+			}
+			else {
+			}
+			entry = entry->NextDllDataEntry();
+		}
+	}
+
+TInt E32Rom::CheckUnpagedMemSize()
+	{
+
+	if (H.iVerbose && gPagedRom)
+		{
+		Print(EDiagnostic, "iMaxUnpagedMemSize 0x%08x (%d)\n", iObey->iMaxUnpagedMemSize, iObey->iMaxUnpagedMemSize);
+		}
+		
+	// Only check if the iMaxUnpagedMemSize is set
+	if (iObey->iMaxUnpagedMemSize <= 0) return KErrNone;
+	
+	// Only for paged rom
+	if (!gPagedRom) 
+		{
+		Print(EWarning, "The unpaged size overflow check is skipped.\n");
+		return KErrNone;
+		}
+	
+	if (iHeader->iPageableRomStart > 0)
+		{
+		if (iHeader->iPageableRomStart > iObey->iMaxUnpagedMemSize) 
+			{
+			Print(EError, "Unpaged memory size overflow: require 0x%08x (%d) bytes while the maximum size is 0x%08x (%d) bytes\n",
+				iHeader->iPageableRomStart, 
+				iHeader->iPageableRomStart, 
+				iObey->iMaxUnpagedMemSize, 
+				iObey->iMaxUnpagedMemSize);
+			
+			return KErrNoMemory;
+			}
+		}
+	else
+		{
+		Print(EWarning, "The size of unpaged memory is not available. The unpaged memory overflow checking is skipped.\n");
+		}
+		
+	return KErrNone;
+}
+TRomNode* E32Rom::RootDirectory() const {
+	return iObey->iRootDirectory; 
+}
+const char* E32Rom::RomFileName() const {
+	return iObey->iRomFileName; 
+}
+TUint32 E32Rom::RomBase() const {
+	return iHeader->iRomBase; 
+}
+TUint32 E32Rom::RomSize() const {
+	return iHeader->iRomSize;
+}
+TVersion E32Rom::Version() const {
+	return iHeader->iVersion;
+}
+TInt64 E32Rom::Time() const {
+	return iHeader->iTime;
+}
+TUint32 E32Rom::CheckSum() const {
+	return iHeader->iCheckSum;
+}
+TUint32 E32Rom::DataRunAddress() const {
+	return iObey->iDataRunAddress;
+}
+TUint32 E32Rom::RomAlign() const {
+	return iObey->iRomAlign;
+}
--- a/imgtools/romtools/rombuild/r_rom.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_rom.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,621 +1,621 @@
-/*
-* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifndef __R_ROM_H__
-#define __R_ROM_H__
-
-#include "e32image.h"
-#include <e32rom.h>
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-#include <fstream>
-#else //!__MSVCDOTNET__
-#include <fstream.h>
-#endif //__MSVCDOTNET__
-#include <boost/thread/thread.hpp>
-#include <boost/thread/mutex.hpp>
-#include <queue>
-
-#include "h_utl.h"
-#include "r_mromimage.h"
-#include <malloc.h>
-
-
-//
-const TUint KRomWrapperSize = 0x100;
-const TUint KRomNameSize = 16;
-//
-const TUint KOverrideStack = 0x01;
-const TUint KOverrideHeapMin = 0x02;
-const TUint KOverrideHeapMax = 0x04;
-const TUint KOverrideAddress = 0x08;
-const TUint KOverrideUid1 = 0x10;
-const TUint KOverrideUid2 = 0x20;
-const TUint KOverrideUid3 = 0x40;
-const TUint KOverrideCallEntryPoint = 0x80;
-const TUint KOverrideNoCallEntryPoint = 0x100;
-const TUint KOverridePriority = 0x200;
-const TUint KOverrideStackReserve = 0x400;
-const TUint KOverrideKeepIAT = 0x800;
-const TUint KOverrideCapability = 0x1000;
-const TUint KOverrideCodeUnpaged = 0x2000;
-const TUint KOverrideCodePaged = 0x4000;
-const TUint KOverrideDataUnpaged = 0x8000;
-const TUint KOverrideDataPaged = 0x10000;
-const TUint KOverrideHCRData = 0x20000 ;
-
-enum TKernelModel {ESingleKernel, EMultipleKernels};
-enum TMemModel {E_MM_Moving, E_MM_Direct, E_MM_Multiple, E_MM_Flexible};
-
-class TRomBuilderEntry;
-class E32Rom;
-typedef queue<TRomBuilderEntry*> EntryQueue;
-
-const TUint KVariantIndependent = 0x01000000;
-
-extern TInt CompareCapabilities(const TUint32* aSubCaps, const TUint32* aSuperCaps, const char* aSubName, const char* aSuperName);
-
-class LoadImageWorker
-	{
-public:
-	static EntryQueue *m_queue;
-	static boost::mutex m_mutex;
-	static TInt m_errors;
-	static TMemModel m_memmodel;
-	LoadImageWorker(EntryQueue* aQueue, TMemModel aMemModel);
-	void operator()();
-	};
-class CompressPageWorker
-	{
-public:
-	static E32Rom* m_rom;
-	static TInt m_nextpage;
-	static TInt m_totalpages;
-	static TInt m_pagesize;
-	static boost::mutex m_mutex;
-	static TInt m_error;
-	CompressPageWorker(E32Rom* aRom, TInt aPageSize, TInt aTotalPages, TInt aNextPage);
-	void operator()();
-	};
-
-class THardwareVariant
-	{
-public:
-	enum THardwareVariantOrder
-		{
-		EUnordered=0,
-		ELess=1,
-		EEqual=2,
-		EGreater=4,
-		};
-public:
-	THardwareVariant() {iVariant=KVariantIndependent;}
-	THardwareVariant(TUint aVariant) {iVariant=aVariant;}
-	operator TUint() const {return iVariant;}
-	TBool MutuallyExclusive(THardwareVariant aHardwareVariant) const;
-	TInt Compare(THardwareVariant aHardwareVariant) const;
-	TBool operator<(THardwareVariant a) const { return ((Compare(a)&ELess)!=0); }
-	TBool operator==(THardwareVariant a) const { return ((Compare(a)&EEqual)!=0); }
-	TBool operator>(THardwareVariant a) const { return ((Compare(a)&EGreater)!=0); }
-	TBool operator<=(THardwareVariant a) const { return ((Compare(a)&(ELess|EEqual))!=0); }
-	TBool operator>=(THardwareVariant a) const { return ((Compare(a)&(EGreater|EEqual))!=0); }
-	TBool IsIndependent() const {return Layer()<=3;}
-	TBool IsCpu() const {return Parent()==3; }
-	TBool IsVariant() const;
-	TUint32 ReturnVariant() const {return iVariant;} 
-	TUint Layer() const {return iVariant>>24;}
-	TUint Parent() const {return (iVariant>>16)&0xff;}
-	TUint VMask() const {return iVariant&0xffff;}
-private:
-	TUint32 iVariant;
-	};
-
-class TRomLoad
-	{
-public:
-	TText name[KRomNameSize];
-	TText versionStr[4];
-	TText buildNumStr[4];
-	TUint romSize;
-	TUint wrapSize;
-	};
-//
-
-// representation of a relocation record for areas.
-class TReloc
-	{
-public:
-	TInt iLength;
-	TUint iSrc;
-	TUint iDest;
-	};
-
-// thing for tracking the various addresses at which to find something
-
-class TAddressRange
-	{
-public:
-	TAddressRange();
-
-	void Append(TAddressRange& aRange);
-	void Extend(TInt aOffset);
-	void Move(TInt aOffset);
-
-public:
-	TAny*	iImagePtr;			// data in the ROM image buffer
-	TUint32	iImageAddr;			// address in the ROM image 
-	TUint32 iRunAddr;			// runtime address, usually the same as the iImageAddr
-	TUint   iSize;				// size of this section
-	};
-
-
-class TImageSection : public TAddressRange
-	{
-public:
-	TImageSection() : TAddressRange(), iFilePtr(0) {}
-
-	TAny* iFilePtr;		// original data in the E32Image file
-
-	void Load() const;	// copy the file data into the image, if needed
-	};
-
-//
-const TUint KFillSize = KRomWrapperSize-sizeof(TRomLoad);
-class CObeyFile;
-class TRomLoaderHeader
-	{
-public:
-	void SetUp(CObeyFile *aObey);
-private:
-	TRomLoad r;
-	TUint8 filler[KFillSize];
-	};
-//
-class TRomBuilderEntry;
-class TRomNode;
-class TRomFile;
-class TDllFindInfo
-	{
-public:
-	TDllFindInfo(const char* aImportName, const TRomBuilderEntry* aEntry);
-	~TDllFindInfo();
-public:
-	const char* iBareName;		// filename+extension to find, not including path UID or version
-	TUint32 iUid3;				// requested UID3 - 0 if don't care
-	TUint32 iModuleVersion;		// requested version
-	TUint32 iHwVariant;			// requested hardware variant
-	};
-
-class TAutoFree
-	{
-public:
-	TAutoFree(void* aPtr) {iPtr=aPtr;}
-	~TAutoFree() {free(iPtr);}
-private:
-	void* iPtr;
-	};
-
-#define AUTO_FREE(p)	TAutoFree _auto_free_##p(p)
-
-class TModuleName
-	{
-public:
-	TModuleName(const TRomBuilderEntry* aEntry);
-	TModuleName(const TDllFindInfo& aInfo);
-	TModuleName(const TRomNode& aNode);
-	TModuleName(const TRomFile& aFile, const TRomNode* aRootDir);
-	~TModuleName();
-	operator const char* () {return iName;}
-private:
-	char* iName;
-	};
-
-// class representing a file (or directory) in the ROM
-class TRomFile
-	{
-public:
-	TRomFile();
-	~TRomFile();
-	TInt AddressFromOrdinal(TLinAddr& aEDataAddr,TLinAddr& aExport, TUint aOrdinal);
-	void Finalise(TInt aSize);
-
-	void Close() { if (--iRefCount<=0) delete this; };
-	void Open() {iRefCount++; };
-
-	TInt MarkDeps();
-	TInt FindRouteTo(TRomFile* aDest, TRomFile** aStack, TInt aIndex);
-	TRomEntry* RomEntry() const {return iRomEntry;}
-	void SetRomEntry(TRomEntry* aEntry);
-
-	TAddressRange iAddresses;
-
-	inline TRomImageHeader* RomImgHdr() const
-		{return (TRomImageHeader*)iAddresses.iImagePtr;}
-
-	TAddressRange iExportDir;
-	TRomBuilderEntry* iRbEntry;	// only until Layout stage
-	TBool iDir;
-	TBool iFinal;
-	THardwareVariant iHwvd;
-	TRomEntry* iRomEntry;		// in ROM image buffer
-	friend class FileEntry;
-
-	TInt iDataBssOffsetInExe;	// for allocating DLL data in process data section
-
-	// dependence graph
-	TInt iNumDeps;
-	TRomFile** iDeps;
-	TInt iNumPDeps;
-	TRomFile** iPDeps;
-	TInt iMark;
-	TRomFile* iAttachProcess;
-	TInt iTotalDataBss;
-
-	// Data used when computing SMP properties.
-	struct TSmpInfo
-		{
-		TSmpInfo() : isInit(0), isActive(0), isSafe(0) {}
-		bool isInit;
-		bool isActive;
-		bool isSafe;
-		} iSmpInfo;
-
-	bool ComputeSmpSafe(const TRomBuilderEntry*);
-public:
-	TUint32 Uid3() const;
-	TUint32 ModuleVersion() const;
-	THardwareVariant HardwareVariant() const;
-	TUint32 ABI() const;
-	TInt ExportDirCount() const;
-	TUint32 RomImageFlags() const;
-	TLinAddr DataBssLinearBase() const;
-	const SSecurityInfo& SecurityInfo() const;
-private:
-	TInt iRefCount;
-	};
-//
-class TRomBuilderEntry;
-class RomFileStructure;
-
-// class representing a directory entry in the ROM file system
-class TRomNode
-	{
-public:
-	TRomNode(const TText* aName, TRomBuilderEntry* aEntry=0);
-	TRomNode(const TText* aName, TRomNode* aNode);
-private:
-	TRomNode(const TRomNode& aNode);
-public:
-	~TRomNode();
-	void Destroy();
-
-	TInt SetAtt(TText *anAttWord);
-	TInt NameCpy(char* aDest); // returns the length of aDest (in UTF-16 characters for Unicode, not bytes)
-	TInt SetBareName();
-
-	TRomNode* NewSubDir(const TText* aName);
-	void AddFile(TRomNode *aChild);
-	TInt Rename(TRomNode *aOldParent, TRomNode* aNewParent, TText* aNewName);
-	TRomNode* FindInDirectory(const TText* aName);
-	TRomNode* FindInDirectory(const TText* aName, THardwareVariant aVariant , TBool aPatchDataFlag=FALSE);
-
-	TRomEntry* RomEntry() const {return iRomFile->RomEntry();}
-	void Finalise(TInt aSize);
-
-	void CountDirectory(TInt& aFileCount, TInt& aDirCount);
-	TInt ProcessDirectory(RomFileStructure* aRFS);
-
-	static void AddExecutableFile(TRomNode*& aLast, TRomNode* aNode);
-	TRomNode* FindImageFileByName(const TDllFindInfo& aInfo, TBool aPrintDiag, TBool& aFallBack);
-	TInt CheckForVersionConflicts(const TRomBuilderEntry* a);
-
-	TRomNode* CopyDirectory(TRomNode*& aLastExecutable, TRomNode* aParent);
-	TInt Alias(TRomNode* aNode, TRomNode*& aLastExecutable);
-public:
-	char* BareName() const;
-	TUint32 Uid3() const;
-	TUint32 ModuleVersion() const;
-	THardwareVariant HardwareVariant() const;
-	TUint32 ABI() const;
-	TInt FullNameLength(TBool aIgnoreHiddenAttrib = EFalse) const;
-	TInt GetFullName(char* aBuf, TBool aIgnoreHiddenAttrib = EFalse) const;
-
-	void Add(TRomNode* aChild);
-	void Remove(TRomNode* aChild);
-
-	static TInt Count;			// seed for unique identifiers
-
-	TRomNode* iSibling;
-	TRomNode* iChild;
-	TRomNode* iParent;
-	TRomNode* iNextExecutable;
-
-protected:
-	TInt iIdentifier;
-	friend class FileEntry;
-
-public:
-	TRomFile* iRomFile;
-	TText* iName;
-	char* iBareName;		// name including extension but without UID or version
-	TUint8 iAtt;
-	TBool iHidden;
-	};
-
-class E32Rom;
-class Area;
-class TRomBuilderEntry : public E32ImageFile
-	{
-public:
-	TRomBuilderEntry(const char *aFileName, TText *aName);
-	~TRomBuilderEntry();
-	TInt SetCodeAlignment(TText *aStr);
-	TInt SetDataAlignment(TText *aStr);
-	TInt SetRelocationAddress(TText *aStr);
-	TInt SetStackReserve(TText *aStr);
-	TInt SetStackSize(TText *aStr);
-	TInt SetHeapSizeMin(TText *aStr);
-	TInt SetHeapSizeMax(TText *aStr);
-	TInt SetCapability(TText *aStr);
-	TInt SetUid1(TText *aStr);
-	TInt SetUid2(TText *aStr);
-	TInt SetUid3(TText *aStr);
-	TInt SetCallEntryPoint(TBool aState);
-	TInt SetPriority(TText *aStr);
-	TInt SetAttachProcess(TText *aStr);
-	TInt OpenImageFile();
-	TInt SizeInRom();
-	void SizeInSections(TInt& aSize1, TInt& aSize2);
-	void LoadToRom();
-	TInt FixupImports(E32Rom& aRom);
-	TInt ResolveDllRefTable(E32Rom& aRom);
-	TInt BuildDependenceGraph(E32Rom& aRom);
-	TInt FindAttachProcess(E32Rom& aRom);
-	const char* GetDefaultAttachProcess();
-	void SetRomNode(TRomNode* aNode);
-	void FixupRomEntries(TInt aSize);
-	TRomEntry* RomEntry() const {return iRomNode->RomEntry(); };
-	void DisplaySize(TPrintType aWhere);
-public:
-	inline TBool Primary() const
-		{return iRomImageFlags & KRomImageFlagPrimary;}
-	inline TBool Variant() const
-		{return iRomImageFlags & KRomImageFlagVariant;}
-	inline TBool Extension() const
-		{return iRomImageFlags & KRomImageFlagExtension;}
-	inline TBool Device() const
-		{return iRomImageFlags & KRomImageFlagDevice;}
-	inline TBool Secondary() const
-		{return iRomImageFlags & KRomImageFlagSecondary;}
-	inline TBool HCRDataFile() const 
-		{ return iOverrideFlags & KOverrideHCRData ;}
-private:
-	TRomBuilderEntry();
-	TRomBuilderEntry(const TRomBuilderEntry&);
-	const TRomBuilderEntry& operator=(const TRomBuilderEntry &);
-	void Relocate();
-public:
-	TText *iName;
-	TBool iResource;
-	TBool iNonXIP;
-	TBool iPreferred;
-	TUint iCompression;
-	TBool iPatched;
-	Area* iArea;
-	TInt  iRomSectionNumber;
-	TUint iOverrideFlags;
-	TUint32 iRelocationAddress;
-	TInt iAlignment;
-	TInt iCodeAlignment;
-	TInt iDataAlignment;
-	TInt iStackSize;
-	TInt iHeapSizeMin;
-	TInt iHeapSizeMax;
-	TProcessPriority iPriority;
-	TUint iUid1;
-	TUint iUid2;
-	TUint iUid3;
-	TLinAddr iDataBssLinearBase;
-	SSecurityInfo iS;
-	char* iBareName;			// EPOC name+extension but without path or version
-	TUint32 iVersionInName;
-	TUint32 iVersionPresentInName;
-
-	THardwareVariant iHardwareVariant;
-	TUint iDataBssOffset;
-	TInt iStackReserve;
-
-	TRomImageHeader* iRomImageHeader;
-
-	TAddressRange iHeaderRange;
-	TImageSection iCodeSection;
-	TImageSection iImportAddressTableSection;
-	TImageSection iExportDirSection;
-	TImageSection iDataSection;
-	TAddressRange iDllRefTableRange;
-
-	TLinAddr**  iIATRefs;	// image addresses of pointers to IAT
-
-	TRomBuilderEntry* iNext;
-	TRomBuilderEntry* iNextInArea;
-
-	TUint32 iRomImageFlags;
-	TText* iProcessName;
-
-	// Used by the collapse routines
-	TInt iImportCount;
-	TUint32 iImportBlockStartAddress;
-	TUint32 iImportBlockEndAddress;
-	TRomNode *iRomNode;
-	};
-//
-class ImpTRomHeader	: public TRomHeader
-	{
-public:
-	void Display();
-	void SetUp(CObeyFile *aObey);
-	void CheckSum(TUint32 aTargetValue);
-	};
-//
-class COrderedFileList
-	{
-public:
-	static COrderedFileList* New(TInt aMaxFiles);
-	~COrderedFileList();
-	void Add(TRomBuilderEntry* anEntry);
-	TInt Count() {return iCount;}
-	TRomBuilderEntry* operator[](TInt anIndex) {return iOrderedFiles[anIndex];}
-private:
-	COrderedFileList(TInt aMaxFiles);
-private:
-	TInt iCount;
-	TInt iMaxFiles;
-	TRomBuilderEntry **iOrderedFiles;
-	};
-//
-class CObeyFile;
-class Area;
-class Memmap;
-class E32Rom : public MRomImage
-	{
-public:
-	E32Rom(CObeyFile *aObey);
-	~E32Rom();
-	TInt Create();
-	TInt CreateExtension(MRomImage* aKernelRom);
-	TInt Align(TInt aVal);
-	void DisplaySizes(TPrintType aWhere);
-	TInt WriteImages(TInt aHeaderType);
-	TInt Compare(char* anImage, TInt aHeaderType);
-	//
-	//
-	char *RomToActualAddress(TUint aPtr);
-	TUint ActualToRomAddress(TAny *aPtr);
-	void Display(TRomImageHeader *aHdr);
-	TRomNode* FindImageFileByName(const TDllFindInfo& aInfo, TBool aPrintDiag, TBool& aFallBack);
-	TInt CheckForVersionConflicts(const TRomBuilderEntry* a);
-	TRomNode* CopyDirectory(TRomNode*& aLastExecutable);
-
-	TRomNode* RootDirectory();
-	TText* RomFileName();
-	TUint32 RomBase();
-	TUint32 RomSize();
-	TVersion Version();
-	TInt64 Time();
-	TUint32 CheckSum();
-	TUint32 DataRunAddress();
-	TUint32 RomAlign();
-
-private:
-	void CalculateDataAddresses();
-	void CalculateDataAddress(TRomBuilderEntry *aFile);
-	char *LayoutRom(char *anAddr);
-	char *ReserveRomExceptionSearchTable(char *anAddr, TRomExceptionSearchTable*& exceptionSearchTable);
-	void ConstructRomExceptionSearchTable(TRomExceptionSearchTable* exceptionSearchTable);
-	void LayoutFile(TRomBuilderEntry*, TAddressRange& aMain, TAddressRange* aSecond, CBytePair* aBPE);
-	void NextRom(TAddressRange* aFirst, TAddressRange* aSecond);
-	TInt TranslateFiles();
-	void EnumerateVariants();
-	TUint32 AlignToChunk(TUint32 anAddr);
-	TUint32 AlignToPage(TUint32 anAddr);
-	TUint32 AllocVirtual(TUint32 aAddr,TUint aSize);
-	TInt LoadDataToRom(TRomBuilderEntry *aFile, TAddressRange& aAddress, CBytePair* aBPE);
-	void LoadFileToRom(TRomBuilderEntry *aFile);
-
-	void Write(ofstream &of, TInt aHeaderType);		// main ROM image
-	void WriteOdd(ofstream &of);					// odd halfwords
-	void WriteEven(ofstream &of);					// even halfwords
-	void WriteSRecord(ofstream &of);				// SREC or S19 format
-
-	TInt LoadContents(char*& anAddr, TRomHeader* aHeader);
-	TInt BuildDependenceGraph();
-	TInt ResolveDllRefTables();
-	TInt ResolveImports();
-	TInt CreateExportDirectory();
-	char *WriteDirectory(char *aAddr, TRomHeader* aHeader);
-	TInt WriteHeadersToRom(char *anAddr);
-	TInt RequiredSize();
-	void SetCompressionInfo(TUint aCompressionType, TUint aCompressedSize, TUint aUncompressedSize);
-	void FinaliseSectionHeader();
-	void FinaliseExtensionHeader(MRomImage* aKernelRom);
-	void DisplayExtensionHeader();
-	void SetImageAddr(TAddressRange& aSet, TAny* aPtr, TUint32 aRunOffset=0);
-	void SetImageAddr(TAddressRange& aSet, TUint aAddr, TUint32 aRunOffset=0);
-	TInt CollapseImportThunks();
-	TInt CollapseImportThunks(TRomBuilderEntry* aFile);
-	TInt CollapseBranches();
-	TInt CollapseBranches(TRomBuilderEntry* aFile);
-	TUint32 FindFinalJumpDestination(TUint32 ja);
-
-	char* AllocateRelocationTable(char* aAddr, TReloc*& aRelocTable);
-	void FillInRelocationTable(TReloc* aRelocTable);
-
-	void LinkKernelExtensions(TRomBuilderEntry* aExtArray[], TInt aExtCount);
-	void FillInCrcs();
-	void ProcessDllData();
-
-	void CreatePageIndex(char*& aAddr);
-	TInt CompressPages();
-	TInt CompressPage(SRomPageInfo& aPageInfo, TInt aOutOffset, CBytePair * aBPE);
-
-	// dependence graph
-	void UnmarkGraph(TInt aMark=0xffffffff);
-	void FindMarked(TInt aMarkMask, TInt aMark, TRomFile**& aList);
-	TInt ProcessDependencies();
-	void ListRouteTo(TRomFile* aStart, TRomFile* aDest, TInt aNDeps);
-
-	void SetSmpFlags();
-	
-	// Check if the unpaged memory size overflows. For page enabled ROM only.
-	TInt CheckUnpagedMemSize();
-	
-	// Initialize the page info prior to compression
-	TInt SetupPages();
-
-	Memmap *iImageMap;
-public:
-	char* iData;
-	TInt iSize;
-	TRomLoaderHeader *iLoaderHeader;
-	TRomHeader *iHeader;
-	TExtensionRomHeader *iExtensionRomHeader;		// NULL if not extension ROM
-	//
-	CObeyFile *iObey;
-
-	char *iSectionPtr;
-	
-	//
-	TInt iSizeUsed;
-	TInt iUncompressedSize;
-	TInt iOverhead;
-	TInt iDirectorySize;
-	TInt iImportsFixedUp;
-	TInt iBranchesFixedUp;
-	TInt iVtableEntriesFixedUp;
-	//
-	TUint32 iNextDataChunkBase;
-	TUint32 iTotalSvDataSize;
-	TUint32 iNextDllDataAddr;
-	char* iPrevPrimaryAddress;
-	char* iPrevVariantAddress;
-	COrderedFileList** iVariantFileLists;
-	TRomBuilderEntry** iPeFiles;
-	};
-
-
-#endif
+/*
+* Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifndef __R_ROM_H__
+#define __R_ROM_H__
+
+#include "e32image.h"
+#include <e32rom.h>
+
+ 
+#include <fstream> 
+#include <boost/thread/thread.hpp>
+#include <boost/thread/mutex.hpp>
+#include <queue>
+
+#include "h_utl.h"
+#include "r_mromimage.h"
+#include <malloc.h>
+
+
+//
+const TUint KRomWrapperSize = 0x100;
+const TUint KRomNameSize = 16;
+//
+const TUint KOverrideStack = 0x01;
+const TUint KOverrideHeapMin = 0x02;
+const TUint KOverrideHeapMax = 0x04;
+const TUint KOverrideAddress = 0x08;
+const TUint KOverrideUid1 = 0x10;
+const TUint KOverrideUid2 = 0x20;
+const TUint KOverrideUid3 = 0x40;
+const TUint KOverrideCallEntryPoint = 0x80;
+const TUint KOverrideNoCallEntryPoint = 0x100;
+const TUint KOverridePriority = 0x200;
+const TUint KOverrideStackReserve = 0x400;
+const TUint KOverrideKeepIAT = 0x800;
+const TUint KOverrideCapability = 0x1000;
+const TUint KOverrideCodeUnpaged = 0x2000;
+const TUint KOverrideCodePaged = 0x4000;
+const TUint KOverrideDataUnpaged = 0x8000;
+const TUint KOverrideDataPaged = 0x10000;
+const TUint KOverrideHCRData = 0x20000 ;
+
+enum TKernelModel {ESingleKernel, EMultipleKernels};
+enum TMemModel {E_MM_Moving, E_MM_Direct, E_MM_Multiple, E_MM_Flexible};
+
+class TRomBuilderEntry;
+class E32Rom;
+typedef queue<TRomBuilderEntry*> EntryQueue;
+
+const TUint KVariantIndependent = 0x01000000;
+
+extern TInt CompareCapabilities(const TUint32* aSubCaps, const TUint32* aSuperCaps, const char* aSubName, const char* aSuperName);
+
+class LoadImageWorker
+	{
+public:
+	static EntryQueue *m_queue;
+	static boost::mutex m_mutex;
+	static TInt m_errors;
+	static TMemModel m_memmodel;
+	LoadImageWorker(EntryQueue* aQueue, TMemModel aMemModel);
+	void operator()();
+	};
+class CompressPageWorker
+	{
+public:
+	static E32Rom* m_rom;
+	static TInt m_nextpage;
+	static TInt m_totalpages;
+	static TInt m_pagesize;
+	static boost::mutex m_mutex;
+	static TInt m_error;
+	CompressPageWorker(E32Rom* aRom, TInt aPageSize, TInt aTotalPages, TInt aNextPage);
+	void operator()();
+	};
+
+class THardwareVariant
+	{
+public:
+	enum THardwareVariantOrder
+		{
+		EUnordered=0,
+		ELess=1,
+		EEqual=2,
+		EGreater=4,
+		};
+public:
+	THardwareVariant() {iVariant=KVariantIndependent;}
+	THardwareVariant(TUint aVariant) {iVariant=aVariant;}
+	operator TUint() const {return iVariant;}
+	TBool MutuallyExclusive(THardwareVariant aHardwareVariant) const;
+	TInt Compare(THardwareVariant aHardwareVariant) const;
+	TBool operator<(THardwareVariant a) const { return ((Compare(a)&ELess)!=0); }
+	TBool operator==(THardwareVariant a) const { return ((Compare(a)&EEqual)!=0); }
+	TBool operator>(THardwareVariant a) const { return ((Compare(a)&EGreater)!=0); }
+	TBool operator<=(THardwareVariant a) const { return ((Compare(a)&(ELess|EEqual))!=0); }
+	TBool operator>=(THardwareVariant a) const { return ((Compare(a)&(EGreater|EEqual))!=0); }
+	TBool IsIndependent() const {return Layer()<=3;}
+	TBool IsCpu() const {return Parent()==3; }
+	TBool IsVariant() const;
+	TUint32 ReturnVariant() const {return iVariant;} 
+	TUint Layer() const {return iVariant>>24;}
+	TUint Parent() const {return (iVariant>>16)&0xff;}
+	TUint VMask() const {return iVariant&0xffff;}
+private:
+	TUint32 iVariant;
+	};
+
+class TRomLoad
+	{
+public:
+	char name[KRomNameSize];
+	char versionStr[4];
+	char buildNumStr[4];
+	TUint romSize;
+	TUint wrapSize;
+	};
+//
+
+// representation of a relocation record for areas.
+class TReloc
+	{
+public:
+	TInt iLength;
+	TUint iSrc;
+	TUint iDest;
+	};
+
+// thing for tracking the various addresses at which to find something
+
+class TAddressRange
+	{
+public:
+	TAddressRange();
+
+	void Append(TAddressRange& aRange);
+	void Extend(TInt aOffset);
+	void Move(TInt aOffset);
+
+public:
+	TAny*	iImagePtr;			// data in the ROM image buffer
+	TUint32	iImageAddr;			// address in the ROM image 
+	TUint32 iRunAddr;			// runtime address, usually the same as the iImageAddr
+	TUint   iSize;				// size of this section
+	};
+
+
+class TImageSection : public TAddressRange
+	{
+public:
+	TImageSection() : TAddressRange(), iFilePtr(0) {}
+
+	TAny* iFilePtr;		// original data in the E32Image file
+
+	void Load() const;	// copy the file data into the image, if needed
+	};
+
+//
+const TUint KFillSize = KRomWrapperSize-sizeof(TRomLoad);
+class CObeyFile;
+class TRomLoaderHeader
+	{
+public:
+	void SetUp(CObeyFile *aObey);
+private:
+	TRomLoad r;
+	TUint8 filler[KFillSize];
+	};
+//
+class TRomBuilderEntry;
+class TRomNode;
+class TRomFile;
+class TDllFindInfo
+	{
+public:
+	TDllFindInfo(const char* aImportName, const TRomBuilderEntry* aEntry);
+	~TDllFindInfo();
+public:
+	const char* iBareName;		// filename+extension to find, not including path UID or version
+	TUint32 iUid3;				// requested UID3 - 0 if don't care
+	TUint32 iModuleVersion;		// requested version
+	TUint32 iHwVariant;			// requested hardware variant
+	};
+
+class TAutoFree
+	{
+public:
+	TAutoFree(void* aPtr) {iPtr=aPtr;}
+	~TAutoFree() {free(iPtr);}
+private:
+	void* iPtr;
+	};
+
+#define AUTO_FREE(p)	TAutoFree _auto_free_##p(p)
+
+class TModuleName
+	{
+public:
+	TModuleName(const TRomBuilderEntry* aEntry);
+	TModuleName(const TDllFindInfo& aInfo);
+	TModuleName(const TRomNode& aNode);
+	TModuleName(const TRomFile& aFile, const TRomNode* aRootDir);
+	~TModuleName();
+	operator const char* () {return iName;}
+private:
+	char* iName;
+	};
+
+// class representing a file (or directory) in the ROM
+class TRomFile
+	{
+public:
+	TRomFile();
+	~TRomFile();
+	TInt AddressFromOrdinal(TLinAddr& aEDataAddr,TLinAddr& aExport, TUint aOrdinal);
+	void Finalise(TInt aSize);
+
+	void Close() { if (--iRefCount<=0) delete this; };
+	void Open() {iRefCount++; };
+
+	TInt MarkDeps();
+	TInt FindRouteTo(TRomFile* aDest, TRomFile** aStack, TInt aIndex);
+	TRomEntry* RomEntry() const {return iRomEntry;}
+	void SetRomEntry(TRomEntry* aEntry);
+
+	TAddressRange iAddresses;
+
+	inline TRomImageHeader* RomImgHdr() const
+		{return (TRomImageHeader*)iAddresses.iImagePtr;}
+
+	TAddressRange iExportDir;
+	TRomBuilderEntry* iRbEntry;	// only until Layout stage
+	TBool iDir;
+	TBool iFinal;
+	THardwareVariant iHwvd;
+	TRomEntry* iRomEntry;		// in ROM image buffer
+	friend class FileEntry;
+
+	TInt iDataBssOffsetInExe;	// for allocating DLL data in process data section
+
+	// dependence graph
+	TInt iNumDeps;
+	TRomFile** iDeps;
+	TInt iNumPDeps;
+	TRomFile** iPDeps;
+	TInt iMark;
+	TRomFile* iAttachProcess;
+	TInt iTotalDataBss;
+
+	// Data used when computing SMP properties.
+	struct TSmpInfo
+		{
+		TSmpInfo() : isInit(0), isActive(0), isSafe(0) {}
+		bool isInit;
+		bool isActive;
+		bool isSafe;
+		} iSmpInfo;
+
+	bool ComputeSmpSafe(const TRomBuilderEntry*);
+public:
+	TUint32 Uid3() const;
+	TUint32 ModuleVersion() const;
+	THardwareVariant HardwareVariant() const;
+	TUint32 ABI() const;
+	TInt ExportDirCount() const;
+	TUint32 RomImageFlags() const;
+	TLinAddr DataBssLinearBase() const;
+	const SSecurityInfo& SecurityInfo() const;
+private:
+	TInt iRefCount;
+	};
+//
+class TRomBuilderEntry;
+class RomFileStructure;
+
+// class representing a directory entry in the ROM file system
+class TRomNode
+	{
+public:
+	TRomNode(const char* aName, TRomBuilderEntry* aEntry=0);
+	TRomNode(const char* aName, TRomNode* aNode);
+private:
+	TRomNode(const TRomNode& aNode);
+public:
+	~TRomNode();
+	void Destroy();
+
+	TInt SetAtt(const char* anAttWord);
+	//TInt NameCpy(const char* aDest); // returns the length of aDest (in UTF-16 characters for Unicode, not bytes)
+	TInt SetBareName();
+
+	TRomNode* NewSubDir(const char* aName);
+	void AddFile(TRomNode *aChild);
+	TInt Rename(TRomNode *aOldParent, TRomNode* aNewParent, const char* aNewName);
+	TRomNode* FindInDirectory(const char* aName);
+	TRomNode* FindInDirectory(const char* aName, THardwareVariant aVariant , TBool aPatchDataFlag=FALSE);
+
+	TRomEntry* RomEntry() const {return iRomFile->RomEntry();}
+	void Finalise(TInt aSize);
+
+	void CountDirectory(TInt& aFileCount, TInt& aDirCount);
+	TInt ProcessDirectory(RomFileStructure* aRFS);
+
+	static void AddExecutableFile(TRomNode*& aLast, TRomNode* aNode);
+	TRomNode* FindImageFileByName(const TDllFindInfo& aInfo, TBool aPrintDiag, TBool& aFallBack);
+	TInt CheckForVersionConflicts(const TRomBuilderEntry* a);
+
+	TRomNode* CopyDirectory(TRomNode*& aLastExecutable, TRomNode* aParent);
+	TInt Alias(TRomNode* aNode, TRomNode*& aLastExecutable);
+public:
+	const char* BareName() const;
+	TUint32 Uid3() const;
+	TUint32 ModuleVersion() const;
+	THardwareVariant HardwareVariant() const;
+	TUint32 ABI() const;
+	TInt FullNameLength(TBool aIgnoreHiddenAttrib = EFalse) const;
+	TInt GetFullName(char* aBuf, TBool aIgnoreHiddenAttrib = EFalse) const;
+
+	void Add(TRomNode* aChild);
+	void Remove(TRomNode* aChild);
+
+	static TInt Count;			// seed for unique identifiers
+
+	TRomNode* iSibling;
+	TRomNode* iChild;
+	TRomNode* iParent;
+	TRomNode* iNextExecutable;
+
+protected:
+	TInt iIdentifier;
+	friend class FileEntry;
+
+public:
+	TRomFile* iRomFile;
+	char* iName;
+	char* iBareName;		// name including extension but without UID or version
+	TUint8 iAtt;
+	TBool iHidden;
+	};
+
+class E32Rom;
+class Area;
+class TRomBuilderEntry : public E32ImageFile
+	{
+public:
+	TRomBuilderEntry(const char *aFileName, const char* aName);
+	~TRomBuilderEntry();
+	TInt SetCodeAlignment(const char* aStr);
+	TInt SetDataAlignment(const char* aStr);
+	TInt SetRelocationAddress(const char* aStr);
+	TInt SetStackReserve(const char* aStr);
+	TInt SetStackSize(const char* aStr);
+	TInt SetHeapSizeMin(const char* aStr);
+	TInt SetHeapSizeMax(const char* aStr);
+	TInt SetCapability(const char* aStr);
+	TInt SetUid1(const char* aStr);
+	TInt SetUid2(const char* aStr);
+	TInt SetUid3(const char* aStr);
+	TInt SetCallEntryPoint(TBool aState);
+	TInt SetPriority(const char* aStr);
+	TInt SetAttachProcess(const char* aStr);
+	TInt OpenImageFile();
+	TInt GetImageFileInfo(TInt aResult);
+	TInt SizeInRom();
+	void SizeInSections(TInt& aSize1, TInt& aSize2);
+	void LoadToRom();
+	TInt FixupImports(E32Rom& aRom);
+	TInt ResolveDllRefTable(E32Rom& aRom);
+	TInt BuildDependenceGraph(E32Rom& aRom);
+	TInt FindAttachProcess(E32Rom& aRom);
+	const char* GetDefaultAttachProcess();
+	void SetRomNode(TRomNode* aNode);
+	void FixupRomEntries(TInt aSize);
+	TRomEntry* RomEntry() const {return iRomNode->RomEntry(); };
+	void DisplaySize(TPrintType aWhere);
+public:
+	inline TBool Primary() const
+		{return iRomImageFlags & KRomImageFlagPrimary;}
+	inline TBool Variant() const
+		{return iRomImageFlags & KRomImageFlagVariant;}
+	inline TBool Extension() const
+		{return iRomImageFlags & KRomImageFlagExtension;}
+	inline TBool Device() const
+		{return iRomImageFlags & KRomImageFlagDevice;}
+	inline TBool Secondary() const
+		{return iRomImageFlags & KRomImageFlagSecondary;}
+	inline TBool HCRDataFile() const 
+		{ return iOverrideFlags & KOverrideHCRData ;}
+private:
+	TRomBuilderEntry();
+	TRomBuilderEntry(const TRomBuilderEntry&);
+	const TRomBuilderEntry& operator=(const TRomBuilderEntry &);
+	void Relocate();
+public:
+	char *iName;
+	TBool iResource;
+	TBool iNonXIP;
+	TBool iPreferred;
+	TUint iCompression;
+	TBool iPatched;
+	Area* iArea;
+	TInt  iRomSectionNumber;
+	TUint iOverrideFlags;
+	TUint32 iRelocationAddress;
+	TInt iAlignment;
+	TInt iCodeAlignment;
+	TInt iDataAlignment;
+	TInt iStackSize;
+	TInt iHeapSizeMin;
+	TInt iHeapSizeMax;
+	TProcessPriority iPriority;
+	TUint iUid1;
+	TUint iUid2;
+	TUint iUid3;
+	TLinAddr iDataBssLinearBase;
+	SSecurityInfo iS;
+	char* iBareName;			// EPOC name+extension but without path or version
+	TUint32 iVersionInName;
+	TUint32 iVersionPresentInName;
+
+	THardwareVariant iHardwareVariant;
+	TUint iDataBssOffset;
+	TInt iStackReserve;
+
+	TRomImageHeader* iRomImageHeader;
+
+	TAddressRange iHeaderRange;
+	TImageSection iCodeSection;
+	TImageSection iImportAddressTableSection;
+	TImageSection iExportDirSection;
+	TImageSection iDataSection;
+	TAddressRange iDllRefTableRange;
+
+	TLinAddr**  iIATRefs;	// image addresses of pointers to IAT
+
+	TRomBuilderEntry* iNext;
+	TRomBuilderEntry* iNextInArea;
+
+	TUint32 iRomImageFlags;
+	char* iProcessName;
+
+	// Used by the collapse routines
+	TInt iImportCount;
+	TUint32 iImportBlockStartAddress;
+	TUint32 iImportBlockEndAddress;
+	TRomNode *iRomNode;
+	};
+//
+class ImpTRomHeader	: public TRomHeader
+	{
+public:
+	void Display();
+	void SetUp(CObeyFile *aObey);
+	void CheckSum(TUint32 aTargetValue);
+	};
+//
+class COrderedFileList
+	{
+public:
+	static COrderedFileList* New(TInt aMaxFiles);
+	~COrderedFileList();
+	void Add(TRomBuilderEntry* anEntry);
+	TInt Count() {return iCount;}
+	TRomBuilderEntry* operator[](TInt anIndex) {return iOrderedFiles[anIndex];}
+private:
+	COrderedFileList(TInt aMaxFiles);
+private:
+	TInt iCount;
+	TInt iMaxFiles;
+	TRomBuilderEntry **iOrderedFiles;
+	};
+//
+class CObeyFile;
+class Area;
+class Memmap;
+class SymbolGenerator;
+class E32Rom : public MRomImage
+	{
+public:
+	E32Rom(CObeyFile *aObey);
+	virtual ~E32Rom();
+	TInt Create();
+	TInt CreateExtension(MRomImage* aKernelRom);
+	TInt Align(TInt aVal);
+	void DisplaySizes(TPrintType aWhere);
+	TInt WriteImages(TInt aHeaderType);
+	TInt Compare(const char* aImage, TInt aHeaderType);
+	//
+	//
+	char *RomToActualAddress(TUint aPtr);
+	TUint ActualToRomAddress(TAny *aPtr);
+	void Display(TRomImageHeader *aHdr);
+	TRomNode* FindImageFileByName(const TDllFindInfo& aInfo, TBool aPrintDiag, TBool& aFallBack);
+	TInt CheckForVersionConflicts(const TRomBuilderEntry* a);
+	TRomNode* CopyDirectory(TRomNode*& aLastExecutable);
+	
+	TRomNode* RootDirectory() const ;
+	const char* RomFileName() const ;
+	TUint32 RomBase() const ;
+	TUint32 RomSize() const ;
+	TVersion Version() const ;
+	TInt64 Time() const ;
+	TUint32 CheckSum() const ;
+	TUint32 DataRunAddress() const ;
+	TUint32 RomAlign() const ;
+
+private:
+	void CalculateDataAddresses();
+	void CalculateDataAddress(TRomBuilderEntry *aFile);
+	char *LayoutRom(char *anAddr);
+	char *ReserveRomExceptionSearchTable(char *anAddr, TRomExceptionSearchTable*& exceptionSearchTable);
+	void ConstructRomExceptionSearchTable(TRomExceptionSearchTable* exceptionSearchTable);
+	void LayoutFile(TRomBuilderEntry*, TAddressRange& aMain, TAddressRange* aSecond, CBytePair* aBPE);
+	void NextRom(TAddressRange* aFirst, TAddressRange* aSecond);
+	TInt TranslateFiles();
+	void EnumerateVariants();
+	TUint32 AlignToChunk(TUint32 anAddr);
+	TUint32 AlignToPage(TUint32 anAddr);
+	TUint32 AllocVirtual(TUint32 aAddr,TUint aSize);
+	TInt LoadDataToRom(TRomBuilderEntry *aFile, TAddressRange& aAddress, CBytePair* aBPE);
+	void LoadFileToRom(TRomBuilderEntry *aFile);
+
+	void Write(ofstream &of, TInt aHeaderType);		// main ROM image
+	void WriteOdd(ofstream &of);					// odd halfwords
+	void WriteEven(ofstream &of);					// even halfwords
+	void WriteSRecord(ofstream &of);				// SREC or S19 format
+
+	TInt LoadContents(char*& anAddr, TRomHeader* aHeader);
+	TInt BuildDependenceGraph();
+	TInt ResolveDllRefTables();
+	TInt ResolveImports();
+	TInt CreateExportDirectory();
+	char *WriteDirectory(char *aAddr, TRomHeader* aHeader);
+	TInt WriteHeadersToRom(char *anAddr);
+	TInt RequiredSize();
+	void SetCompressionInfo(TUint aCompressionType, TUint aCompressedSize, TUint aUncompressedSize);
+	void FinaliseSectionHeader();
+	void FinaliseExtensionHeader(MRomImage* aKernelRom);
+	void DisplayExtensionHeader();
+	void SetImageAddr(TAddressRange& aSet, TAny* aPtr, TUint32 aRunOffset=0);
+	void SetImageAddr(TAddressRange& aSet, TUint aAddr, TUint32 aRunOffset=0);
+	TInt CollapseImportThunks();
+	TInt CollapseImportThunks(TRomBuilderEntry* aFile);
+	TInt CollapseBranches();
+	TInt CollapseBranches(TRomBuilderEntry* aFile);
+	TUint32 FindFinalJumpDestination(TUint32 ja);
+
+	char* AllocateRelocationTable(char* aAddr, TReloc*& aRelocTable);
+	void FillInRelocationTable(TReloc* aRelocTable);
+
+	void LinkKernelExtensions(TRomBuilderEntry* aExtArray[], TInt aExtCount);
+	void FillInCrcs();
+	void ProcessDllData();
+
+	void CreatePageIndex(char*& aAddr);
+	TInt CompressPages();
+	TInt CompressPage(SRomPageInfo& aPageInfo, TInt aOutOffset, CBytePair * aBPE);
+
+	// dependence graph
+	void UnmarkGraph(TInt aMark=0xffffffff);
+	void FindMarked(TInt aMarkMask, TInt aMark, TRomFile**& aList);
+	TInt ProcessDependencies();
+	void ListRouteTo(TRomFile* aStart, TRomFile* aDest, TInt aNDeps);
+
+	void SetSmpFlags();
+	
+	// Check if the unpaged memory size overflows. For page enabled ROM only.
+	TInt CheckUnpagedMemSize();
+	
+	// Initialize the page info prior to compression
+	TInt SetupPages();
+
+	Memmap *iImageMap;
+	SymbolGenerator* iSymGen;
+public:
+	char* iData;
+	TInt iSize;
+	TRomLoaderHeader *iLoaderHeader;
+	TRomHeader *iHeader;
+	TExtensionRomHeader *iExtensionRomHeader;		// NULL if not extension ROM
+	//
+	CObeyFile *iObey;
+
+	char *iSectionPtr;
+	
+	//
+	TInt iSizeUsed;
+	TInt iUncompressedSize;
+	TInt iOverhead;
+	TInt iDirectorySize;
+	TInt iImportsFixedUp;
+	TInt iBranchesFixedUp;
+	TInt iVtableEntriesFixedUp;
+	//
+	TUint32 iNextDataChunkBase;
+	TUint32 iTotalSvDataSize;
+	TUint32 iNextDllDataAddr;
+	char* iPrevPrimaryAddress;
+	char* iPrevVariantAddress;
+	COrderedFileList** iVariantFileLists;
+	TRomBuilderEntry** iPeFiles;
+	};
+
+
+#endif
--- a/imgtools/romtools/rombuild/r_srec.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_srec.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,124 +1,118 @@
-/*
-* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include "r_rom.h"
-#include "r_obey.h"
-
-#include <e32std.h>
-#include <e32std_private.h>
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-#include <iostream>
-#include <fstream>
-#else //!__MSVCDOTNET__
-#include <iostream.h>
-#include <fstream.h>
-#endif //__MSVCDOTNET__
-
-#include <string.h>
-
-const TInt KSRecBytesPerLine=32;		// max line = 1+1+2+8 + (32*2) + 2 = 78
-
-LOCAL_C TInt enchex(TUint nibble)
-//
-// Return ascii hex character corresponding to nibble
-//
-    {
-
-    nibble&=0xf;
-    return(nibble<=9 ? '0'+nibble : 'A'-10+nibble);
-    }
-
-GLDEF_C TUint putbhx(TUint8 *buf,TUint byte)
-//
-// Write byte to buffer as two hex digits
-//
-    {
-
-    *buf++ = (TUint8)enchex(byte>>4);
-    *buf++ = (TUint8)enchex(byte);
-	return byte&0xff;
-    }
-
-GLDEF_C TInt putmot(TUint8 *mcode, TUint8 *mdata,TUint mlen,TUint addr)
-//
-// Write SREC or S19 format to buffer at mcode from mlen bytes of binary data
-// stored in buffer mdata. The code is given address addr.
-// Returns the number of bytes written to mcode.
-//
-    {
-    TUint8 *p,*q,*qend;
-    TUint  sum,byte;
-
-    p=mcode;
-    *p='S';
-#ifdef ALLOW_S_RECORD_THREE_BYTE_ADDRESSES
-	// This is an optimisation which is useful for S-Record downloads over serial cable
-	// but some S-Record tools don't support it, so it's off by default.
-	if ((TUint)((addr>>24)&0xff) == 0)
-		{
-		*(p+1)='2';		// 3-byte address field
-		sum=putbhx(p+=2,3+mlen+1);
- 		}
-	else
-#endif
-		{
-		*(p+1)='3';		// 4-byte address field
-		sum=putbhx(p+=2,4+mlen+1);
-		sum+=putbhx(p+=2,(TUint)((addr>>24)&0xff));
-		}
-    sum+=putbhx(p+=2,(TUint)((addr>>16)&0xff));
-    sum+=putbhx(p+=2,(TUint)((addr>>8)&0xff));
-    sum+=putbhx(p+=2,(TUint)addr);
-    q=mdata;
-    qend=mdata+mlen;
-    for (q=mdata;q<qend;q++)
-		{
-		byte=(*q);
-		sum+=putbhx(p+=2,byte);
-		}
-	putbhx(p+=2,~sum);
-    return((TUint)(p-mcode+2));
-    }
-
-void E32Rom::WriteSRecord(ofstream &of)
-//
-// Write the rom to a file in S record format and return its check sum.
-//
-	{
-
-	TInt i;
-	TUint8 sBuf[256];
-	of << "S00600004844521B\n";
-	TInt size=iObey->iRomSize;
-	TUint8 *ptr=(TUint8 *)iHeader;
-	for (i=0; i<size; i+=KSRecBytesPerLine)
-		{
-		TInt len;
-		if ((i+KSRecBytesPerLine)>size)
-			len=size-i;
-		else
-			len=KSRecBytesPerLine;
-		TUint8 *pS=ptr+i;
-		TInt l=putmot(sBuf,pS,len,i+iObey->iSRecordBase);
-		of.write(reinterpret_cast<char *>(sBuf), l);
-		of<<endl;
-		}
-	of << "S70500000000FA\n";		// Fixed address! - would need to compute the checksum
-	}
-
+/*
+* Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#include "r_rom.h"
+#include "r_obey.h"
+
+#include <e32std.h>
+#include <e32std_private.h>
+ 
+#include <iostream>
+#include <fstream> 
+#include <string.h>
+
+const TInt KSRecBytesPerLine=32;		// max line = 1+1+2+8 + (32*2) + 2 = 78
+
+LOCAL_C TInt enchex(TUint nibble)
+//
+// Return ascii hex character corresponding to nibble
+//
+    {
+
+    nibble&=0xf;
+    return(nibble<=9 ? '0'+nibble : 'A'-10+nibble);
+    }
+
+GLDEF_C TUint putbhx(TUint8 *buf,TUint byte)
+//
+// Write byte to buffer as two hex digits
+//
+    {
+
+    *buf++ = (TUint8)enchex(byte>>4);
+    *buf++ = (TUint8)enchex(byte);
+	return byte&0xff;
+    }
+
+GLDEF_C TInt putmot(TUint8 *mcode, TUint8 *mdata,TUint mlen,TUint addr)
+//
+// Write SREC or S19 format to buffer at mcode from mlen bytes of binary data
+// stored in buffer mdata. The code is given address addr.
+// Returns the number of bytes written to mcode.
+//
+    {
+    TUint8 *p,*q,*qend;
+    TUint  sum,byte;
+
+    p=mcode;
+    *p='S';
+#ifdef ALLOW_S_RECORD_THREE_BYTE_ADDRESSES
+	// This is an optimisation which is useful for S-Record downloads over serial cable
+	// but some S-Record tools don't support it, so it's off by default.
+	if ((TUint)((addr>>24)&0xff) == 0)
+		{
+		*(p+1)='2';		// 3-byte address field
+		sum=putbhx(p+=2,3+mlen+1);
+ 		}
+	else
+#endif
+		{
+		*(p+1)='3';		// 4-byte address field
+		sum=putbhx(p+=2,4+mlen+1);
+		sum+=putbhx(p+=2,(TUint)((addr>>24)&0xff));
+		}
+    sum+=putbhx(p+=2,(TUint)((addr>>16)&0xff));
+    sum+=putbhx(p+=2,(TUint)((addr>>8)&0xff));
+    sum+=putbhx(p+=2,(TUint)addr);
+    q=mdata;
+    qend=mdata+mlen;
+    for (q=mdata;q<qend;q++)
+		{
+		byte=(*q);
+		sum+=putbhx(p+=2,byte);
+		}
+	putbhx(p+=2,~sum);
+    return((TUint)(p-mcode+2));
+    }
+
+void E32Rom::WriteSRecord(ofstream &of)
+//
+// Write the rom to a file in S record format and return its check sum.
+//
+	{
+
+	TInt i;
+	TUint8 sBuf[256];
+	of << "S00600004844521B\n";
+	TInt size=iObey->iRomSize;
+	TUint8 *ptr=(TUint8 *)iHeader;
+	for (i=0; i<size; i+=KSRecBytesPerLine)
+		{
+		TInt len;
+		if ((i+KSRecBytesPerLine)>size)
+			len=size-i;
+		else
+			len=KSRecBytesPerLine;
+		TUint8 *pS=ptr+i;
+		TInt l=putmot(sBuf,pS,len,i+iObey->iSRecordBase);
+		of.write(reinterpret_cast<char *>(sBuf), l);
+		of<<endl;
+		}
+	of << "S70500000000FA\n";		// Fixed address! - would need to compute the checksum
+	}
+
--- a/imgtools/romtools/rombuild/r_t_areaset.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/r_t_areaset.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,428 +1,423 @@
-/*
-* Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-* AreaSet Unit Tests
-*
-*/
-
-
-#if defined(__MSVCDOTNET__) || defined(__TOOLS2__)
-#include <iostream>
-#else //!__MSVCDOTNET__
-#include <iostream.h>
-#endif //__MSVCDOTNET__
-
-#include <stdlib.h>
-#include <string.h>
-#include <stdarg.h>
-
-#include "r_areaset.h"
-#include "r_rom.h"
-
-////////////////////////////////////////////////////////////////////////
-
-LOCAL_C void Test(TBool aExpr, const char* aMsg)
-	{
-	if (! aExpr)
-		{
-		cerr << "Test Failed: " << aMsg << '\n';
-		exit(1);
-		}
-	}
-
-
-LOCAL_C void CheckAreas(const AreaSet* aPAreaSet, ...)
-	{
-	va_list l;
-	va_start(l, aPAreaSet);
-
-	TInt areaCount;
-	for (areaCount = 0;; ++areaCount)
-		{
-		const char* name = va_arg(l, const char*);
-		if (name == 0)
-			break;
-
-		TLinAddr startAddr = va_arg(l, TLinAddr);
-		TUint size = va_arg(l, TUint);
-
-		const Area* pArea = aPAreaSet->FindByName(name);
-		Test(pArea != 0, "unknown name");
-		Test(pArea->DestBaseAddr() == startAddr, "incorrect area start address");
-		Test(pArea->MaxSize() == size, "incorrect area size");
-		}
-
-	Test(areaCount == aPAreaSet->Count(), "incorrect number of areas");
-
-	va_end(l);
-	}
-
-////////////////////////////////////////////////////////////////////////
-
-LOCAL_C void TestAddAreaSuccess()
-	{
-	cout << "TestAddAreaSuccess...\n";
-
-	AreaSet areaSet;
-
-	const char KName1[] = "toto";
-	const TLinAddr KStart1 = 0x666;
-	const TUint KSize1 = 0x42;
-
-	const char* overlappingArea;
-	AreaSet::TAddResult r = areaSet.AddArea(KName1, KStart1, KSize1, overlappingArea);
-	Test(r == AreaSet::EAdded, "adding area 1");
-	Test(overlappingArea == 0, "incorrect overlapping area 1");
-	CheckAreas(&areaSet, KName1, KStart1, KSize1, 0);
-
-	const char KName2[] = "foobar";
-	const TLinAddr KStart2 = 0x100000;
-	const TUint KSize2 = 0x100;
-
-	r = areaSet.AddArea(KName2, KStart2, KSize2, overlappingArea);
-	Test(r == AreaSet::EAdded, "adding area 2");
-	Test(overlappingArea == 0, "incorrect overlapping area 2");
-	CheckAreas(&areaSet, KName1, KStart1, KSize1, KName2, KStart2, KSize2, 0);
-	}
-
-
-LOCAL_C void TestAddingTwoAreas(const char* aName1, TLinAddr aDestBaseAddr1, TUint aSize1,
-								const char* aName2, TLinAddr aDestBaseAddr2, TUint aSize2,
-								AreaSet::TAddResult aExpectedResult)
-	{
-	cout << "Testing overlap between " << aName1 << " and " << aName2 << "\n";
-
-	AreaSet areaSet;
-
-	const char* overlappingArea;
-	AreaSet::TAddResult r = areaSet.AddArea(aName1, aDestBaseAddr1, aSize1, overlappingArea);
-	Test(r == AreaSet::EAdded, "adding area 1");
-	Test(overlappingArea == 0, "incorrect overlapping area 1");
-
-	r = areaSet.AddArea(aName2, aDestBaseAddr2, aSize2, overlappingArea);
-	Test(r == aExpectedResult, "adding area 2");
-
-	Test(areaSet.Count() == ((aExpectedResult == AreaSet::EAdded) ? 2 : 1),
-		 "incorrect area count");
-	if (aExpectedResult == AreaSet::EAdded)
-		{
-		Test(areaSet.Count() == 2, "incorrect area count (should be 2)");
-		Test(overlappingArea == 0, "incorrect overlapping area 2 (should be 0)");
-		}
-	else
-		{
-		Test(areaSet.Count() == 1, "incorrect area count (should be 1)");
-		if (aExpectedResult == AreaSet::EOverlap)
-			Test(strcmp(overlappingArea, aName1) == 0, "incorrect overlapping area 2 (bad name)");
-		else
-			Test(overlappingArea == 0, "incorrect overlapping area 2 (should be 0)");
-		}
-	}
-
-
-LOCAL_C void TestAddAreaOverlap()
-	{
-	cout << "TestAddAreaOverlap...\n";
-
-	const char KNameInitial[] = "initial";
-	const TLinAddr KStartInitial = 0x1000;
-	const TUint KSizeInitial = 0x101;
-
-	// new area overlapping first byte of initial one
-	TestAddingTwoAreas(KNameInitial, KStartInitial, KSizeInitial,
-					   "overlap 1", 0x0F00, 0x101, AreaSet::EOverlap);
-
-	// new area overlapping last byte of initial one
-	TestAddingTwoAreas(KNameInitial, KStartInitial, KSizeInitial,
-					   "overlap 2", 0x01100, 0x101, AreaSet::EOverlap);
-
-	// new area embedded in the initial one
-	TestAddingTwoAreas(KNameInitial, KStartInitial, KSizeInitial,
-					   "overlap 3", 0x01010, 0x10, AreaSet::EOverlap);
-
-	// existing area overlapping first byte of new one
-	TestAddingTwoAreas(KNameInitial, 0x0F00, 0x101, "overlap 10",
-					   KStartInitial, KSizeInitial, AreaSet::EOverlap);
-
-	// existing area overlapping last byte of new one
-	TestAddingTwoAreas(KNameInitial, 0x01100, 0x101, "overlap 11",
-					   KStartInitial, KSizeInitial, AreaSet::EOverlap);
-
-	// existing area embedded in the new one
-	TestAddingTwoAreas(KNameInitial, 0x01010, 0x10, "overlap 12",
-					   KStartInitial, KSizeInitial, AreaSet::EOverlap);
-
-	// new area just before the initial one
-	TestAddingTwoAreas(KNameInitial, KStartInitial, KSizeInitial,
-					   "overlap 4", 0x0F00, 0x100, AreaSet::EAdded);
-	
-	// new area just after the initial one
-	TestAddingTwoAreas(KNameInitial, KStartInitial, KSizeInitial,
-					   "overlap 5", 0x01101, 0x100, AreaSet::EAdded);
-	}
-
-
-LOCAL_C void TestAddAreaDuplicateName()
-	{
-	cout << "TestAddAreaDuplicateName...\n";
-	
-	TestAddingTwoAreas("foobar", 0x10, 0x10,
-					   "foobar", 0x100, 0x10,
-					   AreaSet::EDuplicateName);
-	}
-
-
-LOCAL_C void TestAddAreaOverflow()
-	{
-	cout << "TestAddAreaOverflow...\n";
-	
-	AreaSet areaSet;
-
-	const char KName1[] = "foobar";
-	const char* overlappingArea;
-	AreaSet::TAddResult r = areaSet.AddArea(KName1, 0xFFFFFFFF, 0x02, overlappingArea);
-	Test(r == AreaSet::EOverflow, "adding area 1");
-	Test(areaSet.Count() == 0, "incorrect count after trying to add area 1");
-	Test(areaSet.FindByName(KName1) == 0, "Unexpected name found after trying to add area 1");
-	Test(overlappingArea == 0, "incorrect overlapping area 1");
-
-	const char KName2[] = "barfoo";
-	r = areaSet.AddArea(KName2, 0xFFFFFFFF, 0xFFFFFFFF, overlappingArea);
-	Test(r == AreaSet::EOverflow, "adding area 2");
-	Test(areaSet.Count() == 0, "incorrect count after trying to add area 2");
-	Test(areaSet.FindByName(KName2) == 0, "Unexpected name found after trying to add area 2");
-	Test(overlappingArea == 0, "incorrect overlapping area 2");
-	}
-
-
-
-LOCAL_C void TestAddArea()
-	{
-	TestAddAreaSuccess();
-	TestAddAreaOverlap();
-	TestAddAreaDuplicateName();
-	TestAddAreaOverflow();
-	}
-
-LOCAL_C void TestSrcAddrManipulations()
-	{
-	cout << "TestSrcAddrManipulations...\n";
-
-	//
-	// Creating an AreaSet instance containing one area
-	//
-
-	AreaSet areaSet;
-	const char* overlappingArea;
-	const char KAreaName[] = "foobar";
-	const TUint KMaxSize = 10;
-	AreaSet::TAddResult r = areaSet.AddArea(KAreaName, 0x100, KMaxSize, overlappingArea);
-	Test(r == AreaSet::EAdded, "Failed to add area");
-
-	Area* area = areaSet.FindByName(KAreaName);
-	Test(area != 0, "Failed to find area");
-
-	Test(area->UsedSize() == 0, "used size before allocation");
-
-	const TUint KSrcBaseAddr = 0x100;
-	area->SetSrcBaseAddr(KSrcBaseAddr);
-
-	Test(area->SrcBaseAddr() == KSrcBaseAddr, "destination base address before allocation");
-	Test(area->SrcBaseAddr() == area->SrcLimitAddr(), "destination limit address before allocation");
-
-	//
-	// Allocating some space in the area
-	//
-
-	const TUint KAlloc1 = KMaxSize-1;
-	TUint overflow;
-	TBool allocated = area->ExtendSrcLimitAddr(KSrcBaseAddr+KAlloc1, overflow);
-	Test(allocated, "allocation 1 failed");
-	Test(area->UsedSize() == KAlloc1, "used size after allocation 1");
-	Test(area->SrcBaseAddr()+KAlloc1 == area->SrcLimitAddr(), "destination limit address after allocation 1");
-
-	//
-	// Allocating more than available
-	//
-
-	const TUint KAlloc2 = KMaxSize*2;
-	allocated = area->ExtendSrcLimitAddr(KSrcBaseAddr+KAlloc1+KAlloc2, overflow);
-	Test(! allocated, "allocation 2 should have failed");
-	Test(overflow == KAlloc2+KAlloc1 - KMaxSize, "overflow after allocation 2");
-	Test(area->UsedSize() == KAlloc1, "used size after allocation 2");
-	Test(area->SrcBaseAddr()+KAlloc1 == area->SrcLimitAddr(), "destination limit address after allocation 2");
-
-	//
-	// Allocating just enough to fill the area completely  
-	//
-
-	const TUint KAlloc3 = KMaxSize-KAlloc1;
-	allocated = area->ExtendSrcLimitAddr(KSrcBaseAddr+KAlloc1+KAlloc3, overflow);
-	Test(allocated, "allocation 3 failed");
-	Test(area->UsedSize() == KAlloc1+KAlloc3, "used size after allocation 3");
-	Test(area->UsedSize() == area->MaxSize(), "used size and max size should be equal");
-	Test(area->SrcBaseAddr()+KAlloc1+KAlloc3 == area->SrcLimitAddr(), "destination limit address after allocation 3");
-
-	//
-	// Overflowing the area by one byte
-	//
-
-	const TUint KAlloc4 = 1;
-	allocated = area->ExtendSrcLimitAddr(KSrcBaseAddr+KAlloc1+KAlloc3+KAlloc4, overflow);
-	Test(! allocated, "allocation 4 should have failed");
-	Test(overflow == 1, "overflow after allocation 4");
-	Test(area->UsedSize() == KAlloc1+KAlloc3, "used size after allocation 4");
-	Test(area->SrcBaseAddr()+KAlloc1+KAlloc3 == area->SrcLimitAddr(), "destination limit address after allocation 4");
-	}
-
-
-LOCAL_C void TestFileIterator()
-	{
-	cout << "TestFileIterator...\n";
-
-	//
-	// Creating an area set containing one area
-	//
-
-	AreaSet areaSet;
-	const char* overlappingArea;
-	const char KAreaName[] = "foobar";
-	const TUint KMaxSize = 10;
-	AreaSet::TAddResult r = areaSet.AddArea(KAreaName, 0x100, KMaxSize, overlappingArea);
-	Test(r == AreaSet::EAdded, "Failed to add area");
-
-	Area* area = areaSet.FindByName(KAreaName);
-	Test(area != 0, "Failed to find area");
-
-	FilesInAreaIterator it1(*area);
-	Test(it1.IsDone(), "it1.IsDone()");
-
-	//
-	// Adding one file to that area
-	//
-	
-	TRomBuilderEntry* pfile1 = new TRomBuilderEntry("file1", (TText*) "file1");
-	area->AddFile(pfile1);
-
-	FilesInAreaIterator it2(*area);
-	Test(! it2.IsDone(), "! it2.IsDone() 1");
-	Test(it2.Current() == pfile1, "it2.Current() == pfile1");
-
-	it2.GoToNext();
-	Test(it2.IsDone(), "it2.IsDone()");
-
-	//
-	// Adding a second file to that area
-	//
-
-	TRomBuilderEntry* pFile2 = new TRomBuilderEntry("file2", (TText*) "file2");
-	area->AddFile(pFile2);
-
-	FilesInAreaIterator it3(*area);
-	Test(! it3.IsDone(), "! it3.IsDone() 1");
-	Test(it3.Current() == pfile1, "it3.Current() == pfile1");
-
-	it3.GoToNext();
-	Test(! it3.IsDone(), "it3.IsDone() 2");
-	Test(it3.Current() == pFile2, "it3.Current() == pFile2");
-
-	it3.GoToNext();
-	Test(it3.IsDone(), "it3.IsDone()");
-	}
-
-
-LOCAL_C void TestNonDefaultAreaIterator() 
-	{
-	cout << "TestNonDefaultAreaIterator...\n";
-
-	//
-	// Creating an area set
-	//
-
-	AreaSet areaSet;
-
-	NonDefaultAreasIterator it1(areaSet);
-	Test(it1.IsDone(), "it1.IsDone()");
-	
-	//
-	// Adding a first non default area
-	//
-
-	const char* overlappingArea;
-	const char KAreaName1[] = "area 1";
-	AreaSet::TAddResult r = areaSet.AddArea(KAreaName1, 0x100, 0x10, overlappingArea);
-	Test(r == AreaSet::EAdded, "Failed to add area 1");
-
-	Area* pArea1 = areaSet.FindByName(KAreaName1);
-	Test(pArea1 != 0, "Failed to find area 1");
-
-	NonDefaultAreasIterator it2(areaSet);
-	Test(! it2.IsDone(), "! it2.IsDone()");
-
-	Test(&it2.Current() == pArea1, "&it2.Current() == pArea1");
-
-	it2.GoToNext();
-	Test(it2.IsDone(), "it2.IsDone()");
-
-	//
-	// Adding a default area
-	//
-
-	r = areaSet.AddArea(AreaSet::KDefaultAreaName, 0x50000000, 0x00200000, overlappingArea);
-	Test(r == AreaSet::EAdded, "failed to add default area");
-
-	NonDefaultAreasIterator it3(areaSet);
-	Test(! it3.IsDone(), "! it3.IsDone()");
-
-	Test(&it3.Current() == pArea1, "&it3.Current() == pArea1");
-
-	it3.GoToNext();
-	Test(it3.IsDone(), "it3.IsDone()");
-
-	//
-	// Adding a second non default area
-	//
-
-	const char KAreaName2[] = "area 2";
-	r = areaSet.AddArea(KAreaName2, 0x1000, 0x10, overlappingArea);
-	Test(r == AreaSet::EAdded, "Failed to add area 2");
-
-	Area* pArea2 = areaSet.FindByName(KAreaName2);
-	Test(pArea2 != 0, "Failed to find area 2");
-
-	NonDefaultAreasIterator it4(areaSet);
-	Test(! it4.IsDone(), "! it4.IsDone()");
-
-	Test(&it4.Current() == pArea2, "&it4.Current() == pArea2");
-
-	it4.GoToNext();
-	Test(! it4.IsDone(), "it4.IsDone()");
-	Test(&it4.Current() == pArea1, "&it4.Current() == pArea1");
-
-	it4.GoToNext();
-	Test(it4.IsDone(), "it4.IsDone()");
-	}
-
-////////////////////////////////////////////////////////////////////////
-
-GLDEF_C int main() 
-	{
-	TestAddArea();
-	TestSrcAddrManipulations();
-	TestFileIterator();
-	TestNonDefaultAreaIterator();
-
-	cout << "\nTests OK\n";
-	return 0;
-	}
+/*
+* Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+* AreaSet Unit Tests
+*
+*/
+
+ 
+#include <iostream> 
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+
+#include "r_areaset.h"
+#include "r_rom.h"
+
+////////////////////////////////////////////////////////////////////////
+
+LOCAL_C void Test(TBool aExpr, const char* aMsg)
+	{
+	if (! aExpr)
+		{
+		cerr << "Test Failed: " << aMsg << '\n';
+		exit(1);
+		}
+	}
+
+
+LOCAL_C void CheckAreas(const AreaSet* aPAreaSet, ...)
+	{
+	va_list l;
+	va_start(l, aPAreaSet);
+
+	TInt areaCount;
+	for (areaCount = 0;; ++areaCount)
+		{
+		const char* name = va_arg(l, const char*);
+		if (name == 0)
+			break;
+
+		TLinAddr startAddr = va_arg(l, TLinAddr);
+		TUint size = va_arg(l, TUint);
+
+		const Area* pArea = aPAreaSet->FindByName(name);
+		Test(pArea != 0, "unknown name");
+		Test(pArea->DestBaseAddr() == startAddr, "incorrect area start address");
+		Test(pArea->MaxSize() == size, "incorrect area size");
+		}
+
+	Test(areaCount == aPAreaSet->Count(), "incorrect number of areas");
+
+	va_end(l);
+	}
+
+////////////////////////////////////////////////////////////////////////
+
+LOCAL_C void TestAddAreaSuccess()
+	{
+	cout << "TestAddAreaSuccess...\n";
+
+	AreaSet areaSet;
+
+	const char KName1[] = "toto";
+	const TLinAddr KStart1 = 0x666;
+	const TUint KSize1 = 0x42;
+
+	const char* overlappingArea;
+	AreaSet::TAddResult r = areaSet.AddArea(KName1, KStart1, KSize1, overlappingArea);
+	Test(r == AreaSet::EAdded, "adding area 1");
+	Test(overlappingArea == 0, "incorrect overlapping area 1");
+	CheckAreas(&areaSet, KName1, KStart1, KSize1, 0);
+
+	const char KName2[] = "foobar";
+	const TLinAddr KStart2 = 0x100000;
+	const TUint KSize2 = 0x100;
+
+	r = areaSet.AddArea(KName2, KStart2, KSize2, overlappingArea);
+	Test(r == AreaSet::EAdded, "adding area 2");
+	Test(overlappingArea == 0, "incorrect overlapping area 2");
+	CheckAreas(&areaSet, KName1, KStart1, KSize1, KName2, KStart2, KSize2, 0);
+	}
+
+
+LOCAL_C void TestAddingTwoAreas(const char* aName1, TLinAddr aDestBaseAddr1, TUint aSize1,
+								const char* aName2, TLinAddr aDestBaseAddr2, TUint aSize2,
+								AreaSet::TAddResult aExpectedResult)
+	{
+	cout << "Testing overlap between " << aName1 << " and " << aName2 << "\n";
+
+	AreaSet areaSet;
+
+	const char* overlappingArea;
+	AreaSet::TAddResult r = areaSet.AddArea(aName1, aDestBaseAddr1, aSize1, overlappingArea);
+	Test(r == AreaSet::EAdded, "adding area 1");
+	Test(overlappingArea == 0, "incorrect overlapping area 1");
+
+	r = areaSet.AddArea(aName2, aDestBaseAddr2, aSize2, overlappingArea);
+	Test(r == aExpectedResult, "adding area 2");
+
+	Test(areaSet.Count() == ((aExpectedResult == AreaSet::EAdded) ? 2 : 1),
+		 "incorrect area count");
+	if (aExpectedResult == AreaSet::EAdded)
+		{
+		Test(areaSet.Count() == 2, "incorrect area count (should be 2)");
+		Test(overlappingArea == 0, "incorrect overlapping area 2 (should be 0)");
+		}
+	else
+		{
+		Test(areaSet.Count() == 1, "incorrect area count (should be 1)");
+		if (aExpectedResult == AreaSet::EOverlap)
+			Test(strcmp(overlappingArea, aName1) == 0, "incorrect overlapping area 2 (bad name)");
+		else
+			Test(overlappingArea == 0, "incorrect overlapping area 2 (should be 0)");
+		}
+	}
+
+
+LOCAL_C void TestAddAreaOverlap()
+	{
+	cout << "TestAddAreaOverlap...\n";
+
+	const char KNameInitial[] = "initial";
+	const TLinAddr KStartInitial = 0x1000;
+	const TUint KSizeInitial = 0x101;
+
+	// new area overlapping first byte of initial one
+	TestAddingTwoAreas(KNameInitial, KStartInitial, KSizeInitial,
+					   "overlap 1", 0x0F00, 0x101, AreaSet::EOverlap);
+
+	// new area overlapping last byte of initial one
+	TestAddingTwoAreas(KNameInitial, KStartInitial, KSizeInitial,
+					   "overlap 2", 0x01100, 0x101, AreaSet::EOverlap);
+
+	// new area embedded in the initial one
+	TestAddingTwoAreas(KNameInitial, KStartInitial, KSizeInitial,
+					   "overlap 3", 0x01010, 0x10, AreaSet::EOverlap);
+
+	// existing area overlapping first byte of new one
+	TestAddingTwoAreas(KNameInitial, 0x0F00, 0x101, "overlap 10",
+					   KStartInitial, KSizeInitial, AreaSet::EOverlap);
+
+	// existing area overlapping last byte of new one
+	TestAddingTwoAreas(KNameInitial, 0x01100, 0x101, "overlap 11",
+					   KStartInitial, KSizeInitial, AreaSet::EOverlap);
+
+	// existing area embedded in the new one
+	TestAddingTwoAreas(KNameInitial, 0x01010, 0x10, "overlap 12",
+					   KStartInitial, KSizeInitial, AreaSet::EOverlap);
+
+	// new area just before the initial one
+	TestAddingTwoAreas(KNameInitial, KStartInitial, KSizeInitial,
+					   "overlap 4", 0x0F00, 0x100, AreaSet::EAdded);
+	
+	// new area just after the initial one
+	TestAddingTwoAreas(KNameInitial, KStartInitial, KSizeInitial,
+					   "overlap 5", 0x01101, 0x100, AreaSet::EAdded);
+	}
+
+
+LOCAL_C void TestAddAreaDuplicateName()
+	{
+	cout << "TestAddAreaDuplicateName...\n";
+	
+	TestAddingTwoAreas("foobar", 0x10, 0x10,
+					   "foobar", 0x100, 0x10,
+					   AreaSet::EDuplicateName);
+	}
+
+
+LOCAL_C void TestAddAreaOverflow()
+	{
+	cout << "TestAddAreaOverflow...\n";
+	
+	AreaSet areaSet;
+
+	const char KName1[] = "foobar";
+	const char* overlappingArea;
+	AreaSet::TAddResult r = areaSet.AddArea(KName1, 0xFFFFFFFF, 0x02, overlappingArea);
+	Test(r == AreaSet::EOverflow, "adding area 1");
+	Test(areaSet.Count() == 0, "incorrect count after trying to add area 1");
+	Test(areaSet.FindByName(KName1) == 0, "Unexpected name found after trying to add area 1");
+	Test(overlappingArea == 0, "incorrect overlapping area 1");
+
+	const char KName2[] = "barfoo";
+	r = areaSet.AddArea(KName2, 0xFFFFFFFF, 0xFFFFFFFF, overlappingArea);
+	Test(r == AreaSet::EOverflow, "adding area 2");
+	Test(areaSet.Count() == 0, "incorrect count after trying to add area 2");
+	Test(areaSet.FindByName(KName2) == 0, "Unexpected name found after trying to add area 2");
+	Test(overlappingArea == 0, "incorrect overlapping area 2");
+	}
+
+
+
+LOCAL_C void TestAddArea()
+	{
+	TestAddAreaSuccess();
+	TestAddAreaOverlap();
+	TestAddAreaDuplicateName();
+	TestAddAreaOverflow();
+	}
+
+LOCAL_C void TestSrcAddrManipulations()
+	{
+	cout << "TestSrcAddrManipulations...\n";
+
+	//
+	// Creating an AreaSet instance containing one area
+	//
+
+	AreaSet areaSet;
+	const char* overlappingArea;
+	const char KAreaName[] = "foobar";
+	const TUint KMaxSize = 10;
+	AreaSet::TAddResult r = areaSet.AddArea(KAreaName, 0x100, KMaxSize, overlappingArea);
+	Test(r == AreaSet::EAdded, "Failed to add area");
+
+	Area* area = areaSet.FindByName(KAreaName);
+	Test(area != 0, "Failed to find area");
+
+	Test(area->UsedSize() == 0, "used size before allocation");
+
+	const TUint KSrcBaseAddr = 0x100;
+	area->SetSrcBaseAddr(KSrcBaseAddr);
+
+	Test(area->SrcBaseAddr() == KSrcBaseAddr, "destination base address before allocation");
+	Test(area->SrcBaseAddr() == area->SrcLimitAddr(), "destination limit address before allocation");
+
+	//
+	// Allocating some space in the area
+	//
+
+	const TUint KAlloc1 = KMaxSize-1;
+	TUint overflow;
+	TBool allocated = area->ExtendSrcLimitAddr(KSrcBaseAddr+KAlloc1, overflow);
+	Test(allocated, "allocation 1 failed");
+	Test(area->UsedSize() == KAlloc1, "used size after allocation 1");
+	Test(area->SrcBaseAddr()+KAlloc1 == area->SrcLimitAddr(), "destination limit address after allocation 1");
+
+	//
+	// Allocating more than available
+	//
+
+	const TUint KAlloc2 = KMaxSize*2;
+	allocated = area->ExtendSrcLimitAddr(KSrcBaseAddr+KAlloc1+KAlloc2, overflow);
+	Test(! allocated, "allocation 2 should have failed");
+	Test(overflow == KAlloc2+KAlloc1 - KMaxSize, "overflow after allocation 2");
+	Test(area->UsedSize() == KAlloc1, "used size after allocation 2");
+	Test(area->SrcBaseAddr()+KAlloc1 == area->SrcLimitAddr(), "destination limit address after allocation 2");
+
+	//
+	// Allocating just enough to fill the area completely  
+	//
+
+	const TUint KAlloc3 = KMaxSize-KAlloc1;
+	allocated = area->ExtendSrcLimitAddr(KSrcBaseAddr+KAlloc1+KAlloc3, overflow);
+	Test(allocated, "allocation 3 failed");
+	Test(area->UsedSize() == KAlloc1+KAlloc3, "used size after allocation 3");
+	Test(area->UsedSize() == area->MaxSize(), "used size and max size should be equal");
+	Test(area->SrcBaseAddr()+KAlloc1+KAlloc3 == area->SrcLimitAddr(), "destination limit address after allocation 3");
+
+	//
+	// Overflowing the area by one byte
+	//
+
+	const TUint KAlloc4 = 1;
+	allocated = area->ExtendSrcLimitAddr(KSrcBaseAddr+KAlloc1+KAlloc3+KAlloc4, overflow);
+	Test(! allocated, "allocation 4 should have failed");
+	Test(overflow == 1, "overflow after allocation 4");
+	Test(area->UsedSize() == KAlloc1+KAlloc3, "used size after allocation 4");
+	Test(area->SrcBaseAddr()+KAlloc1+KAlloc3 == area->SrcLimitAddr(), "destination limit address after allocation 4");
+	}
+
+
+LOCAL_C void TestFileIterator()
+	{
+	cout << "TestFileIterator...\n";
+
+	//
+	// Creating an area set containing one area
+	//
+
+	AreaSet areaSet;
+	const char* overlappingArea;
+	const char KAreaName[] = "foobar";
+	const TUint KMaxSize = 10;
+	AreaSet::TAddResult r = areaSet.AddArea(KAreaName, 0x100, KMaxSize, overlappingArea);
+	Test(r == AreaSet::EAdded, "Failed to add area");
+
+	Area* area = areaSet.FindByName(KAreaName);
+	Test(area != 0, "Failed to find area");
+
+	FilesInAreaIterator it1(*area);
+	Test(it1.IsDone(), "it1.IsDone()");
+
+	//
+	// Adding one file to that area
+	//
+	
+	TRomBuilderEntry* pfile1 = new TRomBuilderEntry("file1", "file1");
+	area->AddFile(pfile1);
+
+	FilesInAreaIterator it2(*area);
+	Test(! it2.IsDone(), "! it2.IsDone() 1");
+	Test(it2.Current() == pfile1, "it2.Current() == pfile1");
+
+	it2.GoToNext();
+	Test(it2.IsDone(), "it2.IsDone()");
+
+	//
+	// Adding a second file to that area
+	//
+
+	TRomBuilderEntry* pFile2 = new TRomBuilderEntry("file2", "file2");
+	area->AddFile(pFile2);
+
+	FilesInAreaIterator it3(*area);
+	Test(! it3.IsDone(), "! it3.IsDone() 1");
+	Test(it3.Current() == pfile1, "it3.Current() == pfile1");
+
+	it3.GoToNext();
+	Test(! it3.IsDone(), "it3.IsDone() 2");
+	Test(it3.Current() == pFile2, "it3.Current() == pFile2");
+
+	it3.GoToNext();
+	Test(it3.IsDone(), "it3.IsDone()");
+	}
+
+
+LOCAL_C void TestNonDefaultAreaIterator() 
+	{
+	cout << "TestNonDefaultAreaIterator...\n";
+
+	//
+	// Creating an area set
+	//
+
+	AreaSet areaSet;
+
+	NonDefaultAreasIterator it1(areaSet);
+	Test(it1.IsDone(), "it1.IsDone()");
+	
+	//
+	// Adding a first non default area
+	//
+
+	const char* overlappingArea;
+	const char KAreaName1[] = "area 1";
+	AreaSet::TAddResult r = areaSet.AddArea(KAreaName1, 0x100, 0x10, overlappingArea);
+	Test(r == AreaSet::EAdded, "Failed to add area 1");
+
+	Area* pArea1 = areaSet.FindByName(KAreaName1);
+	Test(pArea1 != 0, "Failed to find area 1");
+
+	NonDefaultAreasIterator it2(areaSet);
+	Test(! it2.IsDone(), "! it2.IsDone()");
+
+	Test(&it2.Current() == pArea1, "&it2.Current() == pArea1");
+
+	it2.GoToNext();
+	Test(it2.IsDone(), "it2.IsDone()");
+
+	//
+	// Adding a default area
+	//
+
+	r = areaSet.AddArea(AreaSet::KDefaultAreaName, 0x50000000, 0x00200000, overlappingArea);
+	Test(r == AreaSet::EAdded, "failed to add default area");
+
+	NonDefaultAreasIterator it3(areaSet);
+	Test(! it3.IsDone(), "! it3.IsDone()");
+
+	Test(&it3.Current() == pArea1, "&it3.Current() == pArea1");
+
+	it3.GoToNext();
+	Test(it3.IsDone(), "it3.IsDone()");
+
+	//
+	// Adding a second non default area
+	//
+
+	const char KAreaName2[] = "area 2";
+	r = areaSet.AddArea(KAreaName2, 0x1000, 0x10, overlappingArea);
+	Test(r == AreaSet::EAdded, "Failed to add area 2");
+
+	Area* pArea2 = areaSet.FindByName(KAreaName2);
+	Test(pArea2 != 0, "Failed to find area 2");
+
+	NonDefaultAreasIterator it4(areaSet);
+	Test(! it4.IsDone(), "! it4.IsDone()");
+
+	Test(&it4.Current() == pArea2, "&it4.Current() == pArea2");
+
+	it4.GoToNext();
+	Test(! it4.IsDone(), "it4.IsDone()");
+	Test(&it4.Current() == pArea1, "&it4.Current() == pArea1");
+
+	it4.GoToNext();
+	Test(it4.IsDone(), "it4.IsDone()");
+	}
+
+////////////////////////////////////////////////////////////////////////
+
+GLDEF_C int main() 
+	{
+	TestAddArea();
+	TestSrcAddrManipulations();
+	TestFileIterator();
+	TestNonDefaultAreaIterator();
+
+	cout << "\nTests OK\n";
+	return 0;
+	}
--- a/imgtools/romtools/rombuild/rombuild.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/rombuild.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,628 +1,605 @@
-// Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
-// All rights reserved.
-// This component and the accompanying materials are made available
-// under the terms of the License "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:
-//
-
-#include <string.h>
-#include <stdlib.h>
-
-#include "h_utl.h"
-#include "h_ver.h"
-
-#include "r_global.h"
-#include "r_rom.h"
-#include "r_obey.h"
-#include "parameterfileprocessor.h"
-
-#include "r_dir.h"
-#include "r_coreimage.h"
-
-const TInt KRomLoaderHeaderNone=0;
-const TInt KRomLoaderHeaderEPOC=1;
-const TInt KRomLoaderHeaderCOFF=2;
-
-static const TInt RombuildMajorVersion=2;
-static const TInt RombuildMinorVersion=14;
-static const TInt RombuildPatchVersion=0;
-static TBool SizeSummary=EFalse;
-static TPrintType SizeWhere=EAlways;
-static char *CompareRom=NULL;
-static TInt MAXIMUM_THREADS = 128;
-static TInt DEFAULT_THREADS = 8;
-
-string filename;			// to store oby filename passed to Rombuild.
-TBool reallyHelp=EFalse;
-TInt gCPUNum = 0;
-TInt gThreadNum = 0;
-char* g_pCharCPUNum = NULL;
-TBool gGenDepGraph = EFalse;
-char* gDepInfoFile = NULL;
-
-void PrintVersion()
-	{
-	Print(EAlways,"\nROMBUILD - Rom builder");
-  	Print(EAlways, " V%d.%d.%d\n", RombuildMajorVersion, RombuildMinorVersion, RombuildPatchVersion);
-  	Print(EAlways,Copyright);
-	}
-
-char HelpText[] = 
-	"Syntax: ROMBUILD [options] obeyfilename\n"
-	"Option: -v verbose,  -?  \n"
-	"        -type-safe-link  \n"
-	"        -s[log|screen|both]           size summary\n"
-	"        -r<FileName>                  compare a sectioned Rom image\n"
-	"        -no-header                    suppress the image loader header\n"
-	"        -gendep                       generate the dependence graph for paged part\n"
-	"        -coff-header                  use a PE-COFF header rather than an EPOC header\n"
-	"        -d<bitmask>                   set trace mask (DEB build only)\n"
-	"        -compress[[=]paged|unpaged]   compress the ROM Image\n"
-	"									   without any argumentum compress both sections\n"
-	"									   paged 	compress paged section only\n"
-	"									   unpaged 	compress unpaged section only\n"	
-	"        -fastcompress  compress files with faster bytepair and tradeoff of compress ratio\n"
-	"        -j<digit> do the main job with <digit> threads\n"
-	"        -compressionmethod <method>   method one of none|inflate|bytepair to set the compression\n"
-	"        -no-sorted-romfs              do not add sorted entries arrays (6.1 compatible)\n"
-	"        -geninc                       to generate include file for licensee tools to use\n"			// DEF095619
-	"        -loglevel<level>              level of information to log (valid levels are 0,1,2,3,4).\n" //Tools like Visual ROM builder need the host/ROM filenames, size & if the file is hidden.
-	"        -wstdpath                     warn if destination path provided for a file is not a standard path\n"
-	"        -argfile=<fileName>           specify argument-file name containing list of command-line arguments to rombuild\n"
-	"        -lowmem                       use memory-mapped file for image build to reduce physical memory consumption\n"
-	"        -coreimage=<core image file>  to pass the core image as input for extension ROM image generation\n";
-
-
-char ReallyHelpText[] =
-	"Priorities:\n"
-	"        low background foreground high windowserver\n"
-	"        fileserver realtimeserver supervisor\n"
-	"Languages:\n"
-	"        Test English French German Spanish Italian Swedish Danish\n"
-	"        Norwegian Finnish American SwissFrench SwissGerman Portuguese\n"
-	"        Turkish Icelandic Russian Hungarian Dutch BelgianFlemish\n"
-	"        Australian BelgianFrench\n"
-	"Compression methods:\n"
-	"        none     no compression on the individual executable image.\n"
-	"        inflate  compress the individual executable image.\n"
-	"        bytepair compress the individual executable image.\n"
-	"Log Level:\n"
-	"        0  produce the default logs\n"
-	"        1  produce file detail logs in addition to the default logs\n"
-	"        2  logs e32 header attributes(same as default log) in addition to the level 1 details\n";
-
-void processParamfile(string aFileName);
-
-void processCommandLine(int argc, char *argv[], TBool paramFileFlag=EFalse)
-//
-// Process the command line arguments, printing a helpful message if none are supplied
-//
-	{
-
-	// If "-argfile" option is passed to Rombuild, then process the parameters
-	// specified in parameter-file first and then the options passed from the 
-	// command-line.
-	string ParamFileArg("-ARGFILE=");	
-	if(paramFileFlag == EFalse)
-	{	
-		for (int count=1; count<argc; count++)
-		{
-			string paramFile;
-			strupr(argv[count]);
-			if(strncmp(argv[count],ParamFileArg.c_str(),ParamFileArg.length())==0)
-			{
-				paramFile.assign(&argv[count][ParamFileArg.length()]);					
-				processParamfile(paramFile);
-			}
-		}
-	}	
-	
-	for (int i=1; i<argc; i++)
-		{
-		strupr(argv[i]);
-		if ((argv[i][0] == '-') || (argv[i][0] == '/'))
-			{ // switch
-			if (argv[i][1] == 'V')
-				H.iVerbose = ETrue;
-			else if (argv[i][1] == 'S')
-				{
-				SizeSummary=ETrue;
-				if (argv[i][2] == 'L')
-					SizeWhere=ELog;
-				if (argv[i][2] == 'S')
-					SizeWhere=EScreen;
-				}
-			else if (strcmp(argv[i], "-FASTCOMPRESS")==0)
-				gFastCompress = ETrue;
-			else if (strcmp(argv[i], "-GENDEP")==0)
-				gGenDepGraph = ETrue;
-			else if (strncmp(argv[i], "-J", 2)==0)
-				{
-					if(argv[i][2])
-						gThreadNum = atoi(&argv[i][2]);
-					else
-						{
-						Print(EWarning, "The option should be like '-j4'.\n");
-						gThreadNum = 0;
-						}
-					if(gThreadNum <= 0 || gThreadNum > MAXIMUM_THREADS)
-						{
-						if(gCPUNum > 0 && gCPUNum <= MAXIMUM_THREADS)
-							{
-							Print(EWarning, "The number of concurrent jobs set by -j should be between 1 and 128. And the number of processors %d will be used as the number of concurrent jobs.\n", gCPUNum);
-							gThreadNum = gCPUNum;
-							}
-						else if(g_pCharCPUNum)
-							{
-							Print(EWarning, "The number of concurrent jobs set by -j should be between 1 and 128. And the NUMBER_OF_PROCESSORS is invalid, so the default value %d will be used.\n", DEFAULT_THREADS);
-							gThreadNum = DEFAULT_THREADS;
-							}
-						else
-							{
-							Print(EWarning, "The number of concurrent jobs set by -j should be between 1 and 128. And the NUMBER_OF_PROCESSORS is not available, so the default value %d will be used.\n", DEFAULT_THREADS);
-							gThreadNum = DEFAULT_THREADS;
-							}
-						}	
-				}
-			else if (strncmp(argv[i],ParamFileArg.c_str(),ParamFileArg.length())==0)
-			{
-				// If "-argfile" option is specified within parameter-file then process it 
-				// otherwise ignore the option.
-				if (paramFileFlag)
-				{
-					String paramFile;
-					paramFile.assign(&argv[i][ParamFileArg.length()]);		
-					processParamfile(paramFile);
-				}
-				else
-				{
-					continue;
-				}
-			}
-			else if (argv[i][1] == 'T')
-				TypeSafeLink=ETrue;
-			else if (argv[i][1] == '?')
-				reallyHelp=ETrue;
-			else if (argv[i][1] == 'R')
-				CompareRom=strdup(&argv[i][2]);
-			else if (strcmp(argv[i], "-NO-HEADER")==0)
-				gHeaderType=KRomLoaderHeaderNone;
-			else if (strcmp(argv[i], "-EPOC-HEADER")==0)
-				gHeaderType=KRomLoaderHeaderEPOC;
-			else if (strcmp(argv[i], "-COFF-HEADER")==0)
-				gHeaderType=KRomLoaderHeaderCOFF;
-			else if (strcmp(argv[i], "-COMPRESS")==0)
-				{				
-				if( (i+1) >= argc || argv[i+1][0] == '-')
-					{
-					// No argument, compress both parts with default compression method
-					// un-paged part compressed by Deflate
-					gCompressUnpaged = ETrue;
-					gCompressUnpagedMethod = KUidCompressionDeflate;					
-					// paged part compressed by the Bytepiar
-					gEnableCompress=ETrue;
-					gCompressionMethod = KUidCompressionBytePair;
-					}
-				else 
-					{
-					// An argument exists
-					i++;
-					strupr(argv[i]);
-					if( strcmp(argv[i], "PAGED") == 0)
-						{
-						gEnableCompress=ETrue;
-						gCompressionMethod = KUidCompressionBytePair;	
-						}	
-					else if( strcmp(argv[i], "UNPAGED") == 0)
-						{
-						gCompressUnpaged=ETrue;
-						gCompressUnpagedMethod = KUidCompressionDeflate;	
-						}	
-					else
-						{
- 						Print (EError, "Unknown -compression argument! Set it to default (no compression)!");
- 						gEnableCompress=EFalse;
-						gCompressionMethod = 0;
-						gCompressUnpaged = EFalse;
-						gCompressUnpagedMethod = 0;					
-						}
-					}
-				}	
-			else if( strcmp(argv[i], "-COMPRESSIONMETHOD") == 0 )
-				{
-				// next argument should be a method
-				if( (i+1) >= argc || argv[i+1][0] == '-')
-					{
-					Print (EError, "Missing compression method! Set it to default (no compression)!");
-					gEnableCompress=EFalse;
-					gCompressionMethod = 0;
-					}
-				else 
-					{
-					i++;
-					strupr(argv[i]);
-					if( strcmp(argv[i], "INFLATE") == 0)
-						{
-						gEnableCompress=ETrue;
-						gCompressionMethod = KUidCompressionDeflate;	
-						}	
-					else if( strcmp(argv[i], "BYTEPAIR") == 0)
-						{
-						gEnableCompress=ETrue;
-						gCompressionMethod = KUidCompressionBytePair;	
-						}	
-					else
-						{
- 						if( strcmp(argv[i], "NONE") != 0)
- 							{
- 							Print (EError, "Unknown compression method! Set it to default (no compression)!");
- 							}
- 						gEnableCompress=EFalse;
-						gCompressionMethod = 0;
-						}
-					}
-					
-				}
-			else if (strcmp(argv[i], "-NO-SORTED-ROMFS")==0)
-				gSortedRomFs=EFalse;
-			else if (strcmp(argv[i], "-GENINC")==0)				// DEF095619
-				gGenInc=ETrue;
- 			else if (strcmp(argv[i], "-WSTDPATH")==0)			// Warn if destination path provided for a file		
- 				gEnableStdPathWarning=ETrue;					// is not a standard path as per platsec
-			else if( strcmp(argv[i], "-LOGLEVEL") == 0)
-				{
-				// next argument should a be loglevel
-				if( (i+1) >= argc || argv[i+1][0] == '-')
-					{
-					Print (EError, "Missing loglevel!");
-					gLogLevel = DEFAULT_LOG_LEVEL;
-					}
-				else
-					{
-					i++;
-					if (strcmp(argv[i], "4") == 0)
-						gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES | LOG_LEVEL_COMPRESSION_INFO | LOG_LEVEL_SMP_INFO);
-					else if (strcmp(argv[i], "3") == 0)
-						gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES | LOG_LEVEL_COMPRESSION_INFO);
-					else if (strcmp(argv[i], "2") == 0)
-						gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES);
-					else if (strcmp(argv[i], "1") == 0)
-						gLogLevel = LOG_LEVEL_FILE_DETAILS;
-					else if (strcmp(argv[i], "0") == 0)
-						gLogLevel = DEFAULT_LOG_LEVEL;
-					else
-						Print(EError, "Only loglevel 0, 1, 2, 3 or 4 is allowed!");
-					}
-				}
-			else if( strcmp(argv[i], "-LOGLEVEL4") == 0)
-				gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES | LOG_LEVEL_COMPRESSION_INFO | LOG_LEVEL_SMP_INFO);
-			else if( strcmp(argv[i], "-LOGLEVEL3") == 0)
-				gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES | LOG_LEVEL_COMPRESSION_INFO);
-			else if( strcmp(argv[i], "-LOGLEVEL2") == 0)
-				gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES);
-			else if( strcmp(argv[i], "-LOGLEVEL1") == 0)
-				gLogLevel = LOG_LEVEL_FILE_DETAILS;
-			else if( strcmp(argv[i], "-LOGLEVEL0") == 0)
-				gLogLevel = DEFAULT_LOG_LEVEL;
-			else if (argv[i][1] == 'D')
-				{
-				TraceMask=strtoul(argv[i]+2, 0, 0);
-				}
-			else if (strcmp(argv[i], "-LOWMEM") == 0)
-				gLowMem = ETrue;
-			else if (strncmp(argv[i], "-COREIMAGE=",11) ==0)
-			{  
-				if(argv[i][11])	
-				{
-					gUseCoreImage = ETrue; 
-					gImageFilename = (TText*)strdup(&argv[i][11]);	
-				}
-				else
-				{
-					Print (EError, "Core ROM image file is missing\n"); 
-				}
-			}
-			else 
-				cout << "Unrecognised option " << argv[i] << "\n";
-			}	
-		else // Must be the obey filename
-			filename=argv[i];
-		}
-	if (paramFileFlag)
-		return;
-	if (filename.empty())
-		{
-		PrintVersion();
-		cout << HelpText;
-		if (reallyHelp)
-			{
-			ObeyFileReader::KeywordHelp();
-			cout << ReallyHelpText;
-			}
-		else
-			Print(EError, "Obey filename is missing\n");
-		}	
-	}
-
-/**
-Function to process parameter-file. 
-
-@param aFileName parameter-file name.
-*/
-void processParamfile(string aFileName)
-{
-	CParameterFileProcessor parameterFile(aFileName);
-	
-	// Invoke fuction "ParameterFileProcessor" to process parameter-file.
-	if(parameterFile.ParameterFileProcessor())
-	{		
-		TUint noOfParameters = parameterFile.GetNoOfArguments();
-		char** parameters = parameterFile.GetParameters();
-		TBool paramFileFlag=ETrue;
-		
-		// Invoke function "processCommandLine" to process parameters read from parameter-file.
-		processCommandLine(noOfParameters, parameters, paramFileFlag);
-	}	
-}
-
-void GenerateIncludeFile(char* aRomName, TInt aUnpagedSize, TInt aPagedSize )
-	{
-	
-	const char * incFileNameExt = ".inc";
-	
-	TText* incFileName;
-	incFileName=new TText[strlen(aRomName) + strlen(incFileNameExt) + 1];  // Place for include file name and ".inc" extension and '\0'
-	strcpy((char *)incFileName, aRomName);
-	
-	char *p = (char*)strrchr((const char *)incFileName, '.');
-	if( NULL != p)
-		{
-		strncpy(p, incFileNameExt, strlen(incFileNameExt) + 1);				// copy extension and the '\0'
-		}
-	else
-		{
-		strcat((char *)incFileName, incFileNameExt);		//Doesn't cotains extension, add to it.
-		}
-		
-	Print(EAlways," (%s)\n", (const char *)incFileName);
-	
-	ofstream incFile((const char*)incFileName, ios::out);
-	if(!incFile)
-		{
-		Print(EError,"Cannot open include file %s for output\n",(const char *)incFileName);		
-		}
-	else
-		{
-		const char * incContent = 
-					"/** Size of the unpaged part of ROM.\n"
-	    			"This part is at the start of the ROM image. */\n"
-					"#define SYMBIAN_ROM_UNPAGED_SIZE 0x%08x\n"
-					"\n"
-					"/** Size of the demand paged part of ROM.\n"
-	    			"This part is stored immediately after the unpaged part in the ROM image. */\n"
-					"#define SYMBIAN_ROM_PAGED_SIZE 0x%08x\n";
-		
-		TText* temp = new TText[strlen(incContent)+ 2 * 8 + 1]; 	// for place of two hex representated values and '\0'
-		
-		sprintf((char *)temp,incContent, aUnpagedSize, aPagedSize);
-		incFile.write((const char *)temp, strlen((const char *)temp));
-		
-		incFile.close();
-		delete[]  temp;
-		}
-	delete[]  incFileName;
-		
-	}
-
-int main(int argc, char *argv[]) 
-{
-	H.SetLogFile((unsigned char *)"ROMBUILD.LOG");
-	TInt r = 0;
-	g_pCharCPUNum = getenv("NUMBER_OF_PROCESSORS");
-	if(g_pCharCPUNum != NULL)
-		gCPUNum = atoi(g_pCharCPUNum);
-		
-	// initialise set of all capabilities
-	ParseCapabilitiesArg(gPlatSecAllCaps, "all");
-
- 	processCommandLine(argc, argv);
- 	if(filename.empty())
-   		return KErrGeneral;
-		
-    if(gThreadNum == 0)
-	{
-		if(gCPUNum > 0 && gCPUNum <= MAXIMUM_THREADS)
-		{
-			Print(EAlways, "The number of processors (%d) is used as the number of concurrent jobs.\n", gCPUNum);
-			gThreadNum = gCPUNum;
-		}
-		else if(g_pCharCPUNum)
-		{
-			Print(EWarning, "The NUMBER_OF_PROCESSORS is invalid, and the default value %d will be used.\n", DEFAULT_THREADS);
-			gThreadNum = DEFAULT_THREADS;
-		}
-		else
-		{
-			Print(EWarning, "The NUMBER_OF_PROCESSORS is not available, and the default value %d will be used.\n", DEFAULT_THREADS);
-			gThreadNum = DEFAULT_THREADS;
-		}
-	}
- 	TText *obeyFileName= (TText*)filename.c_str();	
- 
-	PrintVersion();
-	
-	ObeyFileReader *reader=new ObeyFileReader(obeyFileName);
-	if (!reader->Open())
-	{
-		delete reader;
-		return KErrGeneral;
-	}
-	
-	E32Rom* kernelRom=0;		// for image from obey file
-	CoreRomImage *core= 0;		// for image from core image file
-	MRomImage* imageInfo=0;
-	CObeyFile *mainObeyFile=new CObeyFile(*reader);
-
-	// need check if obey file has coreimage keyword
-	TText *file = mainObeyFile->ProcessCoreImage();
-	if (file)
-	{
-		// hase coreimage keyword but only use if command line option
-		// for coreimage not already selected
-		if (!gUseCoreImage)
-		{
-			gUseCoreImage = ETrue;
-			gImageFilename = file;
-		}
-	}
-
-	if (!gUseCoreImage)
-	{
-		r=mainObeyFile->ProcessKernelRom();
-		if (r==KErrNone)
-		{
-				// Build a kernel ROM using the description compiled into the
-				// CObeyFile object
-				
-				kernelRom = new E32Rom(mainObeyFile);
-				if (kernelRom == 0 || kernelRom->iData == 0)
-					return KErrNoMemory;
-				
-				r=kernelRom->Create();
-				if (r!=KErrNone)
-				{
-					delete kernelRom;
-					delete mainObeyFile;
-					return r;
-				}
-				if (SizeSummary)
-					kernelRom->DisplaySizes(SizeWhere);
-				
-				r=kernelRom->WriteImages(gHeaderType);
-				if (r!=KErrNone)
-				{
-					delete kernelRom;
-					delete mainObeyFile;
-					return r;
-				}
-				
-				if (CompareRom)
-				{
-					r=kernelRom->Compare(CompareRom, gHeaderType);
-					if (r!=KErrNone)
-					{
-						delete kernelRom;
-						delete mainObeyFile;
-						return r;
-					}
-				}
-				imageInfo = kernelRom;
-				mainObeyFile->Release();
-		}
-		else if (r!=KErrNotFound)
-			return r;
-	}
-	else
-	{
-		// need to use core image
-		core = new CoreRomImage((char*)gImageFilename);
-		if (!core)
-		{
-			return KErrNoMemory;
-		}
-		if (!core->ProcessImage(gLowMem))
-		{
-			delete core;
-			delete mainObeyFile;
-			return KErrGeneral;
-		}
-		
-		NumberOfVariants = core->VariantCount();
-		TVariantList::SetNumVariants(NumberOfVariants);
-		TVariantList::SetVariants(core->VariantList());
-		
-		core->SetRomAlign(mainObeyFile->iRomAlign);
-		core->SetDataRunAddress(mainObeyFile->iDataRunAddress);
-
-		gCompressionMethod = core->CompressionType();
-		if(gCompressionMethod)
-		{
-			gEnableCompress = ETrue;
-		}
-		
-		imageInfo = core;
-		if(!mainObeyFile->SkipToExtension())
-		{
-			delete core;
-			delete mainObeyFile;
-			return KErrGeneral;
-		}
-	}
-	
-	if(gGenInc)
-	{
-		Print(EAlways,"Generating include file for ROM image post-processors ");
-		if( gPagedRom )
-		{
-			Print(EAlways,"Paged ROM");
-			GenerateIncludeFile((char*)mainObeyFile->iRomFileName, kernelRom->iHeader->iPageableRomStart, kernelRom->iHeader->iPageableRomSize);
-		}
-		else
-		{
-			Print(EAlways,"Unpaged ROM");
-			int headersize=(kernelRom->iExtensionRomHeader ? sizeof(TExtensionRomHeader) : sizeof(TRomHeader)) - sizeof(TRomLoaderHeader);
-			GenerateIncludeFile((char*)mainObeyFile->iRomFileName, kernelRom->iHeader->iCompressedSize + headersize, kernelRom->iHeader->iPageableRomSize);
-		}
-	}
-	
-	do
-	{
-		CObeyFile* extensionObeyFile = 0;
-		E32Rom* extensionRom = 0;
-
-		extensionObeyFile = new CObeyFile(*reader);
-		r = extensionObeyFile->ProcessExtensionRom(imageInfo);
-		if (r==KErrEof)
-		{
-			delete imageInfo;
-			delete mainObeyFile;
-			delete extensionObeyFile;
-			return KErrNone;
-		}
-		if (r!=KErrNone)
-		{
-			delete extensionObeyFile;
-			break;
-		}
-		
-		extensionRom = new E32Rom(extensionObeyFile);
-		r=extensionRom->CreateExtension(imageInfo);
-		if (r!=KErrNone)
-		{
-			delete extensionRom;
-			delete extensionObeyFile;
-			break;
-		}
-		if (SizeSummary)
-			extensionRom->DisplaySizes(SizeWhere);
-		
-		r=extensionRom->WriteImages(0);		// always a raw image
-		
-		delete extensionRom;
-		delete extensionObeyFile;
-	}
-	while (r==KErrNone);
-
-	delete imageInfo;
-	delete mainObeyFile;
-	free(gDepInfoFile); 
-	return r;
-}
+// Copyright (c) 2007-2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of the License "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:
+//
+
+#include <string.h>
+#include <stdlib.h>
+
+#include "h_utl.h"
+#include "h_ver.h"
+
+#include "r_global.h"
+#include "r_rom.h"
+#include "r_obey.h"
+#include "parameterfileprocessor.h"
+
+#include "r_dir.h"
+#include "r_coreimage.h"
+
+const TInt KRomLoaderHeaderNone=0;
+const TInt KRomLoaderHeaderEPOC=1;
+const TInt KRomLoaderHeaderCOFF=2;
+
+static const TInt RombuildMajorVersion=2;
+static const TInt RombuildMinorVersion=17;
+static const TInt RombuildPatchVersion=3;
+static TBool SizeSummary=EFalse;
+static TPrintType SizeWhere=EAlways;
+static string compareROMName = "";
+static TInt MAXIMUM_THREADS = 128;
+static TInt DEFAULT_THREADS = 8;
+
+string filename;			// to store oby filename passed to Rombuild.
+TBool reallyHelp=EFalse;
+TInt gCPUNum = 0;
+TInt gThreadNum = 0;
+char* g_pCharCPUNum = NULL;
+TBool gGenDepGraph = EFalse;
+string gDepInfoFile = "";
+TBool gGenSymbols = EFalse ;
+void PrintVersion() {
+ 	Print(EAlways,"\nROMBUILD - Rom builder");
+  	Print(EAlways, " V%d.%d.%d\n", RombuildMajorVersion, RombuildMinorVersion, RombuildPatchVersion);
+  	Print(EAlways,Copyright);
+	}
+
+char HelpText[] = 
+	"Syntax: ROMBUILD [options] obeyfilename\n"
+	"Option: -v verbose,  -?  \n"
+	"        -type-safe-link  \n"
+	"        -s[log|screen|both]           size summary\n"
+	"        -r<FileName>                  compare a sectioned Rom image\n"
+	"        -no-header                    suppress the image loader header\n"
+	"        -gendep                       generate the dependence graph for paged part\n"
+	"        -coff-header                  use a PE-COFF header rather than an EPOC header\n"
+	"        -d<bitmask>                   set trace mask (DEB build only)\n"
+	"        -compress[[=]paged|unpaged]   compress the ROM Image\n"
+	"                                      without any argumentum compress both sections\n"
+	"                                      paged 	compress paged section only\n"
+	"                                      unpaged 	compress unpaged section only\n\n"	
+	"        -j<digit>                     do the main job with <digit> threads\n"
+	"        -symbols                      generate symbol file\n"
+	"        -compressionmethod <method>   method one of none|inflate|bytepair to set the compression\n"
+	"        -no-sorted-romfs              do not add sorted entries arrays (6.1 compatible)\n"
+	"        -geninc                       to generate include file for licensee tools to use\n"			// DEF095619
+	"        -loglevel<level>              level of information to log (valid levels are 0,1,2,3,4).\n" //Tools like Visual ROM builder need the host/ROM filenames, size & if the file is hidden.
+	"        -wstdpath                     warn if destination path provided for a file is not a standard path\n"
+	"        -argfile=<fileName>           specify argument-file name containing list of command-line arguments to rombuild\n"
+	"        -lowmem                       use memory-mapped file for image build to reduce physical memory consumption\n"
+	"        -coreimage=<core image file>  to pass the core image as input for extension ROM image generation\n"
+	"        -k                            to enable keepgoing when duplicate files exist in oby\n";
+
+
+char ReallyHelpText[] =
+	"Priorities:\n"
+	"        low background foreground high windowserver\n"
+	"        fileserver realtimeserver supervisor\n"
+	"Languages:\n"
+	"        Test English French German Spanish Italian Swedish Danish\n"
+	"        Norwegian Finnish American SwissFrench SwissGerman Portuguese\n"
+	"        Turkish Icelandic Russian Hungarian Dutch BelgianFlemish\n"
+	"        Australian BelgianFrench\n"
+	"Compression methods:\n"
+	"        none     no compression on the individual executable image.\n"
+	"        inflate  compress the individual executable image.\n"
+	"        bytepair compress the individual executable image.\n"
+	"Log Level:\n"
+	"        0  produce the default logs\n"
+	"        1  produce file detail logs in addition to the default logs\n"
+	"        2  logs e32 header attributes(same as default log) in addition to the level 1 details\n";
+
+void processParamfile(const string& aFileName);
+//
+// Process the command line arguments, printing a helpful message if none are supplied
+//
+void processCommandLine(int argc, char *argv[], TBool paramFileFlag=EFalse) {
+ 
+	// If "-argfile" option is passed to Rombuild, then process the parameters
+	// specified in parameter-file first and then the options passed from the 
+	// command-line.
+	string ParamFileArg("-argfile=");	
+	if(paramFileFlag == EFalse) {
+ 		for (int count=1; count<argc; count++) {
+ 			string paramFile;
+			if(strnicmp(argv[count],ParamFileArg.c_str(),ParamFileArg.length())==0) {
+ 				paramFile.assign(&argv[count][ParamFileArg.length()]);					
+				processParamfile(paramFile);
+			}
+		}
+	}	
+	
+	for (int i=1; i<argc; i++) { 	
+#ifdef __LINUX__	
+		if (argv[i][0] == '-') 
+#else
+		if ((argv[i][0] == '-') || (argv[i][0] == '/'))
+#endif
+		{ // switch
+			char* arg = argv[i] + 1;
+			if (stricmp(arg, "symbols") == 0)  
+				gGenSymbols = ETrue; 
+			else if (stricmp(arg, "v") == 0)
+				H.iVerbose = ETrue;
+			else if (stricmp(arg, "sl") == 0 || stricmp(arg, "slog") == 0) {
+ 				SizeSummary = ETrue;
+				SizeWhere = ELog;
+			}
+			else if (stricmp(arg, "ss") == 0 || stricmp(arg, "sscreen") == 0) {
+				SizeSummary = ETrue;
+				SizeWhere = EScreen; 					
+			}
+			else if(stricmp(arg, "sb") == 0 || stricmp(arg, "sboth") == 0) {
+				SizeSummary = ETrue;
+				SizeWhere = EAlways; 					
+			}
+			else if (stricmp(arg, "gendep")==0)
+				gGenDepGraph = ETrue;
+			else if (stricmp(arg, "k")==0)
+				gKeepGoing = ETrue;
+			else if ('j' == *arg || 'J' == *arg) {
+				if(arg[1])
+					gThreadNum = atoi(arg + 1);
+				else {
+					Print(EWarning, "The option should be like '-j4'.\n");
+					gThreadNum = 0;
+				}
+				if(gThreadNum <= 0 || gThreadNum > MAXIMUM_THREADS) {
+					if(gCPUNum > 0 && gCPUNum <= MAXIMUM_THREADS) {
+						Print(EWarning, "The number of concurrent jobs set by -j should be between 1 and 128. And the number of processors %d will be used as the number of concurrent jobs.\n", gCPUNum);
+						gThreadNum = gCPUNum;
+					}
+					else if(g_pCharCPUNum) {
+						Print(EWarning, "The number of concurrent jobs set by -j should be between 1 and 128. And the NUMBER_OF_PROCESSORS is invalid, so the default value %d will be used.\n", DEFAULT_THREADS);
+						gThreadNum = DEFAULT_THREADS;
+					}
+					else {
+						Print(EWarning, "The number of concurrent jobs set by -j should be between 1 and 128. And the NUMBER_OF_PROCESSORS is not available, so the default value %d will be used.\n", DEFAULT_THREADS);
+						gThreadNum = DEFAULT_THREADS;
+					}
+				}	
+			} 
+			else if (strnicmp(argv[i],ParamFileArg.c_str(),ParamFileArg.length())==0) {
+ 				// If "-argfile" option is specified within parameter-file then process it 
+				// otherwise ignore the option.
+				if (paramFileFlag) {
+ 					string paramFile;
+					paramFile.assign(&argv[i][ParamFileArg.length()]);		
+					processParamfile(paramFile);
+				}
+				else {
+ 					continue;
+				}
+			}
+			else if ('t' == *arg || 'T' == *arg)
+				TypeSafeLink=ETrue;
+			else if (*arg == '?')
+				reallyHelp=ETrue;
+			else if ('r' == *arg || 'R' == *arg)
+				compareROMName.assign(arg + 1);
+			else if (stricmp(arg, "no-header")==0)
+				gHeaderType=KRomLoaderHeaderNone;
+			else if (stricmp(arg, "epoc-header")==0)
+				gHeaderType=KRomLoaderHeaderEPOC;
+			else if (stricmp(arg, "coff-header")==0)
+				gHeaderType=KRomLoaderHeaderCOFF;
+			else if ((stricmp(arg, "compress")==0) || (strnicmp(arg, "compress=", 9)==0))
+				{				
+				if((stricmp(arg, "compress")==0) && ((i+1) >= argc || argv[i+1][0] == '-'))
+					{
+					// No argument, compress both parts with default compression method
+					// un-paged part compressed by Deflate
+					gCompressUnpaged = ETrue;
+					gCompressUnpagedMethod = KUidCompressionDeflate;					
+					// paged part compressed by the Bytepiar
+					gEnableCompress=ETrue;
+					gCompressionMethod = KUidCompressionBytePair;
+					}
+				else 
+					{
+					const int paraMaxLen = 20;
+					char* parameter = new char[paraMaxLen];
+					memset(parameter, 0, paraMaxLen);
+					
+					if(strncmp(arg, "compress=", 9)==0)
+						{
+						int paraLen = strlen(arg + 9);
+						if (paraLen > paraMaxLen - 1)
+							{
+							delete[] parameter;
+							parameter = new char[paraLen + 1];
+							memset(parameter, 0, paraLen + 1);
+							}
+							
+						memcpy(parameter, arg + 9, paraLen);
+						}
+					else
+						{
+						int paraLen = strlen(argv[++i]);
+						if (paraLen > paraMaxLen - 1)
+							{
+							delete[] parameter;
+							parameter = new char[paraLen + 1];
+							memset(parameter, 0, paraLen + 1);
+							}
+						memcpy(parameter, argv[i], paraLen);
+						}
+					// An argument exists 
+					if( stricmp(parameter, "paged") == 0)
+						{
+						gEnableCompress=ETrue;
+						gCompressionMethod = KUidCompressionBytePair;	
+						}	
+					else if( stricmp(parameter, "unpaged") == 0)
+						{
+						gCompressUnpaged=ETrue;
+						gCompressUnpagedMethod = KUidCompressionDeflate;	
+						}	
+					else {
+  						Print (EError, "Unknown -compression argument! Set it to default (no compression)!");
+ 						gEnableCompress=EFalse;
+						gCompressionMethod = 0;
+						gCompressUnpaged = EFalse;
+						gCompressUnpagedMethod = 0;					
+						}
+						
+					delete[] parameter;
+					}
+				}	
+			else if( stricmp(arg, "compressionmethod") == 0 ) {
+ 				// next argument should be a method
+				if( (i+1) >= argc || argv[i+1][0] == '-') {
+ 					Print (EError, "Missing compression method! Set it to default (no compression)!");
+					gEnableCompress=EFalse;
+					gCompressionMethod = 0;
+					}
+				else  {
+ 					i++; 
+					if( stricmp(argv[i], "inflate") == 0) {
+ 						gEnableCompress=ETrue;
+						gCompressionMethod = KUidCompressionDeflate;	
+						}	
+					else if( stricmp(argv[i], "bytepair") == 0) {
+ 						gEnableCompress=ETrue;
+						gCompressionMethod = KUidCompressionBytePair;	
+						}	
+					else {
+  						if( stricmp(argv[i], "none") != 0) {
+  							Print (EError, "Unknown compression method! Set it to default (no compression)!");
+ 							}
+ 						gEnableCompress=EFalse;
+						gCompressionMethod = 0;
+						}
+					}
+					
+				}
+			else if (stricmp(arg, "no-sorted-romfs")==0)
+				gSortedRomFs=EFalse;
+			else if (stricmp(arg, "geninc")==0)				// DEF095619
+				gGenInc=ETrue;
+ 			else if (stricmp(arg, "wstdpath")==0)			// Warn if destination path provided for a file		
+ 				gEnableStdPathWarning=ETrue;					// is not a standard path as per platsec
+			else if( stricmp(arg, "loglevel") == 0) {
+ 				// next argument should a be loglevel
+				if( (i+1) >= argc || argv[i+1][0] == '-') {
+ 					Print (EError, "Missing loglevel!");
+					gLogLevel = DEFAULT_LOG_LEVEL;
+					}
+				else {
+ 					i++;
+					if (stricmp(argv[i], "4") == 0)
+						gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES | LOG_LEVEL_COMPRESSION_INFO | LOG_LEVEL_SMP_INFO);
+					else if (stricmp(argv[i], "3") == 0)
+						gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES | LOG_LEVEL_COMPRESSION_INFO);
+					else if (stricmp(argv[i], "2") == 0)
+						gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES);
+					else if (stricmp(argv[i], "1") == 0)
+						gLogLevel = LOG_LEVEL_FILE_DETAILS;
+					else if (stricmp(argv[i], "0") == 0)
+						gLogLevel = DEFAULT_LOG_LEVEL;
+					else
+						Print(EError, "Only loglevel 0, 1, 2, 3 or 4 is allowed!");
+					}
+				}
+			else if( stricmp(arg, "loglevel4") == 0)
+				gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES | LOG_LEVEL_COMPRESSION_INFO | LOG_LEVEL_SMP_INFO);
+			else if( stricmp(arg, "loglevel3") == 0)
+				gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES | LOG_LEVEL_COMPRESSION_INFO);
+			else if( stricmp(arg, "loglevel2") == 0)
+				gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES);
+			else if( stricmp(arg, "loglevel1") == 0)
+				gLogLevel = LOG_LEVEL_FILE_DETAILS;
+			else if( stricmp(arg, "loglevel0") == 0)
+				gLogLevel = DEFAULT_LOG_LEVEL;
+			else if ('d' == *arg || 'D' == *arg) {
+ 				TraceMask=strtoul(arg+1, 0, 0);
+				}
+			else if (stricmp(arg, "lowmem") == 0)
+				gLowMem = ETrue;
+			else if (strnicmp(arg, "coreimage=",10) ==0) {
+ 				if(argv[i][11])	 {
+ 					gUseCoreImage = ETrue; 
+					gImageFilename.assign(arg + 10);	
+				}
+				else {
+ 					Print (EError, "Core ROM image file is missing\n"); 
+				}
+			}
+			else 
+#ifdef WIN32
+				cout << "Unrecognised option " << argv[i] << "\n";
+#else
+				if(0 == access(argv[i],R_OK)){
+					filename.assign(argv[i]);
+				}
+				else {
+					cout << "Unrecognised option " << argv[i] << "\n";
+				}
+#endif		
+			}	
+		else // Must be the obey filename
+			filename.assign(argv[i]);
+		}
+	if (paramFileFlag)
+		return;
+	if (filename.empty()) {
+ 		PrintVersion();
+		cout << HelpText;
+		if (reallyHelp) {
+ 			ObeyFileReader::KeywordHelp();
+			cout << ReallyHelpText;
+			}
+		else
+			Print(EError, "Obey filename is missing\n");
+		}	
+	}
+
+/**
+Function to process parameter-file. 
+
+@param aFileName parameter-file name.
+*/
+void processParamfile(const string& aFileName) {
+ 	CParameterFileProcessor parameterFile(aFileName);
+	
+	// Invoke fuction "ParameterFileProcessor" to process parameter-file.
+	if(parameterFile.ParameterFileProcessor()) {
+ 		TUint noOfParameters = parameterFile.GetNoOfArguments();
+		char** parameters = parameterFile.GetParameters();
+		TBool paramFileFlag=ETrue;
+		
+		// Invoke function "processCommandLine" to process parameters read from parameter-file.
+		processCommandLine(noOfParameters, parameters, paramFileFlag);
+	}	
+}
+
+void GenerateIncludeFile(const char* aRomName, TInt aUnpagedSize, TInt aPagedSize ) {
+ 	
+ 
+	string incFileName(aRomName);
+	int pos = -1 ;
+	for(int i = incFileName.length() - 1 ; i >= 0 ; i--){
+		char ch = incFileName[i];
+		if(ch == '/' || ch == '\\') 
+			break ;
+		else if(ch == '.'){
+			pos = i ;
+			break ;
+		}		
+	}	
+	if(pos > 0)
+		incFileName.erase(pos,incFileName.length() - pos);
+	incFileName += ".inc"; 
+	
+	ofstream incFile(incFileName.c_str(),ios_base::trunc + ios_base::out);
+	if(!incFile.is_open()) {
+ 		Print(EError,"Cannot open include file %s for output\n", incFileName.c_str());		
+	}
+	else {
+ 		const char incContent[] = 
+					"/** Size of the unpaged part of ROM.\n"
+	    			"This part is at the start of the ROM image. */\n"
+					"#define SYMBIAN_ROM_UNPAGED_SIZE 0x%08x\n"
+					"\n"
+					"/** Size of the demand paged part of ROM.\n"
+	    			"This part is stored immediately after the unpaged part in the ROM image. */\n"
+					"#define SYMBIAN_ROM_PAGED_SIZE 0x%08x\n";
+		// for place of two hex representated values and '\0'
+		char* temp = new char[sizeof(incContent)+ 20]; 		
+		size_t len = sprintf(temp,incContent, aUnpagedSize, aPagedSize);
+		incFile.write(temp, len);		
+		incFile.close();
+		delete[]  temp;
+	} 		
+}
+
+int main(int argc, char *argv[])  {
+ 	H.SetLogFile("ROMBUILD.LOG");
+	TInt r = 0;
+#ifdef __LINUX__
+	gCPUNum = sysconf(_SC_NPROCESSORS_CONF);
+#else
+	g_pCharCPUNum = getenv("NUMBER_OF_PROCESSORS");
+	if(g_pCharCPUNum != NULL)
+		gCPUNum = atoi(g_pCharCPUNum);
+#endif		
+	// initialise set of all capabilities
+	ParseCapabilitiesArg(gPlatSecAllCaps, "all");
+
+ 	processCommandLine(argc, argv);
+ 	if(filename.empty())
+   		return KErrGeneral;
+		
+    if(gThreadNum == 0) {
+ 		if(gCPUNum > 0 && gCPUNum <= MAXIMUM_THREADS) {
+ 			Print(EAlways, "The number of processors (%d) is used as the number of concurrent jobs.\n", gCPUNum);
+			gThreadNum = gCPUNum;
+		}
+		else if(g_pCharCPUNum) {
+ 			Print(EWarning, "The NUMBER_OF_PROCESSORS is invalid, and the default value %d will be used.\n", DEFAULT_THREADS);
+			gThreadNum = DEFAULT_THREADS;
+		}
+		else {
+ 			Print(EWarning, "The NUMBER_OF_PROCESSORS is not available, and the default value %d will be used.\n", DEFAULT_THREADS);
+			gThreadNum = DEFAULT_THREADS;
+		}
+	} 
+	PrintVersion();
+	
+	ObeyFileReader *reader=new ObeyFileReader(filename.c_str());
+	if (!reader->Open()) {
+ 		delete reader;
+		return KErrGeneral;
+	}
+	
+	E32Rom* kernelRom=0;		// for image from obey file
+	CoreRomImage *core= 0;		// for image from core image file
+	MRomImage* imageInfo=0;
+	CObeyFile *mainObeyFile=new CObeyFile(*reader);
+
+	// need check if obey file has coreimage keyword
+	char* file = mainObeyFile->ProcessCoreImage();
+	if (file) {
+ 		// hase coreimage keyword but only use if command line option
+		// for coreimage not already selected
+		if (!gUseCoreImage) {
+ 			gUseCoreImage = ETrue;
+			gImageFilename = file;
+		}	 
+		delete []file ;
+	}
+
+	if (!gUseCoreImage) {
+ 		r=mainObeyFile->ProcessKernelRom();
+		if (r==KErrNone) {
+ 				// Build a kernel ROM using the description compiled into the
+				// CObeyFile object
+				
+				kernelRom = new E32Rom(mainObeyFile);
+				if (kernelRom == 0 || kernelRom->iData == 0)
+					return KErrNoMemory;
+				
+				r=kernelRom->Create();
+				if (r!=KErrNone) {
+ 					delete kernelRom;
+					delete mainObeyFile;
+					return r;
+				}
+				if (SizeSummary)
+					kernelRom->DisplaySizes(SizeWhere);
+				
+				r=kernelRom->WriteImages(gHeaderType);
+				if (r!=KErrNone) {
+ 					delete kernelRom;
+					delete mainObeyFile;
+					return r;
+				}
+				
+				if (compareROMName.length() > 0 ) {
+ 					r=kernelRom->Compare(compareROMName.c_str(), gHeaderType);
+					if (r!=KErrNone) {
+ 						delete kernelRom;
+						delete mainObeyFile;
+						return r;
+					}
+				}
+				imageInfo = kernelRom;
+				mainObeyFile->Release();
+		}
+		else if (r!=KErrNotFound)
+			return r;
+	}
+	else {
+ 		// need to use core image
+		core = new CoreRomImage(gImageFilename.c_str());
+		if (!core) {
+ 			return KErrNoMemory;
+		}
+		if (!core->ProcessImage(gLowMem)) {
+ 			delete core;
+			delete mainObeyFile;
+			return KErrGeneral;
+		}
+		
+		NumberOfVariants = core->VariantCount();
+		TVariantList::SetNumVariants(NumberOfVariants);
+		TVariantList::SetVariants(core->VariantList());
+		
+		core->SetRomAlign(mainObeyFile->iRomAlign);
+		core->SetDataRunAddress(mainObeyFile->iDataRunAddress);
+
+		gCompressionMethod = core->CompressionType();
+		if(gCompressionMethod) {
+ 			gEnableCompress = ETrue;
+		}
+		
+		imageInfo = core;
+		if(!mainObeyFile->SkipToExtension()) {
+ 			delete core;
+			delete mainObeyFile;
+			return KErrGeneral;
+		}
+	}
+	
+	if(gGenInc) {
+ 		Print(EAlways,"Generating include file for ROM image post-processors ");
+		if( gPagedRom ) {
+ 			Print(EAlways,"Paged ROM");
+			GenerateIncludeFile((char*)mainObeyFile->iRomFileName, kernelRom->iHeader->iPageableRomStart, kernelRom->iHeader->iPageableRomSize);
+		}
+		else {
+ 			Print(EAlways,"Unpaged ROM");
+			int headersize=(kernelRom->iExtensionRomHeader ? sizeof(TExtensionRomHeader) : sizeof(TRomHeader)) - sizeof(TRomLoaderHeader);
+			GenerateIncludeFile((char*)mainObeyFile->iRomFileName, kernelRom->iHeader->iCompressedSize + headersize, kernelRom->iHeader->iPageableRomSize);
+		}
+	}
+	
+	do {
+ 		CObeyFile* extensionObeyFile = 0;
+		E32Rom* extensionRom = 0;
+
+		extensionObeyFile = new CObeyFile(*reader);
+		r = extensionObeyFile->ProcessExtensionRom(imageInfo);
+		if (r==KErrEof) {
+ 			delete imageInfo;
+			delete mainObeyFile;
+			delete extensionObeyFile;
+			return KErrNone;
+		}
+		if (r!=KErrNone) {
+ 			delete extensionObeyFile;
+			break;
+		}
+		
+		extensionRom = new E32Rom(extensionObeyFile);
+		r=extensionRom->CreateExtension(imageInfo);
+		if (r!=KErrNone) {
+ 			delete extensionRom;
+			delete extensionObeyFile;
+			break;
+		}
+		if (SizeSummary)
+			extensionRom->DisplaySizes(SizeWhere);
+		
+		r=extensionRom->WriteImages(0);		// always a raw image
+		
+		delete extensionRom;
+		delete extensionObeyFile;
+	}
+	while (r==KErrNone);
+
+	delete imageInfo;
+	delete mainObeyFile;
+ 
+	return r;
+}
--- a/imgtools/romtools/rombuild/rombuild.mmp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/rombuild.mmp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,60 +1,56 @@
-/*
-* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-
-target			rombuild.exe
-targettype		exe
-
-sourcepath	.
-source			 r_dir.cpp r_header.cpp r_obey.cpp r_srec.cpp
-source			 r_rom.cpp rombuild.cpp r_build.cpp r_collapse.cpp
-source			 r_global.cpp r_areaset.cpp
-source			 r_coreimage.cpp r_coreimagereader.cpp
-sourcepath	../../imglib/e32uid
-source			e32uid.cpp
-sourcepath	../../imglib/host
-source			h_file.cpp h_mem.cpp h_utl.cpp
-sourcepath	../../imglib/e32image
-source			e32image.cpp
-sourcepath	../../imglib/e32image/deflate
-source			decode.cpp encode.cpp deflate.cpp inflate.cpp panic.cpp
-source			compress.cpp
-sourcepath	../../imglib/compress
-source			byte_pair.cpp
-source			pagedcompress.cpp
-
-userinclude	../../imglib/compress 	../../imglib/inc 
-userinclude	../../imglib/patchdataprocessor/include ../../imglib/parameterfileprocessor/include
-userinclude ../../imglib/memmap/include
-userinclude	../../imglib/boostlibrary/
-
-OS_LAYER_SYSTEMINCLUDE_SYMBIAN
-
-staticlibrary	patchdataprocessor
-staticlibrary   parameterfileprocessor
-staticlibrary 	memmap
-
-#ifdef TOOLS2_LINUX
-STATICLIBRARY   boost_thread-mgw34-mt-1_39_linux
-OPTION    GCC -O2 -Wno-uninitialized -pthread
-#else
-STATICLIBRARY   boost_thread-mgw34-mt-1_39_win32
-OPTION    GCC -O2 -Wno-uninitialized -mthreads
-#endif
-
-VENDORID 0x70000001
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+
+target			rombuild.exe
+targettype		exe
+
+sourcepath	.
+source			 r_dir.cpp r_header.cpp r_obey.cpp r_srec.cpp
+source			 r_rom.cpp rombuild.cpp r_build.cpp r_collapse.cpp
+source			 r_global.cpp r_areaset.cpp
+source			 r_coreimage.cpp r_coreimagereader.cpp symbolgenerator.cpp
+sourcepath	../../imglib/e32uid
+source			e32uid.cpp
+sourcepath	../../imglib/host
+source			h_file.cpp h_mem.cpp h_utl.cpp utf16string.cpp
+sourcepath	../../imglib/e32image
+source			e32image.cpp
+sourcepath	../../imglib/e32image/deflate
+source			decode.cpp encode.cpp deflate.cpp inflate.cpp panic.cpp
+source			compress.cpp
+sourcepath	../../imglib/compress
+source			byte_pair.cpp
+source			pagedcompress.cpp
+
+userinclude	../../imglib/compress 	../../imglib/inc 
+userinclude	../../imglib/patchdataprocessor/include ../../imglib/parameterfileprocessor/include
+userinclude ../../imglib/memmap/include
+userinclude	../../imglib/boostlibrary/
+
+OS_LAYER_SYSTEMINCLUDE_SYMBIAN
+
+staticlibrary	patchdataprocessor parameterfileprocessor memmap boost_thread-1.39
+
+#ifdef TOOLS2_LINUX
+OPTION    GCC -O2 -Wno-uninitialized -pthread
+#else
+OPTION    GCC -O2 -Wno-uninitialized -mthreads
+#endif
+
+VENDORID 0x70000001
--- a/imgtools/romtools/rombuild/rombuild_mingw.mk	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/romtools/rombuild/rombuild_mingw.mk	Tue Jun 29 14:52:54 2010 +0800
@@ -34,6 +34,7 @@
          r_collapse.cpp \
          r_coreimage.cpp \
          r_coreimagereader.cpp \
+         symbolgenerator.cpp \
 		 r_dir.cpp \
 		 r_global.cpp \
          r_header.cpp \
--- a/imgtools/sisutils/group/sisutils.mmp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/sisutils/group/sisutils.mmp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,32 +1,36 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-target			libsisutils.a
-targettype		lib
-
-sourcepath	../src
-source		sisutils.cpp sis2iby.cpp pkglanguage.cpp pkgfileparser.cpp
-
-userinclude	../inc
-
-OS_LAYER_SYSTEMINCLUDE_SYMBIAN
-
-option GCC -O2 -Wno-uninitialized
-
-VENDORID 0x70000001
-
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+target			libsisutils.a
+targettype		lib
+
+sourcepath	../src
+source		sisutils.cpp sis2iby.cpp pkglanguage.cpp pkgfileparser.cpp
+
+sourcepath	../../imglib/host
+source		utf16string.cpp
+
+userinclude	../inc
+userinclude	../../imglib/inc
+
+OS_LAYER_SYSTEMINCLUDE_SYMBIAN
+
+option GCC -O2 -Wno-uninitialized
+
+VENDORID 0x70000001
+
--- a/imgtools/sisutils/group/sisutils.mrp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/sisutils/group/sisutils.mrp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,7 +1,7 @@
 component	dev_build_imgtools_sisutils
-source	\src\tools\dev\build\imgtools\sisutils
-binary	\src\tools\dev\build\imgtools\sisutils\group all
-exports	\src\tools\dev\build\imgtools\sisutils\group
+source	\src\tools\build\imgtools\sisutils
+binary	\src\tools\build\imgtools\sisutils\group all
+exports	\src\tools\build\imgtools\sisutils\group
 
 notes_source	\component_defs\release.src
 
--- a/imgtools/sisutils/inc/pkgfileparser.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/sisutils/inc/pkgfileparser.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,204 +1,210 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifndef __PKGFILEPARSER_H__
-#define __PKGFILEPARSER_H__
-
-#ifdef WIN32
-#include <windows.h>
-#endif
-
-#include <iostream>
-
-#include <sstream>
-#include <string>
-#include <list>
-#include <map>
-#undef _L
-
-#include "pkglanguage.h"
-
-typedef class PkgParser PKGPARSER, *PPKGPARSER;
-
-//Data structures for pkg file parsing
-#define EOF_TOKEN			0
-#define NUMERIC_TOKEN		1
-#define ALPHA_TOKEN			2
-#define QUOTED_STRING_TOKEN	3
-#define AND_TOKEN			4
-#define OR_TOKEN			5
-#define NOT_TOKEN			6
-#define EXISTS_TOKEN		7
-#define DEVCAP_TOKEN		8
-#define APPCAP_TOKEN		9
-#define GE_TOKEN			10
-#define LE_TOKEN			11
-#define NE_TOKEN			12
-#define IF_TOKEN			13
-#define ELSEIF_TOKEN		14
-#define ELSE_TOKEN			15
-#define ENDIF_TOKEN			16
-#define TYPE_TOKEN			17
-#define KEY_TOKEN			18
-#define LAST_TOKEN			18
-
-#define MAX_STRING 255
-
-typedef union _tag_VARIANTVAL
-{
-	long dwNumber;					// numeric value, e.g. 100
-	wchar_t pszString[MAX_STRING];	// string value, e.g. "crystal"
-}VARIANTVAL;
-
-//Data structures to store the pkg file contents
-/**
-Supported package body statements
-*/
-typedef enum cmd_type {IF, ELSEIF, ELSE, ENDIF, INSTALLFILE, PACKAGE} CMD_TYPE;
-
-/**
-Structure to store the language details
-*/
-typedef struct _tag_LangList
-{
-	String langName;  // Language Name
-	unsigned long langCode; // Language code
-	unsigned long dialectCode; // Dialect code
-}LANG_LIST, *PLANG_LIST;
-
-/**
-Structure to store the package file header details
-*/
-typedef struct _tag_Pkgheader
-{
-	std::list<String> pkgNameList;
-	unsigned long pkgUid;
-	int vMajor;
-	int vMinor;
-	int vBuild;
-	String pkgType;
-}PKG_HEADER, *PPKG_HEADER;
-
-/**
-Structure to store the installable file list
-*/
-typedef struct _tag_InstallFileList
-{
-	int langDepFlg;
-	int pkgFlg;
-	std::list<String> srcFiles;
-	String destFile;
-}INSTALLFILE_LIST, *PINSTALLFILE_LIST;
-
-/**
-Structure to store the package body details
-*/
-typedef struct _tag_CmdBlock
-{
-	CMD_TYPE cmdType; // Command type
-	String cmdExpression; // Expression
-	PINSTALLFILE_LIST iInstallFileList; // Installable file details
-}CMD_BLOCK, *PCMD_BLOCK;
-
-typedef std::list<PLANG_LIST> LANGUAGE_LIST;
-typedef std::list<String> SISFILE_LIST, FILE_LIST;
-typedef std::list<PCMD_BLOCK> CMDBLOCK_LIST;
-
-/** 
-class PkgParser
-	Parses the package file generated by DUMPSIS tool
-
-@internalComponent
-@released
-*/
-class PkgParser
-{
-public:
-	PkgParser(String aFile);
-	~PkgParser();
-
-	void ParsePkgFile();
-	void GetEmbeddedSisList(SISFILE_LIST& embedSisList);
-	void GetInstallOptions(FILE_LIST& aOptions);
-	void GetLanguageList(LANGUAGE_LIST& langList);
-	void GetHeader(PKG_HEADER& pkgHeader);
-	void GetCommandList(CMDBLOCK_LIST& cmdList);
-	String GetPkgFileName()
-	{
-		return iPkgFile;
-	}
-
-private:
-	int OpenFile();
-	void DeleteAll();
-
-	HANDLE iPkgHandle;
-
-	LANGUAGE_LIST iLangList;
-	PKG_HEADER iPkgHeader;
-	SISFILE_LIST iEmbedSisFiles;
-	FILE_LIST iInstallOptions;
-	CMDBLOCK_LIST iPkgBlock;
-
-	String iPkgFile;
-
-	//Parser Methods
-	void AddLanguage(String aLang, unsigned long aCode, unsigned long aDialect);
-	void GetNextChar();
-	void GetNextToken();
-	bool GetStringToken();
-	WORD ParseEscapeChars();
-	void GetAlphaNumericToken();
-	bool IsNumericToken();
-	void GetNumericToken();
-	void ParseEmbeddedBlockL ();
-	void ParseCommentL();
-	void ExpectToken(int aToken);
-	void ParseHeaderL();
-	void ParseLanguagesL();
-	void ParseFileL();
-	void ParsePackageL();
-	void ParseIfBlockL();
-	void ParseLogicalOp(String& aExpression);
-	void ParseRelation(String& aExpression);
-	void ParseUnary(String& aExpression);
-	void ParseFactor(String& aExpression);
-	void ParseOptionsBlockL();
-	void ParsePropertyL();
-	void ParseVendorNameL();
-	void ParseLogoL();
-	void ParseDependencyL();
-	void ParseVersion();
-	void ParseVendorUniqueNameL();
-	void ParseTargetDeviceL();
-
-	//Parser Attributes
-	wchar_t m_pkgChar;
-	int m_token;
-	VARIANTVAL m_tokenValue;
-	int m_nLineNo;
-
-	void ParserError(char* msg);
-
-	friend String wstring2string (const std::wstring& aWide);
-	friend std::wstring string2wstring (const String& aNarrow);
-	friend int CompareTwoString(wchar_t* string ,wchar_t* option);
-	friend int CompareNString(wchar_t* string ,wchar_t* option, int len);
-};
-
-#endif //__PKGFILEPARSER_H__
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifndef __PKGFILEPARSER_H__
+#define __PKGFILEPARSER_H__
+
+#ifdef WIN32
+#ifdef _STLP_INTERNAL_WINDOWS_H
+#define __INTERLOCKED_DECLARED
+#endif
+#include <windows.h>
+#endif
+
+#include <iostream>
+
+#include <sstream>
+#include <string>
+#include <list>
+#include <map>
+#undef _L
+
+#include "pkglanguage.h"
+
+typedef class PkgParser PKGPARSER, *PPKGPARSER;
+
+//Data structures for pkg file parsing
+#define EOF_TOKEN			0
+#define NUMERIC_TOKEN		1
+#define ALPHA_TOKEN			2
+#define QUOTED_STRING_TOKEN	3
+#define AND_TOKEN			4
+#define OR_TOKEN			5
+#define NOT_TOKEN			6
+#define EXISTS_TOKEN		7
+#define DEVCAP_TOKEN		8
+#define APPCAP_TOKEN		9
+#define GE_TOKEN			10
+#define LE_TOKEN			11
+#define NE_TOKEN			12
+#define IF_TOKEN			13
+#define ELSEIF_TOKEN		14
+#define ELSE_TOKEN			15
+#define ENDIF_TOKEN			16
+#define TYPE_TOKEN			17
+#define KEY_TOKEN			18
+#define LAST_TOKEN			18
+
+#define MAX_STRING 255
+
+typedef union _tag_VARIANTVAL
+{
+	TInt32 iNumber;					// numeric value, e.g. 100
+	char iString[MAX_STRING];	// string value, e.g. "crystal"
+}VARIANTVAL;
+
+//Data structures to store the pkg file contents
+/**
+Supported package body statements
+*/
+typedef enum cmd_type {IF, ELSEIF, ELSE, ENDIF, INSTALLFILE, PACKAGE} CMD_TYPE;
+
+/**
+Structure to store the language details
+*/
+typedef struct _tag_LangList
+{
+	string iLangName;  // Language Name
+	TUint32 iLangCode; // Language code
+	TUint32 iDialectCode; // Dialect code
+}LANG_LIST, *PLANG_LIST;
+
+/**
+Structure to store the package file header details
+*/
+typedef struct _tag_Pkgheader
+{
+	list<string> iPkgNames;
+	TUint32 iPkgUID;
+	TInt iMajorVersion;
+	TInt iMinorVersion;
+	TInt iBuildVersion;
+	string iPkgType;
+}PKG_HEADER, *PPKG_HEADER;
+
+/**
+Structure to store the installable file list
+*/
+typedef struct _tag_InstallFileList
+{
+	TInt iLangDepFlag;
+	TInt iPkgFlag;
+	list<string> iSourceFiles;
+	string iDestFile;
+}INSTALLFILE_LIST, *PINSTALLFILE_LIST;
+
+/**
+Structure to store the package body details
+*/
+typedef struct _tag_CmdBlock
+{
+	CMD_TYPE iCmdType; // Command type
+	string iCmdExpr; // Expression
+	PINSTALLFILE_LIST iInstallFileList; // Installable file details
+}CMD_BLOCK, *PCMD_BLOCK;
+
+typedef list<PLANG_LIST> LANGUAGE_LIST;
+typedef list<string> SISFILE_LIST, FILE_LIST;
+typedef list<PCMD_BLOCK> CMDBLOCK_LIST;
+
+/** 
+class PkgParser
+	Parses the package file generated by DUMPSIS tool
+
+@internalComponent
+@released
+*/
+class PkgParser
+{
+public:
+	PkgParser(const string& aFile);
+	~PkgParser();
+
+	void ParsePkgFile();
+	void GetEmbeddedSisList(SISFILE_LIST& embedSisList);
+	void GetInstallOptions(FILE_LIST& aOptions);
+	void GetLanguageList(LANGUAGE_LIST& langList);
+	void GetHeader(PKG_HEADER& pkgHeader);
+	void GetCommandList(CMDBLOCK_LIST& cmdList);
+	const char* GetPkgFileName(){
+		return iPkgFileName.c_str();
+	}
+
+private:
+	bool OpenFile();
+	void DeleteAll(); 
+	
+	const char* iPkgFileContent ;
+	TUint iContentPos ;
+	string iContentStr  ;
+
+	LANGUAGE_LIST iLangList;
+	PKG_HEADER iPkgHeader;
+	SISFILE_LIST iEmbedSisFiles;
+	FILE_LIST iInstallOptions;
+	CMDBLOCK_LIST iPkgBlock;
+
+	string iPkgFileName;
+
+	//Parser Methods
+	void AddLanguage(const string& aLang, TUint32 aCode, TUint32 aDialect);
+	 
+	void GetNextChar() ;
+	inline char GetCurChar() const {
+		return iPkgFileContent[iContentPos] ;
+	}
+	void GetNextToken();
+	bool GetStringToken();
+	TUint16 ParseEscapeChars();
+	void GetAlphaNumericToken();
+	bool IsNumericToken();
+	void GetNumericToken();
+	void ParseEmbeddedBlockL ();
+	void ParseCommentL();
+	inline void ExpectToken(TInt aToken) { 
+		if (iToken!=aToken) 
+			ParserError("Unexpected Token"); 
+	}
+	void ParseHeaderL();
+	void ParseLanguagesL();
+	void ParseFileL();
+	void ParsePackageL();
+	void ParseIfBlockL();
+	void ParseLogicalOp(string& aExpression);
+	void ParseRelation(string& aExpression);
+	void ParseUnary(string& aExpression);
+	void ParseFactor(string& aExpression);
+	void ParseOptionsBlockL();
+	void ParsePropertyL();
+	void ParseVendorNameL();
+	void ParseLogoL();
+	void ParseDependencyL();
+	void ParseVersion();
+	void ParseVendorUniqueNameL();
+	void ParseTargetDeviceL();
+
+	//Parser Attributes 
+	TInt iToken;
+	VARIANTVAL iTokenVal;
+	TInt iLineNumber;
+
+	void ParserError(const char* aMsg);
+ 
+};
+ 
+#endif //__PKGFILEPARSER_H__
--- a/imgtools/sisutils/inc/pkglanguage.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/sisutils/inc/pkglanguage.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,255 +1,254 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifndef __PKGLANGUAGE_H__
-#define __PKGLANGUAGE_H__
-
-#ifdef _MSC_VER 
-	#pragma warning(disable: 4786) // identifier was truncated to '255' characters in the debug information
-	#pragma warning(disable: 4503) // decorated name length exceeded, name was truncated
-#endif
-
-typedef struct
-{
-	wchar_t*		iName;
-	unsigned long	iId;
-} SKeyword;
-
-/** 
-class PkgLanguage
-	Lookup table for the languages supported
-
-@internalComponent
-@released
-*/
-class PkgLanguage
-{
-public:
-	typedef enum 
-	{
-		//This list is lifted directly from E32std.h
-		ELangTest = 0,
-		/** UK English. */
-		ELangEnglish = 1,
-		/** French. */
-		ELangFrench = 2,
-		/** German. */
-		ELangGerman = 3,
-		/** Spanish. */
-		ELangSpanish = 4,
-		/** Italian. */
-		ELangItalian = 5,
-		/** Swedish. */
-		ELangSwedish = 6,
-		/** Danish. */
-		ELangDanish = 7,
-		/** Norwegian. */
-		ELangNorwegian = 8,
-		/** Finnish. */
-		ELangFinnish = 9,
-		/** American. */
-		ELangAmerican = 10,
-		/** Swiss French. */
-		ELangSwissFrench = 11,
-		/** Swiss German. */
-		ELangSwissGerman = 12,
-		/** Portuguese. */
-		ELangPortuguese = 13,
-		/** Turkish. */
-		ELangTurkish = 14,
-		/** Icelandic. */
-		ELangIcelandic = 15,
-		/** Russian. */
-		ELangRussian = 16,
-		/** Hungarian. */
-		ELangHungarian = 17,
-		/** Dutch. */
-		ELangDutch = 18,
-		/** Belgian Flemish. */
-		ELangBelgianFlemish = 19,
-		/** Australian English. */
-		ELangAustralian = 20,
-		/** Belgian French. */
-		ELangBelgianFrench = 21,
-		/** Austrian German. */
-		ELangAustrian = 22,
-		/** New Zealand English. */
-		ELangNewZealand = 23,
-		/** International French. */
-		ELangInternationalFrench = 24,
-		/** Czech. */
-		ELangCzech = 25,
-		/** Slovak. */
-		ELangSlovak = 26,
-		/** Polish. */
-		ELangPolish = 27,
-		/** Slovenian. */
-		ELangSlovenian = 28,
-		/** Taiwanese Chinese. */
-		ELangTaiwanChinese = 29,
-		/** Hong Kong Chinese. */
-		ELangHongKongChinese = 30,
-		/** Peoples Republic of China Chinese. */
-		ELangPrcChinese = 31,
-		/** Japanese. */
-		ELangJapanese = 32,
-		/** Thai. */
-		ELangThai = 33,
-		/** Afrikaans. */
-		ELangAfrikaans = 34,
-		/** Albanian. */
-		ELangAlbanian = 35,
-		/** Amharic. */
-		ELangAmharic = 36,
-		/** Arabic.*/
-		ELangArabic = 37,
-		/** Armenian. */
-		ELangArmenian = 38,
-		/** Tagalog. */
-		ELangTagalog = 39,
-		/** Belarussian. */
-		ELangBelarussian = 40,
-		/** Bengali. */ 
-		ELangBengali = 41,
-		/** Bulgarian. */
-		ELangBulgarian = 42,
-		/** Burmese. */ 
-		ELangBurmese = 43,
-		/** Catalan. */
-		ELangCatalan = 44,
-		/** Croation. */
-		ELangCroatian = 45,
-		/** Canadian English. */
-		ELangCanadianEnglish = 46,
-		/** International English. */
-		ELangInternationalEnglish = 47,
-		/** South African English. */
-		ELangSouthAfricanEnglish = 48,
-		/** Estonian. */
-		ELangEstonian = 49,
-		/** Farsi. */
-		ELangFarsi = 50,
-		/** Canadian French. */
-		ELangCanadianFrench = 51,
-		/** Gaelic. */
-		ELangScotsGaelic = 52,
-		/** Georgian. */
-		ELangGeorgian = 53,
-		/** Greek. */ 
-		ELangGreek = 54,
-		/** Cyprus Greek. */
-		ELangCyprusGreek = 55,
-		/** Gujarati. */
-		ELangGujarati = 56,
-		/** Hebrew. */
-		ELangHebrew = 57,
-		/** Hindi. */ 
-		ELangHindi = 58,
-		/** Indonesian. */
-		ELangIndonesian = 59,
-		/** Irish. */
-		ELangIrish = 60,
-		/** Swiss Italian. */
-		ELangSwissItalian = 61,
-		/** Kannada. */
-		ELangKannada = 62,
-		/** Kazakh. */
-		ELangKazakh = 63,
-		/** Kmer. */
-		ELangKhmer = 64,
-		/** Korean. */
-		ELangKorean = 65,
-		/** Lao. */
-		ELangLao = 66,
-		/** Latvian. */
-		ELangLatvian = 67,
-		/** Lithuanian. */
-		ELangLithuanian = 68,
-		/** Macedonian. */
-		ELangMacedonian = 69,
-		/** Malay. */
-		ELangMalay = 70,
-		/** Malayalam. */
-		ELangMalayalam = 71,
-		/** Marathi. */ 
-		ELangMarathi = 72,
-		/** Moldovian. */
-		ELangMoldavian = 73,
-		/** Mongolian. */
-		ELangMongolian = 74,
-		/** Norwegian Nynorsk. */
-		ELangNorwegianNynorsk = 75,
-		/** Brazilian Portuguese. */
-		ELangBrazilianPortuguese = 76,
-		/** Punjabi. */
-		ELangPunjabi = 77,
-		/** Romanian. */
-		ELangRomanian = 78,
-		/** Serbian. */
-		ELangSerbian = 79,
-		/** Sinhalese. */
-		ELangSinhalese = 80,
-		/** Somali. */
-		ELangSomali = 81,
-		/** International Spanish. */
-		ELangInternationalSpanish = 82,
-		/** American Spanish. */
-		ELangLatinAmericanSpanish = 83,
-		/** Swahili. */
-		ELangSwahili = 84,
-		/** Finland Swedish. */
-		ELangFinlandSwedish = 85,
-		ELangReserved1 = 86,		// reserved for future use
-		/** Tamil. */ 
-		ELangTamil = 87,
-		/** Telugu. */
-		ELangTelugu = 88,
-		/** Tibetan. */
-		ELangTibetan = 89,
-		/** Tigrinya. */
-		ELangTigrinya = 90,
-		/** Cyprus Turkish. */
-		ELangCyprusTurkish = 91,
-		/** Turkmen. */
-		ELangTurkmen = 92,
-		/** Ukrainian. */
-		ELangUkrainian = 93,
-		/** Urdu. */ 
-		ELangUrdu = 94,
-		ELangReserved2 = 95,	// reserved for future use
-		/** Vietnamese. */
-		ELangVietnamese = 96,
-		/** Welsh. */
-		ELangWelsh = 97,
-		/** Zulu. */
-		ELangZulu = 98,
-		/** Basque */
-		ELangBasque = 102,
-		/** Galician */
-		ELangGalician = 103,
-		/** @deprecated 6.2 */
-		ELangOther = 99,
-		ELangIllegal = 100,
-		ELangNone = 0xFFFF
-	}TLanguage;
-
-	static unsigned long GetLanguageCode(std::wstring aLang);
-	static std::wstring GetLanguageName(unsigned long aCode);
-};
-
-#endif //__PKGLANGUAGE_H__
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifndef __PKGLANGUAGE_H__
+#define __PKGLANGUAGE_H__
+
+#ifdef _MSC_VER 
+	#pragma warning(disable: 4786) // identifier was truncated to '255' characters in the debug information
+	#pragma warning(disable: 4503) // decorated name length exceeded, name was truncated
+#endif
+
+typedef struct {
+	char* iName;
+	TUint32	iId;
+} SKeyword;
+
+/** 
+class PkgLanguage
+	Lookup table for the languages supported
+
+@internalComponent
+@released
+*/
+class PkgLanguage
+{
+public:
+	typedef enum 
+	{
+		//This list is lifted directly from E32std.h
+		ELangTest = 0,
+		/** UK English. */
+		ELangEnglish = 1,
+		/** French. */
+		ELangFrench = 2,
+		/** German. */
+		ELangGerman = 3,
+		/** Spanish. */
+		ELangSpanish = 4,
+		/** Italian. */
+		ELangItalian = 5,
+		/** Swedish. */
+		ELangSwedish = 6,
+		/** Danish. */
+		ELangDanish = 7,
+		/** Norwegian. */
+		ELangNorwegian = 8,
+		/** Finnish. */
+		ELangFinnish = 9,
+		/** American. */
+		ELangAmerican = 10,
+		/** Swiss French. */
+		ELangSwissFrench = 11,
+		/** Swiss German. */
+		ELangSwissGerman = 12,
+		/** Portuguese. */
+		ELangPortuguese = 13,
+		/** Turkish. */
+		ELangTurkish = 14,
+		/** Icelandic. */
+		ELangIcelandic = 15,
+		/** Russian. */
+		ELangRussian = 16,
+		/** Hungarian. */
+		ELangHungarian = 17,
+		/** Dutch. */
+		ELangDutch = 18,
+		/** Belgian Flemish. */
+		ELangBelgianFlemish = 19,
+		/** Australian English. */
+		ELangAustralian = 20,
+		/** Belgian French. */
+		ELangBelgianFrench = 21,
+		/** Austrian German. */
+		ELangAustrian = 22,
+		/** New Zealand English. */
+		ELangNewZealand = 23,
+		/** International French. */
+		ELangInternationalFrench = 24,
+		/** Czech. */
+		ELangCzech = 25,
+		/** Slovak. */
+		ELangSlovak = 26,
+		/** Polish. */
+		ELangPolish = 27,
+		/** Slovenian. */
+		ELangSlovenian = 28,
+		/** Taiwanese Chinese. */
+		ELangTaiwanChinese = 29,
+		/** Hong Kong Chinese. */
+		ELangHongKongChinese = 30,
+		/** Peoples Republic of China Chinese. */
+		ELangPrcChinese = 31,
+		/** Japanese. */
+		ELangJapanese = 32,
+		/** Thai. */
+		ELangThai = 33,
+		/** Afrikaans. */
+		ELangAfrikaans = 34,
+		/** Albanian. */
+		ELangAlbanian = 35,
+		/** Amharic. */
+		ELangAmharic = 36,
+		/** Arabic.*/
+		ELangArabic = 37,
+		/** Armenian. */
+		ELangArmenian = 38,
+		/** Tagalog. */
+		ELangTagalog = 39,
+		/** Belarussian. */
+		ELangBelarussian = 40,
+		/** Bengali. */ 
+		ELangBengali = 41,
+		/** Bulgarian. */
+		ELangBulgarian = 42,
+		/** Burmese. */ 
+		ELangBurmese = 43,
+		/** Catalan. */
+		ELangCatalan = 44,
+		/** Croation. */
+		ELangCroatian = 45,
+		/** Canadian English. */
+		ELangCanadianEnglish = 46,
+		/** International English. */
+		ELangInternationalEnglish = 47,
+		/** South African English. */
+		ELangSouthAfricanEnglish = 48,
+		/** Estonian. */
+		ELangEstonian = 49,
+		/** Farsi. */
+		ELangFarsi = 50,
+		/** Canadian French. */
+		ELangCanadianFrench = 51,
+		/** Gaelic. */
+		ELangScotsGaelic = 52,
+		/** Georgian. */
+		ELangGeorgian = 53,
+		/** Greek. */ 
+		ELangGreek = 54,
+		/** Cyprus Greek. */
+		ELangCyprusGreek = 55,
+		/** Gujarati. */
+		ELangGujarati = 56,
+		/** Hebrew. */
+		ELangHebrew = 57,
+		/** Hindi. */ 
+		ELangHindi = 58,
+		/** Indonesian. */
+		ELangIndonesian = 59,
+		/** Irish. */
+		ELangIrish = 60,
+		/** Swiss Italian. */
+		ELangSwissItalian = 61,
+		/** Kannada. */
+		ELangKannada = 62,
+		/** Kazakh. */
+		ELangKazakh = 63,
+		/** Kmer. */
+		ELangKhmer = 64,
+		/** Korean. */
+		ELangKorean = 65,
+		/** Lao. */
+		ELangLao = 66,
+		/** Latvian. */
+		ELangLatvian = 67,
+		/** Lithuanian. */
+		ELangLithuanian = 68,
+		/** Macedonian. */
+		ELangMacedonian = 69,
+		/** Malay. */
+		ELangMalay = 70,
+		/** Malayalam. */
+		ELangMalayalam = 71,
+		/** Marathi. */ 
+		ELangMarathi = 72,
+		/** Moldovian. */
+		ELangMoldavian = 73,
+		/** Mongolian. */
+		ELangMongolian = 74,
+		/** Norwegian Nynorsk. */
+		ELangNorwegianNynorsk = 75,
+		/** Brazilian Portuguese. */
+		ELangBrazilianPortuguese = 76,
+		/** Punjabi. */
+		ELangPunjabi = 77,
+		/** Romanian. */
+		ELangRomanian = 78,
+		/** Serbian. */
+		ELangSerbian = 79,
+		/** Sinhalese. */
+		ELangSinhalese = 80,
+		/** Somali. */
+		ELangSomali = 81,
+		/** International Spanish. */
+		ELangInternationalSpanish = 82,
+		/** American Spanish. */
+		ELangLatinAmericanSpanish = 83,
+		/** Swahili. */
+		ELangSwahili = 84,
+		/** Finland Swedish. */
+		ELangFinlandSwedish = 85,
+		ELangReserved1 = 86,		// reserved for future use
+		/** Tamil. */ 
+		ELangTamil = 87,
+		/** Telugu. */
+		ELangTelugu = 88,
+		/** Tibetan. */
+		ELangTibetan = 89,
+		/** Tigrinya. */
+		ELangTigrinya = 90,
+		/** Cyprus Turkish. */
+		ELangCyprusTurkish = 91,
+		/** Turkmen. */
+		ELangTurkmen = 92,
+		/** Ukrainian. */
+		ELangUkrainian = 93,
+		/** Urdu. */ 
+		ELangUrdu = 94,
+		ELangReserved2 = 95,	// reserved for future use
+		/** Vietnamese. */
+		ELangVietnamese = 96,
+		/** Welsh. */
+		ELangWelsh = 97,
+		/** Zulu. */
+		ELangZulu = 98,
+		/** Basque */
+		ELangBasque = 102,
+		/** Galician */
+		ELangGalician = 103,
+		/** @deprecated 6.2 */
+		ELangOther = 99,
+		ELangIllegal = 100,
+		ELangNone = 0xFFFF
+	}TLanguage;
+
+
+};
+TUint32 GetLanguageCode(const char* aLang);
+const char* GetLanguageName(TUint32 aCode);
+#endif //__PKGLANGUAGE_H__
--- a/imgtools/sisutils/inc/sis2iby.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/sisutils/inc/sis2iby.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,73 +1,73 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifndef __SIS2IBY_H__
-#define __SIS2IBY_H__
-
-#include "pkgfileparser.h"
-
-#define SISEXTRACT_TOOL_NAME	"dumpsis"  // Extract tool
-#define SISEXTRACT_TOOL_DEFOPT	" -x"      // Default options to the tool
-#define SISEXTRACT_TOOL_EXTOPT	" -d "     // Extract path option
-
-typedef std::map<String,PPKGPARSER> PKGFILE_MAP;
-
-/** 
-class Sis2Iby
-	Implements the interfaces of SisUtils
-	Provides methods to generate IBY file(s) from a SIS file
-
-@internalComponent
-@released
-*/
-class Sis2Iby : public SisUtils
-{
-public:
-	Sis2Iby(char* aFile);
-	~Sis2Iby();
-
-	void ProcessSisFile();
-	void GenerateOutput();
-
-private:
-	void GenerateIby(String aPkgFile, PPKGPARSER aParser);
-	TUint32 InvokeExtractTool(String sisFile);
-	void UpdatePkgFileMap(String aPath, String aFile);
-	void GetFileName(String aName, String& aFile);
-	void AppendFileName(String& aPath, String aFile);
-	void NormaliseSourceFile(String& aFile, String aPkgFile);
-	void NormaliseDestFile(String& aFile);
-	void MakeFullPath(String& aFile);
-
-	void WriteLanguages(PPKGPARSER aParser);
-	void WriteFileInclusion(String aSrcFile, String aDestFile, String aPkgName, int pad);
-	void WritePackageHeader(PPKGPARSER aParser);
-	void WriteInstallOptions(PPKGPARSER aParser);
-	void WritePackageBody(PPKGPARSER aParser);
-	void WriteInstallFileList(PINSTALLFILE_LIST aFileList, PPKGPARSER aParser, int pad);
-	void InsertTabs(int num);
-
-	PkgParser *pkgParser;
-	PKGFILE_MAP iPkgFileMap;
-
-	std::ofstream ibyHandle;
-
-	TBool IsValidE32Image(String aFile);
-};
-
-#endif //__SIS2IBY_H__
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifndef __SIS2IBY_H__
+#define __SIS2IBY_H__
+
+#include "pkgfileparser.h"
+
+#define SISEXTRACT_TOOL_NAME	"dumpsis"  // Extract tool
+#define SISEXTRACT_TOOL_DEFOPT	" -x"      // Default options to the tool
+#define SISEXTRACT_TOOL_EXTOPT	" -d "     // Extract path option
+
+typedef map<string,PPKGPARSER> PKGFILE_MAP;
+
+/** 
+class Sis2Iby
+	Implements the interfaces of SisUtils
+	Provides methods to generate IBY file(s) from a SIS file
+
+@internalComponent
+@released
+*/
+class Sis2Iby : public SisUtils
+{
+public:
+	Sis2Iby(const char* aFile);
+	~Sis2Iby();
+
+	void ProcessSisFile();
+	void GenerateOutput();
+
+private:
+	void GenerateIby(string aPkgFile, PPKGPARSER aParser);
+	TUint32 InvokeExtractTool(const string& aSisFile);
+	void UpdatePkgFileMap(const string& aPath, const string& aFile);
+	void GetFileName(const string& aName, string& aFile);
+	void AppendFileName(string& aPath,string aFile);
+	void NormaliseSourceFile(string& aFile, const string& aPkgFile);
+	void NormaliseDestFile(string& aFile);
+	void MakeFullPath(string& aFile);
+
+	void WriteLanguages(PPKGPARSER aParser);
+	void WriteFileInclusion(string aSrcFile, string aDestFile, string aPkgName, TInt aPadding);
+	void WritePackageHeader(PPKGPARSER aParser);
+	void WriteInstallOptions(PPKGPARSER aParser);
+	void WritePackageBody(PPKGPARSER aParser);
+	void WriteInstallFileList(PINSTALLFILE_LIST aFileList, PPKGPARSER aParser, TInt aPadding);
+	void InsertTabs(TInt num);
+
+	PkgParser *pkgParser;
+	PKGFILE_MAP iPkgFileMap;
+
+	ofstream ibyHandle;
+
+	TBool IsValidE32Image(string aFile);
+};
+
+#endif //__SIS2IBY_H__
--- a/imgtools/sisutils/inc/sisutils.h	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/sisutils/inc/sisutils.h	Tue Jun 29 14:52:54 2010 +0800
@@ -1,94 +1,102 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifndef __SISUTILS_H__
-#define __SISUTILS_H__
-
-#ifdef _MSC_VER 
-	#pragma warning(disable: 4786) // identifier was truncated to '255' characters in the debug information
-	#pragma warning(disable: 4503) // decorated name length exceeded, name was truncated
-#endif
-
-#include <string>
-#include <list>
-#include <iostream>
-#include <fstream>
-#include <iomanip>
-#undef _L
-
-#include <e32def.h>
-#include <e32cmn.h>
-
-#define STAT_SUCCESS  (0)
-#define STAT_FAILURE  (-1)
-
-#ifdef WIN32
-#define PATHSEPARATOR  "\\"
-#endif
-
-//typedefs
-typedef std::string String;
-
-/** 
-class SisUtils
-
-@internalComponent
-@released
-*/
-class SisUtils
-{
-public:
-	SisUtils(char* aFile);
-	virtual ~SisUtils();
-
-	void SetVerboseMode();
-
-	virtual void ProcessSisFile() = 0;
-	virtual void GenerateOutput() = 0;
-
-	static String iExtractPath;
-	static String iOutputPath;
-
-protected:
-	TBool IsVerboseMode();
-	TBool IsFileExist(String aFile);
-	TBool MakeDirectory(String aPath);
-	String SisFileName();
-	TUint32 RunCommand(String cmd);
-	void TrimQuotes(String& aStr);
-
-private:
-	TBool iVerboseMode;
-	String iSisFile;
-};
-
-// SisUtils Exception handler
-class SisUtilsException
-{
-public:
-	SisUtilsException(char* aFile, char* aErrMessage);
-	virtual ~SisUtilsException();
-	virtual void Report();
-
-private:
-	String iSisFileName;
-	String iErrMessage;
-};
-
-
-#endif //__SISUTILS_H__
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifndef __SISUTILS_H__
+#define __SISUTILS_H__
+
+#ifdef _MSC_VER 
+	#pragma warning(disable: 4786) // identifier was truncated to '255' characters in the debug information
+	#pragma warning(disable: 4503) // decorated name length exceeded, name was truncated
+#endif
+
+#include <string>
+#include <list>
+#include <iostream>
+#include <fstream>
+#include <iomanip>
+#undef _L
+
+
+#include <e32def.h>
+#include <e32cmn.h>
+
+#define STAT_SUCCESS  (0)
+#define STAT_FAILURE  (-1)
+
+#ifdef WIN32
+#define PATHSEPARATOR  "\\"
+#else // linux
+#define PATHSEPARATOR  "/"
+ 
+//int wcsnicmp(const wchar_t* str1,const wchar_t* str2,size_t n);
+//int wcsicmp(const wchar_t* str1,const wchar_t* str2);
+//int iswdigit(wchar_t ch);
+char *_fullpath( char *absPath, const char *relPath, size_t maxLength );
+#endif
+
+ 
+using namespace std ;
+
+/** 
+class SisUtils
+
+@internalComponent
+@released
+*/
+class SisUtils
+{
+public:
+	SisUtils(const char* aFile);
+	virtual ~SisUtils();
+
+	void SetVerboseMode();
+
+	virtual void ProcessSisFile() = 0;
+	virtual void GenerateOutput() = 0;
+
+	static string iExtractPath;
+	static string iOutputPath;
+
+protected:
+	TBool IsVerboseMode();
+	TBool IsFileExist(string aFile);
+	TBool MakeDirectory(const string& aPath);
+	const char* SisFileName();
+	TUint32 RunCommand(const char* aCmd);
+	void TrimQuotes(string& aStr);
+
+private:
+	TBool iVerboseMode;
+	string iSisFile;
+};
+
+// SisUtils Exception handler
+class SisUtilsException
+{
+public:
+	SisUtilsException(const char* aFile, const char* aErrMessage);
+	virtual ~SisUtilsException();
+	virtual void Report();
+
+private:
+	string iSisFileName;
+	string iErrMessage;
+};
+
+
+#endif //__SISUTILS_H__
--- a/imgtools/sisutils/src/pkgfileparser.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/sisutils/src/pkgfileparser.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,1435 +1,1230 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include "sisutils.h"
-#include "pkgfileparser.h"
-
-// Parse options lookups
-#define MAXTOKENLEN	30
-struct SParseToken
-{
-	WCHAR pszOpt[MAXTOKENLEN];
-	DWORD dwOpt;
-};
-
-const SParseToken KTokens[] =
-{
-	{L"if",		IF_TOKEN},
-	{L"elseif",	ELSEIF_TOKEN},
-	{L"else",	ELSE_TOKEN},
-	{L"endif",	ENDIF_TOKEN},
-	{L"exists",	EXISTS_TOKEN},
-	{L"devprop",DEVCAP_TOKEN},
-	{L"appcap",	APPCAP_TOKEN},
-	{L"package",DEVCAP_TOKEN},
-	{L"appprop",APPCAP_TOKEN},
-	{L"not",	NOT_TOKEN},
-	{L"and",	AND_TOKEN},
-	{L"or",		OR_TOKEN},
-	{L"type",	TYPE_TOKEN},
-	{L"key",	KEY_TOKEN},
-};
-#define NUMPARSETOKENS (sizeof(KTokens)/sizeof(SParseToken))
-
-/**
-Constructor: PkgParser class
-Initilize the parameters to data members.
-
-@internalComponent
-@released
-
-@param aFile	- Name of the package script file
-*/
-PkgParser::PkgParser(String aFile) : iPkgFile(aFile), m_nLineNo(0)
-{
-}
-
-/**
-Destructor: PkgParser class
-Deallocates the memory for data members
-
-@internalComponent
-@released
-*/
-PkgParser::~PkgParser()
-{
-	if(iPkgHandle != INVALID_HANDLE_VALUE)
-	{
-		::CloseHandle(iPkgHandle);
-	}
-
-	DeleteAll();
-}
-
-/**
-OpenFile: Opens the package script file
-
-@internalComponent
-@released
-*/
-int PkgParser::OpenFile()
-{
-	iPkgHandle = ::CreateFileW(string2wstring(iPkgFile).data(),GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
-	
-	return (iPkgHandle != INVALID_HANDLE_VALUE) ? 1 : 0;
-}
-
-/**
-GetEmbeddedSisList: Returns the embedded sis file list
-
-@internalComponent
-@released
-
-@param embedSisList	- reference to sis file list structure
-*/
-void PkgParser::GetEmbeddedSisList(SISFILE_LIST& embedSisList)
-{
-	embedSisList = iEmbedSisFiles;
-}
-
-/**
-GetInstallOptions: Returns the install options read from the package file
-
-@internalComponent
-@released
-
-@param aOptions	- reference to the string list structure
-*/
-void PkgParser::GetInstallOptions(FILE_LIST& aOptions)
-{
-	aOptions = iInstallOptions;
-}
-
-/**
-GetLanguageList: Returns the language list read from the package file
-
-@internalComponent
-@released
-
-@param langList	- reference to the language list structure
-*/
-void PkgParser::GetLanguageList(LANGUAGE_LIST& langList)
-{
-	langList = iLangList;
-}
-
-/**
-GetHeader: Returns the header details read from the package file
-
-@internalComponent
-@released
-
-@param pkgHeader	- reference to the package header structure
-*/
-void PkgParser::GetHeader(PKG_HEADER& pkgHeader)
-{
-	pkgHeader = iPkgHeader;
-}
-
-/**
-GetCommandList: Returns the package body details read from the package file
-
-@internalComponent
-@released
-
-@param cmdList	- reference to the command list structure
-*/
-void PkgParser::GetCommandList(CMDBLOCK_LIST& cmdList)
-{
-	cmdList = iPkgBlock;
-}
-
-/**
-ParsePkgFile: Parses the package file
-
-@internalComponent
-@released
-*/
-void PkgParser::ParsePkgFile()
-{
-	if(!OpenFile())
-	{
-		throw SisUtilsException((char*)iPkgFile.data(), "Could not open file");
-	}
-
-	GetNextChar();
-
-	// skip unicode marker if present
-	if(m_pkgChar==0xFEFF) GetNextChar();
-
-	GetNextToken ();
-	while(m_token!=EOF_TOKEN)
-	{
-		ParseEmbeddedBlockL();
-		switch (m_token)
-		{
-		case '&':
-			GetNextToken ();
-			ParseLanguagesL();
-			break;
-		case '#':
-			GetNextToken ();
-			ParseHeaderL();
-			break;
-		case '%':
-			GetNextToken ();
-			ParseVendorNameL();
-			break;
-		case '=':
-			GetNextToken ();
-			ParseLogoL();
-			break;
-		case '(':
-			GetNextToken ();
-			ParseDependencyL();
-			break;
-		case ':':
-			GetNextToken ();
-			ParseVendorUniqueNameL();
-			break;
-		case '[':
-			GetNextToken ();
-			ParseTargetDeviceL();
-			break;
-		case EOF_TOKEN:
-			break;
-		default:
-			ParserError("Unexpected token");
-			break;
-		}
-	}
-}
-
-/**
-ParseLanguagesL: Parses the language section
-
-@internalComponent
-@released
-*/
-void PkgParser::ParseLanguagesL()
-{
-	unsigned long langCode = 0;
-	unsigned long dialect = 0;
-	
-	while (true)
-	{
-		if (m_token==ALPHA_TOKEN)
-		{
-			langCode = PkgLanguage::GetLanguageCode(m_tokenValue.pszString);
-		}
-		else if (m_token==NUMERIC_TOKEN && m_tokenValue.dwNumber>=0 && m_tokenValue.dwNumber<=1000)
-		{
-			langCode = (m_tokenValue.dwNumber);
-		}
-
-		GetNextToken ();
-
-		// Check if a dialect is defined
-		if (m_token == '(')
-		{
-			GetNumericToken();
-			// Modify the last added language code, combining it with dialect code
-			dialect = (m_tokenValue.dwNumber);
-			GetNextToken ();
-			GetNextToken ();
-		}
-		AddLanguage(wstring2string(PkgLanguage::GetLanguageName(langCode)), langCode, dialect);
-
-		if (m_token!=',')
-			return;
-		GetNextToken ();
-	}
-}
-
-
-/**
-ParseHeaderL: Parses the package header section
-
-@internalComponent
-@released
-*/
-void PkgParser::ParseHeaderL()
-{
-	if (!iLangList.size())
-	{
-		//No languages defined, assuming English."
-		AddLanguage("EN", PkgLanguage::ELangEnglish, 0);
-	}
-	
-	// process application names
-	ExpectToken('{');
-	for (WORD wNumLangs = 0; wNumLangs < iLangList.size(); wNumLangs++)
-	{
-		GetNextToken ();
-		ExpectToken(QUOTED_STRING_TOKEN);
-		iPkgHeader.pkgNameList.push_back(wstring2string(m_tokenValue.pszString));
-		GetNextToken ();
-		if (wNumLangs < (iLangList.size()-1) )
-		{
-			ExpectToken(',');
-		}
-	}
-	ExpectToken('}');
-	GetNextToken (); 
-	
-	ExpectToken(',');
-	GetNextToken ();
-	ExpectToken('(');
-	GetNextToken ();
-	
-	ExpectToken(NUMERIC_TOKEN);
-	iPkgHeader.pkgUid = m_tokenValue.dwNumber;
-	GetNextToken ();
-	
-	ExpectToken(')');
-	GetNextToken ();
-	ExpectToken(',');
-	GetNextToken ();
-	
-	ExpectToken(NUMERIC_TOKEN);
-	iPkgHeader.vMajor = m_tokenValue.dwNumber;
-	GetNextToken ();
-	ExpectToken(',');
-	GetNextToken ();
-	
-	ExpectToken(NUMERIC_TOKEN);
-	iPkgHeader.vMinor = m_tokenValue.dwNumber;
-	GetNextToken ();
-	ExpectToken(',');
-	GetNextToken ();
-	
-	ExpectToken(NUMERIC_TOKEN);
-	iPkgHeader.vBuild = m_tokenValue.dwNumber;
-	GetNextToken ();
-	
-	// Parse any options
-	while (m_token==',')
-	{
-		GetNextToken ();
-		if (m_token==TYPE_TOKEN)
-		{
-			GetNextToken ();
-			ExpectToken('=');
-			GetNextToken ();
-			iPkgHeader.pkgType = wstring2string(m_tokenValue.pszString);
-			GetNextToken ();
-		}
-		else
-			GetNextToken ();
-	}
-}
-
-/**
-ParseEmbeddedBlockL: Parses the package body block
-
-@internalComponent
-@released
-*/
-void PkgParser::ParseEmbeddedBlockL ()
-{
-	while(m_token!=EOF_TOKEN)
-	{
-		switch (m_token)
-		{
-		case QUOTED_STRING_TOKEN:
-			ParseFileL ();
-			break;
-		case '@':
-			GetNextToken ();
-			ParsePackageL ();
-			break;
-		case '!':
-			GetNextToken ();
-			ParseOptionsBlockL();
-			break;
-		case '+':
-			GetNextToken ();
-			ParsePropertyL ();
-			break;
-		case IF_TOKEN:
-			GetNextToken ();
-			ParseIfBlockL ();
-			break;
-		case ';' :
-			ParseCommentL ();
-			break;
-		default :
-			return;
-		}
-	}
-}
-
-/**
-ParseFileL: Parses the file list section
-
-@internalComponent
-@released
-*/
-void PkgParser::ParseFileL()
-{
-	PCMD_BLOCK pCmdBlock = 0;
-	PINSTALLFILE_LIST pFileList = 0;
-	
-	std::wstring sourceFile (m_tokenValue.pszString);
-	
-	// Linux and windows both support forward slashes so if source path is given '\' need to convert
-	// in forward slash for compatibility.
-	wchar_t *pBuffer = (wchar_t*)sourceFile.c_str();
-	wchar_t *pCurrent = pBuffer;
-	while (pBuffer && *pBuffer && (pCurrent = wcschr(pBuffer,L'\\')) != NULL)
-	{
-		*pCurrent = L'/';
-		pBuffer = pCurrent + 1;
-	}
-	
-	GetNextToken ();
-	
-	ExpectToken('-');
-	GetNextToken ();
-	
-	ExpectToken(QUOTED_STRING_TOKEN);
-	
-	std::wstring destinationFile (m_tokenValue.pszString);
-	
-	// SWI only supports backward slashesh so need to convert destination path in backward slash if
-	// user gives '/' in Linux.
-	pBuffer = (wchar_t*)destinationFile.c_str();
-	pCurrent = pBuffer;
-	while (pBuffer && *pBuffer && (pCurrent = wcschr(pBuffer,L'/')) != NULL)
-	{
-		*pCurrent = L'\\';
-		pBuffer = pCurrent + 1;
-	}
-	
-	GetNextToken ();
-	
-	// Test for options
-	if (m_token!=',')
-	{
-		pCmdBlock = new CMD_BLOCK;
-		pFileList = new INSTALLFILE_LIST;
-
-		pCmdBlock->cmdType = INSTALLFILE;
-		pCmdBlock->iInstallFileList = pFileList;
-
-		pFileList->langDepFlg = 0;
-		pFileList->srcFiles.push_back(wstring2string(sourceFile));
-		pFileList->destFile = wstring2string(destinationFile);
-
-		iPkgBlock.push_back(pCmdBlock);
-	}
-	else
-	{	
-		bool needAdd = false;
-		while(m_token==',')
-		{
-			GetNextToken ();
-			std::wstring installOption = m_tokenValue.pszString;
-			if((installOption == L"FF") || (installOption == L"FILE"))
-			{
-				needAdd = true;
-			}
-			GetNextToken ();
-		}
-		if (needAdd)
-		{
-			pCmdBlock = new CMD_BLOCK;
-			pFileList = new INSTALLFILE_LIST;
-
-			pCmdBlock->cmdType = INSTALLFILE;
-			pCmdBlock->iInstallFileList = pFileList;
-
-			pFileList->langDepFlg = 0;
-			pFileList->srcFiles.push_back(wstring2string(sourceFile));
-			pFileList->destFile = wstring2string(destinationFile);
-		
-			iPkgBlock.push_back(pCmdBlock);
-		}
-	}
-}
-
-/**
-ParseIfBlockL: Parses the conditional installation body
-
-@internalComponent
-@released
-*/
-void PkgParser::ParseIfBlockL()
-{
-	PCMD_BLOCK pCmdBlock = 0; 
-
-	//IF
-	pCmdBlock = new CMD_BLOCK;
-	pCmdBlock->cmdType = IF;
-	ParseLogicalOp(pCmdBlock->cmdExpression);
-	iPkgBlock.push_back(pCmdBlock);
-
-	ParseEmbeddedBlockL ();
-	
-	while (m_token==ELSEIF_TOKEN)
-	{
-		GetNextToken ();
-		//ELSEIF
-		pCmdBlock = new CMD_BLOCK;
-		pCmdBlock->cmdType = ELSEIF;
-		ParseLogicalOp(pCmdBlock->cmdExpression);
-		iPkgBlock.push_back(pCmdBlock);
-
-		ParseEmbeddedBlockL ();
-	}
-	
-	if (m_token==ELSE_TOKEN)
-	{
-		GetNextToken ();
-		//ELSEIF
-		pCmdBlock = new CMD_BLOCK;
-		pCmdBlock->cmdType = ELSE;
-		iPkgBlock.push_back(pCmdBlock);
-
-		ParseEmbeddedBlockL ();
-	}
-	
-	ExpectToken(ENDIF_TOKEN);
-	//ENDIF
-	pCmdBlock = new CMD_BLOCK;
-	pCmdBlock->cmdType = ENDIF;
-	iPkgBlock.push_back(pCmdBlock);
-
-	GetNextToken ();
-}
-
-/**
-ParseLogicalOp: Parses the logical expression
-
-@internalComponent
-@released
-*/
-void PkgParser::ParseLogicalOp (String& aExpression)
-{
-    ParseRelation (aExpression);
-	switch (m_token)
-	{
-	case AND_TOKEN:
-	case OR_TOKEN:
-		{
-			if (m_token==AND_TOKEN)
-				aExpression.append(" && ");
-			else
-				aExpression.append(" || ");
-			GetNextToken ();
-			ParseLogicalOp (aExpression);
-		}
-		break;
-	}
-}
-
-/**
-ParseRelation: Parses the relational expression
-
-@internalComponent
-@released
-*/
-void PkgParser::ParseRelation(String& aExpression)
-{
-    ParseUnary (aExpression);
-	switch (m_token)
-	{
-	case '=':
-	case '>':
-	case '<':
-	case GE_TOKEN:
-	case LE_TOKEN:
-	case NE_TOKEN:
-	case APPCAP_TOKEN:
-		{
-			switch (m_token)
-			{
-			case '=':
-				aExpression.append(" == ");
-				break;
-			case '>':
-				aExpression.append(" > ");
-				break;
-			case '<':
-				aExpression.append(" < ");
-				break;
-			case GE_TOKEN:
-				aExpression.append(" >= ");
-				break;
-			case LE_TOKEN:
-				aExpression.append(" <= ");
-				break;
-			case NE_TOKEN:
-				aExpression.append(" != ");
-				break;
-			case APPCAP_TOKEN:
-				aExpression.append(" APPPROP ");
-				break;
-			}
-			GetNextToken ();
-			ParseUnary (aExpression);
-			break;
-		}
-	}
-}
-
-/**
-ParseUnary: Parses the unary expression
-
-@internalComponent
-@released
-*/
-void PkgParser::ParseUnary(String& aExpression)
-{
-    switch (m_token)
-	{
-	case NOT_TOKEN:
-		aExpression.append(" !");
-		GetNextToken ();
-		ParseUnary (aExpression);
-		break;
-	case EXISTS_TOKEN:
-	case DEVCAP_TOKEN:
-		{	// 1 arg function
-			int token=m_token;
-			GetNextToken ();
-			ExpectToken('(');
-			GetNextToken ();
-			if (token==EXISTS_TOKEN)
-			{
-				aExpression.append("EXISTS(\"");
-				ExpectToken(QUOTED_STRING_TOKEN);
-				GetNextToken ();
-				aExpression.append(wstring2string(m_tokenValue.pszString));
-				aExpression.append("\")");
-			}
-			else
-			{
-				aExpression.append("DEVCAP(");
-				ParseUnary (aExpression);
-				aExpression.append(")");
-			}
-			ExpectToken(')');
-			GetNextToken ();
-			break;
-		}
-	default:
-		ParseFactor (aExpression);
-		break;
-	}
-}
-
-/**
-ParseFactor: Parses the expression factor
-
-@internalComponent
-@released
-*/
-void PkgParser::ParseFactor(String& aExpression)
-{
-    switch (m_token) {
-	case '(':
-		{
-			aExpression.append("(");
-			GetNextToken ();
-			ParseLogicalOp (aExpression);
-			ExpectToken(')');
-			aExpression.append(")");
-		}
-		break;
-	case QUOTED_STRING_TOKEN:
-	case ALPHA_TOKEN:
-	case NUMERIC_TOKEN:
-		{
-			switch (m_token)
-			{
-			case QUOTED_STRING_TOKEN:
-				aExpression.append("\"");
-				aExpression.append(wstring2string(m_tokenValue.pszString));
-				aExpression.append("\"");
-				break;
-			case ALPHA_TOKEN:
-				if(!CompareNString(m_tokenValue.pszString,L"option",6))
-				{
-					aExpression.append(" defined(");
-					aExpression.append(wstring2string(m_tokenValue.pszString));
-					aExpression.append(") ");
-				}
-				else
-				{
-					aExpression.append(wstring2string(m_tokenValue.pszString));
-				}
-				break;
-			case NUMERIC_TOKEN:
-				{
-					std::ostringstream str;
-
-					str << "(0x" << std::setbase(16) << m_tokenValue.dwNumber << ")";
-					aExpression.append(str.str());
-				}
-				break;
-			}
-		}
-		break;
-	default:
-		ParserError("ErrBadCondFormat");
-	}
-	GetNextToken ();
-}
-
-
-/**
-ParsePackageL: Parses the embedded package section
-
-@internalComponent
-@released
-*/
-void PkgParser::ParsePackageL()
-{
-	PCMD_BLOCK pCmdBlock = 0;
-	int found = 0;
-
-	ExpectToken(QUOTED_STRING_TOKEN);
-
-	//if the sis file already exists then skip it
-	SISFILE_LIST::iterator begin = iEmbedSisFiles.begin();
-	SISFILE_LIST::iterator end = iEmbedSisFiles.end();
-
-	while(begin != end)
-	{
-		if((*begin).compare(wstring2string(m_tokenValue.pszString)) == 0)
-		{
-			found = 1;
-			break;
-		}
-		++begin;
-	}
-
-	if(!found)
-	{
-		iEmbedSisFiles.push_back(wstring2string(m_tokenValue.pszString));
-	}
-	
-	//add as a command block as well
-	{
-		pCmdBlock = new CMD_BLOCK;
-
-		pCmdBlock->cmdType = PACKAGE;
-		pCmdBlock->iInstallFileList = 0;
-		pCmdBlock->cmdExpression = wstring2string(m_tokenValue.pszString);
-
-		iPkgBlock.push_back(pCmdBlock);
-	}
-
-
-	GetNextToken ();
-
-	ExpectToken(',');
-	GetNextToken ();
-	ExpectToken('(');
-	GetNextToken ();
-	ExpectToken(NUMERIC_TOKEN);
-	GetNextToken ();
-	ExpectToken(')');
-	GetNextToken ();
-}
-
-/**
-ParseCommentL: Parses the comment section
-  Parses a comment line (Does nothing, just throws the line away)
-
-@internalComponent
-@released
-*/
-void PkgParser::ParseCommentL()
-{
-	// parse to end of line
-	while (m_pkgChar && (m_pkgChar!='\n')) GetNextChar();
-	GetNextToken ();
-}
-
-/**
-ParseOptionsBlockL: Parses the install options section
-
-@internalComponent
-@released
-*/
-void PkgParser::ParseOptionsBlockL()
-{
-	WORD wNumLangs;
-	
-	ExpectToken('(');
-	GetNextToken ();
-	
-	for (;;)
-	{
-		ExpectToken('{');
-		GetNextToken ();
-		
-		wNumLangs = 0;
-		while (wNumLangs < iLangList.size())
-		{
-			ExpectToken(QUOTED_STRING_TOKEN);
-			iInstallOptions.push_back(wstring2string(m_tokenValue.pszString));
-			GetNextToken ();
-			if (wNumLangs < iLangList.size() - 1)
-			{
-				ExpectToken(',');
-				GetNextToken ();
-			}
-			wNumLangs++;
-		}
-		
-		ExpectToken('}');
-		GetNextToken ();
-		if (m_token!=',') break;
-		GetNextToken ();
-	}
-	
-	ExpectToken(')');
-	GetNextToken ();	
-}
-
-/**
-ParsePropertyL: Parses the capability options section
-
-@internalComponent
-@released
-*/
-void PkgParser::ParsePropertyL()
-{
-	ExpectToken('(');
-	do
-	{
-		GetNextToken ();
-		
-		ExpectToken(NUMERIC_TOKEN);
-		GetNextToken ();
-		ExpectToken('=');
-		GetNextToken ();
-		ExpectToken(NUMERIC_TOKEN);
-		GetNextToken ();
-	} while (m_token==',');
-	ExpectToken(')');
-	GetNextToken ();
-}
-
-/**
-ParseVendorNameL: Parses the vendor options section
-
-@internalComponent
-@released
-*/
-void PkgParser::ParseVendorNameL()
-{
-	ExpectToken('{');
-	for (WORD wNumLangs = 0; wNumLangs < iLangList.size(); wNumLangs++)
-	{
-		GetNextToken ();
-		ExpectToken(QUOTED_STRING_TOKEN);
-		GetNextToken ();
-		if (wNumLangs < iLangList.size() -1 )
-		{
-			ExpectToken(',');
-		}
-	}
-	ExpectToken('}');
-	GetNextToken ();
-}
-
-/**
-ParseLogoL: Parses the logo options section
-
-@internalComponent
-@released
-*/
-void PkgParser::ParseLogoL()
-{
-	ExpectToken (QUOTED_STRING_TOKEN);
-	GetNextToken ();
-	ExpectToken(',');
-	GetNextToken ();
-	ExpectToken (QUOTED_STRING_TOKEN);
-	GetNextToken ();
-	if (m_token==',')
-	{
-		GetNextToken ();
-		ExpectToken (QUOTED_STRING_TOKEN);
-		GetNextToken ();
-	}
-}
-
-/**
-ParseVersion: Parses the version details
-
-@internalComponent
-@released
-*/
-void PkgParser::ParseVersion()
-{
-	GetNextToken();
-	ExpectToken(NUMERIC_TOKEN);
-
-	GetNextToken();
-	ExpectToken(',');
-	GetNextToken();
-	ExpectToken(NUMERIC_TOKEN);
-
-	GetNextToken();
-	ExpectToken(',');
-	GetNextToken();
-	ExpectToken(NUMERIC_TOKEN);
-
-	GetNextToken();
-}
-
-/**
-ParseDependencyL: Parses the dependency package section
-
-@internalComponent
-@released
-*/
-void PkgParser::ParseDependencyL()
-{
-	ExpectToken(NUMERIC_TOKEN);
-	GetNextToken ();
-	ExpectToken(')');
-	GetNextToken ();
-	ExpectToken(',');
-
-	ParseVersion();
-	if (m_token == '~')
-	{
-		ParseVersion();
-		ExpectToken(',');
-	}
-	
-	GetNextToken ();
-	ExpectToken('{');
-	for (TUint numLangs = 0; numLangs < iLangList.size(); ++numLangs)
-	{
-		GetNextToken ();
-		ExpectToken(QUOTED_STRING_TOKEN);
-		GetNextToken ();
-		if (numLangs < (iLangList.size() - 1))
-			ExpectToken(',');
-	}
-	ExpectToken('}');
-	GetNextToken ();
-}
-
-/**
-ParseVendorUniqueNameL: Parses the vendor unique name section
-
-@internalComponent
-@released
-*/
-void PkgParser::ParseVendorUniqueNameL()
-{
-	ExpectToken(QUOTED_STRING_TOKEN);
-	GetNextToken ();
-}
-
-/**
-ParseTargetDeviceL: Parses the target device name section
-
-@internalComponent
-@released
-*/
-void PkgParser::ParseTargetDeviceL()
-{
-	ExpectToken(NUMERIC_TOKEN);
-	GetNextToken ();
-	ExpectToken(']');
-	GetNextToken ();
-	ExpectToken(',');
-	
-	ParseVersion();
-	if (m_token == '~')
-	{
-		ParseVersion();
-		ExpectToken(',');
-	}
-	GetNextToken ();
-	ExpectToken('{');
-	
-	// must do this before adding language strings	
-	for (TUint numLangs = 0; numLangs < iLangList.size(); ++numLangs)
-	{
-		GetNextToken ();
-		ExpectToken(QUOTED_STRING_TOKEN);
-		GetNextToken ();
-		if (numLangs < (iLangList.size() - 1))
-			ExpectToken(',');
-	}
-	ExpectToken('}');
-	GetNextToken ();
-}
-
-
-/**
-GetNextChar: Reads the next character from the package file
-
-@internalComponent
-@released
-*/
-void PkgParser::GetNextChar()
-{
-#ifdef WIN32
-	DWORD dwBytesRead;
-	if (!::ReadFile(iPkgHandle, (LPVOID)&m_pkgChar, sizeof(WCHAR), &dwBytesRead, NULL) ||
-		dwBytesRead!=sizeof(wchar_t))
-		m_pkgChar='\0';
-#else
-#error "TODO: Implement this function under other OS than Windows"
-#endif
-}
-
-/**
-ExpectToken: Tests the current token value
-
-@internalComponent
-@released
-
-@param aToken - expected token value
-*/
-void PkgParser::ExpectToken(int aToken)
-{
-	if (m_token!=aToken)
-	{
-		ParserError("Unexpected Token");
-	}
-}
-
-/**
-GetNextToken: Reads the next valid token from the package file
-
-@internalComponent
-@released
-*/
-void PkgParser::GetNextToken ()
-{
-	// skip any white space & newLine's
-	while (m_pkgChar == '\n' || isspace(m_pkgChar) || m_pkgChar == 0xA0)
-	{
-		if (m_pkgChar == '\n') ++m_nLineNo;
-		GetNextChar();
-	}
-	
-	if (m_pkgChar == '\0')
-		m_token=EOF_TOKEN;
-	else if (IsNumericToken())
-	{
-		GetNumericToken();
-		m_token=NUMERIC_TOKEN;
-	}
-	else if (isalpha(m_pkgChar))
-	{ // have some alphanumeric text
-		GetAlphaNumericToken();
-		m_token=ALPHA_TOKEN;
-		// check if it is a keyword
-		for(unsigned short wLoop = 0; wLoop < NUMPARSETOKENS; wLoop++)
-		{
-			if(CompareTwoString(m_tokenValue.pszString,(wchar_t*)KTokens[wLoop].pszOpt) == 0)
-			{
-				m_token=KTokens[wLoop].dwOpt;
-				break;
-			}
-		}
-	}
-	else if (m_pkgChar == '\"')
-	{ // have a quoted string
-		GetStringToken();
-		m_token=QUOTED_STRING_TOKEN;
-	}
-	else if (m_pkgChar == '>')
-	{
-		GetNextChar();
-		if (m_pkgChar == '=')
-		{
-			m_token=GE_TOKEN;
-			GetNextChar();
-		}
-		else
-			m_token='>';
-	}
-	else if (m_pkgChar == '<')
-	{
-		// check if start of an escaped string, e.g. <123>"abc"
-		if (GetStringToken())
-			m_token=QUOTED_STRING_TOKEN;
-		else
-		{
-			GetNextChar();
-			if (m_pkgChar == '=')
-			{
-				m_token=LE_TOKEN;
-				GetNextChar();
-			}
-			else if (m_pkgChar == '>')
-			{
-				m_token=NE_TOKEN;
-				GetNextChar();
-			}
-			else
-				m_token='<';
-		}
-	}
-	else
-	{
-		m_token=m_pkgChar;
-		GetNextChar();
-	}
-}
-
-/**
-GetStringToken: Reads the string token from the package file
-
-@internalComponent
-@released
-*/
-bool PkgParser::GetStringToken()
-{
-	DWORD wCount = 0;
-	bool done=false;
-	bool finished=false;
-	DWORD escapeChars = 0;
-	
-	while (!finished)
-	{
-		if (m_pkgChar == '\"')
-		{
-			GetNextChar();
-			while(m_pkgChar && m_pkgChar != '\"')
-			{
-				if(wCount < (MAX_STRING - 1))
-					m_tokenValue.pszString[wCount++] = m_pkgChar;
-				else //We dont want the string with length greater than MAX_STRING to be cut off silently
-					ParserError("Bad String");
-				GetNextChar();
-			}
-			if(m_pkgChar == '\0')
-				ParserError("Bad String");
-			GetNextChar();
-			done=true;
-		}
-		if (m_pkgChar == '<')
-		{
-			m_tokenValue.pszString[wCount] = L'\0';
-			escapeChars=ParseEscapeChars();
-			if (escapeChars>0)
-			{
-				done=true;
-				wCount+=escapeChars;
-				if (wCount>=MAX_STRING) wCount=MAX_STRING-1;
-			}
-		}
-		if (escapeChars==0 || m_pkgChar != '\"')
-			finished=true;
-	}
-	
-	m_tokenValue.pszString[wCount] = L'\0';
-	return done;
-}
-
-/**
-ParseEscapeChars: Parses the escape sequence characters
-
-@internalComponent
-@released
-*/
-WORD PkgParser::ParseEscapeChars()
-{
-	WORD found=0;
-	WCHAR temp[MAX_STRING];
-#ifdef WIN32
-	while (m_pkgChar == '<')
-	{
-		wcscpy(temp,m_tokenValue.pszString);
-		DWORD fileOffset=::SetFilePointer(iPkgHandle, 0L, NULL, FILE_CURRENT);
-		try
-		{
-			GetNextChar();
-			GetNumericToken();
-			if (m_pkgChar=='>')
-				found++;
-			else
-			{
-				::SetFilePointer(iPkgHandle, fileOffset, NULL, FILE_BEGIN);
-				break;
-			}
-		}
-		catch (...)
-		{
-			wcscpy(m_tokenValue.pszString,temp);
-			::SetFilePointer(iPkgHandle, fileOffset, NULL, FILE_BEGIN);
-			break;
-		}
-		DWORD num=m_tokenValue.dwNumber;
-		// watch for CP1252 escapes which aren't appropriate for UNICODE
-		if (num>=0x80 && num<=0x9F) ParserError("Invalid Escape");
-		DWORD len=wcslen(temp);
-		wcscpy(m_tokenValue.pszString,temp);
-		if (len+2<=MAX_STRING)
-		{
-			m_tokenValue.pszString[len]=(WCHAR)num;
-			len++;
-			m_tokenValue.pszString[len]='\0';
-		}
-		GetNextChar();
-	}
-#else
-#error "TODO: Implement this function under other OS than Windows"
-#endif 
-	return found;
-}
-
-/**
-GetAlphaNumericToken: Parse an alphanumeric string from the input line
-
-@internalComponent
-@released
-*/
-void PkgParser::GetAlphaNumericToken()
-{
-	WORD wCount = 0;
-	while(m_pkgChar && (isalnum(m_pkgChar) || ((m_pkgChar) == '_')))
-	{
-		if(wCount < (MAX_STRING - 1))
-			m_tokenValue.pszString[wCount++] = m_pkgChar;
-		GetNextChar();
-	}
-	m_tokenValue.pszString[wCount] = L'\0';
-}
-
-/**
-IsNumericToken: Determines if the next lexeme is a numeric token
-
-@internalComponent
-@released
-*/
-bool PkgParser::IsNumericToken()
-{
-	bool lexemeIsNumber = false;
-	if (iswdigit(m_pkgChar))
-		lexemeIsNumber = true;
-	else if (m_pkgChar == '+' || m_pkgChar == '-')
-	{
-		// we may have a number but we must look ahead one char to be certain
-		
-		WCHAR oldChar = m_pkgChar;
-		DWORD fileOffset=::SetFilePointer(iPkgHandle, 0L, NULL, FILE_CURRENT);
-		GetNextChar();
-		lexemeIsNumber = iswdigit(m_pkgChar) != FALSE;
-		m_pkgChar = oldChar;
-		::SetFilePointer(iPkgHandle,fileOffset,NULL,FILE_BEGIN);
-	}
-	
-	return lexemeIsNumber;
-}
-
-/**
-GetNumericToken: Parse a number from the input line
-
-@internalComponent
-@released
-*/
-void PkgParser::GetNumericToken()
-{
-	WCHAR temp[MAX_STRING];
-	LPWSTR end;
-	bool hexString = false;
-	DWORD dwBytesRead;
-	DWORD fileOffset=::SetFilePointer(iPkgHandle, 0L, NULL, FILE_CURRENT);
-	
-	temp[0]=m_pkgChar;
-	if (!::ReadFile(iPkgHandle, &temp[1], (MAX_STRING-2)*sizeof(WCHAR), &dwBytesRead, NULL) ||
-		dwBytesRead==0)
-		ParserError("Read failed");
-	temp[1+dwBytesRead/sizeof(WCHAR)]='\0';
-	hexString = (!CompareNString(temp, L"0x", 2) || !CompareNString(&temp[1], L"0x", 2));
-	
-	m_tokenValue.dwNumber = wcstoul(temp, &end, (hexString) ? 16 : 10);
-	
-	if (end==temp) ParserError("Read failed"); 
-	::SetFilePointer(iPkgHandle, fileOffset+(end-temp-1)*sizeof(WCHAR), NULL, FILE_BEGIN);
-	GetNextChar();
-}
-
-/**
-AddLanguage: Updates the language list structure
-
-@internalComponent
-@released
-
-@param aLang - Name of the language
-@param aCode - Language code
-@param aDialect - Language dialect code
-*/
-void PkgParser::AddLanguage(String aLang, unsigned long aCode, unsigned long aDialect)
-{
-	PLANG_LIST lc = new LANG_LIST;
-	
-	lc->langName = aLang;
-	lc->langCode = aCode;
-	lc->dialectCode = aDialect;
-
-	iLangList.push_back(lc);
-}
-
-/**
-DeleteAll: Deallocates memory for the data members
-
-@internalComponent
-@released
-*/
-void PkgParser::DeleteAll()
-{
-	while(iPkgBlock.size() > 0)
-	{
-		PCMD_BLOCK ptemp = 0;
-
-		ptemp = iPkgBlock.front();
-		iPkgBlock.pop_front();
-
-		if(ptemp->cmdType == INSTALLFILE)
-		{
-			delete ptemp->iInstallFileList;
-		}
-		delete ptemp;
-	}
-
-	{
-		LANGUAGE_LIST::iterator begin = iLangList.begin();
-		LANGUAGE_LIST::iterator end = iLangList.end();
-		while(begin != end)
-		{
-			PLANG_LIST ptemp = 0;
-			ptemp = (*begin);
-
-			if(ptemp)
-				delete ptemp;
-			++begin;
-		}
-		iLangList.clear();
-	}
-}
-
-/**
-ParserError: Throws exception with the given error message
-
-@internalComponent
-@released
-
-@param msg - error message to be thrown
-*/
-void PkgParser::ParserError(char* msg)
-{
-	std::ostringstream str;
-
-	str << (char*)iPkgFile.data() << "(" << m_nLineNo << "): " << msg;
-
-	throw SisUtilsException("PakageFile-Parser Error", (char*)(str.str()).data());
-}
-
-/**
-wstring2string: Converts wide string to string
-
-@internalComponent
-@released
-
-@param aWide - input wide string
-*/
-String wstring2string (const std::wstring& aWide)
-{
-	int max = ::WideCharToMultiByte(CP_OEMCP,0,aWide.c_str(),aWide.length(),0,0,0,0);
-	String reply;
-	if (max > 0 )
-	{
-		char* buffer = new char [max];
-		try
-		{
-			::WideCharToMultiByte(CP_OEMCP,0,aWide.c_str(),aWide.length(),buffer,max,0,0);
-			reply = String (buffer, max);
-		}
-		catch (...)
-		{
-			throw SisUtilsException("ParserError", "wstring to string conversion failed");
-		}
-		delete [] buffer;
-	}
-	return reply;
-}
-
-/**
-string2wstring: Converts string to wide string
-
-@internalComponent
-@released
-
-@param aNarrow - input string
-*/
-std::wstring string2wstring (const String& aNarrow)
-{
-	int max = ::MultiByteToWideChar(CP_OEMCP,0,aNarrow.c_str(),aNarrow.length(),0,0);
-	std::wstring reply;
-	if (max > 0 )
-	{
-		wchar_t* buffer = new wchar_t [max];
-		try
-		{
-			::MultiByteToWideChar(CP_OEMCP,0,aNarrow.c_str(),aNarrow.length(),buffer,max);
-			reply = std::wstring (buffer, max);
-		}
-		catch (...)
-		{
-			throw SisUtilsException("ParserError", "string to wstring conversion failed");
-		}
-		delete [] buffer;
-	}
-	return reply;
-}
-
-/**
-CompareTwoString: Compares two wide string
-
-@internalComponent
-@released
-
-@param string - first string
-@param option - second string
-*/
-int CompareTwoString(wchar_t* string ,wchar_t* option)
-{
-	return wcsicmp(string,option);
-}
-
-/**
-CompareNString: Compares two wide string for n characters
-
-@internalComponent
-@released
-
-@param string - first string
-@param option - second string
-@param len - no of wide characters to be compared
-*/
-int CompareNString(wchar_t* string ,wchar_t* option, int len)
-{
-	return wcsnicmp(string,option,len);
-}
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.htm ".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#include "sisutils.h"
+#include "pkgfileparser.h"
+#ifdef __LINUX__ 
+#include <strings.h>
+#define stricmp strcasecmp
+#define strnicmp strncasecmp
+#endif
+#include "utf16string.h"
+
+// Parse options lookups
+#define MAXTOKENLEN	30
+struct SParseToken
+{
+	char pszOpt[MAXTOKENLEN];
+	TUint32 dwOpt;
+};
+
+const SParseToken KTokens[] =
+{
+	{ "if",		IF_TOKEN},
+	{ "elseif",	ELSEIF_TOKEN},
+	{ "else",	ELSE_TOKEN},
+	{ "endif",	ENDIF_TOKEN},
+	{ "exists",	EXISTS_TOKEN},
+	{ "devprop",DEVCAP_TOKEN},
+	{ "appcap",	APPCAP_TOKEN},
+	{ "package",DEVCAP_TOKEN},
+	{ "appprop",APPCAP_TOKEN},
+	{ "not",	NOT_TOKEN},
+	{ "and",	AND_TOKEN},
+	{ "or",		OR_TOKEN},
+	{ "type",	TYPE_TOKEN},
+	{ "key",	KEY_TOKEN},
+};
+
+#define NUMPARSETOKENS (sizeof(KTokens)/sizeof(SParseToken))
+
+/**
+Constructor: PkgParser class
+Initilize the parameters to data members.
+
+@internalComponent
+@released
+
+@param aFile	- Name of the package script file
+*/
+PkgParser::PkgParser(const string& aFile) : iPkgFileContent(""),iContentPos(0),iContentStr("") ,iPkgFileName(aFile),iToken(EOF_TOKEN) , iLineNumber(0){
+}
+
+/**
+Destructor: PkgParser class
+Deallocates the memory for data members
+
+@internalComponent
+@released
+*/
+PkgParser::~PkgParser() {
+	 
+	DeleteAll();
+	
+}
+
+/**
+OpenFile: Opens the package script file
+
+@internalComponent
+@released
+*/
+bool PkgParser::OpenFile() {
+	
+	UTF16String str ;
+	if(!str.FromFile(iPkgFileName.c_str()))
+		return false ;
+	
+	if(!str.ToUTF8(iContentStr)) 		 
+		return false ; 
+	 
+	iPkgFileContent = iContentStr.c_str();
+	iContentPos = 0 ;	
+	return true ;
+}
+/** 
+ * GetNextChar : iContentStr is a UTF-8 String, of which char is as follows:
+ * 
+ *0000-007F | 0xxxxxxx
+ *0080-07FF | 110xxxxx 10xxxxxx
+ *0800-FFFF | 1110xxxx 10xxxxxx 10xxxxxx
+ * 10000-10FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
+ */
+void PkgParser::GetNextChar() {		
+	if(iContentPos < iContentStr.length()){
+		if(0 == (iPkgFileContent[iContentPos] & 0x80))
+			iContentPos++;
+		else if(0xC0 == (iPkgFileContent[iContentPos]  & 0xE0))
+			iContentPos += 2 ;
+		else if(0xE0 == (iPkgFileContent[iContentPos]  & 0xF0))
+			iContentPos += 3 ;
+		else
+			iContentPos += 4 ;
+		if(iContentPos >= iContentStr.length())
+			iContentPos = iContentStr.length() ;
+	} 
+}
+/**
+GetEmbeddedSisList: Returns the embedded sis file list
+
+@internalComponent
+@released
+
+@param embedSisList	- reference to sis file list structure
+*/
+void PkgParser::GetEmbeddedSisList(SISFILE_LIST& embedSisList) {
+	embedSisList = iEmbedSisFiles;
+}
+
+/**
+GetInstallOptions: Returns the install options read from the package file
+
+@internalComponent
+@released
+
+@param aOptions	- reference to the string list structure
+*/
+void PkgParser::GetInstallOptions(FILE_LIST& aOptions) {
+	aOptions = iInstallOptions;
+}
+
+/**
+GetLanguageList: Returns the language list read from the package file
+
+@internalComponent
+@released
+
+@param langList	- reference to the language list structure
+*/
+void PkgParser::GetLanguageList(LANGUAGE_LIST& langList){
+	langList = iLangList;
+}
+
+/**
+GetHeader: Returns the header details read from the package file
+
+@internalComponent
+@released
+
+@param pkgHeader	- reference to the package header structure
+*/
+void PkgParser::GetHeader(PKG_HEADER& pkgHeader) {
+	pkgHeader = iPkgHeader;
+}
+
+/**
+GetCommandList: Returns the package body details read from the package file
+
+@internalComponent
+@released
+
+@param cmdList	- reference to the command list structure
+*/
+void PkgParser::GetCommandList(CMDBLOCK_LIST& cmdList) {
+	cmdList = iPkgBlock;
+}
+
+/**
+ParsePkgFile: Parses the package file
+
+@internalComponent
+@released
+*/
+void PkgParser::ParsePkgFile() {
+	if(!OpenFile())
+		throw SisUtilsException(iPkgFileName.c_str(), "Could not open file"); 
+	GetNextToken ();
+	while(iToken!=EOF_TOKEN) {
+		ParseEmbeddedBlockL();
+		switch (iToken)
+		{
+		case '&':
+			GetNextToken ();
+			ParseLanguagesL();
+			break;
+		case '#':
+			GetNextToken ();
+			ParseHeaderL();
+			break;
+		case '%':
+			GetNextToken ();
+			ParseVendorNameL();
+			break;
+		case '=':
+			GetNextToken ();
+			ParseLogoL();
+			break;
+		case '(':
+			GetNextToken ();
+			ParseDependencyL();
+			break;
+		case ':':
+			GetNextToken ();
+			ParseVendorUniqueNameL();
+			break;
+		case '[':
+			GetNextToken ();
+			ParseTargetDeviceL();
+			break;
+		case EOF_TOKEN:
+			break;
+		default:
+			ParserError("Unexpected token");
+			break;
+		}
+	}
+}
+
+/**
+ParseLanguagesL: Parses the language section
+
+@internalComponent
+@released
+*/
+void PkgParser::ParseLanguagesL(){
+	TUint32 iLangCode = 0;
+	TUint32 dialect = 0;
+	
+	while (true){
+		if (iToken==ALPHA_TOKEN){
+			iLangCode = GetLanguageCode(iTokenVal.iString);
+		}
+		else if (iToken==NUMERIC_TOKEN && iTokenVal.iNumber>=0 && iTokenVal.iNumber<=1000)	{
+			iLangCode = (iTokenVal.iNumber);
+		}
+
+		GetNextToken ();
+
+		// Check if a dialect is defined
+		if (iToken == '(')
+		{
+			GetNumericToken();
+			// Modify the last added language code, combining it with dialect code
+			dialect = (iTokenVal.iNumber);
+			GetNextToken ();
+			GetNextToken ();
+		}
+		const char* temp = GetLanguageName(iLangCode);
+		if(NULL != temp){		 
+			AddLanguage(string(temp), iLangCode, dialect);
+		}
+
+		if (iToken!=',')
+			return;
+		GetNextToken ();
+	}
+}
+
+
+/**
+ParseHeaderL: Parses the package header section
+
+@internalComponent
+@released
+*/
+void PkgParser::ParseHeaderL() {
+	if (!iLangList.size()) {
+		//No languages defined, assuming English."
+		AddLanguage("EN", PkgLanguage::ELangEnglish, 0);
+	}
+	
+	// process application names
+	ExpectToken('{');
+	for (TUint16 wNumLangs = 0; wNumLangs < iLangList.size(); wNumLangs++) 	{
+		GetNextToken ();
+		ExpectToken(QUOTED_STRING_TOKEN);
+		iPkgHeader.iPkgNames.push_back(string(iTokenVal.iString));
+		GetNextToken ();
+		if (wNumLangs < (iLangList.size()-1) ) {
+			ExpectToken(',');
+		}
+	}
+	ExpectToken('}');
+	GetNextToken (); 
+	
+	ExpectToken(',');
+	GetNextToken ();
+	ExpectToken('(');
+	GetNextToken ();
+	
+	ExpectToken(NUMERIC_TOKEN);
+	iPkgHeader.iPkgUID = iTokenVal.iNumber;
+	GetNextToken (); 
+	ExpectToken(')'); 
+
+	GetNextToken ();
+	ExpectToken(',');
+	GetNextToken ();
+	
+	ExpectToken(NUMERIC_TOKEN);
+	iPkgHeader.iMajorVersion = iTokenVal.iNumber;
+	GetNextToken ();
+	ExpectToken(',');
+	GetNextToken ();
+	
+	ExpectToken(NUMERIC_TOKEN);
+	iPkgHeader.iMinorVersion = iTokenVal.iNumber;
+	GetNextToken ();
+	ExpectToken(',');
+	GetNextToken ();
+	
+	ExpectToken(NUMERIC_TOKEN);
+	iPkgHeader.iBuildVersion = iTokenVal.iNumber;
+	GetNextToken ();
+	
+	// Parse any options
+	while (iToken==',') {
+		GetNextToken ();
+		if (iToken==TYPE_TOKEN) {
+			GetNextToken ();
+			ExpectToken('=');
+			GetNextToken ();
+			iPkgHeader.iPkgType = iTokenVal.iString;
+			GetNextToken ();
+		}
+		else
+			GetNextToken ();
+	}
+}
+
+/**
+ParseEmbeddedBlockL: Parses the package body block
+
+@internalComponent
+@released
+*/
+void PkgParser::ParseEmbeddedBlockL () {
+	while(iToken!=EOF_TOKEN) {
+		switch (iToken) {
+		case QUOTED_STRING_TOKEN:
+			ParseFileL ();
+			break;
+		case '@':
+			GetNextToken ();
+			ParsePackageL ();
+			break;
+		case '!':
+			GetNextToken ();
+			ParseOptionsBlockL();
+			break;
+		case '+':
+			GetNextToken ();
+			ParsePropertyL ();
+			break;
+		case IF_TOKEN:
+			GetNextToken ();
+			ParseIfBlockL ();
+			break;
+		case ';' :
+			ParseCommentL ();
+			break;
+		default :
+			return;
+		}
+	}
+}
+
+/**
+ParseFileL: Parses the file list section
+
+@internalComponent
+@released
+*/
+void PkgParser::ParseFileL() {
+	PCMD_BLOCK pCmdBlock = 0;
+	PINSTALLFILE_LIST pFileList = 0;
+	
+	string sourceFile (iTokenVal.iString);
+	
+	// Linux and windows both support forward slashes so if source path is given '\' need to convert
+	// in forward slash for compatibility.
+	char* pBuffer = const_cast<char*>(sourceFile.data());
+	char* pCurrent = pBuffer;
+	while (pBuffer && *pBuffer && (pCurrent = strchr(pBuffer,'\\')) != NULL) {
+		*pCurrent = '/';
+		pBuffer = pCurrent + 1;
+	}
+	
+	GetNextToken ();
+	
+	ExpectToken('-');
+	GetNextToken ();
+	
+	ExpectToken(QUOTED_STRING_TOKEN);
+	
+	string destinationFile (iTokenVal.iString);
+	
+	// SWI only supports backward slashesh so need to convert destination path in backward slash if
+	// user gives '/' in Linux.
+	pBuffer = const_cast<char*>(destinationFile.data());
+	pCurrent = pBuffer;
+	while (pBuffer && *pBuffer && (pCurrent = strchr(pBuffer,'/')) != NULL) {
+		*pCurrent = '\\';
+		pBuffer = pCurrent + 1;
+	}
+	
+	GetNextToken ();
+	
+	// Test for options
+	if (iToken!=',') {
+		pCmdBlock = new CMD_BLOCK;
+		pFileList = new INSTALLFILE_LIST;
+
+		pCmdBlock->iCmdType = INSTALLFILE;
+		pCmdBlock->iInstallFileList = pFileList;
+
+		pFileList->iLangDepFlag = 0;
+		pFileList->iSourceFiles.push_back(sourceFile);
+		pFileList->iDestFile = destinationFile;
+
+		iPkgBlock.push_back(pCmdBlock);
+	}
+	else {	
+		bool needAdd = false;
+		while(iToken==',') {
+			GetNextToken ();
+			string installOption = iTokenVal.iString;
+			if((installOption == "FF") || (installOption == "FILE")) {
+				needAdd = true;
+			}
+			GetNextToken ();
+		}
+		if (needAdd) {
+			pCmdBlock = new CMD_BLOCK;
+			pFileList = new INSTALLFILE_LIST;
+
+			pCmdBlock->iCmdType = INSTALLFILE;
+			pCmdBlock->iInstallFileList = pFileList;
+
+			pFileList->iLangDepFlag = 0;
+			pFileList->iSourceFiles.push_back(sourceFile);
+			pFileList->iDestFile = destinationFile;
+		
+			iPkgBlock.push_back(pCmdBlock);
+		}
+	}
+}
+
+/**
+ParseIfBlockL: Parses the conditional installation body
+
+@internalComponent
+@released
+*/
+void PkgParser::ParseIfBlockL() {
+	PCMD_BLOCK pCmdBlock = 0; 
+
+	//IF
+	pCmdBlock = new CMD_BLOCK;
+	pCmdBlock->iCmdType = IF;
+	ParseLogicalOp(pCmdBlock->iCmdExpr);
+	iPkgBlock.push_back(pCmdBlock);
+
+	ParseEmbeddedBlockL ();
+	
+	while (iToken==ELSEIF_TOKEN){
+		GetNextToken ();
+		//ELSEIF
+		pCmdBlock = new CMD_BLOCK;
+		pCmdBlock->iCmdType = ELSEIF;
+		ParseLogicalOp(pCmdBlock->iCmdExpr);
+		iPkgBlock.push_back(pCmdBlock);
+
+		ParseEmbeddedBlockL ();
+	}
+	
+	if (iToken==ELSE_TOKEN) {
+		GetNextToken ();
+		//ELSEIF
+		pCmdBlock = new CMD_BLOCK;
+		pCmdBlock->iCmdType = ELSE;
+		iPkgBlock.push_back(pCmdBlock);
+
+		ParseEmbeddedBlockL ();
+	}
+	
+	ExpectToken(ENDIF_TOKEN);
+	//ENDIF
+	pCmdBlock = new CMD_BLOCK;
+	pCmdBlock->iCmdType = ENDIF;
+	iPkgBlock.push_back(pCmdBlock);
+
+	GetNextToken ();
+}
+
+/**
+ParseLogicalOp: Parses the logical expression
+
+@internalComponent
+@released
+*/
+void PkgParser::ParseLogicalOp (string& aExpression) {
+    ParseRelation (aExpression);
+	switch (iToken) {
+	case AND_TOKEN:
+	case OR_TOKEN:
+		{
+			if (iToken==AND_TOKEN)
+				aExpression.append(" && ");
+			else
+				aExpression.append(" || ");
+			GetNextToken ();
+			ParseLogicalOp (aExpression);
+		}
+		break;
+	}
+}
+
+/**
+ParseRelation: Parses the relational expression
+
+@internalComponent
+@released
+*/
+void PkgParser::ParseRelation(string& aExpression) {
+    ParseUnary (aExpression);
+	switch (iToken)
+	{
+	case '=':
+	case '>':
+	case '<':
+	case GE_TOKEN:
+	case LE_TOKEN:
+	case NE_TOKEN:
+	case APPCAP_TOKEN:
+		{
+			switch (iToken)
+			{
+			case '=':
+				aExpression.append(" == ");
+				break;
+			case '>':
+				aExpression.append(" > ");
+				break;
+			case '<':
+				aExpression.append(" < ");
+				break;
+			case GE_TOKEN:
+				aExpression.append(" >= ");
+				break;
+			case LE_TOKEN:
+				aExpression.append(" <= ");
+				break;
+			case NE_TOKEN:
+				aExpression.append(" != ");
+				break;
+			case APPCAP_TOKEN:
+				aExpression.append(" APPPROP ");
+				break;
+			}
+			GetNextToken ();
+			ParseUnary (aExpression);
+			break;
+		}
+	}
+}
+
+/**
+ParseUnary: Parses the unary expression
+
+@internalComponent
+@released
+*/
+void PkgParser::ParseUnary(string& aExpression) {
+    switch (iToken) 	{
+	case NOT_TOKEN:
+		aExpression.append(" !");
+		GetNextToken ();
+		ParseUnary (aExpression);
+		break;
+	case EXISTS_TOKEN:
+	case DEVCAP_TOKEN:
+		{	// 1 arg function
+			TInt token=iToken;
+			GetNextToken ();
+			ExpectToken('(');
+			GetNextToken ();
+			if (token==EXISTS_TOKEN)
+			{
+				aExpression.append("EXISTS(\"");
+				ExpectToken(QUOTED_STRING_TOKEN);
+				GetNextToken ();
+				aExpression.append(string(iTokenVal.iString));
+				aExpression.append("\")");
+			}
+			else
+			{
+				aExpression.append("DEVCAP(");
+				ParseUnary (aExpression);
+				aExpression.append(")");
+			}
+			ExpectToken(')');
+			GetNextToken ();
+			break;
+		}
+	default:
+		ParseFactor (aExpression);
+		break;
+	}
+}
+
+/**
+ParseFactor: Parses the expression factor
+
+@internalComponent
+@released
+*/
+void PkgParser::ParseFactor(string& aExpression) {
+    switch (iToken) {
+	case '(':
+		{
+			aExpression.append("(");
+			GetNextToken ();
+			ParseLogicalOp (aExpression); 
+			ExpectToken(')'); 
+			aExpression.append(")");
+		}
+		break;
+	case QUOTED_STRING_TOKEN:
+	case ALPHA_TOKEN:
+	case NUMERIC_TOKEN:
+		{
+			switch (iToken)
+			{
+			case QUOTED_STRING_TOKEN:
+				aExpression.append("\"");
+				aExpression.append(iTokenVal.iString);
+				aExpression.append("\"");
+				break;
+			case ALPHA_TOKEN:
+				if(!strnicmp(iTokenVal.iString,"option",6)) {
+					aExpression.append(" defined(");
+					aExpression.append(iTokenVal.iString); 
+					ExpectToken(')'); 
+				}
+				else {
+					aExpression.append(iTokenVal.iString);
+				}
+				break;
+			case NUMERIC_TOKEN:
+				{
+					ostringstream str;
+
+					str << "(0x" << setbase(16) << iTokenVal.iNumber << ")";
+					aExpression.append(str.str());
+				}
+				break;
+			}
+		}
+		break;
+	default:
+		ParserError("ErrBadCondFormat");
+	}
+	GetNextToken ();
+}
+
+
+/**
+ParsePackageL: Parses the embedded package section
+
+@internalComponent
+@released
+*/
+void PkgParser::ParsePackageL() {
+	PCMD_BLOCK pCmdBlock = 0;
+	TInt found = 0;
+
+	ExpectToken(QUOTED_STRING_TOKEN);
+
+	//if the sis file already exists then skip it
+	SISFILE_LIST::iterator begin = iEmbedSisFiles.begin();
+	SISFILE_LIST::iterator end = iEmbedSisFiles.end();
+
+	while(begin != end) {
+		if((*begin) == iTokenVal.iString) {
+			found = 1;
+			break;
+		}
+		++begin;
+	}
+
+	if(!found)
+		iEmbedSisFiles.push_back(string(iTokenVal.iString));
+		
+	//add as a command block as well
+	 
+	pCmdBlock = new CMD_BLOCK;
+
+	pCmdBlock->iCmdType = PACKAGE;
+	pCmdBlock->iInstallFileList = 0;
+	pCmdBlock->iCmdExpr = iTokenVal.iString;
+
+	iPkgBlock.push_back(pCmdBlock);
+	 
+
+
+	GetNextToken ();
+
+	ExpectToken(',');
+	GetNextToken ();
+	ExpectToken('(');
+	GetNextToken ();
+	ExpectToken(NUMERIC_TOKEN);
+	GetNextToken ();
+	ExpectToken(')');
+	GetNextToken ();
+}
+
+/**
+ParseCommentL: Parses the comment section
+  Parses a comment line (Does nothing, just throws the line away)
+
+@internalComponent
+@released
+*/
+void PkgParser::ParseCommentL() {
+	// parse to end of line
+	while (GetCurChar() && (GetCurChar()!='\n')) GetNextChar();
+	GetNextToken ();
+}
+
+/**
+ParseOptionsBlockL: Parses the install options section
+
+@internalComponent
+@released
+*/
+void PkgParser::ParseOptionsBlockL() {
+	TUint16 wNumLangs;
+	
+	ExpectToken('(');
+	GetNextToken ();
+	
+	for (;;){
+		ExpectToken('{');
+		GetNextToken ();
+		
+		wNumLangs = 0;
+		while (wNumLangs < iLangList.size()){
+			ExpectToken(QUOTED_STRING_TOKEN);
+			iInstallOptions.push_back(string(iTokenVal.iString));
+			GetNextToken ();
+			if (wNumLangs < iLangList.size() - 1){
+				ExpectToken(',');
+				GetNextToken ();
+			}
+			wNumLangs++;
+		}
+		
+		ExpectToken('}');
+		GetNextToken ();
+		if (iToken!=',') break;
+		GetNextToken ();
+	}
+	ExpectToken(')'); 
+	GetNextToken ();	
+}
+
+/**
+ParsePropertyL: Parses the capability options section
+
+@internalComponent
+@released
+*/
+void PkgParser::ParsePropertyL() {
+	ExpectToken('(');
+	do {
+		GetNextToken ();		
+		ExpectToken(NUMERIC_TOKEN);
+		GetNextToken ();
+		ExpectToken('=');
+		GetNextToken ();
+		ExpectToken(NUMERIC_TOKEN);
+		GetNextToken ();
+	} while (iToken==','); 
+	ExpectToken(')'); 
+	GetNextToken ();
+}
+
+/**
+ParseVendorNameL: Parses the vendor options section
+
+@internalComponent
+@released
+*/
+void PkgParser::ParseVendorNameL() {
+	ExpectToken('{');
+	for (TUint16 wNumLangs = 0; wNumLangs < iLangList.size(); wNumLangs++) {
+		GetNextToken ();
+		ExpectToken(QUOTED_STRING_TOKEN);
+		GetNextToken ();
+		if (wNumLangs < iLangList.size() -1 )
+		{
+			ExpectToken(',');
+		}
+	}
+	ExpectToken('}');
+	GetNextToken ();
+}
+
+/**
+ParseLogoL: Parses the logo options section
+
+@internalComponent
+@released
+*/
+void PkgParser::ParseLogoL() {
+	ExpectToken (QUOTED_STRING_TOKEN);
+	GetNextToken ();
+	ExpectToken(',');
+	GetNextToken ();
+	ExpectToken (QUOTED_STRING_TOKEN);
+	GetNextToken ();
+	if (iToken==',')
+	{
+		GetNextToken ();
+		ExpectToken (QUOTED_STRING_TOKEN);
+		GetNextToken ();
+	}
+}
+
+/**
+ParseVersion: Parses the version details
+
+@internalComponent
+@released
+*/
+void PkgParser::ParseVersion() {
+	GetNextToken();
+	ExpectToken(NUMERIC_TOKEN);
+
+	GetNextToken();
+	ExpectToken(',');
+	GetNextToken();
+	ExpectToken(NUMERIC_TOKEN);
+
+	GetNextToken();
+	ExpectToken(',');
+	GetNextToken();
+	ExpectToken(NUMERIC_TOKEN);
+
+	GetNextToken();
+}
+
+/**
+ParseDependencyL: Parses the dependency package section
+
+@internalComponent
+@released
+*/
+void PkgParser::ParseDependencyL() {
+	ExpectToken(NUMERIC_TOKEN);
+	GetNextToken (); 
+	ExpectToken(')'); 
+	GetNextToken ();
+	ExpectToken(',');
+
+	ParseVersion();
+	if (iToken == '~') {
+		ParseVersion();
+		ExpectToken(',');
+	}
+	
+	GetNextToken ();
+	ExpectToken('{');
+	for (TUint numLangs = 0; numLangs < iLangList.size(); ++numLangs) {
+		GetNextToken ();
+		ExpectToken(QUOTED_STRING_TOKEN);
+		GetNextToken ();
+		if (numLangs < (iLangList.size() - 1))
+			ExpectToken(',');
+	}
+	ExpectToken('}');
+	GetNextToken ();
+}
+
+/**
+ParseVendorUniqueNameL: Parses the vendor unique name section
+
+@internalComponent
+@released
+*/
+void PkgParser::ParseVendorUniqueNameL() {
+	ExpectToken(QUOTED_STRING_TOKEN);
+	GetNextToken ();
+}
+
+/**
+ParseTargetDeviceL: Parses the target device name section
+
+@internalComponent
+@released
+*/
+void PkgParser::ParseTargetDeviceL() {
+	ExpectToken(NUMERIC_TOKEN);
+	GetNextToken ();
+	ExpectToken(']');
+	GetNextToken ();
+	ExpectToken(',');
+	
+	ParseVersion();
+	if (iToken == '~') {
+		ParseVersion();
+		ExpectToken(',');
+	}
+	GetNextToken ();
+	ExpectToken('{');
+	
+	// must do this before adding language strings	
+	for (TUint numLangs = 0; numLangs < iLangList.size(); ++numLangs) {
+		GetNextToken ();
+		ExpectToken(QUOTED_STRING_TOKEN);
+		GetNextToken ();
+		if (numLangs < (iLangList.size() - 1))
+			ExpectToken(',');
+	}
+	ExpectToken('}');
+	GetNextToken ();
+}
+ 
+
+ 
+
+/**
+GetNextToken: Reads the next valid token from the package file
+
+@internalComponent
+@released
+*/
+void PkgParser::GetNextToken () {
+	// skip any white space & newLine's
+	while (GetCurChar() == '\n' || isspace(GetCurChar()) || GetCurChar() == (char)0xA0) {
+		if (GetCurChar() == '\n') ++iLineNumber;
+		GetNextChar();
+	}
+	
+	if (GetCurChar() == '\0')
+		iToken=EOF_TOKEN;
+	else if (IsNumericToken()){
+		GetNumericToken();
+		iToken=NUMERIC_TOKEN;
+	}
+	else if (isalpha(GetCurChar())){ // have some alphanumeric text
+		GetAlphaNumericToken();
+		iToken=ALPHA_TOKEN;
+		// check if it is a keyword
+		for(unsigned short wLoop = 0; wLoop < NUMPARSETOKENS; wLoop++){
+			if(stricmp(iTokenVal.iString,KTokens[wLoop].pszOpt) == 0){
+				iToken=KTokens[wLoop].dwOpt;
+				break;
+			}
+		}
+	}
+	else if (GetCurChar() == '\"')	{ // have a quoted string
+		GetStringToken();
+		iToken=QUOTED_STRING_TOKEN;
+	}
+	else if (GetCurChar() == '>')	{
+		GetNextChar();
+		if (GetCurChar() == '='){
+			iToken=GE_TOKEN;
+			GetNextChar();
+		}
+		else
+			iToken='>';
+	}
+	else if (GetCurChar() == '<'){
+		// check if start of an escaped string, e.g. <123>"abc"
+		if (GetStringToken())
+			iToken=QUOTED_STRING_TOKEN;
+		else{
+			GetNextChar();
+			if (GetCurChar() == '='){
+				iToken=LE_TOKEN;
+				GetNextChar();
+			}
+			else if (GetCurChar() == '>'){
+				iToken=NE_TOKEN;
+				GetNextChar();
+			}
+			else
+				iToken='<';
+		}
+	}
+	else{
+		iToken=GetCurChar();
+		GetNextChar();
+	}
+}
+
+/**
+GetStringToken: Reads the string token from the package file
+
+@internalComponent
+@released
+*/
+bool PkgParser::GetStringToken() {
+	TUint32 wCount = 0;
+	bool done=false;
+	bool finished=false;
+	TUint32 escapeChars = 0;
+	
+	while (!finished){
+		if (GetCurChar() == '\"'){
+			GetNextChar();
+			while(GetCurChar() && GetCurChar() != '\"'){
+				if(wCount < (MAX_STRING - 1))
+					iTokenVal.iString[wCount++] = GetCurChar();
+				else //We dont want the string with length greater than MAX_STRING to be cut off silently
+					ParserError("Bad string");
+				GetNextChar();
+			}
+			if(GetCurChar() == '\0')
+				ParserError("Bad string");
+			GetNextChar();
+			done=true;
+		}
+		if (GetCurChar() == '<'){
+			iTokenVal.iString[wCount] = L'\0';
+			escapeChars=ParseEscapeChars();
+			if (escapeChars>0)
+			{
+				done=true;
+				wCount+=escapeChars;
+				if (wCount>=MAX_STRING) wCount=MAX_STRING-1;
+			}
+		}
+		if (escapeChars==0 || GetCurChar() != '\"')
+			finished=true;
+	}
+	
+	iTokenVal.iString[wCount] = L'\0';
+	return done;
+}
+
+/**
+ParseEscapeChars: Parses the escape sequence characters
+
+@internalComponent
+@released
+*/
+TUint16 PkgParser::ParseEscapeChars() {
+	TUint16 found=0;
+	char temp[MAX_STRING];
+ 
+	while (GetCurChar() == '<'){
+		strcpy(temp,iTokenVal.iString);
+		TUint savedPos = iContentPos ;	
+		try	{
+			GetNextChar();
+			GetNumericToken();
+			if (GetCurChar()=='>')
+				found++;
+			else {
+				iContentPos = savedPos ;
+				break;
+			}
+		}
+		catch (...)	{
+			strcpy(iTokenVal.iString,temp);
+			iContentPos = savedPos ;
+			break;
+		}
+		TUint32 num=iTokenVal.iNumber;
+		// watch for CP1252 escapes which aren't appropriate for UNICODE
+		if (num>=0x80 && num<=0x9F) ParserError("Invalid Escape");
+		TUint32 len=strlen(temp);
+		memcpy(iTokenVal.iString,temp, len + 1);
+		if ((len + 2) <= MAX_STRING){
+			iTokenVal.iString[len]= static_cast<char>(num);
+			len++;
+			iTokenVal.iString[len]='\0';
+		}
+		GetNextChar();
+	}
+ 
+	return found;
+}
+
+/**
+GetAlphaNumericToken: Parse an alphanumeric string from the input line
+
+@internalComponent
+@released
+*/
+void PkgParser::GetAlphaNumericToken()
+{
+	size_t length = 0;
+	TUint savedPos = iContentPos ;	
+	TUint bound = iContentStr.length();
+	while((iContentPos < bound) && 
+		(isalnum(iPkgFileContent[iContentPos]) || (iPkgFileContent[iContentPos] == '_'))) {
+		iContentPos ++ ;
+		if(length < (MAX_STRING - 1)) length ++ ; 
+	}
+	memcpy(iTokenVal.iString,&iPkgFileContent[savedPos],length);	
+	iTokenVal.iString[length] = 0;
+}
+
+/**
+IsNumericToken: Determines if the next lexeme is a numeric token
+
+@internalComponent
+@released
+*/
+bool PkgParser::IsNumericToken() { 
+	char ch = iPkgFileContent[iContentPos];
+	if (isdigit(ch))
+		return true ;
+	else if (ch == '+' || ch == '-'){
+		// we may have a number but we must look ahead one char to be certain	
+		return isdigit(iPkgFileContent[iContentPos + 1]) != 0; 
+	}	
+	return false ;
+}
+
+/**
+GetNumericToken: Parse a number from the input line
+
+@internalComponent
+@released
+*/
+void PkgParser::GetNumericToken() {
+	 
+	int base = 10; 
+	const char* temp = &iPkgFileContent[iContentPos] ;
+	if(*temp == '0' &&( temp[1] == 'x' || temp[1] == 'X')){
+		base = 16 ;
+		temp += 2;
+	}
+	char *end = const_cast<char*>(temp) ;
+	iTokenVal.iNumber = strtoul(temp, &end, base);
+	iContentPos = end - iPkgFileContent ;
+}
+
+/**
+AddLanguage: Updates the language list structure
+
+@internalComponent
+@released
+
+@param aLang - Name of the language
+@param aCode - Language code
+@param aDialect - Language dialect code
+*/
+void PkgParser::AddLanguage(const string& aLang, TUint32 aCode, TUint32 aDialect) {
+	PLANG_LIST lc = new LANG_LIST;
+	
+	lc->iLangName = aLang;
+	lc->iLangCode = aCode;
+	lc->iDialectCode = aDialect;
+
+	iLangList.push_back(lc);
+}
+
+/**
+DeleteAll: Deallocates memory for the data members
+
+@internalComponent
+@released
+*/
+void PkgParser::DeleteAll() {
+	while(iPkgBlock.size() > 0){
+		PCMD_BLOCK ptemp = 0;
+
+		ptemp = iPkgBlock.front();
+		iPkgBlock.pop_front();
+
+		if(ptemp->iCmdType == INSTALLFILE)
+		{
+			delete ptemp->iInstallFileList;
+		}
+		delete ptemp;
+	}
+
+
+	LANGUAGE_LIST::iterator begin = iLangList.begin();
+	LANGUAGE_LIST::iterator end = iLangList.end();
+	while(begin != end)	{
+		PLANG_LIST ptemp = 0;
+		ptemp = (*begin);
+
+		if(ptemp)
+			delete ptemp;
+		++begin;
+	}
+	iLangList.clear(); 
+	iPkgFileContent = "" ;
+	iContentPos = 0 ;
+	iContentStr.clear(); 
+	
+}
+
+/**
+ParserError: Throws exception with the given error message
+
+@internalComponent
+@released
+
+@param msg - error message to be thrown
+*/
+void PkgParser::ParserError(const char* aMsg) {
+	ostringstream str;
+	str << iPkgFileName.c_str() << "(" << iLineNumber << "): " << aMsg;
+	throw SisUtilsException("PakageFile-Parser Error", str.str().c_str());
+}
--- a/imgtools/sisutils/src/pkglanguage.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/sisutils/src/pkglanguage.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,178 +1,178 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-
-#include "sisutils.h"
-#include "pkglanguage.h"
-#include "pkgfileparser.h"
-
-// Language options
-static const SKeyword KLanguages [] = 
-{
-	{ L"EN", PkgLanguage::ELangEnglish },
-	{ L"FR", PkgLanguage::ELangFrench},
-	{ L"GE", PkgLanguage::ELangGerman},
-	{ L"SP", PkgLanguage::ELangSpanish},
-	{ L"IT", PkgLanguage::ELangItalian},
-	{ L"SW", PkgLanguage::ELangSwedish},
-	{ L"DA", PkgLanguage::ELangDanish},
-	{ L"NO", PkgLanguage::ELangNorwegian},
-	{ L"FI", PkgLanguage::ELangFinnish},
-	{ L"AM", PkgLanguage::ELangAmerican},
-	{ L"SF", PkgLanguage::ELangSwissFrench},
-	{ L"SG", PkgLanguage::ELangSwissGerman},
-	{ L"PO", PkgLanguage::ELangPortuguese},
-	{ L"TU", PkgLanguage::ELangTurkish},
-	{ L"IC", PkgLanguage::ELangIcelandic},
-	{ L"RU", PkgLanguage::ELangRussian},
-	{ L"HU", PkgLanguage::ELangHungarian},
-	{ L"DU", PkgLanguage::ELangDutch},
-	{ L"BL", PkgLanguage::ELangBelgianFlemish},
-	{ L"AU", PkgLanguage::ELangAustralian},
-	{ L"BF", PkgLanguage::ELangBelgianFrench},
-	{ L"AS", PkgLanguage::ELangAustrian},
-	{ L"NZ", PkgLanguage::ELangNewZealand},
-	{ L"IF", PkgLanguage::ELangInternationalFrench},
-	{ L"CS", PkgLanguage::ELangCzech},
-	{ L"SK", PkgLanguage::ELangSlovak},
-	{ L"PL", PkgLanguage::ELangPolish},
-	{ L"SL", PkgLanguage::ELangSlovenian},
-	{ L"TC", PkgLanguage::ELangTaiwanChinese},
-	{ L"HK", PkgLanguage::ELangHongKongChinese},
-	{ L"ZH", PkgLanguage::ELangPrcChinese},
-	{ L"JA", PkgLanguage::ELangJapanese},
-	{ L"TH", PkgLanguage::ELangThai},
-		  
-	{ L"AF", PkgLanguage::ELangAfrikaans },
-	{ L"SQ", PkgLanguage::ELangAlbanian },
-	{ L"AH", PkgLanguage::ELangAmharic },
-	{ L"AR", PkgLanguage::ELangArabic },
-	{ L"HY", PkgLanguage::ELangArmenian },
-	{ L"TL", PkgLanguage::ELangTagalog },
-	{ L"BE", PkgLanguage::ELangBelarussian },
-	{ L"BN", PkgLanguage::ELangBengali },
-	{ L"BG", PkgLanguage::ELangBulgarian },
-	{ L"MY", PkgLanguage::ELangBurmese },
-	{ L"CA", PkgLanguage::ELangCatalan },
-	{ L"HR", PkgLanguage::ELangCroatian },
-	{ L"CE", PkgLanguage::ELangCanadianEnglish },
-	{ L"IE", PkgLanguage::ELangInternationalEnglish },
-	{ L"SA", PkgLanguage::ELangSouthAfricanEnglish },
-	{ L"ET", PkgLanguage::ELangEstonian },
-	{ L"FA", PkgLanguage::ELangFarsi },
-	{ L"CF", PkgLanguage::ELangCanadianFrench },
-	{ L"GD", PkgLanguage::ELangScotsGaelic },
-	{ L"KA", PkgLanguage::ELangGeorgian },
-	{ L"EL", PkgLanguage::ELangGreek },
-	{ L"CG", PkgLanguage::ELangCyprusGreek },
-	{ L"GU", PkgLanguage::ELangGujarati },
-	{ L"HE", PkgLanguage::ELangHebrew },
-	{ L"HI", PkgLanguage::ELangHindi },
-	{ L"IN", PkgLanguage::ELangIndonesian },
-	{ L"GA", PkgLanguage::ELangIrish },
-	{ L"SZ", PkgLanguage::ELangSwissItalian },
-	{ L"KN", PkgLanguage::ELangKannada },
-	{ L"KK", PkgLanguage::ELangKazakh },
-	{ L"KM", PkgLanguage::ELangKhmer },
-	{ L"KO", PkgLanguage::ELangKorean },
-	{ L"LO", PkgLanguage::ELangLao },
-	{ L"LV", PkgLanguage::ELangLatvian },
-	{ L"LT", PkgLanguage::ELangLithuanian },
-	{ L"MK", PkgLanguage::ELangMacedonian },
-	{ L"MS", PkgLanguage::ELangMalay },
-	{ L"ML", PkgLanguage::ELangMalayalam },
-	{ L"MR", PkgLanguage::ELangMarathi },
-	{ L"MO", PkgLanguage::ELangMoldavian },
-	{ L"MN", PkgLanguage::ELangMongolian },
-	{ L"NN", PkgLanguage::ELangNorwegianNynorsk },
-	{ L"BP", PkgLanguage::ELangBrazilianPortuguese },
-	{ L"PA", PkgLanguage::ELangPunjabi },
-	{ L"RO", PkgLanguage::ELangRomanian },
-	{ L"SR", PkgLanguage::ELangSerbian },
-	{ L"SI", PkgLanguage::ELangSinhalese },
-	{ L"SO", PkgLanguage::ELangSomali },
-	{ L"OS", PkgLanguage::ELangInternationalSpanish },
-	{ L"LS", PkgLanguage::ELangLatinAmericanSpanish },
-	{ L"SH", PkgLanguage::ELangSwahili },
-	{ L"FS", PkgLanguage::ELangFinlandSwedish },
-	//{L"??", PkgLanguage::ELangReserved1 },
-	{ L"TA", PkgLanguage::ELangTamil },
-	{ L"TE", PkgLanguage::ELangTelugu },
-	{ L"BO", PkgLanguage::ELangTibetan },
-	{ L"TI", PkgLanguage::ELangTigrinya },
-	{ L"CT", PkgLanguage::ELangCyprusTurkish },
-	{ L"TK", PkgLanguage::ELangTurkmen },
-	{ L"UK", PkgLanguage::ELangUkrainian },
-	{ L"UR", PkgLanguage::ELangUrdu },
-	//{L"??", PkgLanguage::ELangReserved2 },
-	{ L"VI", PkgLanguage::ELangVietnamese },
-	{ L"CY", PkgLanguage::ELangWelsh },
-	{ L"ZU", PkgLanguage::ELangZulu },
-	{ L"BA", PkgLanguage::ELangBasque },
-	{ L"GL", PkgLanguage::ELangGalician },
-	//{L"??", PkgLanguage::ELangOther },
-	//{L"??", PkgLanguage::ELangNone  }
-	
-	{ NULL, PkgLanguage::ELangNone }
-	
-};
-
-#define NUMLANGUAGES (sizeof(KLanguages)/sizeof(SKeyword))
-
-/**
-GetLanguageCode: Returns the languge code for the given language
-
-@internalComponent
-@released
-
-@param aLang  - Name of the language
-*/
-unsigned long PkgLanguage::GetLanguageCode(std::wstring aLang)
-{
-	int index = NUMLANGUAGES - 1;
-
-	while(index--)
-	{
-		if(!CompareTwoString(KLanguages[index].iName, (wchar_t*)aLang.data()))
-			return KLanguages[index].iId;
-	}
-
-	return PkgLanguage::ELangNone;
-}
-
-/**
-GetLanguageName: Returns the languge name for the given language code
-
-@internalComponent
-@released
-
-@param aCode  - Language code
-*/
-std::wstring PkgLanguage::GetLanguageName(unsigned long aCode)
-{
-	int index = NUMLANGUAGES - 1;
-
-	while(index--)
-	{
-		if(KLanguages[index].iId == aCode)
-			return KLanguages[index].iName;
-	}
-
-	return NULL;
-}
-
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+
+#include "sisutils.h"
+#include "pkglanguage.h"
+#include "pkgfileparser.h"
+#ifndef WIN32
+#include <strings.h>
+#define stricmp strcasecmp
+#define strnicmp strncasecmp
+#endif
+// Language options
+static const SKeyword KLanguages [] = 
+{
+	{ "EN", PkgLanguage::ELangEnglish },
+	{ "FR", PkgLanguage::ELangFrench},
+	{ "GE", PkgLanguage::ELangGerman},
+	{ "SP", PkgLanguage::ELangSpanish},
+	{ "IT", PkgLanguage::ELangItalian},
+	{ "SW", PkgLanguage::ELangSwedish},
+	{ "DA", PkgLanguage::ELangDanish},
+	{ "NO", PkgLanguage::ELangNorwegian},
+	{ "FI", PkgLanguage::ELangFinnish},
+	{ "AM", PkgLanguage::ELangAmerican},
+	{ "SF", PkgLanguage::ELangSwissFrench},
+	{ "SG", PkgLanguage::ELangSwissGerman},
+	{ "PO", PkgLanguage::ELangPortuguese},
+	{ "TU", PkgLanguage::ELangTurkish},
+	{ "IC", PkgLanguage::ELangIcelandic},
+	{ "RU", PkgLanguage::ELangRussian},
+	{ "HU", PkgLanguage::ELangHungarian},
+	{ "DU", PkgLanguage::ELangDutch},
+	{ "BL", PkgLanguage::ELangBelgianFlemish},
+	{ "AU", PkgLanguage::ELangAustralian},
+	{ "BF", PkgLanguage::ELangBelgianFrench},
+	{ "AS", PkgLanguage::ELangAustrian},
+	{ "NZ", PkgLanguage::ELangNewZealand},
+	{ "IF", PkgLanguage::ELangInternationalFrench},
+	{ "CS", PkgLanguage::ELangCzech},
+	{ "SK", PkgLanguage::ELangSlovak},
+	{ "PL", PkgLanguage::ELangPolish},
+	{ "SL", PkgLanguage::ELangSlovenian},
+	{ "TC", PkgLanguage::ELangTaiwanChinese},
+	{ "HK", PkgLanguage::ELangHongKongChinese},
+	{ "ZH", PkgLanguage::ELangPrcChinese},
+	{ "JA", PkgLanguage::ELangJapanese},
+	{ "TH", PkgLanguage::ELangThai},
+		  
+	{ "AF", PkgLanguage::ELangAfrikaans },
+	{ "SQ", PkgLanguage::ELangAlbanian },
+	{ "AH", PkgLanguage::ELangAmharic },
+	{ "AR", PkgLanguage::ELangArabic },
+	{ "HY", PkgLanguage::ELangArmenian },
+	{ "TL", PkgLanguage::ELangTagalog },
+	{ "BE", PkgLanguage::ELangBelarussian },
+	{ "BN", PkgLanguage::ELangBengali },
+	{ "BG", PkgLanguage::ELangBulgarian },
+	{ "MY", PkgLanguage::ELangBurmese },
+	{ "CA", PkgLanguage::ELangCatalan },
+	{ "HR", PkgLanguage::ELangCroatian },
+	{ "CE", PkgLanguage::ELangCanadianEnglish },
+	{ "IE", PkgLanguage::ELangInternationalEnglish },
+	{ "SA", PkgLanguage::ELangSouthAfricanEnglish },
+	{ "ET", PkgLanguage::ELangEstonian },
+	{ "FA", PkgLanguage::ELangFarsi },
+	{ "CF", PkgLanguage::ELangCanadianFrench },
+	{ "GD", PkgLanguage::ELangScotsGaelic },
+	{ "KA", PkgLanguage::ELangGeorgian },
+	{ "EL", PkgLanguage::ELangGreek },
+	{ "CG", PkgLanguage::ELangCyprusGreek },
+	{ "GU", PkgLanguage::ELangGujarati },
+	{ "HE", PkgLanguage::ELangHebrew },
+	{ "HI", PkgLanguage::ELangHindi },
+	{ "IN", PkgLanguage::ELangIndonesian },
+	{ "GA", PkgLanguage::ELangIrish },
+	{ "SZ", PkgLanguage::ELangSwissItalian },
+	{ "KN", PkgLanguage::ELangKannada },
+	{ "KK", PkgLanguage::ELangKazakh },
+	{ "KM", PkgLanguage::ELangKhmer },
+	{ "KO", PkgLanguage::ELangKorean },
+	{ "LO", PkgLanguage::ELangLao },
+	{ "LV", PkgLanguage::ELangLatvian },
+	{ "LT", PkgLanguage::ELangLithuanian },
+	{ "MK", PkgLanguage::ELangMacedonian },
+	{ "MS", PkgLanguage::ELangMalay },
+	{ "ML", PkgLanguage::ELangMalayalam },
+	{ "MR", PkgLanguage::ELangMarathi },
+	{ "MO", PkgLanguage::ELangMoldavian },
+	{ "MN", PkgLanguage::ELangMongolian },
+	{ "NN", PkgLanguage::ELangNorwegianNynorsk },
+	{ "BP", PkgLanguage::ELangBrazilianPortuguese },
+	{ "PA", PkgLanguage::ELangPunjabi },
+	{ "RO", PkgLanguage::ELangRomanian },
+	{ "SR", PkgLanguage::ELangSerbian },
+	{ "SI", PkgLanguage::ELangSinhalese },
+	{ "SO", PkgLanguage::ELangSomali },
+	{ "OS", PkgLanguage::ELangInternationalSpanish },
+	{ "LS", PkgLanguage::ELangLatinAmericanSpanish },
+	{ "SH", PkgLanguage::ELangSwahili },
+	{ "FS", PkgLanguage::ELangFinlandSwedish },
+	//{"??", PkgLanguage::ELangReserved1 },
+	{ "TA", PkgLanguage::ELangTamil },
+	{ "TE", PkgLanguage::ELangTelugu },
+	{ "BO", PkgLanguage::ELangTibetan },
+	{ "TI", PkgLanguage::ELangTigrinya },
+	{ "CT", PkgLanguage::ELangCyprusTurkish },
+	{ "TK", PkgLanguage::ELangTurkmen },
+	{ "UK", PkgLanguage::ELangUkrainian },
+	{ "UR", PkgLanguage::ELangUrdu },
+	//{"??", PkgLanguage::ELangReserved2 },
+	{ "VI", PkgLanguage::ELangVietnamese },
+	{ "CY", PkgLanguage::ELangWelsh },
+	{ "ZU", PkgLanguage::ELangZulu },
+	{ "BA", PkgLanguage::ELangBasque },
+	{ "GL", PkgLanguage::ELangGalician },
+	//{"??", PkgLanguage::ELangOther },
+	//{"??", PkgLanguage::ELangNone  }
+	
+	{ NULL, PkgLanguage::ELangNone }
+	
+};
+
+#define NUMLANGUAGES (sizeof(KLanguages)/sizeof(SKeyword))
+
+/**
+GetLanguageCode: Returns the languge code for the given language
+
+@internalComponent
+@released
+
+@param aLang  - Name of the language
+*/
+TUint32 GetLanguageCode(const char* aLang) {
+	TInt index = NUMLANGUAGES - 1;
+
+	while(index--){
+		if(!stricmp(KLanguages[index].iName,aLang))
+			return KLanguages[index].iId;
+	}
+
+	return PkgLanguage::ELangNone;
+}
+
+/**
+GetLanguageName: Returns the languge name for the given language code
+
+@internalComponent
+@released
+
+@param aCode  - Language code
+*/
+const char* GetLanguageName(TUint32 aCode) {
+	
+	TInt index = NUMLANGUAGES - 1;
+	while(index--) {
+		if(KLanguages[index].iId == aCode)
+			return KLanguages[index].iName;
+	}
+
+	return NULL;
+}
+
--- a/imgtools/sisutils/src/sis2iby.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/sisutils/src/sis2iby.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,675 +1,589 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#include "sisutils.h"
-#include "sis2iby.h"
-
-/**
-Constructor: Sis2Iby class
-Initilize the parameters to data members.
-
-@internalComponent
-@released
-
-@param aFile	- SIS file name
-*/
-Sis2Iby::Sis2Iby(char* aFile) : SisUtils(aFile)
-{
-}
-
-/**
-Destructor: Sis2Iby class
-Deallocates the memory for data members
-
-@internalComponent
-@released
-*/
-Sis2Iby::~Sis2Iby()
-{
-	PKGFILE_MAP::iterator begin = iPkgFileMap.begin();
-	PKGFILE_MAP::iterator end = iPkgFileMap.end();
-	while(begin != end)
-	{
-		PPKGPARSER ptemp = 0;
-		ptemp = (*begin).second;
-
-		if(ptemp)
-			delete ptemp;
-		++begin;
-	}
-	iPkgFileMap.clear();
-}
-
-/**
-ProcessSisFile: Processes the input sis file
-  Invoke the DUMPSIS tool to extract the sis file contents
-  Creates package parser object for each of the package file
-
-@internalComponent
-@released
-*/
-void Sis2Iby::ProcessSisFile()
-{
-	TUint32 retStatus = STAT_SUCCESS;
-	String sisFile = SisFileName();
-
-	if(IsVerboseMode())
-	{
-		std::cout << "Processing " << (char*)sisFile.data() << std::endl;
-	}
-
-	if(IsFileExist(sisFile))
-	{
-		retStatus = InvokeExtractTool(sisFile);
-
-		switch(retStatus)
-		{
-		case STAT_SUCCESS:
-			{
-				UpdatePkgFileMap(iExtractPath, sisFile);
-			}
-			break;
-		case STAT_FAILURE:
-			{
-				throw SisUtilsException((char*)sisFile.data(), "Failed to extract SIS file");
-			}
-		}
-	}
-	else
-		throw SisUtilsException((char*)sisFile.data(), "File not found");
-}
-
-/**
-GenerateOutput: Generates IBY for each of the package file
-
-@internalComponent
-@released
-*/
-void Sis2Iby::GenerateOutput()
-{
-	PKGFILE_MAP::iterator begin = iPkgFileMap.begin();
-	PKGFILE_MAP::iterator end = iPkgFileMap.end();
-	while(begin != end)
-	{
-		GenerateIby((*begin).first, (*begin).second);
-		++begin;
-	}
-}
-
-/**
-GenerateOutput: Generates IBY file for the given package file
-
-@internalComponent
-@released
-
-@param aPkgFile - package file name
-@param aParser - corresponding package file reader object
-*/
-void Sis2Iby::GenerateIby(String aPkgFile, PPKGPARSER aParser)
-{
-	String ibyFile = iOutputPath;
-	
-	AppendFileName(ibyFile, aPkgFile);
-	ibyFile.append(".iby");
-
-	if( !MakeDirectory(iOutputPath) )
-		throw SisUtilsException((char*)iOutputPath.data(), "Failed to create path");
-
-	if(IsVerboseMode())
-	{
-		std::cout << "Generating IBY file " << (char*)ibyFile.data() << std::endl;
-	}
-
-	ibyHandle.open((char*)ibyFile.data(),(std::ios::out));
-
-	if(!ibyHandle.good())
-	{
-		throw SisUtilsException((char*)ibyFile.data(), "Failed to create IBY file");
-	}
-
-	// Generating Header
-	MakeFullPath(aPkgFile);
-	ibyHandle << "\n// Generated IBY file for the package file: ";
-	ibyHandle << aPkgFile;
-
-	// Language Supported
-	WriteLanguages(aParser);
-
-	// Package Header
-	WritePackageHeader(aParser);
-
-	// Install options list
-	WriteInstallOptions(aParser);
-
-	// Package Body
-	WritePackageBody(aParser);
-
-	ibyHandle.close();
-}
-
-/**
-InvokeExtractTool: Invokes the SIS file extraction tool and returns the status
-
-@internalComponent
-@released
-
-@param sisFile - SIS file name
-*/
-TUint32 Sis2Iby::InvokeExtractTool(String sisFile)
-{
-	String cmdLine;
-
-	cmdLine.append(SISEXTRACT_TOOL_NAME SISEXTRACT_TOOL_DEFOPT);
-
-	AppendFileName(iExtractPath, sisFile);
-
-	cmdLine.append(SISEXTRACT_TOOL_EXTOPT);
-	cmdLine.append("\"" + iExtractPath + "\" ");
-	cmdLine.append(sisFile);
-
-	if(IsVerboseMode())
-	{
-		std::cout << "Executing " << (char*)cmdLine.data() << std::endl;
-	}
-
-	return RunCommand(cmdLine);
-}
-
-/**
-UpdatePkgFileMap: Update the package file map by getting the embedded sis file list from the parser object
-
-@internalComponent
-@released
-
-@param aPath - Extract path
-@param aFile - SIS file name
-*/
-void Sis2Iby::UpdatePkgFileMap(String aPath, String aFile)
-{
-	String pkgFileName;
-	std::list<String> sisList;
-
-	// main pkg file
-	pkgFileName = aPath;
-	AppendFileName(pkgFileName, aFile);
-	pkgFileName.append(".pkg");
-
-	// create an instance for the pkg file parser
-	// get the embedded sis file list
-	// add each as pkg file into the list
-	pkgParser = 0;
-	if( IsFileExist(pkgFileName) )
-	{
-		pkgParser = new PkgParser(pkgFileName);
-
-		if(pkgParser)
-		{
-			pkgParser->ParsePkgFile();
-
-			iPkgFileMap[pkgFileName] = pkgParser;
-
-			pkgParser->GetEmbeddedSisList(sisList);
-			SISFILE_LIST::iterator begin = sisList.begin();
-			SISFILE_LIST::iterator end = sisList.end();
-
-			while(begin != end)
-			{
-				String currPath = aPath;
-
-				currPath.append(PATHSEPARATOR);
-				GetFileName((*begin), currPath);
-				UpdatePkgFileMap(currPath, (*begin));
-
-				++begin;
-			}
-		}
-		else
-			throw SisUtilsException((char*)pkgFileName.data(), "Could not create parser object");
-	}
-	else
-		throw SisUtilsException((char*)pkgFileName.data(), "File not found");
-}
-
-/**
-WriteLanguages: Writes language section in the IBY file
-
-@internalComponent
-@released
-
-@param aParser - Package file parser object
-*/
-void Sis2Iby::WriteLanguages(PPKGPARSER aParser)
-{
-	LANGUAGE_LIST lanMap;
-	PLANG_LIST langCode;
-
-	aParser->GetLanguageList(lanMap);
-	ibyHandle << "\n// Languages: ";
-
-	LANGUAGE_LIST::iterator begin = lanMap.begin();
-	LANGUAGE_LIST::iterator end = lanMap.end();
-
-	while(begin != end)
-	{
-		langCode = (*begin);
-
-		ibyHandle << " " << langCode->langName;
-		ibyHandle << "(" << langCode->langCode;
-
-		if(langCode->dialectCode)
-		{
-			ibyHandle << "-" << langCode->dialectCode;
-		}
-		ibyHandle << ")";
-
-		++begin;
-	}
-}
-
-/**
-WritePackageHeader: Writes package header section in the IBY file
-
-@internalComponent
-@released
-
-@param aParser - Package file parser object
-*/
-void Sis2Iby::WritePackageHeader(PPKGPARSER aParser)
-{
-	PKG_HEADER pkgHeader;
-	std::list<String> pkgList;
-	std::ostringstream str;
-
-	aParser->GetHeader(pkgHeader);
-
-	ibyHandle << "\n// Header: ";
-
-	pkgList = pkgHeader.pkgNameList;
-	while(pkgList.size())
-	{
-		ibyHandle << "\"" << pkgList.front() << "\" ";
-		pkgList.pop_front();
-	}
-
-	str << "(0x" << std::setbase(16) << pkgHeader.pkgUid << ")";
-
-	ibyHandle << str.str();
-}
-
-/**
-WriteInstallOptions: Writes install option section in the IBY file
-
-@internalComponent
-@released
-
-@param aParser - Package file parser object
-*/
-void Sis2Iby::WriteInstallOptions(PPKGPARSER aParser)
-{
-	std::list<String> optList;
-	String ibyName;
-
-	aParser->GetInstallOptions(optList);
-	SISFILE_LIST::iterator begin = optList.begin();
-	SISFILE_LIST::iterator end = optList.end();
-
-	if(begin != end)
-	{
-		ibyHandle << "\n// Install Options: ";
-	}
-
-	while(begin != end)
-	{
-		ibyHandle << " \"" << (*begin) << "\"";
-		++begin;
-	}
-}
-
-/**
-InsertTabs: Inserts spaces for indentation in the output IBY file
-
-@internalComponent
-@released
-
-@param num - num of spaces to be inserted
-*/
-void Sis2Iby::InsertTabs(int num)
-{
-	ibyHandle << "\n";
-	while(num--)
-	{
-		ibyHandle << "  ";
-	}
-}
-
-/**
-WritePackageBody: Writes package body details in the IBY file
-
-@internalComponent
-@released
-
-@param aParser - Package file parser object
-*/
-void Sis2Iby::WritePackageBody(PPKGPARSER aParser)
-{
-	CMDBLOCK_LIST cmdList;
-	PCMD_BLOCK cmd;
-	int pad = 0;
-
-	ibyHandle << "\n\n";
-	aParser->GetCommandList(cmdList);
-
-	CMDBLOCK_LIST::iterator begin = cmdList.begin();
-	CMDBLOCK_LIST::iterator end = cmdList.end();
-
-	while(begin != end)
-	{
-		cmd = (*begin);
-
-		switch(cmd->cmdType)
-		{
-		case IF:
-			{
-				InsertTabs(pad);
-				ibyHandle << "#if " << cmd->cmdExpression;
-				pad++;
-			}
-			break;
-		case ELSEIF:
-			{
-				InsertTabs(pad-1);
-				ibyHandle << "#elif " << cmd->cmdExpression;
-			}
-			break;
-		case ELSE:
-			{
-				InsertTabs(pad-1);
-				ibyHandle << "#else";
-			}
-			break;
-		case ENDIF:
-			{
-				--pad;
-				InsertTabs(pad);
-				ibyHandle << "#endif";
-			}
-			break;
-		case INSTALLFILE:
-			{
-				WriteInstallFileList(cmd->iInstallFileList, aParser, pad);
-			}
-			break;
-		case PACKAGE:
-			{
-				InsertTabs(pad);
-				ibyHandle << "#include " << "\"" << cmd->cmdExpression << "\"";
-			}
-			break;
-		}
-
-		++begin;
-	}
-}
-
-/**
-WriteFileInclusion: Writes installable file details in the IBY file
-
-@internalComponent
-@released
-
-@param aSrcFile - Name of the source file
-@param aDestFile - Name of the destination file
-@param aPkgName - Name of the package file
-*/
-void Sis2Iby::WriteFileInclusion(String aSrcFile, String aDestFile, String aPkgName, int pad)
-{
-	NormaliseSourceFile(aSrcFile, aPkgName);
-
-	InsertTabs(pad);
-	if(IsValidE32Image(aSrcFile))
-	{
-		ibyHandle << "file = ";
-	}
-	else
-	{
-		ibyHandle << "data = ";
-	}
-
-	ibyHandle << aSrcFile << " ";
-	NormaliseDestFile(aDestFile);
-	ibyHandle << aDestFile;
-}
-
-/**
-WriteInstallFileList: Writes installable file details in the IBY file
-
-@internalComponent
-@released
-
-@param aFileList - Installable file list structure
-@param aParser - Package file parser object
-@param pad - Number of spaces for indentation purpose
-*/
-void Sis2Iby::WriteInstallFileList(PINSTALLFILE_LIST aFileList, PPKGPARSER aParser, int pad)
-{
-	WriteFileInclusion(aFileList->srcFiles.front(), aFileList->destFile, aParser->GetPkgFileName(), pad);
-}
-
-/**
-AppendFileName: Appends file name to the given path
-
-@internalComponent
-@released
-
-@param aPath - Source path
-@param aFile - File name
-*/
-void Sis2Iby::AppendFileName(String& aPath, String aFile)
-{
-	TUint pos = 0;
-
-	TrimQuotes(aPath);
-	TrimQuotes(aFile);
-
-	pos = aPath.rfind(PATHSEPARATOR);
-	if(pos == String::npos)
-	{
-		aPath.append(PATHSEPARATOR);
-	}
-
-	if(pos < (aPath.length()-1))
-	{
-		aPath.append(PATHSEPARATOR);
-	}
-
-	GetFileName(aFile, aPath);
-	return;
-}
-
-/**
-GetFileName: Returns the base file name
-
-@internalComponent
-@released
-
-@param aName - Input file name
-@param aFile - Output parameter to hold the return value
-*/
-void Sis2Iby::GetFileName(String aName, String& aFile)
-{
-	TUint spos = 0, epos = 0;
-
-	spos = aName.rfind(PATHSEPARATOR);
-	if(spos != String::npos)
-	{
-		spos += 1;
-	}
-	else
-	{
-		spos = 0;
-	}
-
-	epos = aName.rfind(".");
-	if(epos == String::npos)
-	{
-		epos = aName.size();
-	}
-
-	aFile.append(aName.substr(spos, (epos-spos)));
-}
-
-/**
-MakeFullPath: Returns the absolute path of the given file
-
-@internalComponent
-@released
-
-@param aFile - Input file name
-*/
-void Sis2Iby::MakeFullPath(String& aFile)
-{
-#ifdef WIN32
-	char fPath[_MAX_PATH];
-
-	if( _fullpath(fPath, (char*)aFile.data(), _MAX_PATH) != NULL )
-	{
-		aFile.assign(fPath);
-	}
-#else
-#error "TODO: Implement this function under other OS than Windows"
-#endif
-	return;
-}
-
-/**
-NormaliseSourceFile: Normalise the source file with its absolute path
-
-@internalComponent
-@released
-
-@param aFile - Input file name
-@param aPkgFile - Package file path
-*/
-void Sis2Iby::NormaliseSourceFile(String& aFile, String aPkgFile)
-{
-	String result;
-	TUint pos = 0;
-
-	pos = aPkgFile.rfind(PATHSEPARATOR);
-	if(pos != String::npos)
-	{
-		result = aPkgFile.substr(0,pos);
-	}
-	else
-	{
-		result = ".";
-	}
-
-	result.append(PATHSEPARATOR);
-	result.append(aFile);
-
-	MakeFullPath(result);
-
-	aFile = "\"" + result + "\"";
-}
-
-/**
-NormaliseDestFile: Normalise the destination file
-
-@internalComponent
-@released
-
-@param aFile - Input file name
-*/
-void Sis2Iby::NormaliseDestFile(String& aFile)
-{
-	TUint pos = 0;
-
-	/** Comment by KunXu to fix DEF122540 on 18 Jun 2008
-	pos = aFile.find("$:");
-	if(pos != String::npos)
-	{
-		aFile.replace(pos, 2, "");
-	}
-
-	pos = aFile.find("!:");
-	if(pos != String::npos)
-	{
-		aFile.replace(pos, 2, "");
-	}
-	**/
-
-	/** Add by KunXu to fix DEF122540 on 18 Jun 2008 **/
-	/** Ignore any drive indication in the filename to generate an iby file **/
-	/** Begin **/
-	pos = aFile.find(":");
-	if (1 == pos)
-	{
-		char chFirst = aFile[0];
-		if ('$' == chFirst || '!' == chFirst || (chFirst >='a' && chFirst <='z') || (chFirst >='A' && chFirst <='Z'))
-		{
-			aFile.replace(0, 2, "");
-		}
-	}
-	/** End **/
-
-	aFile = "\"" + aFile + "\"";
-}
-
-/**
-IsValidE32Image: Checks whether the given file is E32 image
-
-@internalComponent
-@released
-
-@param aFile - Input file name
-*/
-TBool Sis2Iby::IsValidE32Image(String aFile)
-{
-	std::ifstream aIfs;
-	TInt8 aSig[5];
-	TUint32 e32SigOffset = 0x10, fileSize = 0;
-	TBool validE32 = EFalse;
-
-	TrimQuotes(aFile);
-
-	aIfs.open(aFile.c_str(), std::ios::in | std::ios::binary);
-
-	if( !aIfs.is_open() )
-	{
-		throw SisUtilsException((char*)aFile.data(), "Cannot open file");
-	}
-
-	aIfs.seekg(0,std::ios::end);
-	fileSize = aIfs.tellg();
-	if(fileSize > 20)
-	{
-		aIfs.seekg(e32SigOffset,std::ios::beg);
-		aIfs.read((char*)aSig, 4);
-		aSig[4] = '\0';
-
-		if(!strcmp((char*)aSig, "EPOC"))
-		{
-			validE32 = ETrue;
-		}
-	}
-
-	aIfs.close();
-
-	return validE32;
-}
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#include "sisutils.h"
+#include "sis2iby.h"
+
+/**
+Constructor: Sis2Iby class
+Initilize the parameters to data members.
+
+@internalComponent
+@released
+
+@param aFile	- SIS file name
+*/
+Sis2Iby::Sis2Iby(const char* aFile) : SisUtils(aFile) {
+}
+
+/**
+Destructor: Sis2Iby class
+Deallocates the memory for data members
+
+@internalComponent
+@released
+*/
+Sis2Iby::~Sis2Iby() {
+	PKGFILE_MAP::iterator begin = iPkgFileMap.begin();
+	PKGFILE_MAP::iterator end = iPkgFileMap.end();
+	while(begin != end) {
+		PPKGPARSER ptemp = 0;
+		ptemp = (*begin).second;
+
+		if(ptemp)
+			delete ptemp;
+		++begin;
+	}
+	iPkgFileMap.clear();
+}
+
+/**
+ProcessSisFile: Processes the input sis file
+  Invoke the DUMPSIS tool to extract the sis file contents
+  Creates package parser object for each of the package file
+
+@internalComponent
+@released
+*/
+void Sis2Iby::ProcessSisFile() {
+	TUint32 retStatus = STAT_SUCCESS;
+	string sisFile = SisFileName();
+
+	if(IsVerboseMode()) {
+		cout << "Processing " << sisFile.c_str() << endl;
+	}
+
+	if(IsFileExist(sisFile)) {
+		retStatus = InvokeExtractTool(sisFile);
+
+		switch(retStatus) {
+		case STAT_SUCCESS: 
+			UpdatePkgFileMap(iExtractPath, sisFile); 
+			break;
+		case STAT_FAILURE:
+			throw SisUtilsException(sisFile.c_str(), "Failed to extract SIS file");
+			break ;
+		}
+	}
+	else
+		throw SisUtilsException(sisFile.c_str(), "File not found");
+}
+
+/**
+GenerateOutput: Generates IBY for each of the package file
+
+@internalComponent
+@released
+*/
+void Sis2Iby::GenerateOutput() {
+	PKGFILE_MAP::iterator begin = iPkgFileMap.begin();
+	PKGFILE_MAP::iterator end = iPkgFileMap.end();
+	while(begin != end) {
+		GenerateIby((*begin).first, (*begin).second);
+		++begin;
+	}
+}
+
+/**
+GenerateOutput: Generates IBY file for the given package file
+
+@internalComponent
+@released
+
+@param aPkgFile - package file name
+@param aParser - corresponding package file reader object
+*/
+void Sis2Iby::GenerateIby(string aPkgFile, PPKGPARSER aParser) {
+	string ibyFile = iOutputPath;
+	
+	AppendFileName(ibyFile, aPkgFile);
+	ibyFile.append(".iby");
+
+	if( !MakeDirectory(iOutputPath) )
+		throw SisUtilsException(iOutputPath.c_str(), "Failed to create path");
+
+	if(IsVerboseMode())	{
+		cout << "Generating IBY file " << ibyFile.c_str() << endl;
+	}
+
+	ibyHandle.open(ibyFile.c_str(),ios_base::out);
+
+	if(!ibyHandle.good()) 	{
+		throw SisUtilsException(ibyFile.c_str() , "Failed to create IBY file");
+	}
+
+	// Generating Header
+	MakeFullPath(aPkgFile);
+	ibyHandle << "\n// Generated IBY file for the package file: ";
+	ibyHandle << aPkgFile;
+
+	// Language Supported
+	WriteLanguages(aParser);
+
+	// Package Header
+	WritePackageHeader(aParser);
+
+	// Install options list
+	WriteInstallOptions(aParser);
+
+	// Package Body
+	WritePackageBody(aParser);
+
+	ibyHandle.close();
+}
+
+/**
+InvokeExtractTool: Invokes the SIS file extraction tool and returns the status
+
+@internalComponent
+@released
+
+@param sisFile - SIS file name
+*/
+TUint32 Sis2Iby::InvokeExtractTool(const string& aSisFile) {
+	string cmdLine;
+
+	cmdLine.append(SISEXTRACT_TOOL_NAME SISEXTRACT_TOOL_DEFOPT);
+
+	AppendFileName(iExtractPath, aSisFile);
+
+	cmdLine.append(SISEXTRACT_TOOL_EXTOPT);
+	cmdLine.append("\"" + iExtractPath + "\" ");
+	cmdLine.append(aSisFile);
+
+	if(IsVerboseMode()) {
+		cout << "Executing " << cmdLine.c_str() << endl;
+	}
+
+	return RunCommand(cmdLine.c_str());
+}
+
+/**
+UpdatePkgFileMap: Update the package file map by getting the embedded sis file list from the parser object
+
+@internalComponent
+@released
+
+@param aPath - Extract path
+@param aFile - SIS file name
+*/
+void Sis2Iby::UpdatePkgFileMap(const string& aPath, const string& aFile) {
+	string pkgFileName;
+	list<string> sisList;
+
+	// main pkg file
+	pkgFileName = aPath;
+	AppendFileName(pkgFileName, aFile);
+	pkgFileName.append(".pkg");
+
+	// create an instance for the pkg file parser
+	// get the embedded sis file list
+	// add each as pkg file into the list
+	pkgParser = 0;
+	if( IsFileExist(pkgFileName) ) {
+		pkgParser = new PkgParser(pkgFileName);
+
+		if(pkgParser) {
+			pkgParser->ParsePkgFile();
+
+			iPkgFileMap[pkgFileName] = pkgParser;
+
+			pkgParser->GetEmbeddedSisList(sisList);
+			SISFILE_LIST::iterator begin = sisList.begin();
+			SISFILE_LIST::iterator end = sisList.end();
+
+			while(begin != end) {
+				string currPath = aPath;
+
+				currPath.append(PATHSEPARATOR);
+				GetFileName((*begin), currPath);
+				UpdatePkgFileMap(currPath, (*begin));
+
+				++begin;
+			}
+		}
+		else
+			throw SisUtilsException(pkgFileName.c_str(), "Could not create parser object");
+	}
+	else
+		throw SisUtilsException(pkgFileName.c_str(), "File not found");
+}
+
+/**
+WriteLanguages: Writes language section in the IBY file
+
+@internalComponent
+@released
+
+@param aParser - Package file parser object
+*/
+void Sis2Iby::WriteLanguages(PPKGPARSER aParser) {
+	LANGUAGE_LIST lanMap;
+	PLANG_LIST iLangCode;
+
+	aParser->GetLanguageList(lanMap);
+	ibyHandle << "\n// Languages: ";
+
+	LANGUAGE_LIST::iterator begin = lanMap.begin();
+	LANGUAGE_LIST::iterator end = lanMap.end();
+
+	while(begin != end) {
+		iLangCode = (*begin);
+
+		ibyHandle << " " << iLangCode->iLangName;
+		ibyHandle << "(" << iLangCode->iLangCode;
+
+		if(iLangCode->iDialectCode) {
+			ibyHandle << "-" << iLangCode->iDialectCode;
+		}
+		ibyHandle << ")";
+
+		++begin;
+	}
+}
+
+/**
+WritePackageHeader: Writes package header section in the IBY file
+
+@internalComponent
+@released
+
+@param aParser - Package file parser object
+*/
+void Sis2Iby::WritePackageHeader(PPKGPARSER aParser) {
+	PKG_HEADER pkgHeader;
+	list<string> pkgList;
+	ostringstream str;
+
+	aParser->GetHeader(pkgHeader);
+
+	ibyHandle << "\n// Header: ";
+
+	pkgList = pkgHeader.iPkgNames;
+	while(pkgList.size())
+	{
+		ibyHandle << "\"" << pkgList.front() << "\" ";
+		pkgList.pop_front();
+	}
+
+	str << "(0x" << setbase(16) << pkgHeader.iPkgUID << ")";
+
+	ibyHandle << str.str();
+}
+
+/**
+WriteInstallOptions: Writes install option section in the IBY file
+
+@internalComponent
+@released
+
+@param aParser - Package file parser object
+*/
+void Sis2Iby::WriteInstallOptions(PPKGPARSER aParser) {
+	list<string> optList;
+	string ibyName;
+
+	aParser->GetInstallOptions(optList);
+	SISFILE_LIST::iterator begin = optList.begin();
+	SISFILE_LIST::iterator end = optList.end();
+
+	if(begin != end) {
+		ibyHandle << "\n// Install Options: ";
+	}
+
+	while(begin != end) {
+		ibyHandle << " \"" << (*begin) << "\"";
+		++begin;
+	}
+}
+
+/**
+InsertTabs: Inserts spaces for indentation in the output IBY file
+
+@internalComponent
+@released
+
+@param num - num of spaces to be inserted
+*/
+void Sis2Iby::InsertTabs(TInt num) {
+	ibyHandle << "\n";
+	while(num--) {
+		ibyHandle << "  ";
+	}
+}
+
+/**
+WritePackageBody: Writes package body details in the IBY file
+
+@internalComponent
+@released
+
+@param aParser - Package file parser object
+*/
+void Sis2Iby::WritePackageBody(PPKGPARSER aParser) {
+	CMDBLOCK_LIST cmdList;
+	PCMD_BLOCK cmd;
+	TInt pad = 0;
+
+	ibyHandle << "\n\n";
+	aParser->GetCommandList(cmdList);
+
+	CMDBLOCK_LIST::iterator begin = cmdList.begin();
+	CMDBLOCK_LIST::iterator end = cmdList.end();
+
+	while(begin != end) {
+		cmd = (*begin);
+
+		switch(cmd->iCmdType)
+		{
+		case IF:			 
+			InsertTabs(pad);
+			ibyHandle << "#if " << cmd->iCmdExpr;
+			pad++;
+			 
+			break;
+		case ELSEIF:			
+			InsertTabs(pad-1);
+			ibyHandle << "#elif " << cmd->iCmdExpr;			
+			break;
+		case ELSE:		
+			InsertTabs(pad-1);
+			ibyHandle << "#else";			
+			break;
+		case ENDIF:			
+			--pad;
+			InsertTabs(pad);
+			ibyHandle << "#endif";			
+			break;
+		case INSTALLFILE:			
+			WriteInstallFileList(cmd->iInstallFileList, aParser, pad);			
+			break;
+		case PACKAGE:			
+			InsertTabs(pad);
+			ibyHandle << "#include " << "\"" << cmd->iCmdExpr << "\"";			
+			break;
+		}
+
+		++begin;
+	}
+}
+
+/**
+WriteFileInclusion: Writes installable file details in the IBY file
+
+@internalComponent
+@released
+
+@param aSrcFile - Name of the source file
+@param aDestFile - Name of the destination file
+@param aPkgName - Name of the package file
+*/
+void Sis2Iby::WriteFileInclusion(string aSrcFile, string aDestFile, string aPkgName, TInt aPadding) {
+	NormaliseSourceFile(aSrcFile, aPkgName);
+
+	InsertTabs(aPadding);
+	if(IsValidE32Image(aSrcFile)){
+		ibyHandle << "file = ";
+	}
+	else {
+		ibyHandle << "data = ";
+	}
+
+	ibyHandle << aSrcFile << " ";
+	NormaliseDestFile(aDestFile);
+	ibyHandle << aDestFile;
+}
+
+/**
+WriteInstallFileList: Writes installable file details in the IBY file
+
+@internalComponent
+@released
+
+@param aFileList - Installable file list structure
+@param aParser - Package file parser object
+@param pad - Number of spaces for indentation purpose
+*/
+void Sis2Iby::WriteInstallFileList(PINSTALLFILE_LIST aFileList, PPKGPARSER aParser, TInt aPadding) {
+	WriteFileInclusion(aFileList->iSourceFiles.front(), aFileList->iDestFile, aParser->GetPkgFileName(), aPadding);
+}
+
+/**
+AppendFileName: Appends file name to the given path
+
+@internalComponent
+@released
+
+@param aPath - Source path
+@param aFile - File name
+*/
+void Sis2Iby::AppendFileName(string& aPath, string aFile) {
+	TUint pos = 0;
+
+	TrimQuotes(aPath);
+	TrimQuotes(aFile);
+
+	pos = aPath.rfind(PATHSEPARATOR);
+	if(pos == string::npos) {
+		aPath.append(PATHSEPARATOR);
+	}
+
+	if(pos < (aPath.length() - 1)) {
+		aPath.append(PATHSEPARATOR);
+	}
+
+	GetFileName(aFile, aPath);
+	return;
+}
+
+/**
+GetFileName: Returns the base file name
+
+@internalComponent
+@released
+
+@param aName - Input file name
+@param aFile - Output parameter to hold the return value
+*/
+void Sis2Iby::GetFileName(const string& aName, string& aFile) {
+	TUint spos = 0, epos = 0;
+
+	spos = aName.rfind(PATHSEPARATOR);
+	if(spos != string::npos) {
+		spos += 1;
+	}
+	else {
+		spos = 0;
+	}
+
+	epos = aName.rfind(".");
+	if(epos == string::npos) {
+		epos = aName.size();
+	}
+
+	aFile.append(aName.substr(spos, (epos-spos)));
+}
+
+/**
+MakeFullPath: Returns the absolute path of the given file
+
+@internalComponent
+@released
+
+@param aFile - Input file name
+*/
+#ifndef _MAX_PATH
+#define _MAX_PATH 1024
+#endif
+void Sis2Iby::MakeFullPath(string& aFile) {
+ 
+	char path[_MAX_PATH];
+	if( _fullpath(path, aFile.c_str(), _MAX_PATH) != NULL ) {
+		aFile.assign(path);
+	}
+
+}
+
+/**
+NormaliseSourceFile: Normalise the source file with its absolute path
+
+@internalComponent
+@released
+
+@param aFile - Input file name
+@param aPkgFile - Package file path
+*/
+void Sis2Iby::NormaliseSourceFile(string& aFile, const string& aPkgFile) {
+	string result;
+	TUint pos = 0;
+
+	pos = aPkgFile.rfind(PATHSEPARATOR);
+	if(pos != string::npos) {
+		result = aPkgFile.substr(0,pos);
+	}
+	else {
+		result = ".";
+	}
+
+	result.append(PATHSEPARATOR);
+	result.append(aFile);
+
+	MakeFullPath(result);
+
+	aFile = "\"" + result + "\"";
+}
+
+/**
+NormaliseDestFile: Normalise the destination file
+
+@internalComponent
+@released
+
+@param aFile - Input file name
+*/
+void Sis2Iby::NormaliseDestFile(string& aFile) {
+	TUint pos = 0; 
+	pos = aFile.find(":");
+	if (1 == pos) {
+		char chFirst = aFile[0];
+		if ('$' == chFirst || '!' == chFirst || (chFirst >='a' && chFirst <='z') || (chFirst >='A' && chFirst <='Z')) {
+			aFile.replace(0, 2, "");
+		}
+	}
+ 
+
+	aFile = "\"" + aFile + "\"";
+}
+
+/**
+IsValidE32Image: Checks whether the given file is E32 image
+
+@internalComponent
+@released
+
+@param aFile - Input file name
+*/
+TBool Sis2Iby::IsValidE32Image(string aFile) {
+	ifstream file;
+	char sig[5];
+	TUint32 e32SigOffset = 0x10, fileSize = 0;
+	TBool validE32 = EFalse;
+
+	TrimQuotes(aFile);
+
+	file.open(aFile.c_str(), ios_base::in | ios_base::binary);
+
+	if( !file.is_open() ) {
+		throw SisUtilsException(aFile.c_str(), "Cannot open file");
+	}
+
+	file.seekg(0,ios_base::end);
+	fileSize = file.tellg();
+	if(fileSize > 20) {
+		file.seekg(e32SigOffset,ios_base::beg);
+		file.read(sig, 4);
+		sig[4] = '\0';
+
+		if(!strcmp(sig, "EPOC")) {
+			validE32 = ETrue;
+		}
+	}
+
+	file.close();
+	return validE32;
+}
--- a/imgtools/sisutils/src/sisutils.cpp	Fri Jun 25 20:58:33 2010 +0800
+++ b/imgtools/sisutils/src/sisutils.cpp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,291 +1,389 @@
-/*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of the License "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: 
-*
-*/
-
-
-#ifdef WIN32
-#include <windows.h>
-#include <direct.h>
-#endif
-
-#include "sisutils.h"
-
-/**
-Constructor: SisUtilsException class
-Initilize the parameters to data members.
-
-@internalComponent
-@released
-
-@param aFile	- Name of the file
-@param aErrMessage - Error message
-*/
-SisUtilsException::SisUtilsException(char* aFile, char* aErrMessage) : \
-	iSisFileName(aFile), iErrMessage(aErrMessage)
-{
-}
-
-/**
-Destructor: SisUtilsException class
-Deallocates the memory for data members
-
-@internalComponent
-@released
-*/
-SisUtilsException::~SisUtilsException()
-{
-}
-
-/**
-Report: Reports error message on the console
-
-@internalComponent
-@released
-*/
-void SisUtilsException::Report()
-{
-	std::cout << "Error : ";
-	std::cout << iSisFileName.c_str() << " : ";
-	std::cout << iErrMessage.c_str();
-	std::cout << std::endl;
-}
-
-/**
-Constructor: SisUtils class
-Initilize the parameters to data members.
-
-@internalComponent
-@released
-
-@param aFile	- Name of the SIS file
-*/
-SisUtils::SisUtils(char* aFile) :  iVerboseMode(EFalse),iSisFile(aFile)
-{
-}
-
-/**
-Destructor: SisUtils class
-Deallocates the memory for data members
-
-@internalComponent
-@released
-*/
-SisUtils::~SisUtils()
-{
-}
-
-/**
-SetVerboseMode: Sets the verbose mode
-
-@internalComponent
-@released
-*/
-void SisUtils::SetVerboseMode()
-{
-	iVerboseMode = ETrue;
-}
-
-/**
-SisFileName: Returns the SIS file name
-
-@internalComponent
-@released
-*/
-String SisUtils::SisFileName()
-{
-	return iSisFile;
-}
-
-/**
-IsVerboseMode: Returns the status of the verbose mode
-
-@internalComponent
-@released
-*/
-TBool SisUtils::IsVerboseMode()
-{
-	return iVerboseMode;
-}
-
-/**
-IsFileExist: Tests whether the give file exists or not
-
-@internalComponent
-@released
-
-@param aFile - Name of the file
-*/
-TBool SisUtils::IsFileExist(String aFile)
-{
-	std::ifstream aIfs;
-
-	TrimQuotes(aFile);
-
-	aIfs.open((char*)aFile.data(), std::ios::in);
-
-	if( aIfs.fail() )
-	{
-		aIfs.close();
-		return EFalse;
-	}
-
-	aIfs.close();
-
-	return ETrue;
-}
-
-/**
-RunCommand: Runs the given command
-
-@internalComponent
-@released
-
-@param cmd - Command line as string
-*/
-TUint32 SisUtils::RunCommand(String cmd)
-{
-	TUint32 iExitCode = STAT_SUCCESS;
-
-#ifdef WIN32
-    STARTUPINFO si;
-    PROCESS_INFORMATION pi;
-	DWORD dwWaitResult;
-
-    memset(&si, 0, sizeof(si));
-    si.cb = sizeof(si);
-    memset(&pi, 0, sizeof(pi));
-
-    if( !::CreateProcess( NULL,   // No module name (use command line)
-        (char*)cmd.data(),        // Command line
-        NULL,           // Process handle not inheritable
-        NULL,           // Thread handle not inheritable
-        FALSE,          // Set handle inheritance to FALSE
-        DETACHED_PROCESS | CREATE_NO_WINDOW,              // process creation flags
-        NULL,           // Use parent's environment block
-        NULL,           // Use parent's starting directory 
-        &si,            // Pointer to STARTUPINFO structure
-        &pi )           // Pointer to PROCESS_INFORMATION structure
-    ) 
-    {
-		return static_cast<TUint32>(STAT_FAILURE);
-    }
-
-	dwWaitResult = ::WaitForSingleObject( pi.hProcess, INFINITE );
-
-	if(dwWaitResult == WAIT_OBJECT_0)
-	{
-		::GetExitCodeProcess(pi.hProcess, &iExitCode);
-		if(iExitCode != STAT_SUCCESS)
-		{
-			iExitCode = static_cast<TUint32>(STAT_FAILURE);
-		}
-	}
-	else
-	{
-		iExitCode = static_cast<TUint32>(STAT_FAILURE);
-	}
-
-	::CloseHandle( pi.hProcess );
-	::CloseHandle( pi.hThread );
-#else
-#error "TODO: Implement this function under other OS than Windows"
-#endif
-
-	return iExitCode;
-}
-
-/**
-TrimQuotes: Remove the quotes in the given file name
-
-@internalComponent
-@released
-
-@param aStr - File name
-*/
-void SisUtils::TrimQuotes(String& aStr)
-{
-	TUint spos = 0, epos = 0;
-
-	spos = aStr.find("\"");
-	if(spos == String::npos)
-		return;
-
-	epos = aStr.rfind("\"");
-
-	if(spos == epos)
-	{
-		epos = aStr.size();
-		aStr = aStr.substr(spos+1,epos);
-	}
-	else
-	{
-		aStr = aStr.substr(spos+1,epos-1);
-
-		spos = aStr.find("\"");
-		while( spos != String::npos )
-		{
-			aStr.erase(spos,1);
-			spos = aStr.find("\"");
-		}
-	}
-
-	return;
-}
-
-/**
-MakeDirectory: Creates directory if it is not exist
-
-@internalComponent
-@released
-
-@param aPath - Directory name to be created
-*/
-TBool SisUtils::MakeDirectory(String aPath)
-{
-	TBool status = ETrue;
-	TUint currpos = 0;
-	String dir;
-
-	do
-	{
-		currpos = aPath.find_first_of(PATHSEPARATOR, currpos);
-		if(currpos == String::npos)
-		{
-			dir = aPath.substr(0, aPath.length());
-		}
-		else
-		{
-			dir = aPath.substr(0, currpos);
-			currpos++;
-		}
-
-#ifdef WIN32
-		if(mkdir((char*)dir.data()) != 0)
-		{
-			if(errno != EEXIST)
-			{
-				status = EFalse;
-			}
-		}
-#else
-#error "TODO: Implement this function under other OS than Windows"
-#endif
-		if(status == EFalse)
-			break;
-	} while(currpos != String::npos);
-
-	return status;
-}
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of the License "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: 
+*
+*/
+
+
+#ifdef WIN32
+#ifdef _STLP_INTERNAL_WINDOWS_H
+#define __INTERLOCKED_DECLARED
+#endif
+#include <windows.h>
+#include <direct.h>
+#define MKDIR mkdir
+#else
+#include <unistd.h>
+#include <sys/wait.h>
+
+#include <sys/stat.h>
+#include <sys/types.h>
+#define MKDIR(a) mkdir(a,0777)
+#endif
+
+#include "sisutils.h"
+#include <errno.h>
+
+
+/**
+Constructor: SisUtilsException class
+Initilize the parameters to data members.
+
+@internalComponent
+@released
+
+@param aFile	- Name of the file
+@param aErrMessage - Error message
+*/
+SisUtilsException::SisUtilsException(const char* aFile, const char* aErrMessage) : \
+	iSisFileName(aFile), iErrMessage(aErrMessage)
+{
+}
+
+/**
+Destructor: SisUtilsException class
+Deallocates the memory for data members
+
+@internalComponent
+@released
+*/
+SisUtilsException::~SisUtilsException()
+{
+}
+
+/**
+Report: Reports error message on the console
+
+@internalComponent
+@released
+*/
+void SisUtilsException::Report()
+{
+	cout << "Error : " << iSisFileName.c_str() << " : " << iErrMessage.c_str() << endl;
+}
+
+/**
+Constructor: SisUtils class
+Initilize the parameters to data members.
+
+@internalComponent
+@released
+
+@param aFile	- Name of the SIS file
+*/
+SisUtils::SisUtils(const char* aFile) :  iVerboseMode(EFalse),iSisFile(aFile)
+{
+}
+
+/**
+Destructor: SisUtils class
+Deallocates the memory for data members
+
+@internalComponent
+@released
+*/
+SisUtils::~SisUtils()
+{
+}
+
+/**
+SetVerboseMode: Sets the verbose mode
+
+@internalComponent
+@released
+*/
+void SisUtils::SetVerboseMode()
+{
+	iVerboseMode = ETrue;
+}
+
+/**
+SisFileName: Returns the SIS file name
+
+@internalComponent
+@released
+*/
+const char* SisUtils::SisFileName()
+{
+	return iSisFile.c_str();
+}
+
+/**
+IsVerboseMode: Returns the status of the verbose mode
+
+@internalComponent
+@released
+*/
+TBool SisUtils::IsVerboseMode()
+{
+	return iVerboseMode;
+}
+
+/**
+IsFileExist: Tests whether the give file exists or not
+
+@internalComponent
+@released
+
+@param aFile - Name of the file
+*/
+TBool SisUtils::IsFileExist(string aFile)
+{
+	ifstream file;
+	TrimQuotes(aFile);
+	file.open(aFile.c_str(), ios_base::in);
+	TBool retVal = EFalse ;
+	if(file.is_open()){
+		file.close();
+		retVal = ETrue ;
+	}
+	return retVal;
+}
+
+/**
+RunCommand: Runs the given command
+
+@internalComponent
+@released
+
+@param cmd - Command line as string
+*/
+TUint32 SisUtils::RunCommand(const char* aCmd) {
+	TUint32 iExitCode = STAT_SUCCESS;
+
+#ifdef WIN32
+	STARTUPINFO si ; 
+	PROCESS_INFORMATION pi ; 
+	memset(&si,0,sizeof(STARTUPINFO));
+	si.cb = sizeof(STARTUPINFO);
+	memset(&pi,0,sizeof(PROCESS_INFORMATION));
+
+    if( !::CreateProcess( NULL,   // No module name (use command line)
+        const_cast<char*>(aCmd),        // Command line
+        NULL,           // Process handle not inheritable
+        NULL,           // Thread handle not inheritable
+        FALSE,          // Set handle inheritance to FALSE
+        DETACHED_PROCESS | CREATE_NO_WINDOW,              // process creation flags
+        NULL,           // Use parent's environment block
+        NULL,           // Use parent's starting directory 
+        &si,            // Pointer to STARTUPINFO structure
+        &pi ))           // Pointer to PROCESS_INFORMATION structure     
+		return static_cast<TUint32>(STAT_FAILURE);
+    
+
+	TUint32 dwWaitResult = ::WaitForSingleObject( pi.hProcess, INFINITE );
+	if(dwWaitResult == WAIT_OBJECT_0) {
+		::GetExitCodeProcess(pi.hProcess, &iExitCode);
+		if(iExitCode != STAT_SUCCESS){
+			iExitCode = static_cast<TUint32>(STAT_FAILURE);
+		}
+	}
+	else {
+		iExitCode = static_cast<TUint32>(STAT_FAILURE);
+	}
+
+	::CloseHandle( pi.hProcess );
+	::CloseHandle( pi.hThread );
+#else
+
+	TInt child_pid  = fork();
+	if( -1 == child_pid)
+		return (TUint32)STAT_FAILURE;
+	if(0 == child_pid){
+		if(-1 == execl(aCmd,"",NULL))
+			return (TUint32)STAT_FAILURE;
+	}
+	else{
+		TInt status = 0 ;
+		iExitCode = (TUint32)STAT_FAILURE;
+        while(wait(&status) != child_pid);
+        iExitCode  = WEXITSTATUS(status)  ;
+	}
+	
+#endif
+
+	return iExitCode;
+}
+
+/**
+TrimQuotes: Remove the quotes in the given file name
+
+@internalComponent
+@released
+
+@param aStr - File name
+*/
+void SisUtils::TrimQuotes(string& aStr) {
+
+	TUint spos  = aStr.find("\"");
+	if(spos == string::npos)
+		return;
+
+	TUint epos = aStr.rfind("\"");
+
+	if(spos == epos) {
+		epos = aStr.size();
+		aStr = aStr.substr(spos+1,epos);
+	}
+	else {
+		aStr = aStr.substr(spos+1,epos-1);
+		spos = aStr.find("\"");
+		while( spos != string::npos )
+		{
+			aStr.erase(spos,1);
+			spos = aStr.find("\"");
+		}
+	}
+
+	return;
+}
+
+/**
+MakeDirectory: Creates directory if it is not exist
+
+@internalComponent
+@released
+
+@param aPath - Directory name to be created
+*/
+TBool SisUtils::MakeDirectory(const string& aPath) {
+	TBool status = ETrue;
+	TUint currpos = 0;
+	string dir;
+
+	do 	{
+		currpos = aPath.find_first_of(PATHSEPARATOR, currpos);
+		if(currpos == string::npos) {
+			dir = aPath.substr(0, aPath.length());
+		} else {
+			dir = aPath.substr(0, currpos);
+			currpos++;
+		}
+ 
+		if(MKDIR(dir.c_str()) != 0){
+			if(errno != EEXIST)	{
+				status = EFalse;
+			}
+		} 
+		if(status == EFalse)
+			break;
+	} while(currpos != string::npos);
+
+	return status;
+}
+#ifndef WIN32
+/*static inline wchar_t to_lowerW(wchar_t aChar){
+	return (aChar >= L'A' && aChar <= L'Z') ? (aChar | 0x20) : aChar ; 
+}
+int wcsnicmp(const wchar_t* str1,const wchar_t* str2,size_t n){
+	wchar_t a , b ;
+	size_t i = 0 ;
+	while(*str1 && *str2){
+		a = to_lowerW(*str1) ;
+		b = to_lowerW(*str2) ; 
+		if(a > b )
+			return 1 ;
+		else if(a < b)
+			return -1 ;
+		if(++i >= n) break ;
+		str1++ ;
+		str2++ ;		
+	}
+	return 0;
+}
+int wcsicmp(const wchar_t* str1,const wchar_t* str2){
+	wchar_t a , b ;
+	while(*str1 && *str2){
+		a = to_lowerW(*str1) ;
+		b = to_lowerW(*str2) ; 
+		if(a > b )
+			return 1 ;
+		else if(a < b)
+			return -1 ;
+		str1++ ;
+		str2++ ;
+	}
+	if(0 == *str1 && 0 == *str2){
+		return 0 ;
+	}
+	else if(*str1)
+		return 1;
+	else
+		return -1;
+}
+int iswdigit(wchar_t ch){
+	if(ch >= L'0' && ch <= L'9') return 1 ;
+	return 0;
+}*/
+char *_fullpath(char* absPath, const char*relPath, size_t maxLength){
+	if(*relPath == '/'){
+		return strncpy(absPath,relPath,maxLength);
+	}
+	*absPath = 0 ;
+	getcwd(absPath,maxLength);
+	size_t len = strlen(absPath);
+	//absPath[len++] = '/';
+	int upward = 0 ;
+	int status = 0 ;
+	const char* savedPath = relPath ;
+	while(*relPath){
+		if(*relPath == '.'){
+			status ++ ;
+		}
+		else if(*relPath == '/'){
+			if(status == 2){
+				upward ++ ;
+			}
+			else if(status != 1)
+				break ;
+			status = 0 ;
+			savedPath = relPath + 1;
+		}
+		else {
+			break ;
+		}
+		relPath ++ ;
+			
+	}
+	if(0 == *relPath){ // like ".." or "." 
+		if(2 == status) 
+			upward ++ ;			 
+	}
+	else {
+		relPath = savedPath ;
+	}
+	char* pathEnd = &absPath[len];	
+	while(upward > 0){ // we have "../" in the beginning of relPath
+		pathEnd -- ;
+		if(pathEnd <= absPath)	return NULL ;
+		while(pathEnd > absPath){
+			pathEnd -- ;
+			if(*pathEnd == '/')
+				break ;
+		}
+		upward -- ;
+	}
+	if(0 != *relPath){
+		*pathEnd = '/' ;
+		char* conjBegin = pathEnd + 1;
+		size_t bufLen = maxLength - (conjBegin - absPath);	
+		strncpy(conjBegin,relPath,bufLen);
+	}else {
+		*pathEnd = 0 ;
+	}
+		
+	return absPath ;
+	 
+}
+#endif
--- a/package_definition.xml	Fri Jun 25 20:58:33 2010 +0800
+++ b/package_definition.xml	Tue Jun 29 14:52:54 2010 +0800
@@ -1,76 +1,76 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<SystemDefinition schema="3.0.0">
-    <package id="build" levels="lowlevel-libs middleware framework ui" name="Build">
-        <collection id="bintools" level="framework" name="Binary Tools">
-            <component filter="build_SFPhase3" id="evalid" name="Evalid" >
-                <unit bldFile="bintools/evalid" mrp="bintools/evalid/evalid.mrp"/>
-            </component>
-            <component filter="build_SFPhase1" id="rcomp" name="Resource Compiler" >
-                <unit bldFile="bintools/rcomp/group" mrp="bintools/rcomp/group/rcomp.mrp"/>
-            </component>
-            <component filter="build_SFPhase1" id="checklib" name="checklib" >
-                <unit bldFile="bintools/checklib/group" mrp="bintools/checklib/group/checklib.mrp"/>
-            </component>
-            <component filter="build_SFPhase1" id="elftools" name="elftools" >
-                <unit bldFile="bintools/elftools/group" mrp="bintools/elftools/group/elftools.mrp"/>
-            </component>
-        </collection>
-        <collection id="srctools" level="middleware" name="Source Tools">
-            <component filter="build_SFPhase1" id="tranasm" name="tranasm" >
-                <unit bldFile="srctools/tranasm/group" mrp="srctools/tranasm/group/tranasm.mrp"/>
-            </component>
-        </collection>
-        <collection id="e32tools" level="middleware" name="E32 Tools">
-            <component filter="build_SFPhase1" id="elf2e32" name="elf2e32 (Postlinker)" >
-                <unit bldFile="e32tools/elf2e32/group" mrp="e32tools/elf2e32/group/elf2e32.mrp"/>
-            </component>
-            <component filter="build_SFPhase1" id="e32lib" name="E32 Image Library" >
-                <unit bldFile="e32tools/e32lib/group" mrp="e32tools/e32lib/group/e32lib.mrp"/>
-            </component>
-        </collection>
-        <collection id="buildtoolguides" level="ui" name="Build Tool Guides">
-            <component filter="build_SFPhase3" id="emulconfiguratorguide" name="Emulator Configurator Guide" >
-                <unit bldFile="buildtoolguides/emulconfiguratorguide/group" mrp="buildtoolguides/emulconfiguratorguide/group/emulbuilderguide.mrp"/>
-            </component>
-            <component filter="build_SFPhase3" id="romtoolsguide" name="ROM Tools Guide" >
-                <unit bldFile="buildtoolguides/romtoolsguide/group" mrp="buildtoolguides/romtoolsguide/group/romtoolsguide.mrp"/>
-            </component>
-            <component filter="build_SFPhase3" id="sbsv2guide" name="SBSv2 Guide" >
-                <unit bldFile="buildtoolguides/sbsv2guide/group" mrp="buildtoolguides/sbsv2guide/group/sbsv2guide.mrp"/>
-            </component>
-        </collection>
-        <collection id="sbsv2" level="middleware" name="Symbian Build System v2">
-            <component filter="build_SFPhase3" id="cpp-raptor" name="CPP (Raptor)" >
-                <unit bldFile="sbsv2/cpp-raptor/group" mrp="sbsv2/cpp-raptor/group/cpp-raptor.mrp"/>
-            </component>
-            <component filter="build_SFPhase3" id="pvmgmake" name="PVM Gmake" >
-                <unit bldFile="sbsv2/pvmgmake/group" mrp="sbsv2/pvmgmake/group/pvmgmake.mrp"/>
-            </component>
-            <component filter="build_SFPhase3" id="raptor" name="SBSv2 (Raptor)" >
-                <unit bldFile="sbsv2/raptor/group" mrp="sbsv2/raptor/group/raptor.mrp"/>
-            </component>
-        </collection>
-        <collection id="imgtools" level="framework" name="Image Tools">
-            <component filter="build_SFPhase3" id="romtools" name="ROM Tools" >
-                <unit bldFile="imgtools/romtools/group" mrp="imgtools/romtools/group/romtools.mrp"/>
-            </component>
-            <component filter="build_SFPhase3" id="buildrom" name="Build ROM" >
-                <unit bldFile="imgtools/buildrom/group" mrp="imgtools/buildrom/group/buildrom.mrp"/>
-            </component>
-            <component filter="build_SFPhase1" id="imglib" name="ROM/ROFS Image Library" >
-                <unit bldFile="imgtools/imglib/group" mrp="imgtools/imglib/group/imglib.mrp"/>
-            </component>
-            <component filter="build_SFPhase3" id="sisutils" name="SIS Utility Library" >
-                <unit bldFile="imgtools/sisutils/group" mrp="imgtools/sisutils/group/sisutils.mrp"/>
-            </component>
-            <component filter="build_SFPhase2" id="imgcheck" name="Image Checker" >
-                <unit bldFile="imgtools/imgcheck/group" mrp="imgtools/imgcheck/group/imgcheck.mrp"/>
-            </component>
-        </collection>
-        <collection id="build_info" name="Build Info" level="ui">
-          <component id="build_metadata" name="Build Metadata" filter="build_SFPhase3">
-            <unit mrp="build_info/build_metadata/build_metadata.mrp"/>
-          </component>
-        </collection>
-    </package>
-</SystemDefinition>
+<?xml version="1.0" encoding="UTF-8"?>
+<SystemDefinition schema="3.0.0">
+    <package id="build" levels="lowlevel-libs middleware framework ui" name="Build">
+        <collection id="bintools" level="framework" name="Binary Tools">
+            <component filter="build_SFPhase3" id="evalid" name="Evalid" >
+                <unit bldFile="bintools/evalid" mrp="bintools/evalid/evalid.mrp"/>
+            </component>
+            <component filter="build_SFPhase1" id="rcomp" name="Resource Compiler" >
+                <unit bldFile="bintools/rcomp/group" mrp="bintools/rcomp/group/rcomp.mrp"/>
+            </component>
+            <component filter="build_SFPhase1" id="checklib" name="checklib" >
+                <unit bldFile="bintools/checklib/group" mrp="bintools/checklib/group/checklib.mrp"/>
+            </component>
+            <component filter="build_SFPhase1" id="elftools" name="elftools" >
+                <unit bldFile="bintools/elftools/group" mrp="bintools/elftools/group/elftools.mrp"/>
+            </component>
+        </collection>
+        <collection id="srctools" level="middleware" name="Source Tools">
+            <component filter="build_SFPhase1" id="tranasm" name="tranasm" >
+                <unit bldFile="srctools/tranasm/group" mrp="srctools/tranasm/group/tranasm.mrp"/>
+            </component>
+        </collection>
+        <collection id="e32tools" level="middleware" name="E32 Tools">
+            <component filter="build_SFPhase1" id="elf2e32" name="elf2e32 (Postlinker)" >
+                <unit bldFile="e32tools/elf2e32/group" mrp="e32tools/elf2e32/group/elf2e32.mrp"/>
+            </component>
+            <component filter="build_SFPhase1" id="e32lib" name="E32 Image Library" >
+                <unit bldFile="e32tools/e32lib/group" mrp="e32tools/e32lib/group/e32lib.mrp"/>
+            </component>
+        </collection>
+        <collection id="buildtoolguides" level="ui" name="Build Tool Guides">
+            <component filter="build_SFPhase3" id="emulconfiguratorguide" name="Emulator Configurator Guide" >
+                <unit bldFile="buildtoolguides/emulconfiguratorguide/group" mrp="buildtoolguides/emulconfiguratorguide/group/emulbuilderguide.mrp"/>
+            </component>
+            <component filter="build_SFPhase3" id="romtoolsguide" name="ROM Tools Guide" >
+                <unit bldFile="buildtoolguides/romtoolsguide/group" mrp="buildtoolguides/romtoolsguide/group/romtoolsguide.mrp"/>
+            </component>
+            <component filter="build_SFPhase3" id="sbsv2guide" name="SBSv2 Guide" >
+                <unit bldFile="buildtoolguides/sbsv2guide/group" mrp="buildtoolguides/sbsv2guide/group/sbsv2guide.mrp"/>
+            </component>
+        </collection>
+        <collection id="sbsv2" level="middleware" name="Symbian Build System v2">
+            <component filter="build_SFPhase3" id="cpp-raptor" name="CPP (Raptor)" >
+                <unit bldFile="sbsv2/cpp-raptor/group" mrp="sbsv2/cpp-raptor/group/cpp-raptor.mrp"/>
+            </component>
+            <component filter="build_SFPhase3" id="pvmgmake" name="PVM Gmake" >
+                <unit bldFile="sbsv2/pvmgmake/group" mrp="sbsv2/pvmgmake/group/pvmgmake.mrp"/>
+            </component>
+            <component filter="build_SFPhase3" id="raptor" name="SBSv2 (Raptor)" >
+                <unit bldFile="sbsv2/raptor/group" mrp="sbsv2/raptor/group/raptor.mrp"/>
+            </component>
+        </collection>
+        <collection id="imgtools" level="framework" name="Image Tools">
+            <component filter="build_SFPhase3" id="romtools" name="ROM Tools" >
+                <unit bldFile="imgtools/romtools/group" mrp="imgtools/romtools/group/romtools.mrp"/>
+            </component>
+            <component filter="build_SFPhase3" id="buildrom" name="Build ROM" >
+                <unit bldFile="imgtools/buildrom/group" mrp="imgtools/buildrom/group/buildrom.mrp"/>
+            </component>
+            <component filter="build_SFPhase1" id="imglib" name="ROM/ROFS Image Library" >
+                <unit bldFile="imgtools/imglib/group" mrp="imgtools/imglib/group/imglib.mrp"/>
+            </component>
+            <component filter="build_SFPhase3" id="sisutils" name="SIS Utility Library" >
+                <unit bldFile="imgtools/sisutils/group" mrp="imgtools/sisutils/group/sisutils.mrp"/>
+            </component>
+            <component filter="build_SFPhase2" id="imgcheck" name="Image Checker" >
+                <unit bldFile="imgtools/imgcheck/group" mrp="imgtools/imgcheck/group/imgcheck.mrp"/>
+            </component>
+        </collection>
+        <collection id="build_info" name="Build Info" level="ui">
+          <component id="build_metadata" name="Build Metadata" filter="build_SFPhase3">
+            <unit mrp="build_info/build_metadata/build_metadata.mrp"/>
+          </component>
+        </collection>
+    </package>
+</SystemDefinition>
--- a/sbsv1/abld/e32util/createrfifile.pl	Fri Jun 25 20:58:33 2010 +0800
+++ b/sbsv1/abld/e32util/createrfifile.pl	Tue Jun 29 14:52:54 2010 +0800
@@ -15,10 +15,14 @@
 #
 
 use File::Basename;
+# Version
+my $MajorVersion = 1;
+my $MinorVersion = 1;
+my $PatchVersion = 0;
 
 if (@ARGV <2)
 	{
-	print (STDERR "\ncreaterfifile.pl\n");
+	print (STDERR "\nCREATERFIFILE resource files combine tool V$MajorVersion.$MinorVersion.$PatchVersion\n");
 	print STDERR << 'END_OF_HELP';
 
 Usage: createrfifile.pl rss_cpp_deps_file.d output_file.rfi [exclude path]
--- a/sbsv1/abld/e32util/efreeze.pl	Fri Jun 25 20:58:33 2010 +0800
+++ b/sbsv1/abld/e32util/efreeze.pl	Tue Jun 29 14:52:54 2010 +0800
@@ -39,7 +39,7 @@
 # Version
 my $MajorVersion = 1;
 my $MinorVersion = 1;
-my $PatchVersion = 0;
+my $PatchVersion = 1;
 
 use lib $PerlLibPath;
 use Defutl;
--- a/sbsv1/abld/e32util/gendef.pl	Fri Jun 25 20:58:33 2010 +0800
+++ b/sbsv1/abld/e32util/gendef.pl	Tue Jun 29 14:52:54 2010 +0800
@@ -1,74 +1,74 @@
-# Copyright (c) 2008-2009 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:
-# e32toolp/e32util/gendef.pl
-# 
-#
-
-use FindBin;		# for FindBin::Bin
-
-my $PerlLibPath;    # fully qualified pathname of the directory containing our Perl modules
-
-BEGIN {
-# check user has a version of perl that will cope
-	require 5.005_03;
-# establish the path to the Perl libraries: currently the same directory as this script
-	$PerlLibPath = $FindBin::Bin;	# X:/epoc32/tools
-	$PerlLibPath =~ s/\//\\/g;	# X:\epoc32\tools
-	$PerlLibPath .= "\\";
-}
-
-use lib $PerlLibPath;
-use E32tpver;
-
-# THE MAIN PROGRAM SECTION
-##########################
-
-unless (@ARGV>1)
-{
-	&Usage;
-}
-my @exports = @ARGV;
-my $outfile = shift @exports;
-
-open OUTFILE, ">$outfile" or die "Gendef.pl: Unable to open $outfile for writing";
-
-print OUTFILE "EXPORTS\n";
-my $exportNum = 1;
-foreach (@exports)
-{
-	print OUTFILE "\t$_ @ $exportNum NONAME\n";
-	++$exportNum;
-}
-
-close OUTFILE;
-
-#######################################################################
-# SUBROUTINES
-#######################################################################
-
-sub Usage () {
-
-	print(
-		"\n",
-		"GENDEF - Generate a DEF file from passed exports (Build ",&E32tpver,")\n",
-		"\n",
-		"GENDEF.PL [output def file] [1st export name] ([Other export names]...)\n",
-		"\n",
-		"\n",
-		"\n"
-	);
-	exit 1;
-}
-
-
+#!/usr/bin/perl
+# Copyright (c) 2008-2009 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:
+# e32toolp/e32util/gendef.pl
+# 
+#
+
+use FindBin;		# for FindBin::Bin
+
+my $PerlLibPath;    # fully qualified pathname of the directory containing our Perl modules
+
+BEGIN {
+# check user has a version of perl that will cope
+	require 5.005_03;
+}
+
+# Version
+my $MajorVersion = 1;
+my $MinorVersion = 1;
+my $PatchVersion = 0;
+
+
+# THE MAIN PROGRAM SECTION
+##########################
+
+unless (@ARGV>1)
+{
+	&Usage;
+}
+my @exports = @ARGV;
+my $outfile = shift @exports;
+
+open OUTFILE, ">$outfile" or die "Gendef.pl: Unable to open $outfile for writing";
+
+print OUTFILE "EXPORTS\n";
+my $exportNum = 1;
+foreach (@exports)
+{
+	print OUTFILE "\t$_ @ $exportNum NONAME\n";
+	++$exportNum;
+}
+
+close OUTFILE;
+
+#######################################################################
+# SUBROUTINES
+#######################################################################
+
+sub Usage () {
+
+	print(
+		"\n",
+		"GENDEF - Generate a DEF file from passed exports V$MajorVersion.$MinorVersion.$PatchVersion\n",
+		"\n",
+		"GENDEF.PL [output def file] [1st export name] ([Other export names]...)\n",
+		"\n",
+		"\n",
+		"\n"
+	);
+	exit 1;
+}
+
+
--- a/sbsv1/abld/e32util/h2inc.pl	Fri Jun 25 20:58:33 2010 +0800
+++ b/sbsv1/abld/e32util/h2inc.pl	Tue Jun 29 14:52:54 2010 +0800
@@ -1,3 +1,4 @@
+#!/usr/bin/perl
 # Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies).
 # All rights reserved.
 # This component and the accompanying materials are made available
@@ -19,6 +20,11 @@
 # 
 #
 
+# Version
+my $MajorVersion = 1;
+my $MinorVersion = 1;
+my $PatchVersion = 0;
+
 %basictypes = (
 	TInt8		=>	1,
 	TUint8		=>	1,
@@ -38,7 +44,7 @@
 );
 
 if (scalar(@ARGV)!=3) {
-	die "perl h2inc.pl <input.h> <output.inc> <format>\n";
+	die "H2INC format management tools V$MajorVersion.$MinorVersion.$PatchVersion\nperl h2inc.pl <input.h> <output.inc> <format>\n";
 }
 my ($infile, $outfile, $format) = @ARGV;
 open IN, $infile or die "Can't open $infile for input\n";
--- a/sbsv1/abld/e32util/makedef.pl	Fri Jun 25 20:58:33 2010 +0800
+++ b/sbsv1/abld/e32util/makedef.pl	Tue Jun 29 14:52:54 2010 +0800
@@ -45,7 +45,7 @@
 # Version
 my $MajorVersion = 1;
 my $MinorVersion = 1;
-my $PatchVersion = 0;
+my $PatchVersion = 1;
 
 my %Options;	# command line option information
 
--- a/sbsv1/abld/e32util/omapsig.pl	Fri Jun 25 20:58:33 2010 +0800
+++ b/sbsv1/abld/e32util/omapsig.pl	Tue Jun 29 14:52:54 2010 +0800
@@ -1,3 +1,4 @@
+#!/usr/bin/perl
 # e32toolp\e32util\omapsig.pl
 #
 # Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
@@ -24,8 +25,13 @@
 use IO::Handle;
 use File::Copy;
 
+# Version
+my $MajorVersion = 1;
+my $MinorVersion = 1;
+my $PatchVersion = 0;
+
 if (scalar(@ARGV)!=3) {
-	die "perl omapsig.pl <load address in hex> <input miniboot> <output minboot with sig>\n";
+	die "OMAPSIG signature tool V$MajorVersion.$MinorVersion.$PatchVersion\nperl omapsig.pl <load address in hex> <input miniboot> <output minboot with sig>\n";
 }
 
 my ($load_address, $infile, $outfile) = @ARGV;
@@ -53,4 +59,4 @@
 close $out;
 
 print "signed miniboot output ", -s $outfile, " bytes\n";
-exit;
\ No newline at end of file
+exit;
--- a/sbsv1/abld/e32util/prepdef.pl	Fri Jun 25 20:58:33 2010 +0800
+++ b/sbsv1/abld/e32util/prepdef.pl	Tue Jun 29 14:52:54 2010 +0800
@@ -40,7 +40,7 @@
 # Version
 my $MajorVersion = 1;
 my $MinorVersion = 1;
-my $PatchVersion = 0;
+my $PatchVersion = 1;
 
 # THE MAIN PROGRAM SECTION
 ##########################
--- a/sbsv1/abld/genutil/listzip.pl	Fri Jun 25 20:58:33 2010 +0800
+++ b/sbsv1/abld/genutil/listzip.pl	Tue Jun 29 14:52:54 2010 +0800
@@ -1,3 +1,4 @@
+#!/usr/bin/perl
 # Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
 # All rights reserved.
 # This component and the accompanying materials are made available
@@ -20,6 +21,11 @@
 # 
 #
 
+# Version
+my $MajorVersion = 1;
+my $MinorVersion = 1;
+my $PatchVersion = 0;
+
 sub _print_usage_and_die();
 sub _print_err_and_die(@);
 
@@ -36,12 +42,12 @@
 
     for (@raw_data)
     {
-        if ($_ =~ /^\s*\d+\s+\d\d[-|\/]\d\d[-|\/]\d\d\s+\d\d:\d\d\s+(.*)/)
+        if ($_ =~ /^\s*\d+\s+\d\d[-|\/|\.]\d\d[-|\/|\.]\d\d\s+\d\d:\d\d\s+(.*)/)
         {
             my $line = "${prefix}/$1";
-            $line =~ s/\//\\/g;
+            $line =~ s/\//\\/g if($^O =~ /^MSWin32$/i);
 	    # don't print directories under the <build> tags
-	    if (!($line =~ /\\$/)) {
+	    if (!($line =~ /[\\|\/]$/)) {
 		    print "$line\n";
 		    }
         }
@@ -50,7 +56,7 @@
 
 sub _print_usage_and_die()
 {
-    print "usage: listzip.pl <prefix> <zipfile>\n";
+    print "LISTZIP zip files process tool V$MajorVersion.$MinorVersion.$PatchVersion\nusage: listzip.pl <prefix> <zipfile>\n";
     exit 2;
 }
 
--- a/sbsv1/abld/group/bld.inf	Fri Jun 25 20:58:33 2010 +0800
+++ b/sbsv1/abld/group/bld.inf	Tue Jun 29 14:52:54 2010 +0800
@@ -49,6 +49,11 @@
 ../platform/extractvars.make		/epoc32/tools/compilation_config/extractvars.make
 ../platform/GCCE.mk			/epoc32/tools/compilation_config/GCCE.mk
 ../genutil/listzip.pl			/epoc32/tools/listzip.pl
+../genutil/conv_khronos_openvg_hdr_to_cpp.pl        /epoc32/tools/conv_khronos_openvg_hdr_to_cpp.pl 
+../genutil/ecopyfile.pl        /epoc32/tools/ecopyfile.pl
+../genutil/conv_khronos_hdr_to_cpp.pl        /epoc32/tools/conv_khronos_hdr_to_cpp.pl  
+../e32util/armasm2as.pl        /epoc32/tools/armasm2as.pl
+../e32util/copyfeaturevariants.pl        /epoc32/tools/copyfeaturevariants.pl 
 
 // BSF files
 ../platform/armv6.bsf        /epoc32/tools/armv6.bsf 
@@ -77,7 +82,6 @@
 ../e32util/epocmbm.pl        /epoc32/tools/epocmbm.pl 
 ../platform/cl_edg.pm        /epoc32/tools/cl_edg.pm 
 ../platform/cl_tools.pm        /epoc32/tools/cl_tools.pm 
-../genutil/conv_khronos_openvg_hdr_to_cpp.pl        /epoc32/tools/conv_khronos_openvg_hdr_to_cpp.pl 
 ../e32util/fixsource.bat        /epoc32/tools/fixsource.bat 
 ../platform/cl_generic.pm        /epoc32/tools/cl_generic.pm 
 ../platform/e32variant.pm        /epoc32/tools/e32variant.pm 
@@ -111,8 +115,7 @@
 ../platform/findimp.pl        /epoc32/tools/findimp.pl 
 ../e32util/checksource.pm        /epoc32/tools/checksource.pm 
 ../e32util/genshimsrc.bat        /epoc32/tools/genshimsrc.bat 
-../toolinfo/rvct_ver2set.pm        /epoc32/tools/rvct_ver2set.pm 
-../e32util/armasm2as.pl        /epoc32/tools/armasm2as.pl  
+../toolinfo/rvct_ver2set.pm        /epoc32/tools/rvct_ver2set.pm   
 ../e32util/selectbootmak.pl        /epoc32/tools/selectbootmak.pl 
 ../makmake/makhelp.pm        /epoc32/tools/makhelp.pm 
 ../platform/cl_codewarrior.pm        /epoc32/tools/cl_codewarrior.pm 
@@ -123,7 +126,6 @@
 ../bldmake/bldmake.bat        /epoc32/tools/bldmake.bat 
 ../e32util/listfeaturevariants.pl        /epoc32/tools/listfeaturevariants.pl 
 ../memtrace/memtrace.pl        /epoc32/tools/memtrace.pl 
-../genutil/ecopyfile.pl        /epoc32/tools/ecopyfile.pl 
 ../genutil/ermdir.pl        /epoc32/tools/ermdir.pl 
 ../platform/armutl.pm        /epoc32/tools/armutl.pm 
 ../platform/cl_arm.pm        /epoc32/tools/cl_arm.pm 
@@ -135,10 +137,8 @@
 ../genutil/output.pm        /epoc32/tools/output.pm 
 ../e32util/efreeze.bat        /epoc32/tools/efreeze.bat 
 ../platform/cw_project_template_v4.xml        /epoc32/tools/cw_project_template_v4.xml 
-../e32util/copyfeaturevariants.pl        /epoc32/tools/copyfeaturevariants.pl 
 ../platform/fcloggerutl.pm        /epoc32/tools/fcloggerutl.pm 
 ../platform/cl_win.pm        /epoc32/tools/cl_win.pm 
-../genutil/conv_khronos_hdr_to_cpp.pl        /epoc32/tools/conv_khronos_hdr_to_cpp.pl 
 ../e32util/featurevariantmap.pm        /epoc32/tools/featurevariantmap.pm 
 ../e32util/preprocessor.pm        /epoc32/tools/preprocessor.pm 
 ../platform/winutl.pm        /epoc32/tools/winutl.pm 
--- a/sbsv1/abld/group/release.txt	Fri Jun 25 20:58:33 2010 +0800
+++ b/sbsv1/abld/group/release.txt	Tue Jun 29 14:52:54 2010 +0800
@@ -1,3 +1,29 @@
+
+<unchange>
+================
+(Made by Zheng Shen 12/06/2010)
+1) minor: enable the following scripts on Linux
+conv_khronos_openvg_hdr_to_cpp.pl
+conv_khronos_hdr_to_cpp.pl
+copyfeaturevariants.pl
+ecopyfile.pl
+armasm2as.pl 
+
+===============
+sym_lkup_util 	version 1.1.0
+listzip 	version 1.1.0
+prepdef 	version 1.1.1
+omapsig 	version 1.1.0
+makedef 	version 1.1.1
+h2inc 		version 1.1.0
+gendef 		version 1.1.0
+createrfifile 	version 1.1.0
+efreeze 	version 1.1.1
+================
+(Made by Marvin Shi 02/06/2010)
+1) change for linux porting
+
+=======
 Version 1.1.0 (efreeze.pl)
 Version 1.1.0 (prepdef.pl)
 Version 1.1.0 (makedef.pl)
--- a/sbsv1/abld/platform/sym_lkup_util.pl	Fri Jun 25 20:58:33 2010 +0800
+++ b/sbsv1/abld/platform/sym_lkup_util.pl	Tue Jun 29 14:52:54 2010 +0800
@@ -41,6 +41,12 @@
 my %Symbols = ();
 my @Imports = ();
 
+# Version
+my $MajorVersion = 1;
+my $MinorVersion = 1;
+my $PatchVersion = 0;
+
+
 {
 	unless (GetOptions(\%Options, 'sym=s', 'o=s', 'map=s', 'ignore_export_dir')) {
 		exit 1;
@@ -50,6 +56,21 @@
 	$mapFile = $Options{map};
 	$IgnoreExportDir = $Options{ignore_export_dir};
 
+	unless($ImportSymFile)
+	{
+		print(
+			 "\n",
+			 "SYM_LKUP_UTIL symbol process tool V$MajorVersion.$MinorVersion.$PatchVersion\n",
+			 "\n",
+			 "options:\n",
+			 " -sym symbol file\n",
+			 " -o   output file\n",
+			 " -map  map file\n",
+			 "\n"
+		);
+		exit 1;
+	}
+
 	ReadSymFile() if $ImportSymFile;
 	ReadMapFile() if $mapFile;
 	
--- a/srctools/tranasm/group/bld.inf	Fri Jun 25 20:58:33 2010 +0800
+++ b/srctools/tranasm/group/bld.inf	Tue Jun 29 14:52:54 2010 +0800
@@ -20,7 +20,12 @@
 TOOLS2
 
 PRJ_EXPORTS
+
+#ifdef TOOLS2_LINUX
+../tranasm		/epoc32/tools/tranasm
+#else
 ../tranasm.bat		/epoc32/tools/tranasm.bat
+#endif
 ../tranasm.pl		/epoc32/tools/tranasm.pl
 ../tranasm_x86.pl	/epoc32/tools/tranasm_x86.pl
 
--- a/srctools/tranasm/group/tranasm.mrp	Fri Jun 25 20:58:33 2010 +0800
+++ b/srctools/tranasm/group/tranasm.mrp	Tue Jun 29 14:52:54 2010 +0800
@@ -1,7 +1,7 @@
 component       dev_build_srctools_tranasm
 
-source          /src/tools/dev/build/srctools/tranasm
-exports         /src/tools/dev/build/srctools/tranasm/group
+source          /src/tools/build/srctools/tranasm
+exports         /src/tools/build/srctools/tranasm/group
 
 notes_source    release.txt